repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
caiyingyuan/tigase71
src/main/java/tigase/net/IOService.java
37628
/* * IOService.java * * Tigase Jabber/XMPP Server * Copyright (C) 2004-2013 "Tigase, Inc." <office@tigase.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. Look for COPYING file in the top folder. * If not, see http://www.gnu.org/licenses/. * */ package tigase.net; //~--- non-JDK imports -------------------------------------------------------- import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.CharBuffer; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import java.nio.charset.MalformedInputException; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.TrustManager; import tigase.cert.CertCheckResult; import tigase.cert.CertificateUtil; import tigase.io.BufferUnderflowException; import tigase.io.IOInterface; import tigase.io.SocketIO; import tigase.io.TLSEventHandler; import tigase.io.TLSIO; import tigase.io.TLSUtil; import tigase.io.TLSWrapper; import tigase.io.ZLibIO; import tigase.stats.StatisticsList; import tigase.util.IOListener; import tigase.xmpp.JID; /** * <code>IOService</code> offers thread safe * <code>call()</code> method execution, however you must be prepared that other * methods can be called simultaneously like * <code>stop()</code>, * <code>getProtocol()</code> or * <code>isConnected()</code>. <br> It is recommended that developers extend * <code>AbsractServerService</code> rather then implement * <code>ServerService</code> interface directly. <p> If you directly implement * <code>ServerService</code> interface you must take care about * <code>SocketChannel</code> I/O, queuing tasks, processing results and thread * safe execution of * <code>call()</code> method. If you however extend * <code>IOService</code> class all this basic operation are implemented and you * have only to take care about parsing data received from network socket. * Parsing data is expected to be implemented in * <code>parseData(char[] data)</code> method. </p> * * <p> Created: Tue Sep 28 23:00:34 2004 </p> * * @param <RefObject> is a reference object stored by this service. This is e * reference to higher level data object keeping more information about the * connection. * @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a> * @version $Rev$ */ public abstract class IOService<RefObject> implements Callable<IOService<?>>, TLSEventHandler, IOListener { /** * Field description */ public static final String CERT_CHECK_RESULT = "cert-check-result"; /** * Field description */ public static final String CERT_REQUIRED_DOMAIN = "cert-required-domain"; /** * Field description */ public static final String HOSTNAME_KEY = "hostname-key"; /** * Field description */ public static final String PORT_TYPE_PROP_KEY = "type"; /** * This is key used to store session ID in temporary session data * storage. As it is used by many components it is required that all * components access session ID with this constant. */ public static final String SESSION_ID_KEY = "sessionID"; /** Field description */ public static final String SSL_PROTOCOLS_KEY = "ssl-protocols"; /** * Variable * <code>log</code> is a class logger. */ private static final Logger log = Logger.getLogger(IOService.class.getName()); private static final long MAX_ALLOWED_EMPTY_CALLS = 1000; //~--- fields --------------------------------------------------------------- /** * The saved partial bytes for multi-byte UTF-8 characters between reads */ protected byte[] partialCharacterBytes = null; private JID connectionId = null; private ConnectionType connectionType = null; private JID dataReceiver = null; /** * Field description */ private long empty_read_call_count = 0; private String id = null; /** * This variable keeps the time of last transfer in any direction it is * used to help detect dead connections. */ private long lastTransferTime = 0; private String local_address = null; private long[] rdData = new long[60]; private RefObject refObject = null; private String remote_address = null; private IOServiceListener<IOService<RefObject>> serviceListener = null; private boolean socketServiceReady = false; /** * <code>socketInput</code> buffer keeps data read from socket. */ private ByteBuffer socketInput = null; private int socketInputSize = 2048; private IOInterface socketIO = null; private boolean stopping = false; private long[] wrData = new long[60]; private ConcurrentMap<String, Object> sessionData = new ConcurrentHashMap<String, Object>(4, 0.75f, 4); // properties from block below should not be used without proper knowledge // ----- BEGIN --------------------------------------------------------------- /** Field description */ protected CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder(); /** Field description */ protected CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder(); /** Field description */ protected CharBuffer cb = CharBuffer.allocate(2048); private final ReentrantLock writeInProgress = new ReentrantLock(); private final ReentrantLock readInProgress = new ReentrantLock(); private TrustManager[] x509TrustManagers; private int bufferLimit = 0; private Certificate peerCertificate; //~--- methods -------------------------------------------------------------- /** * Method * <code>accept</code> is used to perform * * @param socketChannel a * <code>SocketChannel</code> value * * @throws IOException */ public void accept(final SocketChannel socketChannel) throws IOException { try { if (socketChannel.isConnectionPending()) { socketChannel.finishConnect(); } // end of if (socketChannel.isConnecyionPending()) socketIO = new SocketIO(socketChannel); } catch (IOException e) { String host = (String) sessionData.get("remote-hostname"); if (host == null) { host = (String) sessionData.get("remote-host"); } String sock_str = null; try { sock_str = socketChannel.socket().toString(); } catch (Exception ex) { sock_str = ex.toString(); } log.log(Level.FINER, "Problem connecting to remote host: {0}, address: {1}, socket: {2} - exception: {3}, session data: {4}", new Object[] { host, remote_address, sock_str, e, sessionData }); throw e; } socketInputSize = socketIO.getSocketChannel().socket().getReceiveBufferSize(); socketInput = ByteBuffer.allocate(socketInputSize); socketInput.order(byteOrder()); Socket sock = socketIO.getSocketChannel().socket(); local_address = sock.getLocalAddress().getHostAddress(); remote_address = sock.getInetAddress().getHostAddress(); id = local_address + "_" + sock.getLocalPort() + "_" + remote_address + "_" + sock .getPort(); setLastTransferTime(); } @Override public IOService<?> call() throws IOException { writeData(null); boolean readLock = true; if (stopping) { stop(); } else { readLock = readInProgress.tryLock(); if (readLock) { try { processSocketData(); if ((receivedPackets() > 0) && (serviceListener != null)) { serviceListener.packetsReady(this); } // end of if (receivedPackets.size() > 0) } finally { readInProgress.unlock(); if (!isConnected()) { // added to sooner detect disconnection of peer - ie. client if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, stopping connection due to the fact that it was disconnected, forceStop()", toString()); } forceStop(); } } } } return readLock && socketServiceReady ? this : null; } @Override public boolean checkBufferLimit(int bufferSize) { return (bufferLimit == 0 || bufferSize <= bufferLimit); } /** * Method description * * * */ public ConnectionType connectionType() { return this.connectionType; } /** * Method description * */ public void forceStop() { if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "Socket: {0}, Force stop called...", socketIO); } try { if ((socketIO != null) && socketIO.isConnected()) { synchronized (socketIO) { if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "Calling stop on: {0}", socketIO); } socketIO.stop(); } } } catch (Exception e) { // Well, do nothing, we are closing the connection anyway.... if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Socket: " + socketIO + ", Exception while stopping service: " + connectionId, e); } } finally { if (serviceListener != null) { if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "Calling stop on the listener: {0}", serviceListener); } IOServiceListener<IOService<RefObject>> tmp = serviceListener; serviceListener = null; // The temp can still be null if the forceStop is called concurrently if (tmp != null) { tmp.serviceStopped(this); } } else { if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "Service listener is null: {0}", socketIO); } } } } @Override public void handshakeCompleted(TLSWrapper wrapper) { String reqCertDomain = (String) getSessionData().get(CERT_REQUIRED_DOMAIN); CertCheckResult certCheckResult = wrapper.getCertificateStatus(false); if (reqCertDomain != null) { // if reqCertDomain is set then verify if certificate got from server // is allowed for reqCertDomain try { Certificate[] certs = wrapper.getTlsEngine().getSession() .getPeerCertificates(); if (certs != null && certs.length > 0) { Certificate peerCert = certs[0]; if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS handshake veryfing if certificate from connection matches domain {1}", new Object[]{this, reqCertDomain}); } if (!CertificateUtil.verifyCertificateForDomain((X509Certificate) peerCert, reqCertDomain)) { certCheckResult = CertCheckResult.invalid; } } } catch (Exception e) { certCheckResult = CertCheckResult.invalid; } } sessionData.put(CERT_CHECK_RESULT, certCheckResult); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS handshake completed: {1}", new Object[] { this, certCheckResult }); } if (!wrapper.getTlsEngine().getUseClientMode() && ( wrapper.getTlsEngine().getWantClientAuth() || wrapper.getTlsEngine().getNeedClientAuth())) { try { Certificate[] certs = wrapper.getTlsEngine().getSession() .getPeerCertificates(); this.peerCertificate = certs[certs.length - 1]; } catch (SSLPeerUnverifiedException e) { this.peerCertificate = null; } catch (Exception e) { this.peerCertificate = null; log.log(Level.WARNING, "Problem with extracting subjectAltName", e); } } serviceListener.tlsHandshakeCompleted(this); } /** * Method description * * * @throws IOException */ public abstract void processWaitingPackets() throws IOException; /** * Method description * * * @param clientMode * * @throws IOException */ public void startSSL(boolean clientMode, boolean wantClientAuth, boolean needClientAuth) throws IOException { if (socketIO instanceof TLSIO) { throw new IllegalStateException("SSL mode is already activated."); } String tls_hostname = null; int port = 0; if (clientMode) { tls_hostname = (String) this.getSessionData().get("remote-host"); if (tls_hostname == null) tls_hostname = (String) this.getSessionData().get("remote-hostname"); port = ((InetSocketAddress) socketIO.getSocketChannel().getRemoteAddress()).getPort(); } SSLContext sslContext; if (x509TrustManagers != null) { sslContext = TLSUtil.getSSLContext("SSL", tls_hostname, clientMode, x509TrustManagers); } else { sslContext = TLSUtil.getSSLContext("SSL", tls_hostname, clientMode); } TLSWrapper wrapper = new TLSWrapper(sslContext, this, tls_hostname, port, clientMode, wantClientAuth, needClientAuth); socketIO = new TLSIO(socketIO, wrapper, byteOrder()); setLastTransferTime(); encoder.reset(); decoder.reset(); } /** * Method description * * * @param clientMode * * @throws IOException */ public void startTLS(boolean clientMode, boolean wantClientAuth, boolean needClientAuth) throws IOException { if (socketIO.checkCapabilities(TLSIO.TLS_CAPS)) { throw new IllegalStateException("TLS mode is already activated " + connectionId); } // This should not take more then 100ms int counter = 0; while (isConnected() && waitingToSend() && (++counter < 10)) { writeData(null); try { Thread.sleep(10); } catch (InterruptedException ex) {} } if (counter >= 10) { stop(); } else { String tls_hostname = (String) sessionData.get(HOSTNAME_KEY); int port = 0; if (clientMode) { port = ((InetSocketAddress) socketIO.getSocketChannel().getRemoteAddress()).getPort(); if (tls_hostname == null) { tls_hostname = (String) this.getSessionData().get("remote-host"); if (tls_hostname == null) tls_hostname = (String) this.getSessionData().get("remote-hostname"); } } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Starting TLS for domain: {1}", new Object[] { this, tls_hostname }); } SSLContext sslContext; if (x509TrustManagers != null) { sslContext = TLSUtil.getSSLContext("TLS", tls_hostname, clientMode, x509TrustManagers); } else { sslContext = TLSUtil.getSSLContext("TLS", tls_hostname, clientMode); } TLSWrapper wrapper = new TLSWrapper(sslContext, this, tls_hostname, port, clientMode, wantClientAuth, needClientAuth); socketIO = new TLSIO(socketIO, wrapper, byteOrder()); setLastTransferTime(); encoder.reset(); decoder.reset(); } } /** * Method description * * * @param level */ public void startZLib(int level) { if (socketIO.checkCapabilities(ZLibIO.ZLIB_CAPS)) { throw new IllegalStateException("ZLIB mode is already activated."); } socketIO = new ZLibIO(socketIO, level); ((ZLibIO) socketIO).setIOListener(this); } /** * Describe * <code>stop</code> method here. * */ public void stop() { if ((socketIO != null) && socketIO.waitingToSend()) { stopping = true; } else { forceStop(); } } @Override public String toString() { return getConnectionId() + ", type: " + connectionType + ", Socket: " + socketIO; } /** * Method description * * * */ public boolean waitingToRead() { return true; } /** * Method description * * * */ public boolean waitingToSend() { return socketIO.waitingToSend(); } /** * Method description * * * */ public int waitingToSendSize() { return socketIO.waitingToSendSize(); } //~--- get methods ---------------------------------------------------------- /** * Method description * * * @param reset * * */ public long getBuffOverflow(boolean reset) { return socketIO.getBuffOverflow(reset); } /** * Method description * * * @param reset * * */ public long getBytesReceived(boolean reset) { return socketIO.getBytesReceived(reset); } /** * Method description * * * @param reset * * */ public long getBytesSent(boolean reset) { return socketIO.getBytesSent(reset); } /** * @return the connectionId */ public JID getConnectionId() { return connectionId; } /** * Method description * * * */ public JID getDataReceiver() { return this.dataReceiver; } /** * This method returns the time of last transfer in any direction * through this service. It is used to help detect dead connections. * * */ public long getLastTransferTime() { return lastTransferTime; } /** * Method description * * * */ public String getLocalAddress() { return local_address; } /** * Method returns local port of opened socket * * @return */ public int getLocalPort() { Socket sock = socketIO.getSocketChannel().socket(); return sock.getLocalPort(); } /** * Method description * * * */ public long[] getReadCounters() { return rdData; } /** * Method description * * * */ public RefObject getRefObject() { return refObject; } /** * Returns a remote IP address for the TCP/IP connection. * * * @return a remote IP address for the TCP/IP connection. */ public String getRemoteAddress() { return remote_address; } /** * Method description * * * */ public ConcurrentMap<String, Object> getSessionData() { return sessionData; } /** * Method * <code>getSocketChannel</code> is used to perform * * @return a * <code>SocketChannel</code> value */ public SocketChannel getSocketChannel() { return socketIO.getSocketChannel(); } /** * Method description * * * @param list * @param reset */ public void getStatistics(StatisticsList list, boolean reset) { if (socketIO != null) { socketIO.getStatistics(list, reset); } } /** * Method description * * * */ public long getTotalBuffOverflow() { return socketIO.getTotalBuffOverflow(); } /** * Method description * * * */ public long getTotalBytesReceived() { return socketIO.getTotalBytesReceived(); } /** * Method description * * * */ public long getTotalBytesSent() { return socketIO.getTotalBytesSent(); } /** * Method description * * * */ public String getUniqueId() { return id; } /** * Method description * * * */ public long[] getWriteCounters() { return wrData; } /** * Method description * * * */ public TrustManager[] getX509TrustManagers() { return x509TrustManagers; } /** * Describe * <code>isConnected</code> method here. * * @return a * <code>boolean</code> value */ public boolean isConnected() { boolean result = (socketIO == null) ? false : socketIO.isConnected(); if (log.isLoggable(Level.FINEST)) { // if (socketIO.getSocketChannel().socket().getLocalPort() == 5269) { // Throwable thr = new Throwable(); // // thr.fillInStackTrace(); // log.log(Level.FINEST, "Socket: " + socketIO + ", Connected: " + result, // thr); // } log.log(Level.FINEST, "Socket: {0}, Connected: {1}, id: {2}", new Object[] { socketIO, result, connectionId }); } return result; } //~--- set methods ---------------------------------------------------------- public void setBufferLimit(int bufferLimit) { this.bufferLimit = bufferLimit; } /** * @param connectionId the connectionId to set */ public void setConnectionId(JID connectionId) { this.connectionId = connectionId; socketIO.setLogId(connectionId.toString()); } /** * Method description * * * @param address */ public void setDataReceiver(JID address) { this.dataReceiver = address; } /** * Method description * * * @param sl */ // @SuppressWarnings("unchecked") public void setIOServiceListener(IOServiceListener<IOService<RefObject>> sl) { this.serviceListener = sl; } /** * Method description * * * @param refObject */ public void setRefObject(RefObject refObject) { this.refObject = refObject; } /** * Method description * * * @param props */ public void setSessionData(Map<String, Object> props) { // Sometimes, some values are null which is allowed in the original Map // however, ConcurrentHashMap does not allow nulls as value so we have // to copy Maps carefully. sessionData = new ConcurrentHashMap<String, Object>(props.size()); for (Map.Entry<String, Object> entry : props.entrySet()) { if (entry.getValue() != null) { sessionData.put(entry.getKey(), entry.getValue()); } } connectionType = ConnectionType.valueOf(sessionData.get(PORT_TYPE_PROP_KEY) .toString()); } /** * Method description * * * @param trustManager */ public void setX509TrustManagers(TrustManager[] trustManager) { this.x509TrustManagers = trustManager; } //~--- methods -------------------------------------------------------------- /** * Method description * * * */ protected ByteOrder byteOrder() { return ByteOrder.BIG_ENDIAN; } /** * Describe * <code>debug</code> method here. * * @param msg a * <code>char[]</code> value * @return a * <code>boolean</code> value */ protected boolean debug(final char[] msg) { if (msg != null) { System.out.print(new String(msg)); // log.finest("\n" + new String(msg) + "\n"); } // end of if (msg != null) return true; } /** * Describe * <code>debug</code> method here. * * @param msg a * <code>String</code> value * @param prefix * @return a * <code>boolean</code> value */ protected boolean debug(final String msg, final String prefix) { if (log.isLoggable(Level.FINEST)) { if ((msg != null) && (msg.trim().length() > 0)) { String log_msg = "\n" + ((connectionType() != null) ? connectionType().toString() : "null-type") + " " + prefix + "\n" + msg + "\n"; // System.out.print(log_msg); log.finest(log_msg); } } return true; } /** * Method description * * * @throws IOException */ protected abstract void processSocketData() throws IOException; /** * Method description * * * * * @throws IOException */ protected ByteBuffer readBytes() throws IOException { setLastTransferTime(); if (log.isLoggable(Level.FINEST) && (empty_read_call_count > 10)) { Throwable thr = new Throwable(); thr.fillInStackTrace(); log.log(Level.FINEST, "Socket: " + socketIO, thr); } try { ByteBuffer tmpBuffer = socketIO.read(socketInput); if (socketIO.bytesRead() > 0) { empty_read_call_count = 0; return tmpBuffer; } else { if ((++empty_read_call_count) > MAX_ALLOWED_EMPTY_CALLS && (!writeInProgress .isLocked())) { log.log(Level.WARNING, "Socket: {0}, Max allowed empty calls excceeded, closing connection.", socketIO); forceStop(); } } } catch (BufferUnderflowException ex) { resizeInputBuffer(); return readBytes(); } catch (Exception eof) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Socket: " + socketIO + ", Exception reading data", eof); } // eof.printStackTrace(); forceStop(); } return null; } /** * Method description * */ protected void readCompleted() { decoder.reset(); } /** * Describe * <code>readData</code> method here. * * @return a * <code>char[]</code> value * @exception IOException if an error occurs */ protected char[] readData() throws IOException { setLastTransferTime(); if (log.isLoggable(Level.FINEST) && (empty_read_call_count > 10)) { Throwable thr = new Throwable(); thr.fillInStackTrace(); log.log(Level.FINEST, "Socket: " + socketIO, thr); } // Generally it should not happen as it is called only in // call() which has concurrent call protection. // synchronized (socketIO) { try { // resizeInputBuffer(); // Maybe we can shrink the input buffer?? if ((socketInput.capacity() > socketInputSize) && (socketInput.remaining() == socketInput.capacity())) { // Yes, looks like we can if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, "Socket: {0}, Resizing socketInput down to {1} bytes.", new Object[] { socketIO, socketInputSize }); } socketInput = ByteBuffer.allocate(socketInputSize); socketInput.order(byteOrder()); cb = CharBuffer.allocate(socketInputSize * 4); } // if (log.isLoggable(Level.FINEST)) { // log.finer("Before read from socket."); // log.finer("socketInput.capacity()=" + socketInput.capacity()); // log.finer("socketInput.remaining()=" + socketInput.remaining()); // log.finer("socketInput.limit()=" + socketInput.limit()); // log.finer("socketInput.position()=" + socketInput.position()); // } ByteBuffer tmpBuffer = socketIO.read(socketInput); if (socketIO.bytesRead() > 0) { empty_read_call_count = 0; char[] result = null; // There might be some characters read from the network // but the buffer may still be null or empty because there might // be not enough data to decode TLS or compressed buffer. if (tmpBuffer != null) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Socket: {0}, Reading network binary data: {1}", new Object[] { socketIO, socketIO.bytesRead() }); } // Restore the partial bytes for multibyte UTF8 characters if (partialCharacterBytes != null) { if (log.isLoggable(Level.FINEST)) { log.finest("Reloading partial bytes " + partialCharacterBytes.length); } ByteBuffer oldTmpBuffer = tmpBuffer; tmpBuffer = ByteBuffer.allocate(partialCharacterBytes.length + oldTmpBuffer .remaining() + 2); tmpBuffer.order(byteOrder()); tmpBuffer.put(partialCharacterBytes); tmpBuffer.put(oldTmpBuffer); tmpBuffer.flip(); oldTmpBuffer.clear(); partialCharacterBytes = null; } // if (log.isLoggable(Level.FINEST)) { // log.finer("Before decoding data"); // log.finer("socketInput.capacity()=" + socketInput.capacity()); // log.finer("socketInput.remaining()=" + socketInput.remaining()); // log.finer("socketInput.limit()=" + socketInput.limit()); // log.finer("socketInput.position()=" + socketInput.position()); // log.finer("tmpBuffer.capacity()=" + tmpBuffer.capacity()); // log.finer("tmpBuffer.remaining()=" + tmpBuffer.remaining()); // log.finer("tmpBuffer.limit()=" + tmpBuffer.limit()); // log.finer("tmpBuffer.position()=" + tmpBuffer.position()); // log.finer("cb.capacity()=" + cb.capacity()); // log.finer("cb.remaining()=" + cb.remaining()); // log.finer("cb.limit()=" + cb.limit()); // log.finer("cb.position()=" + cb.position()); // } // tmpBuffer.flip(); if (cb.capacity() < tmpBuffer.remaining() * 4) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Socket: {0}, resizing character buffer to: {1}", new Object[] { socketIO, tmpBuffer.remaining() }); } cb = CharBuffer.allocate(tmpBuffer.remaining() * 4); } CoderResult cr = decoder.decode(tmpBuffer, cb, false); if (cr.isMalformed()) { throw new MalformedInputException(tmpBuffer.remaining()); } if (cb.remaining() > 0) { cb.flip(); result = new char[cb.remaining()]; cb.get(result); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Socket: {0}, Decoded character data: {1}", new Object[] { socketIO, new String(result) }); } // if (log.isLoggable(Level.FINEST)) { // log.finer("Just after decoding."); // log.finer("tmpBuffer.capacity()=" + tmpBuffer.capacity()); // log.finer("tmpBuffer.remaining()=" + tmpBuffer.remaining()); // log.finer("tmpBuffer.limit()=" + tmpBuffer.limit()); // log.finer("tmpBuffer.position()=" + tmpBuffer.position()); // log.finer("cb.capacity()=" + cb.capacity()); // log.finer("cb.remaining()=" + cb.remaining()); // log.finer("cb.limit()=" + cb.limit()); // log.finer("cb.position()=" + cb.position()); // } } if (cr.isUnderflow() && (tmpBuffer.remaining() > 0)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Socket: {0}, UTF-8 decoder data underflow: {1}", new Object[] { socketIO, tmpBuffer.remaining() }); } // Save the partial bytes of a multibyte character such that they // can be restored on the next read. partialCharacterBytes = new byte[tmpBuffer.remaining()]; tmpBuffer.get(partialCharacterBytes); } tmpBuffer.clear(); cb.clear(); // if (log.isLoggable(Level.FINEST)) { // log.finer("Before return from method."); // log.finer("tmpBuffer.capacity()=" + tmpBuffer.capacity()); // log.finer("tmpBuffer.remaining()=" + tmpBuffer.remaining()); // log.finer("tmpBuffer.limit()=" + tmpBuffer.limit()); // log.finer("tmpBuffer.position()=" + tmpBuffer.position()); // log.finer("cb.capacity()=" + cb.capacity()); // log.finer("cb.remaining()=" + cb.remaining()); // log.finer("cb.limit()=" + cb.limit()); // log.finer("cb.position()=" + cb.position()); // } return result; } } else { // Detecting infinite read 0 bytes // sometimes it happens that the connection has been lost // and the select thinks there are some bytes waiting for reading // and 0 bytes are read if ((++empty_read_call_count) > MAX_ALLOWED_EMPTY_CALLS && (!writeInProgress .isLocked())) { log.log(Level.WARNING, "Socket: {0}, Max allowed empty calls excceeded, closing connection.", socketIO); forceStop(); } } } catch (BufferUnderflowException ex) { // Obtain more inbound network data for src, // then retry the operation. resizeInputBuffer(); return null; // } catch (MalformedInputException ex) { //// This happens after TLS initialization sometimes, maybe reset helps // decoder.reset(); } catch (Exception eof) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Socket: " + socketIO + ", Exception reading data", eof); } // eof.printStackTrace(); forceStop(); } // end of try-catch // } return null; } /** * Method description * * * */ protected abstract int receivedPackets(); /** * Method description * * * @param data */ protected void writeBytes(ByteBuffer data) { // Try to lock the data writing method boolean locked = writeInProgress.tryLock(); // If cannot lock and nothing to send, just leave if (!locked && (data == null)) { return; } // Otherwise wait..... if (!locked) { writeInProgress.lock(); } // Avoid concurrent calls here (one from call() and another from // application) try { if ((data != null) && data.hasRemaining()) { int length = data.remaining(); socketIO.write(data); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Socket: {0}, wrote: {1}", new Object[] { socketIO, length }); } // idx_start = idx_offset; // idx_offset = Math.min(idx_start + out_buff_size, data.length()); // } setLastTransferTime(); // addWritten(data.length()); empty_read_call_count = 0; } else { if (socketIO.waitingToSend()) { socketIO.write(null); setLastTransferTime(); empty_read_call_count = 0; } } } catch (Exception e) { if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "Data writing exception " + connectionId, e); } forceStop(); } finally { writeInProgress.unlock(); } } /** * Describe * <code>writeData</code> method here. * * @param data a * <code>String</code> value */ protected void writeData(final String data) { // Try to lock the data writing method boolean locked = writeInProgress.tryLock(); // If cannot lock and nothing to send, just leave if (!locked && (data == null)) { return; } // Otherwise wait..... if (!locked) { writeInProgress.lock(); } // Avoid concurrent calls here (one from call() and another from // application) try { if ((data != null) && (data.length() > 0)) { if (log.isLoggable(Level.FINEST)) { if (data.length() < 256) { log.log(Level.FINEST, "Socket: {0}, Writing data ({1}): {2}", new Object[] { socketIO, data.length(), data }); } else { log.log(Level.FINEST, "Socket: {0}, Writing data: {1}", new Object[] { socketIO, data.length() }); } } ByteBuffer dataBuffer = null; // int out_buff_size = data.length(); // int idx_start = 0; // int idx_offset = Math.min(idx_start + out_buff_size, data.length()); // // while (idx_start < data.length()) { // String data_str = data.substring(idx_start, idx_offset); // if (log.isLoggable(Level.FINEST)) { // log.finest("Writing data_str (" + data_str.length() + "), idx_start=" // + idx_start + ", idx_offset=" + idx_offset + ": " + data_str); // } encoder.reset(); // dataBuffer = encoder.encode(CharBuffer.wrap(data, idx_start, // idx_offset)); dataBuffer = encoder.encode(CharBuffer.wrap(data)); encoder.flush(dataBuffer); socketIO.write(dataBuffer); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Socket: {0}, wrote: {1}", new Object[] { socketIO, data.length() }); } // idx_start = idx_offset; // idx_offset = Math.min(idx_start + out_buff_size, data.length()); // } setLastTransferTime(); // addWritten(data.length()); empty_read_call_count = 0; } else { if (socketIO.waitingToSend()) { socketIO.write(null); setLastTransferTime(); empty_read_call_count = 0; } } } catch (Exception e) { if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "Data writing exception " + connectionId, e); } forceStop(); } finally { writeInProgress.unlock(); } } protected boolean isSocketServiceReady() { return socketServiceReady; } protected void setSocketServiceReady(boolean value) { this.socketServiceReady = value; } //~--- get methods ---------------------------------------------------------- /** * Method description * * */ protected boolean isInputBufferEmpty() { return (socketInput != null) && (socketInput.remaining() == socketInput.capacity()); } //~--- methods -------------------------------------------------------------- private void resizeInputBuffer() throws IOException { int netSize = socketIO.getInputPacketSize(); // Resize buffer if needed. // if (netSize > socketInput.remaining()) { if (netSize > socketInput.capacity() - socketInput.remaining()) { // int newSize = netSize + socketInput.capacity(); int newSize = socketInput.capacity() + socketInputSize; if (!checkBufferLimit(bufferLimit)) { throw new IOException("Input buffer size limit exceeded"); } if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, "Socket: {0}, Resizing socketInput to {1} bytes.", new Object[] { socketIO, newSize }); } ByteBuffer b = ByteBuffer.allocate(newSize); b.order(byteOrder()); b.put(socketInput); socketInput = b; } else { // if (log.isLoggable(Level.FINEST)) { // log.finer(" Before flip()"); // log.finer("input.capacity()=" + socketInput.capacity()); // log.finer("input.remaining()=" + socketInput.remaining()); // log.finer("input.limit()=" + socketInput.limit()); // log.finer("input.position()=" + socketInput.position()); // } // socketInput.flip(); // if (log.isLoggable(Level.FINEST)) { // log.finer(" Before compact()"); // log.finer("input.capacity()=" + socketInput.capacity()); // log.finer("input.remaining()=" + socketInput.remaining()); // log.finer("input.limit()=" + socketInput.limit()); // log.finer("input.position()=" + socketInput.position()); // } if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, "Socket: {0}, Compacting socketInput.", socketIO); } socketInput.compact(); // if (log.isLoggable(Level.FINEST)) { // log.finer(" After compact()"); // log.finer("input.capacity()=" + socketInput.capacity()); // log.finer("input.remaining()=" + socketInput.remaining()); // log.finer("input.limit()=" + socketInput.limit()); // log.finer("input.position()=" + socketInput.position()); // } } } //~--- set methods ---------------------------------------------------------- private void setLastTransferTime() { lastTransferTime = System.currentTimeMillis(); } public Certificate getPeerCertificate() { return peerCertificate; } } // IOService //~ Formatted in Tigase Code Convention on 13/05/29
agpl-3.0
shenan4321/BIMplatform
generated/cn/dlb/bim/models/ifc2x3tc1/impl/IfcTerminatorSymbolImpl.java
2311
/** * Copyright (C) 2009-2014 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package cn.dlb.bim.models.ifc2x3tc1.impl; import org.eclipse.emf.ecore.EClass; import cn.dlb.bim.models.ifc2x3tc1.Ifc2x3tc1Package; import cn.dlb.bim.models.ifc2x3tc1.IfcAnnotationCurveOccurrence; import cn.dlb.bim.models.ifc2x3tc1.IfcTerminatorSymbol; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Ifc Terminator Symbol</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link cn.dlb.bim.models.ifc2x3tc1.impl.IfcTerminatorSymbolImpl#getAnnotatedCurve <em>Annotated Curve</em>}</li> * </ul> * * @generated */ public class IfcTerminatorSymbolImpl extends IfcAnnotationSymbolOccurrenceImpl implements IfcTerminatorSymbol { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IfcTerminatorSymbolImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Ifc2x3tc1Package.Literals.IFC_TERMINATOR_SYMBOL; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public IfcAnnotationCurveOccurrence getAnnotatedCurve() { return (IfcAnnotationCurveOccurrence) eGet(Ifc2x3tc1Package.Literals.IFC_TERMINATOR_SYMBOL__ANNOTATED_CURVE, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setAnnotatedCurve(IfcAnnotationCurveOccurrence newAnnotatedCurve) { eSet(Ifc2x3tc1Package.Literals.IFC_TERMINATOR_SYMBOL__ANNOTATED_CURVE, newAnnotatedCurve); } } //IfcTerminatorSymbolImpl
agpl-3.0
BrickbitSolutions/lpm-catering
src/main/java/be/brickbit/lpm/catering/repository/PreparationTaskRepository.java
636
package be.brickbit.lpm.catering.repository; import be.brickbit.lpm.catering.domain.PreparationTask; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List; public interface PreparationTaskRepository extends JpaRepository<PreparationTask, Long>{ @Query("SELECT t FROM PreparationTask t WHERE t.orderLine.product.preparation.queueName = :queueName AND (t.status = 'IN_PROGRESS' OR t.status = 'QUEUED')") List<PreparationTask> findAllByQueueName(@Param("queueName") String queueName); }
agpl-3.0
hogi/kunagi
src/test/java/scrum/TestUtil.java
8156
package scrum; import ilarkesto.base.Str; import ilarkesto.base.Sys; import ilarkesto.base.Utl; import ilarkesto.base.time.Date; import ilarkesto.base.time.DateAndTime; import ilarkesto.base.time.Time; import ilarkesto.core.logging.Log; import ilarkesto.persistence.AEntity; import scrum.server.ScrumWebApplication; import scrum.server.admin.User; import scrum.server.calendar.SimpleEvent; import scrum.server.collaboration.Comment; import scrum.server.collaboration.Wikipage; import scrum.server.impediments.Impediment; import scrum.server.issues.Issue; import scrum.server.pr.BlogEntry; import scrum.server.project.Project; import scrum.server.project.Requirement; import scrum.server.risks.Risk; import scrum.server.sprint.Sprint; import scrum.server.sprint.Task; public class TestUtil { private static boolean initialized; private static ScrumWebApplication app; public static void initialize() { if (initialized) return; initialized = true; Log.setDebugEnabled(false); Sys.setHeadless(true); app = new ScrumWebApplication(); app.setTestMode(true); app.start(); } public static User getDuke() { initialize(); User duke = app.getUserDao().getUserByName("duke"); if (duke == null) duke = app.getUserDao().postUserWithDefaultPassword("duke"); duke.setEmail("duke@kunagi.org"); duke.setEmailVerified(true); return duke; } public static User getAdmin() { initialize(); User admin = app.getUserDao().getUserByName("admin"); if (admin == null) { admin = app.getUserDao().postUserWithDefaultPassword("admin"); admin.setAdmin(true); } return admin; } public static void createComments(AEntity parent, int count) { for (int i = 0; i < count; i++) { createComment(parent); } } public static Comment createComment(AEntity parent) { return createComment(parent, DateAndTime.now().addHours(Utl.randomInt(-100000, -1)), Str.generateRandomSentence(1, 2), Str.generateRandomParagraph(), true); } public static Comment createComment(AEntity parent, DateAndTime dateAndTime, String author, String text, boolean published) { Comment comment = app.getCommentDao().newEntityInstance(); comment.setParent(parent); comment.setDateAndTime(dateAndTime); comment.setAuthorName(author); comment.setText(text); comment.setPublished(published); return comment; } public static Task createTask(Requirement requirement, int number, int work) { return createTask(requirement, number, Str.generateRandomSentence(2, 6), work); } public static Task createTask(Requirement requirement, int number, String label, int work) { Task task = app.getTaskDao().newEntityInstance(); task.setRequirement(requirement); task.setNumber(number); task.setLabel(label); task.setRemainingWork(work); return task; } public static User createUser(String name) { User user = app.getUserDao().newEntityInstance(); user.setName(name); return user; } public static Issue createIssue(Project project, int number) { return createIssue(project, number, Str.generateRandomSentence(4, 8), Str.generateRandomParagraph(), Str.generateRandomParagraph(), true); } public static Issue createIssue(Project project, int number, String label, String description, String statement, boolean published) { Issue issue = app.getIssueDao().newEntityInstance(); issue.setProject(project); issue.setNumber(number); issue.setLabel(label); issue.setDescription(description); issue.setStatement(statement); issue.setPublished(published); return issue; } public static Wikipage createWikipage(Project project, String name) { String text = "== " + name + " =="; text += "\n\n" + Str.generateRandomParagraph(); text += "\n\n" + "* " + name + "\n* " + name; text += "\n\n" + Str.generateRandomParagraph(); return createWikipage(project, name, text); } public static Wikipage createWikipage(Project project, String name, String text) { Wikipage wikipage = app.getWikipageDao().newEntityInstance(); wikipage.setProject(project); wikipage.setName(name); wikipage.setText(text); return wikipage; } public static SimpleEvent createSimpleEvent(Project project, int number) { return createSimpleEvent(project, Date.inDays(number), "Event #" + number, "Location #" + number, "Note for Event #" + number); } public static SimpleEvent createSimpleEvent(Project project, Date date, String label, String location, String note) { SimpleEvent event = app.getSimpleEventDao().newEntityInstance(); event.setProject(project); event.setDate(date); event.setLabel(label); event.setLocation(location); event.setNote(note); return event; } public static Risk createRisk(Project project, int number) { return createRisk(project, number, "Risk #" + number, "Risk #" + number + " description"); } public static Risk createRisk(Project project, int number, String label, String description) { Risk risk = app.getRiskDao().newEntityInstance(); risk.setProject(project); risk.setNumber(number); risk.setLabel(label); risk.setDescription(description); risk.setImpact(number); risk.setProbability(number); return risk; } public static Impediment createImpediment(Project project, int number) { return createImpediment(project, Date.beforeDays(number), number, "Impediment #" + number, "Impediment #" + number + " description."); } public static Impediment createImpediment(Project project, Date date, int number, String label, String description) { Impediment impediment = app.getImpedimentDao().newEntityInstance(); impediment.setProject(project); impediment.setDate(date); impediment.setNumber(number); impediment.setLabel(label); impediment.setDescription(description); return impediment; } public static BlogEntry createBlogEntry(Project project, int number) { DateAndTime date = new DateAndTime(Date.beforeDays(number * 5), Time.now()); return createBlogEntry(project, number, Str.generateRandomSentence(4, 6), Str.generateRandomParagraph(), date); } public static BlogEntry createBlogEntry(Project project, int number, String title, String text, DateAndTime dateAndTime) { BlogEntry entry = app.getBlogEntryDao().newEntityInstance(); entry.setProject(project); entry.setNumber(number); entry.setTitle(title); entry.setText(text); entry.setDateAndTime(dateAndTime); return entry; } public static Requirement createRequirement(Project project, int number) { return createRequirement(project, number, Str.generateRandomSentence(4, 5) + " (#" + number + ")", Str.generateRandomParagraph(), Str.generateRandomParagraph()); } public static Requirement createRequirement(Project project, int number, String label, String description, String testDescription) { Requirement requirement = app.getRequirementDao().newEntityInstance(); requirement.setProject(project); requirement.setNumber(number); requirement.setLabel(label); requirement.setDescription(description); requirement.setTestDescription(testDescription); return requirement; } public static Sprint createSprint(Project project, Date end) { return createSprint(project, end.beforeDays(30), end); } public static Sprint createSprint(Project project, Date begin, Date end) { Sprint sprint = app.getSprintDao().newEntityInstance(); sprint.setProject(project); sprint.setBegin(begin); sprint.setEnd(end); sprint.setLabel("Sprint from " + begin + " to " + end); sprint.setGoal("Sprint from " + begin + " to " + end); return sprint; } public static Project createProject() { return createProject(getDuke()); } public static Project createProject(User admin) { return createProject(admin, Str.generateRandomWord(5, 10, true)); } public static Project createProject(User admin, String label) { Project project = app.getProjectDao().postProject(admin); project.setLabel(label); project.setShortDescription(Str.generateRandomSentence(4, 4)); project.setDescription(Str.generateRandomParagraph()); project.setLongDescription(Str.generateRandomParagraphs(5, null, null, "\n\n")); return project; } public static ScrumWebApplication getApp() { return app; } }
agpl-3.0
NoraUi/NoraUi
src/main/java/com/github/noraui/gherkin/Inequality.java
725
/** * NoraUi is licensed under the license GNU AFFERO GENERAL PUBLIC LICENSE * * @author Nicolas HALLOUIN * @author Stéphane GRILLON */ package com.github.noraui.gherkin; public enum Inequality { SUPERIOR(">"), INFERIOR("<"), SUPERIOR_OR_EQUALS(">="), INFERIOR_OR_EQUALS("<="), EQUALS("=="), NOT_EQUALS("!="); private String value; Inequality(String value) { this.value = value; } public String getValue() { return value; } public static Inequality findBySymbol(String Symbol) { for (Inequality inequality : values()) { if (inequality.value.equals(Symbol)) { return inequality; } } return null; } }
agpl-3.0
o2oa/o2oa
o2server/x_processplatform_service_processing/src/main/java/com/x/processplatform/service/processing/jaxrs/snap/ActionUpload.java
2094
package com.x.processplatform.service.processing.jaxrs.snap; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.StringUtils; import com.google.gson.JsonElement; import com.x.base.core.container.EntityManagerContainer; import com.x.base.core.container.factory.EntityManagerContainerFactory; import com.x.base.core.entity.annotation.CheckPersistType; import com.x.base.core.entity.annotation.CheckRemoveType; import com.x.base.core.project.executor.ProcessPlatformExecutorFactory; import com.x.base.core.project.http.ActionResult; import com.x.base.core.project.http.EffectivePerson; import com.x.base.core.project.jaxrs.WrapString; import com.x.processplatform.core.entity.content.Snap; class ActionUpload extends BaseAction { ActionResult<Wo> execute(EffectivePerson effectivePerson, JsonElement jsonElement) throws Exception { Snap snap = this.convertToWrapIn(jsonElement, Snap.class); check(snap); Callable<ActionResult<Wo>> callable = new Callable<ActionResult<Wo>>() { public ActionResult<Wo> call() throws Exception { ActionResult<Wo> result = new ActionResult<>(); try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { Snap exist = emc.find(snap.getId(), Snap.class); if (null != exist) { emc.beginTransaction(Snap.class); emc.remove(exist, CheckRemoveType.all); emc.commit(); } emc.beginTransaction(Snap.class); emc.persist(snap, CheckPersistType.all); emc.commit(); Wo wo = new Wo(); wo.setValue(snap.getId()); result.setData(wo); return result; } } }; return ProcessPlatformExecutorFactory.get(snap.getJob()).submit(callable).get(300, TimeUnit.SECONDS); } private boolean check(Snap snap) { if (StringUtils.isBlank(snap.getId())) { return false; } if (StringUtils.isBlank(snap.getJob())) { return false; } return !((null == snap.getProperties().getWorkCompleted()) && snap.getProperties().getWorkList().isEmpty()); } public static class Wo extends WrapString { } }
agpl-3.0
4thline/feeds
src/main/java/com/sun/syndication/io/impl/NumberParser.java
2988
package com.sun.syndication.io.impl; /** * A helper class that parses Numbers out of Strings in a lenient manner. * * <p> * No method will throw any sort of Exception when parsing a string. * All methods accept any Java String or null as legal input, if the * input is non null, whitespace will be trimmed first, and then parsing * will be attempted. * </p> * <p> * :TODO: Add Integer, Float, and Double methods as needed. * </p> */ public class NumberParser { /** * Private constructor to avoid NumberParser instances creation. */ private NumberParser() { } /** * Parses a Long out of a string. * * @param str string to parse for a Long. * @return the Long represented by the given string, * It returns <b>null</b> if it was not possible to parse the the string. */ public static Long parseLong(String str) { if (null != str) { try { return new Long(Long.parseLong(str.trim())); } catch (Exception e) { // :IGNORE: } } return null; } /** * Parse an Integer from a String. If the String is not an integer <b>null</b> is returned * and no exception is thrown. * * @param str the String to parse * @return The Integer represented by the String, or null if it could not be parsed. */ public static Integer parseInt(String str) { if (null != str) { try { return new Integer(Integer.parseInt(str.trim())); } catch (Exception e) { // :IGNORE: } } return null; } /** * Parse a Float from a String without exceptions. If the String is not a Float then null is returned * * @param str the String to parse * @return The Float represented by the String, or null if it could not be parsed. */ public static Float parseFloat(String str) { if (null != str) { try { return new Float(Float.parseFloat(str.trim())); } catch (Exception e) { // :IGNORE: } } return null; } /** * Parse a float from a String, with a default value * * @param str * @param def the value to return if the String cannot be parsed * @return */ public static float parseFloat(String str, float def) { Float result = parseFloat(str); return (result == null) ? def : result.floatValue(); } /** * Parses a long out of a string. * * @param str string to parse for a long. * @param def default value to return if it is not possible to parse the the string. * @return the long represented by the given string, or the default. */ public static long parseLong(String str, long def) { Long ret = parseLong(str); return (null == ret) ? def : ret.longValue(); } }
agpl-3.0
imCodePartnerAB/imcms
src/main/java/com/imcode/imcms/domain/service/api/FileDocumentService.java
6648
package com.imcode.imcms.domain.service.api; import com.imcode.imcms.domain.dto.DocumentDTO; import com.imcode.imcms.domain.dto.DocumentFileDTO; import com.imcode.imcms.domain.dto.FileDocumentDTO; import com.imcode.imcms.domain.service.DocumentFileService; import com.imcode.imcms.domain.service.DocumentService; import com.imcode.imcms.util.Value; import imcode.server.Config; import imcode.server.document.index.DocumentIndex; import lombok.SneakyThrows; import org.apache.commons.io.FilenameUtils; import org.apache.log4j.Logger; import org.apache.solr.common.SolrInputDocument; import org.apache.tika.Tika; import org.apache.tika.metadata.HttpHeaders; import org.apache.tika.metadata.Metadata; import org.springframework.core.io.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; /** * Service for work with File Documents only. * * @author Serhii Maksymchuk from Ubrainians for imCode * 29.12.17. */ @Service @Transactional public class FileDocumentService implements DocumentService<FileDocumentDTO> { private final Logger logger = Logger.getLogger(getClass()); private final DocumentService<DocumentDTO> defaultDocumentService; private final DocumentFileService documentFileService; private final File filesRoot; private final Predicate<DocumentFileDTO> fileDocFileFilter; private final Tika tika = Value.with(new Tika(), t -> t.setMaxStringLength(-1)); @SneakyThrows public FileDocumentService(DocumentService<DocumentDTO> documentService, DocumentFileService documentFileService, @org.springframework.beans.factory.annotation.Value("${FilePath}") Resource filesRoot, Config config) { this.defaultDocumentService = documentService; this.documentFileService = documentFileService; this.filesRoot = filesRoot.getFile(); this.fileDocFileFilter = buildFileDocFilter(config); } private static String getExtension(String filename) { return FilenameUtils.getExtension(org.apache.commons.lang3.StringUtils.trimToEmpty(filename)).toLowerCase(); } @Override public long countDocuments() { return defaultDocumentService.countDocuments(); } @Override public FileDocumentDTO get(int docId) { final FileDocumentDTO fileDocument = new FileDocumentDTO(defaultDocumentService.get(docId)); final List<DocumentFileDTO> documentFiles = documentFileService.getByDocId(docId) .stream() .map(DocumentFileDTO::new) .collect(Collectors.toList()); fileDocument.setFiles(documentFiles); return fileDocument; } public FileDocumentDTO save(FileDocumentDTO saveMe) { final int savedDocId = defaultDocumentService.save(saveMe).getId(); documentFileService.saveAll(saveMe.getFiles(), savedDocId); return saveMe; } @Override public FileDocumentDTO copy(int docId) { final int copiedDocId = defaultDocumentService.copy(docId).getId(); documentFileService.copy(docId, copiedDocId); return get(copiedDocId); } @Override public boolean publishDocument(int docId, int userId) { return defaultDocumentService.publishDocument(docId, userId); } @Override public void deleteByDocId(Integer docIdToDelete) { defaultDocumentService.deleteByDocId(docIdToDelete); } @Override public SolrInputDocument index(int docId) { final SolrInputDocument solrInputDocument = defaultDocumentService.index(docId); final FileDocumentDTO fileDocumentDTO = get(docId); fileDocumentDTO.getFiles() .stream() .filter(DocumentFileDTO::isDefaultFile) .findFirst() .filter(fileDocFileFilter) .ifPresent(documentFileDTO -> { final File file = new File(filesRoot, documentFileDTO.getFilename()); if (!file.exists()) { return; } solrInputDocument.addField(DocumentIndex.FIELD__MIME_TYPE, documentFileDTO.getMimeType()); try (final InputStream fileInputStream = new FileInputStream(file)) { final Metadata metadata = new Metadata(); metadata.set(HttpHeaders.CONTENT_DISPOSITION, documentFileDTO.getFilename()); metadata.set(HttpHeaders.CONTENT_TYPE, documentFileDTO.getMimeType()); final String content = tika.parseToString(fileInputStream, metadata); solrInputDocument.addField(DocumentIndex.FIELD__TEXT, content); } catch (Exception e) { logger.error(String.format("Unable to index doc %d file '%s'.", docId, documentFileDTO), e); } }); return solrInputDocument; } private Predicate<DocumentFileDTO> buildFileDocFilter(Config config) { final Set<String> disabledFileExtensions = config.getIndexDisabledFileExtensionsAsSet(); final Set<String> disabledFileMimes = config.getIndexDisabledFileMimesAsSet(); final boolean noIgnoredFileNamesAndExtensions = disabledFileExtensions.isEmpty() && disabledFileMimes.isEmpty(); return documentFileDTO -> { if (noIgnoredFileNamesAndExtensions) { return true; } else { final String ext = getExtension(documentFileDTO.getFilename()); final String mime = getExtension(documentFileDTO.getMimeType()); return !(disabledFileExtensions.contains(ext) || disabledFileMimes.contains(mime)); } }; } @Override public FileDocumentDTO createFromParent(Integer parentDocId) { return Value.with( new FileDocumentDTO(defaultDocumentService.createFromParent(parentDocId)), fileDocumentDTO -> fileDocumentDTO.setFiles(new ArrayList<>()) ); } @Override public List<FileDocumentDTO> getDocumentsByTemplateName(String templateName) { return null; } @Override public String getUniqueAlias(String alias) { return defaultDocumentService.getUniqueAlias(alias); } }
agpl-3.0
BrunoEberhard/open-ech
src/main/model/ch/ech/ech0020/v3/EventKeyExchange.java
442
package ch.ech.ech0020.v3; import java.util.List; import org.minimalj.model.annotation.NotEmpty; import javax.annotation.Generated; import org.minimalj.model.Keys; @Generated(value="org.minimalj.metamodel.generator.ClassGenerator") public class EventKeyExchange { public static final EventKeyExchange $ = Keys.of(EventKeyExchange.class); public Object id; @NotEmpty public List<ch.ech.ech0044.PersonIdentification> keyExchangePerson; }
agpl-3.0
malikov/platform-android
ushahidi/src/main/java/com/ushahidi/android/presentation/view/ui/form/validator/LinkValidator.java
1177
/* * Copyright (c) 2014 Ushahidi. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program in the file LICENSE-AGPL. If not, see * https://www.gnu.org/licenses/agpl-3.0.html */ package com.ushahidi.android.presentation.view.ui.form.validator; import android.util.Patterns; /** * Validator for web URLs * * @author Ushahidi Team <team@ushahidi.com> */ public class LinkValidator extends PatternValidator { /** * Default constructor * * @param errorMessage The error message */ public LinkValidator(String errorMessage) { super(errorMessage, Patterns.WEB_URL); } }
agpl-3.0
pianairco/piana-project
piana-webtool2/src/main/java/ir/piana/dev/webtool2/server/annotation/PianaServer.java
950
package ir.piana.dev.webtool2.server.annotation; import ir.piana.dev.webtool2.server.http.HttpServerType; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by ASUS on 7/28/2017. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) //on class level public @interface PianaServer { HttpServerType serverType() default HttpServerType.JETTY; String httpIp() default "localhost"; int httpPort() default 8000; String httpDocIp() default "localhost"; int httpDocPort() default 8000; String docStartUrl() default "piana-doc"; String httpBaseRoute() default ""; boolean removeOtherCookies() default false; String outputClassPath() default "./classes"; PianaServerSession serverSession() default @PianaServerSession; PianaServerCORS serverCORS() default @PianaServerCORS; }
agpl-3.0
MartinHaeusler/chronos
org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/api/SphereTransactionContext.java
427
package org.chronos.chronosphere.internal.api; import org.chronos.chronograph.api.structure.ChronoGraph; import org.chronos.chronosphere.internal.ogm.api.ChronoEPackageRegistry; public interface SphereTransactionContext { public ChronoSphereTransactionInternal getTransaction(); public default ChronoGraph getGraph() { return this.getTransaction().getGraph(); } public ChronoEPackageRegistry getChronoEPackage(); }
agpl-3.0
HedvigInsurance/bot-service
src/main/java/com/hedvig/botService/enteties/message/MessageBody.java
3263
package com.hedvig.botService.enteties.message; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.hedvig.botService.utils.ConversationUtils; import com.hedvig.botService.utils.MessageUtil; import com.hedvig.botService.enteties.UserContext; import javax.persistence.Column; import javax.persistence.DiscriminatorColumn; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import com.hedvig.libs.translations.Translations; import lombok.ToString; import static com.hedvig.botService.enteties.message.SelectItem.SELECT_POST_FIX; @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "body_type") @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @JsonSubTypes.Type(value = MessageBodyText.class, name = "text"), @JsonSubTypes.Type(value = MessageBodyNumber.class, name = "number"), @JsonSubTypes.Type(value = MessageBodySingleSelect.class, name = "single_select"), @JsonSubTypes.Type(value = MessageBodyMultipleSelect.class, name = "multiple_select"), @JsonSubTypes.Type(value = MessageBodyAudio.class, name = "audio"), @JsonSubTypes.Type(value = MessageBodyHero.class, name = "hero"), @JsonSubTypes.Type(value = MessageBodyParagraph.class, name = "paragraph"), @JsonSubTypes.Type(value = MessageBodyBankIdCollect.class, name = "bankid_collect"), @JsonSubTypes.Type(value = MessageBodyFileUpload.class, name = "file_upload") }) @ToString public class MessageBody { protected final String ID_PLACEHOLDER_POST_FIX = ".placeholder"; protected final String ID_FROM_USER_POST_FIX = ".from.user"; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public Integer id; @Column(length = 10485760) public String text; @Column(length = 10485) public String imageURL; @Column public String language; public Integer imageWidth; public Integer imageHeight; public MessageBody(String text) { this.text = text; } MessageBody() {} public void render(String id, Boolean fromUser, UserContext userContext, Translations translations) { if (text.isEmpty()) { return; } String localizationKey; if (fromUser) { if (this instanceof MessageBodySingleSelect) { localizationKey = ((MessageBodySingleSelect) this).getSelectedItem().value + SELECT_POST_FIX + ID_FROM_USER_POST_FIX; } else { localizationKey = MessageUtil.INSTANCE.getBaseMessageId(id) + ID_FROM_USER_POST_FIX; } } else { localizationKey = MessageUtil.INSTANCE.getBaseMessageId(id); } String localizedText = translations.get(localizationKey, userContext.getLocale()); if (localizedText != null) { Integer index = ConversationUtils.INSTANCE.getSplitIndexFromText(id); localizedText = ConversationUtils.INSTANCE.getSplitFromIndex(localizedText, index); } this.language = userContext.getLocale().getLanguage(); this.text = userContext.replaceWithContext(localizedText != null ? localizedText : this.text); } }
agpl-3.0
lpellegr/programming
programming-core/src/main/java/org/objectweb/proactive/core/body/reply/Reply.java
2184
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2012 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.objectweb.proactive.core.body.reply; import java.io.IOException; import org.objectweb.proactive.core.body.UniversalBody; import org.objectweb.proactive.core.body.future.MethodCallResult; import org.objectweb.proactive.core.body.message.Message; public interface Reply extends Message { public MethodCallResult getResult(); /** * Sends this reply to the body destination * @param destinationBody the body destination of this reply * @return value used by fault-tolerance mechanism. * @exception java.io.IOException if the reply fails to be sent */ public void send(UniversalBody destinationBody) throws IOException; // AUTOMATIC CONTINUATION public boolean isAutomaticContinuation(); }
agpl-3.0
horizon-institute/artcodes-android
library/src/main/java/uk/ac/horizon/artcodes/process/OtsuThresholder.java
4240
/* * Artcodes recognises a different marker scheme that allows the * creation of aesthetically pleasing, even beautiful, codes. * Copyright (C) 2013-2016 The University of Nottingham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.ac.horizon.artcodes.process; import android.content.Context; import org.opencv.core.Mat; import org.opencv.core.Size; import org.opencv.imgproc.Imgproc; import java.util.List; import java.util.Map; import uk.ac.horizon.artcodes.camera.CameraFocusControl; import uk.ac.horizon.artcodes.detect.DetectorSetting; import uk.ac.horizon.artcodes.detect.ImageBuffers; import uk.ac.horizon.artcodes.detect.handler.MarkerDetectionHandler; import uk.ac.horizon.artcodes.model.Experience; import uk.ac.horizon.artcodes.scanner.R; public class OtsuThresholder implements ImageProcessor { public static class Factory implements ImageProcessorFactory { public String getName() { return "OTSU"; } public ImageProcessor create(Context context, Experience experience, MarkerDetectionHandler handler, CameraFocusControl cameraFocusControl, Map<String, String> args) { return new OtsuThresholder(); } } private enum Display { none, greyscale, threshold; private static final Display[] vals = values(); public Display next() { return vals[(this.ordinal() + 1) % vals.length]; } } private transient int tiles = 1; private Display display = Display.none; public OtsuThresholder() { } @Override public void process(ImageBuffers buffers) { Mat image = buffers.getImageInGrey(); Imgproc.GaussianBlur(image, image, new Size(5, 5), 0); if (display == Display.greyscale) { Imgproc.cvtColor(image, buffers.getOverlay(false), Imgproc.COLOR_GRAY2BGRA); } tiles = 1; final int tileHeight = (int) image.size().height / tiles; final int tileWidth = (int) image.size().width / tiles; // Split image into tiles and apply process on each image tile separately. for (int tileRow = 0; tileRow < tiles; tileRow++) { final int startRow = tileRow * tileHeight; int endRow; if (tileRow < tiles - 1) { endRow = (tileRow + 1) * tileHeight; } else { endRow = (int) image.size().height; } for (int tileCol = 0; tileCol < tiles; tileCol++) { final int startCol = tileCol * tileWidth; int endCol; if (tileCol < tiles - 1) { endCol = (tileCol + 1) * tileWidth; } else { endCol = (int) image.size().width; } final Mat tileMat = image.submat(startRow, endRow, startCol, endCol); Imgproc.threshold(tileMat, tileMat, 127, 255, Imgproc.THRESH_OTSU); tileMat.release(); } } if (display == Display.threshold) { Imgproc.cvtColor(image, buffers.getOverlay(false), Imgproc.COLOR_GRAY2BGRA); } buffers.setImage(image); } @Override public void getSettings(List<DetectorSetting> settings) { settings.add(new DetectorSetting() { @Override public void nextValue() { display = display.next(); } @Override public int getIcon() { switch (display) { case none: return R.drawable.ic_image_24dp; case greyscale: return R.drawable.ic_gradient_24dp; case threshold: return R.drawable.ic_filter_b_and_w_24dp; } return 0; } @Override public int getText() { switch (display) { case none: return R.string.draw_threshold_off; case greyscale: return R.string.draw_threshold_greyscale; case threshold: return R.string.draw_threshold_on; } return 0; } }); } }
agpl-3.0
Asqatasun/Asqatasun
rules/rules-rgaa4.0/src/test/java/org/asqatasun/rules/rgaa40/Rgaa40Rule130501Test.java
4737
/** * Asqatasun - Automated webpage assessment * Copyright (C) 2008-2020 Asqatasun.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: asqatasun AT asqatasun DOT org */ package org.asqatasun.rules.rgaa40; import org.asqatasun.entity.audit.ProcessResult; import org.asqatasun.entity.audit.TestSolution; import org.asqatasun.rules.rgaa40.test.Rgaa40RuleImplementationTestCase; /** * Unit test class for implementation of rule 13.5.1 (referential RGAA 4.0) * * For more details about implementation, refer to <a href="https://gitlab.com/asqatasun/Asqatasun/-/blob/master/documentation/en/90_Rules/rgaa4.0/13.Consultation/Rule-13-5-1.md">rule 13.5.1 design page</a>. * @see <a href="https://www.numerique.gouv.fr/publications/rgaa-accessibilite/methode/criteres/#test-13-5-1">13.5.1 rule specification</a> */ public class Rgaa40Rule130501Test extends Rgaa40RuleImplementationTestCase { /** * Default constructor * @param testName */ public Rgaa40Rule130501Test(String testName) { super(testName); } @Override protected void setUpRuleImplementationClassName() { setRuleImplementationClassName( "org.asqatasun.rules.rgaa40.Rgaa40Rule130501"); } @Override protected void setUpWebResourceMap() { // addWebResource("Rgaa40.Test.13.5.1-1Passed-01"); // addWebResource("Rgaa40.Test.13.5.1-2Failed-01"); addWebResource("Rgaa40.Test.13.5.1-3NMI-01"); // addWebResource("Rgaa40.Test.13.5.1-4NA-01"); } @Override protected void setProcess() { //---------------------------------------------------------------------- //------------------------------1Passed-01------------------------------ //---------------------------------------------------------------------- // checkResultIsPassed(processPageTest("Rgaa40.Test.13.5.1-1Passed-01"), 1); //---------------------------------------------------------------------- //------------------------------2Failed-01------------------------------ //---------------------------------------------------------------------- // ProcessResult processResult = processPageTest("Rgaa40.Test.13.5.1-2Failed-01"); // checkResultIsFailed(processResult, 1, 1); // checkRemarkIsPresent( // processResult, // TestSolution.FAILED, // "#MessageHere", // "#CurrentElementHere", // 1, // new ImmutablePair("#ExtractedAttributeAsEvidence", "#ExtractedAttributeValue")); //---------------------------------------------------------------------- //------------------------------3NMI-01--------------------------------- //---------------------------------------------------------------------- ProcessResult processResult = processPageTest("Rgaa40.Test.13.5.1-3NMI-01"); checkResultIsNotTested(processResult); // temporary result to make the result buildable before implementation // checkResultIsPreQualified(processResult, 2, 1); // checkRemarkIsPresent( // processResult, // TestSolution.NEED_MORE_INFO, // "#MessageHere", // "#CurrentElementHere", // 1, // new ImmutablePair("#ExtractedAttributeAsEvidence", "#ExtractedAttributeValue")); //---------------------------------------------------------------------- //------------------------------4NA-01------------------------------ //---------------------------------------------------------------------- // checkResultIsNotApplicable(processPageTest("Rgaa40.Test.13.5.1-4NA-01")); } @Override protected void setConsolidate() { // The consolidate method can be removed when real implementation is done. // The assertions are automatically tested regarding the file names by // the abstract parent class assertEquals(TestSolution.NOT_TESTED, consolidate("Rgaa40.Test.13.5.1-3NMI-01").getValue()); } }
agpl-3.0
MakeITBologna/zefiro
zefiro/src/main/java/it/makeit/zefiro/dao/TaskComplete.java
4149
package it.makeit.zefiro.dao; import java.util.Date; import java.util.List; import it.makeit.alfresco.workflow.model.Candidate; import it.makeit.alfresco.workflow.model.Task; import it.makeit.zefiro.DecodedFieldNote; import it.makeit.zefiro.DecodedFieldNote.DecodingType; /** * @author Alba Quarto */ public class TaskComplete extends Task implements BaseData { private String processName; private String processTitle; private String processDescription; private String processBusinessKey; private String ProcessStartUserId; private String startUserFirstName; private String startUserLastName; private String assigneeFirstName; private String assigneeLastName; private String ownerFirstName; private String ownerLastName; private List<Candidate> candidates; private Date processStartedAt; public String getProcessName() { return processName; } public String getProcessTitle() { return processTitle; } public String getProcessDescription() { return processDescription; } public String getProcessBusinessKey() { return processBusinessKey; } public String getProcessStartUserId() { return ProcessStartUserId; } @DecodedFieldNote(decodingType = DecodingType.PROCESS, value = "name") public void setProcessName(String processName) { this.processName = processName; } @DecodedFieldNote(decodingType = DecodingType.PROCESS, value = "title") public void setProcessTitle(String processTitle) { this.processTitle = processTitle; } @DecodedFieldNote(decodingType = DecodingType.PROCESS, value = "description") public void setProcessDescription(String processDescription) { this.processDescription = processDescription; } @DecodedFieldNote(decodingType = DecodingType.PROCESS, value = "businessKey") public void setProcessBusinessKey(String processBusinessKey) { this.processBusinessKey = processBusinessKey; } @DecodedFieldNote(decodingType = DecodingType.PROCESS, value = "startUserId") public void setProcessStartUserId(String processStartUserId) { ProcessStartUserId = processStartUserId; } public String getStartUserFirstName() { return startUserFirstName; } public String getStartUserLastName() { return startUserLastName; } public String getAssigneeFirstName() { return assigneeFirstName; } public String getAssigneeLastName() { return assigneeLastName; } public String getOwnerFirstName() { return ownerFirstName; } public String getOwnerLastName() { return ownerLastName; } @DecodedFieldNote(decodingType = DecodingType.PROCESS, value = "startUserFirstName") public void setStartUserFirstName(String startUserFirstName) { this.startUserFirstName = startUserFirstName; } @DecodedFieldNote(decodingType = DecodingType.PROCESS, value = "startUserLastName") public void setStartUserLastName(String startUserLastName) { this.startUserLastName = startUserLastName; } @DecodedFieldNote(decodingType = DecodingType.ASSIGNEE, value = "firstName") public void setAssigneeFirstName(String assigneeFirstName) { this.assigneeFirstName = assigneeFirstName; } @DecodedFieldNote(decodingType = DecodingType.ASSIGNEE, value = "lastName") public void setAssigneeLastName(String assigneeLastName) { this.assigneeLastName = assigneeLastName; } @DecodedFieldNote(decodingType = DecodingType.OWNER, value = "firstName") public void setOwnerFirstName(String ownerFirstName) { this.ownerFirstName = ownerFirstName; } @DecodedFieldNote(decodingType = DecodingType.OWNER, value = "lastName") public void setOwnerLastName(String ownerLastName) { this.ownerLastName = ownerLastName; } public List<Candidate> getCandidates() { return candidates; } public void setCandidates(List<Candidate> candidates) { this.candidates = candidates; } public Date getProcessStartedAt() { return processStartedAt; } @DecodedFieldNote(decodingType = DecodingType.PROCESS, value = "startedAt") public void setProcessStartedAt(Date processStartedAt) { this.processStartedAt = processStartedAt; } }
agpl-3.0
CecileBONIN/Silverpeas-Core
lib-core/src/main/java/com/silverpeas/thumbnail/model/ThumbnailDAO.java
8093
/** * Copyright (C) 2000 - 2013 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.silverpeas.thumbnail.model; import com.stratelia.silverpeas.silvertrace.SilverTrace; import com.stratelia.webactiv.util.DBUtil; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; public class ThumbnailDAO { private static final String INSERT_THUMBNAIL = "INSERT INTO sb_thumbnail_thumbnail " + "(instanceid, objectid, objecttype, originalattachmentname, modifiedattachmentname," + "mimetype, xstart, ystart, xlength, ylength) " + "VALUES ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ?)"; private static final String UPDATE_THUMBNAIL = "UPDATE sb_thumbnail_thumbnail " + "SET xstart = ?, ystart = ?, xlength = ?, ylength = ?, originalattachmentname = ?, " + "modifiedattachmentname = ? WHERE objectId = ? AND objectType = ? AND instanceId = ? "; private static final String DELETE_THUMBNAIL = "DELETE FROM sb_thumbnail_thumbnail " + "WHERE objectId = ? AND objectType = ? AND instanceId = ? "; private static final String DELETE_COMPONENT_THUMBNAILS = "DELETE FROM sb_thumbnail_thumbnail WHERE instanceId = ?"; private static final String SELECT_THUMBNAIL_BY_PK = "SELECT instanceid, objectid, objecttype, " + "originalattachmentname, modifiedattachmentname, mimetype, xstart, ystart, xlength, " + "ylength FROM sb_thumbnail_thumbnail WHERE objectId = ? AND objectType = ? AND instanceId = ?"; private static final String MOVE_THUMBNAIL = "UPDATE sb_thumbnail_thumbnail " + " SET instanceId = ? WHERE objectId = ? AND objectType = ? AND instanceId = ? "; public static ThumbnailDetail insertThumbnail(Connection con, ThumbnailDetail thumbnailDetail) throws SQLException { PreparedStatement prepStmt = null; try { prepStmt = con.prepareStatement(INSERT_THUMBNAIL); prepStmt.setString(1, thumbnailDetail.getInstanceId()); prepStmt.setInt(2, thumbnailDetail.getObjectId()); prepStmt.setInt(3, thumbnailDetail.getObjectType()); prepStmt.setString(4, thumbnailDetail.getOriginalFileName()); if (thumbnailDetail.getCropFileName() != null) { prepStmt.setString(5, thumbnailDetail.getCropFileName()); } else { prepStmt.setNull(5, Types.VARCHAR); } if (thumbnailDetail.getMimeType() != null) { prepStmt.setString(6, thumbnailDetail.getMimeType()); } else { prepStmt.setNull(6, Types.VARCHAR); } if (thumbnailDetail.getXStart() != -1) { prepStmt.setInt(7, thumbnailDetail.getXStart()); } else { prepStmt.setNull(7, Types.INTEGER); } if (thumbnailDetail.getYStart() != -1) { prepStmt.setInt(8, thumbnailDetail.getYStart()); } else { prepStmt.setNull(8, Types.INTEGER); } if (thumbnailDetail.getXLength() != -1) { prepStmt.setInt(9, thumbnailDetail.getXLength()); } else { prepStmt.setNull(9, Types.INTEGER); } if (thumbnailDetail.getYLength() != -1) { prepStmt.setInt(10, thumbnailDetail.getYLength()); } else { prepStmt.setNull(10, Types.INTEGER); } prepStmt.executeUpdate(); } finally { DBUtil.close(prepStmt); } return thumbnailDetail; } public static void updateThumbnail(Connection con, ThumbnailDetail thumbToUpdate) throws SQLException { PreparedStatement prepStmt = null; try { prepStmt = con.prepareStatement(UPDATE_THUMBNAIL); prepStmt.setInt(1, thumbToUpdate.getXStart()); prepStmt.setInt(2, thumbToUpdate.getYStart()); prepStmt.setInt(3, thumbToUpdate.getXLength()); prepStmt.setInt(4, thumbToUpdate.getYLength()); prepStmt.setString(5, thumbToUpdate.getOriginalFileName()); prepStmt.setString(6, thumbToUpdate.getCropFileName()); prepStmt.setInt(7, thumbToUpdate.getObjectId()); prepStmt.setInt(8, thumbToUpdate.getObjectType()); prepStmt.setString(9, thumbToUpdate.getInstanceId()); prepStmt.executeUpdate(); } finally { DBUtil.close(prepStmt); } } public static void deleteThumbnail(Connection con, int objectId, int objectType, String instanceId) throws SQLException { PreparedStatement prepStmt = null; try { prepStmt = con.prepareStatement(DELETE_THUMBNAIL); prepStmt.setInt(1, objectId); prepStmt.setInt(2, objectType); prepStmt.setString(3, instanceId); prepStmt.executeUpdate(); } finally { DBUtil.close(prepStmt); } } public static void moveThumbnail(Connection con, ThumbnailDetail thumbToUpdate, String toInstanceId) throws SQLException { PreparedStatement prepStmt = null; try { prepStmt = con.prepareStatement(MOVE_THUMBNAIL); prepStmt.setString(1, toInstanceId); prepStmt.setInt(2, thumbToUpdate.getObjectId()); prepStmt.setInt(3, thumbToUpdate.getObjectType()); prepStmt.setString(4, thumbToUpdate.getInstanceId()); prepStmt.executeUpdate(); } finally { DBUtil.close(prepStmt); } } public static void deleteAllThumbnails(Connection con, String instanceId) throws SQLException { PreparedStatement prepStmt = null; try { prepStmt = con.prepareStatement(DELETE_COMPONENT_THUMBNAILS); prepStmt.setString(1, instanceId); prepStmt.executeUpdate(); } finally { DBUtil.close(prepStmt); } } public static ThumbnailDetail selectByKey(Connection con, String instanceId, int objectId, int objectType) throws SQLException { SilverTrace.info("publication", "ThumbnailDAO.selectByPubId()", "root.MSG_GEN_ENTER_METHOD", "objectId = " + objectId + "objectType" + objectType + "instanceId" + instanceId); ResultSet rs = null; ThumbnailDetail thumbnailDetail = null; PreparedStatement prepStmt = null; try { prepStmt = con.prepareStatement(SELECT_THUMBNAIL_BY_PK); prepStmt.setInt(1, objectId); prepStmt.setInt(2, objectType); prepStmt.setString(3, instanceId); rs = prepStmt.executeQuery(); if (rs.next()) { thumbnailDetail = resultSet2ThumbDetail(rs); } } finally { DBUtil.close(rs, prepStmt); } return thumbnailDetail; } static ThumbnailDetail resultSet2ThumbDetail(ResultSet rs) throws SQLException { ThumbnailDetail thumbnailDetail = new ThumbnailDetail(rs.getString("instanceid"), rs.getInt( "objectid"), rs.getInt("objecttype")); thumbnailDetail.setOriginalFileName(rs.getString("originalattachmentname")); thumbnailDetail.setCropFileName(rs.getString("modifiedattachmentname")); thumbnailDetail.setMimeType(rs.getString("mimetype")); thumbnailDetail.setXStart(rs.getInt("xstart")); thumbnailDetail.setYStart(rs.getInt("ystart")); thumbnailDetail.setXLength(rs.getInt("xlength")); thumbnailDetail.setYLength(rs.getInt("ylength")); return thumbnailDetail; } }
agpl-3.0
rakam-io/rakam
rakam-postgresql/src/main/java/org/rakam/postgresql/PostgresqlApiKeyService.java
1161
package org.rakam.postgresql; import org.rakam.analysis.JDBCPoolDataSource; import org.rakam.postgresql.analysis.JDBCApiKeyService; import javax.inject.Inject; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; public class PostgresqlApiKeyService extends JDBCApiKeyService { @Inject public PostgresqlApiKeyService(JDBCPoolDataSource connectionPool) { super(connectionPool); } @Override public void setup() { try (Connection connection = connectionPool.getConnection()) { Statement statement = connection.createStatement(); statement.execute("CREATE TABLE IF NOT EXISTS api_key (" + " id SERIAL NOT NULL,\n" + " project VARCHAR(255) NOT NULL,\n" + " write_key VARCHAR(255) NOT NULL,\n" + " master_key VARCHAR(255) NOT NULL,\n" + " created_at TIMESTAMP default current_timestamp NOT NULL," + "PRIMARY KEY (id)\n" + " )"); } catch (SQLException e) { throw new RuntimeException(e); } } }
agpl-3.0
ebonnet/Silverpeas-Core
core-library/src/main/java/org/silverpeas/core/cache/service/VolatileCacheServiceProvider.java
2507
/* * Copyright (C) 2000 - 2013 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have recieved a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.silverpeas.core.cache.service; import static org.silverpeas.core.cache.service.CacheServiceProvider.getSessionCacheService; /** * @author Yohann Chastagnier */ public class VolatileCacheServiceProvider { /** * Hidden constructor */ private VolatileCacheServiceProvider() { } /** * Gets the volatile resource cache linked to the current user session.<br/> * For example (and for now), this cache permits to handle attachments linked to a contribution * not yet persisted. In case of the user does not persist its contribution, all resources * linked to a "volatile" contribution (attachments for the example) are automatically deleted * on the user session closing. * @return the volatile resource cache linked to the current user session. */ public static VolatileResourceCacheService getSessionVolatileResourceCacheService() { VolatileResourceCacheService volatileResourceCacheService = getSessionCacheService() .get(VolatileResourceCacheService.class.getName(), VolatileResourceCacheService.class); if (volatileResourceCacheService == null) { volatileResourceCacheService = new VolatileResourceCacheService(); getSessionCacheService() .put(VolatileResourceCacheService.class.getName(), volatileResourceCacheService); } return volatileResourceCacheService; } }
agpl-3.0
ZsZs/ProcessPuzzleFramework
Implementation/DomainTier/Source/com/processpuzzle/persistence/query/transformer/domain/ConditionTransformer.java
4403
/* Name: - ConditionTransformer Description: - Requires: - Provides: - Part of: ProcessPuzzle Framework, Domain and Business Model Ready Architecture. Provides content, workflow and social networking functionality. http://www.processpuzzle.com ProcessPuzzle - Content and Workflow Management Integration Business Platform Author(s): - Zsolt Zsuffa Copyright: (C) 2011 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 com.processpuzzle.persistence.query.transformer.domain; import java.util.Stack; import com.processpuzzle.commons.persistence.query.BooleanOperator; import com.processpuzzle.commons.persistence.query.ConditionElement; import com.processpuzzle.commons.persistence.query.Operator; import com.processpuzzle.commons.persistence.query.QueryCondition; import com.processpuzzle.commons.persistence.query.QueryContext; import com.processpuzzle.persistence.query.domain.DefaultAttributeCondition; import com.processpuzzle.persistence.query.domain.DefaultQueryContext; public abstract class ConditionTransformer { protected Stack<String> operandRegister = new Stack<String>(); String createConditionFragment( String targetAlias, QueryCondition<?> condition, QueryContext context ) { if( condition.elementsCount() > 0 ){ for( ConditionElement conditionElement : condition.getElements() ){ if( conditionElement instanceof DefaultAttributeCondition ){ DefaultAttributeCondition attributeCondition = ((DefaultAttributeCondition) conditionElement); String conditionText = attributeCondition.toString(); conditionText = replaceVariablesWithValues( conditionText, context ); conditionText = replace( conditionText, attributeCondition.getAttributeName(), targetAlias + "." + attributeCondition.getAttributeName() ); operandRegister.push( conditionText ); }else if( conditionElement instanceof BooleanOperator ){ String operand_1 = operandRegister.pop(); String operand_2 = operandRegister.pop(); String operator = ((Operator) conditionElement).toString(); String result = converToInfixNotation( operand_1, operand_2, operator ); operandRegister.push( result ); } } return operandRegister.pop(); }else return ""; } protected String converToInfixNotation( String operand_1, String operand_2, String operator ) { return encloseInParentheses( operand_1 ) + " " + operator + " " + encloseInParentheses( operand_2 ); } protected String encloseInParentheses( String operand ) { String enhancedOperand = "(" + operand + ")"; return enhancedOperand; } // Private helper methods private String replaceVariablesWithValues( String condition, QueryContext context ) { String variableInCondition = DefaultQueryContext.findVariable( condition ); if( variableInCondition != null ){ String variableName = DefaultQueryContext.stripVariableName( variableInCondition ); Object variableValue = context.getAttributeValue( variableName ); if( variableValue == null ) throw new MissingQueryConditionVariable( variableName ); return replace( condition, variableInCondition, variableValue.toString() ); }else return condition; } private String replace( String str, String pattern, String replace ) { int s = 0; int e = 0; StringBuffer result = new StringBuffer(); while( (e = str.indexOf( pattern, s )) >= 0 ){ result.append( str.substring( s, e ) ); result.append( replace ); s = e + pattern.length(); } result.append( str.substring( s ) ); return result.toString(); } }
agpl-3.0
cogtool/cogtool
java/edu/cmu/cs/hcii/cogtool/model/MenuItem.java
10386
/******************************************************************************* * CogTool Copyright Notice and Distribution Terms * CogTool 1.3, Copyright (c) 2005-2013 Carnegie Mellon University * This software is distributed under the terms of the FSF Lesser * Gnu Public License (see LGPL.txt). * * CogTool is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * CogTool is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CogTool; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * CogTool makes use of several third-party components, with the * following notices: * * Eclipse SWT version 3.448 * Eclipse GEF Draw2D version 3.2.1 * * Unless otherwise indicated, all Content made available by the Eclipse * Foundation is provided to you under the terms and conditions of the Eclipse * Public License Version 1.0 ("EPL"). A copy of the EPL is provided with this * Content and is also available at http://www.eclipse.org/legal/epl-v10.html. * * CLISP version 2.38 * * Copyright (c) Sam Steingold, Bruno Haible 2001-2006 * This software is distributed under the terms of the FSF Gnu Public License. * See COPYRIGHT file in clisp installation folder for more information. * * ACT-R 6.0 * * Copyright (c) 1998-2007 Dan Bothell, Mike Byrne, Christian Lebiere & * John R Anderson. * This software is distributed under the terms of the FSF Lesser * Gnu Public License (see LGPL.txt). * * Apache Jakarta Commons-Lang 2.1 * * This product contains software developed by the Apache Software Foundation * (http://www.apache.org/) * * jopt-simple version 1.0 * * Copyright (c) 2004-2013 Paul R. Holser, Jr. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * Mozilla XULRunner 1.9.0.5 * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/. * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * The J2SE(TM) Java Runtime Environment version 5.0 * * Copyright 2009 Sun Microsystems, Inc., 4150 * Network Circle, Santa Clara, California 95054, U.S.A. All * rights reserved. U.S. * See the LICENSE file in the jre folder for more information. ******************************************************************************/ package edu.cmu.cs.hcii.cogtool.model; import java.util.ArrayList; import java.util.List; import edu.cmu.cs.hcii.cogtool.util.ObjectLoader; import edu.cmu.cs.hcii.cogtool.util.ObjectSaver; public class MenuItem extends AMenuWidget implements ChildWidget { public static final int edu_cmu_cs_hcii_cogtool_model_MenuItem_version = 0; protected static final String parentVAR = "parent"; private static ObjectSaver.IDataSaver<MenuItem> SAVER = new ObjectSaver.ADataSaver<MenuItem>() { @Override public int getVersion() { return edu_cmu_cs_hcii_cogtool_model_MenuItem_version; } @Override public void saveData(MenuItem v, ObjectSaver saver) throws java.io.IOException { saver.saveObject(v.parent, parentVAR); } }; public static void registerSaver() { ObjectSaver.registerSaver(MenuItem.class.getName(), SAVER); } private static ObjectLoader.IObjectLoader<MenuItem> LOADER = new ObjectLoader.AObjectLoader<MenuItem>() { @Override public MenuItem createObject() { return new MenuItem(); } @Override public void set(MenuItem target, String variable, Object value) { if (variable != null) { if (variable.equals(parentVAR)) { target.parent = (AMenuWidget) value; } } } }; public static void registerLoader() { ObjectLoader.registerLoader(MenuItem.class.getName(), edu_cmu_cs_hcii_cogtool_model_MenuItem_version, LOADER); } protected AMenuWidget parent; protected MenuItem() { // For loading and duplicating super(NO_CHILDREN, AParentWidget.CHILDREN_RIGHT); } public MenuItem(AMenuWidget header, DoubleRectangle bounds, String useTitle) { super(bounds, WidgetType.MenuItem, NO_CHILDREN, AParentWidget.CHILDREN_RIGHT); parent = header; parent.addItem(this); setTitle(useTitle); } @Override public MenuHeader getTopHeader() { if (parent != null) { return parent.getTopHeader(); } return null; } @Override public ContextMenu getContextMenu() { if (parent != null) { return parent.getContextMenu(); } return null; } public AParentWidget getParent() { return parent; } public void setParent(AParentWidget menuParent) { parent = (AMenuWidget) menuParent; } @Override public FrameElement getRootElement() { return parent.getRootElement(); } public boolean isSubmenu() { return (widgetType == WidgetType.Submenu); } @Override public boolean canHaveChildren() { return isSubmenu(); } public void setSubmenu(boolean menu) { if (menu) { widgetType = WidgetType.Submenu; childItems = new SimpleWidgetGroup(SimpleWidgetGroup.VERTICAL); childItems.setAuthority(parentGroup); } else { widgetType = WidgetType.MenuItem; //TODO:mlh assert this.childItems.widgetCount() is zero? childItems = null; } raiseAlert(new Widget.WidgetChange(this, Widget.WidgetChange.TYPE)); } @Override public void addItem(int index, ChildWidget item) { if (widgetType != WidgetType.Submenu) { setSubmenu(true); } super.addItem(index, item); } @Override public boolean removeItem(ChildWidget item) { if (super.removeItem(item)) { if (itemCount() == 0) { setSubmenu(false); } return true; } return false; } /** * Looks at all of the transitions of all of its parent's children and finds * the smallest curve index not in use */ @Override public void assignCurveIndex(Transition t) { List<Transition> allTransitions = new ArrayList<Transition>(); // TODO Curves are not currently being assigned when doing an import // from XML, because the parent is not yet set. This is a bug, and // should be fixed. Ticket #775 MenuHeader header = getTopHeader(); ContextMenu menu = getContextMenu(); if (header != null) { header.addAllTransitions(allTransitions); } else if (menu != null) { menu.addAllTransitions(allTransitions); } int[] indexes = new int[allTransitions.size()]; t.setCurveIndex(computeCurveIndex(t, allTransitions.iterator(), indexes)); } /** * Create a "deep" copy of this widget. * <p> * It is the responsibility of the caller to "place" the copy * (usually by adding it to an Frame). * * @param duplicator the manager of duplicate Frame instances * @return the widget copy * @author mlh */ public ChildWidget duplicate(AParentWidget copyParent, Frame.IFrameDuplicator duplicator, SimpleWidgetGroup.IWidgetDuplicator situator) { MenuItem widgetCopy = new MenuItem(); widgetCopy.setParent(copyParent); widgetCopy.setSubmenu(isSubmenu()); widgetCopy.copyState(this, duplicator, situator); situator.placeInContext(this, widgetCopy); return widgetCopy; } public ChildWidget duplicate(AParentWidget copyParent, Frame.IFrameDuplicator duplicator, SimpleWidgetGroup.IWidgetDuplicator situator, int insertIndex) { ChildWidget childCopy = duplicate(copyParent, duplicator, situator); copyParent.addItem(insertIndex, childCopy); return childCopy; } }
lgpl-2.1
windauer/exist
exist-core/src/main/java/org/exist/xquery/functions/system/Restore.java
7396
/* * eXist Open Source Native XML Database * Copyright (C) 2001-2011 The eXist-db Project * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * \$Id\$ */ package org.exist.xquery.functions.system; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.dom.QName; import org.exist.dom.memtree.MemTreeBuilder; import org.exist.security.SecurityManager; import org.exist.security.Subject; import org.exist.storage.BrokerPool; import org.exist.storage.DBBroker; import org.exist.storage.txn.Txn; import org.exist.xquery.BasicFunction; import org.exist.xquery.Cardinality; import org.exist.xquery.FunctionSignature; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.FunctionParameterSequenceType; import org.exist.xquery.value.NodeValue; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.Type; import java.nio.file.Paths; import java.util.Optional; import org.exist.backup.restore.listener.AbstractRestoreListener; import org.exist.backup.restore.listener.RestoreListener; import static org.exist.xquery.functions.system.SystemModule.functionSignatures; import static org.exist.xquery.FunctionDSL.*; public class Restore extends BasicFunction { protected final static Logger logger = LogManager.getLogger(Restore.class); public static final FunctionParameterSequenceType PARAM_DIR_OR_FILE = param("dir-or-file", Type.STRING, "This is either a backup directory with the backup descriptor (__contents__.xml) or a backup ZIP file."); public static final FunctionParameterSequenceType PARAM_ADMIN_PASS = optParam("admin-pass", Type.STRING, "The password for the admin user"); public static final FunctionParameterSequenceType PARAM_NEW_ADMIN_PASS = optParam("new-admin-pass", Type.STRING, "Set the admin password to this new password."); private static final String FS_RESTORE_NAME = "restore"; static final FunctionSignature[] FS_RESTORE = functionSignatures( FS_RESTORE_NAME, "Restore the database or a section of the database (admin user only).", returns(Type.NODE, "the restore results"), arities( arity( PARAM_DIR_OR_FILE, PARAM_ADMIN_PASS, PARAM_NEW_ADMIN_PASS ), arity( PARAM_DIR_OR_FILE, PARAM_ADMIN_PASS, PARAM_NEW_ADMIN_PASS, param("overwrite", Type.BOOLEAN, "Should newer versions of apps installed in the database be overwritten " + "by those found in the backup? False by default.") ) ) ); public final static QName RESTORE_ELEMENT = new QName("restore", SystemModule.NAMESPACE_URI, SystemModule.PREFIX); public Restore(XQueryContext context, FunctionSignature signature) { super(context, signature); } @Override public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { final String dirOrFile = args[0].getStringValue(); String adminPass = null; if (args[1].hasOne()) {adminPass = args[1].getStringValue();} String adminPassAfter = null; if (args[2].hasOne()) {adminPassAfter = args[2].getStringValue();} final boolean overwriteApps = args.length == 4 && args[3].effectiveBooleanValue(); final MemTreeBuilder builder = context.getDocumentBuilder(); builder.startDocument(); builder.startElement(RESTORE_ELEMENT, null); final BrokerPool pool = context.getBroker().getBrokerPool(); try { final Subject admin = pool.getSecurityManager().authenticate(SecurityManager.DBA_USER, adminPass); try (final DBBroker broker = pool.get(Optional.of(admin)); final Txn transaction = broker.continueOrBeginTransaction()) { final RestoreListener listener = new XMLRestoreListener(builder); final org.exist.backup.Restore restore = new org.exist.backup.Restore(); restore.restore(broker, transaction, adminPassAfter, Paths.get(dirOrFile), listener, overwriteApps); transaction.commit(); } } catch (final Exception e) { throw new XPathException(this, "restore failed with exception: " + e.getMessage(), e); } builder.endElement(); builder.endDocument(); return (NodeValue) builder.getDocument().getDocumentElement(); } private static class XMLRestoreListener extends AbstractRestoreListener { public final static QName COLLECTION_ELEMENT = new QName("collection", SystemModule.NAMESPACE_URI, SystemModule.PREFIX); public final static QName RESOURCE_ELEMENT = new QName("resource", SystemModule.NAMESPACE_URI, SystemModule.PREFIX); public final static QName INFO_ELEMENT = new QName("info", SystemModule.NAMESPACE_URI, SystemModule.PREFIX); public final static QName WARN_ELEMENT = new QName("warn", SystemModule.NAMESPACE_URI, SystemModule.PREFIX); public final static QName ERROR_ELEMENT = new QName("error", SystemModule.NAMESPACE_URI, SystemModule.PREFIX); private final MemTreeBuilder builder; private XMLRestoreListener(final MemTreeBuilder builder) { this.builder = builder; } @Override public void createdCollection(final String collection) { builder.startElement(COLLECTION_ELEMENT, null); builder.characters(collection); builder.endElement(); } @Override public void restoredResource(final String resource) { builder.startElement(RESOURCE_ELEMENT, null); builder.characters(resource); builder.endElement(); } @Override public void info(String message) { builder.startElement(INFO_ELEMENT, null); builder.characters(message); builder.endElement(); } @Override public void warn(final String message) { builder.startElement(WARN_ELEMENT, null); builder.characters(message); builder.endElement(); } @Override public void error(final String message) { builder.startElement(ERROR_ELEMENT, null); builder.characters(message); builder.endElement(); } } }
lgpl-2.1
netarchivesuite/netarchivesuite-svngit-migration
tests/dk/netarkivet/common/tools/ExtractCDXTester.java
5510
/*$Id$ * $Revision$ * $Date$ * $Author$ * * The Netarchive Suite - Software to harvest and preserve websites * Copyright 2004-2012 The Royal Danish Library, the Danish State and * University Library, the National Library of France and the Austrian * National Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package dk.netarkivet.common.tools; import dk.netarkivet.common.utils.cdx.CDXRecord; import dk.netarkivet.testutils.preconfigured.MoveTestFiles; import dk.netarkivet.testutils.preconfigured.PreserveStdStreams; import dk.netarkivet.testutils.preconfigured.PreventSystemExit; import junit.framework.TestCase; import java.io.File; import java.util.ArrayList; import java.util.List; /** * We do not test behaviour on bad ARC files, * relying on the unit test of ExtractCDXJob. */ public class ExtractCDXTester extends TestCase { private PreventSystemExit pse = new PreventSystemExit(); private PreserveStdStreams pss = new PreserveStdStreams(true); private MoveTestFiles mtf = new MoveTestFiles( TestInfo.DATA_DIR, TestInfo.WORKING_DIR); public void setUp(){ mtf.setUp(); pss.setUp(); pse.setUp(); } public void tearDown(){ pse.tearDown(); pss.tearDown(); mtf.tearDown(); } /** * Verify that indexing a single ARC file works as expected. */ public void testMainOneFile() { File arcfile = TestInfo.ARC1; ExtractCDX.main(new String[]{ arcfile.getAbsolutePath() }); List<CDXRecord> rList = getRecords(); assertEquals( "Output CDX records should be 1-1 with input ARC file records", 1, rList.size()); assertMatches(rList, 0, TestInfo.ARC1_URI, TestInfo.ARC1_MIME, TestInfo.ARC1_CONTENT); } /** * Verify that indexing more than one ARC file works as expected. */ public void testMainSeveralFiles() { ExtractCDX.main(new String[]{ TestInfo.ARC1.getAbsolutePath(), TestInfo.ARC2.getAbsolutePath()}); List<CDXRecord> rList = getRecords(); assertEquals( "Output CDX records should be 1-1 with input ARC file records", 2, rList.size()); assertMatches(rList, 0, TestInfo.ARC1_URI, TestInfo.ARC1_MIME, TestInfo.ARC1_CONTENT); assertMatches(rList, 1, TestInfo.ARC2_URI, TestInfo.ARC2_MIME, TestInfo.ARC2_CONTENT); } /** * Verify that non-ARC files are rejected and execution fails. */ public void testMainNonArc() { try { ExtractCDX.main(new String[]{ TestInfo.ARC1.getAbsolutePath(), TestInfo.INDEX_FILE.getAbsolutePath()}); fail("Calling ExtractCDX with non-arc file should System.exit"); } catch (SecurityException e) { //Expected assertEquals( "No output should be sent to stdout when ExtraqctCDX fails", "", pss.getOut()); } } /** * Verifies that calling ExtractCDX without arguments fails. */ public void testNoArguments() { try { ExtractCDX.main(new String[]{}); fail("Calling ExtractCDX without arguments should System.exit"); } catch (SecurityException e) { //Expected assertEquals( "No output should be sent to stdout when ExtraqctCDX fails", "", pss.getOut()); } } /** * Parses output from stdOut as a cdx file. * @return All records from the output cdx file, as a List. */ private List<CDXRecord> getRecords() { List<CDXRecord> result = new ArrayList<CDXRecord>(); for (String cdxLine : pss.getOut().split("\n")) { result.add(new CDXRecord(cdxLine.split("\\s+"))); } return result; } /** * Asserts that the nth record in the given list * has the specified uri and mimetype, and the * the length field matches the length of the given * content. */ private void assertMatches( List<CDXRecord> rList, int index, String uri, String mime, String content) { CDXRecord rec = rList.get(index); assertEquals( "Output CDX records should be 1-1 with input ARC file records", uri, rec.getURL()); assertEquals( "Output CDX records should be 1-1 with input ARC file records", mime, rec.getMimetype()); assertEquals( "Output CDX records should be 1-1 with input ARC file records", content.length(), rec.getLength()); } }
lgpl-2.1
IDgis/geo-publisher
publisher-commons/src/main/java/nl/idgis/publisher/stream/messages/End.java
265
package nl.idgis.publisher.stream.messages; import java.io.Serializable; public class End implements Serializable{ private static final long serialVersionUID = -9124523083667024682L; @Override public String toString() { return "End []"; } }
lgpl-2.1
opendatatrentino/s-match
src/main/java/it/unitn/disi/nlptools/components/PipelineComponentException.java
560
package it.unitn.disi.nlptools.components; import it.unitn.disi.common.components.ConfigurableException; /** * Exception for pipeline components. * * @author <a rel="author" href="http://autayeu.com/">Aliaksandr Autayeu</a> */ public class PipelineComponentException extends ConfigurableException { public PipelineComponentException(String errorDescription) { super(errorDescription); } public PipelineComponentException(String errorDescription, Throwable cause) { super(errorDescription, cause); } }
lgpl-2.1
mbatchelor/pentaho-reporting
libraries/libpixie/src/main/java/org/pentaho/reporting/libraries/pixie/wmf/bitmap/BitmapCompression.java
3049
/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * 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 Lesser General Public License for more details. * * Copyright (c) 2001 - 2013 Object Refinery Ltd, Hitachi Vantara and Contributors.. All rights reserved. */ package org.pentaho.reporting.libraries.pixie.wmf.bitmap; import java.io.IOException; import java.io.InputStream; public abstract class BitmapCompression { private int height; private int width; private int bpp; private boolean topDown; protected BitmapCompression() { } public void setDimension( final int width, final int height ) { this.width = width; this.height = height; } public int getHeight() { return height; } public int getWidth() { return width; } public int getBpp() { return bpp; } public void setBpp( final int bpp ) { this.bpp = bpp; } public void setTopDown( final boolean b ) { this.topDown = b; } public boolean isTopDown() { return topDown; } public abstract int[] decompress( InputStream in, GDIPalette palette ) throws IOException; public static int[] expandMonocrome( final int b, final GDIPalette pal ) { final int tColor = pal.lookupColor( 1 ); final int fColor = pal.lookupColor( 0 ); final int[] retval = new int[ 8 ]; if ( ( b & 0x01 ) == 0x01 ) { retval[ 0 ] = tColor; } else { retval[ 0 ] = fColor; } if ( ( b & 0x02 ) == 0x02 ) { retval[ 1 ] = tColor; } else { retval[ 1 ] = fColor; } if ( ( b & 0x04 ) == 0x04 ) { retval[ 2 ] = tColor; } else { retval[ 2 ] = fColor; } if ( ( b & 0x08 ) == 0x08 ) { retval[ 3 ] = tColor; } else { retval[ 3 ] = fColor; } if ( ( b & 0x10 ) == 0x10 ) { retval[ 4 ] = tColor; } else { retval[ 4 ] = fColor; } if ( ( b & 0x20 ) == 0x20 ) { retval[ 5 ] = tColor; } else { retval[ 5 ] = fColor; } if ( ( b & 0x40 ) == 0x40 ) { retval[ 6 ] = tColor; } else { retval[ 6 ] = fColor; } if ( ( b & 0x80 ) == 0x80 ) { retval[ 7 ] = tColor; } else { retval[ 7 ] = fColor; } return retval; } public static int[] expand4BitTuple( final int b, final GDIPalette pal ) { final int[] retval = new int[ 2 ]; retval[ 0 ] = pal.lookupColor( ( b & 0xF0 ) >> 4 ); retval[ 1 ] = pal.lookupColor( b & 0x0F ); return retval; } }
lgpl-2.1
acionescu/mdb-commons
src/test/java/ro/zg/mdb/test/robo/RoboSimulation.java
4423
/******************************************************************************* * Copyright 2011 Adrian Cristian Ionescu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package ro.zg.mdb.test.robo; import java.util.HashSet; import java.util.Set; import ro.zg.mdb.core.meta.persistence.MdbInstance; import ro.zg.mdb.core.meta.persistence.SchemaManager; import ro.zg.mdb.core.meta.persistence.data.MdbConfig; import ro.zg.mdb.persistence.MemoryPersistenceManager; import ro.zg.util.statistics.Monitor; public class RoboSimulation { private static MemoryPersistenceManager mpm = new MemoryPersistenceManager(); private SchemaManager dao; private Set<RobotManager> robots = new HashSet<RobotManager>(); private int maxSlotPos = 100; private int minSlotPos = 0; private int robotsPerType = 100; private int maxTurns = 100; private SlotManager slotManager; public RoboSimulation(SchemaManager dao) { super(); this.dao = dao; } public void test1() throws InterruptedException { maxSlotPos = 100; minSlotPos = 0; robotsPerType = 100; maxTurns = 100; slotManager = new SlotManager(dao); Robot r = null; for (int i = 0; i < robotsPerType; i++) { r = new SlotCreatorRobot(getRandomPos()); startRobot(r); r = new SlotUpdaterRobot(getRandomPos()); startRobot(r); r = new SlotReaderRobot(getRandomPos()); startRobot(r); r = new SlotDestroyerRobot(getRandomPos()); startRobot(r); } System.out.println("running..."); for (RobotManager rm : robots) { rm.join(); } } public void test2() throws InterruptedException { maxSlotPos = 1; minSlotPos = 0; robotsPerType = 100; maxTurns = 100; slotManager = new SlotManager(dao); Robot r = null; for (int i = 0; i < robotsPerType; i++) { r = new SlotCreatorRobot(getRandomPos(),false); startRobot(r); r = new SlotUpdaterRobot(getRandomPos(),false); startRobot(r); r = new SlotReaderRobot(getRandomPos(),false); startRobot(r); r = new SlotDestroyerRobot(getRandomPos(),false); startRobot(r); } System.out.println("running..."); for (RobotManager rm : robots) { rm.join(); } } private int getRandomPos() { return minSlotPos + (int) (Math.random() * (maxSlotPos - minSlotPos)); } private void startRobot(Robot r) throws InterruptedException { RobotManager rm = new RobotManager(r); robots.add(rm); rm.start(); } private synchronized void printError(Exception e) { e.printStackTrace(); mpm.print(System.out); System.exit(100); } private class RobotManager extends Thread { private Robot robot; public RobotManager(Robot robot) { super(); this.robot = robot; } public void run() { int turn = 0; while (turn++ < maxTurns) { Monitor m = Monitor.getMonitor("Robot"); long counterId = m.startCounter(); try { robot.executeTurn(new RobotContext(slotManager)); } catch (Exception e) { printError(e); } m.stopCounter(counterId); if (robot.getPosition() < minSlotPos) { robot.setPosition(maxSlotPos); } if (robot.getPosition() > maxSlotPos) { robot.setPosition(minSlotPos); } Thread.yield(); } } } public static void main(String[] args) throws Exception { SchemaManager sm = new MdbInstance("TestInstance",mpm,new MdbConfig()).getSchema("RoboSim"); RoboSimulation sim = new RoboSimulation(sm); sim.test1(); // sim.test2(); mpm.print(System.out); sim.slotManager.printStats(System.out); Monitor.getMonitor("Robot").printStats(System.out); // sm.createCommand(Slot.class).insert(new Slot(567,'T')).execute(); // long updated = sm.createCommand(Slot.class).update(new Slot(567, 'P')).where().field("position").eq(567) // .execute(); // System.out.println(updated); // mpm.print(System.out); } }
lgpl-2.1
trejkaz/jna
contrib/x11/src/jnacontrib/x11/api/X.java
43606
/* Copyright (c) 2008 Stefan Endrullis, All Rights Reserved * * The contents of this file is dual-licensed under 2 * alternative Open Source/Free licenses: LGPL 2.1 or later and * Apache License 2.0. (starting with JNA version 4.0.0). * * You can freely decide which license you want to apply to * the project. * * You may obtain a copy of the LGPL License at: * * http://www.gnu.org/licenses/licenses.html * * A copy is also included in the downloadable source code package * containing JNA, in file "LGPL2.1". * * You may obtain a copy of the Apache License at: * * http://www.apache.org/licenses/ * * A copy is also included in the downloadable source code package * containing JNA, in file "AL2.0". */ package jnacontrib.x11.api; import com.sun.jna.Native; import com.sun.jna.NativeLong; import com.sun.jna.Pointer; import com.sun.jna.Memory; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.NativeLongByReference; import com.sun.jna.ptr.PointerByReference; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.ArrayList; import java.awt.Rectangle; import com.sun.jna.platform.unix.X11; import com.sun.jna.platform.unix.X11.Atom; import com.sun.jna.platform.unix.X11.WindowByReference; /** * Object oriented X window system. * <p/> * Some code segments in this class are based on the code of the program * wmctrl (licensed under GPLv2) written by Tomas Styblo &lt;tripie@cpan.org&gt;. * Thanks a lot, Tomas! * * @author Stefan Endrullis */ public class X { /** Remove/unset property. */ public static final int _NET_WM_STATE_REMOVE = 0; /** Add/set property. */ public static final int _NET_WM_STATE_ADD = 1; /** Toggle property. */ public static final int _NET_WM_STATE_TOGGLE = 2; /** Maximal property value length. */ public static final int MAX_PROPERTY_VALUE_LEN = 4096; private static final X11 x11 = X11.INSTANCE; private static int bytesToInt(byte[] prop) { return ((prop[3] & 0xff) << 24) | ((prop[2] & 0xff) << 16) | ((prop[1] & 0xff) << 8) | ((prop[0] & 0xff)); } private static int bytesToInt(byte[] prop, int offset) { return ((prop[3 + offset] & 0xff) << 24) | ((prop[2 + offset] & 0xff) << 16) | ((prop[1 + offset] & 0xff) << 8) | ((prop[offset] & 0xff)); } /** * X Display. */ public static class Display { /** * Open display. */ private X11.Display x11Display; /** * HashMap<String,X11.Atom>. */ private HashMap<String, Atom> atomsHash = new HashMap<String, Atom>(); /** * Creates the OOWindowUtils using the default display. */ public Display() { x11Display = x11.XOpenDisplay(null); if (x11Display == null) { throw new Error("Can't open X Display"); } } /** * Creates the OOWindowUtils using a given display. * * @param x11Display open display */ public Display(X11.Display x11Display) { this.x11Display = x11Display; if (x11Display == null) { throw new Error("X Display is null"); } } /** * Closes the display. */ public void close() { x11.XCloseDisplay(x11Display); } /** * Flushes the output buffer / event queue. */ public void flush() { x11.XFlush(x11Display); } /** * Returns the X11 display. * * @return X11 display */ public X11.Display getX11Display() { return x11Display; } /** * Get internal atoms by name. * * @param name name of the atom * @return atom */ public X11.Atom getAtom(String name) { X11.Atom atom = atomsHash.get(name); if (atom == null) { atom = x11.XInternAtom(x11Display, name, false); atomsHash.put(name, atom); } return atom; } /** * Returns the window manager information as an window. * * @return window manager information as an window * @throws X11Exception thrown if X11 window errors occurred */ public Window getWindowManagerInfo() throws X11Exception { Window rootWindow = getRootWindow(); try { return rootWindow.getWindowProperty(X11.XA_WINDOW, "_NET_SUPPORTING_WM_CHECK"); } catch (X11Exception e) { try { return rootWindow.getWindowProperty(X11.XA_CARDINAL, "_WIN_SUPPORTING_WM_CHECK"); } catch (X11Exception e1) { throw new X11Exception("Cannot get window manager info properties. (_NET_SUPPORTING_WM_CHECK or _WIN_SUPPORTING_WM_CHECK)"); } } } /** * Returns the root window. * * @return root window */ public Window getRootWindow() { return new Window(this, x11.XDefaultRootWindow(x11Display)); } /** * Returns the current active window. * * @return current active window * @throws X11Exception thrown if X11 window errors occurred */ public Window getActiveWindow() throws X11Exception { return getRootWindow().getWindowProperty(X11.XA_WINDOW, "_NET_ACTIVE_WINDOW"); } /** * Returns all windows managed by the window manager. * * @return all windows managed by the window manager * @throws X11Exception thrown if X11 window errors occurred */ public Window[] getWindows() throws X11Exception { byte[] bytes; Window rootWindow = getRootWindow(); try { bytes = rootWindow.getProperty(X11.XA_WINDOW, "_NET_CLIENT_LIST"); } catch (X11Exception e) { try { bytes = rootWindow.getProperty(X11.XA_CARDINAL, "_WIN_CLIENT_LIST"); } catch (X11Exception e1) { throw new X11Exception("Cannot get client list properties (_NET_CLIENT_LIST or _WIN_CLIENT_LIST)"); } } Window[] windowList = new Window[bytes.length / X11.Window.SIZE]; for (int i = 0; i < windowList.length; i++) { windowList[i] = new Window(this, new X11.Window(bytesToInt(bytes, X11.XID.SIZE * i))); } return windowList; } /** * Returns the number of desktops. * * @return number of desktops * @throws X11Exception thrown if X11 window errors occurred */ public int getDesktopCount() throws X11Exception { Window root = getRootWindow(); try { return root.getIntProperty(X11.XA_CARDINAL, "_NET_NUMBER_OF_DESKTOPS"); } catch (X11Exception e) { try { return root.getIntProperty(X11.XA_CARDINAL, "_WIN_WORKSPACE_COUNT"); } catch (X11Exception e1) { throw new X11Exception("Cannot get number of desktops properties (_NET_NUMBER_OF_DESKTOPS or _WIN_WORKSPACE_COUNT)"); } } } /** * Returns the number of the active desktop. * * @return number of the active desktop * @throws X11Exception thrown if X11 window errors occurred */ public int getActiveDesktopNumber() throws X11Exception { Window root = getRootWindow(); int cur_desktop; try { cur_desktop = root.getIntProperty(X11.XA_CARDINAL, "_NET_CURRENT_DESKTOP"); } catch (X11Exception e) { try { cur_desktop = root.getIntProperty(X11.XA_CARDINAL, "_WIN_WORKSPACE"); } catch (X11Exception e1) { throw new X11Exception("Cannot get current desktop properties (_NET_CURRENT_DESKTOP or _WIN_WORKSPACE property)"); } } return cur_desktop; } /** * Returns the available desktops. * * @return available desktops * @throws X11Exception thrown if X11 window errors occurred */ public Desktop[] getDesktops() throws X11Exception { Window root = getRootWindow(); String[] desktopNames; try { desktopNames = root.getUtf8ListProperty(getAtom("UTF8_STRING"), "_NET_DESKTOP_NAMES"); } catch (X11Exception e) { try { desktopNames = root.getStringListProperty(X11.XA_STRING, "_WIN_WORKSPACE_NAMES"); } catch (X11Exception e1) { throw new X11Exception("Cannot get desktop names properties (_NET_DESKTOP_NAMES or _WIN_WORKSPACE_NAMES)"); } } Desktop[] desktops = new Desktop[getDesktopCount()]; for (int i = 0; i < desktops.length; i++) { desktops[i] = new Desktop(this, i, desktopNames[i]); } return desktops; } /** * Switches to the given desktop. * * @param nr desktop number * @throws X11Exception thrown if X11 window errors occurred */ public void switchDesktop(int nr) throws X11Exception { getRootWindow().clientMsg("_NET_CURRENT_DESKTOP", nr, 0, 0, 0, 0); } /** * Sets the "showing the desktop" state. * * @param state true if the desktop should be shown * @throws X11Exception thrown if X11 window errors occurred */ public void showingDesktop(boolean state) throws X11Exception { getRootWindow().clientMsg("_NET_SHOWING_DESKTOP", state ? 1 : 0, 0, 0, 0, 0); } /** * Enables / disables the auto-repeat of pressed keys. * * @param on true if auto-repeat shall be enabled */ public void setKeyAutoRepeat(boolean on) { if (on) { x11.XAutoRepeatOn(x11Display); } else { x11.XAutoRepeatOff(x11Display); } } /** * Returns the key symbol corresponding to the the key name. * * @param keyName name of the key * @return key symbol */ public X11.KeySym getKeySym(String keyName) { return x11.XStringToKeysym(keyName); } /** * Returns the key symbol corresponding to the keycode. * * @param keyCode keycode * @param index element of the keycode vector * @return key symbol */ public X11.KeySym getKeySym(byte keyCode, int index) { return x11.XKeycodeToKeysym(x11Display, keyCode, index); } /** * Returns the keycode corresponding to the key symbol. * * @param keySym key symbol * @return keycode */ public byte getKeyCode(X11.KeySym keySym) { return x11.XKeysymToKeycode(x11Display, keySym); } /** * Returns the keycode corresponding to the key name. * * @param keyName name of the key * @return keycode */ public byte getKeyCode(String keyName) { return x11.XKeysymToKeycode(x11Display, getKeySym(keyName)); } /** * Returns the key name corresponding to the key symbol. * * @param keySym key symbol * @return name of the key */ public String getKeyName(X11.KeySym keySym) { return x11.XKeysymToString(keySym); } /** * Returns the key name corresponding to the keycode and the index in the keycode vector. * * @param keyCode keycode * @param index index in the keycode vector * @return name of the key */ public String getKeyName(byte keyCode, int index) { return getKeyName(getKeySym(keyCode, index)); } /** * Returns the modifier keymap. * * @return modifier keymap */ public ModifierKeymap getModifierKeymap() { X11.XModifierKeymapRef xModifierKeymapRef = x11.XGetModifierMapping(x11Display); ModifierKeymap modifierKeymap = new ModifierKeymap(xModifierKeymapRef); x11.XFreeModifiermap(xModifierKeymapRef); return modifierKeymap; } /** * Sets the modifier keymap. * * @param modifierKeymap modifier keymap */ public void setModifierKeymap(ModifierKeymap modifierKeymap) { X11.XModifierKeymapRef xModifierKeymapRef = modifierKeymap.toXModifierKeyamp(); x11.XSetModifierMapping(x11Display,xModifierKeymapRef); } } /** * Modifier keymap. The lists shift, lock, control, mod1, mod1, mod1, mod1, mod1 * contain the keycodes as Byte objects. You can directly access these lists to * read, replace, remove or insert new keycodes to these modifiers. * To apply a new modifier keymap call * {@link X.Display#setModifierKeymap(ModifierKeymap)}. */ public static class ModifierKeymap { /** Shift modifier as an ArrayList&lt;Byte&gt;. */ public ArrayList<Byte> shift = new ArrayList<Byte>(4); /** Lock modifier as an ArrayList&lt;Byte&gt;. */ public ArrayList<Byte> lock = new ArrayList<Byte>(4); /** Control modifier as an ArrayList&lt;Byte&gt;. */ public ArrayList<Byte> control = new ArrayList<Byte>(4); /** Mod1 modifier as an ArrayList&lt;Byte&gt;. */ public ArrayList<Byte> mod1 = new ArrayList<Byte>(4); /** Mod2 modifier as an ArrayList&lt;Byte&gt;. */ public ArrayList<Byte> mod2 = new ArrayList<Byte>(4); /** Mod3 modifier as an ArrayList&lt;Byte&gt;. */ public ArrayList<Byte> mod3 = new ArrayList<Byte>(4); /** Mod4 modifier as an ArrayList&lt;Byte&gt;. */ public ArrayList<Byte> mod4 = new ArrayList<Byte>(4); /** Mod5 modifier as an ArrayList&lt;Byte&gt;. */ public ArrayList<Byte> mod5 = new ArrayList<Byte>(4); /** * Creates an empty modifier keymap. */ public ModifierKeymap() { } /** * Creates a modifier keymap and reads the modifiers from the XModifierKeymap. * * @param xModifierKeymapRef XModifierKeymap */ public ModifierKeymap(X11.XModifierKeymapRef xModifierKeymapRef) { fromXModifierKeymap(xModifierKeymapRef); } /** * Reads all modifiers from the XModifierKeymap. * * @param xModifierKeymapRef XModifierKeymap */ public void fromXModifierKeymap(X11.XModifierKeymapRef xModifierKeymapRef) { int count = xModifierKeymapRef.max_keypermod; byte[] keys = xModifierKeymapRef.modifiermap.getByteArray(0, 8*count); ArrayList<Byte>[] allModifiers = getAllModifiers(); for (int modNr = 0; modNr < 8; modNr++) { ArrayList<Byte> modifier = allModifiers[modNr]; modifier.clear(); for (int keyNr = 0; keyNr < count; keyNr++) { byte key = keys[modNr*count + keyNr]; if (key != 0) { modifier.add(Byte.valueOf(key)); } } } } /** * Returns an XModifierKeymap corresponding to this object. * * @return XModifierKeymap */ public X11.XModifierKeymapRef toXModifierKeyamp() { ArrayList<Byte>[] allModifiers = getAllModifiers(); // determine max list size int count = 0; for (int i = 0; i < allModifiers.length; i++) { count = Math.max(count, allModifiers[i].size()); } byte[] keys = new byte[8*count]; for (int modNr = 0; modNr < 8; modNr++) { ArrayList<Byte> modifier = allModifiers[modNr]; for (int keyNr = 0; keyNr < modifier.size(); keyNr++) { keys[modNr*count + keyNr] = modifier.get(keyNr).byteValue(); } } X11.XModifierKeymapRef xModifierKeymapRef = new X11.XModifierKeymapRef(); xModifierKeymapRef.max_keypermod = count; xModifierKeymapRef.modifiermap = new Memory(keys.length); xModifierKeymapRef.modifiermap.write(0, keys, 0, keys.length); return xModifierKeymapRef; } /** * Returns all modifiers as an array. * * @return array of modifier lists */ public ArrayList<Byte>[] getAllModifiers() { return new ArrayList[] { shift, lock, control, mod1, mod2, mod3, mod4, mod5 }; } } /** * X Desktop. */ public static class Desktop { public X.Display display; public int number; public String name; public Desktop(Display display, int number, String name) { this.display = display; this.number = number; this.name = name; } } /** * X Window. */ public static class Window { private X.Display display; private X11.Window x11Window; /** * Returns the X11 window object. * * @return X11 window */ public X11.Window getX11Window() { return x11Window; } /** * Returns the ID of the window. * * @return window ID */ public int getID() { return x11Window.intValue(); } /** * Creates the window. * * @param display display where the window is allocated * @param x11Window X11 window */ public Window(X.Display display, X11.Window x11Window) { this.display = display; this.x11Window = x11Window; } /** * Returns the title of the window. * * @return title of the window * @throws X11Exception thrown if X11 window errors occurred */ public String getTitle() throws X11Exception { try { return getUtf8Property(display.getAtom("UTF8_STRING"), "_NET_WM_NAME"); } catch (X11Exception e) { return getUtf8Property(X11.XA_STRING, X11.XA_WM_NAME); } } /** * Returns the window class. * * @return window class * @throws X11Exception thrown if X11 window errors occurred */ public String getWindowClass() throws X11Exception { return getUtf8Property(X11.XA_STRING, X11.XA_WM_CLASS); } /** * Returns the PID of the window. * * @return PID of the window * @throws X11Exception thrown if X11 window errors occurred */ public Integer getPID() throws X11Exception { return getIntProperty(X11.XA_CARDINAL, "_NET_WM_PID"); } /** * Returns the desktop ID of the window. * * @return desktop ID of the window * @throws X11Exception thrown if X11 window errors occurred */ public int getDesktop() throws X11Exception { try { return getIntProperty(X11.XA_CARDINAL, "_NET_WM_DESKTOP"); } catch (X11Exception e) { return getIntProperty(X11.XA_CARDINAL, "_WIN_WORKSPACE"); } } /** * Returns the client machine name of the window. * * @return client machine name of the window * @throws X11Exception thrown if X11 window errors occurred */ public String getMachine() throws X11Exception { return getStringProperty(X11.XA_STRING, "WM_CLIENT_MACHINE"); } /** * Returns the XWindowAttributes of the window. * * @return XWindowAttributes of the window */ public X11.XWindowAttributes getXWindowAttributes() { X11.XWindowAttributes xwa = new X11.XWindowAttributes(); x11.XGetWindowAttributes(display.x11Display, x11Window, xwa); return xwa; } /** * Returns the geometry of the window. * * @return geometry of the window */ public Geometry getGeometry() { X11.WindowByReference junkRoot = new X11.WindowByReference(); IntByReference junkX = new IntByReference(); IntByReference junkY = new IntByReference(); IntByReference x = new IntByReference(); IntByReference y = new IntByReference(); IntByReference width = new IntByReference(); IntByReference height = new IntByReference(); IntByReference borderWidth = new IntByReference(); IntByReference depth = new IntByReference(); x11.XGetGeometry(display.x11Display, x11Window, junkRoot, junkX, junkY, width, height, borderWidth, depth); x11.XTranslateCoordinates(display.x11Display, x11Window, junkRoot.getValue(), junkX.getValue(), junkY.getValue(), x, y, junkRoot); return new Geometry(x.getValue(), y.getValue(), width.getValue(), height.getValue(), borderWidth.getValue(), depth.getValue()); } /** * Returns the bounding box of the window. * * @return bounding box of the window */ public Rectangle getBounds() { X11.WindowByReference junkRoot = new X11.WindowByReference(); IntByReference junkX = new IntByReference(); IntByReference junkY = new IntByReference(); IntByReference x = new IntByReference(); IntByReference y = new IntByReference(); IntByReference width = new IntByReference(); IntByReference height = new IntByReference(); IntByReference border_width = new IntByReference(); IntByReference depth = new IntByReference(); x11.XGetGeometry(display.x11Display, x11Window, junkRoot, junkX, junkY, width, height, border_width, depth); x11.XTranslateCoordinates(display.x11Display, x11Window, junkRoot.getValue(), junkX.getValue(), junkY.getValue(), x, y, junkRoot); int xVal = x.getValue(); int yVal = y.getValue(); return new Rectangle(xVal, yVal, xVal + width.getValue(), yVal + height.getValue()); } /** * Activates the window. * * @throws X11Exception thrown if X11 window errors occurred */ public void activate() throws X11Exception { clientMsg("_NET_ACTIVE_WINDOW", 0, 0, 0, 0, 0); x11.XMapRaised(display.x11Display, x11Window); } /** * Moves the window to the specified desktop. * * @param desktopNr desktop * @return X11.SUCCESS if closing was successful * @throws X11Exception thrown if X11 window errors occurred */ public int moveToDesktop(int desktopNr) throws X11Exception { return clientMsg("_NET_WM_DESKTOP", desktopNr, 0, 0, 0, 0); } /** * Selects the input events to listen for. * * @param eventMask event mask representing the events to listen for */ public void selectInput(int eventMask) { x11.XSelectInput(display.x11Display, x11Window, new NativeLong(eventMask)); } public int nextEvent(X11.XEvent event) { return x11.XNextEvent(display.x11Display, event); } public void sendEvent(int eventMask, X11.XEvent event) { x11.XSendEvent(display.x11Display, x11Window, 1, new NativeLong(eventMask), event); } /** * Closes the window gracefully. * * @return X11.SUCCESS if closing was successful * @throws X11Exception thrown if X11 window errors occurred */ public int close() throws X11Exception { return clientMsg("_NET_CLOSE_WINDOW", 0, 0, 0, 0, 0); } /** * Returns the property value as integer. * * @param xa_prop_type property type * @param xa_prop_name property name * @return property value as integer or null if not found * @throws X11Exception thrown if X11 window errors occurred */ public Integer getIntProperty(X11.Atom xa_prop_type, X11.Atom xa_prop_name) throws X11Exception { byte[] property = getProperty(xa_prop_type, xa_prop_name); if( property == null ){ return null; } return bytesToInt(property); } /** * Returns the property value as integer. * * @param xa_prop_type property type * @param xa_prop_name property name * @return property value as integer * @throws X11Exception thrown if X11 window errors occurred */ public Integer getIntProperty(X11.Atom xa_prop_type, String xa_prop_name) throws X11Exception { return getIntProperty(xa_prop_type, display.getAtom(xa_prop_name)); } /** * Returns the property value as window. * * @param xa_prop_type property type * @param xa_prop_name property name * @return property value as window, or null if not found * @throws X11Exception thrown if X11 window errors occurred */ public Window getWindowProperty(X11.Atom xa_prop_type, X11.Atom xa_prop_name) throws X11Exception { Integer windowId = getIntProperty(xa_prop_type, xa_prop_name); if( windowId == null ){ return null; } X11.Window x11Window = new X11.Window(windowId); return new Window(display, x11Window); } /** * Returns the property value as window. * * @param xa_prop_type property type * @param xa_prop_name property name * @return property value as window * @throws X11Exception thrown if X11 window errors occurred */ public Window getWindowProperty(X11.Atom xa_prop_type, String xa_prop_name) throws X11Exception { return getWindowProperty(xa_prop_type, display.getAtom(xa_prop_name)); } /** * Returns the property value as a null terminated byte array. * * @param xa_prop_type property type * @param xa_prop_name property name * @return property value as a null terminated byte array, or null if not found * @throws X11Exception thrown if X11 window errors occurred */ public byte[] getNullTerminatedProperty(X11.Atom xa_prop_type, X11.Atom xa_prop_name) throws X11Exception { byte[] bytesOrig = getProperty(xa_prop_type, xa_prop_name); byte[] bytesDest; if( bytesOrig == null ){ return null; } // search for '\0' int i; for (i = 0; i < bytesOrig.length; i++) { if (bytesOrig[i] == '\0') break; } if (i < bytesOrig.length - 1) { bytesDest = new byte[i + 1]; System.arraycopy(bytesOrig, 0, bytesDest, 0, i + 1); } else { bytesDest = bytesOrig; } return bytesDest; } /** * Returns the property value as a null terminated byte array. * * @param xa_prop_type property type * @param xa_prop_name property name * @return property value as a null terminated byte array * @throws X11Exception thrown if X11 window errors occurred */ public byte[] getNullTerminatedProperty(X11.Atom xa_prop_type, String xa_prop_name) throws X11Exception { return getNullTerminatedProperty(xa_prop_type, display.getAtom(xa_prop_name)); } /** * Returns the property value as byte array where every '\0' character is replaced by '.'. * * @param xa_prop_type property type * @param xa_prop_name property name * @return property value as byte array where every '\0' character is replaced by '.'. null if the property was not found * @throws X11Exception thrown if X11 window errors occurred */ public byte[] getNullReplacedStringProperty(X11.Atom xa_prop_type, X11.Atom xa_prop_name) throws X11Exception { byte[] bytes = getProperty(xa_prop_type, xa_prop_name); if( bytes == null ){ return null; } // search for '\0' int i; for (i = 0; i < bytes.length; i++) { if (bytes[i] == '\0') { bytes[i] = '.'; } } return bytes; } /** * Returns the property value as byte array where every '\0' character is replaced by '.'. * * @param xa_prop_type property type * @param xa_prop_name property name * @return property value as byte array where every '\0' character is replaced by '.' * @throws X11Exception thrown if X11 window errors occurred */ public byte[] getNullReplacedStringProperty(X11.Atom xa_prop_type, String xa_prop_name) throws X11Exception { return getNullReplacedStringProperty(xa_prop_type, display.getAtom(xa_prop_name)); } /** * Returns the property value as string where every '\0' character is replaced by '.'. * * @param xa_prop_type property type * @param xa_prop_name property name * @return property value as string where every '\0' character is replaced by '.' * @throws X11Exception thrown if X11 window errors occurred */ public String getStringProperty(X11.Atom xa_prop_type, X11.Atom xa_prop_name) throws X11Exception { return new String(getNullReplacedStringProperty(xa_prop_type, xa_prop_name)); } /** * Returns the property value as string where every '\0' character is replaced by '.'. * * @param xa_prop_type property type * @param xa_prop_name property name * @return property value as string where every '\0' character is replaced by '.' * @throws X11Exception thrown if X11 window errors occurred */ public String getStringProperty(X11.Atom xa_prop_type, String xa_prop_name) throws X11Exception { return new String(getNullReplacedStringProperty(xa_prop_type, xa_prop_name)); } /** * Returns the property value as string list. * * @param xa_prop_type property type * @param xa_prop_name property name * @return property value as string list * @throws X11Exception thrown if X11 window errors occurred */ public String[] getStringListProperty(X11.Atom xa_prop_type, X11.Atom xa_prop_name) throws X11Exception { return new String(getProperty(xa_prop_type, xa_prop_name)).split("\0"); } /** * Returns the property value as string list. * * @param xa_prop_type property type * @param xa_prop_name property name * @return property value as string list, or null if the property value does not exist * @throws X11Exception thrown if X11 window errors occurred */ public String[] getStringListProperty(X11.Atom xa_prop_type, String xa_prop_name) throws X11Exception { byte[] property = getProperty(xa_prop_type, xa_prop_name); if( property == null ){ return null; } return new String(property).split("\0"); } /** * Returns the property value as UTF8 string where every '\0' character is replaced by '.'. * * @param xa_prop_type property type * @param xa_prop_name property name * @return property value as UTF8 string where every '\0' character is replaced by '.' * @throws X11Exception thrown if X11 window errors occurred */ public String getUtf8Property(X11.Atom xa_prop_type, X11.Atom xa_prop_name) throws X11Exception { try { byte[] property = getNullReplacedStringProperty(xa_prop_type, xa_prop_name); if( property == null ){ return null; } return new String(property, "UTF8"); } catch (UnsupportedEncodingException e) { throw new X11Exception(e); } } /** * Returns the property value as UTF8 string where every '\0' character is replaced by '.'. * * @param xa_prop_type property type * @param xa_prop_name property name * @return property value as UTF8 string where every '\0' character is replaced by '.' * @throws X11Exception thrown if X11 window errors occurred */ public String getUtf8Property(X11.Atom xa_prop_type, String xa_prop_name) throws X11Exception { return getUtf8Property(xa_prop_type, display.getAtom(xa_prop_name)); } /** * Returns the property value as UTF8 string list * * @param xa_prop_type property type * @param xa_prop_name property name * @return property value as UTF8 string list * @throws X11Exception thrown if X11 window errors occurred */ public String[] getUtf8ListProperty(X11.Atom xa_prop_type, X11.Atom xa_prop_name) throws X11Exception { try { return new String(getProperty(xa_prop_type, xa_prop_name), "UTF8").split("\0"); } catch (UnsupportedEncodingException e) { throw new X11Exception(e); } } /** * Returns the property value as UTF8 string list * * @param xa_prop_type property type * @param xa_prop_name property name * @return property value as UTF8 string list * @throws X11Exception thrown if X11 window errors occurred */ public String[] getUtf8ListProperty(X11.Atom xa_prop_type, String xa_prop_name) throws X11Exception { return getUtf8ListProperty(xa_prop_type, display.getAtom(xa_prop_name)); } /** * Returns the property value as a byte array. * * @param xa_prop_type property type * @param xa_prop_name property name * @return property value as a byte array * @throws X11Exception thrown if X11 window errors occurred */ public byte[] getProperty(X11.Atom xa_prop_type, X11.Atom xa_prop_name) throws X11Exception { X11.AtomByReference xa_ret_type_ref = new X11.AtomByReference(); IntByReference ret_format_ref = new IntByReference(); NativeLongByReference ret_nitems_ref = new NativeLongByReference(); NativeLongByReference ret_bytes_after_ref = new NativeLongByReference(); PointerByReference ret_prop_ref = new PointerByReference(); NativeLong long_offset = new NativeLong(0); NativeLong long_length = new NativeLong(MAX_PROPERTY_VALUE_LEN / 4); /* MAX_PROPERTY_VALUE_LEN / 4 explanation (XGetWindowProperty manpage): * * long_length = Specifies the length in 32-bit multiples of the * data to be retrieved. */ if (x11.XGetWindowProperty(display.x11Display, x11Window, xa_prop_name, long_offset, long_length, false, xa_prop_type, xa_ret_type_ref, ret_format_ref, ret_nitems_ref, ret_bytes_after_ref, ret_prop_ref) != X11.Success) { String prop_name = x11.XGetAtomName(display.x11Display, xa_prop_name); throw new X11Exception("Cannot get " + prop_name + " property."); } X11.Atom xa_ret_type = xa_ret_type_ref.getValue(); Pointer ret_prop = ret_prop_ref.getValue(); if( xa_ret_type == null ){ //the specified property does not exist for the specified window return null; } if( xa_ret_type == null ){ //the specified property does not exist for the specified window return null; } if( xa_ret_type == null ){ //the specified property does not exist for the specified window return null; } if (xa_ret_type == null || xa_prop_type == null || !xa_ret_type.toNative().equals(xa_prop_type.toNative())) { x11.XFree(ret_prop); String prop_name = x11.XGetAtomName(display.x11Display, xa_prop_name); throw new X11Exception("Invalid type of " + prop_name + " property"); } int ret_format = ret_format_ref.getValue(); long ret_nitems = ret_nitems_ref.getValue().longValue(); // null terminate the result to make string handling easier int nbytes; if (ret_format == 32) nbytes = Native.LONG_SIZE; else if (ret_format == 16) nbytes = Native.LONG_SIZE / 2; else if (ret_format == 8) nbytes = 1; else if (ret_format == 0) nbytes = 0; else throw new X11Exception("Invalid return format"); int length = Math.min((int) ret_nitems * nbytes, MAX_PROPERTY_VALUE_LEN); byte[] ret = ret_prop.getByteArray(0, length); x11.XFree(ret_prop); return ret; } /** * Returns the property value as a byte array. * * @param xa_prop_type property type * @param xa_prop_name property name * @return property value as a byte array * @throws X11Exception thrown if X11 window errors occurred */ public byte[] getProperty(X11.Atom xa_prop_type, String xa_prop_name) throws X11Exception { return getProperty(xa_prop_type, display.getAtom(xa_prop_name)); } public int clientMsg(String msg, int data0, int data1, int data2, int data3, int data4) throws X11Exception { return clientMsg( msg, new NativeLong(data0), new NativeLong(data1), new NativeLong(data2), new NativeLong(data3), new NativeLong(data4) ); } public int clientMsg(String msg, NativeLong data0, NativeLong data1, NativeLong data2, NativeLong data3, NativeLong data4) throws X11Exception { X11.XClientMessageEvent event; NativeLong mask = new NativeLong(X11.SubstructureRedirectMask | X11.SubstructureNotifyMask); event = new X11.XClientMessageEvent(); event.type = X11.ClientMessage; event.serial = new NativeLong(0); event.send_event = 1; event.message_type = display.getAtom(msg); event.window = x11Window; event.format = 32; event.data.setType(NativeLong[].class); event.data.l[0] = data0; event.data.l[1] = data1; event.data.l[2] = data2; event.data.l[3] = data3; event.data.l[4] = data4; X11.XEvent e = new X11.XEvent(); e.setTypedValue(event); if (x11.XSendEvent(display.x11Display, display.getRootWindow().x11Window, 0, mask, e) != 0) { return X11.Success; } else { throw new X11Exception("Cannot send " + msg + " event."); } } public Window[] getSubwindows() throws X11Exception { WindowByReference root = new WindowByReference(); WindowByReference parent = new WindowByReference(); PointerByReference children = new PointerByReference(); IntByReference childCount = new IntByReference(); if (x11.XQueryTree(display.x11Display, x11Window, root, parent, children, childCount) == 0){ throw new X11Exception("Can't query subwindows"); } if( childCount.getValue() == 0 ){ return null; } Window[] retVal = new Window[ childCount.getValue() ]; //Depending on if we're running on 64-bit or 32-bit systems, //the Window ID size may be different; we need to make sure that //we get the data properly no matter what if (X11.XID.SIZE == 4) { int[] windows = children.getValue().getIntArray( 0, childCount.getValue() ); for( int x = 0; x < retVal.length; x++ ){ X11.Window win = new X11.Window( windows [ x ] ); retVal[ x ] = new Window( display, win ); } } else { long[] windows = children.getValue().getLongArray( 0, childCount.getValue() ); for( int x = 0; x < retVal.length; x++ ){ X11.Window win = new X11.Window( windows [ x ] ); retVal[ x ] = new Window( display, win ); } } x11.XFree(children.getValue()); return retVal; } public String toString() { return x11Window.toString(); } public static class Geometry { public int x, y, width, height, borderWidth, depth; public Geometry(int x, int y, int width, int height, int border_width, int depth) { this.x = x; this.y = y; this.width = width; this.height = height; this.borderWidth = border_width; this.depth = depth; } } } /** * General exception which is thrown when an X11 window error occurred. */ public static class X11Exception extends Exception { private static final long serialVersionUID = 1L; public X11Exception() { } public X11Exception(String message) { super(message); } public X11Exception(String message, Throwable cause) { super(message, cause); } public X11Exception(Throwable cause) { super(cause); } } }
lgpl-2.1
geotools/geotools
modules/extension/brewer/src/main/java/org/geotools/brewer/styling/builder/NamedLayerBuilder.java
3289
/* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2014, Open Source Geospatial Foundation (OSGeo) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package org.geotools.brewer.styling.builder; import java.util.ArrayList; import java.util.List; import org.geotools.styling.FeatureTypeConstraint; import org.geotools.styling.NamedLayer; import org.geotools.styling.Style; public class NamedLayerBuilder extends AbstractSLDBuilder<NamedLayer> { List<FeatureTypeConstraintBuilder> featureTypeConstraint = new ArrayList<>(); private String name; List<StyleBuilder> styles = new ArrayList<>(); public NamedLayerBuilder() { this(null); } public NamedLayerBuilder(AbstractSLDBuilder<?> parent) { super(parent); reset(); } public NamedLayerBuilder name(String name) { this.unset = false; this.name = name; return this; } public StyleBuilder style() { this.unset = false; StyleBuilder sb = new StyleBuilder(this); styles.add(sb); return sb; } @Override public NamedLayer build() { if (unset) { return null; } NamedLayer layer = sf.createNamedLayer(); layer.setName(name); List<FeatureTypeConstraint> list = new ArrayList<>(); for (FeatureTypeConstraintBuilder constraint : featureTypeConstraint) { list.add(constraint.build()); } layer.layerFeatureConstraints().addAll(list); for (StyleBuilder sb : styles) { layer.addStyle(sb.build()); } if (parent == null) { reset(); } return layer; } @Override public NamedLayerBuilder reset() { unset = false; this.name = null; featureTypeConstraint.clear(); return this; } @Override public NamedLayerBuilder reset(NamedLayer layer) { if (layer == null) { return unset(); } this.name = layer.getName(); featureTypeConstraint.clear(); if (layer.layerFeatureConstraints() != null) { for (FeatureTypeConstraint featureConstraint : layer.layerFeatureConstraints()) { featureTypeConstraint.add( new FeatureTypeConstraintBuilder(this).reset(featureConstraint)); } } styles.clear(); for (Style style : layer.getStyles()) { styles.add(new StyleBuilder().reset(style)); } unset = false; return this; } @Override public NamedLayerBuilder unset() { return (NamedLayerBuilder) super.unset(); } @Override protected void buildSLDInternal(StyledLayerDescriptorBuilder sb) { sb.namedLayer().init(this); } }
lgpl-2.1
xwiki/xwiki-commons
xwiki-commons-core/xwiki-commons-legacy/xwiki-commons-legacy-component/xwiki-commons-legacy-component-default/src/test/java/org/xwiki/component/EmbeddableComponentManagerTest.java
2823
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.component; import org.junit.jupiter.api.Test; import org.xwiki.component.descriptor.DefaultComponentDescriptor; import org.xwiki.component.embed.EmbeddableComponentManager; import org.xwiki.component.manager.ComponentManager; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Unit test to prove that we keep backward compatibility for the {@link EmbeddableComponentManager} class. * * @version $Id$ * @since 4.1M1 */ class EmbeddableComponentManagerTest { public static interface Role { } public static class RoleImpl implements Role { } @Test void lookupComponent() throws Exception { ComponentManager cm = new EmbeddableComponentManager(); // Register without hint DefaultComponentDescriptor<Role> cd1 = new DefaultComponentDescriptor<Role>(); cd1.setRole(Role.class); cd1.setImplementation(RoleImpl.class); cm.registerComponent(cd1); // Register with a hint DefaultComponentDescriptor<Role> cd2 = new DefaultComponentDescriptor<Role>(); cd2.setRole(Role.class); cd2.setRoleHint("hint"); cd2.setImplementation(RoleImpl.class); cm.registerComponent(cd2); // Here are the tests, calling deprecated APIs assertNotNull(cm.lookup(Role.class)); assertNotNull(cm.lookup(Role.class, "hint")); assertEquals(2, cm.lookupList(Role.class).size()); assertEquals(2, cm.lookupMap(Role.class).size()); assertTrue(cm.hasComponent(Role.class)); assertTrue(cm.hasComponent(Role.class, "hint")); assertEquals(cd2, cm.getComponentDescriptor(Role.class, "hint")); cm.unregisterComponent(Role.class, "hint"); assertEquals(1, cm.lookupList(Role.class).size()); } }
lgpl-2.1
clee749/DescentMaze
src/pilot/RandomSolver.java
1208
package pilot; import java.awt.Point; import maze.CellSide; import maze.MazeUtility; public class RandomSolver extends MazeWalker { private final CellSide[] directions; private final Point[] next_locations; public RandomSolver(MazeUtility maze) { super(maze); directions = new CellSide[4]; next_locations = new Point[4]; } @Override public CellSide nextUnvisited() { int num_valid_directions = 0; for (CellSide direction : CellSide.values()) { Point next = getLocationInDirection(location.x, location.y, direction); if (maze.isValidCell(next.x, next.y) && !maze.hasWall(location.x, location.y, direction) && !visited[next.x][next.y]) { directions[num_valid_directions] = direction; next_locations[num_valid_directions] = next; ++num_valid_directions; } } if (num_valid_directions > 0) { int index = (int) (Math.random() * num_valid_directions); CellSide direction = directions[index]; Point next = next_locations[index]; path.push(direction); visited[next.x][next.y] = true; next_location = next_locations[index]; return direction; } return null; } }
lgpl-2.1
dtag-dbu/speechalyzer
src/FelixUtil/src/com/felix/util/SwingUtil.java
5846
package com.felix.util; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.Point; import java.awt.event.ActionListener; import java.util.Vector; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JPanel; /** * Helper class around swing code. * * @author felix * */ public class SwingUtil { /** * Retrieve the value for a specific key for a Point (constructed from 2 * integers). E.g. point 13 2341 constructs new Point(13, 2341) * * @param key * The key. * @return The value a a Point. */ public static Point getPoint(KeyValues keyValues, String key) { String val = keyValues.getHashMap().get(key); if (val == null) { System.err.println("WARNING: no value for " + key); } int x = Integer.parseInt(val.trim().split(" ")[0]); int y = Integer.parseInt(val.trim().split(" ")[1]); return new Point(x, y); } /** * Retrieve the value for a specific key for a Dimension (constructed from 2 * integers). E.g. point 13 2341 constructs new Dimension(13, 2341) * * @param key * The key. * @return The value a a Dimension. **/ public static Dimension getDimension(KeyValues keyValues, String key) { String val = keyValues.getHashMap().get(key); if (val == null) { System.err.println("WARNING: no value for " + key); } int x = Integer.parseInt(val.trim().split(" ")[0]); int y = Integer.parseInt(val.trim().split(" ")[1]); return new Dimension(x, y); } /** * Return a button with action command set to name. * * @param name * @param l * @return */ public final static JButton makeButton(String name, ActionListener l) { JButton button = new JButton(name); button.addActionListener(l); button.setActionCommand(name); return button; } public final static JPanel makeButtonPanel(Vector<String> names, ActionListener actionListener) { JPanel pane = new JPanel(); for(String s : names) { JButton b = makeButton(s, actionListener); pane.add(b); } return pane; } /** * Return a button with action command set to name. * * @param name * @param l * @return */ public final static JButton makeWhiteOnBlackButton(String name, ActionListener l) { JButton button = new JButton(name); button.addActionListener(l); button.setActionCommand(name); button.setForeground(Color.white); button.setBackground(Color.black); return button; } public final static ImagePanel getImagePanel(String img) { ImagePanel ret = new ImagePanel(img); return ret; } public final static ImagePanel getImagePanel(Image[] images) { ImagePanel ret = new ImagePanel(images); return ret; } /** * Helper class for panels with background image. * * @author felix * */ public static class ImagePanel extends JPanel { private static final long serialVersionUID = 1L; private Image _img; private Image[] _images; private Image _additionalImg; private Point _additionalImageLocation; /** * Constructor with background image path. * * @param _img */ public ImagePanel(String img) { this(new ImageIcon(img).getImage()); } /** * Constructor with a array of images to be kept in memory and switched. * * @param images */ public ImagePanel(Image[] images) { _images = images; this._img = _images[0]; Dimension size = new Dimension(_img.getWidth(null), _img .getHeight(null)); setMySize(size); repaint(); } /** * Switch bg image. * * @param _img */ public void switchImage(String img) { switchImage(new ImageIcon(img).getImage()); } /** * Switch bg image. * * @param _img */ public void switchImage(int index) { this._img = _images[index]; Dimension size = new Dimension(_img.getWidth(null), _img .getHeight(null)); setMySize(size); update(getGraphics()); } /** * Switch bg image. * * @param _img */ public void switchImage(Image img) { this._img = img; Dimension size = new Dimension(_img.getWidth(null), _img .getHeight(null)); setMySize(size); update(getGraphics()); } /** * Constructor with background image. * * @param _img */ public ImagePanel(Image img) { this._img = img; Dimension size = new Dimension(img.getWidth(null), img .getHeight(null)); setMySize(size); repaint(); } public void setAdditionalImage(Image img, Point loc) { _additionalImg = img; _additionalImageLocation = loc; } public void paintComponent(Graphics g) { g.drawImage(_img, 0, 0, null); if (_additionalImg != null) { g.drawImage(_additionalImg, _additionalImageLocation.x, _additionalImageLocation.y, null); } } private void setMySize(Dimension size) { setPreferredSize(size); setMinimumSize(size); setMaximumSize(size); setSize(size); } } public static InvisibleButton getInvisibleButton(int width, int height) { return new InvisibleButton(width, height); } /** * A button without borders, icons or text. * * @author felix * */ public static class InvisibleButton extends JButton { /** */ private static final long serialVersionUID = 1L; int _width, _height; public InvisibleButton(int width, int height) { _width = width; _height = height; } public boolean isBorderPainted() { return false; } public String getText() { return ""; } public boolean isContentAreaFilled() { return false; } public Dimension getPreferredSize() { return new Dimension(_width, _height); } } }
lgpl-2.1
thilokru/Controller-Support
src/main/java/com/mhfs/controller/hotplug/ExtendedMethods.java
249
package com.mhfs.controller.hotplug; import com.mhfs.controller.daemon.ProvidedMethods; import com.mhfs.ipc.CallFuture; public interface ExtendedMethods extends ProvidedMethods { public CallFuture<Boolean> startControllerSelection(); }
lgpl-2.1
geotools/geotools
modules/extension/ysld/src/main/java/org/geotools/ysld/transform/sld/TextSymbolizerHandler.java
5889
/* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2016 Open Source Geospatial Foundation (OSGeo) * (C) 2014-2016 Boundless Spatial * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package org.geotools.ysld.transform.sld; import java.io.IOException; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; /** Handles xml parse events for {@link org.geotools.styling.TextSymbolizer} elements. */ public class TextSymbolizerHandler extends SymbolizerHandler { @Override public void element(XMLStreamReader xml, SldTransformContext context) throws XMLStreamException, IOException { String name = xml.getLocalName(); if ("TextSymbolizer".equals(name)) { context.mapping().scalar("text").mapping(); } else if ("Label".equals(name)) { context.scalar("label").push(new ExpressionHandler()); } else if ("Font".equals(name)) { context.push(new FontHandler()); } else if ("LabelPlacement".equals(name)) { context.scalar("placement").push(new PlacementHandler()); } else if ("Halo".equals(name)) { context.scalar("halo").push(new HaloHandler()); } else if ("Fill".equals(name)) { context.push(new FillHandler()); } else { super.element(xml, context); } } @Override public void endElement(XMLStreamReader xml, SldTransformContext context) throws XMLStreamException, IOException { String name = xml.getLocalName(); if ("TextSymbolizer".equals(name)) { dumpOptions(context).endMapping().endMapping().pop(); } else { super.endElement(xml, context); } } static class FontHandler extends SldTransformHandler { @Override public void element(XMLStreamReader xml, SldTransformContext context) throws XMLStreamException, IOException { String name = xml.getLocalName(); if ("CssParameter".equals(name) || "SvgParameter".equals(name)) { context.push(new ParameterHandler()); } } @Override public void endElement(XMLStreamReader xml, SldTransformContext context) throws XMLStreamException, IOException { String name = xml.getLocalName(); if ("Font".equals(name)) { context.pop(); } } } static class PlacementHandler extends SldTransformHandler { @Override public void element(XMLStreamReader xml, SldTransformContext context) throws XMLStreamException, IOException { String name = xml.getLocalName(); if ("LabelPlacement".equals(name)) { context.mapping(); } else if ("PointPlacement".equals(name)) { context.scalar("type").scalar("point"); } else if ("LinePlacement".equals(name)) { context.scalar("type").scalar("line"); } else if ("AnchorPoint".equals(name)) { context.scalar("anchor").push(new AnchorHandler()); } else if ("Displacement".equals(name)) { context.scalar("displacement").push(new DisplacementHandler()); } else if ("Rotation".equals(name)) { context.scalar("rotation").push(new ExpressionHandler()); } else if ("PerpendicularOffset".equals(name)) { context.scalar("offset").push(new ExpressionHandler()); } else if ("IsRepeated".equals(name)) { context.scalar("repeat").scalar(xml.getElementText()); } else if ("IsAligned".equals(name)) { context.scalar("align").scalar(xml.getElementText()); } else if ("GeneralizeLine".equals(name)) { context.scalar("generalize").scalar(xml.getElementText()); } else if ("InitialGap".equals(name)) { context.scalar("initial-gap").push(new ExpressionHandler()); } else if ("Gap".equals(name)) { context.scalar("gap").push(new ExpressionHandler()); } } @Override public void endElement(XMLStreamReader xml, SldTransformContext context) throws XMLStreamException, IOException { String name = xml.getLocalName(); if ("LabelPlacement".equals(name)) { context.endMapping().pop(); } } } static class HaloHandler extends SldTransformHandler { @Override public void element(XMLStreamReader xml, SldTransformContext context) throws XMLStreamException, IOException { String name = xml.getLocalName(); if ("Halo".equals(name)) { context.mapping(); } else if ("Fill".equals(name)) { context.push(new FillHandler()); } else if ("Radius".equals(name)) { context.scalar("radius").push(new ExpressionHandler()); } } @Override public void endElement(XMLStreamReader xml, SldTransformContext context) throws XMLStreamException, IOException { String name = xml.getLocalName(); if ("Halo".equals(name)) { context.endMapping().pop(); } } } }
lgpl-2.1
jbossws/jbossws-cxf
modules/testsuite/shared-tests/src/test/java/org/jboss/test/ws/jaxws/jbws3287/Endpoint.java
1280
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.ws.jaxws.jbws3287; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; @WebService(name="Endpoint") @SOAPBinding(style = SOAPBinding.Style.RPC) public interface Endpoint { public String echo(String input); }
lgpl-2.1
1fechner/FeatureExtractor
sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/test/java/org/hibernate/test/onetoone/optional/Address.java
505
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.test.onetoone.optional; /** * @author Gavin King */ public class Address { public String entityName; public String street; public String state; public String zip; public String toString() { return this.getClass() + ":" + street; } }
lgpl-2.1
luiz158/yougi-javaee7
java/src/main/java/org/yougi/web/model/RegistrationConfirmationMBean.java
4200
/* Yougi is a web application conceived to manage user groups or * communities focused on a certain domain of knowledge, whose members are * constantly sharing information and participating in social and educational * events. Copyright (C) 2011 Hildeberto Mendonça. * * This application is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * This application is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * There is a full copy of the GNU Lesser General Public License along with * this library. Look for the file license.txt at the root level. If you do not * find it, write to the Free Software Foundation, Inc., 59 Temple Place, * Suite 330, Boston, MA 02111-1307 USA. * */ package org.yougi.web.model; import org.yougi.business.UserAccountBean; import org.yougi.entity.UserAccount; import org.yougi.util.ResourceBundleHelper; import org.yougi.annotation.ManagedProperty; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; /** * @author Hildeberto Mendonca - http://www.hildeberto.com */ @Named @RequestScoped public class RegistrationConfirmationMBean { @EJB private UserAccountBean userAccountBean; @Inject private FacesContext context; private UserAccount userAccount; @Inject @ManagedProperty("#{param.code}") private String code; private String informedCode; private Boolean validated; public RegistrationConfirmationMBean() { this.userAccount = new UserAccount(); } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } /** * @return the code informed manually by the user. */ public String getInformedCode() { return informedCode; } public void setInformedCode(String informedCode) { this.informedCode = informedCode; } public UserAccount getUserAccount() { return userAccount; } public void setUserAccount(UserAccount userAccount) { this.userAccount = userAccount; } /** * @return the whether the registration was validated. */ public Boolean getValidated() { return validated; } public void setValidated(Boolean validated) { this.validated = validated; } /** * Validates the registration when the confirmation code comes * through query string. */ @PostConstruct public void load() { if(this.code != null && !this.code.isEmpty()) { this.userAccount = userAccountBean.confirmUser(this.code); if(this.userAccount != null) { this.validated = Boolean.TRUE; } else { this.validated = Boolean.FALSE; context.addMessage(this.informedCode, new FacesMessage(FacesMessage.SEVERITY_WARN, ResourceBundleHelper.getMessage("warnCode0003"), "")); } } } /** * Validates the registration when the confirmation code is * manually informed. */ public String confirmUser() { if(this.informedCode != null && !this.informedCode.isEmpty()) { this.userAccount = userAccountBean.confirmUser(this.informedCode); if(this.userAccount != null) { this.validated = Boolean.TRUE; } else { this.validated = Boolean.FALSE; } if(!this.validated) { context.addMessage(this.informedCode, new FacesMessage(FacesMessage.SEVERITY_WARN, ResourceBundleHelper.getMessage("warnCode0003"), "")); } } return "registration_confirmation"; } }
lgpl-2.1
Tictim/TTMPMOD
libs_n/gregtech/api/gui/GT_ContainerMetaTile_Machine.java
7505
package gregtech.api.gui; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import gregtech.api.interfaces.tileentity.IGregTechTileEntity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.ICrafting; import java.util.Iterator; /** * NEVER INCLUDE THIS FILE IN YOUR MOD!!! * <p/> * The Container I use for all my MetaTileEntities */ public class GT_ContainerMetaTile_Machine extends GT_Container { public int mActive = 0, mMaxProgressTime = 0, mProgressTime = 0, mEnergy = 0, mSteam = 0, mSteamStorage = 0, mStorage = 0, mOutput = 0, mInput = 0, mID = 0, mDisplayErrorCode = 0; private int oActive = 0, oMaxProgressTime = 0, oProgressTime = 0, oEnergy = 0, oSteam = 0, oSteamStorage = 0, oStorage = 0, oOutput = 0, oInput = 0, oID = 0, oDisplayErrorCode = 0, mTimer = 0; public GT_ContainerMetaTile_Machine(InventoryPlayer aInventoryPlayer, IGregTechTileEntity aTileEntity) { super(aInventoryPlayer, aTileEntity); mTileEntity = aTileEntity; if (mTileEntity != null && mTileEntity.getMetaTileEntity() != null) { addSlots(aInventoryPlayer); if (doesBindPlayerInventory()) bindPlayerInventory(aInventoryPlayer); detectAndSendChanges(); } else { aInventoryPlayer.player.openContainer = aInventoryPlayer.player.inventoryContainer; } } public GT_ContainerMetaTile_Machine(InventoryPlayer aInventoryPlayer, IGregTechTileEntity aTileEntity, boolean doesBindInventory) { super(aInventoryPlayer, aTileEntity); mTileEntity = aTileEntity; if (mTileEntity != null && mTileEntity.getMetaTileEntity() != null) { addSlots(aInventoryPlayer); if (doesBindPlayerInventory() && doesBindInventory) bindPlayerInventory(aInventoryPlayer); detectAndSendChanges(); } else { aInventoryPlayer.player.openContainer = aInventoryPlayer.player.inventoryContainer; } } @Override public void detectAndSendChanges() { super.detectAndSendChanges(); if (mTileEntity.isClientSide() || mTileEntity.getMetaTileEntity() == null) return; mStorage = (int) Math.min(Integer.MAX_VALUE, mTileEntity.getEUCapacity()); mEnergy = (int) Math.min(Integer.MAX_VALUE, mTileEntity.getStoredEU()); mSteamStorage = (int) Math.min(Integer.MAX_VALUE, mTileEntity.getSteamCapacity()); mSteam = (int) Math.min(Integer.MAX_VALUE, mTileEntity.getStoredSteam()); mOutput = (int) Math.min(Integer.MAX_VALUE, mTileEntity.getOutputVoltage()); mInput = (int) Math.min(Integer.MAX_VALUE, mTileEntity.getInputVoltage()); mDisplayErrorCode = mTileEntity.getErrorDisplayID(); mProgressTime = mTileEntity.getProgress(); mMaxProgressTime = mTileEntity.getMaxProgress(); mActive = mTileEntity.isActive() ? 1 : 0; mTimer++; Iterator var2 = this.crafters.iterator(); while (var2.hasNext()) { ICrafting var1 = (ICrafting) var2.next(); if (mTimer % 500 == 10 || oEnergy != mEnergy) { var1.sendProgressBarUpdate(this, 0, mEnergy & 65535); var1.sendProgressBarUpdate(this, 1, mEnergy >>> 16); } if (mTimer % 500 == 10 || oStorage != mStorage) { var1.sendProgressBarUpdate(this, 2, mStorage & 65535); var1.sendProgressBarUpdate(this, 3, mStorage >>> 16); } if (mTimer % 500 == 10 || oOutput != mOutput) { var1.sendProgressBarUpdate(this, 4, mOutput); } if (mTimer % 500 == 10 || oInput != mInput) { var1.sendProgressBarUpdate(this, 5, mInput); } if (mTimer % 500 == 10 || oDisplayErrorCode != mDisplayErrorCode) { var1.sendProgressBarUpdate(this, 6, mDisplayErrorCode); } if (mTimer % 500 == 10 || oProgressTime != mProgressTime) { var1.sendProgressBarUpdate(this, 11, mProgressTime & 65535); var1.sendProgressBarUpdate(this, 12, mProgressTime >>> 16); } if (mTimer % 500 == 10 || oMaxProgressTime != mMaxProgressTime) { var1.sendProgressBarUpdate(this, 13, mMaxProgressTime & 65535); var1.sendProgressBarUpdate(this, 14, mMaxProgressTime >>> 16); } if (mTimer % 500 == 10 || oID != mID) { var1.sendProgressBarUpdate(this, 15, mID); } if (mTimer % 500 == 10 || oActive != mActive) { var1.sendProgressBarUpdate(this, 16, mActive); } if (mTimer % 500 == 10 || oSteam != mSteam) { var1.sendProgressBarUpdate(this, 17, mSteam & 65535); var1.sendProgressBarUpdate(this, 18, mSteam >>> 16); } if (mTimer % 500 == 10 || oSteamStorage != mSteamStorage) { var1.sendProgressBarUpdate(this, 19, mSteamStorage & 65535); var1.sendProgressBarUpdate(this, 20, mSteamStorage >>> 16); } } oID = mID; oSteam = mSteam; oInput = mInput; oActive = mActive; oOutput = mOutput; oEnergy = mEnergy; oStorage = mStorage; oSteamStorage = mSteamStorage; oProgressTime = mProgressTime; oMaxProgressTime = mMaxProgressTime; oDisplayErrorCode = mDisplayErrorCode; } @SideOnly(Side.CLIENT) @Override public void updateProgressBar(int par1, int par2) { super.updateProgressBar(par1, par2); switch (par1) { case 0: mEnergy = mEnergy & -65536 | par2; break; case 1: mEnergy = mEnergy & 65535 | par2 << 16; break; case 2: mStorage = mStorage & -65536 | par2; break; case 3: mStorage = mStorage & 65535 | par2 << 16; break; case 4: mOutput = par2; break; case 5: mInput = par2; break; case 6: mDisplayErrorCode = par2; break; case 11: mProgressTime = mProgressTime & -65536 | par2; break; case 12: mProgressTime = mProgressTime & 65535 | par2 << 16; break; case 13: mMaxProgressTime = mMaxProgressTime & -65536 | par2; break; case 14: mMaxProgressTime = mMaxProgressTime & 65535 | par2 << 16; break; case 15: mID = par2; break; case 16: mActive = par2; break; case 17: mSteam = mSteam & -65536 | par2; break; case 18: mSteam = mSteam & 65535 | par2 << 16; break; case 19: mSteamStorage = mSteamStorage & -65536 | par2; break; case 20: mSteamStorage = mSteamStorage & 65535 | par2 << 16; break; } } @Override public boolean canInteractWith(EntityPlayer player) { return mTileEntity.isUseableByPlayer(player); } }
lgpl-2.1
EgorZhuk/pentaho-reporting
engine/core/src/main/java/org/pentaho/reporting/engine/classic/core/modules/parser/bundle/writer/elements/LegacyElementWriteHandler.java
8922
/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * 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 Lesser General Public License for more details. * * Copyright (c) 2001 - 2013 Object Refinery Ltd, Pentaho Corporation and Contributors.. All rights reserved. */ package org.pentaho.reporting.engine.classic.core.modules.parser.bundle.writer.elements; import java.io.IOException; import org.pentaho.reporting.engine.classic.core.Element; import org.pentaho.reporting.engine.classic.core.filter.DataSource; import org.pentaho.reporting.engine.classic.core.filter.templates.Template; import org.pentaho.reporting.engine.classic.core.modules.parser.bundle.BundleNamespaces; import org.pentaho.reporting.engine.classic.core.modules.parser.bundle.writer.BundleWriterException; import org.pentaho.reporting.engine.classic.core.modules.parser.bundle.writer.BundleWriterState; import org.pentaho.reporting.engine.classic.core.modules.parser.ext.ExtParserModule; import org.pentaho.reporting.engine.classic.core.modules.parser.ext.factory.base.ArrayClassFactory; import org.pentaho.reporting.engine.classic.core.modules.parser.ext.factory.base.ClassFactoryCollector; import org.pentaho.reporting.engine.classic.core.modules.parser.ext.factory.base.ObjectDescription; import org.pentaho.reporting.engine.classic.core.modules.parser.ext.factory.base.ObjectFactoryException; import org.pentaho.reporting.engine.classic.core.modules.parser.ext.factory.base.URLClassFactory; import org.pentaho.reporting.engine.classic.core.modules.parser.ext.factory.datasource.DataSourceCollector; import org.pentaho.reporting.engine.classic.core.modules.parser.ext.factory.datasource.DefaultDataSourceFactory; import org.pentaho.reporting.engine.classic.core.modules.parser.ext.factory.elements.DefaultElementFactory; import org.pentaho.reporting.engine.classic.core.modules.parser.ext.factory.objects.BandLayoutClassFactory; import org.pentaho.reporting.engine.classic.core.modules.parser.ext.factory.objects.DefaultClassFactory; import org.pentaho.reporting.engine.classic.core.modules.parser.ext.factory.stylekey.DefaultStyleKeyFactory; import org.pentaho.reporting.engine.classic.core.modules.parser.ext.factory.stylekey.PageableLayoutStyleKeyFactory; import org.pentaho.reporting.engine.classic.core.modules.parser.ext.factory.templates.DefaultTemplateCollection; import org.pentaho.reporting.engine.classic.core.modules.parser.ext.factory.templates.TemplateCollector; import org.pentaho.reporting.engine.classic.core.modules.parser.ext.factory.templates.TemplateDescription; import org.pentaho.reporting.engine.classic.core.modules.parser.extwriter.DataSourceWriter; import org.pentaho.reporting.engine.classic.core.modules.parser.extwriter.ReportWriter; import org.pentaho.reporting.engine.classic.core.modules.parser.extwriter.ReportWriterContext; import org.pentaho.reporting.engine.classic.core.modules.parser.extwriter.ReportWriterException; import org.pentaho.reporting.engine.classic.core.modules.parser.extwriter.TemplateWriter; import org.pentaho.reporting.libraries.docbundle.WriteableDocumentBundle; import org.pentaho.reporting.libraries.xmlns.common.AttributeList; import org.pentaho.reporting.libraries.xmlns.writer.XmlWriter; import org.pentaho.reporting.libraries.xmlns.writer.XmlWriterSupport; /** * Todo: Document Me * * @author Thomas Morgner */ public class LegacyElementWriteHandler extends AbstractElementWriteHandler { public LegacyElementWriteHandler() { } /** * Writes a single element as XML structure. * * @param bundle * the bundle to which to write to. * @param state * the current write-state. * @param xmlWriter * the xml writer. * @param element * the element. * @throws IOException * if an IO error occured. * @throws BundleWriterException * if an Bundle writer. */ @SuppressWarnings( "deprecation" ) public void writeElement( final WriteableDocumentBundle bundle, final BundleWriterState state, final XmlWriter xmlWriter, final Element element ) throws IOException, BundleWriterException { if ( bundle == null ) { throw new NullPointerException(); } if ( state == null ) { throw new NullPointerException(); } if ( xmlWriter == null ) { throw new NullPointerException(); } if ( element == null ) { throw new NullPointerException(); } final AttributeList attList = createMainAttributes( element, xmlWriter ); attList.addNamespaceDeclaration( "ext", ExtParserModule.NAMESPACE ); xmlWriter.writeTag( BundleNamespaces.LAYOUT, "legacy", attList, XmlWriterSupport.OPEN ); writeElementBody( bundle, state, element, xmlWriter ); final ReportWriter writer = new ReportWriter( state.getMasterReport(), "UTF-8" ); writer.addClassFactoryFactory( new URLClassFactory() ); writer.addClassFactoryFactory( new DefaultClassFactory() ); writer.addClassFactoryFactory( new BandLayoutClassFactory() ); writer.addClassFactoryFactory( new ArrayClassFactory() ); writer.addStyleKeyFactory( new DefaultStyleKeyFactory() ); writer.addStyleKeyFactory( new PageableLayoutStyleKeyFactory() ); writer.addTemplateCollection( new DefaultTemplateCollection() ); writer.addElementFactory( new DefaultElementFactory() ); writer.addDataSourceFactory( new DefaultDataSourceFactory() ); final DataSource datasource = element.getDataSource(); if ( datasource instanceof Template ) { writeLegacyTemplate( xmlWriter, writer, (Template) datasource ); } else { writeLegacyDataSource( xmlWriter, writer, datasource ); } xmlWriter.writeCloseTag(); } private void writeLegacyTemplate( final XmlWriter xmlWriter, final ReportWriterContext writerContext, final Template template ) throws BundleWriterException, IOException { final TemplateCollector tc = writerContext.getTemplateCollector(); // the template description of the element template will get the // template name as its name. final TemplateDescription templateDescription = tc.getDescription( template ); if ( templateDescription == null ) { throw new BundleWriterException( "Unknown template type: " + template ); } // create the parent description before the template description is filled. final TemplateDescription parentTemplate = (TemplateDescription) templateDescription.getInstance(); try { templateDescription.setParameterFromObject( template ); final TemplateWriter templateWriter = new TemplateWriter( writerContext, xmlWriter, templateDescription, parentTemplate ); templateWriter.write(); } catch ( ObjectFactoryException ofe ) { throw new BundleWriterException( "Error while preparing the template", ofe ); } catch ( ReportWriterException e ) { throw new BundleWriterException( "Failed to write legacy template " + template, e ); } } private void writeLegacyDataSource( final XmlWriter xmlWriter, final ReportWriterContext writerContext, final DataSource datasource ) throws BundleWriterException, IOException { final ClassFactoryCollector classFactoryCollector = writerContext.getClassFactoryCollector(); ObjectDescription od = classFactoryCollector.getDescriptionForClass( datasource.getClass() ); if ( od == null ) { od = classFactoryCollector.getSuperClassObjectDescription( datasource.getClass(), null ); } if ( od == null ) { throw new BundleWriterException( "Unable to resolve DataSource: " + datasource.getClass() ); } final DataSourceCollector dataSourceCollector = writerContext.getDataSourceCollector(); final String dsname = dataSourceCollector.getDataSourceName( od ); if ( dsname == null ) { throw new BundleWriterException( "No name for DataSource " + datasource ); } xmlWriter.writeTag( ExtParserModule.NAMESPACE, "datasource", "type", dsname, XmlWriterSupport.OPEN ); try { final DataSourceWriter dsWriter = new DataSourceWriter( writerContext, datasource, od, xmlWriter ); dsWriter.write(); } catch ( ReportWriterException e ) { throw new BundleWriterException( "Failed to write legacy DataSource " + datasource, e ); } xmlWriter.writeCloseTag(); } }
lgpl-2.1
mbatchelor/pentaho-reporting
engine/core/src/main/java/org/pentaho/reporting/engine/classic/core/states/process/EndCrosstabColumnBodyHandler.java
1925
/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * 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 Lesser General Public License for more details. * * Copyright (c) 2001 - 2013 Object Refinery Ltd, Hitachi Vantara and Contributors.. All rights reserved. */ package org.pentaho.reporting.engine.classic.core.states.process; import org.pentaho.reporting.engine.classic.core.ReportProcessingException; import org.pentaho.reporting.engine.classic.core.event.ReportEvent; public class EndCrosstabColumnBodyHandler implements AdvanceHandler { public static final AdvanceHandler HANDLER = new EndCrosstabColumnBodyHandler(); public EndCrosstabColumnBodyHandler() { } public ProcessState advance( final ProcessState state ) throws ReportProcessingException { final ProcessState next = state.deriveForAdvance(); next.leavePresentationGroup(); next.fireReportEvent(); return next; } public ProcessState commit( final ProcessState next ) throws ReportProcessingException { next.setAdvanceHandler( EndCrosstabColumnAxisHandler.HANDLER ); return next; } public int getEventCode() { return ReportEvent.GROUP_BODY_FINISHED | ReportEvent.CROSSTABBING_COL; } public boolean isFinish() { return false; } public boolean isRestoreHandler() { return false; } }
lgpl-2.1
openlimit-signcubes/dss
validation-policy/src/main/java/eu/europa/esig/dss/validation/process/bbb/xcv/sub/checks/CertificateIssuedToNaturalPersonCheck.java
2470
/** * DSS - Digital Signature Services * Copyright (C) 2015 European Commission, provided under the CEF programme * * This file is part of the "DSS - Digital Signature Services" project. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package eu.europa.esig.dss.validation.process.bbb.xcv.sub.checks; import eu.europa.esig.dss.detailedreport.jaxb.XmlSubXCV; import eu.europa.esig.dss.diagnostic.CertificateWrapper; import eu.europa.esig.dss.enumerations.Indication; import eu.europa.esig.dss.enumerations.SubIndication; import eu.europa.esig.dss.policy.jaxb.LevelConstraint; import eu.europa.esig.dss.validation.process.CertificatePolicyIdentifiers; import eu.europa.esig.dss.validation.process.ChainItem; import eu.europa.esig.dss.i18n.I18nProvider; import eu.europa.esig.dss.i18n.MessageTag; public class CertificateIssuedToNaturalPersonCheck extends ChainItem<XmlSubXCV> { private final CertificateWrapper certificate; public CertificateIssuedToNaturalPersonCheck(I18nProvider i18nProvider, XmlSubXCV result, CertificateWrapper certificate, LevelConstraint constraint) { super(i18nProvider, result, constraint); this.certificate = certificate; } @Override protected boolean process() { // This check only uses the certificate (not the TL) return CertificatePolicyIdentifiers.isNatural(certificate); } @Override protected MessageTag getMessageTag() { return MessageTag.BBB_XCV_CMDCIITNP; } @Override protected MessageTag getErrorMessageTag() { return MessageTag.BBB_XCV_CMDCIITNP_ANS; } @Override protected Indication getFailedIndicationForConclusion() { return Indication.INDETERMINATE; } @Override protected SubIndication getFailedSubIndicationForConclusion() { return SubIndication.CHAIN_CONSTRAINTS_FAILURE; } }
lgpl-2.1
EgorZhuk/pentaho-reporting
engine/core/src/main/java/org/pentaho/reporting/engine/classic/core/PageDefinition.java
3749
/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * 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 Lesser General Public License for more details. * * Copyright (c) 2001 - 2013 Object Refinery Ltd, Pentaho Corporation and Contributors.. All rights reserved. */ package org.pentaho.reporting.engine.classic.core; import java.awt.geom.Rectangle2D; import java.awt.print.PageFormat; import java.io.Serializable; /** * A logical page definition for a report. * <p/> * Page oriented reports use the page definition to distribute the content of one logical page to the physical pages. * The order of the physical pages in the page definition defines the content order in the generated documents. * <p/> * Flow oriented reports will use the page-definitions width as default width for the layouting. * <p/> * If a logical page is completly empty, it will be removed from the report and a pageCanceled event is fired. If a * physical page within a non empty logical page is empty, if depends on the ReportProcessor whether the page is printed * as empty page or whether it will be removed from the report. * <p/> * Areas of the logical page not covered by the physical pages will not cause errors, the content in these areas will be * ignored and not printed. * <p/> * Page definitions must not be changed during the report processing, or funny things will happen. * * @author Thomas Morgner */ public interface PageDefinition extends Cloneable, Serializable { /** * Returns the total width of the logical page. * * @return the width of the page. */ public float getWidth(); /** * Returns the total height of the logical page. * * @return the height of the page. */ public float getHeight(); /** * Returns the number of physical pages in this logical page definition. * * @return the number of physical pages in the page definition. */ public int getPageCount(); /** * Returns all page positions as array. * * @return the collected page positions * @see PageDefinition#getPagePosition(int) */ public Rectangle2D[] getPagePositions(); /** * Describes the internal position of the given page within the logical page. The logical page does not include any * page margins, the printable area for a page starts at (0,0). * * @param index * the index of the physical pageformat * @return the bounds for the page. */ public Rectangle2D getPagePosition( int index ); /** * Returns the page format for the given page number. The page format contains local coordinates - that means that the * point (0,0) denotes the upper left corner of this returned page format and not global coordinates. * * @param pos * the position of the pageformat within the page * @return the given pageformat. */ public PageFormat getPageFormat( int pos ); /** * Creates a copy of the page definition. * * @return a copy of the page definition. * @throws CloneNotSupportedException * if cloning failed for some reason. */ public Object clone() throws CloneNotSupportedException; }
lgpl-2.1
geotools/geotools
modules/library/xml/src/main/java/org/geotools/gml/GMLHandlerJTS.java
1218
/* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2002-2008, Open Source Geospatial Foundation (OSGeo) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package org.geotools.gml; /** * LEVEL3 saxGML4j GML handler: Gets JTS objects. * * <p>This handler must be implemented by the parent of a GMLFilterGeometry filter in order to * handle the JTS objects passed to it from the child. * * @author Rob Hranac, Vision for New York * @version $Id$ */ public interface GMLHandlerJTS extends org.xml.sax.ContentHandler { /** * Receives OGC simple feature type geometry from parent. * * @param geometry the simple feature geometry */ void geometry(org.locationtech.jts.geom.Geometry geometry); }
lgpl-2.1
halfspiral/tuxguitar
TuxGuitar/src/org/herac/tuxguitar/app/view/component/tab/TGControl.java
9468
package org.herac.tuxguitar.app.view.component.tab; import org.herac.tuxguitar.app.TuxGuitar; import org.herac.tuxguitar.app.system.keybindings.KeyBindingActionManager; import org.herac.tuxguitar.app.ui.TGApplication; import org.herac.tuxguitar.app.view.util.TGBufferedPainterListenerLocked; import org.herac.tuxguitar.graphics.TGPainter; import org.herac.tuxguitar.graphics.TGRectangle; import org.herac.tuxguitar.graphics.control.TGBeatImpl; import org.herac.tuxguitar.graphics.control.TGMeasureImpl; import org.herac.tuxguitar.player.base.MidiPlayer; import org.herac.tuxguitar.ui.UIFactory; import org.herac.tuxguitar.ui.event.UIDisposeEvent; import org.herac.tuxguitar.ui.event.UIDisposeListener; import org.herac.tuxguitar.ui.event.UIFocusEvent; import org.herac.tuxguitar.ui.event.UIFocusGainedListener; import org.herac.tuxguitar.ui.event.UISelectionEvent; import org.herac.tuxguitar.ui.event.UISelectionListener; import org.herac.tuxguitar.ui.layout.UITableLayout; import org.herac.tuxguitar.ui.resource.UIRectangle; import org.herac.tuxguitar.ui.widget.UICanvas; import org.herac.tuxguitar.ui.widget.UIContainer; import org.herac.tuxguitar.ui.widget.UIScrollBar; import org.herac.tuxguitar.ui.widget.UIScrollBarPanel; import org.herac.tuxguitar.util.TGContext; public class TGControl { private static final int SCROLL_INCREMENT = 50; private TGContext context; private UIScrollBarPanel container; private UICanvas canvas; private UIScrollBar hScroll; private UIScrollBar vScroll; private Tablature tablature; private int width; private int height; private int scrollX; private int scrollY; private boolean resetScroll; protected long lastVScrollTime; protected long lastHScrollTime; private boolean painting; public TGControl(TGContext context, UIContainer parent) { this.context = context; this.tablature = TablatureEditor.getInstance(this.context).getTablature(); this.initialize(parent); } public void initialize(UIContainer parent) { UIFactory factory = TGApplication.getInstance(this.context).getFactory(); UITableLayout layout = new UITableLayout(0f); this.container = factory.createScrollBarPanel(parent, true, true, false); this.container.setLayout(layout); this.container.addFocusGainedListener(new UIFocusGainedListener() { public void onFocusGained(UIFocusEvent event) { TGControl.this.setFocus(); } }); this.canvas = factory.createCanvas(this.container, false); this.hScroll = this.container.getHScroll(); this.vScroll = this.container.getVScroll(); this.canvas.addPaintListener(new TGBufferedPainterListenerLocked(this.context, new TGControlPaintListener(this))); this.canvas.addMouseDownListener(this.tablature.getEditorKit().getMouseKit()); this.canvas.addMouseUpListener(this.tablature.getEditorKit().getMouseKit()); this.canvas.addMouseMoveListener(this.tablature.getEditorKit().getMouseKit()); this.canvas.addMouseExitListener(this.tablature.getEditorKit().getMouseKit()); this.hScroll.setIncrement(SCROLL_INCREMENT); this.hScroll.addSelectionListener(new UISelectionListener() { public void onSelect(UISelectionEvent event) { TGControl.this.redraw(); } }); this.vScroll.setIncrement(SCROLL_INCREMENT); this.vScroll.addSelectionListener(new UISelectionListener() { public void onSelect(UISelectionEvent event) { TGControl.this.redraw(); } }); KeyBindingActionManager.getInstance(this.context).appendListenersTo(this.canvas); this.canvas.setPopupMenu(TuxGuitar.getInstance().getItemManager().getPopupMenu()); this.canvas.addDisposeListener(new UIDisposeListener() { public void onDispose(UIDisposeEvent event) { TGControl.this.canvas.setPopupMenu(null); } }); layout.set(this.canvas, 1, 1, UITableLayout.ALIGN_FILL, UITableLayout.ALIGN_FILL, true, true, 1, 1, null, null, 0f); } public void paintTablature(TGPainter painter){ this.setPainting(true); try{ this.checkScroll(); int oldWidth = this.width; int oldHeight = this.height; TGRectangle area = createRectangle(this.canvas.getBounds()); this.scrollX = this.hScroll.getValue(); this.scrollY = this.vScroll.getValue(); this.tablature.paintTablature(painter, area, -this.scrollX, -this.scrollY); this.width = Math.round(this.tablature.getViewLayout().getWidth()); this.height = Math.round(this.tablature.getViewLayout().getHeight()); this.updateScroll(); if( MidiPlayer.getInstance(this.context).isRunning()){ this.paintTablaturePlayMode(painter); } // Si no estoy reproduciendo y hay cambios // muevo el scroll al compas que tiene el caret else if(this.tablature.getCaret().hasChanges() || (this.width != oldWidth || this.height != oldHeight)){ // Mover el scroll puede necesitar redibujar // por eso es importante desmarcar los cambios antes de hacer el moveScrollTo this.tablature.getCaret().setChanges(false); this.moveScrollTo(this.tablature.getCaret().getMeasure(), area); } }catch(Throwable throwable){ throwable.printStackTrace(); } this.setPainting(false); } private void paintTablaturePlayMode(TGPainter painter){ try{ TGMeasureImpl measure = TuxGuitar.getInstance().getEditorCache().getPlayMeasure(); TGBeatImpl beat = TuxGuitar.getInstance().getEditorCache().getPlayBeat(); if(measure != null && measure.hasTrack(this.tablature.getCaret().getTrack().getNumber())){ this.moveScrollTo(measure); if(!measure.isOutOfBounds()){ this.tablature.getViewLayout().paintPlayMode(painter, measure, beat); } } }catch(Throwable throwable){ throwable.printStackTrace(); } } public void resetScroll(){ this.resetScroll = true; } public void checkScroll(){ if( this.resetScroll ){ this.hScroll.setValue(0); this.vScroll.setValue(0); this.resetScroll = false; } } public void updateScroll(){ UIRectangle bounds = this.canvas.getBounds(); this.hScroll.setMaximum(Math.max(Math.round(this.width - bounds.getWidth()), 0)); this.vScroll.setMaximum(Math.max(Math.round(this.height - bounds.getHeight()), 0)); this.hScroll.setThumb(Math.round(bounds.getWidth())); this.vScroll.setThumb(Math.round(bounds.getHeight())); } public void moveScrollTo(TGMeasureImpl measure){ this.moveScrollTo(measure, createRectangle(this.canvas.getBounds())); } public void moveScrollTo(TGMeasureImpl measure, TGRectangle area) { if( measure != null && measure.getTs() != null ){ int mX = Math.round(measure.getPosX()); int mY = Math.round(measure.getPosY()); int mWidth = Math.round(measure.getWidth(this.tablature.getViewLayout())); int mHeight = Math.round(measure.getTs().getSize()); int marginWidth = Math.round(this.tablature.getViewLayout().getFirstMeasureSpacing()); int marginHeight = Math.round(this.tablature.getViewLayout().getFirstTrackSpacing()); boolean playMode = MidiPlayer.getInstance(this.context).isRunning(); //Solo se ajusta si es necesario Integer hScrollValue = this.computeScrollValue(this.scrollX, mX, mWidth, marginWidth, Math.round(area.getWidth()), this.width, playMode); if( hScrollValue != null ) { this.hScroll.setValue(hScrollValue); } //Solo se ajusta si es necesario Integer vScrollValue = this.computeScrollValue(this.scrollY, mY, mHeight, marginHeight, Math.round(area.getHeight()), this.height, playMode); if( vScrollValue != null ) { this.vScroll.setValue(vScrollValue); } // Si cambio el valor de algun scroll redibuja la pantalla if( this.scrollX != this.hScroll.getValue() || this.scrollY != this.vScroll.getValue() ){ redraw(); } } } public Integer computeScrollValue(int scrollPos, int mPos, int mSize, int mMargin, int areaSize, int fullSize, boolean playMode) { Integer value = null; // when position is less than scroll if( mPos < 0 && (areaSize >= (mSize + mMargin) || ((mPos + mSize - mMargin) <= 0))) { value = ((scrollPos + mPos) - mMargin); } // when position is greater than scroll else if((mPos + mSize) > areaSize && (areaSize >= (mSize + mMargin) || mPos > areaSize)){ value = (scrollPos + mPos + mSize + mMargin - areaSize); if( playMode ) { value += Math.min((fullSize - (scrollPos + mPos + mSize + mMargin)), (areaSize - mSize - (mMargin * 2))); } } return (value != null ? Math.max(value, 0) : null); } public void setFocus() { if(!this.isDisposed() ){ this.canvas.setFocus(); } } public void redraw(){ if(!this.isDisposed() ){ this.setPainting(true); this.canvas.redraw(); } } public void redrawPlayingMode() { if(!this.isDisposed() && !this.isPainting() && MidiPlayer.getInstance(this.context).isRunning()) { this.redraw(); } } public boolean isPainting() { return this.painting; } public void setPainting(boolean painting) { this.painting = painting; } public TGContext getContext() { return this.context; } public Tablature getTablature() { return tablature; } public UIContainer getContainer() { return container; } public UICanvas getCanvas() { return canvas; } public boolean isDisposed() { return (this.container == null || this.container.isDisposed() || this.canvas == null || this.canvas.isDisposed()); } public TGRectangle createRectangle(UIRectangle rectangle){ return new TGRectangle(rectangle.getX(),rectangle.getY(),rectangle.getWidth(),rectangle.getHeight()); } }
lgpl-2.1
fakechris/WinStoneUdp
src/java/winstone/crypto/RC4.java
6932
/* * Copyright (C) 2003 Clarence Ho (clarence@clarenceho.net) * All rights reserved. * * Redistribution and use of this software for non-profit, educational, * or persoanl purposes, in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the author nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * In case of using this software for other purposes not stated above, * please conact Clarence Ho (clarence@clarenceho.net) for permission. * * THIS SOFTWARE IS PROVIDED BY CLARENCE HO "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package winstone.crypto; /** * This is a simple implementation of the RC4 (tm) encryption algorithm. The * author implemented this class for some simple applications * that don't need/want/require the Sun's JCE framework. * <p> * But if you are looking for encryption algorithms for a * full-blown application, * it would be better to stick with Sun's JCE framework. You can find * a *free* JCE implementation with RC4 (tm) at * Cryptix (http://www.cryptix.org/). * <p> * Note that RC4 (tm) is a trademark of RSA Data Security, Inc. * Also, if you are within USA, you may need to acquire licenses from * RSA to use RC4. * Please check your local law. The author is not * responsible for any illegal use of this code. * <p> * @author Clarence Ho */ public class RC4 { public static final byte DEFAULT_KEY[] = {(byte) 0xee, 0x21, (byte) 0x99, (byte) 0xc1, 0x10, (byte) 0xf2, (byte) 0xba, 0x38}; private byte state[] = new byte[256]; private int x; private int y; public RC4() throws NullPointerException { this(DEFAULT_KEY); } /** * Initializes the class with a string key. The length * of a normal key should be between 1 and 2048 bits. But * this method doens't check the length at all. * * @param key the encryption/decryption key */ public RC4(String key) throws NullPointerException { this(key.getBytes()); } /** * Initializes the class with a byte array key. The length * of a normal key should be between 1 and 2048 bits. But * this method doens't check the length at all. * * @param key the encryption/decryption key */ public RC4(byte[] key) throws NullPointerException { for (int i=0; i < 256; i++) { state[i] = (byte)i; } x = 0; y = 0; int index1 = 0; int index2 = 0; byte tmp; if (key == null || key.length == 0) { throw new NullPointerException(); } for (int i=0; i < 256; i++) { index2 = ((key[index1] & 0xff) + (state[i] & 0xff) + index2) & 0xff; tmp = state[i]; state[i] = state[index2]; state[index2] = tmp; index1 = (index1 + 1) % key.length; } } /** * RC4 encryption/decryption. * * @param data the data to be encrypted/decrypted * @return the result of the encryption/decryption */ public byte[] rc4(String data) { if (data == null) { return null; } byte[] tmp = data.getBytes(); this.rc4(tmp); return tmp; } /** * RC4 encryption/decryption. * * @param buf the data to be encrypted/decrypted * @return the result of the encryption/decryption */ public byte[] rc4(byte[] buf) { //int lx = this.x; //int ly = this.y; int xorIndex; byte tmp; if (buf == null) { return null; } byte[] result = new byte[buf.length]; for (int i=0; i < buf.length; i++) { x = (x + 1) & 0xff; y = ((state[x] & 0xff) + y) & 0xff; tmp = state[x]; state[x] = state[y]; state[y] = tmp; xorIndex = ((state[x] &0xff) + (state[y] & 0xff)) & 0xff; result[i] = (byte)(buf[i] ^ state[xorIndex]); } //this.x = lx; //this.y = ly; return result; } /** * RC4 encryption/decryption. * * @param buf the data to be encrypted/decrypted * @return the result of the encryption/decryption */ public byte[] rc4(byte[] buf, int offset, int length) { //int lx = this.x; //int ly = this.y; int xorIndex; byte tmp; if (buf == null || buf.length < length+offset ) { return null; } byte[] result = new byte[length]; for (int i = offset; i < offset+length; i++) { x = (x + 1) & 0xff; y = ((state[x] & 0xff) + y) & 0xff; tmp = state[x]; state[x] = state[y]; state[y] = tmp; xorIndex = ((state[x] &0xff) + (state[y] & 0xff)) & 0xff; result[i] = (byte)(buf[i] ^ state[xorIndex]); } //this.x = lx; //this.y = ly; return result; } public byte rc4(byte buf) { //int lx = this.x; //int ly = this.y; int xorIndex; byte tmp; x = (x + 1) & 0xff; y = ((state[x] & 0xff) + y) & 0xff; tmp = state[x]; state[x] = state[y]; state[y] = tmp; xorIndex = ((state[x] &0xff) + (state[y] & 0xff)) & 0xff; byte result = (byte)(buf ^ state[xorIndex]); //this.x = lx; //this.y = ly; return result; } }
lgpl-2.1
openlimit-signcubes/dss
dss-timestamp-remote/src/test/java/eu/europa/esig/dss/ws/timestamp/remote/RemoteTimestampServiceTest.java
6324
/** * DSS - Digital Signature Services * Copyright (C) 2015 European Commission, provided under the CEF programme * * This file is part of the "DSS - Digital Signature Services" project. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package eu.europa.esig.dss.ws.timestamp.remote; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.File; import java.util.Arrays; import java.util.List; import javax.xml.crypto.dsig.CanonicalizationMethod; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import eu.europa.esig.dss.diagnostic.DiagnosticData; import eu.europa.esig.dss.diagnostic.TimestampWrapper; import eu.europa.esig.dss.enumerations.DigestAlgorithm; import eu.europa.esig.dss.enumerations.SignatureLevel; import eu.europa.esig.dss.enumerations.SignaturePackaging; import eu.europa.esig.dss.enumerations.TimestampType; import eu.europa.esig.dss.model.DSSDocument; import eu.europa.esig.dss.model.FileDocument; import eu.europa.esig.dss.model.SignatureValue; import eu.europa.esig.dss.model.ToBeSigned; import eu.europa.esig.dss.spi.DSSUtils; import eu.europa.esig.dss.test.signature.PKIFactoryAccess; import eu.europa.esig.dss.utils.Utils; import eu.europa.esig.dss.validation.CertificateVerifier; import eu.europa.esig.dss.validation.SignedDocumentValidator; import eu.europa.esig.dss.validation.reports.Reports; import eu.europa.esig.dss.validation.timestamp.TimestampToken; import eu.europa.esig.dss.ws.timestamp.dto.TimestampResponseDTO; import eu.europa.esig.dss.xades.DSSXMLUtils; import eu.europa.esig.dss.xades.XAdESSignatureParameters; import eu.europa.esig.dss.xades.signature.XAdESService; public class RemoteTimestampServiceTest extends PKIFactoryAccess { private RemoteTimestampService timestampService; @BeforeEach public void init() { timestampService = new RemoteTimestampService(); timestampService.setTSPSource(getGoodTsa()); } @Test public void simpleTest() { byte[] contentToBeTimestamped = "Hello World!".getBytes(); byte[] digestValue = DSSUtils.digest(DigestAlgorithm.SHA1, contentToBeTimestamped); TimestampResponseDTO timestampResponse = timestampService.getTimestampResponse(DigestAlgorithm.SHA1, digestValue); assertNotNull(timestampResponse); assertTrue(Utils.isArrayNotEmpty(timestampResponse.getBinaries())); } @Test public void signatureWithContentTimestamp() throws Exception { DSSDocument documentToSign = new FileDocument(new File("src/test/resources/sample.xml")); String canonicalizationAlgo = CanonicalizationMethod.EXCLUSIVE; DigestAlgorithm digestAlgorithm = DigestAlgorithm.SHA1; XAdESSignatureParameters signatureParameters = new XAdESSignatureParameters(); signatureParameters.setSigningCertificate(getSigningCert()); signatureParameters.setCertificateChain(getCertificateChain()); signatureParameters.setSignaturePackaging(SignaturePackaging.ENVELOPING); signatureParameters.setSignatureLevel(SignatureLevel.XAdES_BASELINE_B); signatureParameters.setDigestAlgorithm(digestAlgorithm); byte[] digest = DSSUtils.digest(digestAlgorithm, DSSXMLUtils.canonicalize(canonicalizationAlgo, DSSUtils.toByteArray(documentToSign))); TimestampResponseDTO timeStampResponse = timestampService.getTimestampResponse(digestAlgorithm, digest); TimestampToken timestampToken = new TimestampToken(timeStampResponse.getBinaries(), TimestampType.ALL_DATA_OBJECTS_TIMESTAMP); timestampToken.setCanonicalizationMethod(canonicalizationAlgo); signatureParameters.setContentTimestamps(Arrays.asList(timestampToken)); XAdESService service = new XAdESService(getCompleteCertificateVerifier()); ToBeSigned dataToSign = service.getDataToSign(documentToSign, signatureParameters); SignatureValue signatureValue = getToken().sign(dataToSign, signatureParameters.getDigestAlgorithm(), signatureParameters.getMaskGenerationFunction(), getPrivateKeyEntry()); DSSDocument signedDocument = service.signDocument(documentToSign, signatureParameters, signatureValue); SignedDocumentValidator validator = SignedDocumentValidator.fromDocument(signedDocument); CertificateVerifier certificateVerifier = getOfflineCertificateVerifier(); certificateVerifier.setIncludeTimestampTokenValues(true); validator.setCertificateVerifier(certificateVerifier); Reports reports = validator.validateDocument(); assertNotNull(reports); DiagnosticData diagnosticData = reports.getDiagnosticData(); List<TimestampWrapper> timestampList = diagnosticData.getTimestampList(); assertNotNull(timestampList); assertEquals(1, timestampList.size()); TimestampWrapper timestamp = timestampList.get(0); assertTrue(timestamp.getType().isContentTimestamp()); assertEquals(TimestampType.ALL_DATA_OBJECTS_TIMESTAMP, timestamp.getType()); assertTrue(Arrays.equals(timeStampResponse.getBinaries(), timestamp.getBinaries())); } @Test public void noTSPSourceDefinedTest() { Exception exception = assertThrows(NullPointerException.class, () -> { RemoteTimestampService remoteTimestampService = new RemoteTimestampService(); byte[] contentToBeTimestamped = "Hello World!".getBytes(); byte[] digestValue = DSSUtils.digest(DigestAlgorithm.SHA1, contentToBeTimestamped); remoteTimestampService.getTimestampResponse(DigestAlgorithm.SHA1, digestValue); }); assertEquals("TSPSource must be not null!", exception.getMessage()); } @Override protected String getSigningAlias() { return GOOD_USER; } }
lgpl-2.1
randomBEAR/pervasive_minecraft_mod
src/main/java/com/weathercraft/minecraft/gui/RenderGuiHandler.java
801
package com.weathercraft.minecraft.gui; import net.minecraft.client.Minecraft; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; /** * Created by Sara on 15/05/2016. */ public class RenderGuiHandler { int ecoPoints = 0; int tickCount = 0; String[] tips = {"Plant a tree today", "Switch off the lights when you leave a room", ":D :D :D", "oh no"}; int tipIndex = 0; public RenderGuiHandler(){} @SubscribeEvent public void onRenderGui(RenderGameOverlayEvent event){ new WeatherCraftGui(Minecraft.getMinecraft(), ecoPoints, tips[tipIndex]); tickCount++; if (tickCount%2000 == 0){ tipIndex++; if (tipIndex>=3) tipIndex = 0; } } }
lgpl-2.1
lat-lon/deegree2-base
deegree2-core/src/main/java/org/deegree/ogcwebservices/wms/StyleNotDefinedException.java
1982
//$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2009 by: Department of Geography, University of Bonn and lat/lon GmbH This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: info@deegree.org ----------------------------------------------------------------------------*/ package org.deegree.ogcwebservices.wms; import org.deegree.ogcbase.ExceptionCode; import org.deegree.ogcwebservices.OGCWebServiceException; /** * * * @version $Revision$ * @author <a href="mailto:poth@lat-lon.de">Andreas Poth</a> */ public class StyleNotDefinedException extends OGCWebServiceException { private static final long serialVersionUID = 6488167058082479718L; /** * Creates a new StyleNotDefinedException object. * * @param message */ public StyleNotDefinedException( String message ) { super( message ); this.code = ExceptionCode.STYLE_NOT_DEFINED; } }
lgpl-2.1
geotools/geotools
modules/library/main/src/test/java/org/geotools/temporal/reference/DefaultCalendarEraTest.java
8813
/* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2008, Open Source Geospatial Foundation (OSGeo) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package org.geotools.temporal.reference; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import java.util.Calendar; import java.util.Collection; import java.util.Date; import org.geotools.metadata.iso.citation.Citations; import org.geotools.referencing.NamedIdentifier; import org.geotools.temporal.object.DefaultCalendarDate; import org.geotools.temporal.object.DefaultInstant; import org.geotools.temporal.object.DefaultJulianDate; import org.geotools.temporal.object.DefaultPeriod; import org.geotools.temporal.object.DefaultPosition; import org.geotools.util.SimpleInternationalString; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.opengis.temporal.CalendarDate; import org.opengis.temporal.CalendarEra; import org.opengis.temporal.IndeterminateValue; import org.opengis.temporal.Instant; import org.opengis.temporal.JulianDate; import org.opengis.temporal.Period; import org.opengis.temporal.TemporalReferenceSystem; import org.opengis.util.InternationalString; /** @author Mehdi Sidhoum (Geomatys) */ public class DefaultCalendarEraTest { private CalendarEra calendarEra1; private CalendarEra calendarEra2; private Calendar cal = Calendar.getInstance(); @Before public void setUp() { NamedIdentifier name1 = new NamedIdentifier(Citations.CRS, "Julian calendar"); NamedIdentifier name2 = new NamedIdentifier(Citations.CRS, "Babylonian calendar"); TemporalReferenceSystem frame1 = new DefaultTemporalReferenceSystem(name1, null); TemporalReferenceSystem frame2 = new DefaultTemporalReferenceSystem(name2, null); int[] calendarDate1 = {1900, 1, 1}; int[] calendarDate2 = {400, 1, 1}; CalendarDate referenceDate1 = new DefaultCalendarDate( frame1, IndeterminateValue.BEFORE, new SimpleInternationalString("Gregorian calendar"), calendarDate1); CalendarDate referenceDate2 = new DefaultCalendarDate( frame2, IndeterminateValue.NOW, new SimpleInternationalString("Babylonian calendar"), calendarDate2); JulianDate julianReference = new DefaultJulianDate(frame1, IndeterminateValue.NOW, 123456789); cal.set(1900, 0, 1); Instant begining1 = new DefaultInstant(new DefaultPosition(cal.getTime())); cal.set(2000, 9, 17); Instant ending1 = new DefaultInstant(new DefaultPosition(cal.getTime())); cal.set(2000, 1, 1); Instant begining2 = new DefaultInstant(new DefaultPosition(cal.getTime())); cal.set(2012, 1, 1); Instant ending2 = new DefaultInstant(new DefaultPosition(cal.getTime())); Period epochOfUse1 = new DefaultPeriod(begining1, ending1); Period epochOfUse2 = new DefaultPeriod(begining2, ending2); calendarEra1 = new DefaultCalendarEra( new SimpleInternationalString("Cenozoic"), new SimpleInternationalString("no description"), referenceDate1, julianReference, epochOfUse1); calendarEra2 = new DefaultCalendarEra( new SimpleInternationalString("Mesozoic"), new SimpleInternationalString(""), referenceDate2, julianReference, epochOfUse2); } @After public void tearDown() { calendarEra1 = null; calendarEra2 = null; } /** Test of getName method, of class DefaultCalendarEra. */ @Test public void testGetName() { InternationalString result = calendarEra1.getName(); assertNotEquals(calendarEra2.getName(), result); } /** Test of getReferenceEvent method, of class DefaultCalendarEra. */ @Test public void testGetReferenceEvent() { InternationalString result = calendarEra1.getReferenceEvent(); assertNotEquals(calendarEra2.getReferenceEvent(), result); } /** Test of getReferenceDate method, of class DefaultCalendarEra. */ @Test public void testGetReferenceDate() { CalendarDate result = calendarEra1.getReferenceDate(); assertNotEquals(calendarEra2.getReferenceDate(), result); } /** Test of getJulianReference method, of class DefaultCalendarEra. */ @Test public void testGetJulianReference() { JulianDate result = calendarEra1.getJulianReference(); assertEquals(calendarEra2.getJulianReference(), result); } /** Test of getEpochOfUse method, of class DefaultCalendarEra. */ @Test public void testGetEpochOfUse() { Period result = calendarEra1.getEpochOfUse(); assertNotEquals(calendarEra2.getEpochOfUse(), result); } /** Test of setName method, of class DefaultCalendarEra. */ @Test public void testSetName() { InternationalString result = calendarEra1.getName(); ((DefaultCalendarEra) calendarEra1).setName(new SimpleInternationalString("new Era")); assertNotEquals(calendarEra1.getName(), result); } /** Test of setReferenceEvent method, of class DefaultCalendarEra. */ @Test public void testSetReferenceEvent() { InternationalString result = calendarEra1.getReferenceEvent(); ((DefaultCalendarEra) calendarEra1) .setReferenceEvent(new SimpleInternationalString("new Era description")); assertNotEquals(calendarEra1.getReferenceEvent(), result); } /** Test of setReferenceDate method, of class DefaultCalendarEra. */ @Test public void testSetReferenceDate() { CalendarDate result = calendarEra1.getReferenceDate(); int[] date = {1950, 6, 10}; ((DefaultCalendarEra) calendarEra1) .setReferenceDate(new DefaultCalendarDate(null, null, null, date)); assertNotEquals(calendarEra1.getReferenceDate(), result); } /** Test of setJulianReference method, of class DefaultCalendarEra. */ @Test public void testSetJulianReference() { JulianDate result = calendarEra1.getJulianReference(); ((DefaultCalendarEra) calendarEra1) .setJulianReference(new DefaultJulianDate(null, null, 785410)); assertNotEquals(calendarEra1.getJulianReference(), result); } /** Test of setEpochOfUse method, of class DefaultCalendarEra. */ @Test public void testSetEpochOfUse() { Period result = calendarEra1.getEpochOfUse(); cal.set(1900, 10, 10); ((DefaultCalendarEra) calendarEra1) .setEpochOfUse( new DefaultPeriod( new DefaultInstant(new DefaultPosition(cal.getTime())), new DefaultInstant(new DefaultPosition(new Date())))); assertNotEquals(calendarEra1.getEpochOfUse(), result); } /** Test of getDatingSystem method, of class DefaultCalendarEra. */ @Test public void testGetDatingSystem() { Collection<org.opengis.temporal.Calendar> result = ((DefaultCalendarEra) calendarEra1).getDatingSystem(); assertEquals(((DefaultCalendarEra) calendarEra2).getDatingSystem(), result); } /** Test of equals method, of class DefaultCalendarEra. */ @Test public void testEquals() { assertNotEquals(null, calendarEra1); assertEquals(calendarEra1, calendarEra1); assertNotEquals(calendarEra1, calendarEra2); } /** Test of hashCode method, of class DefaultCalendarEra. */ @Test public void testHashCode() { int result = calendarEra1.hashCode(); assertNotEquals(calendarEra2.hashCode(), result); } /** Test of toString method, of class DefaultCalendarEra. */ @Test public void testToString() { String result = calendarEra1.toString(); assertNotEquals(calendarEra2.toString(), result); } }
lgpl-2.1
tomazzupan/wildfly
testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/layered/LayeredDistributionTestCase.java
9219
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.manualmode.layered; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.concurrent.TimeUnit; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.apache.commons.io.FileUtils; import org.jboss.arquillian.container.test.api.ContainerController; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.TargetsContainer; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.junit.InSequence; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.management.ManagementOperations; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Basic layered distribution integration test. * * @author Dominik Pospisil <dpospisi@redhat.com> */ @RunWith(Arquillian.class) public class LayeredDistributionTestCase { private static final Logger log = Logger.getLogger(LayeredDistributionTestCase.class); private static final String CONTAINER = "jbossas-layered"; private static final String AS_PATH = ".." + File.separator + CONTAINER; private final File layersDir = new File(AS_PATH + File.separator + "modules" + File.separator + "system" + File.separator + "layers"); private static final String TEST_LAYER = "test"; private static final String PRODUCT_NAME = "Test-Product"; private static final String PRODUCT_VERSION = "1.0.0-Test"; private static final String DEPLOYMENT = "test-deployment"; private static final String webURI = "http://" + TestSuiteEnvironment.getServerAddress() + ":8080"; @ArquillianResource private ContainerController controller; @ArquillianResource private Deployer deployer; @Deployment(name = DEPLOYMENT, managed = false, testable = false) @TargetsContainer(CONTAINER) public static Archive<?> getDeployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, "test-deployment.war"); // set dependency to the test deployment war.addClass(LayeredTestServlet.class); war.setManifest(new StringAsset( "Manifest-Version: 1.0" + System.getProperty("line.separator") + "Dependencies: org.jboss.ldtc, org.jboss.modules" + System.getProperty("line.separator"))); return war; } @Test @InSequence(-1) public void before() throws Exception { buildLayer(TEST_LAYER); buildProductModule(TEST_LAYER); buildTestModule(TEST_LAYER); log.trace("===starting server==="); controller.start(CONTAINER); log.trace("===appserver started==="); //deployer.deploy(DEPLOYMENT); //log.trace("===deployment deployed==="); } @Test @InSequence(1) public void after() throws Exception { try { //deployer.undeploy(DEPLOYMENT); //log.trace("===deployment undeployed==="); } finally { controller.stop(CONTAINER); log.trace("===appserver stopped==="); } } @Test public void testLayeredProductVersion() throws Throwable { final ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient(); ModelNode readAttrOp = new ModelNode(); readAttrOp.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION); readAttrOp.get(ModelDescriptionConstants.NAME).set("product-name"); ModelNode result = ManagementOperations.executeOperation(client, readAttrOp); Assert.assertEquals(result.asString(), PRODUCT_NAME); readAttrOp.get(ModelDescriptionConstants.NAME).set("product-version"); result = ManagementOperations.executeOperation(client, readAttrOp); Assert.assertEquals(result.asString(), PRODUCT_VERSION); } @Test public void testLayeredDeployment() throws Throwable { deployer.deploy(DEPLOYMENT); // test that the deployment can access class from a layered module String response = HttpRequest.get(webURI + "/test-deployment/LayeredTestServlet", 10, TimeUnit.SECONDS); Assert.assertTrue(response.contains("LayeredTestServlet")); deployer.undeploy(DEPLOYMENT); } private void buildLayer(String layer) throws Exception { File asDir = new File(AS_PATH); log.trace("AS dir:" + asDir); Assert.assertTrue(asDir.exists()); Assert.assertTrue(layersDir.exists()); File layerDir = new File(layersDir, layer); if (layerDir.exists()) { FileUtils.deleteDirectory(layerDir); } // set layers.conf File layersConf = new File(AS_PATH, "modules" + File.separator + "layers.conf"); FileUtils.writeStringToFile(layersConf, "layers=test" + System.getProperty("line.separator")); } private void buildProductModule(String layer) throws Exception { File layerDir = new File(layersDir, layer); File moduleDir = new File(layerDir, "org" + File.separator + "jboss" + File.separator + "as" + File.separator + "product" + File.separator + "test"); Assert.assertTrue(moduleDir.mkdirs()); File moduleXmlFile = new File(moduleDir, "module.xml"); FileUtils.copyInputStreamToFile(LayeredDistributionTestCase.class.getResourceAsStream("/layered/product-module.xml"), moduleXmlFile); File manifestDir = new File(moduleDir, "classes" + File.separator + "META-INF"); Assert.assertTrue(manifestDir.mkdirs()); File moduleManifestFile = new File(manifestDir, "MANIFEST.MF"); Manifest m = new Manifest(); m.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); m.getMainAttributes().putValue("JBoss-Product-Release-Name", PRODUCT_NAME); m.getMainAttributes().putValue("JBoss-Product-Release-Version", PRODUCT_VERSION); OutputStream manifestStream = new BufferedOutputStream(new FileOutputStream(moduleManifestFile)); m.write(manifestStream); manifestStream.flush(); manifestStream.close(); // set product.conf Path binDir = Paths.get(AS_PATH, "bin"); if (Files.notExists(binDir)){ Files.createDirectory(binDir); } Path productConf = binDir.resolve("product.conf"); Files.deleteIfExists(productConf); Files.write(productConf, Collections.singleton("slot=test"), StandardCharsets.UTF_8); } private void buildTestModule(String layer) throws Exception { File layerDir = new File(layersDir, layer); File moduleDir = new File(layerDir, "org" + File.separator + "jboss" + File.separator + "ldtc" + File.separator + File.separator + "main"); Assert.assertTrue(moduleDir.mkdirs()); File moduleXmlFile = new File(moduleDir, "module.xml"); FileUtils.copyInputStreamToFile(LayeredDistributionTestCase.class.getResourceAsStream("/layered/test-module.xml"), moduleXmlFile); JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "test-module.jar"); jar.addClass(LayeredTestModule.class); File jarFile = new File(moduleDir, "test-module.jar"); jar.as(ZipExporter.class).exportTo(jarFile); } }
lgpl-2.1
TheAwesomeGem/MineFantasy
src/main/java/minefantasy/item/weapon/ItemDagger.java
1030
package minefantasy.item.weapon; import minefantasy.api.weapon.IStealthWeapon; import minefantasy.api.weapon.IWeaponCustomSpeed; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.EnumToolMaterial; import net.minecraft.item.ItemStack; public class ItemDagger extends ItemWeaponMF implements IWeaponCustomSpeed, IStealthWeapon { public ItemDagger(int id, EnumToolMaterial material) { super(id, material); } public ItemDagger(int id, EnumToolMaterial material, float dam, int uses) { this(id, material); } @Override public float getDamageModifier() { return 0.5F; } @Override public int getHitTime(ItemStack weapon, EntityLivingBase target) { return -2; } @Override public float getBackstabModifier() { return 4.0F; } @Override public float getDropModifier() { return 3.0F; } @Override public boolean canDropAttack() { return true; } @Override public float getDurability() { return 0.5F; } @Override public int getHandsUsed() { return 1; } }
lgpl-2.1
thilokru/Controller-Support
src/main/java/com/mhfs/controller/mappings/actions/ActionButtonInvoke.java
1303
package com.mhfs.controller.mappings.actions; import java.lang.reflect.Method; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; public class ActionButtonInvoke extends ActionToEvent<Object> { private int buttonID; public ActionButtonInvoke(int id) { this.buttonID = id; } @Override public String getActionName() { return "INVOKE_BUTTON"; } @Override public String getActionDescription() { GuiScreen screen = Minecraft.getMinecraft().currentScreen; if(screen == null)return "<ERROR>"; for(GuiButton button : ActionButtonChange.reflectiveButtonListRetrieve(screen)) { if(button.id == buttonID) { return button.displayString; } } return ""; } @Override public void buttonDown() { GuiScreen screen = Minecraft.getMinecraft().currentScreen; for(GuiButton button : ActionButtonChange.reflectiveButtonListRetrieve(screen)) { if(button.id == buttonID) { try{ Method method = GuiScreen.class.getDeclaredMethod("actionPerformed", GuiButton.class); method.setAccessible(true); method.invoke(screen, button); } catch (Exception e) { throw new RuntimeException("Unable to reflect on GuiScreen!", e); } } } } @Override public void buttonUp() {} }
lgpl-2.1
herculeshssj/unirio-ppgi-goalservice
GoalService/core/src/main/ie/deri/wsmx/wrapper/ManagabilityWrapper.java
5750
/* * Copyright (c) 2005 National University of Ireland, Galway * * 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 ie.deri.wsmx.wrapper; import ie.deri.wsmx.core.configuration.ComponentConfiguration; import ie.deri.wsmx.core.configuration.annotation.Exposed; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import javax.management.Descriptor; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.ObjectName; import javax.management.modelmbean.DescriptorSupport; import javax.management.modelmbean.ModelMBeanAttributeInfo; import javax.management.modelmbean.ModelMBeanConstructorInfo; import javax.management.modelmbean.ModelMBeanInfo; import javax.management.modelmbean.ModelMBeanInfoSupport; import javax.management.modelmbean.ModelMBeanNotificationInfo; import javax.management.modelmbean.ModelMBeanOperationInfo; import org.apache.log4j.Logger; /** * This wrapper is used to abstract a component, that wishes to * expose its managability, away from JMX. Using reflection * we can extract most information automatically and create * the necessary MBean descriptors instead of having the component * manually create them. * * <pre> * Created on 06.03.2005 * Committed by $$Author: haselwanter $$ * $$Source: /cygdrive/e/progs/cygwin/usr/maczar/cvsbackup/core/src/main/ie/deri/wsmx/wrapper/ManagabilityWrapper.java,v $$ * </pre> * * @author Thomas Haselwanter * @author Michal Zaremba * * @version $Revision: 1.5 $ $Date: 2006-01-25 02:07:29 $ */ public class ManagabilityWrapper { static Logger logger = Logger.getLogger(ManagabilityWrapper.class); private transient Object component = null; private transient List<ModelMBeanOperationInfo> wrapperOperations = new ArrayList<ModelMBeanOperationInfo>(); String description = ""; public ManagabilityWrapper() { super(); } public void registerComponent(Object component, ComponentConfiguration configuration) { this.component = component; description = configuration.getDescription(); } public void removeComponent() { this.component = null; } @Override public String toString() { return "ManagabilityWrapper for " + component.getClass(); } /** * Add a method to the set of exposed methods of the component * that underlies this wrapper. This is done by extracting information * out of a given method to create a JMX compliant instrumentation for * this method. * * @param method the method to be exposed */ public void addExposedMethod(Method method) { Descriptor desc = new DescriptorSupport( new String[] { "name=" + method.getName(), "descriptorType=operation", "class=" + component.getClass().getCanonicalName(), "role=operation"}); MBeanParameterInfo[] parameters = new MBeanParameterInfo[method.getParameterTypes().length]; for (int i = 0; i < method.getParameterTypes().length; i++) { Class clazz = method.getParameterTypes()[i]; parameters[i] = new MBeanParameterInfo("parameter", clazz.getCanonicalName(), ""); } wrapperOperations.add( new ModelMBeanOperationInfo( method.getName(), method.getAnnotation(Exposed.class).description(), parameters, method.getReturnType().getName(), MBeanOperationInfo.ACTION, desc) ); } public void addExposedMethods(List<Method> methods) { for(Method m : methods) addExposedMethod(m); } public ModelMBeanInfo getModelMBeanInfo(ObjectName objectName) { Descriptor wrapperDescription = new DescriptorSupport( new String[] { ("name=" + objectName), "descriptorType=mbean", ("displayName=ManagabilityWrapper"), "type=ie.deri.wsmx.wrapper.ManagabilityWrapper", "log=T", "logFile=wrapper.log", "currencyTimeLimit=-1" }); ModelMBeanConstructorInfo[] wConstructors = new ModelMBeanConstructorInfo[0]; ModelMBeanInfo cmMBeanInfo = new ModelMBeanInfoSupport( "ManagabilityWrapper", description, new ModelMBeanAttributeInfo[0], wConstructors, wrapperOperations.toArray(new ModelMBeanOperationInfo[]{}), new ModelMBeanNotificationInfo[0]); try { cmMBeanInfo.setMBeanDescriptor(wrapperDescription); } catch (Exception e) { logger.warn("CreateMBeanInfo failed with " + e.getMessage()); } return cmMBeanInfo; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
lgpl-2.1
cytoscape/cytoscape-impl
swing-application-impl/src/main/java/org/cytoscape/internal/command/ConsoleCommandHandler.java
2416
/* vim: set ts=2: */ /** * Copyright (c) 2010 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer. * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions, and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * 3. Redistributions must acknowledge that this software was * originally developed by the UCSF Computer Graphics Laboratory * under support by the NIH National Center for Research Resources, * grant P41-RR01081. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package org.cytoscape.internal.command; public class ConsoleCommandHandler implements MessageHandler { public void appendCommand(String s) { System.out.println("COMMAND: "+s+"\n"); } public void appendError(String s) { System.out.println("ERROR: "+s+"\n"); } public void appendResult(String s) { // Be a little careful. We want to space newlines to they all // appear in column order String[] splitString = s.split("\n"); if (splitString.length > 1) { for (String splitS: splitString) System.out.println("--> "+splitS+"\n"); } else System.out.println("--> "+s+"\n"); } public void appendWarning(String s) { System.out.println("WARNING: "+s+"\n"); } public void appendMessage(String s) { System.out.println( " "+s+"\n"); } }
lgpl-2.1
pub-burrito/apiviz-doclava
src/main/java/org/jboss/apiviz/Graphviz.java
7836
/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.apiviz; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import com.sun.javadoc.RootDoc; /** * @author The APIviz Project (apiviz-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev$, $Date$ * */ public class Graphviz { public static final String GRAPHVIZ_EXECUTABLE_FIRST_LINE_CHECK = "^.*[Gg][Rr][Aa][Pp][Hh][Vv][Ii][Zz].*$"; private static boolean homeDetermined; private static File home; public static boolean isAvailable(RootDoc root) { String executable = Graphviz.getExecutable(root); File home = Graphviz.getHome(root); ProcessBuilder pb = new ProcessBuilder(executable, "-V"); pb.redirectErrorStream(true); if (home != null) { root.printNotice("Graphviz Home: " + home); pb.directory(home); } root.printNotice("Graphviz Executable: " + executable); Process p; try { p = pb.start(); } catch (IOException e) { root.printWarning(e.getMessage()); return false; } BufferedReader in = new BufferedReader( new InputStreamReader(p.getInputStream())); OutputStream out = p.getOutputStream(); try { out.close(); String line = null; while((line = in.readLine()) != null) { if (line.matches(GRAPHVIZ_EXECUTABLE_FIRST_LINE_CHECK)) { root.printNotice("Graphviz Version: " + line); return true; } else { root.printWarning("Unknown Graphviz output: " + line); } } return false; } catch (IOException e) { root.printWarning("Problem detecting Graphviz: " + e.getMessage()); return false; } finally { try { out.close(); } catch (IOException e) { // Shouldn't happen. } try { in.close(); } catch (IOException e) { // Shouldn't happen. } for (;;) { try { p.waitFor(); break; } catch (InterruptedException e) { // Ignore } } } } public static void writeImageAndMap( RootDoc root, String diagram, File outputDirectory, String filename) throws IOException { File pngFile = new File(outputDirectory, filename + ".png"); File mapFile = new File(outputDirectory, filename + ".map"); pngFile.delete(); mapFile.delete(); ProcessBuilder pb = new ProcessBuilder( Graphviz.getExecutable(root), "-Tcmapx", "-o", mapFile.getAbsolutePath(), "-Tpng", "-o", pngFile.getAbsolutePath()); pb.redirectErrorStream(true); File home = Graphviz.getHome(root); if (home != null) { pb.directory(home); } Process p = pb.start(); BufferedReader in = new BufferedReader( new InputStreamReader(p.getInputStream())); Writer out = new OutputStreamWriter(p.getOutputStream(), "UTF-8"); try { out.write(diagram); out.close(); String line = null; while((line = in.readLine()) != null) { System.err.println(line); } } finally { try { out.close(); } catch (IOException e) { // Shouldn't happen. } try { in.close(); } catch (IOException e) { // Shouldn't happen. } for (;;) { try { int result = p.waitFor(); if (result != 0) { throw new IllegalStateException("Graphviz exited with a non-zero return value: " + result); } break; } catch (InterruptedException e) { // Ignore } } } } private static String getExecutable(RootDoc root) { String command = "dot"; try { String osName = System.getProperty("os.name"); if (osName != null && osName.indexOf("Windows") >= 0) { File path = Graphviz.getHome(root); if (path != null) { command = path.getAbsolutePath() + File.separator + "dot.exe"; } else { command = "dot.exe"; } } } catch (Exception e) { // ignore me! } return command; } private static File getHome(RootDoc root) { if (homeDetermined) { return home; } File graphvizDir = null; try { String graphvizHome = System.getProperty("graphviz.home"); if (graphvizHome != null) { root.printNotice( "Using the 'graphviz.home' system property: " + graphvizHome); } else { root.printNotice( "The 'graphviz.home' system property was not specified."); graphvizHome = System.getenv("GRAPHVIZ_HOME"); if (graphvizHome != null) { root.printNotice( "Using the 'GRAPHVIZ_HOME' environment variable: " + graphvizHome); } else { root.printNotice( "The 'GRAPHVIZ_HOME' environment variable was not specified."); } } if (graphvizHome != null) { graphvizDir = new File(graphvizHome); if (!graphvizDir.exists() || !graphvizDir.isDirectory()) { root.printWarning( "The specified graphviz home directory does not exist: " + graphvizDir.getPath()); graphvizDir = null; } } if (graphvizDir == null) { root.printNotice( "System path will be used as graphviz home directory was not specified."); } } catch (Exception e) { // ignore... } homeDetermined = true; return home = graphvizDir; } private Graphviz() { // Unused } }
lgpl-2.1
andreasprlic/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/SimpleMMcifParser.java
35903
/* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * * created at Mar 4, 2008 */ package org.biojava.nbio.structure.io.mmcif; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.io.MMCIFFileReader; import org.biojava.nbio.structure.io.StructureIOFile; import org.biojava.nbio.structure.io.mmcif.model.AtomSite; import org.biojava.nbio.structure.io.mmcif.model.AtomSites; import org.biojava.nbio.structure.io.mmcif.model.AuditAuthor; import org.biojava.nbio.structure.io.mmcif.model.CIFLabel; import org.biojava.nbio.structure.io.mmcif.model.Cell; import org.biojava.nbio.structure.io.mmcif.model.ChemComp; import org.biojava.nbio.structure.io.mmcif.model.ChemCompAtom; import org.biojava.nbio.structure.io.mmcif.model.ChemCompBond; import org.biojava.nbio.structure.io.mmcif.model.ChemCompDescriptor; import org.biojava.nbio.structure.io.mmcif.model.DatabasePDBremark; import org.biojava.nbio.structure.io.mmcif.model.DatabasePDBrev; import org.biojava.nbio.structure.io.mmcif.model.DatabasePdbrevRecord; import org.biojava.nbio.structure.io.mmcif.model.Entity; import org.biojava.nbio.structure.io.mmcif.model.EntityPoly; import org.biojava.nbio.structure.io.mmcif.model.EntityPolySeq; import org.biojava.nbio.structure.io.mmcif.model.EntitySrcGen; import org.biojava.nbio.structure.io.mmcif.model.EntitySrcNat; import org.biojava.nbio.structure.io.mmcif.model.EntitySrcSyn; import org.biojava.nbio.structure.io.mmcif.model.Exptl; import org.biojava.nbio.structure.io.mmcif.model.IgnoreField; import org.biojava.nbio.structure.io.mmcif.model.PdbxChemCompDescriptor; import org.biojava.nbio.structure.io.mmcif.model.PdbxChemCompIdentifier; import org.biojava.nbio.structure.io.mmcif.model.PdbxEntityNonPoly; import org.biojava.nbio.structure.io.mmcif.model.PdbxNonPolyScheme; import org.biojava.nbio.structure.io.mmcif.model.PdbxPolySeqScheme; import org.biojava.nbio.structure.io.mmcif.model.PdbxStructAssembly; import org.biojava.nbio.structure.io.mmcif.model.PdbxStructAssemblyGen; import org.biojava.nbio.structure.io.mmcif.model.PdbxStructOperList; import org.biojava.nbio.structure.io.mmcif.model.Refine; import org.biojava.nbio.structure.io.mmcif.model.Struct; import org.biojava.nbio.structure.io.mmcif.model.StructAsym; import org.biojava.nbio.structure.io.mmcif.model.StructConn; import org.biojava.nbio.structure.io.mmcif.model.StructKeywords; import org.biojava.nbio.structure.io.mmcif.model.StructNcsOper; import org.biojava.nbio.structure.io.mmcif.model.StructRef; import org.biojava.nbio.structure.io.mmcif.model.StructRefSeq; import org.biojava.nbio.structure.io.mmcif.model.StructRefSeqDif; import org.biojava.nbio.structure.io.mmcif.model.StructSite; import org.biojava.nbio.structure.io.mmcif.model.StructSiteGen; import org.biojava.nbio.structure.io.mmcif.model.Symmetry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A simple mmCif file parser * * * Usage: * <pre> String file = "path/to/mmcif/file"; StructureIOFile pdbreader = new MMCIFFileReader(); Structure s = pdbreader.getStructure(file); System.out.println(s); // you can convert it to a PDB file... System.out.println(s.toPDB()); * </pre> * For more documentation see <a href="http://biojava.org/wiki/BioJava:CookBook#Protein_Structure">http://biojava.org/wiki/BioJava:CookBook#Protein_Structure</a>. * * @author Andreas Prlic * @author Jose Duarte * @since 1.7 */ public class SimpleMMcifParser implements MMcifParser { /** * The header appearing at the beginning of a mmCIF file. * A "block code" can be added to it of no more than 32 chars. * See http://www.iucr.org/__data/assets/pdf_file/0019/22618/cifguide.pdf */ public static final String MMCIF_TOP_HEADER = "data_"; public static final String COMMENT_CHAR = "#"; public static final String LOOP_START = "loop_"; public static final String FIELD_LINE = "_"; // the following are the 3 valid quoting characters in CIF /** * Quoting character ' */ private static final char S1 = '\''; /** * Quoting character " */ private static final char S2 = '\"'; /** * Quoting character ; (multi-line quoting) */ public static final String STRING_LIMIT = ";"; private List<MMcifConsumer> consumers ; private Struct struct ; private static final Logger logger = LoggerFactory.getLogger(SimpleMMcifParser.class); public SimpleMMcifParser(){ consumers = new ArrayList<MMcifConsumer>(); struct = null; } @Override public void addMMcifConsumer(MMcifConsumer consumer) { consumers.add(consumer); } @Override public void clearConsumers() { consumers.clear(); } @Override public void removeMMcifConsumer(MMcifConsumer consumer) { consumers.remove(consumer); } public static void main(String[] args){ String file = "/Users/andreas/WORK/PDB/mmCif/a9/1a9n.cif.gz"; //String file = "/Users/andreas/WORK/PDB/MMCIF/1gav.mmcif"; //String file = "/Users/andreas/WORK/PDB/MMCIF/100d.cif"; //String file = "/Users/andreas/WORK/PDB/MMCIF/1a4a.mmcif"; System.out.println("parsing " + file); StructureIOFile pdbreader = new MMCIFFileReader(); try { Structure s = pdbreader.getStructure(file); System.out.println(s); // convert it to a PDB file... System.out.println(s.toPDB()); } catch (IOException e) { e.printStackTrace(); } } @Override public void parse(InputStream inStream) throws IOException { parse(new BufferedReader(new InputStreamReader(inStream))); } @Override public void parse(BufferedReader buf) throws IOException { triggerDocumentStart(); // init container objects... struct = new Struct(); String line = null; boolean inLoop = false; boolean inLoopData = false; List<String> loopFields = new ArrayList<String>(); List<String> lineData = new ArrayList<String>(); Set<String> loopWarnings = new HashSet<String>(); // used only to reduce logging statements String category = null; // the first line is a data_PDBCODE line, test if this looks like a mmcif file line = buf.readLine(); if (line == null || !line.startsWith(MMCIF_TOP_HEADER)){ logger.error("This does not look like a valid mmCIF file! The first line should start with 'data_', but is: '" + line+"'"); triggerDocumentEnd(); return; } while ( (line = buf.readLine ()) != null ){ if (line.isEmpty() || line.startsWith(COMMENT_CHAR)) continue; logger.debug(inLoop + " " + line); if (line.startsWith(MMCIF_TOP_HEADER)){ // either first line in file, or beginning of new section if ( inLoop) { //System.out.println("new data and in loop: " + line); inLoop = false; inLoopData = false; lineData.clear(); loopFields.clear(); } } if ( inLoop) { if ( line.startsWith(LOOP_START)){ loopFields.clear(); inLoop = true; inLoopData = false; continue; } if ( line.matches("\\s*"+FIELD_LINE+"\\w+.*")) { if (inLoopData && line.startsWith(FIELD_LINE)) { logger.debug("Found a field line after reading loop data. Toggling to inLoop=false"); inLoop = false; inLoopData = false; loopFields.clear(); // a boring normal line List<String> data = processLine(line, buf, 2); if ( data.size() < 1){ // this can happen if empty lines at end of file lineData.clear(); continue; } String key = data.get(0); int pos = key.indexOf("."); if ( pos < 0 ) { // looks like a chem_comp file // line should start with data, otherwise something is wrong! if (! line.startsWith(MMCIF_TOP_HEADER)){ logger.warn("This does not look like a valid mmCIF file! The first line should start with 'data_', but is '" + line+"'"); triggerDocumentEnd(); return; } // ignore the first line... category=null; lineData.clear(); continue; } category = key.substring(0,pos); String value = data.get(1); loopFields.add(key.substring(pos+1,key.length())); lineData.add(value); logger.debug("Found data for category {}: {}", key, value); continue; } // found another field. String txt = line.trim(); if ( txt.indexOf('.') > -1){ String[] spl = txt.split("\\."); category = spl[0]; String attribute = spl[1]; loopFields.add(attribute); logger.debug("Found category: {}, attribute: {}",category, attribute); if ( spl.length > 2){ logger.warn("Found nested attribute in {}, not supported yet!",txt); } } else { category = txt; logger.debug("Found category without attribute: {}",category); } } else { // in loop and we found a data line lineData = processLine(line, buf, loopFields.size()); logger.debug("Found a loop data line with {} data fields", lineData.size()); logger.debug("Data fields: {}", lineData.toString()); if ( lineData.size() != loopFields.size()){ logger.warn("Expected {} data fields, but found {} in line: {}",loopFields.size(),lineData.size(),line); } endLineChecks(category, loopFields, lineData, loopWarnings); lineData.clear(); inLoopData = true; } } else { // not in loop if ( line.startsWith(LOOP_START)){ if ( category != null) endLineChecks(category, loopFields, lineData, loopWarnings); resetBuffers(loopFields, lineData, loopWarnings); category = null; inLoop = true; inLoopData = false; logger.debug("Detected LOOP_START: '{}'. Toggling to inLoop=true", LOOP_START); continue; } else { logger.debug("Normal line "); inLoop = false; // a boring normal line List<String> data = processLine(line, buf, 2); if ( data.size() < 1){ // this can happen if empty lines at end of file lineData.clear(); continue; } String key = data.get(0); int pos = key.indexOf("."); if ( pos < 0 ) { // looks like a chem_comp file // line should start with data, otherwise something is wrong! if (! line.startsWith(MMCIF_TOP_HEADER)){ logger.warn("This does not look like a valid mmCIF file! The first line should start with 'data_', but is '" + line+"'"); triggerDocumentEnd(); return; } // ignore the first line... category=null; lineData.clear(); continue; } if (category!=null && !key.substring(0,pos).equals(category)) { // we've changed category: need to flush the previous one endLineChecks(category, loopFields, lineData, loopWarnings); resetBuffers(loopFields, lineData, loopWarnings); } category = key.substring(0,pos); String value = data.get(1); loopFields.add(key.substring(pos+1,key.length())); lineData.add(value); logger.debug("Found data for category {}: {}", key, value); } } } if (category!=null && lineData.size()>0 && lineData.size()==loopFields.size()) { // the last category in the file will still be missing, we add it now endLineChecks(category, loopFields, lineData, loopWarnings); resetBuffers(loopFields, lineData, loopWarnings); } if (struct != null){ triggerStructData(struct); } triggerDocumentEnd(); } private void resetBuffers(List<String> loopFields, List<String> lineData, Set<String> loopWarnings) { loopFields.clear(); lineData.clear(); loopWarnings.clear(); } private List<String> processSingleLine(String line){ List<String> data = new ArrayList<String>(); if ( line.trim().length() == 0){ return data; } if ( line.trim().length() == 1){ if ( line.startsWith(STRING_LIMIT)) return data; } boolean inString = false; // semicolon (;) quoting boolean inS1 = false; // single quote (') quoting boolean inS2 = false; // double quote (") quoting String word = ""; for (int i=0; i< line.length(); i++ ){ Character c = line.charAt(i); Character nextC = null; if (i < line.length() - 1) nextC = line.charAt(i+1); Character prevC = null; if (i>0) prevC = line.charAt(i-1); if (c == ' ') { if ( ! inString){ if ( ! word.equals("")) data.add(word.trim()); word = ""; } else { // we are in a string, add the space word += c; } } else if (c == S1 ) { if ( inString){ boolean wordEnd = false; if (! inS2) { if (nextC==null || Character.isWhitespace(nextC)){ i++; wordEnd = true; } } if ( wordEnd ) { // at end of string if ( ! word.equals("")) data.add(word.trim()); word = ""; inString = false; inS1 = false; } else { word += c; } } else if (prevC==null || prevC==' ') { // the beginning of a new string inString = true; inS1 = true; } else { word += c; } } else if ( c == S2 ){ if ( inString){ boolean wordEnd = false; if (! inS1) { if (nextC==null || Character.isWhitespace(nextC)){ i++; wordEnd = true; } } if ( wordEnd ) { // at end of string if ( ! word.equals("")) data.add(word.trim()); word = ""; inString = false; inS2 = false; } else { word += c; } } else if (prevC==null || prevC==' ') { // the beginning of a new string inString = true; inS2 = true; } else { word += c; } } else { word += c; } } if ( ! word.trim().equals("")) data.add(word); return data; } /** * Get the content of a cif entry * * @param line * @param buf * @return */ private List<String> processLine(String line, BufferedReader buf, int fieldLength) throws IOException{ //System.out.println("XX processLine " + fieldLength + " " + line); // go through the line and process each character List<String> lineData = new ArrayList<String>(); boolean inString = false; StringBuilder bigWord = null; while ( true ){ if ( line.startsWith(STRING_LIMIT)){ if (! inString){ inString = true; if ( line.length() > 1) bigWord = new StringBuilder(line.substring(1)); else bigWord = new StringBuilder(""); } else { // the end of a word lineData.add(bigWord.toString()); bigWord = null; inString = false; } } else { if ( inString ) bigWord.append(line); else { List<String> dat = processSingleLine(line); for (String d : dat){ lineData.add(d); } } } //System.out.println("in process line : " + lineData.size() + " " + fieldLength); if ( lineData.size() > fieldLength){ logger.warn("wrong data length ("+lineData.size()+ ") should be ("+fieldLength+") at line " + line + " got lineData: " + lineData); return lineData; } if ( lineData.size() == fieldLength) return lineData; line = buf.readLine(); if ( line == null) break; } return lineData; } private void endLineChecks(String category,List<String> loopFields, List<String> lineData, Set<String> loopWarnings ) throws IOException{ logger.debug("Processing category {}, with fields: {}",category,loopFields.toString()); // System.out.println("parsed the following data: " +category + " fields: "+ // loopFields + " DATA: " + // lineData); if ( loopFields.size() != lineData.size()){ logger.warn("looks like we got a problem with nested string quote characters:"); throw new IOException("data length ("+ lineData.size() + ") != fields length ("+loopFields.size()+ ") category: " +category + " fields: "+ loopFields + " DATA: " + lineData ); } if ( category.equals("_entity")){ Entity e = (Entity) buildObject( Entity.class.getName(), loopFields,lineData, loopWarnings); triggerNewEntity(e); } else if (category.equals("_entity_poly")) { EntityPoly ep = (EntityPoly) buildObject(EntityPoly.class.getName(), loopFields, lineData, loopWarnings); triggerNewEntityPoly(ep); } else if ( category.equals("_struct")){ struct = (Struct) buildObject( Struct.class.getName(), loopFields, lineData, loopWarnings); } else if ( category.equals("_atom_site")){ AtomSite a = (AtomSite) buildObject( AtomSite.class.getName(), loopFields, lineData, loopWarnings); triggerNewAtomSite(a); } else if ( category.equals("_database_PDB_rev")){ DatabasePDBrev dbrev = (DatabasePDBrev) buildObject( DatabasePDBrev.class.getName(), loopFields, lineData, loopWarnings); triggerNewDatabasePDBrev(dbrev); } else if ( category.equals("_database_PDB_rev_record")){ DatabasePdbrevRecord dbrev = (DatabasePdbrevRecord) buildObject( DatabasePdbrevRecord.class.getName(), loopFields, lineData, loopWarnings); triggerNewDatabasePDBrevRecord(dbrev); }else if ( category.equals("_database_PDB_remark")){ DatabasePDBremark remark = (DatabasePDBremark) buildObject( DatabasePDBremark.class.getName(), loopFields, lineData, loopWarnings); triggerNewDatabasePDBremark(remark); } else if ( category.equals("_exptl")){ Exptl exptl = (Exptl) buildObject( Exptl.class.getName(), loopFields,lineData, loopWarnings); triggerExptl(exptl); } else if ( category.equals("_cell")){ Cell cell = (Cell) buildObject( Cell.class.getName(), loopFields,lineData, loopWarnings); triggerNewCell(cell); } else if ( category.equals("_symmetry")){ Symmetry symmetry = (Symmetry) buildObject( Symmetry.class.getName(), loopFields,lineData, loopWarnings); triggerNewSymmetry(symmetry); } else if ( category.equals("_struct_ncs_oper")) { StructNcsOper sNcsOper = (StructNcsOper) buildObject( StructNcsOper.class.getName(), loopFields, lineData, loopWarnings); triggerNewStructNcsOper(sNcsOper); } else if ( category.equals("_atom_sites")) { AtomSites atomSites = (AtomSites) buildObject( AtomSites.class.getName(), loopFields, lineData, loopWarnings); triggerNewAtomSites(atomSites); } else if ( category.equals("_struct_ref")){ StructRef sref = (StructRef) buildObject( StructRef.class.getName(), loopFields,lineData, loopWarnings); triggerNewStrucRef(sref); } else if ( category.equals("_struct_ref_seq")){ StructRefSeq sref = (StructRefSeq) buildObject( StructRefSeq.class.getName(), loopFields,lineData, loopWarnings); triggerNewStrucRefSeq(sref); } else if ( category.equals("_struct_ref_seq_dif")) { StructRefSeqDif sref = (StructRefSeqDif) buildObject( StructRefSeqDif.class.getName(), loopFields, lineData, loopWarnings); triggerNewStrucRefSeqDif(sref); } else if ( category.equals("_struct_site_gen")) { StructSiteGen sref = (StructSiteGen) buildObject( StructSiteGen.class.getName(), loopFields, lineData, loopWarnings); triggerNewStructSiteGen(sref); } else if ( category.equals("_struct_site")) { StructSite sref = (StructSite) buildObject( StructSite.class.getName(), loopFields, lineData, loopWarnings); triggerNewStructSite(sref); } else if ( category.equals("_entity_poly_seq")){ EntityPolySeq exptl = (EntityPolySeq) buildObject( EntityPolySeq.class.getName(), loopFields,lineData, loopWarnings); triggerNewEntityPolySeq(exptl); } else if ( category.equals("_entity_src_gen")){ EntitySrcGen entitySrcGen = (EntitySrcGen) buildObject( EntitySrcGen.class.getName(), loopFields,lineData, loopWarnings); triggerNewEntitySrcGen(entitySrcGen); } else if ( category.equals("_entity_src_nat")){ EntitySrcNat entitySrcNat = (EntitySrcNat) buildObject( EntitySrcNat.class.getName(), loopFields,lineData, loopWarnings); triggerNewEntitySrcNat(entitySrcNat); } else if ( category.equals("_pdbx_entity_src_syn")){ EntitySrcSyn entitySrcSyn = (EntitySrcSyn) buildObject( EntitySrcSyn.class.getName(), loopFields,lineData, loopWarnings); triggerNewEntitySrcSyn(entitySrcSyn); } else if ( category.equals("_struct_asym")){ StructAsym sasym = (StructAsym) buildObject( StructAsym.class.getName(), loopFields,lineData, loopWarnings); triggerNewStructAsym(sasym); } else if ( category.equals("_pdbx_poly_seq_scheme")){ PdbxPolySeqScheme ppss = (PdbxPolySeqScheme) buildObject( PdbxPolySeqScheme.class.getName(), loopFields,lineData, loopWarnings); triggerNewPdbxPolySeqScheme(ppss); } else if ( category.equals("_pdbx_nonpoly_scheme")){ PdbxNonPolyScheme ppss = (PdbxNonPolyScheme) buildObject( PdbxNonPolyScheme.class.getName(), loopFields,lineData, loopWarnings); triggerNewPdbxNonPolyScheme(ppss); } else if ( category.equals("_pdbx_entity_nonpoly")){ PdbxEntityNonPoly pen = (PdbxEntityNonPoly) buildObject( PdbxEntityNonPoly.class.getName(), loopFields,lineData, loopWarnings ); triggerNewPdbxEntityNonPoly(pen); } else if ( category.equals("_struct_keywords")){ StructKeywords kw = (StructKeywords)buildObject( StructKeywords.class.getName(), loopFields,lineData, loopWarnings ); triggerNewStructKeywords(kw); } else if (category.equals("_refine")){ Refine r = (Refine)buildObject( Refine.class.getName(), loopFields,lineData, loopWarnings ); triggerNewRefine(r); } else if (category.equals("_chem_comp")){ ChemComp c = (ChemComp)buildObject( ChemComp.class.getName(), loopFields, lineData, loopWarnings ); triggerNewChemComp(c); } else if (category.equals("_audit_author")) { AuditAuthor aa = (AuditAuthor)buildObject( AuditAuthor.class.getName(), loopFields, lineData, loopWarnings); triggerNewAuditAuthor(aa); } else if (category.equals("_pdbx_chem_comp_descriptor")) { ChemCompDescriptor ccd = (ChemCompDescriptor) buildObject( ChemCompDescriptor.class.getName(), loopFields, lineData, loopWarnings); triggerNewChemCompDescriptor(ccd); } else if (category.equals("_pdbx_struct_oper_list")) { PdbxStructOperList structOper = (PdbxStructOperList) buildObject( PdbxStructOperList.class.getName(), loopFields, lineData, loopWarnings ); triggerNewPdbxStructOper(structOper); } else if (category.equals("_pdbx_struct_assembly")) { PdbxStructAssembly sa = (PdbxStructAssembly) buildObject( PdbxStructAssembly.class.getName(), loopFields, lineData, loopWarnings); triggerNewPdbxStructAssembly(sa); } else if (category.equals("_pdbx_struct_assembly_gen")) { PdbxStructAssemblyGen sa = (PdbxStructAssemblyGen) buildObject( PdbxStructAssemblyGen.class.getName(), loopFields, lineData, loopWarnings); triggerNewPdbxStructAssemblyGen(sa); } else if ( category.equals("_chem_comp_atom")){ ChemCompAtom atom = (ChemCompAtom)buildObject( ChemCompAtom.class.getName(), loopFields,lineData, loopWarnings); triggerNewChemCompAtom(atom); }else if ( category.equals("_chem_comp_bond")){ ChemCompBond bond = (ChemCompBond)buildObject( ChemCompBond.class.getName(), loopFields,lineData, loopWarnings); triggerNewChemCompBond(bond); } else if ( category.equals("_pdbx_chem_comp_identifier")){ PdbxChemCompIdentifier id = (PdbxChemCompIdentifier)buildObject( PdbxChemCompIdentifier.class.getName(), loopFields,lineData, loopWarnings); triggerNewPdbxChemCompIdentifier(id); } else if ( category.equals("_pdbx_chem_comp_descriptor")){ PdbxChemCompDescriptor id = (PdbxChemCompDescriptor)buildObject( PdbxChemCompDescriptor.class.getName(), loopFields,lineData, loopWarnings); triggerNewPdbxChemCompDescriptor(id); } else if ( category.equals("_struct_conn")){ StructConn id = (StructConn)buildObject( StructConn.class.getName(), loopFields,lineData, loopWarnings); triggerNewStructConn(id); } else { logger.debug("Using a generic bean for category {}",category); // trigger a generic bean that can deal with all missing data types... triggerGeneric(category,loopFields,lineData); } } // private PdbxStructOperList getPdbxStructOperList(List<String> loopFields, // List<String> lineData) { // PdbxStructOperList so = new PdbxStructOperList(); // // //System.out.println(loopFields); // //System.out.println(lineData); // // String id = lineData.get(loopFields.indexOf("id")); // so.setId(id); // so.setType(lineData.get(loopFields.indexOf("type"))); // Matrix matrix = new Matrix(3,3); // for (int i = 1 ; i <=3 ; i++){ // for (int j =1 ; j <= 3 ; j++){ // String max = String.format("matrix[%d][%d]",j,i); // // String val = lineData.get(loopFields.indexOf(max)); // Double d = Double.parseDouble(val); // matrix.set(j-1,i-1,d); // // matrix.set(i-1,j-1,d); // } // } // // double[] coords =new double[3]; // // for ( int i = 1; i <=3 ; i++){ // String v = String.format("vector[%d]",i); // String val = lineData.get(loopFields.indexOf(v)); // Double d = Double.parseDouble(val); // coords[i-1] = d; // } // // so.setMatrix(matrix); // so.setVector(coords); // // // // return so; // } public void triggerNewPdbxStructOper(PdbxStructOperList structOper) { for(MMcifConsumer c : consumers){ c.newPdbxStructOperList(structOper); } } public void triggerNewStructNcsOper(StructNcsOper sNcsOper) { for(MMcifConsumer c : consumers){ c.newStructNcsOper(sNcsOper); } } public void triggerNewAtomSites(AtomSites atomSites) { for(MMcifConsumer c : consumers){ c.newAtomSites(atomSites); } } /** * Populates a bean object from the {@link org.biojava.nbio.structure.io.mmcif.model} package, * from the data read from a CIF file. * It uses reflection to lookup the field and setter method names given the category * found in the CIF file. * <p> * Due to limitations in variable names in java, not all fields can have names * exactly as defined in the CIF categories. In those cases the {@link CIFLabel} tag * can be used in the field names to give the appropriate name that corresponds to the * CIF category, which is the name that will be then looked up here. * The {@link IgnoreField} tag can also be used to exclude fields from being looked up. * @param className * @param loopFields * @param lineData * @param warnings * @return */ private Object buildObject(String className, List<String> loopFields, List<String> lineData, Set<String> warnings) { Object o = null; Class<?> c = null; try { // build up the Entity object from the line data... c = Class.forName(className); o = c.newInstance(); } catch (InstantiationException|ClassNotFoundException|IllegalAccessException e){ logger.error( "Error while constructing {}: {}", className, e.getMessage()); return null; } // these methods get the fields but also looking at the IgnoreField and CIFLabel annotations Field[] fields = MMCIFFileTools.getFields(c); String[] names = MMCIFFileTools.getFieldNames(fields); // let's build a map of all methods so that we can look up the setter methods later Method[] methods = c.getMethods(); Map<String,Method> methodMap = new HashMap<String, Method>(); for (Method m : methods) { methodMap.put(m.getName(),m); } // and a map of all the fields so that we can lookup them up later Map<String, Field> names2fields = new HashMap<>(); for (int i=0;i<fields.length;i++) { names2fields.put(names[i], fields[i]); } int pos = -1 ; for (String key: loopFields){ pos++; String val = lineData.get(pos); // we first start looking up the field which can be annotated with a CIFLabel if they // need alternative names (e.g. for field _symmetry.space_group_name_H-M, since hyphen is not allowed in var names in java) Field field = names2fields.get(key); if (field == null) { produceWarning(key, val, c, warnings); continue; } // now we need to find the corresponding setter // note that we can't use the field directly and then call Field.set() because many setters // have more functionality than just setting the value (e.g. some setters in ChemComp) // building up the setter method name: need to upper case the first letter, leave the rest untouched String setterMethodName = "set" + field.getName().substring(0,1).toUpperCase() + field.getName().substring(1, field.getName().length()); Method setter = methodMap.get(setterMethodName); if (setter==null) { produceWarning(key, val, c, warnings); continue; } // now we populate the object with the values by invoking the corresponding setter method, // note that all of the mmCif container classes have only one argument (they are beans) Class<?>[] pType = setter.getParameterTypes(); try { if ( pType[0].getName().equals(Integer.class.getName())) { if ( val != null && ! val.equals("?") && !val.equals(".")) { Integer intVal = Integer.parseInt(val); setter.invoke(o, intVal); } } else { // default val is a String setter.invoke(o, val); } } catch (IllegalAccessException|InvocationTargetException e) { logger.error("Could not invoke setter {} with value {} for class {}", setterMethodName, val, className); } } return o; } private void produceWarning(String key, String val, Class<?> c, Set<String> warnings) { String warning = "Trying to set field " + key + " in "+ c.getName() +" found in file, but no corresponding field could be found in model class (value:" + val + ")"; String warnkey = key+"-"+c.getName(); // Suppress duplicate warnings or attempts to store empty data if( val.equals("?") || val.equals(".") || ( warnings != null && warnings.contains(warnkey)) ) { logger.debug(warning); } else { logger.warn(warning); } if(warnings != null) { warnings.add(warnkey); } } public void triggerGeneric(String category, List<String> loopFields, List<String> lineData){ for(MMcifConsumer c : consumers){ c.newGenericData(category, loopFields, lineData); } } public void triggerNewEntity(Entity entity){ for(MMcifConsumer c : consumers){ c.newEntity(entity); } } public void triggerNewEntityPoly(EntityPoly entityPoly) { for(MMcifConsumer c : consumers){ c.newEntityPoly(entityPoly); } } public void triggerNewEntityPolySeq(EntityPolySeq epolseq){ for(MMcifConsumer c : consumers){ c.newEntityPolySeq(epolseq); } } public void triggerNewEntitySrcGen(EntitySrcGen entitySrcGen){ for(MMcifConsumer c : consumers){ c.newEntitySrcGen(entitySrcGen); } } public void triggerNewEntitySrcNat(EntitySrcNat entitySrcNat){ for(MMcifConsumer c : consumers){ c.newEntitySrcNat(entitySrcNat); } } public void triggerNewEntitySrcSyn(EntitySrcSyn entitySrcSyn){ for(MMcifConsumer c : consumers){ c.newEntitySrcSyn(entitySrcSyn); } } public void triggerNewChemComp(ChemComp cc){ for(MMcifConsumer c : consumers){ c.newChemComp(cc); } } public void triggerNewStructAsym(StructAsym sasym){ for(MMcifConsumer c : consumers){ c.newStructAsym(sasym); } } private void triggerStructData(Struct struct){ for(MMcifConsumer c : consumers){ c.setStruct(struct); } } private void triggerNewAtomSite(AtomSite atom){ for(MMcifConsumer c : consumers){ c.newAtomSite(atom); } } private void triggerNewAuditAuthor(AuditAuthor aa){ for(MMcifConsumer c : consumers){ c.newAuditAuthor(aa); } } private void triggerNewDatabasePDBrev(DatabasePDBrev dbrev){ for(MMcifConsumer c : consumers){ c.newDatabasePDBrev(dbrev); } } private void triggerNewDatabasePDBrevRecord(DatabasePdbrevRecord dbrev){ for(MMcifConsumer c : consumers){ c.newDatabasePDBrevRecord(dbrev); } } private void triggerNewDatabasePDBremark(DatabasePDBremark remark){ for(MMcifConsumer c : consumers){ c.newDatabasePDBremark(remark); } } private void triggerExptl(Exptl exptl){ for(MMcifConsumer c : consumers){ c.newExptl(exptl); } } private void triggerNewCell(Cell cell) { for(MMcifConsumer c : consumers){ c.newCell(cell); } } private void triggerNewSymmetry(Symmetry symmetry) { for(MMcifConsumer c : consumers){ c.newSymmetry(symmetry); } } private void triggerNewStrucRef(StructRef sref){ for(MMcifConsumer c : consumers){ c.newStructRef(sref); } } private void triggerNewStrucRefSeq(StructRefSeq sref){ for(MMcifConsumer c : consumers){ c.newStructRefSeq(sref); } } private void triggerNewStrucRefSeqDif(StructRefSeqDif sref){ for(MMcifConsumer c : consumers){ c.newStructRefSeqDif(sref); } } private void triggerNewPdbxPolySeqScheme(PdbxPolySeqScheme ppss){ for(MMcifConsumer c : consumers){ c.newPdbxPolySeqScheme(ppss); } } private void triggerNewPdbxNonPolyScheme(PdbxNonPolyScheme ppss){ for(MMcifConsumer c : consumers){ c.newPdbxNonPolyScheme(ppss); } } public void triggerNewPdbxEntityNonPoly(PdbxEntityNonPoly pen){ for (MMcifConsumer c: consumers){ c.newPdbxEntityNonPoly(pen); } } public void triggerNewStructKeywords(StructKeywords kw){ for (MMcifConsumer c: consumers){ c.newStructKeywords(kw); } } public void triggerNewRefine(Refine r){ for (MMcifConsumer c: consumers){ c.newRefine(r); } } public void triggerDocumentStart(){ for(MMcifConsumer c : consumers){ c.documentStart(); } } public void triggerDocumentEnd(){ for(MMcifConsumer c : consumers){ c.documentEnd(); } } public void triggerNewChemCompDescriptor(ChemCompDescriptor ccd) { for(MMcifConsumer c : consumers){ c.newChemCompDescriptor(ccd); } } private void triggerNewPdbxStructAssembly(PdbxStructAssembly sa) { for(MMcifConsumer c : consumers){ c.newPdbxStrucAssembly(sa); } } private void triggerNewPdbxStructAssemblyGen(PdbxStructAssemblyGen sa) { for(MMcifConsumer c : consumers){ c.newPdbxStrucAssemblyGen(sa); } } private void triggerNewChemCompAtom(ChemCompAtom atom) { for(MMcifConsumer c : consumers){ c.newChemCompAtom(atom); } } private void triggerNewChemCompBond(ChemCompBond bond) { for(MMcifConsumer c : consumers){ c.newChemCompBond(bond); } } private void triggerNewPdbxChemCompIdentifier(PdbxChemCompIdentifier id) { for(MMcifConsumer c : consumers){ c.newPdbxChemCompIndentifier(id); } } private void triggerNewPdbxChemCompDescriptor(PdbxChemCompDescriptor id) { for(MMcifConsumer c : consumers){ c.newPdbxChemCompDescriptor(id); } } private void triggerNewStructConn(StructConn id) { for(MMcifConsumer c : consumers){ c.newStructConn(id); } } private void triggerNewStructSiteGen(StructSiteGen id) { for (MMcifConsumer c : consumers) { c.newStructSiteGen(id); } } private void triggerNewStructSite(StructSite id) { for (MMcifConsumer c : consumers) { c.newStructSite(id); } } }
lgpl-2.1
soultek101/projectzulu1.7.10
src/main/java/com/stek101/projectzulu/common/blocks/itemblockdeclarations/AloeVeraDeclaration.java
1089
package com.stek101.projectzulu.common.blocks.itemblockdeclarations; import net.minecraft.block.Block; import com.google.common.base.Optional; import com.stek101.projectzulu.common.api.BlockList; import com.stek101.projectzulu.common.blocks.BlockAloeVera; import com.stek101.projectzulu.common.blocks.ItemAloeVera; import com.stek101.projectzulu.common.core.DefaultProps; import com.stek101.projectzulu.common.core.itemblockdeclaration.BlockDeclaration; import cpw.mods.fml.common.registry.GameRegistry; public class AloeVeraDeclaration extends BlockDeclaration { public AloeVeraDeclaration() { super("AloeVera"); } @Override protected boolean createBlock() { BlockList.aloeVera = Optional.of((new BlockAloeVera()).setBlockName(name.toLowerCase()).setBlockTextureName( DefaultProps.blockKey + ":" + name.toLowerCase())); return true; } @Override public void registerBlock() { Block block = BlockList.aloeVera.get(); GameRegistry.registerBlock(block, ItemAloeVera.class, name.toLowerCase()); } }
lgpl-2.1
lhanson/checkstyle
src/tests/com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheckTest.java
12315
//////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2010 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import org.junit.Test; public class HiddenFieldCheckTest extends BaseCheckTestSupport { @Test public void testNoParameters() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HiddenFieldCheck.class); checkConfig.addAttribute("tokens", "VARIABLE_DEF"); final String[] expected = { "18:13: 'hidden' hides a field.", "27:13: 'hidden' hides a field.", "32:18: 'hidden' hides a field.", "46:17: 'innerHidden' hides a field.", "55:17: 'innerHidden' hides a field.", "56:17: 'hidden' hides a field.", "61:22: 'innerHidden' hides a field.", "64:22: 'hidden' hides a field.", "76:17: 'innerHidden' hides a field.", "77:17: 'hidden' hides a field.", "82:13: 'hidden' hides a field.", "138:13: 'hidden' hides a field.", "143:13: 'hidden' hides a field.", "148:13: 'hidden' hides a field.", "152:13: 'hidden' hides a field.", "200:17: 'hidden' hides a field.", "217:13: 'hidden' hides a field.", "223:13: 'hiddenStatic' hides a field.", }; verify(checkConfig, getPath("InputHiddenField.java"), expected); } @Test public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HiddenFieldCheck.class); final String[] expected = { "18:13: 'hidden' hides a field.", "21:33: 'hidden' hides a field.", "27:13: 'hidden' hides a field.", "32:18: 'hidden' hides a field.", "36:33: 'hidden' hides a field.", "46:17: 'innerHidden' hides a field.", "49:26: 'innerHidden' hides a field.", "55:17: 'innerHidden' hides a field.", "56:17: 'hidden' hides a field.", "61:22: 'innerHidden' hides a field.", "64:22: 'hidden' hides a field.", "69:17: 'innerHidden' hides a field.", "70:17: 'hidden' hides a field.", "76:17: 'innerHidden' hides a field.", "77:17: 'hidden' hides a field.", "82:13: 'hidden' hides a field.", "100:29: 'prop' hides a field.", "106:29: 'prop' hides a field.", "112:29: 'prop' hides a field.", "124:28: 'prop' hides a field.", "138:13: 'hidden' hides a field.", "143:13: 'hidden' hides a field.", "148:13: 'hidden' hides a field.", "152:13: 'hidden' hides a field.", "179:23: 'y' hides a field.", "200:17: 'hidden' hides a field.", "210:20: 'hidden' hides a field.", "217:13: 'hidden' hides a field.", "223:13: 'hiddenStatic' hides a field.", "230:41: 'x' hides a field.", }; verify(checkConfig, getPath("InputHiddenField.java"), expected); } /** tests ignoreFormat property */ @Test public void testIgnoreFormat() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HiddenFieldCheck.class); checkConfig.addAttribute("ignoreFormat", "^i.*$"); final String[] expected = { "18:13: 'hidden' hides a field.", "21:33: 'hidden' hides a field.", "27:13: 'hidden' hides a field.", "32:18: 'hidden' hides a field.", "36:33: 'hidden' hides a field.", "56:17: 'hidden' hides a field.", "64:22: 'hidden' hides a field.", "70:17: 'hidden' hides a field.", "77:17: 'hidden' hides a field.", "82:13: 'hidden' hides a field.", "100:29: 'prop' hides a field.", "106:29: 'prop' hides a field.", "112:29: 'prop' hides a field.", "124:28: 'prop' hides a field.", "138:13: 'hidden' hides a field.", "143:13: 'hidden' hides a field.", "148:13: 'hidden' hides a field.", "152:13: 'hidden' hides a field.", "179:23: 'y' hides a field.", "200:17: 'hidden' hides a field.", "210:20: 'hidden' hides a field.", "217:13: 'hidden' hides a field.", "223:13: 'hiddenStatic' hides a field.", "230:41: 'x' hides a field.", }; verify(checkConfig, getPath("InputHiddenField.java"), expected); } /** tests ignoreSetter property */ @Test public void testIgnoreSetter() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HiddenFieldCheck.class); checkConfig.addAttribute("ignoreSetter", "true"); final String[] expected = { "18:13: 'hidden' hides a field.", "21:33: 'hidden' hides a field.", "27:13: 'hidden' hides a field.", "32:18: 'hidden' hides a field.", "36:33: 'hidden' hides a field.", "46:17: 'innerHidden' hides a field.", "49:26: 'innerHidden' hides a field.", "55:17: 'innerHidden' hides a field.", "56:17: 'hidden' hides a field.", "61:22: 'innerHidden' hides a field.", "64:22: 'hidden' hides a field.", "69:17: 'innerHidden' hides a field.", "70:17: 'hidden' hides a field.", "76:17: 'innerHidden' hides a field.", "77:17: 'hidden' hides a field.", "82:13: 'hidden' hides a field.", "106:29: 'prop' hides a field.", "112:29: 'prop' hides a field.", "124:28: 'prop' hides a field.", "138:13: 'hidden' hides a field.", "143:13: 'hidden' hides a field.", "148:13: 'hidden' hides a field.", "152:13: 'hidden' hides a field.", "179:23: 'y' hides a field.", "200:17: 'hidden' hides a field.", "210:20: 'hidden' hides a field.", "217:13: 'hidden' hides a field.", "223:13: 'hiddenStatic' hides a field.", "230:41: 'x' hides a field.", }; verify(checkConfig, getPath("InputHiddenField.java"), expected); } /** tests ignoreConstructorParameter property */ @Test public void testIgnoreConstructorParameter() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HiddenFieldCheck.class); checkConfig.addAttribute("ignoreConstructorParameter", "true"); final String[] expected = { "18:13: 'hidden' hides a field.", "27:13: 'hidden' hides a field.", "32:18: 'hidden' hides a field.", "36:33: 'hidden' hides a field.", "46:17: 'innerHidden' hides a field.", "55:17: 'innerHidden' hides a field.", "56:17: 'hidden' hides a field.", "61:22: 'innerHidden' hides a field.", "64:22: 'hidden' hides a field.", "69:17: 'innerHidden' hides a field.", "70:17: 'hidden' hides a field.", "76:17: 'innerHidden' hides a field.", "77:17: 'hidden' hides a field.", "82:13: 'hidden' hides a field.", "100:29: 'prop' hides a field.", "106:29: 'prop' hides a field.", "112:29: 'prop' hides a field.", "124:28: 'prop' hides a field.", "138:13: 'hidden' hides a field.", "143:13: 'hidden' hides a field.", "148:13: 'hidden' hides a field.", "152:13: 'hidden' hides a field.", "179:23: 'y' hides a field.", "200:17: 'hidden' hides a field.", "217:13: 'hidden' hides a field.", "223:13: 'hiddenStatic' hides a field.", "230:41: 'x' hides a field.", }; verify(checkConfig, getPath("InputHiddenField.java"), expected); } /** Test against a class with field declarations in different order */ @Test public void testReordered() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HiddenFieldCheck.class); final String[] expected = { "18:13: 'hidden' hides a field.", "21:40: 'hidden' hides a field.", "27:13: 'hidden' hides a field.", "32:18: 'hidden' hides a field.", "36:33: 'hidden' hides a field.", "46:17: 'innerHidden' hides a field.", "49:26: 'innerHidden' hides a field.", "55:17: 'innerHidden' hides a field.", "56:17: 'hidden' hides a field.", "61:22: 'innerHidden' hides a field.", "64:22: 'hidden' hides a field.", "69:17: 'innerHidden' hides a field.", "70:17: 'hidden' hides a field.", "76:17: 'innerHidden' hides a field.", "77:17: 'hidden' hides a field.", "83:13: 'hidden' hides a field.", "105:17: 'hidden' hides a field.", "118:21: 'hidden' hides a field.", "125:13: 'hidden' hides a field.", "131:13: 'hiddenStatic' hides a field.", }; verify(checkConfig, getPath("InputHiddenFieldReorder.java"), expected); } @Test public void testIgnoreAbstractMethods() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HiddenFieldCheck.class); checkConfig.addAttribute("ignoreAbstractMethods", "true"); final String[] expected = { "18:13: 'hidden' hides a field.", "21:33: 'hidden' hides a field.", "27:13: 'hidden' hides a field.", "32:18: 'hidden' hides a field.", "36:33: 'hidden' hides a field.", "46:17: 'innerHidden' hides a field.", "49:26: 'innerHidden' hides a field.", "55:17: 'innerHidden' hides a field.", "56:17: 'hidden' hides a field.", "61:22: 'innerHidden' hides a field.", "64:22: 'hidden' hides a field.", "69:17: 'innerHidden' hides a field.", "70:17: 'hidden' hides a field.", "76:17: 'innerHidden' hides a field.", "77:17: 'hidden' hides a field.", "82:13: 'hidden' hides a field.", "100:29: 'prop' hides a field.", "106:29: 'prop' hides a field.", "112:29: 'prop' hides a field.", "124:28: 'prop' hides a field.", "138:13: 'hidden' hides a field.", "143:13: 'hidden' hides a field.", "148:13: 'hidden' hides a field.", "152:13: 'hidden' hides a field.", "179:23: 'y' hides a field.", "200:17: 'hidden' hides a field.", "210:20: 'hidden' hides a field.", "217:13: 'hidden' hides a field.", "223:13: 'hiddenStatic' hides a field.", }; verify(checkConfig, getPath("InputHiddenField.java"), expected); } }
lgpl-2.1
elelpublic/wikipower
src/test/java/com/infodesire/wikipower/storage/StorageLocatorTest.java
3889
// (C) 1998-2015 Information Desire Software GmbH // www.infodesire.com package com.infodesire.wikipower.storage; import static org.junit.Assert.*; import com.google.common.io.Files; import com.infodesire.bsmcommons.file.FilePath; import com.infodesire.bsmcommons.io.Bytes; import com.infodesire.bsmcommons.io.Charsets; import com.infodesire.bsmcommons.io.PrintStringWriter; import com.infodesire.bsmcommons.zip.Unzip; import com.infodesire.wikipower.wiki.Page; import com.infodesire.wikipower.wiki.RenderConfig; import com.infodesire.wikipower.wiki.Renderer; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.codehaus.plexus.util.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; public class StorageLocatorTest { private File tempDir; private Renderer renderer; @Before public void setUp() throws Exception { tempDir = Files.createTempDir(); RenderConfig config = new RenderConfig(); renderer = new Renderer( config ); } @After public void tearDown() throws Exception { FileUtils.deleteDirectory( tempDir ); } @Test public void testLocate() throws IOException, InstantiationException, IllegalAccessException { File zipFile = File.createTempFile( "WikipackStorageTest", ".wikipack" ); OutputStream outputStream = new FileOutputStream( zipFile ); ZipOutputStream zipOut = new ZipOutputStream( outputStream ); zipFile( zipOut, "main.markdown", "main" ); zipFile( zipOut, "sub/sub1.markdown", "sub1" ); zipFile( zipOut, "sub/sub2.markdown", "sub2" ); zipFile( zipOut, "sub/sub/subsub.markdown", "subsub" ); zipOut.close(); Unzip.unzip( zipFile, tempDir ); Storage s; s = StorageLocator.locateStorage( zipFile.toURI().toURL().toString(), null ); assertTrue( s instanceof WikipackStorage ); assertPageContent( s, "main.markdown", "main" ); assertPageContent( s, "sub/sub/subsub.markdown", "subsub" ); s = StorageLocator.locateStorage( tempDir.toURI().toURL().toString(), null ); assertTrue( s instanceof FileStorage ); assertPageContent( s, "main.markdown", "main" ); assertPageContent( s, "sub/sub/subsub.markdown", "subsub" ); s = StorageLocator.locateStorage( "classpath:///sample.wikipack", null ); assertTrue( s instanceof WikipackStorage ); assertPageContent( s, "main.markdown", "main" ); assertPageContent( s, "sub/sub/subsub.markdown", "subsub" ); try { s = StorageLocator.locateStorage( "classpath:///sample1.wikipack", null ); fail( "No storage exception thrown when resource not found" ); } catch( StorageException ex ) {} } private void assertPageContent( Storage s, String path, String html ) throws InstantiationException, IllegalAccessException, IOException { Page p = s.getPage( FilePath.parse( path ) ); PrintStringWriter content = new PrintStringWriter(); renderer.render( p, content ); assertTrue( "Expected somewhat like " + html + " but found " + content, containsHtml( html, content.toString() ) ); } private boolean containsHtml( String string, String content ) { int body = content.indexOf( "<body>" ); int found = content.indexOf( string ); int endBody = content.indexOf( "</body>" ); return body != -1 && found != -1 && endBody != -1 && body < found && found < endBody; } private void zipFile( ZipOutputStream zipOut, String fileName, String content ) throws IOException { zipOut.putNextEntry( new ZipEntry( fileName ) ); InputStream from = new ByteArrayInputStream( content.getBytes( Charsets.UTF_8 )); Bytes.pipe( from, zipOut ); } }
lgpl-2.1
mbatchelor/pentaho-reporting
designer/datasource-editor-kettle/src/main/java/org/pentaho/reporting/ui/datasources/kettle/parameter/FilteringParameterTableModel.java
2148
/*! * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * 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 Lesser General Public License for more details. * * Copyright (c) 2002-2017 Hitachi Vantara.. All rights reserved. */ package org.pentaho.reporting.ui.datasources.kettle.parameter; import org.pentaho.reporting.libraries.designtime.swing.table.PropertyTableModel; import org.pentaho.reporting.libraries.designtime.swing.table.RowMapperTableModel; import java.beans.PropertyEditor; public class FilteringParameterTableModel extends RowMapperTableModel implements PropertyTableModel { private FormulaParameterTableModel backend; private FilterStrategy<FormulaParameterTableModel> filterType; public FilteringParameterTableModel( final FilterStrategy<FormulaParameterTableModel> filterType, final FormulaParameterTableModel backend ) { super( backend ); if ( filterType == null ) { throw new NullPointerException(); } if ( backend == null ) { throw new NullPointerException(); } this.filterType = filterType; this.backend = backend; recomputeRowCount(); } protected boolean isFiltered( final int row ) { return filterType.isAcceptedRow( row, backend ) == false; } public Class getClassForCell( final int row, final int col ) { return backend.getClassForCell( mapToModel( row ), col ); } public PropertyEditor getEditorForCell( final int row, final int column ) { return backend.getEditorForCell( mapToModel( row ), column ); } }
lgpl-2.1
fazz/digidoc4j
src/org/digidoc4j/impl/bdoc/ManifestValidator.java
9700
/* DigiDoc4J library * * This software is released under either the GNU Library General Public * License (see LICENSE.LGPL). * * Note that the only valid version of the LGPL license as far as this * project is concerned is the original GNU Library General Public License * Version 2.1, February 1999 */ package org.digidoc4j.impl.bdoc; import eu.europa.ec.markt.dss.DSSXMLUtils; import eu.europa.ec.markt.dss.signature.DSSDocument; import eu.europa.ec.markt.dss.signature.InMemoryDocument; import eu.europa.ec.markt.dss.signature.validation.AdvancedSignature; import eu.europa.ec.markt.dss.validation102853.SignedDocumentValidator; import org.apache.xml.security.signature.Reference; import org.digidoc4j.Signature; import org.digidoc4j.exceptions.DigiDoc4JException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; /** * For validating meta data within the manifest file and signature files. */ public class ManifestValidator { static final Logger logger = LoggerFactory.getLogger(ManifestValidator.class); private InMemoryDocument manifestFile; private SignedDocumentValidator asicValidator; private List<DSSDocument> detachedContents; /** * Constructor. * * @param validator Validator object */ public ManifestValidator(SignedDocumentValidator validator) { logger.debug(""); asicValidator = validator; detachedContents = asicValidator.getDetachedContents(); for (DSSDocument dssDocument : detachedContents) { if ("META-INF/manifest.xml".equals(dssDocument.getName())) { manifestFile = (InMemoryDocument) dssDocument; break; } } } /** * Validate the container. * * @param signatures list of signatures * @return list of error messages */ public List<String> validateDocument(Collection<Signature> signatures) { logger.debug(""); if (manifestFile == null) { String errorMessage = "Container does not contain manifest file."; logger.error(errorMessage); throw new DigiDoc4JException(errorMessage); } List<String> errorMessages = new ArrayList<>(); Set<ManifestEntry> manifestEntries = getManifestFileItems(); Set<ManifestEntry> signatureEntries = new HashSet<>(); for (Signature signature : signatures) { signatureEntries = getSignatureEntries((BDocSignature) signature); errorMessages.addAll(validateEntries(manifestEntries, signatureEntries, signature.getId())); } errorMessages.addAll(validateFilesInContainer(signatureEntries)); return errorMessages; } private List<String> validateFilesInContainer(Set<ManifestEntry> signatureEntries) { logger.debug(""); ArrayList<String> errorMessages = new ArrayList<>(); if (signatureEntries.size() == 0) return errorMessages; List<String> filesInContainer = new ArrayList<>(getFilesInContainer()); if (filesInContainer.size() != signatureEntries.size()) { List<String> signatureEntriesFileNames = getFileNamesFromManifestEntrySet(signatureEntries); filesInContainer.removeAll(signatureEntriesFileNames); for (String fileName : filesInContainer) { errorMessages.add("Container contains a file named " + fileName + " which is not found in the signature " + "file"); } } return errorMessages; } private List<String> getFileNamesFromManifestEntrySet(Set<ManifestEntry> signatureEntries) { logger.debug(""); List<String> signatureEntriesFileNames = new ArrayList<>(); for (ManifestEntry entry : signatureEntries) { signatureEntriesFileNames.add(entry.getFileName()); } return signatureEntriesFileNames; } @SuppressWarnings("unchecked") static List<String> validateEntries(Set<ManifestEntry> manifestEntries, Set<ManifestEntry> signatureEntries, String signatureId) { logger.debug(""); ArrayList<String> errorMessages = new ArrayList<>(); if (signatureEntries.size() == 0) return errorMessages; Set<ManifestEntry> one = new HashSet(manifestEntries); Set<ManifestEntry> two = new HashSet(signatureEntries); one.removeAll(signatureEntries); two.removeAll(manifestEntries); for (ManifestEntry manifestEntry : one) { String fileName = manifestEntry.getFileName(); ManifestEntry signatureEntry = signatureEntryForFile(fileName, signatureEntries); if (signatureEntry != null) { errorMessages.add("Manifest file has an entry for file " + fileName + " with mimetype " + manifestEntry.getMimeType() + " but the signature file for signature " + signatureId + " indicates the mimetype is " + signatureEntry.getMimeType()); two.remove(signatureEntry); } else { errorMessages.add("Manifest file has an entry for file " + fileName + " with mimetype " + manifestEntry.getMimeType() + " but the signature file for signature " + signatureId + " does not have an entry for this file"); } } for (ManifestEntry manifestEntry : two) { errorMessages.add("The signature file for signature " + signatureId + " has an entry for file " + manifestEntry.getFileName() + " with mimetype " + manifestEntry.getMimeType() + " but the manifest file does not have an entry for this file"); } return errorMessages; } private static ManifestEntry signatureEntryForFile(String fileName, Set<ManifestEntry> signatureEntries) { logger.debug("File name: " + fileName); for (ManifestEntry signatureEntry : signatureEntries) { if (fileName.equals(signatureEntry.getFileName())) { return signatureEntry; } } return null; } private Set<ManifestEntry> getSignatureEntries(BDocSignature signature) { logger.debug(""); Set<ManifestEntry> signatureEntries = new HashSet<>(); List<Reference> references = signature.getOrigin().getReferences(); for (Reference reference : references) { if (reference.getType().equals("")) { String mimeTypeString = null; Node signatureNode = signature.getOrigin().getSignatureElement(); Node node = DSSXMLUtils.getNode(signatureNode, "./ds:SignedInfo/ds:Reference[@URI=\"" + reference.getURI() + "\"]"); if (node != null) { String referenceId = node.getAttributes().getNamedItem("Id").getNodeValue(); mimeTypeString = DSSXMLUtils.getValue(signatureNode, "./ds:Object/xades:QualifyingProperties/xades:SignedProperties/" + "xades:SignedDataObjectProperties/xades:DataObjectFormat" + "[@ObjectReference=\"#" + referenceId + "\"]/xades:MimeType"); } // TODO: mimeTypeString == null ? node == null? String uri = getFileURI(reference); signatureEntries.add(new ManifestEntry(uri, mimeTypeString)); } } return signatureEntries; } private String getFileURI(Reference reference) { String uri = reference.getURI(); try { uri = new URI(uri).getPath(); } catch (URISyntaxException e) { logger.debug("Does not parse as an URI, therefore assuming it's not encoded: '" + uri + "'"); } return uri; } Set<ManifestEntry> getManifestFileItems() { logger.debug(""); Set<ManifestEntry> entries = new HashSet<>(); Element root = DSSXMLUtils.buildDOM(manifestFile).getDocumentElement(); Node firstChild = root.getFirstChild(); while (firstChild != null) { String nodeName = firstChild.getNodeName(); if ("manifest:file-entry".equals(nodeName)) { NamedNodeMap attributes = firstChild.getAttributes(); String textContent = attributes.getNamedItem("manifest:full-path").getTextContent(); String mimeType = attributes.getNamedItem("manifest:media-type").getTextContent(); if (!"/".equals(textContent)) if (!entries.add(new ManifestEntry(textContent, mimeType))) { DigiDoc4JException digiDoc4JException = new DigiDoc4JException("duplicate entry in manifest file"); logger.error(digiDoc4JException.getMessage()); throw digiDoc4JException; } } firstChild = firstChild.getNextSibling(); } return entries; } private List<String> getFilesInContainer() { logger.debug(""); List<String> fileEntries = new ArrayList<>(); List<String> signatureFileNames = getSignatureFileNames(); for (DSSDocument detachedContent : detachedContents) { String name = detachedContent.getName(); if (!("META-INF/manifest.xml".equals(name) || ("META-INF/".equals(name)) || ("mimetype".equals(name) || signatureFileNames.contains(name)))) { fileEntries.add(name); } } return fileEntries; } private List<String> getSignatureFileNames() { logger.debug(""); List<String> signatureFileNames = new ArrayList<>(); for (AdvancedSignature signature : asicValidator.getSignatures()) { String signatureFileName = "META-INF/signature" + signature.getId().toLowerCase() + ".xml"; if (signatureFileNames.contains(signatureFileName)) { String errorMessage = "Duplicate signature file: " + signatureFileName; logger.error(errorMessage); throw new DigiDoc4JException(errorMessage); } signatureFileNames.add(signatureFileName); } return signatureFileNames; } }
lgpl-2.1
alesharik/SimplyInstruments
src/main/java/SimplyTools/assembler/AssemblerRegister.java
1150
package SimplyTools.assembler; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.item.Item; import net.minecraftforge.client.MinecraftForgeClient; import SimplyTools.SimplyTools; import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.registry.GameRegistry; public class AssemblerRegister { public static Block AssemblerBlock; //public static TileEntity TileEntityAssembler = new TileEntityAssembler(); public static void CInit() { GameRegistry.registerBlock(AssemblerBlock = new AssemblerBlock("AssemblerBlock", Material.wood), "AssemblerBlock"); GameRegistry.registerTileEntity(AssemblerTileEntity.class, "512"); NetworkRegistry.INSTANCE.registerGuiHandler(SimplyTools.MODID, new GUIHandler()); } public static void ClInit() { ClientRegistry.bindTileEntitySpecialRenderer(AssemblerTileEntity.class, new AssemblerSpecialRenderer()); MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(AssemblerRegister.AssemblerBlock), new AssemblerBlockRenderAsItem()); } }
lgpl-2.1
CypraxPuch/abixen-platform
abixen-platform-modules/src/main/java/com/abixen/platform/module/chart/service/ChartConfigurationService.java
1378
/** * Copyright (c) 2010-present Abixen Systems. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.abixen.platform.module.chart.service; import com.abixen.platform.module.chart.form.ChartConfigurationForm; import com.abixen.platform.module.chart.model.impl.ChartConfiguration; public interface ChartConfigurationService { ChartConfiguration buildChartConfiguration(ChartConfigurationForm chartConfigurationForm); ChartConfigurationForm createChartConfiguration(ChartConfigurationForm chartConfigurationForm); ChartConfigurationForm updateChartConfiguration(ChartConfigurationForm chartConfigurationForm); ChartConfiguration findChartConfigurationByModuleId(Long id); ChartConfiguration createChartConfiguration(ChartConfiguration chartConfiguration); ChartConfiguration updateChartConfiguration(ChartConfiguration chartConfiguration); }
lgpl-2.1
mdippery/3ddv
src/main/java/org/nees/rpi/vis/ui/VisUtils.java
2852
/** * Copyright (c) 2004-2007 Rensselaer Polytechnic Institute * Copyright (c) 2007 NEES Cyberinfrastructure Center * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * For more information: http://nees.rpi.edu/3dviewer/ */ package org.nees.rpi.vis.ui; import javax.swing.*; import java.awt.image.BufferedImage; import java.awt.image.ColorConvertOp; import java.awt.*; import java.awt.color.ColorSpace; import java.io.IOException; /** * */ public abstract class VisUtils { public static BufferedImage toBufferedImage(Image image, int type) { int w = image.getWidth(null); int h = image.getHeight(null); BufferedImage result = new BufferedImage(w, h, type); Graphics2D g = result.createGraphics(); g.drawImage(image, 0, 0, null); g.dispose(); return result; } public static FontMetrics getFontMetrics(Font font) { BufferedImage bimage = new BufferedImage(40, 40,BufferedImage.TYPE_INT_RGB); Graphics g = bimage.createGraphics(); return g.getFontMetrics(font); } public static Image scaleImage(BufferedImage image, double compHeight) { double scaledWidth = image.getWidth(), scaledHeight = image.getHeight(); if (compHeight < image.getHeight()) { scaledWidth = image.getWidth() * (compHeight / image.getHeight()); scaledHeight = compHeight; } if (scaledWidth > compHeight) { scaledHeight = scaledHeight * (compHeight / scaledWidth); scaledWidth = compHeight; } if (scaledHeight != image.getHeight()) { return image.getScaledInstance( (int)scaledWidth, (int)scaledHeight, Image.SCALE_AREA_AVERAGING); } return image; } public static BufferedImage getGrayScaleImage(BufferedImage image) { ColorConvertOp grayOp = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null); return grayOp.filter(image, null); } public static JFrame getParentFrame(JComponent c) { Container parent = c.getParent(); if (parent == null) return null; else if (parent instanceof JFrame) return (JFrame) parent; else return getParentFrame((JComponent)parent); } }
lgpl-2.1
Sable/heros
src/heros/flowfunc/Gen.java
1373
/******************************************************************************* * Copyright (c) 2012 Eric Bodden. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * Contributors: * Eric Bodden - initial API and implementation ******************************************************************************/ package heros.flowfunc; import static heros.TwoElementSet.twoElementSet; import static java.util.Collections.singleton; import heros.FlowFunction; import java.util.Set; /** * Function that creates a new value (e.g. returns a set containing a fixed value when given * a specific parameter), but acts like the identity function for all other parameters. * * @param <D> The type of data-flow facts to be computed by the tabulation problem. */ public class Gen<D> implements FlowFunction<D> { private final D genValue; private final D zeroValue; public Gen(D genValue, D zeroValue){ this.genValue = genValue; this.zeroValue = zeroValue; } public Set<D> computeTargets(D source) { if(source.equals(zeroValue)) { return twoElementSet(source, genValue); } else { return singleton(source); } } }
lgpl-2.1
plast-lab/soot
src/main/java/soot/baf/InstanceOfInst.java
993
package soot.baf; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam, Patrick Pominville and Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.Type; public interface InstanceOfInst extends Inst { public Type getCheckType(); public void setCheckType(Type type); }
lgpl-2.1
tywo45/talent-aio
example/im/talent-aio-examples-im-common/src/main/java/com/talent/aio/examples/im/common/http/KeyValue.java
997
/** * ************************************************************************** * * @说明: * @项目名称: talent-aio-examples-im-common * * @author: tanyaowu * @创建时间: 2017年2月23日 下午3:04:40 * * ************************************************************************** */ package com.talent.aio.examples.im.common.http; /** * * @author tanyaowu * @创建时间 2017年2月23日 下午3:04:40 * * @操作列表 * 编号 | 操作时间 | 操作人员 | 操作说明 * (1) | 2017年2月23日 | tanyaowu | 新建类 * */ public class KeyValue { private String key; private String value; /** * @return the key */ public String getKey() { return key; } /** * @param key the key to set */ public void setKey(String key) { this.key = key; } /** * @return the value */ public String getValue() { return value; } /** * @param value the value to set */ public void setValue(String value) { this.value = value; } }
lgpl-2.1
threerings/nenya
core/src/main/java/com/threerings/cast/builder/ClassEditor.java
3662
// // Nenya library - tools for developing networked games // Copyright (C) 2002-2012 Three Rings Design, Inc., All Rights Reserved // https://github.com/threerings/nenya // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.cast.builder; import java.util.List; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import com.samskivert.swing.HGroupLayout; import com.samskivert.swing.VGroupLayout; import com.threerings.cast.ComponentClass; /** * The class editor displays a label and a slider that allow the user to * select the desired component for a given component class. */ public class ClassEditor extends JPanel implements ChangeListener { /** * Constructs a class editor. */ public ClassEditor (BuilderModel model, ComponentClass cclass, List<Integer> components) { _model = model; _components = components; _cclass = cclass; VGroupLayout vgl = new VGroupLayout(VGroupLayout.STRETCH); vgl.setOffAxisPolicy(VGroupLayout.STRETCH); setLayout(vgl); HGroupLayout hgl = new HGroupLayout(); hgl.setJustification(HGroupLayout.LEFT); JPanel sub = new JPanel(hgl); sub.add(new JLabel(cclass.name + ": ")); sub.add(_clabel = new JLabel("0")); add(sub); // create the slider allowing selection of available components int max = components.size() - 1; JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, max, 0); slider.setSnapToTicks(true); slider.addChangeListener(this); add(slider); // set the starting component for this class setSelectedComponent(0); } // documentation inherited public void stateChanged (ChangeEvent e) { JSlider source = (JSlider)e.getSource(); if (!source.getValueIsAdjusting()) { int val = source.getValue(); // update the model with the newly selected component setSelectedComponent(val); // update the label with the new value _clabel.setText(Integer.toString(val)); } } /** * Sets the selected component in the builder model for the * component class associated with this editor to the component at * the given index in this editor's list of available components. */ protected void setSelectedComponent (int idx) { int cid = _components.get(idx).intValue(); _model.setSelectedComponent(_cclass, cid); } /** The component class associated with this editor. */ protected ComponentClass _cclass; /** The components selectable via this editor. */ protected List<Integer> _components; /** The label denoting the currently selected component index. */ protected JLabel _clabel; /** The builder model. */ protected BuilderModel _model; }
lgpl-2.1
moldfire/Summoner
src/main/java/com/moldfire/summoner/entity/EntityMFSKelpie.java
8799
package com.moldfire.summoner.entity; import com.google.common.base.Predicate; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityAgeable; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.EntityAIAttackOnCollide; import net.minecraft.entity.ai.EntityAIBase; import net.minecraft.entity.ai.EntityAIFollowOwner; import net.minecraft.entity.ai.EntityAIFollowParent; import net.minecraft.entity.ai.EntityAIHurtByTarget; import net.minecraft.entity.ai.EntityAILeapAtTarget; import net.minecraft.entity.ai.EntityAILookIdle; import net.minecraft.entity.ai.EntityAIMate; import net.minecraft.entity.ai.EntityAINearestAttackableTarget; import net.minecraft.entity.ai.EntityAIOwnerHurtByTarget; import net.minecraft.entity.ai.EntityAIOwnerHurtTarget; import net.minecraft.entity.ai.EntityAIPanic; import net.minecraft.entity.ai.EntityAIRunAroundLikeCrazy; import net.minecraft.entity.ai.EntityAISwimming; import net.minecraft.entity.ai.EntityAITargetNonTamed; import net.minecraft.entity.ai.EntityAITempt; import net.minecraft.entity.ai.EntityAIWander; import net.minecraft.entity.ai.EntityAIWatchClosest; import net.minecraft.entity.monster.EntitySkeleton; import net.minecraft.entity.passive.EntityAnimal; import net.minecraft.entity.passive.EntityRabbit; import net.minecraft.entity.passive.EntitySheep; import net.minecraft.entity.passive.EntitySquid; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.pathfinding.PathNavigateGround; import net.minecraft.potion.Potion; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MathHelper; import net.minecraft.world.World; public class EntityMFSKelpie extends EntityMFS { public EntityMFSKelpie(World worldIn) { super(worldIn); ((PathNavigateGround)this.getNavigator()).setAvoidsWater(true); this.tasks.addTask(0, new EntityAISwimming(this)); this.tasks.addTask(1, new EntityAIPanic(this, 1.2D)); this.tasks.addTask(2, new EntityAIWander(this, 0.7D)); this.tasks.addTask(3, new EntityAIWatchClosest(this, EntityPlayer.class, 6.0F)); this.tasks.addTask(4, new EntityAILookIdle(this)); this.setTamed(false); } @Override protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(53.0D); this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.42499999403953552D); } @Override public boolean canBreatheUnderwater() { return true; } @Override public void onLivingUpdate() { super.onLivingUpdate(); for(int y = 0; y < 3; y++) { if(worldObj.getBlockState(getPosition().add(0, -y, 0)) == Blocks.air.getDefaultState()) { continue; } if(worldObj.getBlockState(new BlockPos(getPosition().add(0, -y, 0))) == Blocks.water.getDefaultState()) { this.inWater = true; break; } else if(worldObj.getBlockState(getPosition().add(0, -y, 0)) != Blocks.air.getDefaultState() && worldObj.getBlockState(new BlockPos(getPosition().add(0, -y, 0))) != Blocks.water.getDefaultState()) { this.inWater = false; break; } /*if(this.isTamed()) { if(!this.inWater) { this.worldObj.spawnParticle(EnumParticleTypes.REDSTONE, this.posX, this.posY+2, this.posZ, 0, 0.1F, 0, 0); } else { this.worldObj.spawnParticle(EnumParticleTypes.REDSTONE, this.posX-1, this.posY+2, this.posZ, 0, 0.1F, 0, 0); } }*/ } if(this.isInWater()) { this.setSize(1.4F, 1.6F); } else { this.setSize(0.6F, 1.8F); } } private void mountTo(EntityPlayer player) { player.rotationYaw = this.rotationYaw; player.rotationPitch = this.rotationPitch; //this.setEatingHaystack(false); //this.setRearing(false); if (!this.worldObj.isRemote) { player.mountEntity(this); } } /** * Returns the sound this mob makes while it's alive. */ @Override protected String getLivingSound() { return null;//Reference.MOD_ID+":mob.imp.say"; } /** * Returns the sound this mob makes when it is hurt. */ @Override protected String getHurtSound() { return null;//Reference.MOD_ID+":mob.imp.hurt"; } /** * Returns the sound this mob makes on death. */ @Override protected String getDeathSound() { return null;//Reference.MOD_ID+":mob.imp.hurt"; } @Override protected void playStepSound(BlockPos pos, Block blockIn) { //this.playSound("mob.horse.step", 0.15F, 1.0F); } /** * Returns the volume for the sounds this mob makes. */ @Override protected float getSoundVolume() { return 0.4F; } @Override protected Item getDropItem() { return null; } /** * Drop 0-2 items of this living's type */ @Override protected void dropFewItems(boolean p_70628_1_, int p_70628_2_) { } /** * Called when a player interacts with a mob. e.g. gets milk from a cow, gets into the saddle on a pig. */ @Override public boolean interact(EntityPlayer player) { super.interact(player); if(this.isTamed() && this.riddenByEntity == null) { this.mountTo(player); return true; } return false; } @Override public void moveEntityWithHeading(float strafe, float forward) { if (this.riddenByEntity != null && this.riddenByEntity instanceof EntityLivingBase && this.isTamed()) { this.prevRotationYaw = this.rotationYaw = this.riddenByEntity.rotationYaw; this.rotationPitch = this.riddenByEntity.rotationPitch * 0.5F; this.setRotation(this.rotationYaw, this.rotationPitch); this.rotationYawHead = this.renderYawOffset = this.rotationYaw; strafe = ((EntityLivingBase)this.riddenByEntity).moveStrafing * 0.5F; forward = ((EntityLivingBase)this.riddenByEntity).moveForward; if (forward <= 0.0F) { forward *= 0.25F; } if (this.onGround) { strafe = 0.0F; forward = 0.0F; this.motionY = 0; this.isAirBorne = true; if (forward > 0.0F) { float f = MathHelper.sin(this.rotationYaw * (float)Math.PI / 180.0F); float f1 = MathHelper.cos(this.rotationYaw * (float)Math.PI / 180.0F); this.motionX += (double)(-0.16F * f); this.motionZ += (double)(0.16F * f1); } } this.stepHeight = 1.0F; if(!this.inWater && this.riddenByEntity != null) { this.jumpMovementFactor = this.getAIMoveSpeed() * 0.1F; } else { this.jumpMovementFactor = this.getAIMoveSpeed() * 2F; } if (!this.worldObj.isRemote) { this.setAIMoveSpeed((float)this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).getAttributeValue()); super.moveEntityWithHeading(strafe, forward); } this.prevLimbSwingAmount = this.limbSwingAmount; double d1 = this.posX - this.prevPosX; double d0 = this.posZ - this.prevPosZ; float f2 = MathHelper.sqrt_double(d1 * d1 + d0 * d0) * 4.0F; if (f2 > 1.0F) { f2 = 1.0F; } this.limbSwingAmount += (f2 - this.limbSwingAmount) * 0.4F; this.limbSwing += this.limbSwingAmount; } else { this.stepHeight = 0.5F; this.jumpMovementFactor = 0.02F; super.moveEntityWithHeading(strafe, forward); } } @Override public float getEyeHeight() { return this.height; } @Override public EntityAgeable createChild(EntityAgeable ageable) { return null; } }
lgpl-2.1
LorenzoDCC/carpentersblocks
carpentersblocks/util/stairs/StairsTransform.java
16115
package carpentersblocks.util.stairs; import net.minecraft.block.Block; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import carpentersblocks.block.BlockCarpentersStairs; import carpentersblocks.data.Stairs; import carpentersblocks.data.Stairs.Type; import carpentersblocks.tileentity.TEBase; import carpentersblocks.util.BlockProperties; public class StairsTransform { /** * Transforms stairs to connect with adjacent stairs. */ public static int transformStairs(World world, int stairsID, int x, int y, int z) { Block block_XN = world.getBlock(x - 1, y, z); Block block_XP = world.getBlock(x + 1, y, z); Block block_YN = world.getBlock(x, y - 1, z); Block block_YP = world.getBlock(x, y + 1, z); Block block_ZN = world.getBlock(x, y, z - 1); Block block_ZP = world.getBlock(x, y, z + 1); Stairs stairs_XN = block_XN != null && block_XN instanceof BlockCarpentersStairs ? Stairs.stairsList[BlockProperties.getMetadata((TEBase) world.getTileEntity(x - 1, y, z))] : null; Stairs stairs_XP = block_XP != null && block_XP instanceof BlockCarpentersStairs ? Stairs.stairsList[BlockProperties.getMetadata((TEBase) world.getTileEntity(x + 1, y, z))] : null; Stairs stairs_YN = block_YN != null && block_YN instanceof BlockCarpentersStairs ? Stairs.stairsList[BlockProperties.getMetadata((TEBase) world.getTileEntity(x, y - 1, z))] : null; Stairs stairs_YP = block_YP != null && block_YP instanceof BlockCarpentersStairs ? Stairs.stairsList[BlockProperties.getMetadata((TEBase) world.getTileEntity(x, y + 1, z))] : null; Stairs stairs_ZN = block_ZN != null && block_ZN instanceof BlockCarpentersStairs ? Stairs.stairsList[BlockProperties.getMetadata((TEBase) world.getTileEntity(x, y, z - 1))] : null; Stairs stairs_ZP = block_ZP != null && block_ZP instanceof BlockCarpentersStairs ? Stairs.stairsList[BlockProperties.getMetadata((TEBase) world.getTileEntity(x, y, z + 1))] : null; /* Transform into normal side. */ if (stairs_YN != null) { if (stairs_YN.stairsType.equals(Type.NORMAL_SIDE)) { return stairs_YN.stairsID; } } if (stairs_YP != null) { if (stairs_YP.stairsType.equals(Type.NORMAL_SIDE)) { return stairs_YP.stairsID; } } /* Transform into normal corner. */ Stairs stairs = Stairs.stairsList[stairsID]; if (stairs_ZN != null) { if (stairs_XN != null) { if (stairs_ZN.facings.contains(ForgeDirection.WEST) && stairs_XN.facings.contains(ForgeDirection.NORTH)) { return stairs_XN.isPositive && stairs_ZN.isPositive ? Stairs.ID_NORMAL_INT_POS_NW : Stairs.ID_NORMAL_INT_NEG_NW; } if (stairs_ZN.facings.contains(ForgeDirection.EAST) && stairs_XN.facings.contains(ForgeDirection.SOUTH)) { return stairs_XN.isPositive && stairs_ZN.isPositive ? Stairs.ID_NORMAL_EXT_POS_SE : Stairs.ID_NORMAL_EXT_NEG_SE; } } if (stairs_XP != null) { if (stairs_ZN.facings.contains(ForgeDirection.EAST) && stairs_XP.facings.contains(ForgeDirection.NORTH)) { return stairs_XP.isPositive && stairs_ZN.isPositive ? Stairs.ID_NORMAL_INT_POS_NE : Stairs.ID_NORMAL_INT_NEG_NE; } if (stairs_ZN.facings.contains(ForgeDirection.WEST) && stairs_XP.facings.contains(ForgeDirection.SOUTH)) { return stairs_XP.isPositive && stairs_ZN.isPositive ? Stairs.ID_NORMAL_EXT_POS_SW : Stairs.ID_NORMAL_EXT_NEG_SW; } } } if (stairs_ZP != null) { if (stairs_XN != null) { if (stairs_ZP.facings.contains(ForgeDirection.WEST) && stairs_XN.facings.contains(ForgeDirection.SOUTH)) { return stairs_XN.isPositive && stairs_ZP.isPositive ? Stairs.ID_NORMAL_INT_POS_SW : Stairs.ID_NORMAL_INT_NEG_SW; } if (stairs_ZP.facings.contains(ForgeDirection.EAST) && stairs_XN.facings.contains(ForgeDirection.NORTH)) { return stairs_XN.isPositive && stairs_ZP.isPositive ? Stairs.ID_NORMAL_EXT_POS_NE : Stairs.ID_NORMAL_EXT_NEG_NE; } } if (stairs_XP != null) { if (stairs_ZP.facings.contains(ForgeDirection.EAST) && stairs_XP.facings.contains(ForgeDirection.SOUTH)) { return stairs_XP.isPositive && stairs_ZP.isPositive ? Stairs.ID_NORMAL_INT_POS_SE : Stairs.ID_NORMAL_INT_NEG_SE; } if (stairs_ZP.facings.contains(ForgeDirection.WEST) && stairs_XP.facings.contains(ForgeDirection.NORTH)) { return stairs_XP.isPositive && stairs_ZP.isPositive ? Stairs.ID_NORMAL_EXT_POS_NW : Stairs.ID_NORMAL_EXT_NEG_NW; } } } if (stairs_XN != null) { if (stairs.facings.contains(ForgeDirection.WEST)) { if (stairs_XN.facings.contains(ForgeDirection.SOUTH) && !stairs_XN.facings.contains(ForgeDirection.EAST)) { return stairs_XN.isPositive ? Stairs.ID_NORMAL_INT_POS_SW : Stairs.ID_NORMAL_INT_NEG_SW; } if (stairs_XN.facings.contains(ForgeDirection.NORTH) && !stairs_XN.facings.contains(ForgeDirection.EAST)) { return stairs_XN.isPositive ? Stairs.ID_NORMAL_INT_POS_NW : Stairs.ID_NORMAL_INT_NEG_NW; } } if (stairs.facings.contains(ForgeDirection.EAST)) { if (stairs_XN.facings.contains(ForgeDirection.SOUTH) && !stairs_XN.facings.contains(ForgeDirection.EAST)) { return stairs_XN.isPositive ? Stairs.ID_NORMAL_EXT_POS_SE : Stairs.ID_NORMAL_EXT_NEG_SE; } if (stairs_XN.facings.contains(ForgeDirection.NORTH) && !stairs_XN.facings.contains(ForgeDirection.EAST)) { return stairs_XN.isPositive ? Stairs.ID_NORMAL_EXT_POS_NE : Stairs.ID_NORMAL_EXT_NEG_NE; } } } if (stairs_XP != null) { if (stairs.facings.contains(ForgeDirection.WEST)) { if (stairs_XP.facings.contains(ForgeDirection.SOUTH) && !stairs_XP.facings.contains(ForgeDirection.WEST)) { return stairs_XP.isPositive ? Stairs.ID_NORMAL_EXT_POS_SW : Stairs.ID_NORMAL_EXT_NEG_SW; } if (stairs_XP.facings.contains(ForgeDirection.NORTH) && !stairs_XP.facings.contains(ForgeDirection.WEST)) { return stairs_XP.isPositive ? Stairs.ID_NORMAL_EXT_POS_NW : Stairs.ID_NORMAL_EXT_NEG_NW; } } if (stairs.facings.contains(ForgeDirection.EAST)) { if (stairs_XP.facings.contains(ForgeDirection.SOUTH) && !stairs_XP.facings.contains(ForgeDirection.WEST)) { return stairs_XP.isPositive ? Stairs.ID_NORMAL_INT_POS_SE : Stairs.ID_NORMAL_INT_NEG_SE; } if (stairs_XP.facings.contains(ForgeDirection.NORTH) && !stairs_XP.facings.contains(ForgeDirection.WEST)) { return stairs_XP.isPositive ? Stairs.ID_NORMAL_INT_POS_NE : Stairs.ID_NORMAL_INT_NEG_NE; } } } if (stairs_ZN != null) { if (stairs.facings.contains(ForgeDirection.NORTH)) { if (stairs_ZN.facings.contains(ForgeDirection.EAST) && !stairs_ZN.facings.contains(ForgeDirection.SOUTH)) { return stairs_ZN.isPositive ? Stairs.ID_NORMAL_INT_POS_NE : Stairs.ID_NORMAL_INT_NEG_NE; } if (stairs_ZN.facings.contains(ForgeDirection.WEST) && !stairs_ZN.facings.contains(ForgeDirection.SOUTH)) { return stairs_ZN.isPositive ? Stairs.ID_NORMAL_INT_POS_NW : Stairs.ID_NORMAL_INT_NEG_NW; } } if (stairs.facings.contains(ForgeDirection.SOUTH)) { if (stairs_ZN.facings.contains(ForgeDirection.EAST) && !stairs_ZN.facings.contains(ForgeDirection.SOUTH)) { return stairs_ZN.isPositive ? Stairs.ID_NORMAL_EXT_POS_SE : Stairs.ID_NORMAL_EXT_NEG_SE; } if (stairs_ZN.facings.contains(ForgeDirection.WEST) && !stairs_ZN.facings.contains(ForgeDirection.SOUTH)) { return stairs_ZN.isPositive ? Stairs.ID_NORMAL_EXT_POS_SW : Stairs.ID_NORMAL_EXT_NEG_SW; } } } if (stairs_ZP != null) { if (stairs.facings.contains(ForgeDirection.NORTH)) { if (stairs_ZP.facings.contains(ForgeDirection.EAST) && !stairs_ZP.facings.contains(ForgeDirection.NORTH)) { return stairs_ZP.isPositive ? Stairs.ID_NORMAL_EXT_POS_NE : Stairs.ID_NORMAL_EXT_NEG_NE; } if (stairs_ZP.facings.contains(ForgeDirection.WEST) && !stairs_ZP.facings.contains(ForgeDirection.NORTH)) { return stairs_ZP.isPositive ? Stairs.ID_NORMAL_EXT_POS_NW : Stairs.ID_NORMAL_EXT_NEG_NW; } } if (stairs.facings.contains(ForgeDirection.SOUTH)) { if (stairs_ZP.facings.contains(ForgeDirection.EAST) && !stairs_ZP.facings.contains(ForgeDirection.NORTH)) { return stairs_ZP.isPositive ? Stairs.ID_NORMAL_INT_POS_SE : Stairs.ID_NORMAL_INT_NEG_SE; } if (stairs_ZP.facings.contains(ForgeDirection.WEST) && !stairs_ZP.facings.contains(ForgeDirection.NORTH)) { return stairs_ZP.isPositive ? Stairs.ID_NORMAL_INT_POS_SW : Stairs.ID_NORMAL_INT_NEG_SW; } } } return stairsID; } /** * Transforms adjacent stairs to connect to source stairs. */ public static void transformAdjacentStairs(World world, int stairsID, int x, int y, int z) { Block block_XN = world.getBlock(x - 1, y, z); Block block_XP = world.getBlock(x + 1, y, z); Block block_ZN = world.getBlock(x, y, z - 1); Block block_ZP = world.getBlock(x, y, z + 1); Stairs stairs_XN = block_XN != null && block_XN instanceof BlockCarpentersStairs ? Stairs.stairsList[BlockProperties.getMetadata((TEBase) world.getTileEntity(x - 1, y, z))] : null; Stairs stairs_XP = block_XP != null && block_XP instanceof BlockCarpentersStairs ? Stairs.stairsList[BlockProperties.getMetadata((TEBase) world.getTileEntity(x + 1, y, z))] : null; Stairs stairs_ZN = block_ZN != null && block_ZN instanceof BlockCarpentersStairs ? Stairs.stairsList[BlockProperties.getMetadata((TEBase) world.getTileEntity(x, y, z - 1))] : null; Stairs stairs_ZP = block_ZP != null && block_ZP instanceof BlockCarpentersStairs ? Stairs.stairsList[BlockProperties.getMetadata((TEBase) world.getTileEntity(x, y, z + 1))] : null; Stairs stairs = Stairs.stairsList[stairsID]; TEBase TE_XN = stairs_XN != null ? (TEBase) world.getTileEntity(x - 1, y, z) : null; TEBase TE_XP = stairs_XP != null ? (TEBase) world.getTileEntity(x + 1, y, z) : null; TEBase TE_ZN = stairs_ZN != null ? (TEBase) world.getTileEntity(x, y, z - 1) : null; TEBase TE_ZP = stairs_ZP != null ? (TEBase) world.getTileEntity(x, y, z + 1) : null; if (stairs.facings.contains(ForgeDirection.WEST)) { if (stairs_ZN != null && stairs.isPositive == stairs_ZN.isPositive) { if (stairs_ZN.facings.contains(ForgeDirection.NORTH)) { BlockProperties.setMetadata(TE_ZN, stairs.isPositive ? Stairs.ID_NORMAL_EXT_POS_NW : Stairs.ID_NORMAL_EXT_NEG_NW); } if (stairs_ZN.facings.contains(ForgeDirection.SOUTH)) { BlockProperties.setMetadata(TE_ZN, stairs.isPositive ? Stairs.ID_NORMAL_INT_POS_SW : Stairs.ID_NORMAL_INT_NEG_SW); } } if (stairs_ZP != null && stairs.isPositive == stairs_ZP.isPositive) { if (stairs_ZP.facings.contains(ForgeDirection.SOUTH)) { BlockProperties.setMetadata(TE_ZP, stairs.isPositive ? Stairs.ID_NORMAL_EXT_POS_SW : Stairs.ID_NORMAL_EXT_NEG_SW); } if (stairs_ZP.facings.contains(ForgeDirection.NORTH)) { BlockProperties.setMetadata(TE_ZP, stairs.isPositive ? Stairs.ID_NORMAL_INT_POS_NW : Stairs.ID_NORMAL_INT_NEG_NW); } } } if (stairs.facings.contains(ForgeDirection.EAST)) { if (stairs_ZN != null && stairs.isPositive == stairs_ZN.isPositive) { if (stairs_ZN.facings.contains(ForgeDirection.NORTH)) { BlockProperties.setMetadata(TE_ZN, stairs.isPositive ? Stairs.ID_NORMAL_EXT_POS_NE : Stairs.ID_NORMAL_EXT_NEG_NE); } if (stairs_ZN.facings.contains(ForgeDirection.SOUTH)) { BlockProperties.setMetadata(TE_ZN, stairs.isPositive ? Stairs.ID_NORMAL_INT_POS_SE : Stairs.ID_NORMAL_INT_NEG_SE); } } if (stairs_ZP != null && stairs.isPositive == stairs_ZP.isPositive) { if (stairs_ZP.facings.contains(ForgeDirection.SOUTH)) { BlockProperties.setMetadata(TE_ZP, stairs.isPositive ? Stairs.ID_NORMAL_EXT_POS_SE : Stairs.ID_NORMAL_EXT_NEG_SE); } if (stairs_ZP.facings.contains(ForgeDirection.NORTH)) { BlockProperties.setMetadata(TE_ZP, stairs.isPositive ? Stairs.ID_NORMAL_INT_POS_NE : Stairs.ID_NORMAL_INT_NEG_NE); } } } if (stairs.facings.contains(ForgeDirection.NORTH)) { if (stairs_XN != null && stairs.isPositive == stairs_XN.isPositive) { if (stairs_XN.facings.contains(ForgeDirection.WEST)) { BlockProperties.setMetadata(TE_XN, stairs.isPositive ? Stairs.ID_NORMAL_EXT_POS_NW : Stairs.ID_NORMAL_EXT_NEG_NW); } if (stairs_XN.facings.contains(ForgeDirection.EAST)) { BlockProperties.setMetadata(TE_XN, stairs.isPositive ? Stairs.ID_NORMAL_INT_POS_NE : Stairs.ID_NORMAL_INT_NEG_NE); } } if (stairs_XP != null && stairs.isPositive == stairs_XP.isPositive) { if (stairs_XP.facings.contains(ForgeDirection.EAST)) { BlockProperties.setMetadata(TE_XP, stairs.isPositive ? Stairs.ID_NORMAL_EXT_POS_NE : Stairs.ID_NORMAL_EXT_NEG_NE); } if (stairs_XP.facings.contains(ForgeDirection.WEST)) { BlockProperties.setMetadata(TE_XP, stairs.isPositive ? Stairs.ID_NORMAL_INT_POS_NW : Stairs.ID_NORMAL_INT_NEG_NW); } } } if (stairs.facings.contains(ForgeDirection.SOUTH)) { if (stairs_XN != null && stairs.isPositive == stairs_XN.isPositive) { if (stairs_XN.facings.contains(ForgeDirection.WEST)) { BlockProperties.setMetadata(TE_XN, stairs.isPositive ? Stairs.ID_NORMAL_EXT_POS_SW : Stairs.ID_NORMAL_EXT_NEG_SW); } if (stairs_XN.facings.contains(ForgeDirection.EAST)) { BlockProperties.setMetadata(TE_XN, stairs.isPositive ? Stairs.ID_NORMAL_INT_POS_SE : Stairs.ID_NORMAL_INT_NEG_SE); } } if (stairs_XP != null && stairs.isPositive == stairs_XP.isPositive) { if (stairs_XP.facings.contains(ForgeDirection.EAST)) { BlockProperties.setMetadata(TE_XP, stairs.isPositive ? Stairs.ID_NORMAL_EXT_POS_SE : Stairs.ID_NORMAL_EXT_NEG_SE); } if (stairs_XP.facings.contains(ForgeDirection.WEST)) { BlockProperties.setMetadata(TE_XP, stairs.isPositive ? Stairs.ID_NORMAL_INT_POS_SW : Stairs.ID_NORMAL_INT_NEG_SW); } } } } }
lgpl-2.1
KDE/kross-interpreters
java/krossjava/java/KrossClassLoader.java
8535
package org.kde.kdebindings.java.krossjava; import java.util.*; import java.util.zip.*; import java.util.jar.*; import java.io.*; import java.net.*; import java.lang.reflect.*; /** * KrossClassLoader is a ClassLoader that allows the required flexibility * to make the bridge between Java and C. */ public class KrossClassLoader extends URLClassLoader { //This is ugly but I can't think of anything better for static access private static KrossClassLoader kcl = null; private Map storedClasses = new Hashtable(); private Map extensions = new Hashtable(); public static final int UNKNOWN_DATA = 0; public static final int CLASS_DATA = 1; public static final int JAR_DATA = 2; /** * Constructor. */ public KrossClassLoader(){ super(new URL[0], KrossClassLoader.class.getClassLoader()); kcl = this; } /** * Defines code in this classloader. This can be used to define an extension, a script, * or even a collection of classes via a JAR file. This method inspects the given data * and then executes addSingleClass or addJARData. * @param name A name to register the code by. This is used to prevent double definitions. * @param data The raw class data, either Java bytecode or a JAR file. * @return The correct classname of the added script. */ public String addClass(String name, byte[] data){ //TODO: check difference between compiled //and non-compiled, compile if needed switch(getDataType(data)){ case UNKNOWN_DATA: //TODO: compile System.out.println("Didn't get a valid script!"); return ""; case CLASS_DATA: return addSingleClass(name, data); case JAR_DATA: return addJARData(name, data); default: System.out.println("Unknown class data!"); return ""; } } /** * Defines a new Java class. * @param name A name to register the code by. This is used to prevent double definitions. * @param data A complete class definition in bytecode. * @return The real classname as defined by the bytecode. */ public String addSingleClass(String name, byte[] data){ //TODO: check difference between compiled //and non-compiled, compile if needed if(getDataType(data) != CLASS_DATA){ //TODO: compile System.out.println("Didn't get a valid classfile!"); } if(storedClasses.containsKey(name)){ //System.out.println("Class " + name + " already loaded."); return ((Class)storedClasses.get(name)).getName(); } try { Class c = defineClass(null, data, 0, data.length); //The passed name may be not the actual classname! //We allow both ways of access here. if(name != null && !name.equals("")) storedClasses.put(name,c); storedClasses.put(c.getName(),c); return c.getName(); } catch (LinkageError e) { e.printStackTrace(); } return ""; } /** * Defines a set of new classes. This makes it easy to add complex scripts. * Every .class file in the JAR is defined as a new class. If the manifest contains a * "Kross-Main" attribute in the main section, the value is considered to be the entry * class of a script and will be returned as the script name. * @param name A name to register the code by. This is used to prevent double definitions. * @param data The contents of a JAR file. * @return The value of the Kross-Main attribute, or "" if none could be found. */ public String addJARData(String name, byte[] data){ //TODO: perhaps make this useful as collection of KrossQExtensions, too? ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(data)); Manifest mf = null; try{ byte[] buff = new byte[1024]; ZipEntry entry = zis.getNextEntry(); while( entry != null){ String entryname = entry.getName(); if(entryname.endsWith(".class")){ ByteArrayOutputStream bos = new ByteArrayOutputStream(); int actread = zis.read(buff); while(actread > 0){ bos.write(buff, 0, actread); actread = zis.read(buff); } addSingleClass(entryname, bos.toByteArray()); } else if(entryname.equals("META-INF/MANIFEST.MF")) { mf = new Manifest(zis); } entry = zis.getNextEntry(); } } catch(IOException e) { //I don't think this can happen, unless perhaps with wrong data... Hmm. e.printStackTrace(); } if(mf != null){ Attributes attr = mf.getMainAttributes(); String val = attr.getValue("Kross-Main"); if(val != null) return val; else return ""; } else return ""; } /** * Adds an extension to the list of known extensions that can be imported. * @param name The name of the previously-defined KrossQExtension class that bridges this extension. * @param p A pointer to the JVMExtension in the C world. * @return An instance of the KrossQExtension, set up with the given pointer. */ public KrossQExtension addExtension(String name, long p) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { //TODO: think about the right exception handling here KrossQExtension ext = (KrossQExtension)newInstance(name, new Long(p)); extensions.put(name, ext); return ext; } /** * Creates a new instance of a given class with the default constructor. */ public Object newInstance(String name) throws ClassNotFoundException, InstantiationException, IllegalAccessException { return loadClass(name).newInstance(); } /** * Creates a new instance of a given class, using the given objects as parameters * to the constructor. */ public Object newInstance(String name, Object[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { Class c = loadClass(name); Class[] sig = new Class[args.length]; for(int i=0;i<args.length;i++) { sig[i] = args[i].getClass(); } Constructor con = c.getConstructor(sig); return con.newInstance(args); } /** * Creates a new instance of a given class, using a single object as parameter to the constructor. */ public Object newInstance(String name, Object arg) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { Object[] args = new Object[1]; args[0] = arg; return newInstance(name, args); } /** * Returns a loaded KrossQExtension to use in scripts. * @param name The name by which a module was registered. * @return The KrossQExtension bridging the given module. */ public static KrossQExtension importModule(String name) { if(kcl == null){ //TODO: either exception or C++ error handling System.out.println("Oops, KCL not initialized yet!"); return null; } if(kcl.isLoadedExtension(name)){ return kcl.getLoadedExtension(name); } else { //TODO: throw exception System.out.println("Module not found: " + name); return null; } } /** * Searches a class by name. * @see URLClassLoader#findClass(String) */ public Class findClass(String name) throws ClassNotFoundException{ if(storedClasses.containsKey(name)){ return (Class)storedClasses.get(name); } return super.findClass(name); } /** * Checks whether data is loadable by this classloader. * @param data The data to be inspected. * @return True if the data is in a known format (class bytecode, JAR), false otherwise. */ public static boolean isClassData(byte[] data){ return getDataType(data) != UNKNOWN_DATA; } /** * Returns the type of data, as determined by magic number. * @param data The data to be inspected. * @return One of UNKNOWN_DATA, CLASS_DATA or JAR_DATA. */ public static int getDataType(byte[] data){ if(data == null || data.length < 4) return UNKNOWN_DATA; //TODO: endianness? int magic = byteArrayToInt(data); if(magic == 0xCAFEBABE) return CLASS_DATA; if(magic == 0x504b0304) //PK\003\004 return JAR_DATA; return UNKNOWN_DATA; } /** * Returns the magic number for some data. * @param data The data to be inspected. * @return An int representing the numeric value of the first four bytes. */ public static int byteArrayToInt(byte[] b) { int value = 0; for (int i = 0; i < 4; i++) { int shift = (4 - 1 - i) * 8; value += (b[i] & 0x000000FF) << shift; } return value; } /** * Checks whether a given name is associated to a module. */ public boolean isLoadedExtension(String name){ return extensions.containsKey(name); } /** * Returns the module with the given name. */ public KrossQExtension getLoadedExtension(String name){ return (KrossQExtension)extensions.get(name); } }
lgpl-2.1
gburlet/tuxguitar
TuxGuitar-android/src/org/herac/tuxguitar/android/browser/model/TGBrowserFactory.java
390
package org.herac.tuxguitar.android.browser.model; public interface TGBrowserFactory { String getName(); String getType(); TGBrowserSettings restoreSettings(String settings); void createSettings(TGBrowserFactorySettingsHandler handler) throws TGBrowserException; void createBrowser(TGBrowserFactoryHandler handler, TGBrowserSettings settings) throws TGBrowserException; }
lgpl-2.1
keredson/DKO
examples/sakila/src/sakila/Example0.java
321
package sakila; import org.kered.dko.Query; import com.mycompany.dko.sakila.Actor; public class Example0 { public static void main(String[] args) { Query<Actor> actors = Actor.ALL.limit(10); for (Actor actor : actors) { System.out.println(actor.getFirstName() +" "+ actor.getLastName()); } } }
lgpl-2.1
comundus/opencms-comundus
src/main/java/org/opencms/db/oracle8/CmsVfsDriver.java
1620
/* * File : $Source: /usr/local/cvs/opencms/src/org/opencms/db/oracle8/CmsVfsDriver.java,v $ * Date : $Date: 2008-02-27 12:05:53 $ * Version: $Revision: 1.3 $ * * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) 2002 - 2008 Alkacon Software GmbH (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software GmbH, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.db.oracle8; /** * Oracle8 implementation of the VFS driver methods.<p> * * @author Michael Moossen * * @version $Revision: 1.3 $ * @since 6.0.0 */ public class CmsVfsDriver extends org.opencms.db.oracle.CmsVfsDriver { // no modifications needed }
lgpl-2.1
James-Whitney/Galaxy-Safe
src/main/java/Galaxy/Safe/Reference.java
1257
package Galaxy.Safe; public class Reference { public static final String MOD_ID = "galaxysafe"; public static final String NAME = "Galaxy's Safe"; public static final String VERSION = "1.0"; public static final String ACCEPTED_VERSIONS = "[1.10.2]"; public static final String CLIENT_PROXY_CLASS = "Galaxy.Safe.proxy.ClientProxy"; public static final String SERVER_PROXY_CLASS = "Galaxy.Safe.proxy.ClientProxy"; /* public static enum SafeItems { SAFE("safe", "ItemSafe"); private String unlocalizedName; private String registryName; SafeItems(String unlocalizedName, String registryName) { this.unlocalizedName = unlocalizedName; this.registryName = registryName; } public String getRegistryName() { return registryName; } public String getUnlocalizedName() { return unlocalizedName; } }*/ public static enum SafeBlocks { SAFE("safe", "BlockSafe"); private String unlocalizedName; private String registryName; SafeBlocks(String unlocalizedName, String registryName) { this.unlocalizedName = unlocalizedName; this.registryName = registryName; } public String getRegistryName() { return registryName; } public String getUnlocalizedName() { return unlocalizedName; } } }
lgpl-2.1
handong106324/sqLogWeb
src/com/jiangge/utils/algorithm/AES.java
4366
package com.jiangge.utils.algorithm; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /** * ¼ÓÃܺͽâÃÜËã·¨ * @author Administrator * */ public class AES { private static final String PASSWORD = "1234567890"; /** * »ñÈ¡½âÃܺóµÄ×Ö·û´® * @param content * @return */ public static String RevertAESCode(String content){ byte[] decryptFrom = parseHexStr2Byte(content); byte[] decryptResult = decrypt(decryptFrom, PASSWORD); String decryptString = new String(decryptResult); return decryptString; } /** * »ñÈ¡½âÃܺóµÄ×Ö·û´® * @param content * @param passcode * @return */ public static String RevertAESCode(String content,String passcode){ byte[] decryptFrom = parseHexStr2Byte(content); byte[] decryptResult = decrypt(decryptFrom, passcode); String decryptString = new String(decryptResult); return decryptString; } /** * »ñÈ¡¼ÓÃܺóµÄ×Ö·û´® * @param content * @return */ public static String GetAESCode(String content){ byte[] encryptResult = encrypt(content, PASSWORD); String encryptResultStr = parseByte2HexStr(encryptResult); return encryptResultStr; } /** * »ñÈ¡¼ÓÃܺóµÄ×Ö·û´® * @param content * @param passcode * @return */ public static String GetAESCode(String content,String passcode){ byte[] encryptResult = encrypt(content, passcode); String encryptResultStr = parseByte2HexStr(encryptResult); return encryptResultStr; } /** * ¼ÓÃÜ * @param content * @param password * @return */ private static byte[] encrypt(String content, String password) { try{ KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat,"AES"); /**´´½¨ÃÜÂëÆ÷**/ Cipher cipher = Cipher.getInstance("AES"); byte[] byteContent = content.getBytes("utf-8"); /**³õʼ»¯ÃÜÂëÆ÷**/ cipher.init(Cipher.ENCRYPT_MODE, key); byte[] result = cipher.doFinal(byteContent); return result; }catch(Exception e) { System.out.println("³ö´íÁË:" + e.getMessage()); } return null; } /** * ½âÃÜ * @param content * @param password * @return */ private static byte[] decrypt(byte[] content, String password) { try{ KeyGenerator kgen = KeyGenerator. getInstance("AES"); kgen.init(128,new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat,"AES"); /**´´½¨ÃÜÂëÆ÷**/ Cipher cipher = Cipher.getInstance("AES"); /**³õʼ»¯ÃÜÂëÆ÷**/ cipher.init(Cipher.DECRYPT_MODE, key); byte[] result = cipher.doFinal(content); return result; }catch(Exception e) { System.out.println("³ö´íÁË:"+ e.getMessage()); } return null; } /** * ½«¶þ½øÖÆ×ª»»³ÉÊ®Áù½øÖÆ * @param buf * @return */ private static String parseByte2HexStr(byte buf[]) { StringBuffer sb = new StringBuffer(); for(int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if(hex.length() == 1) { hex = '0'+ hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } /** * ½«Ê®Áù½øÖÆ×ª»»Îª¶þ½øÖÆ * @param hexStr * @return */ private static byte[] parseHexStr2Byte(String hexStr) { if(hexStr.length() < 1) { return null ; }else{ byte[] result =new byte[hexStr.length() / 2]; for(int i = 0; i < hexStr.length() / 2; i++) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1,i * 2 + 2),16); result[i] = (byte) (high * 16 + low); } return result; } } /** * ¼ÓÃܺͽâÃÜ * @param args */ public static void main(String[] args) { /**Êý¾Ý³õʼ»¯**/ String content ="http://www.baidu.com/"; String password ="1234567890"; /**¼ÓÃÜ**/ System.out.println("¼ÓÃÜǰ£º"+ content); String encryptResultStr = GetAESCode(content,password); System.out.println("¼ÓÃܺó£º" + encryptResultStr); /**½âÃÜ**/ String decryptString = RevertAESCode(encryptResultStr,password); System.out.println("½âÃܺó£º"+new String(decryptString)); } }
lgpl-2.1
keijokapp/digidoc4j
test/org/digidoc4j/testutils/TestHelpers.java
462
package org.digidoc4j.testutils; import java.util.ArrayList; import java.util.List; import org.digidoc4j.exceptions.DigiDoc4JException; public class TestHelpers { public static boolean containsErrorMessage(List<DigiDoc4JException> errors, String message) { List<String> errorMessages = new ArrayList<>(); for (DigiDoc4JException error : errors) { errorMessages.add(error.getMessage()); } return errorMessages.contains(message); } }
lgpl-2.1
agentlab/powerloom-osgi
plugins/edu.isi.powerloom/src/edu/isi/powerloom/logic/ClashJustification.java
4877
// -*- Mode: Java -*- // // ClashJustification.java /* +---------------------------- BEGIN LICENSE BLOCK ---------------------------+ | | | Version: MPL 1.1/GPL 2.0/LGPL 2.1 | | | | The contents of this file are subject to the Mozilla Public License | | Version 1.1 (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.mozilla.org/MPL/ | | | | Software distributed under the License is distributed on an "AS IS" basis, | | WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License | | for the specific language governing rights and limitations under the | | License. | | | | The Original Code is the PowerLoom KR&R System. | | | | The Initial Developer of the Original Code is | | UNIVERSITY OF SOUTHERN CALIFORNIA, INFORMATION SCIENCES INSTITUTE | | 4676 Admiralty Way, Marina Del Rey, California 90292, U.S.A. | | | | Portions created by the Initial Developer are Copyright (C) 1997-2012 | | the Initial Developer. All Rights Reserved. | | | | Contributor(s): | | | | Alternatively, the contents of this file may be used under the terms of | | either the GNU General Public License Version 2 or later (the "GPL"), or | | the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), | | in which case the provisions of the GPL or the LGPL are applicable instead | | of those above. If you wish to allow use of your version of this file only | | under the terms of either the GPL or the LGPL, and not to allow others to | | use your version of this file under the terms of the MPL, indicate your | | decision by deleting the provisions above and replace them with the notice | | and other provisions required by the GPL or the LGPL. If you do not delete | | the provisions above, a recipient may use your version of this file under | | the terms of any one of the MPL, the GPL or the LGPL. | | | +----------------------------- END LICENSE BLOCK ----------------------------+ */ package edu.isi.powerloom.logic; import edu.isi.stella.javalib.Native; import edu.isi.stella.javalib.StellaSpecialVariable; import edu.isi.stella.*; public class ClashJustification extends Justification { /** The inference direction for this inference. */ public Keyword direction; public static ClashJustification newClashJustification() { { ClashJustification self = null; self = new ClashJustification(); self.negativeScore = Stella.NULL_FLOAT; self.positiveScore = Stella.NULL_FLOAT; self.truthValue = null; self.reversePolarityP = false; self.substitution = null; self.patternJustification = null; self.antecedents = Stella.NIL; self.proposition = null; self.inferenceRule = null; self.direction = Logic.KWD_FORWARD; return (self); } } public static Stella_Object accessClashJustificationSlotValue(ClashJustification self, Symbol slotname, Stella_Object value, boolean setvalueP) { if (slotname == Logic.SYM_LOGIC_DIRECTION) { if (setvalueP) { self.direction = ((Keyword)(value)); } else { value = self.direction; } } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + slotname + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } return (value); } public Keyword inferenceDirection() { { ClashJustification self = this; return (self.direction); } } public Surrogate primaryType() { { ClashJustification self = this; return (Logic.SGT_LOGIC_CLASH_JUSTIFICATION); } } }
lgpl-2.1
moise-lang/moise
src/main/java/ora4mas/nopl/tools/os2nopl.java
20664
package ora4mas.nopl.tools; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import moise.common.MoiseElement; import moise.os.Cardinality; import moise.os.CardinalitySet; import moise.os.OS; import moise.os.fs.Goal; import moise.os.fs.Mission; import moise.os.fs.Plan.PlanOpType; import moise.os.fs.Scheme; import moise.os.ns.NS; import moise.os.ns.NS.OpTypes; import moise.os.ns.Norm; import moise.os.ss.Compatibility; import moise.os.ss.Group; import moise.os.ss.Role; import moise.os.ss.RoleRel.RoleRelScope; import moise.os.ss.SS; /** translate an OS to a NP */ public class os2nopl { // constants for properties public static final String PROP_RoleInGroup = "role_in_group"; public static final String PROP_RoleCardinality = "role_cardinality"; public static final String PROP_RoleCompatibility = "role_compatibility"; public static final String PROP_WellFormedResponsible = "well_formed_responsible"; public static final String PROP_SubgroupInGroup = "subgroup_in_group"; public static final String PROP_SubgroupCardinality = "subgroup_cardinality"; public static final String PROP_MissionPermission = "mission_permission"; public static final String PROP_LeaveMission = "mission_left"; public static final String PROP_MissionCardinality = "mission_cardinality"; public static final String PROP_AchNotEnabledGoal = "ach_not_enabled_goal"; public static final String PROP_AchNotCommGoal = "ach_not_committed_goal"; //public static final String PROP_NotCompGoal = "goal_non_compliance"; // properties for groups public static final String[] NOP_GR_PROPS = new String[] { PROP_RoleInGroup, PROP_RoleCardinality, PROP_RoleCompatibility, PROP_WellFormedResponsible, PROP_SubgroupInGroup, PROP_SubgroupCardinality}; // properties for schemes public static final String[] NOP_SCH_PROPS = new String[] { //PROP_NotCompGoal, PROP_LeaveMission, PROP_AchNotEnabledGoal, PROP_AchNotCommGoal, PROP_MissionPermission, PROP_MissionCardinality }; // properties for norms public static final String[] NOP_NS_PROPS = new String[] { }; private static final String NGOAL = "ngoal"; // id of the goal obligations // condition for each property private static final Map<String, String> condCode = new HashMap<String, String>(); static { condCode.put(PROP_RoleInGroup, "play(Agt,R,Gr) & group_id(Gr) & not role_cardinality(R,_,_)"); condCode.put(PROP_RoleCardinality, "group_id(Gr) & role_cardinality(R,_,RMax) & rplayers(R,Gr,RP) & RP > RMax"); condCode.put(PROP_RoleCompatibility, "play(Agt,R1,Gr) & play(Agt,R2,Gr) & group_id(Gr) & R1 < R2 & not fcompatible(R1,R2,gr_inst)"); // note that is have to be play and not fplay condCode.put(PROP_SubgroupInGroup, "group_id(Gr) & subgroup(G,GT,Gr) & not subgroup_cardinality(GT,_,_)"); condCode.put(PROP_SubgroupCardinality, "group_id(Gr) & subgroup_cardinality(SG,_,SGMax) & .count(subgroup(_,SG,Gr),SGP) & SGP > SGMax"); condCode.put(PROP_WellFormedResponsible, "responsible(Gr,S) & not well_formed(Gr)"); // not monitor_scheme(S) & condCode.put(PROP_MissionPermission, "committed(Agt,M,S) & not (mission_role(M,R) & responsible(Gr,S) & fplay(Agt,R,Gr))"); condCode.put(PROP_LeaveMission, "leaved_mission(Agt,M,S) & not mission_accomplished(S,M)"); condCode.put(PROP_MissionCardinality, "scheme_id(S) & mission_cardinality(M,_,MMax) & mplayers(M,S,MP) & MP > MMax"); condCode.put(PROP_AchNotEnabledGoal, "done(S,G,Agt) & mission_goal(M,G) & not mission_accomplished(S,M) & not enabled(S,G)"); condCode.put(PROP_AchNotCommGoal, "done(S,G,Agt) & .findall(M, mission_goal(M,G) & (committed(Agt,M,S) | mission_accomplished(S,M)), [])"); //condCode.put(PROP_NotCompGoal, "obligation(Agt,"+NGOA+"(S,M,G),Obj,TTF) & not Obj & `now` > TTF"); } // arguments that 'explains' the property private static final Map<String, String> argsCode = new HashMap<String, String>(); static { argsCode.put(PROP_RoleInGroup, "Agt,R,Gr"); argsCode.put(PROP_RoleCardinality, "R,Gr,RP,RMax"); argsCode.put(PROP_RoleCompatibility, "R1,R2,Gr"); argsCode.put(PROP_SubgroupInGroup, "G,GT,Gr"); argsCode.put(PROP_SubgroupCardinality, "SG,Gr,SGP,SGMax"); argsCode.put(PROP_WellFormedResponsible, "Gr"); argsCode.put(PROP_MissionPermission, "Agt,M,S"); argsCode.put(PROP_LeaveMission, "Agt,M,S"); argsCode.put(PROP_MissionCardinality, "M,S,MP,MMax"); argsCode.put(PROP_AchNotEnabledGoal, "S,G,Agt"); argsCode.put(PROP_AchNotCommGoal, "S,G,Agt"); //argsCode.put(PROP_NotCompGoal , "obligation(Agt,"+NGOA+"(S,M,G),Obj,TTF)"); } /** transforms an OS into NPL code */ public static String transform(OS os) { StringBuilder np = new StringBuilder(); np.append(header(os)); // main scope np.append("scope organisation("+os.getId()+") {\n\n"); np.append( roleHierarchy( os.getSS()) + "\n\n"); // groups np.append( transform( os.getSS().getRootGrSpec() )+ "\n"); // schemes for (Scheme sch: os.getFS().getSchemes()) np.append( transform( sch, true) + "\n"); np.append("} // end of organisation "+os.getId()+"\n"); return np.toString(); } /** transforms a Group Spec into NPL code */ public static String transform(Group gr) { if (gr == null) return ""; StringBuilder np = new StringBuilder(); np.append("scope group("+gr.getId()+") {\n\n"); np.append(" // ** Facts from OS\n"); CardinalitySet<Role> roles = gr.getRoles(); for (Role r: roles) { Cardinality c = roles.getCardinality(r); np.append(" role_cardinality("+r.getId()+","+c.getMin()+","+c.getMax()+").\n"); } for (Group sg: gr.getSubGroups()) { Cardinality c = gr.getSubGroupCardinality(sg); np.append(" subgroup_cardinality("+sg.getId()+","+c.getMin()+","+c.getMax()+").\n"); } np.append("\n"); for (Compatibility c: gr.getUpCompatibilities()) { String scope = "gr_inst"; if (c.getScope() == RoleRelScope.InterGroup) scope = "org"; np.append(" compatible("+c.getSource()+","+c.getTarget()+","+scope+").\n"); if (c.isBiDir()) np.append(" compatible("+c.getTarget()+","+c.getSource()+","+scope+").\n"); } np.append("\n // ** Rules\n"); np.append(" rplayers(R,G,V) :- .count(play(_,R,G),V).\n"); np.append(" well_formed(G)"); String sep = " :-\n"; for (Role r: roles) { Cardinality c = roles.getCardinality(r); String var = "V"+r.getId(); np.append(sep+" rplayers("+r.getId()+",G,"+var+") & "+var+" >= "+c.getMin()+" & "+var+" <= "+c.getMax()); sep = " &\n"; } for (Group sg: gr.getSubGroups()) { Cardinality c = gr.getSubGroupCardinality(sg); String var = "S"+sg.getId(); np.append(sep+" .count(subgroup(_,"+sg.getId()+",G),"+var+") & "+var+" >= "+c.getMin()+" & "+var+" <= "+c.getMax()); //+" & subgroup_well_formed("+sg.getId()+")"); sep = " &\n"; } np.append(sep+" .findall(GInst, subgroup(GInst,_,G), ListSubgroups) & all_subgroups_well_formed(ListSubgroups).\n"); np.append(" all_subgroups_well_formed([]).\n"); np.append(" all_subgroups_well_formed([H|T]) :- subgroup_well_formed(H) & all_subgroups_well_formed(T).\n"); np.append("\n // ** Properties check \n"); generateProperties(NOP_GR_PROPS, gr.getSS().getOS().getNS(), np); np.append("} // end of group "+gr.getId()+"\n"); for (Group sgr: gr.getSubGroups()) { np.append("\n\n// ** Group "+sgr.getId()+", subgroup of "+gr.getId()+"\n"); np.append( transform(sgr) + "\n"); } return np.toString(); } public static String transform(Role r) { StringBuilder np = new StringBuilder(); for (Role sr: r.getSubRoles()) { np.append(" subrole("+sr.getId()+","+r.getId()+").\n"); np.append( transform(sr) ); } return np.toString(); } private static String roleHierarchy(SS ss) { StringBuilder np = new StringBuilder("\n // Role hierarchy\n"); np.append( transform( ss.getRoleDef("soc")) + "\n"); np.append( " // f* rules implement the role hierarchy transitivity\n"); np.append( " // t* rules implement the transitivity of some relations\n\n"); np.append( " // fplay(A,R,G) is true if A play R in G or if A play a subrole of R in G\n"); np.append( " fplay(A,R,G) :- play(A,R,G).\n"); np.append( " fplay(A,R,G) :- subrole(R1,R) & fplay(A,R1,G).\n\n"); np.append( " // fcompatible(R1,R2,S) is true if R1 or its sub-roles are compatible with R2 in scope S\n"); np.append( " fcompatible(R1,R2,S) :- tsubrole(R1,R2).\n"); np.append( " fcompatible(R1,R2,S) :- tsubrole(R1,R1a) & tsubrole(R2,R2a) & compatible(R1a,R2a,S).\n"); np.append( " fcompatible(R1,R2,S) :- tcompatible(R1,R2,S,[R1,R2]).\n"); // member is there to avoid infinity loops np.append( " tcompatible(R1,R2,S,Path) :- compatible(R1,R3,S) & not .member(R3,Path) & tcompatible(R3,R2,S,[R3|Path]).\n"); np.append( " tsubrole(R,R).\n"); np.append( " tsubrole(R1,R2) :- subrole(R1,R2).\n"); np.append( " tsubrole(R1,R2) :- subrole(R1,R3) & tsubrole(R3,R2).\n"); return np.toString(); } /** transforms a Scheme Spec into NPL code */ public static String transform(Scheme sch, boolean isSB) { StringBuilder np = new StringBuilder(); np.append("scope scheme("+sch.getId()+") {\n\n"); np.append(" // ** Facts from OS\n\n"); if (!isSB) { np.append( roleHierarchy(sch.getFS().getOS().getSS())); } np.append(" // mission_cardinality(mission id, min, max)\n"); for (Mission m: sch.getMissions()) { Cardinality c = sch.getMissionCardinality(m); np.append(" mission_cardinality("+m.getId()+","+c.getMin()+","+c.getMax()+").\n"); } np.append("\n // mission_role(mission id, role id)\n"); Set<String> generated = new HashSet<String>(); for (Norm dr: sch.getFS().getOS().getNS().getNorms()) { if (sch.getMissions().contains(dr.getMission())) { String rel = " mission_role("+dr.getMission().getId()+","+dr.getRole().getId()+").\n"; if (!generated.contains(rel)) { generated.add(rel); np.append(rel); } } } np.append("\n // mission_goal(mission id, goal id)\n"); for (Mission m: sch.getMissions()) { for (Goal g: m.getGoals()) { np.append(" mission_goal("+m.getId()+","+g.getId()+").\n"); } } np.append("\n // goal(missions, goal id, dependence (on goal statisfaction), type, #ags to satisfy, ttf)\n"); StringBuilder superGoal = new StringBuilder(); for (Goal g: sch.getGoals()) { try { superGoal.append(" super_goal("+g.getInPlan().getTargetGoal().getId()+", "+g.getId()+").\n"); } catch (Exception e) {} StringBuilder smis = new StringBuilder("["); String com = ""; for (String m: sch.getGoalMissionsId(g)) { smis.append(com+m); com = ","; } smis.append("]"); String ttf = g.getTTF(); if (ttf.length() == 0) ttf = "1 year"; List<Goal> precond = g.getPreConditionGoals(); String prec = precond.toString(); if (g.hasPlan() && g.getPlan().getOp() == PlanOpType.choice) prec = "dep(or,"+prec+")"; else prec = "dep(and,"+prec+")"; String nag = g.getMinAgToSatisfy() == -1 ? "all" : ""+g.getMinAgToSatisfy(); np.append(" goal("+smis+","+g.getId()+","+prec+","+g.getType()+","+nag+",`"+ttf+"`)"); if (g.getLocation() != null && g.getLocation().length() > 0) { np.append("[location(\""+g.getLocation()+"\")]"); //} else { // np.append("[location(\"anywhere\")]"); } np.append(".\n"); } np.append(superGoal.toString()); np.append("\n // ** Rules\n"); np.append(" mplayers(M,S,V) :- .count(committed(_,M,S),V).\n"); np.append(" well_formed(S)"); String sep = " :- \n"; for (Mission m: sch.getMissions()) { Cardinality c = sch.getMissionCardinality(m); String var = "V"+m.getId(); np.append(sep+" (mission_accomplished(S,"+m.getId()+") | not mission_accomplished(S,"+m.getId()+") & mplayers("+m.getId()+",S,"+var+") & "+var+" >= "+c.getMin()+" & "+var+" <= "+c.getMax()+")"); sep = " &\n"; } np.append(".\n"); np.append(" is_finished(S) :- satisfied(S,"+sch.getRoot().getId()+").\n"); np.append(" mission_accomplished(S,M) :- .findall(Goal, mission_goal(M,Goal), MissionGoals) & all_satisfied(S,MissionGoals).\n"); np.append(" all_satisfied(_,[]).\n"); np.append(" all_satisfied(S,[G|T]) :- satisfied(S,G) & all_satisfied(S,T).\n"); np.append(" any_satisfied(S,[G|_]) :- satisfied(S,G).\n"); np.append(" any_satisfied(S,[G|T]) :- not satisfied(S,G) & any_satisfied(S,T).\n\n"); np.append(" // enabled goals (i.e. dependence between goals)\n"); np.append(" enabled(S,G) :- goal(_, G, dep(or,PCG), _, NP, _) & NP \\== 0 & any_satisfied(S,PCG).\n"); np.append(" enabled(S,G) :- goal(_, G, dep(and,PCG), _, NP, _) & NP \\== 0 & all_satisfied(S,PCG).\n"); np.append(" super_satisfied(S,G) :- super_goal(SG,G) & satisfied(S,SG).\n"); np.append("\n // ** Norms\n"); np.append("\n // --- Properties check ---\n"); if (isSB) { generateProperties(NOP_SCH_PROPS, sch.getFS().getOS().getNS(), np); } else { generateProperties(NOP_NS_PROPS, sch.getFS().getOS().getNS(), np); } if (!isSB) { np.append("\n // --- commitments ---\n"); for (Norm nrm: sch.getFS().getOS().getNS().getNorms()) { if (sch.getMissions().contains(nrm.getMission())) { np.append(generateNormEntry( nrm, sch.getMissionCardinality(nrm.getMission())) ); } } } if (isSB) { np.append("\n // agents are obliged to fulfill their enabled goals\n"); np.append(" norm "+NGOAL+": \n"); np.append(" committed(A,M,S) & mission_goal(M,G) & \n"); //np.append(" enabled(S,G) & \n"); // tested by the maint. cond. of the norm np.append(" ((goal(_,G,_,achievement,_,D) & What = satisfied(S,G)) | \n"); np.append(" (goal(_,G,_,performance,_,D) & What = done(S,G,A))) &\n"); // TODO: implement location as annot for What. create an internal action to add this annot? //np.append(" ((goal(_,G,_,_,_,_)[location(L)] & WhatL = What[location(L)]) | (not goal(_,G,_,_,_,_)[location(L)] & WhatL = What)) &\n"); np.append(" well_formed(S) & \n"); np.append(" not satisfied(S,G) & \n"); np.append(" not super_satisfied(S,G)\n"); np.append(" -> obligation(A,enabled(S,G),What,`now` + D).\n"); // TODO: maintenance goals //np.append(" // maintenance goals\n"); } np.append("} // end of scheme "+sch.getId()+"\n"); return np.toString(); } private static void generateProperties(String[] props, NS ns, StringBuilder np) { String defaultM = ns.getStrProperty("default_management", "fail"); for (String prop: props) { // check if some norm exist for the propriety String conf = ns.getStrProperty(prop, defaultM); if (conf.equals("ignore")) continue; np.append(" norm "+prop+": "); String space = " "; if (conf.equals("fail")) { np.append(" \n"); } else { np.append("true\n"); np.append(" -> prohibition(Agt,true,\n"); space += " "; } String sep = ""; for (String t: condCode.get(prop).split("&")) { np.append(sep+space+t.trim()); sep = " &\n"; } if (conf.equals("fail")) { np.append("\n -> fail("+prop+"("+argsCode.get(prop)+")).\n"); } else { np.append(",\n"+space+"`never`).\n"); } } } public static String generateNormEntry(Norm nrm, Cardinality card) { StringBuilder np = new StringBuilder(); String id = nrm.getId(); String m = nrm.getMission().getId(); String tc = nrm.getTimeConstraint() == null ? "+`1 year`" : "+`"+nrm.getTimeConstraint().getTC()+"`"; String comment = ""; String args = ""; String condition = nrm.getCondition(); // macro condition if (condition.startsWith("#")) { condition = condition.substring(1); comment = " // "+condition; args = "("+argsCode.get(condition)+")"; condition = condCode.get(condition) + " &\n "; } else if (condition.equals("true")) { condition = ""; } else { condition = condition + " &\n "; } String extraCond = "not mission_accomplished(S,"+m+") // if all mission's goals are satisfied, the agent is not obliged to commit to the mission"; condition = condition + "scheme_id(S) & responsible(Gr,S)"; String mplayers = "mplayers("+m+",S,V) & mission_cardinality("+m+",MMinCard,MMaxCard) & "; String fplay = "fplay(A,"+nrm.getRole().getId()+",Gr)"; String cons = args+",committed(A,"+m+",S), `now`"+tc+").\n"; if (card.getMin() > 0 && nrm.getType() == OpTypes.obligation) { // the obligation np.append(" norm "+id+": "+comment+"\n"); np.append(" "+condition); np.append(" &\n "+mplayers+"V < MMinCard"); np.append(" &\n "+fplay); np.append(" &\n "+extraCond); np.append("\n -> obligation("+"A,not well_formed(S)"+cons); id = "p"+id; } if (card.getMin() < card.getMax() || nrm.getType() == OpTypes.permission) { // the permission np.append(" norm "+id+": "+comment+"\n"); np.append(" "+condition); np.append(" &\n "+mplayers+"V < MMaxCard"); if (nrm.getType() == OpTypes.obligation) // an obl was created np.append(" & V >= MMinCard"); np.append(" &\n fplay(A,"+nrm.getRole().getId()+",Gr)"); np.append(" &\n "+extraCond); np.append("\n -> permission("+"A,responsible(Gr,S)"+cons); } return np.toString(); } public static String header(MoiseElement ele) { StringBuilder np = new StringBuilder(); np.append("/*\n"); np.append(" This program was automatically generated from\n"); np.append(" the organisation specification '"+ele.getId()+"'\n on "+new SimpleDateFormat("MMMM dd, yyyy - HH:mm:ss").format(new Date())+"\n\n"); np.append(" This is a MOISE tool, see more at http://moise.sourceforge.net\n\n"); np.append("*/\n\n"); return np.toString(); } }
lgpl-3.0
NeuroML/org.neuroml.export
src/main/java/org/lemsml/export/vhdl/edlems/EDDisplay.java
221
package org.lemsml.export.vhdl.edlems; import java.util.ArrayList; public class EDDisplay { public String name; public String timeScale; public String xmin; public String xmax; public ArrayList<EDLine> lines; }
lgpl-3.0
Semantive/jts
src/main/java/com/vividsolutions/jts/operation/buffer/OffsetCurveBuilder.java
13274
/* * The JTS Topology Suite is a collection of Java classes that * implement the fundamental operations required to validate a given * geo-spatial data set to a known topological specification. * * Copyright (C) 2001 Vivid Solutions * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ package com.vividsolutions.jts.operation.buffer; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.CoordinateArrays; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.PrecisionModel; import com.vividsolutions.jts.geomgraph.Position; /** * Computes the raw offset curve for a * single {@link Geometry} component (ring, line or point). * A raw offset curve line is not noded - * it may contain self-intersections (and usually will). * The final buffer polygon is computed by forming a topological graph * of all the noded raw curves and tracing outside contours. * The points in the raw curve are rounded * to a given {@link PrecisionModel}. * * @version 1.7 */ public class OffsetCurveBuilder { private double distance = 0.0; private PrecisionModel precisionModel; private BufferParameters bufParams; public OffsetCurveBuilder( PrecisionModel precisionModel, BufferParameters bufParams ) { this.precisionModel = precisionModel; this.bufParams = bufParams; } /** * Gets the buffer parameters being used to generate the curve. * * @return the buffer parameters being used */ public BufferParameters getBufferParameters() { return bufParams; } /** * This method handles single points as well as LineStrings. * LineStrings are assumed <b>not</b> to be closed (the function will not * fail for closed lines, but will generate superfluous line caps). * * @param inputPts the vertices of the line to offset * @param distance the offset distance * @return a Coordinate array representing the curve * or null if the curve is empty */ public Coordinate[] getLineCurve(Coordinate[] inputPts, double distance) { this.distance = distance; // a zero or negative width buffer of a line/point is empty if (distance < 0.0 && !bufParams.isSingleSided()) return null; if (distance == 0.0) return null; double posDistance = Math.abs(distance); OffsetSegmentGenerator segGen = getSegGen(posDistance); if (inputPts.length <= 1) { computePointCurve(inputPts[0], segGen); } else { if (bufParams.isSingleSided()) { boolean isRightSide = distance < 0.0; computeSingleSidedBufferCurve(inputPts, isRightSide, segGen); } else computeLineBufferCurve(inputPts, segGen); } Coordinate[] lineCoord = segGen.getCoordinates(); return lineCoord; } /** * This method handles the degenerate cases of single points and lines, * as well as rings. * * @return a Coordinate array representing the curve * or null if the curve is empty */ public Coordinate[] getRingCurve(Coordinate[] inputPts, int side, double distance) { this.distance = distance; if (inputPts.length <= 2) return getLineCurve(inputPts, distance); // optimize creating ring for for zero distance if (distance == 0.0) { return copyCoordinates(inputPts); } OffsetSegmentGenerator segGen = getSegGen(distance); computeRingBufferCurve(inputPts, side, segGen); return segGen.getCoordinates(); } public Coordinate[] getOffsetCurve(Coordinate[] inputPts, double distance) { this.distance = distance; // a zero width offset curve is empty if (distance == 0.0) return null; boolean isRightSide = distance < 0.0; double posDistance = Math.abs(distance); OffsetSegmentGenerator segGen = getSegGen(posDistance); if (inputPts.length <= 1) { computePointCurve(inputPts[0], segGen); } else { computeOffsetCurve(inputPts, isRightSide, segGen); } Coordinate[] curvePts = segGen.getCoordinates(); // for right side line is traversed in reverse direction, so have to reverse generated line if (isRightSide) CoordinateArrays.reverse(curvePts); return curvePts; } private static Coordinate[] copyCoordinates(Coordinate[] pts) { Coordinate[] copy = new Coordinate[pts.length]; for (int i = 0; i < copy.length; i++) { copy[i] = new Coordinate(pts[i]); } return copy; } private OffsetSegmentGenerator getSegGen(double distance) { return new OffsetSegmentGenerator(precisionModel, bufParams, distance); } /** * Use a value which results in a potential distance error which is * significantly less than the error due to * the quadrant segment discretization. * For QS = 8 a value of 100 is reasonable. * This should produce a maximum of 1% distance error. */ private static final double SIMPLIFY_FACTOR = 100.0; /** * Computes the distance tolerance to use during input * line simplification. * * @param distance the buffer distance * @return the simplification tolerance */ private static double simplifyTolerance(double bufDistance) { return bufDistance / SIMPLIFY_FACTOR; } private void computePointCurve(Coordinate pt, OffsetSegmentGenerator segGen) { switch (bufParams.getEndCapStyle()) { case BufferParameters.CAP_ROUND: segGen.createCircle(pt); break; case BufferParameters.CAP_SQUARE: segGen.createSquare(pt); break; // otherwise curve is empty (e.g. for a butt cap); } } private void computeLineBufferCurve(Coordinate[] inputPts, OffsetSegmentGenerator segGen) { double distTol = simplifyTolerance(distance); //--------- compute points for left side of line // Simplify the appropriate side of the line before generating Coordinate[] simp1 = BufferInputLineSimplifier.simplify(inputPts, distTol); // MD - used for testing only (to eliminate simplification) // Coordinate[] simp1 = inputPts; int n1 = simp1.length - 1; segGen.initSideSegments(simp1[0], simp1[1], Position.LEFT); for (int i = 2; i <= n1; i++) { segGen.addNextSegment(simp1[i], true); } segGen.addLastSegment(); // add line cap for end of line segGen.addLineEndCap(simp1[n1 - 1], simp1[n1]); //---------- compute points for right side of line // Simplify the appropriate side of the line before generating Coordinate[] simp2 = BufferInputLineSimplifier.simplify(inputPts, -distTol); // MD - used for testing only (to eliminate simplification) // Coordinate[] simp2 = inputPts; int n2 = simp2.length - 1; // since we are traversing line in opposite order, offset position is still LEFT segGen.initSideSegments(simp2[n2], simp2[n2 - 1], Position.LEFT); for (int i = n2 - 2; i >= 0; i--) { segGen.addNextSegment(simp2[i], true); } segGen.addLastSegment(); // add line cap for start of line segGen.addLineEndCap(simp2[1], simp2[0]); segGen.closeRing(); } /* private void OLDcomputeLineBufferCurve(Coordinate[] inputPts) { int n = inputPts.length - 1; // compute points for left side of line initSideSegments(inputPts[0], inputPts[1], Position.LEFT); for (int i = 2; i <= n; i++) { addNextSegment(inputPts[i], true); } addLastSegment(); // add line cap for end of line addLineEndCap(inputPts[n - 1], inputPts[n]); // compute points for right side of line initSideSegments(inputPts[n], inputPts[n - 1], Position.LEFT); for (int i = n - 2; i >= 0; i--) { addNextSegment(inputPts[i], true); } addLastSegment(); // add line cap for start of line addLineEndCap(inputPts[1], inputPts[0]); vertexList.closeRing(); } */ private void computeSingleSidedBufferCurve(Coordinate[] inputPts, boolean isRightSide, OffsetSegmentGenerator segGen) { double distTol = simplifyTolerance(distance); if (isRightSide) { // add original line segGen.addSegments(inputPts, true); //---------- compute points for right side of line // Simplify the appropriate side of the line before generating Coordinate[] simp2 = BufferInputLineSimplifier.simplify(inputPts, -distTol); // MD - used for testing only (to eliminate simplification) // Coordinate[] simp2 = inputPts; int n2 = simp2.length - 1; // since we are traversing line in opposite order, offset position is still LEFT segGen.initSideSegments(simp2[n2], simp2[n2 - 1], Position.LEFT); segGen.addFirstSegment(); for (int i = n2 - 2; i >= 0; i--) { segGen.addNextSegment(simp2[i], true); } } else { // add original line segGen.addSegments(inputPts, false); //--------- compute points for left side of line // Simplify the appropriate side of the line before generating Coordinate[] simp1 = BufferInputLineSimplifier.simplify(inputPts, distTol); // MD - used for testing only (to eliminate simplification) // Coordinate[] simp1 = inputPts; int n1 = simp1.length - 1; segGen.initSideSegments(simp1[0], simp1[1], Position.LEFT); segGen.addFirstSegment(); for (int i = 2; i <= n1; i++) { segGen.addNextSegment(simp1[i], true); } } segGen.addLastSegment(); segGen.closeRing(); } private void computeOffsetCurve(Coordinate[] inputPts, boolean isRightSide, OffsetSegmentGenerator segGen) { double distTol = simplifyTolerance(distance); if (isRightSide) { //---------- compute points for right side of line // Simplify the appropriate side of the line before generating Coordinate[] simp2 = BufferInputLineSimplifier.simplify(inputPts, -distTol); // MD - used for testing only (to eliminate simplification) // Coordinate[] simp2 = inputPts; int n2 = simp2.length - 1; // since we are traversing line in opposite order, offset position is still LEFT segGen.initSideSegments(simp2[n2], simp2[n2 - 1], Position.LEFT); segGen.addFirstSegment(); for (int i = n2 - 2; i >= 0; i--) { segGen.addNextSegment(simp2[i], true); } } else { //--------- compute points for left side of line // Simplify the appropriate side of the line before generating Coordinate[] simp1 = BufferInputLineSimplifier.simplify(inputPts, distTol); // MD - used for testing only (to eliminate simplification) // Coordinate[] simp1 = inputPts; int n1 = simp1.length - 1; segGen.initSideSegments(simp1[0], simp1[1], Position.LEFT); segGen.addFirstSegment(); for (int i = 2; i <= n1; i++) { segGen.addNextSegment(simp1[i], true); } } segGen.addLastSegment(); } private void computeRingBufferCurve(Coordinate[] inputPts, int side, OffsetSegmentGenerator segGen) { // simplify input line to improve performance double distTol = simplifyTolerance(distance); // ensure that correct side is simplified if (side == Position.RIGHT) distTol = -distTol; Coordinate[] simp = BufferInputLineSimplifier.simplify(inputPts, distTol); // Coordinate[] simp = inputPts; int n = simp.length - 1; segGen.initSideSegments(simp[n - 1], simp[0], side); for (int i = 1; i <= n; i++) { boolean addStartPoint = i != 1; segGen.addNextSegment(simp[i], addStartPoint); } segGen.closeRing(); } }
lgpl-3.0
SirmaITT/conservation-space-1.7.0
docker/sirma-platform/platform/seip-parent/platform/commons/commons-jms/src/test/java/com/sirmaenterprise/sep/jms/impl/sender/MessageSenderProducerTest.java
5680
package com.sirmaenterprise.sep.jms.impl.sender; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anySet; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.argThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Collections; import java.util.Set; import javax.enterprise.inject.spi.Annotated; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.inject.spi.InjectionPoint; import javax.jms.CompletionListener; import javax.jms.DeliveryMode; import javax.jms.JMSContext; import javax.jms.JMSException; import javax.jms.Message; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import com.sirma.itt.seip.testutil.CustomMatcher; import com.sirma.itt.seip.testutil.mocks.InstanceProxyMock; import com.sirmaenterprise.sep.jms.annotations.JmsSender; import com.sirmaenterprise.sep.jms.api.MessageSender; import com.sirmaenterprise.sep.jms.api.SendOptions; import com.sirmaenterprise.sep.jms.api.SenderService; import com.sirmaenterprise.sep.jms.convert.MessageWriter; import com.sirmaenterprise.sep.jms.convert.MessageWriters; /** * Test for {@link MessageSenderProducer} * * @author <a href="mailto:borislav.bonev@sirma.bg">Borislav Bonev</a> * @since 23/05/2017 */ public class MessageSenderProducerTest { @InjectMocks private MessageSenderProducer producer; @Mock private SenderService senderService; @Spy private InstanceProxyMock<SenderService> senderServiceInstance = new InstanceProxyMock<>(); @Mock private MessageSender messageSender; @Mock private BeanManager beanManager; @Mock private InjectionPoint point; @Mock private Annotated annotated; @Mock private Bean<?> bean; @Spy private MessageWriters messageWriters; @JmsSender(destination = "destinationQueue", writer = CustomWriter.class, async = CustomListener.class, replyTo = "replyQueue", timeToLive = 1000, jmsType = "testMessage", priority = 8, deliveryDelay = 2000, persistent = false) MessageSender sender; @JmsSender(destination = "destinationQueue") MessageSender defaultSender; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); senderServiceInstance.set(senderService); when(senderService.createSender(anyString(), any(SendOptions.class))).thenReturn(messageSender); when(point.getAnnotated()).thenReturn(annotated); when(beanManager.getBeans(any(), any())).thenReturn(Collections.singleton(bean)); when(beanManager.resolve(anySet())).then(a -> a.getArgumentAt(0, Set.class).iterator().next()); when(beanManager.getReference(any(Bean.class), eq(CustomWriter.class), any())).thenReturn(new CustomWriter()); when(beanManager.getReference(any(Bean.class), eq(CustomListener.class), any())).thenReturn( new CustomListener()); } @Test public void produceWithEverythingSet() throws Exception { when(annotated.getAnnotation(JmsSender.class)).then(a -> MessageSenderProducerTest.class.getDeclaredField ("sender").getAnnotation(JmsSender.class)); when(messageSender.isActive()).thenReturn(Boolean.TRUE); MessageSender produce = producer.produce(point, beanManager); assertNotNull(produce); assertTrue(produce.isActive()); verify(senderService).createSender(eq("destinationQueue"), argThat(CustomMatcher.of((SendOptions options) -> { assertEquals("replyQueue", options.getReplyTo()); assertEquals(1000, options.getTimeToLive()); assertEquals("testMessage", options.getJmsType()); assertEquals(8, options.getPriority()); assertEquals(2000, options.getDeliveryDelay()); assertEquals(DeliveryMode.NON_PERSISTENT, options.getDeliveryMode()); assertTrue(options.getWriter() instanceof CustomWriter); assertTrue(options.getCompletionListener() instanceof CustomListener); }))); } @Test public void produceUsingDefault() throws Exception { when(annotated.getAnnotation(JmsSender.class)).then(a -> MessageSenderProducerTest.class.getDeclaredField ("defaultSender").getAnnotation(JmsSender.class)); when(messageSender.isActive()).thenReturn(Boolean.TRUE); MessageSender produce = producer.produce(point, beanManager); assertNotNull(produce); assertTrue(produce.isActive()); verify(senderService).createSender(eq("destinationQueue"), argThat(CustomMatcher.of((SendOptions options) -> { assertNull(options.getReplyTo()); assertEquals(Message.DEFAULT_TIME_TO_LIVE, options.getTimeToLive()); assertNull(options.getJmsType()); assertEquals(Message.DEFAULT_PRIORITY, options.getPriority()); assertEquals(Message.DEFAULT_DELIVERY_DELAY, options.getDeliveryDelay()); assertEquals(Message.DEFAULT_DELIVERY_MODE, options.getDeliveryMode()); assertNull(options.getWriter()); assertNull(options.getCompletionListener()); }))); } private static class CustomWriter implements MessageWriter<Object, Message> { @Override public Message write(Object data, JMSContext context) throws JMSException { return null; } } private static class CustomListener implements CompletionListener { @Override public void onCompletion(Message message) { } @Override public void onException(Message message, Exception exception) { } } }
lgpl-3.0
premium-minds/billy
billy-france/src/test/java/com/premiumminds/billy/france/test/fixtures/MockFRInvoiceEntity.java
2373
/* * Copyright (C) 2017 Premium Minds. * * This file is part of billy france (FR Pack). * * billy france (FR Pack) is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * billy france (FR Pack) is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with billy france (FR Pack). If not, see <http://www.gnu.org/licenses/>. */ package com.premiumminds.billy.france.test.fixtures; import java.util.ArrayList; import java.util.List; import com.premiumminds.billy.core.test.fixtures.MockGenericInvoiceEntity; import com.premiumminds.billy.france.persistence.entities.FRInvoiceEntity; import com.premiumminds.billy.france.services.entities.FRInvoiceEntry; import com.premiumminds.billy.france.services.entities.FRPayment; public class MockFRInvoiceEntity extends MockGenericInvoiceEntity implements FRInvoiceEntity { private static final long serialVersionUID = 1L; protected boolean cancelled; protected boolean billed; protected String eacCode; protected List<FRPayment> payments; public MockFRInvoiceEntity() { this.payments = new ArrayList<>(); } @Override public void setCancelled(boolean cancelled) { this.cancelled = cancelled; } @Override public void setBilled(boolean billed) { this.billed = billed; } @Override public boolean isCancelled() { return this.cancelled; } @Override public boolean isBilled() { return this.billed; } @SuppressWarnings("unchecked") @Override public List<FRInvoiceEntry> getEntries() { return (List<FRInvoiceEntry>) (List<?>) super.getEntries(); } @Override public void setEACCode(String eacCode) { this.eacCode = eacCode; } @Override public String getEACCode() { return this.eacCode; } @Override public List<FRPayment> getPayments() { return this.payments; } }
lgpl-3.0
Albloutant/Galacticraft
common/micdoodle8/mods/galacticraft/core/tick/GCCoreTickHandlerClient.java
18304
package micdoodle8.mods.galacticraft.core.tick; import java.util.EnumSet; import java.util.List; import micdoodle8.mods.galacticraft.api.block.IDetectableResource; import micdoodle8.mods.galacticraft.api.prefab.entity.EntityAutoRocket; import micdoodle8.mods.galacticraft.api.prefab.entity.EntitySpaceshipBase; import micdoodle8.mods.galacticraft.api.prefab.entity.EntitySpaceshipBase.EnumLaunchPhase; import micdoodle8.mods.galacticraft.api.vector.Vector3; import micdoodle8.mods.galacticraft.api.world.IGalacticraftWorldProvider; import micdoodle8.mods.galacticraft.core.GCCoreConfigManager; import micdoodle8.mods.galacticraft.core.GCCoreThreadRequirementMissing; import micdoodle8.mods.galacticraft.core.GalacticraftCore; import micdoodle8.mods.galacticraft.core.client.ClientProxyCore; import micdoodle8.mods.galacticraft.core.client.GCCoreCloudRenderer; import micdoodle8.mods.galacticraft.core.client.GCCoreSkyProviderOrbit; import micdoodle8.mods.galacticraft.core.client.GCCoreSkyProviderOverworld; import micdoodle8.mods.galacticraft.core.client.gui.GCCoreGuiChoosePlanet; import micdoodle8.mods.galacticraft.core.client.gui.GCCoreOverlayCountdown; import micdoodle8.mods.galacticraft.core.client.gui.GCCoreOverlayDockingRocket; import micdoodle8.mods.galacticraft.core.client.gui.GCCoreOverlayLander; import micdoodle8.mods.galacticraft.core.client.gui.GCCoreOverlayOxygenTankIndicator; import micdoodle8.mods.galacticraft.core.client.gui.GCCoreOverlayOxygenWarning; import micdoodle8.mods.galacticraft.core.client.gui.GCCoreOverlaySpaceship; import micdoodle8.mods.galacticraft.core.client.sounds.GCCoreSoundUpdaterSpaceship; import micdoodle8.mods.galacticraft.core.dimension.GCCoreWorldProviderSpaceStation; import micdoodle8.mods.galacticraft.core.entities.GCCoreEntityLander; import micdoodle8.mods.galacticraft.core.entities.GCCoreEntityRocketT1; import micdoodle8.mods.galacticraft.core.entities.player.GCCorePlayerSP; import micdoodle8.mods.galacticraft.core.items.GCCoreItemSensorGlasses; import micdoodle8.mods.galacticraft.core.network.GCCorePacketHandlerServer.EnumPacketServer; import micdoodle8.mods.galacticraft.core.util.GCCoreUtil; import micdoodle8.mods.galacticraft.core.util.OxygenUtil; import micdoodle8.mods.galacticraft.core.util.PacketUtil; import micdoodle8.mods.galacticraft.core.util.PlayerUtil; import micdoodle8.mods.galacticraft.core.wrappers.BlockMetaList; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityClientPlayerMP; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.gui.inventory.GuiInventory; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.client.renderer.EntityRenderer; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.minecraft.world.WorldProviderSurface; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.GL11; import tconstruct.client.tabs.TabRegistry; import com.google.common.collect.Lists; import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.ITickHandler; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.ObfuscationReflectionHelper; import cpw.mods.fml.common.TickType; import cpw.mods.fml.common.network.PacketDispatcher; import cpw.mods.fml.relauncher.Side; /** * GCCoreTickHandlerClient.java * * This file is part of the Galacticraft project * * @author micdoodle8 * @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html) * */ public class GCCoreTickHandlerClient implements ITickHandler { public static int airRemaining; public static int airRemaining2; public static boolean checkedVersion = true; private static boolean lastInvKeyPressed; private static long tickCount; public static boolean addTabsNextTick = false; private static GCCoreThreadRequirementMissing missingRequirementThread; static { for (final String s : GCCoreConfigManager.detectableIDs) { final String[] split = s.split(":"); int blockID = Integer.parseInt(split[0]); List<Integer> metaList = Lists.newArrayList(); metaList.add(Integer.parseInt(split[1])); for (BlockMetaList blockMetaList : ClientProxyCore.detectableBlocks) { if (blockMetaList.getBlockID() == blockID) { metaList.addAll(blockMetaList.getMetaList()); break; } } if (!metaList.contains(0)) { metaList.add(0); } ClientProxyCore.detectableBlocks.add(new BlockMetaList(blockID, metaList)); } } @Override public void tickStart(EnumSet<TickType> type, Object... tickData) { final Minecraft minecraft = FMLClientHandler.instance().getClient(); final WorldClient world = minecraft.theWorld; final EntityClientPlayerMP player = minecraft.thePlayer; if (type.equals(EnumSet.of(TickType.CLIENT))) { if (GCCoreTickHandlerClient.tickCount >= Long.MAX_VALUE) { GCCoreTickHandlerClient.tickCount = 0; } GCCoreTickHandlerClient.tickCount++; if (GCCoreTickHandlerClient.tickCount % 20 == 0) { if (player != null && player.inventory.armorItemInSlot(3) != null && player.inventory.armorItemInSlot(3).getItem() instanceof GCCoreItemSensorGlasses) { ClientProxyCore.valueableBlocks.clear(); for (int i = -4; i < 5; i++) { for (int j = -4; j < 5; j++) { for (int k = -4; k < 5; k++) { int x = MathHelper.floor_double(player.posX + i); int y = MathHelper.floor_double(player.posY + j); int z = MathHelper.floor_double(player.posZ + k); final int id = player.worldObj.getBlockId(x, y, z); if (id != 0) { final Block block = Block.blocksList[id]; int metadata = world.getBlockMetadata(x, y, z); boolean isDetectable = false; for (BlockMetaList blockMetaList : ClientProxyCore.detectableBlocks) { if (blockMetaList.getBlockID() == id && blockMetaList.getMetaList().contains(metadata)) { isDetectable = true; break; } } if (isDetectable) { if (!this.alreadyContainsBlock(x, y, z)) { ClientProxyCore.valueableBlocks.add(new Vector3(x, y, z)); } } else if (block instanceof IDetectableResource && ((IDetectableResource) block).isValueable(metadata)) { if (!this.alreadyContainsBlock(x, y, z)) { ClientProxyCore.valueableBlocks.add(new Vector3(x, y, z)); } List<Integer> metaList = Lists.newArrayList(); metaList.add(metadata); for (BlockMetaList blockMetaList : ClientProxyCore.detectableBlocks) { if (blockMetaList.getBlockID() == id) { metaList.addAll(blockMetaList.getMetaList()); break; } } ClientProxyCore.detectableBlocks.add(new BlockMetaList(id, metaList)); } } } } } } } if (GCCoreTickHandlerClient.addTabsNextTick) { if (minecraft.currentScreen.getClass().equals(GuiInventory.class)) { GCCoreTickHandlerClient.addTabsToInventory((GuiContainer) minecraft.currentScreen); } GCCoreTickHandlerClient.addTabsNextTick = false; } if (minecraft.currentScreen != null && minecraft.currentScreen instanceof GuiMainMenu) { GalacticraftCore.playersServer.clear(); GalacticraftCore.playersClient.clear(); ClientProxyCore.playerItemData.clear(); if (GCCoreTickHandlerClient.missingRequirementThread == null) { GCCoreTickHandlerClient.missingRequirementThread = new GCCoreThreadRequirementMissing(FMLCommonHandler.instance().getEffectiveSide()); GCCoreTickHandlerClient.missingRequirementThread.start(); } } if (world != null && GCCoreTickHandlerClient.checkedVersion) { GCCoreUtil.checkVersion(Side.CLIENT); GCCoreTickHandlerClient.checkedVersion = false; } if (player != null && player.ridingEntity != null && player.ridingEntity instanceof EntitySpaceshipBase) { final Object[] toSend = { player.ridingEntity.rotationPitch }; PacketDispatcher.sendPacketToServer(PacketUtil.createPacket(GalacticraftCore.CHANNEL, EnumPacketServer.UPDATE_SHIP_PITCH, toSend)); final Object[] toSend2 = { player.ridingEntity.rotationYaw }; PacketDispatcher.sendPacketToServer(PacketUtil.createPacket(GalacticraftCore.CHANNEL, EnumPacketServer.UPDATE_SHIP_YAW, toSend2)); } if (world != null && world.provider instanceof WorldProviderSurface) { if (world.provider.getSkyRenderer() == null && player.ridingEntity != null && player.ridingEntity.posY >= 200) { world.provider.setSkyRenderer(new GCCoreSkyProviderOverworld()); } else if (world.provider.getSkyRenderer() != null && world.provider.getSkyRenderer() instanceof GCCoreSkyProviderOverworld && (player.ridingEntity == null || player.ridingEntity.posY < 200)) { world.provider.setSkyRenderer(null); } } if (world != null && world.provider instanceof GCCoreWorldProviderSpaceStation) { if (world.provider.getSkyRenderer() == null) { world.provider.setSkyRenderer(new GCCoreSkyProviderOrbit(new ResourceLocation(GalacticraftCore.ASSET_DOMAIN, "textures/gui/planets/overworld.png"), true, true)); } if (world.provider.getCloudRenderer() == null) { world.provider.setCloudRenderer(new GCCoreCloudRenderer()); } } if (player != null && player.ridingEntity != null && player.ridingEntity instanceof EntitySpaceshipBase) { final EntitySpaceshipBase ship = (EntitySpaceshipBase) player.ridingEntity; if (minecraft.gameSettings.keyBindLeft.pressed) { ship.turnYaw(-1.0F); final Object[] toSend = { ship.rotationYaw }; PacketDispatcher.sendPacketToServer(PacketUtil.createPacket(GalacticraftCore.CHANNEL, EnumPacketServer.UPDATE_SHIP_YAW, toSend)); } if (minecraft.gameSettings.keyBindRight.pressed) { ship.turnYaw(1.0F); final Object[] toSend = { ship.rotationYaw }; PacketDispatcher.sendPacketToServer(PacketUtil.createPacket(GalacticraftCore.CHANNEL, EnumPacketServer.UPDATE_SHIP_YAW, toSend)); } if (minecraft.gameSettings.keyBindForward.pressed) { if (ship.getLaunched()) { ship.turnPitch(-0.7F); final Object[] toSend = { ship.rotationPitch }; PacketDispatcher.sendPacketToServer(PacketUtil.createPacket(GalacticraftCore.CHANNEL, EnumPacketServer.UPDATE_SHIP_PITCH, toSend)); } } if (minecraft.gameSettings.keyBindBack.pressed) { if (ship.getLaunched()) { ship.turnPitch(0.7F); final Object[] toSend = { ship.rotationPitch }; PacketDispatcher.sendPacketToServer(PacketUtil.createPacket(GalacticraftCore.CHANNEL, EnumPacketServer.UPDATE_SHIP_PITCH, toSend)); } } } if (world != null) { for (int i = 0; i < world.loadedEntityList.size(); i++) { final Entity e = (Entity) world.loadedEntityList.get(i); if (e != null) { if (e instanceof GCCoreEntityRocketT1) { final GCCoreEntityRocketT1 eship = (GCCoreEntityRocketT1) e; if (eship.rocketSoundUpdater == null) { eship.rocketSoundUpdater = new GCCoreSoundUpdaterSpaceship(FMLClientHandler.instance().getClient().sndManager, eship, FMLClientHandler.instance().getClient().thePlayer); } } } } } if (FMLClientHandler.instance().getClient().currentScreen instanceof GCCoreGuiChoosePlanet) { player.motionY = 0; } if (world != null && world.provider instanceof IGalacticraftWorldProvider) { world.setRainStrength(0.0F); } if (!minecraft.gameSettings.keyBindJump.pressed) { ClientProxyCore.lastSpacebarDown = false; } if (player != null && player.ridingEntity != null && minecraft.gameSettings.keyBindJump.pressed && !ClientProxyCore.lastSpacebarDown) { final Object[] toSend = { 0 }; PacketDispatcher.sendPacketToServer(PacketUtil.createPacket(GalacticraftCore.CHANNEL, EnumPacketServer.IGNITE_ROCKET, toSend)); ClientProxyCore.lastSpacebarDown = true; } } } private boolean alreadyContainsBlock(int x1, int y1, int z1) { return ClientProxyCore.valueableBlocks.contains(new Vector3(x1, y1, z1)); } public static void zoom(float value) { try { ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, FMLClientHandler.instance().getClient().entityRenderer, value, 15); ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, FMLClientHandler.instance().getClient().entityRenderer, value, 16); } catch (final Exception ex) { ex.printStackTrace(); } } @Override public void tickEnd(EnumSet<TickType> type, Object... tickData) { final Minecraft minecraft = FMLClientHandler.instance().getClient(); final EntityPlayerSP player = minecraft.thePlayer; final GCCorePlayerSP playerBaseClient = PlayerUtil.getPlayerBaseClientFromPlayer(player); if (player != null && player.inventory.armorItemInSlot(3) != null) { player.inventory.armorItemInSlot(3); } if (type.equals(EnumSet.of(TickType.CLIENT))) { boolean invKeyPressed = Keyboard.isKeyDown(minecraft.gameSettings.keyBindInventory.keyCode); if (!GCCoreTickHandlerClient.lastInvKeyPressed && invKeyPressed && minecraft.currentScreen != null && minecraft.currentScreen.getClass() == GuiInventory.class) { GCCoreTickHandlerClient.addTabsToInventory((GuiContainer) minecraft.currentScreen); } GCCoreTickHandlerClient.lastInvKeyPressed = invKeyPressed; } else if (type.equals(EnumSet.of(TickType.RENDER))) { final float partialTickTime = (Float) tickData[0]; if (player != null) { ClientProxyCore.playerPosX = player.prevPosX + (player.posX - player.prevPosX) * partialTickTime; ClientProxyCore.playerPosY = player.prevPosY + (player.posY - player.prevPosY) * partialTickTime; ClientProxyCore.playerPosZ = player.prevPosZ + (player.posZ - player.prevPosZ) * partialTickTime; ClientProxyCore.playerRotationYaw = player.prevRotationYaw + (player.rotationYaw - player.prevRotationYaw) * partialTickTime; ClientProxyCore.playerRotationPitch = player.prevRotationPitch + (player.rotationPitch - player.prevRotationPitch) * partialTickTime; } if (player != null && player.ridingEntity != null && player.ridingEntity instanceof GCCoreEntityRocketT1) { float f = (((GCCoreEntityRocketT1) player.ridingEntity).timeSinceLaunch - 250F) / 175F; if (f < 0) { f = 0F; } if (f > 1) { f = 1F; } final ScaledResolution scaledresolution = new ScaledResolution(minecraft.gameSettings, minecraft.displayWidth, minecraft.displayHeight); scaledresolution.getScaledWidth(); scaledresolution.getScaledHeight(); minecraft.entityRenderer.setupOverlayRendering(); GL11.glEnable(GL11.GL_BLEND); GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glDepthMask(false); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glColor4f(1.0F, 1.0F, 1.0F, f); GL11.glDisable(GL11.GL_ALPHA_TEST); GL11.glDepthMask(true); GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); } if (minecraft.currentScreen == null && player != null && player.ridingEntity != null && player.ridingEntity instanceof EntitySpaceshipBase && minecraft.gameSettings.thirdPersonView != 0 && !minecraft.gameSettings.hideGUI) { GCCoreOverlaySpaceship.renderSpaceshipOverlay(((EntitySpaceshipBase) player.ridingEntity).getSpaceshipGui()); } if (minecraft.currentScreen == null && player != null && player.ridingEntity != null && player.ridingEntity instanceof GCCoreEntityLander && minecraft.gameSettings.thirdPersonView != 0 && !minecraft.gameSettings.hideGUI) { GCCoreOverlayLander.renderLanderOverlay(); } if (minecraft.currentScreen == null && player != null && player.ridingEntity != null && player.ridingEntity instanceof EntityAutoRocket && minecraft.gameSettings.thirdPersonView != 0 && !minecraft.gameSettings.hideGUI) { GCCoreOverlayDockingRocket.renderDockingOverlay(); } if (minecraft.currentScreen == null && player != null && player.ridingEntity != null && player.ridingEntity instanceof EntitySpaceshipBase && minecraft.gameSettings.thirdPersonView != 0 && !minecraft.gameSettings.hideGUI && ((EntitySpaceshipBase) minecraft.thePlayer.ridingEntity).launchPhase != EnumLaunchPhase.LAUNCHED.getPhase()) { GCCoreOverlayCountdown.renderCountdownOverlay(); } if (player != null && player.worldObj.provider instanceof IGalacticraftWorldProvider && OxygenUtil.shouldDisplayTankGui(minecraft.currentScreen)) { int var6 = (GCCoreTickHandlerClient.airRemaining - 90) * -1; if (GCCoreTickHandlerClient.airRemaining <= 0) { var6 = 90; } int var7 = (GCCoreTickHandlerClient.airRemaining2 - 90) * -1; if (GCCoreTickHandlerClient.airRemaining2 <= 0) { var7 = 90; } GCCoreOverlayOxygenTankIndicator.renderOxygenTankIndicator(var6, var7, !GCCoreConfigManager.oxygenIndicatorLeft, !GCCoreConfigManager.oxygenIndicatorBottom); } if (playerBaseClient != null && player.worldObj.provider instanceof IGalacticraftWorldProvider && !playerBaseClient.oxygenSetupValid && minecraft.currentScreen == null && !playerBaseClient.capabilities.isCreativeMode) { GCCoreOverlayOxygenWarning.renderOxygenWarningOverlay(); } } } public static void addTabsToInventory(GuiContainer gui) { boolean tConstructLoaded = Loader.isModLoaded("TConstruct"); if (!tConstructLoaded) { if (!GCCoreTickHandlerClient.addTabsNextTick) { GCCoreTickHandlerClient.addTabsNextTick = true; return; } TabRegistry.addTabsToInventory(gui); } } @Override public String getLabel() { return "Galacticraft Client"; } @Override public EnumSet<TickType> ticks() { return EnumSet.of(TickType.RENDER, TickType.CLIENT); } }
lgpl-3.0
waterguo/antsdb
fish-server/src/main/java/com/antsdb/saltedfish/minke/MinkeCache.java
8156
/*------------------------------------------------------------------------------------------------- _______ __ _ _______ _______ ______ ______ |_____| | \ | | |______ | \ |_____] | | | \_| | ______| |_____/ |_____] Copyright (c) 2016, antsdb.com and/or its affiliates. All rights reserved. *-xguo0<@ This program is free software: you can redistribute it and/or modify it under the terms of the GNU GNU Lesser General Public License, version 3, as published by the Free Software Foundation. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/lgpl-3.0.en.html> -------------------------------------------------------------------------------------------------*/ package com.antsdb.saltedfish.minke; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.slf4j.Logger; import com.antsdb.saltedfish.cpp.KeyBytes; import com.antsdb.saltedfish.nosql.ConfigService; import com.antsdb.saltedfish.nosql.LogSpan; import com.antsdb.saltedfish.nosql.Replicable; import com.antsdb.saltedfish.nosql.StorageEngine; import com.antsdb.saltedfish.nosql.StorageTable; import com.antsdb.saltedfish.nosql.SysMetaRow; import com.antsdb.saltedfish.util.LongLong; import com.antsdb.saltedfish.util.UberFormatter; import com.antsdb.saltedfish.util.UberUtil; /** * * @author *-xguo0<@ */ public final class MinkeCache implements LogSpan, StorageEngine { static final Logger _log = UberUtil.getThisLogger(); /* an empty range goes from 0 to ff */ static final Range EMPTY_RANGE = new Range(KeyBytes.getMinKey(),true, KeyBytes.getMaxKey(), true); StorageEngine stoarge; Minke minke; long cacheMiss = 0; ConcurrentMap<Integer, MinkeCacheTable> tableById = new ConcurrentHashMap<>(); boolean isMutable = true; private int verificationMode; CacheStrategy strategy = new AllButBlobStrategy(); public MinkeCache(StorageEngine storage) { this.stoarge = storage; } @Override public void open(File home, ConfigService config, boolean isMutable) throws Exception { this.minke = new Minke(); this.isMutable = isMutable; this.strategy = config.getCacheStrategy(); config.getProperties().setProperty("minke.size", String.valueOf(config.getCacheSize())); this.verificationMode = config.getCacheVerificationMode(); this.minke.open(home, config, isMutable); } @Override public StorageTable getTable(int id) { MinkeCacheTable result = this.tableById.get(id); if (result == null) { MinkeTable mtable = (MinkeTable)this.minke.getTable(id); if (mtable != null) { _log.warn("minke and humpback are out of sync for table: {}", id); } } return result; } @Override public StorageTable createTable(SysMetaRow meta) { // we dont care temp. tables if (meta.getTableId() < 0) return null; StorageTable stable = this.stoarge.createTable(meta); MinkeTable mtable = (MinkeTable)this.minke.createTable(meta); MinkeCacheTable result = new MinkeCacheTable(this, mtable, stable, meta); this.tableById.put(meta.getTableId(), result); // set an empty range so following inserts doesn't hit hbase mtable.putRange(EMPTY_RANGE); return result; } @Override public boolean deleteTable(int id) { boolean result = true; if (id >= 0) { // only harass hbase when this is not a temporary table this.stoarge.deleteTable(id); } this.minke.deleteTable(id); this.tableById.remove(id); return result; } @Override public void createNamespace(String name) { this.stoarge.createNamespace(name); this.minke.createNamespace(name); } @Override public void deleteNamespace(String name) { this.stoarge.deleteNamespace(name); this.minke.deleteNamespace(name); } @Override public boolean isTransactionRecoveryRequired() { return this.stoarge.isTransactionRecoveryRequired(); } @Override public LongLong getLogSpan() { LongLong spanMinke = this.minke.getLogSpan(); LongLong spanStorage = this.stoarge.getLogSpan(); LongLong result = new LongLong(0, Math.min(spanMinke.y, spanStorage.y)); return result; } @Override public void close() throws IOException { this.minke.close(); this.stoarge.close(); } void resetCacheHitRatio() { this.minke.resetHitCount(); this.cacheMiss = 0; } public long getCacheHits() { long hits = this.minke.getHitCount(); return hits; } public long getCacheMiss() { return this.cacheMiss; } public double getCacheHitRatio() { long hits = this.minke.getHitCount(); long misses = this.cacheMiss; long total = hits + misses; if (total == 0) { return 0; } return hits/(double)total; } void cacheMiss() { this.cacheMiss++; } @Override public void setEndSpacePointer(long sp) { this.minke.setEndSpacePointer(sp); } @Override public void checkpoint() throws Exception { this.minke.checkpoint(); } @Override public void gc(long timestamp) { this.minke.gc(timestamp); } public void checkpointIfNeccessary() throws Exception { this.minke.checkpointIfNeccessary(); } public Map<String, Object> getSummary() { Map<String, Object> props = new HashMap<>(); props.putAll(this.minke.getSummary()); props.put("cache hit ratio", getCacheHitRatio()); props.put("cache hits", getCacheHits()); props.put("cache miss", getCacheMiss()); props.put("max cache size", UberFormatter.capacity(this.minke.size)); props.put("current cache file size", UberFormatter.capacity(this.minke.getCurrentFileSize())); props.put("cache usage %", getUsage()); return props; } public int getUsage() { long used = this.minke.getUsedPageCount(); long usage = used * 100 / this.minke.getMaxPages(); return (int)usage; } void clear() { for (MinkeCacheTable i:this.tableById.values()) { MinkeTable mtable = i.mtable; this.minke.deleteTable(mtable.tableId); this.getStorage().deleteTable(mtable.tableId); } this.tableById.clear(); resetCacheHitRatio(); } public Minke getMinke() { return this.minke; } public StorageEngine getStorage() { return this.stoarge; } /** * is cache verification enabled ? * @return 0:diabled; 1:only after fetch; 2:always */ int getVerificationMode() { return this.verificationMode; } @Override public void syncTable(SysMetaRow row) { if (row.getTableId() < 0) { // we dont care about temporary table return; } this.minke.syncTable(row); this.stoarge.syncTable(row); MinkeCacheTable mctable = this.tableById.get(row.getTableId()); if (row.isDeleted() && mctable != null) { this.tableById.remove(row.getTableId()); } else if (!row.isDeleted() && mctable == null) { MinkeTable mtable = (MinkeTable)this.minke.getTable(row.getTableId()); StorageTable stable = this.stoarge.getTable(row.getTableId()); mctable = new MinkeCacheTable(this, mtable, stable, row); this.tableById.put(row.getTableId(), mctable); } } @Override public boolean exist(int tableId) { return this.stoarge.exist(tableId); } @Override public Replicable getReplicable() { return this.stoarge.getReplicable(); } }
lgpl-3.0
chechulinYuri/stepout
app/src/main/java/com/stepout/main/DataExchange.java
22352
package com.stepout.main; import android.app.Application; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.telephony.TelephonyManager; import android.util.Log; import com.facebook.model.GraphUser; import com.parse.DeleteCallback; import com.parse.FindCallback; import com.parse.GetCallback; import com.parse.Parse; import com.parse.ParseException; import com.parse.ParseFile; import com.parse.ParseGeoPoint; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.PushService; import com.parse.SaveCallback; import com.squareup.otto.Bus; import com.stepout.main.models.Event; import com.stepout.main.models.User; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Yuri on 25.07.2014. */ public class DataExchange extends Application { public static final String EVENT_TABLE_NAME = "Event"; public static final String USER_TABLE_NAME = "User"; public static final String CATEGORY_TABLE_NAME = "Categories"; public static final String MESSAGE_COL_NAME = "message"; public static final String CATEGORY_COL_NAME = "category"; public static final String AUTHOR_HASH_COL_NAME = "authorHash"; public static final String DATE_COL_NAME = "date"; public static final String COORDINATES_COL_NAME = "coordinates"; public static final String RESPONDENTS_HASH_COL_NAME = "respondentsHash"; public static final String USER_HASH_COL_NAME = "userHash"; public static final String EVENT_HASH_COL_NAME = "eventHash"; public static final String FACEBOOK_ID_COL_NAME = "fbId"; public static final String FIRST_NAME_COL_NAME = "firstName"; public static final String LAST_NAME_COL_NAME = "lastName"; public static final String PHONE_COL_NAME = "phone"; public static final String OBJECT_ID_COL_NAME = "objectId"; public static final String NAME_COL_NAME = "name"; public static final String IMAGE_COL_NAME = "image"; public static final double EVENTS_VISIBILITY_RADIUS_IN_MILES = 50; public static final ArrayList<Event> uploadedEvents = new ArrayList<Event>(); public static final ArrayList<Event> searchEventResult = new ArrayList<Event>(); public static final ArrayList<Event> filterEventResult = new ArrayList<Event>(); public static HashMap<String, Bitmap> categories = new HashMap<String, Bitmap>(); public static final String LOG_TAG = "asd"; public static Bus bus; public static Context context; public static final String STATUS_SUCCESS = "STATUS_SUCCESS"; public static final String STATUS_FAIL = "STATUS_FAIL"; public static final String STATUS_REMOVE_SUCCESS = "STATUS_REMOVE_SUCCESS"; public static final String STATUS_REMOVE_FAIL = "STATUS_REMOVE_FAIL"; public static final String STATUS_UPDATE_EVENT_SUCCESS = "STATUS_UPDATE_EVENT_SUCCESS"; public static final String STATUS_UPDATE_EVENT_FAIL = "STATUS_UPDATE_EVENT_FAIL"; public static final String STATUS_SEARCH_SUCCESS = "STATUS_SEARCH_SUCCESS"; public static final String STATUS_SEARCH_FAIL = "STATUS_SEARCH_FAIL"; public static final String STATUS_FILTER_SUCCESS = "STATUS_FILTER_SUCCESS"; public static final String STATUS_FILTER_FAIL = "STATUS_FILTER_FAIL"; public static final String EVENT_HASH_FOR_VIEW_EVENT_ACTIVITY_KEY = "EVENT_HASH_FOR_VIEW_EVENT_ACTIVITY_KEY"; public static final String LOCATION_OF_NEW_EVENT_LAT_KEY = "LOCATION_OF_NEW_EVENT_LAT_KEY"; public static final String LOCATION_OF_NEW_EVENT_LNG_KEY = "LOCATION_OF_NEW_EVENT_LNG_KEY"; public static final String PREFIX_FOR_CHANNEL_NAME = "channel_"; public void onCreate() { super.onCreate(); Parse.initialize(getApplicationContext(), "w8w75nqgzFroCnZEqO6auY85PJnTRKILNXYZUeKa", "UNH39pBxBzLAD4ekMZQUp0VzGUACPTPTHBT5x8qg"); bus = new Bus(); context = getApplicationContext(); PushService.setDefaultPushCallback(getApplicationContext(), MainActivity.class); } public static void getCategories() { categories = new HashMap<String, Bitmap>(); Log.d(LOG_TAG, "start category loading"); ParseQuery<ParseObject> query = ParseQuery.getQuery(CATEGORY_TABLE_NAME); query.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> objects, ParseException e) { if (e == null) { Log.d(LOG_TAG, "category loaded"); for (ParseObject po: objects) { ParseFile imageFile = po.getParseFile(IMAGE_COL_NAME); try { byte[] imageBytes = imageFile.getData(); Bitmap bmp = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length); categories.put(po.getString(NAME_COL_NAME), bmp); } catch (ParseException e1) { e1.printStackTrace(); } } } else { Log.d(LOG_TAG, e.getMessage()); } bus.post(categories); } }); } public static User loginFb(GraphUser fbUser, Context context) { if (!isRegistered(fbUser.getId())) { TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); String phone = telephonyManager.getLine1Number(); User newUser = new User(fbUser.getFirstName(), fbUser.getLastName(), phone, fbUser.getId()); return saveUserToParseCom(newUser); } return getUserByFbId(fbUser.getId()); } public static User saveUserToParseCom(User user) { String userHash = null; ParseObject userParse = new ParseObject(USER_TABLE_NAME); userParse.put(FACEBOOK_ID_COL_NAME, user.getFbId()); userParse.put(FIRST_NAME_COL_NAME, user.getFirstName()); userParse.put(LAST_NAME_COL_NAME, user.getLastName()); if (user.getPhone() != null) { userParse.put(PHONE_COL_NAME, user.getPhone()); } try { userParse.save(); userHash = userParse.getObjectId(); } catch(ParseException e) { Log.d("ERROR", e.getMessage()); } if (userHash != null) { user.setHash(userHash); return user; } return null; } public static User getUserByFbId(String fbId) { ParseQuery<ParseObject> query = ParseQuery.getQuery(USER_TABLE_NAME); query.whereEqualTo(FACEBOOK_ID_COL_NAME, fbId); try { List<ParseObject> objects = query.find(); if (objects.size() > 0) { ParseObject obj = objects.get(0); User user = new User( obj.getString(FIRST_NAME_COL_NAME), obj.getString(LAST_NAME_COL_NAME), obj.getString(PHONE_COL_NAME), obj.getString(FACEBOOK_ID_COL_NAME) ); user.setHash(obj.getObjectId()); return user; } } catch(ParseException e) { Log.d("ERROR", e.getMessage()); } return null; } public static void getUserByHash(String userHash) { ParseQuery<ParseObject> query = ParseQuery.getQuery(USER_TABLE_NAME); query.whereEqualTo(OBJECT_ID_COL_NAME, userHash); query.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> objects, ParseException e) { if (e == null) { ParseObject obj = objects.get(0); User user = new User( obj.getString(FIRST_NAME_COL_NAME), obj.getString(LAST_NAME_COL_NAME), obj.getString(PHONE_COL_NAME), obj.getString(FACEBOOK_ID_COL_NAME) ); user.setHash(obj.getObjectId()); bus.post(user); } } }); } public static boolean isRegistered(String fbId) { if (getUserByFbId(fbId) == null) { return false; } else { return true; } } public static void saveEventToParseCom(final Event event) { final ParseObject eventParse = new ParseObject(EVENT_TABLE_NAME); eventParse.put(MESSAGE_COL_NAME, event.getMessage()); eventParse.put(CATEGORY_COL_NAME, event.getCategory()); eventParse.put(AUTHOR_HASH_COL_NAME, event.getAuthorHash()); eventParse.put(DATE_COL_NAME, event.getDate()); eventParse.put(COORDINATES_COL_NAME, event.getCoordinates()); eventParse.put(RESPONDENTS_HASH_COL_NAME, event.getRespondentsHash()); eventParse.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { if (e == null) { Event ev = new Event( eventParse.getString(MESSAGE_COL_NAME), eventParse.getParseGeoPoint(COORDINATES_COL_NAME), eventParse.getString(CATEGORY_COL_NAME), eventParse.getString(AUTHOR_HASH_COL_NAME), eventParse.getDate(DATE_COL_NAME), eventParse.<String>getList(RESPONDENTS_HASH_COL_NAME) ); ev.setHash(eventParse.getObjectId()); bus.post(ev); } } }); } public static void respondToEvent(final String eventHash, final String userHash) { ParseQuery<ParseObject> query = ParseQuery.getQuery(EVENT_TABLE_NAME); query.whereEqualTo(OBJECT_ID_COL_NAME, eventHash); query.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> objects, ParseException e) { if (e == null) { final ParseObject eventParseObj = objects.get(0); eventParseObj.getList(RESPONDENTS_HASH_COL_NAME).add(userHash); eventParseObj.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { if (e == null) { for (Event ev : uploadedEvents) { if (ev.getHash().equals(eventParseObj.getObjectId())) { ev.getRespondentsHash().add(userHash); } } bus.post(STATUS_SUCCESS); } else { bus.post(STATUS_FAIL); } } }); } } }); } public static void unresponseFromEvent(String eventHash, final String userHash) { ParseQuery<ParseObject> query = ParseQuery.getQuery(EVENT_TABLE_NAME); query.whereEqualTo(OBJECT_ID_COL_NAME, eventHash); query.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> objects, ParseException e) { if (e == null) { final ParseObject eventParseObj = objects.get(0); eventParseObj.getList(RESPONDENTS_HASH_COL_NAME).remove(userHash); eventParseObj.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { if (e == null) { for (Event ev : uploadedEvents) { if (ev.getHash().equals(eventParseObj.getObjectId())) { ev.getRespondentsHash().remove(userHash); } } bus.post(STATUS_SUCCESS); } else { bus.post(STATUS_FAIL); } } }); } } }); } public static void getEventByHash(String eventHash) { ParseQuery<ParseObject> query = ParseQuery.getQuery(EVENT_TABLE_NAME); query.whereEqualTo(OBJECT_ID_COL_NAME, eventHash); query.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> objects, ParseException e) { if (e == null) { if (objects.size() > 0) { ParseObject po = objects.get(0); Event ev = new Event( po.getString(MESSAGE_COL_NAME), po.getParseGeoPoint(COORDINATES_COL_NAME), po.getString(CATEGORY_COL_NAME), po.getString(AUTHOR_HASH_COL_NAME), po.getDate(DATE_COL_NAME), po.<String>getList(RESPONDENTS_HASH_COL_NAME) ); ev.setHash(po.getObjectId()); bus.post(ev); } else { Log.d(LOG_TAG, "getEventByHash event not found"); bus.post(new Event()); } } else { Log.d(LOG_TAG, e.getMessage()); bus.post(new Event()); } } }); } public static void removeEvent(final String eventHash, String userHash) { ParseQuery<ParseObject> query = ParseQuery.getQuery(EVENT_TABLE_NAME); query.whereEqualTo(OBJECT_ID_COL_NAME, eventHash); query.whereEqualTo(AUTHOR_HASH_COL_NAME, userHash); query.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> parseObjects, ParseException e) { if (e == null && parseObjects.size() > 0) { parseObjects.get(0).deleteInBackground(new DeleteCallback() { @Override public void done(ParseException e) { if (e == null) { for (Event event: uploadedEvents) { if (event.getHash().equals(eventHash)) { uploadedEvents.remove(event); break; } } bus.post(STATUS_REMOVE_SUCCESS); } else { bus.post(STATUS_REMOVE_FAIL); } } }); } else { bus.post(STATUS_REMOVE_FAIL); } } }); } public static void updateEvent(final Event event, String userHash) { ParseQuery<ParseObject> query = ParseQuery.getQuery(EVENT_TABLE_NAME); query.getInBackground(event.getHash(), new GetCallback<ParseObject>() { public void done(ParseObject eventParse, ParseException e) { if (e == null) { eventParse.put(MESSAGE_COL_NAME, event.getMessage()); eventParse.put(CATEGORY_COL_NAME, event.getCategory()); eventParse.put(AUTHOR_HASH_COL_NAME, event.getAuthorHash()); eventParse.put(DATE_COL_NAME, event.getDate()); eventParse.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { if (e == null) { for (int i = 0; i < uploadedEvents.size(); i++) { Event ev = uploadedEvents.get(i); if (ev.getHash().equals(event.getHash())) { uploadedEvents.set(i, event); break; } } bus.post(STATUS_UPDATE_EVENT_SUCCESS); } else { bus.post(STATUS_UPDATE_EVENT_FAIL); } } }); } else { bus.post(STATUS_UPDATE_EVENT_FAIL); } } }); } public static void getEventsInRadius(double lan, double lng) { final ArrayList<Event> events = new ArrayList<Event>(); ParseQuery<ParseObject> query = ParseQuery.getQuery(EVENT_TABLE_NAME); query.whereWithinMiles(COORDINATES_COL_NAME, new ParseGeoPoint(lan, lng), EVENTS_VISIBILITY_RADIUS_IN_MILES); query.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> parseObjects, ParseException e) { if (e == null) { for (int i = 0; i < parseObjects.size(); i++) { ParseObject po = parseObjects.get(i); Event ev = new Event( po.getString(MESSAGE_COL_NAME), po.getParseGeoPoint(COORDINATES_COL_NAME), po.getString(CATEGORY_COL_NAME), po.getString(AUTHOR_HASH_COL_NAME), po.getDate(DATE_COL_NAME), po.<String>getList(RESPONDENTS_HASH_COL_NAME) ); ev.setHash(po.getObjectId()); events.add(ev); } bus.post(events); } } }); } public static void searchEventsInRadius(String key, Double lan, Double lng) { final ArrayList<Event> events = new ArrayList<Event>(); ParseQuery<ParseObject> query = ParseQuery.getQuery(EVENT_TABLE_NAME); query.whereWithinMiles(COORDINATES_COL_NAME, new ParseGeoPoint(lan, lng), EVENTS_VISIBILITY_RADIUS_IN_MILES); query.whereContains(MESSAGE_COL_NAME, key); query.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> parseObjects, ParseException e) { if (e == null) { for (int i = 0; i < parseObjects.size(); i++) { ParseObject po = parseObjects.get(i); Event ev = new Event( po.getString(MESSAGE_COL_NAME), po.getParseGeoPoint(COORDINATES_COL_NAME), po.getString(CATEGORY_COL_NAME), po.getString(AUTHOR_HASH_COL_NAME), po.getDate(DATE_COL_NAME), po.<String>getList(RESPONDENTS_HASH_COL_NAME) ); ev.setHash(po.getObjectId()); events.add(ev); } searchEventResult.clear(); searchEventResult.addAll(events); bus.post(STATUS_SEARCH_SUCCESS); } else { bus.post(STATUS_SEARCH_FAIL); } } }); } public static void filterEventsInRadius(HashMap<String, Boolean> categoriesFlags, boolean onlyRespondEvent, Double lan, Double lng, String userHash) { final ArrayList<Event> events = new ArrayList<Event>(); List<ParseQuery<ParseObject>> queries = new ArrayList<ParseQuery<ParseObject>>(); for(Map.Entry<String, Boolean> entry : categoriesFlags.entrySet()) { if (entry.getValue()) { ParseQuery<ParseObject> subQuery = ParseQuery.getQuery(EVENT_TABLE_NAME); subQuery.whereEqualTo(CATEGORY_COL_NAME, entry.getKey()); queries.add(subQuery); } } ParseQuery<ParseObject> query; if (queries.size() > 0) { query = ParseQuery.or(queries); } else { query = ParseQuery.getQuery(EVENT_TABLE_NAME); } query.whereWithinMiles(COORDINATES_COL_NAME, new ParseGeoPoint(lan, lng), EVENTS_VISIBILITY_RADIUS_IN_MILES); if (onlyRespondEvent) { query.whereEqualTo(RESPONDENTS_HASH_COL_NAME, userHash); } query.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> parseObjects, ParseException e) { if (e == null) { for (int i = 0; i < parseObjects.size(); i++) { ParseObject po = parseObjects.get(i); Event ev = new Event( po.getString(MESSAGE_COL_NAME), po.getParseGeoPoint(COORDINATES_COL_NAME), po.getString(CATEGORY_COL_NAME), po.getString(AUTHOR_HASH_COL_NAME), po.getDate(DATE_COL_NAME), po.<String>getList(RESPONDENTS_HASH_COL_NAME) ); ev.setHash(po.getObjectId()); events.add(ev); } filterEventResult.clear(); filterEventResult.addAll(events); bus.post(STATUS_FILTER_SUCCESS); } else { bus.post(STATUS_FILTER_FAIL); } } }); } }
lgpl-3.0
hannoman/xxl
src/xxl/core/functions/ArrayFactory.java
4619
/* XXL: The eXtensible and fleXible Library for data processing Copyright (C) 2000-2011 Prof. Dr. Bernhard Seeger Head of the Database Research Group Department of Mathematics and Computer Science University of Marburg Germany This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; If not, see <http://www.gnu.org/licenses/>. http://code.google.com/p/xxl/ */ package xxl.core.functions; import java.util.Iterator; import java.util.List; import xxl.core.cursors.sources.EmptyCursor; /** * This class provides a factory method for typed arrays. The ArrayFactory * creates an array and fills it with objects. An iterator of arguments can be * passed to the invoke method of this class to create the objects which are * stored in the array. * * @param <T> the component type of the array to be returned. * @deprecated replaced by {@link Functional.ArrayFactory} */ @SuppressWarnings("serial") @Deprecated public class ArrayFactory<T> extends AbstractFunction<Object, T[]> { /** * A factory method that gets one parameter and returns an array. */ protected Function<Object, T[]> newArray; /** * A factory method that gets one parameter and returns an object used for * initializing the array. */ protected Function<Object, ? extends T> newObject; /** * Creates a new ArrayFactory. * * @param newArray factory method that returns an array. * @param newObject factory method that returns the elements of the array. */ public ArrayFactory(Function<Object, T[]> newArray, Function<Object, ? extends T> newObject) { this.newArray = newArray; this.newObject = newObject; } /** * Returns the result of the ArrayFactory as a typed array. This method * calls the invoke method of the newArray function which returns an array * of typed objects. After this, the invoke method of the newObject * function is called, so many times as the length of the array. As * parameter to the function an element of the iterator is given that is * specified as second argument. * * @param arguments the arguments to this function. The first arguments * must be an object used as argument to the newArray function. * The second argument must be an iterator holding the arguments to * the newObject function. * @return the initialized array. */ @Override public T[] invoke(List<? extends Object> arguments) { if (arguments.size() != 2) throw new IllegalArgumentException("the function must be invoked with an object and an iterator."); T[] array = newArray.invoke(arguments.get(0)); Iterator<?> newObjectArguments = (Iterator<?>)arguments.get(1); for (int i = 0; i < array.length; i++) array[i] = newObject.invoke(newObjectArguments.hasNext() ? newObjectArguments.next() : null); //call invoke on newObject with argument-Object from arguments-Iterator return array; } /** * Returns the result of the ArrayFactory as a typed array. This method * calls the invoke method of the newArray function using the given * argument which returns an array of typed objects. After this, the invoke * method of the newObject function is called without any arguments, so * many times as the length of the array. * * @param argument the argument to the newArray function. * @return the initialized array. */ @Override public T[] invoke(Object argument) { return invoke(argument, EmptyCursor.DEFAULT_INSTANCE); } /** * Returns the result of the ArrayFactory as a typed array. This method * calls the invoke method of the newArray function using the argument * <code>null</code> which returns an array of typed objects. After this, * the invoke method of the newObject function is called without any * arguments, so many times as the length of the array. * * @return the initialized array. */ @Override public T[] invoke() { return invoke((Object)null); } }
lgpl-3.0
smartfeeling/smartly
smartly_package_01_htmldeployer/src_yahoo/old/mozilla/javascript/EvaluatorException.java
4012
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package old.mozilla.javascript; /** * The class of exceptions thrown by the JavaScript engine. */ public class EvaluatorException extends RhinoException { static final long serialVersionUID = -8743165779676009808L; public EvaluatorException(String detail) { super(detail); } /** * Create an exception with the specified detail message. * * Errors internal to the JavaScript engine will simply throw a * RuntimeException. * * @param detail the error message * @param sourceName the name of the source reponsible for the error * @param lineNumber the line number of the source */ public EvaluatorException(String detail, String sourceName, int lineNumber) { this(detail, sourceName, lineNumber, null, 0); } /** * Create an exception with the specified detail message. * * Errors internal to the JavaScript engine will simply throw a * RuntimeException. * * @param detail the error message * @param sourceName the name of the source reponsible for the error * @param lineNumber the line number of the source * @param columnNumber the columnNumber of the source (may be zero if * unknown) * @param lineSource the source of the line containing the error (may be * null if unknown) */ public EvaluatorException(String detail, String sourceName, int lineNumber, String lineSource, int columnNumber) { super(detail); recordErrorOrigin(sourceName, lineNumber, lineSource, columnNumber); } /** * @deprecated Use {@link RhinoException#sourceName()} from the super class. */ public String getSourceName() { return sourceName(); } /** * @deprecated Use {@link RhinoException#lineNumber()} from the super class. */ public int getLineNumber() { return lineNumber(); } /** * @deprecated Use {@link RhinoException#columnNumber()} from the super class. */ public int getColumnNumber() { return columnNumber(); } /** * @deprecated Use {@link RhinoException#lineSource()} from the super class. */ public String getLineSource() { return lineSource(); } }
lgpl-3.0
cismet/cids-custom-wuppertal
src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/SimpleWebDavPanel.java
28135
/*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ /* * 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 de.cismet.cids.custom.objecteditors.wunda_blau; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.jdesktop.beansbinding.AutoBinding; import org.jdesktop.beansbinding.BindingGroup; import org.jdesktop.beansbinding.ELProperty; import org.jdesktop.swingbinding.JListBinding; import org.jdesktop.swingbinding.SwingBindings; import org.jdesktop.swingx.JXErrorPane; import org.jdesktop.swingx.error.ErrorInfo; import org.openide.awt.Mnemonics; import org.openide.util.NbBundle; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.logging.Level; import javax.swing.DefaultListCellRenderer; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.SwingWorker; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import de.cismet.cids.client.tools.WebDavTunnelHelper; import de.cismet.cids.custom.objectrenderer.utils.ObjectRendererUtils; import de.cismet.cids.dynamics.CidsBean; import de.cismet.cids.dynamics.CidsBeanStore; import de.cismet.cids.dynamics.Disposable; import de.cismet.cids.editors.EditorClosedEvent; import de.cismet.cids.editors.EditorSaveListener; import de.cismet.cids.server.actions.WebDavTunnelAction; import de.cismet.cismap.commons.gui.MappingComponent; import de.cismet.connectioncontext.ConnectionContext; import de.cismet.connectioncontext.ConnectionContextProvider; import de.cismet.tools.CismetThreadPool; import de.cismet.tools.gui.RoundedPanel; import de.cismet.tools.gui.SemiRoundedPanel; import de.cismet.tools.gui.StaticSwingTools; import de.cismet.tools.gui.downloadmanager.AbstractDownload; import de.cismet.tools.gui.downloadmanager.Download; import de.cismet.tools.gui.downloadmanager.DownloadManager; import de.cismet.tools.gui.downloadmanager.DownloadManagerDialog; /** * DOCUMENT ME! * * @author jruiz * @version $Revision$, $Date$ */ public class SimpleWebDavPanel extends javax.swing.JPanel implements CidsBeanStore, EditorSaveListener, Disposable, ConnectionContextProvider { //~ Static fields/initializers --------------------------------------------- private static final Logger LOG = Logger.getLogger(SimpleWebDavPanel.class); /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The * content of this method is always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { GridBagConstraints gridBagConstraints; bindingGroup = new BindingGroup(); final RoundedPanel pnlFotos = new RoundedPanel(); final SemiRoundedPanel pnlHeaderFotos = new SemiRoundedPanel(); final JLabel lblHeaderFotos = new JLabel(); final JPanel jPanel2 = new JPanel(); final JPanel jPanel1 = new JPanel(); final JScrollPane jspFotoList = new JScrollPane(); lstFotos = new JList(); final JPanel pnlCtrlButtons = new JPanel(); btnAddImg = new JButton(); btnRemoveImg = new JButton(); final FormListener formListener = new FormListener(); setName("Form"); // NOI18N setOpaque(false); setLayout(new GridBagLayout()); pnlFotos.setMinimumSize(new Dimension(400, 200)); pnlFotos.setName("pnlFotos"); // NOI18N pnlFotos.setPreferredSize(new Dimension(400, 200)); pnlFotos.setLayout(new GridBagLayout()); pnlHeaderFotos.setBackground(new Color(51, 51, 51)); pnlHeaderFotos.setForeground(new Color(51, 51, 51)); pnlHeaderFotos.setName("pnlHeaderFotos"); // NOI18N pnlHeaderFotos.setLayout(new FlowLayout()); lblHeaderFotos.setForeground(new Color(255, 255, 255)); Mnemonics.setLocalizedText( lblHeaderFotos, NbBundle.getMessage(SimpleWebDavPanel.class, "SimpleWebDavPanel.lblHeaderFotos.text")); // NOI18N lblHeaderFotos.setName("lblHeaderFotos"); // NOI18N pnlHeaderFotos.add(lblHeaderFotos); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; pnlFotos.add(pnlHeaderFotos, gridBagConstraints); jPanel2.setName("jPanel2"); // NOI18N jPanel2.setOpaque(false); jPanel2.setLayout(new GridBagLayout()); jPanel1.setName("jPanel1"); // NOI18N jPanel1.setOpaque(false); jPanel1.setLayout(new GridBagLayout()); jspFotoList.setMinimumSize(new Dimension(250, 130)); jspFotoList.setName("jspFotoList"); // NOI18N lstFotos.setMinimumSize(new Dimension(250, 130)); lstFotos.setName("lstFotos"); // NOI18N lstFotos.setPreferredSize(new Dimension(250, 130)); final ELProperty eLProperty = ELProperty.create("${cidsBean." + beanCollProp + "}"); final JListBinding jListBinding = SwingBindings.createJListBinding( AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, lstFotos); bindingGroup.addBinding(jListBinding); lstFotos.addMouseListener(formListener); lstFotos.addListSelectionListener(formListener); jspFotoList.setViewportView(lstFotos); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridheight = 2; gridBagConstraints.fill = GridBagConstraints.BOTH; gridBagConstraints.anchor = GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; jPanel1.add(jspFotoList, gridBagConstraints); pnlCtrlButtons.setName("pnlCtrlButtons"); // NOI18N pnlCtrlButtons.setOpaque(false); pnlCtrlButtons.setLayout(new GridBagLayout()); btnAddImg.setIcon(new ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N Mnemonics.setLocalizedText( btnAddImg, NbBundle.getMessage(SimpleWebDavPanel.class, "SimpleWebDavPanel.btnAddImg.text")); // NOI18N btnAddImg.setBorderPainted(false); btnAddImg.setContentAreaFilled(false); btnAddImg.setName("btnAddImg"); // NOI18N btnAddImg.addActionListener(formListener); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.insets = new Insets(0, 0, 5, 0); pnlCtrlButtons.add(btnAddImg, gridBagConstraints); btnRemoveImg.setIcon(new ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N Mnemonics.setLocalizedText( btnRemoveImg, NbBundle.getMessage(SimpleWebDavPanel.class, "SimpleWebDavPanel.btnRemoveImg.text")); // NOI18N btnRemoveImg.setBorderPainted(false); btnRemoveImg.setContentAreaFilled(false); btnRemoveImg.setName("btnRemoveImg"); // NOI18N btnRemoveImg.addActionListener(formListener); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridy = 1; gridBagConstraints.insets = new Insets(5, 0, 0, 0); pnlCtrlButtons.add(btnRemoveImg, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = GridBagConstraints.BOTH; gridBagConstraints.anchor = GridBagConstraints.NORTH; gridBagConstraints.insets = new Insets(0, 5, 0, 0); jPanel1.add(pnlCtrlButtons, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new Insets(10, 10, 10, 5); jPanel2.add(jPanel1, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlFotos.add(jPanel2, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.fill = GridBagConstraints.BOTH; gridBagConstraints.anchor = GridBagConstraints.NORTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(pnlFotos, gridBagConstraints); bindingGroup.bind(); } /** * Code for dispatching events from components to event handlers. * * @version $Revision$, $Date$ */ private class FormListener implements ActionListener, MouseListener, ListSelectionListener { /** * Creates a new FormListener object. */ FormListener() { } /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ @Override public void actionPerformed(final ActionEvent evt) { if (evt.getSource() == btnAddImg) { SimpleWebDavPanel.this.btnAddImgActionPerformed(evt); } else if (evt.getSource() == btnRemoveImg) { SimpleWebDavPanel.this.btnRemoveImgActionPerformed(evt); } } /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ @Override public void mouseClicked(final MouseEvent evt) { if (evt.getSource() == lstFotos) { SimpleWebDavPanel.this.lstFotosMouseClicked(evt); } } /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ @Override public void mouseEntered(final MouseEvent evt) { } /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ @Override public void mouseExited(final MouseEvent evt) { } /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ @Override public void mousePressed(final MouseEvent evt) { } /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ @Override public void mouseReleased(final MouseEvent evt) { } /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ @Override public void valueChanged(final ListSelectionEvent evt) { if (evt.getSource() == lstFotos) { SimpleWebDavPanel.this.lstFotosValueChanged(evt); } } } // </editor-fold>//GEN-END:initComponents //~ Instance fields -------------------------------------------------------- private final WebDavTunnelHelper webdavHelper; private final String beanCollProp; private final String nameProp; private final String bildClassName; private final JFileChooser fileChooser = new JFileChooser(); private final List<CidsBean> removeNewAddedFotoBean = new ArrayList<>(); private final List<CidsBean> removedFotoBeans = new ArrayList<>(); private final MappingComponent map = new MappingComponent(); private boolean listListenerEnabled = true; private CidsBean cidsBean; private final ConnectionContext connectionContext; // Variables declaration - do not modify//GEN-BEGIN:variables JButton btnAddImg; JButton btnRemoveImg; JList lstFotos; private BindingGroup bindingGroup; // End of variables declaration//GEN-END:variables //~ Constructors ----------------------------------------------------------- /** * Creates a new WebDavPicturePanel object. */ public SimpleWebDavPanel() { this(true, "dokumente", "dokumentClass", "name", "webDavTunnelAction", ConnectionContext.createDummy()); } /** * Creates new form WebDavPicturePanel. * * @param editable DOCUMENT ME! * @param beanCollProp DOCUMENT ME! * @param bildClassName DOCUMENT ME! * @param nameProp DOCUMENT ME! * @param tunnelAction webdavDirectory urlProp DOCUMENT ME! * @param connectionContext DOCUMENT ME! */ public SimpleWebDavPanel(final boolean editable, final String beanCollProp, final String bildClassName, final String nameProp, final String tunnelAction, final ConnectionContext connectionContext) { this.beanCollProp = beanCollProp; this.bildClassName = bildClassName; this.nameProp = nameProp; this.connectionContext = connectionContext; WebDavTunnelHelper webdavHelper = null; try { webdavHelper = new WebDavTunnelHelper("WUNDA_BLAU", tunnelAction); } catch (final Exception ex) { final String message = "Fehler beim Initialisieren der Bilderablage."; LOG.error(message, ex); ObjectRendererUtils.showExceptionWindowToUser(message, ex, null); } this.webdavHelper = webdavHelper; initComponents(); lstFotos.setCellRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(final JList list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) { final Component component = super.getListCellRendererComponent( list, value, index, isSelected, cellHasFocus); if ((component instanceof JLabel) && (value instanceof CidsBean)) { final CidsBean dokumentBean = (CidsBean)value; final String name = (String)dokumentBean.getProperty(nameProp); ((JLabel)component).setText(name); } return component; } }); fileChooser.setMultiSelectionEnabled(true); lstFotos.getModel().addListDataListener(new ListDataListener() { @Override public void intervalAdded(final ListDataEvent e) { // defineButtonStatus(); } @Override public void intervalRemoved(final ListDataEvent e) { // defineButtonStatus(); } @Override public void contentsChanged(final ListDataEvent e) { // defineButtonStatus(); } }); btnAddImg.setVisible(editable); btnRemoveImg.setVisible(editable); } //~ Methods ---------------------------------------------------------------- /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void lstFotosValueChanged(final ListSelectionEvent evt) { //GEN-FIRST:event_lstFotosValueChanged if (!evt.getValueIsAdjusting() && listListenerEnabled) { } } //GEN-LAST:event_lstFotosValueChanged /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnAddImgActionPerformed(final ActionEvent evt) { //GEN-FIRST:event_btnAddImgActionPerformed if (JFileChooser.APPROVE_OPTION == fileChooser.showOpenDialog(this)) { final File[] selFiles = fileChooser.getSelectedFiles(); if ((selFiles != null) && (selFiles.length > 0)) { CismetThreadPool.execute(new ImageUploadWorker(Arrays.asList(selFiles))); } } } //GEN-LAST:event_btnAddImgActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnRemoveImgActionPerformed(final ActionEvent evt) { //GEN-FIRST:event_btnRemoveImgActionPerformed final Object[] selection = lstFotos.getSelectedValues(); if ((selection != null) && (selection.length > 0)) { final int answer = JOptionPane.showConfirmDialog( StaticSwingTools.getParentFrame(this), "Sollen die Fotos wirklich gelöscht werden?", "Fotos entfernen", JOptionPane.YES_NO_OPTION); if (answer == JOptionPane.YES_OPTION) { try { listListenerEnabled = false; final List<Object> removeList = Arrays.asList(selection); final List<CidsBean> fotos = cidsBean.getBeanCollectionProperty(beanCollProp); if (fotos != null) { fotos.removeAll(removeList); } // TODO set the laufende_nr for (int i = 0; i < lstFotos.getModel().getSize(); i++) { final CidsBean foto = (CidsBean)lstFotos.getModel().getElementAt(i); foto.setProperty("laufende_nummer", i + 1); } for (final Object toDeleteObj : removeList) { if (toDeleteObj instanceof CidsBean) { final CidsBean fotoToDelete = (CidsBean)toDeleteObj; removedFotoBeans.add(fotoToDelete); } } } catch (final Exception ex) { LOG.error(ex, ex); showExceptionToUser(ex, this); } finally { // TODO check the laufende_nummer attribute listListenerEnabled = true; final int modelSize = lstFotos.getModel().getSize(); if (modelSize > 0) { lstFotos.setSelectedIndex(0); } } } } } //GEN-LAST:event_btnRemoveImgActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void lstFotosMouseClicked(final MouseEvent evt) { //GEN-FIRST:event_lstFotosMouseClicked if (evt.getClickCount() == 2) { final CidsBean dokumentBean = (CidsBean)lstFotos.getSelectedValue(); if (DownloadManagerDialog.getInstance().showAskingForUserTitleDialog(getParent())) { final String jobname = DownloadManagerDialog.getInstance().getJobName(); final Download download = new AbstractDownload() { { status = State.WAITING; this.directory = jobname; final String dateiname = (String)dokumentBean.getProperty("dateiname"); final int extIndex = dateiname.lastIndexOf("."); final String extension = (extIndex >= 0) ? dateiname.substring(extIndex) : ""; final String filename = (extIndex >= 0) ? dateiname.substring(0, extIndex) : dateiname; determineDestinationFile(filename, extension); } @Override public void run() { try { status = State.RUNNING; stateChanged(); final InputStream is = webdavHelper.getFileFromWebDAV((String)dokumentBean.getProperty( nameProp), getConnectionContext()); try(final OutputStream os = new FileOutputStream(fileToSaveTo)) { IOUtils.copy(is, os); } if (status == State.RUNNING) { status = State.COMPLETED; stateChanged(); } } catch (final Exception ex) { LOG.error(ex, ex); status = State.ABORTED; stateChanged(); } } }; DownloadManager.instance().add(download); } } } //GEN-LAST:event_lstFotosMouseClicked @Override public CidsBean getCidsBean() { return cidsBean; } @Override public void setCidsBean(final CidsBean cidsBean) { bindingGroup.unbind(); this.cidsBean = cidsBean; bindingGroup.bind(); if (cidsBean != null) { if (lstFotos.getModel().getSize() > 0) { lstFotos.setSelectedIndex(0); } } } /** * DOCUMENT ME! * * @param bi DOCUMENT ME! * @param component DOCUMENT ME! * @param insetX DOCUMENT ME! * @param insetY DOCUMENT ME! * * @return DOCUMENT ME! */ public static Image adjustScale(final BufferedImage bi, final JComponent component, final int insetX, final int insetY) { final double scalex = (double)component.getWidth() / bi.getWidth(); final double scaley = (double)component.getHeight() / bi.getHeight(); final double scale = Math.min(scalex, scaley); if (scale <= 1d) { return bi.getScaledInstance((int)(bi.getWidth() * scale) - insetX, (int)(bi.getHeight() * scale) - insetY, Image.SCALE_SMOOTH); } else { return bi; } } /** * DOCUMENT ME! * * @param ex DOCUMENT ME! * @param parent DOCUMENT ME! */ private static void showExceptionToUser(final Exception ex, final JComponent parent) { final ErrorInfo ei = new ErrorInfo( "Fehler", "Beim Vorgang ist ein Fehler aufgetreten", null, null, ex, Level.SEVERE, null); JXErrorPane.showDialog(parent, ei); } @Override public void editorClosed(final EditorClosedEvent event) { if (EditorSaveStatus.SAVE_SUCCESS == event.getStatus()) { for (final CidsBean deleteBean : removedFotoBeans) { final String fileName = (String)deleteBean.getProperty(nameProp); try { webdavHelper.deleteFileFromWebDAV(fileName, getConnectionContext()); deleteBean.delete(); } catch (final Exception ex) { LOG.error(ex, ex); showExceptionToUser(ex, this); } } } else { for (final CidsBean deleteBean : removeNewAddedFotoBean) { final String fileName = (String)deleteBean.getProperty(nameProp); try { webdavHelper.deleteFileFromWebDAV(fileName, getConnectionContext()); } catch (final Exception ex) { LOG.error(ex, ex); showExceptionToUser(ex, this); } } } } @Override public boolean prepareForSave() { return true; } @Override public void dispose() { bindingGroup.unbind(); map.getFeatureCollection().removeAllFeatures(); map.dispose(); cidsBean = null; } @Override public ConnectionContext getConnectionContext() { return connectionContext; } //~ Inner Classes ---------------------------------------------------------- /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ final class ImageUploadWorker extends SwingWorker<Collection<CidsBean>, Void> { //~ Instance fields ---------------------------------------------------- private final Collection<File> dokumente; //~ Constructors ------------------------------------------------------- /** * Creates a new ImageUploadWorker object. * * @param dokumente DOCUMENT ME! */ public ImageUploadWorker(final Collection<File> dokumente) { this.dokumente = dokumente; } //~ Methods ------------------------------------------------------------ @Override protected Collection<CidsBean> doInBackground() throws Exception { final Collection<CidsBean> newBeans = new ArrayList<>(); for (final File dokument : dokumente) { webdavHelper.uploadFileToWebDAV(dokument.getName(), dokument, SimpleWebDavPanel.this, getConnectionContext()); final CidsBean newDokument = CidsBean.createNewCidsBeanFromTableName( "WUNDA_BLAU", bildClassName, getConnectionContext()); newDokument.setProperty(nameProp, dokument.getName()); newDokument.setProperty("messstelle", cidsBean.getProperty("id")); newBeans.add(newDokument); } return newBeans; } @Override protected void done() { try { final Collection<CidsBean> newBeans = get(); if (!newBeans.isEmpty()) { final List<CidsBean> oldBeans = cidsBean.getBeanCollectionProperty(beanCollProp); oldBeans.addAll(newBeans); removeNewAddedFotoBean.addAll(newBeans); lstFotos.setSelectedValue(newBeans.iterator().next(), true); } } catch (final InterruptedException ex) { LOG.warn(ex, ex); } catch (final ExecutionException ex) { LOG.error(ex, ex); } } } }
lgpl-3.0
MarkyVasconcelos/Towel
src/com/towel/bean/DefaultFormatter.java
435
package com.towel.bean; /** * Default formatter that returns the same object passed as paramater to the * methods. * * @author Marcos A. Vasconcelos Junior */ public class DefaultFormatter implements Formatter { @Override public Object format(Object obj) { return obj; } @Override public Object parse(Object obj) { return obj; } @Override public String getName() { return "obj_def"; } }
lgpl-3.0
OpenSoftwareSolutions/PDFReporter-Studio
com.jaspersoft.studio.components/src/com/jaspersoft/studio/components/crosstab/model/crosstab/command/wizard/Wrapper.java
2389
/******************************************************************************* * Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com. * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * 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.jaspersoft.studio.components.crosstab.model.crosstab.command.wizard; import net.sf.jasperreports.crosstabs.design.JRDesignCrosstabColumnGroup; import net.sf.jasperreports.crosstabs.design.JRDesignCrosstabRowGroup; public class Wrapper { private Object value; private AgregationFunctionEnum calculation = AgregationFunctionEnum.UNIQUE; private String oldExpText; private String label = null; public Wrapper(Object value) { super(); this.value = value; if (value instanceof JRDesignCrosstabColumnGroup) { JRDesignCrosstabColumnGroup cg = (JRDesignCrosstabColumnGroup) value; oldExpText = cg.getBucket().getExpression().getText(); } else if (value instanceof JRDesignCrosstabRowGroup) { JRDesignCrosstabRowGroup rg = (JRDesignCrosstabRowGroup) value; oldExpText = rg.getBucket().getExpression().getText(); } } public String getOldExpText() { return oldExpText; } public Object getValue() { return value; } public void setCalculation(AgregationFunctionEnum calculation) { this.calculation = calculation; } public AgregationFunctionEnum getCalculation() { return calculation; } @Override public boolean equals(Object obj) { if (obj instanceof Wrapper) return value.equals(((Wrapper) obj).getValue()); return super.equals(obj); } @Override public int hashCode() { return value.hashCode(); } /** * Return the name of the object without any special syntax like $ etc.. * The value comes from the old expression text * which we assume is in the form $?{AAAAAA} * * @return String */ public String getLabel() { String label = getOldExpText(); if (label == null) return ""; // this case should never be true. label = label.substring(3, label.length() - 1); return label; } }
lgpl-3.0
MSRP-OSS/msrp-java
lib/slf4j-1.5.8/slf4j-ext/src/main/java/org/slf4j/profiler/Profiler.java
8096
/* * Copyright (c) 2004-2008 QOS.ch * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.slf4j.profiler; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.Marker; import org.slf4j.MarkerFactory; // + Profiler [BAS] // |-- elapsed time [doX] 0 milliseconds. // |-- elapsed time [doYYYYY] 56 milliseconds. // |--+ Profiler Y // |-- elapsed time [doZ] 21 milliseconds. // |-- elapsed time [doZ] 21 milliseconds. // |-- Total elapsed time [Y] 78 milliseconds. // |-- elapsed time [doZ] 21 milliseconds. // |-- Total elapsed time [BAS] 78 milliseconds. /** * A poor man's profiler to measure the time elapsed performing * some lengthy task. * * @author Ceki G&uuml;lc&uuml; */ public class Profiler implements TimeInstrument { final static String PROFILER_MARKER_NAME = "PROFILER"; final static int MIN_SW_NAME_LENGTH = 24; final static int MIN_SW_ELAPSED_TIME_NUMBER_LENGTH = 9; final String name; final StopWatch globalStopWatch; //List<StopWatch> stopwatchList = new ArrayList<StopWatch>(); List<TimeInstrument> childTimeInstrumentList = new ArrayList<TimeInstrument>(); // optional field ProfilerRegistry profilerRegistry; //optional field Logger logger; public Profiler(String name) { this.name = name; this.globalStopWatch = new StopWatch(name); } public String getName() { return name; } public ProfilerRegistry getProfilerRegistry() { return profilerRegistry; } public void registerWith(ProfilerRegistry profilerRegistry) { if (profilerRegistry == null) { return; } this.profilerRegistry = profilerRegistry; profilerRegistry.put(this); } public Logger getLogger() { return logger; } public void setLogger(Logger logger) { this.logger = logger; } /** * Starts a child stop watch and stops any previously started time instruments. */ public void start(String name) { stopLastTimeInstrument(); StopWatch childSW = new StopWatch(name); childTimeInstrumentList.add(childSW); } public Profiler startNested(String name) { stopLastTimeInstrument(); Profiler nestedProfiler = new Profiler(name); nestedProfiler.registerWith(profilerRegistry); nestedProfiler.setLogger(logger); childTimeInstrumentList.add(nestedProfiler); return nestedProfiler; } TimeInstrument getLastTimeInstrument() { if (childTimeInstrumentList.size() > 0) { return childTimeInstrumentList.get(childTimeInstrumentList.size() - 1); } else { return null; } } void stopLastTimeInstrument() { TimeInstrument last = getLastTimeInstrument(); if (last != null) { last.stop(); } } // void stopNestedProfilers() { // for (Object child : childTimeInstrumentList) { // if (child instanceof Profiler) // ((Profiler) child).stop(); // } // } public long elapsedTime() { return globalStopWatch.elapsedTime(); } public TimeInstrument stop() { stopLastTimeInstrument(); globalStopWatch.stop(); return this; } public TimeInstrumentStatus getStatus() { return globalStopWatch.status; } /** * This method is used in tests. */ void sanityCheck() throws IllegalStateException { if(getStatus() != TimeInstrumentStatus.STOPPED) { throw new IllegalStateException("time instrument ["+getName()+" is not stopped"); } long totalElapsed = globalStopWatch.elapsedTime(); long childTotal = 0; for(TimeInstrument ti: childTimeInstrumentList) { childTotal += ti.elapsedTime(); if(ti.getStatus() != TimeInstrumentStatus.STOPPED) { throw new IllegalStateException("time instrument ["+ti.getName()+" is not stopped"); } if(ti instanceof Profiler) { Profiler nestedProfiler = (Profiler) ti; nestedProfiler.sanityCheck(); } } if(totalElapsed < childTotal) { throw new IllegalStateException("children have a higher accumulated elapsed time"); } } static String TOP_PROFILER_FIRST_PREFIX = "+"; static String NESTED_PROFILER_FIRST_PREFIX = "|---+"; static String TOTAL_ELAPSED = " Total "; static String SUBTOTAL_ELAPSED = " Subtotal "; static String ELAPSED_TIME = " elapsed time "; public void print() { System.out.println(toString()); } @Override public String toString() { DurationUnit du = Util.selectDurationUnitForDisplay(globalStopWatch); return buildProfilerString(du, TOP_PROFILER_FIRST_PREFIX, TOTAL_ELAPSED, ""); } public void log() { Marker profilerMarker = MarkerFactory.getMarker(PROFILER_MARKER_NAME); if(logger == null) { throw new NullPointerException("If you invoke the log() method, then you must associate a logger with this profiler."); } if (logger.isDebugEnabled(profilerMarker)) { DurationUnit du = Util.selectDurationUnitForDisplay(globalStopWatch); String r = buildProfilerString(du, TOP_PROFILER_FIRST_PREFIX, TOTAL_ELAPSED, ""); logger.debug(profilerMarker, SpacePadder.LINE_SEP+r); } } private String buildProfilerString(DurationUnit du, String firstPrefix, String label, String indentation) { StringBuffer buf = new StringBuffer(); buf.append(firstPrefix); buf.append(" Profiler ["); buf.append(name); buf.append("]"); buf.append(SpacePadder.LINE_SEP); for (TimeInstrument child : childTimeInstrumentList) { if (child instanceof StopWatch) { buildStopWatchString(buf, du, ELAPSED_TIME, indentation, (StopWatch) child); } else if (child instanceof Profiler) { Profiler profiler = (Profiler) child; String subString = profiler .buildProfilerString(du, NESTED_PROFILER_FIRST_PREFIX, SUBTOTAL_ELAPSED, indentation + " "); buf.append(subString); buildStopWatchString(buf, du, ELAPSED_TIME, indentation, profiler.globalStopWatch); } } buildStopWatchString(buf, du, label, indentation, globalStopWatch); return buf.toString(); } private static void buildStopWatchString(StringBuffer buf, DurationUnit du, String prefix, String indentation, StopWatch sw) { buf.append(indentation); buf.append("|--"); buf.append(prefix); SpacePadder.leftPad(buf, "[" + sw.getName() + "]", MIN_SW_NAME_LENGTH); buf.append(" "); String timeStr = Util.durationInDurationUnitsAsStr(sw.elapsedTime(), du); SpacePadder.leftPad(buf, timeStr, MIN_SW_ELAPSED_TIME_NUMBER_LENGTH); buf.append(" "); Util.appendDurationUnitAsStr(buf, du); buf.append(SpacePadder.LINE_SEP); } }
lgpl-3.0
qspin/qtaste
kernel/src/main/java/com/qspin/qtaste/ui/treetable/AbstractCellEditor.java
3071
/* Copyright 2007-2009 QSpin - www.qspin.be This file is part of QTaste framework. QTaste is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QTaste is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with QTaste. If not, see <http://www.gnu.org/licenses/>. */ package com.qspin.qtaste.ui.treetable; import java.util.EventObject; import javax.swing.CellEditor; import javax.swing.event.CellEditorListener; import javax.swing.event.ChangeEvent; import javax.swing.event.EventListenerList; /** * @author vdubois */ public class AbstractCellEditor implements CellEditor { protected EventListenerList listenerList = new EventListenerList(); public Object getCellEditorValue() { return null; } public boolean isCellEditable(EventObject e) { return true; } public boolean shouldSelectCell(EventObject anEvent) { return false; } public boolean stopCellEditing() { return true; } public void cancelCellEditing() { } public void addCellEditorListener(CellEditorListener l) { listenerList.add(CellEditorListener.class, l); } public void removeCellEditorListener(CellEditorListener l) { listenerList.remove(CellEditorListener.class, l); } /** * Notify all listeners that have registered interest for * notification on this event type. * * @see EventListenerList */ protected void fireEditingStopped() { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == CellEditorListener.class) { ((CellEditorListener) listeners[i + 1]).editingStopped(new ChangeEvent(this)); } } } /** * Notify all listeners that have registered interest for * notification on this event type. * * @see EventListenerList */ protected void fireEditingCanceled() { // Guaranteed to return a non-null array Object[] listeners = listenerList.getListenerList(); // Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == CellEditorListener.class) { ((CellEditorListener) listeners[i + 1]).editingCanceled(new ChangeEvent(this)); } } } }
lgpl-3.0
WangDaYeeeeee/GeometricWeather
app/src/main/java/wangdaye/com/geometricweather/common/retrofit/TLSCompactHelper.java
4099
package wangdaye.com.geometricweather.common.retrofit; import android.os.Build; import android.util.Log; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import okhttp3.ConnectionSpec; import okhttp3.OkHttpClient; import okhttp3.TlsVersion; import okhttp3.internal.Util; /** * TLS compact service. * */ public class TLSCompactHelper { /** * Enables TLS v1.2 when creating SSLSockets. * <p/> * For some reason, android supports TLS v1.2 from API 16, but enables it by * default only from API 20. * @link https://developer.android.com/reference/javax/net/ssl/SSLSocket.html * @see SSLSocketFactory */ private static class Tls12SocketFactory extends SSLSocketFactory { private static final String[] TLS_V12_ONLY = {"TLSv1.2"}; private final SSLSocketFactory delegate; Tls12SocketFactory(SSLSocketFactory base) { this.delegate = base; } @Override public String[] getDefaultCipherSuites() { return delegate.getDefaultCipherSuites(); } @Override public String[] getSupportedCipherSuites() { return delegate.getSupportedCipherSuites(); } @Override public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { return patch(delegate.createSocket(s, host, port, autoClose)); } @Override public Socket createSocket(String host, int port) throws IOException { return patch(delegate.createSocket(host, port)); } @Override public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException { return patch(delegate.createSocket(host, port, localHost, localPort)); } @Override public Socket createSocket(InetAddress host, int port) throws IOException { return patch(delegate.createSocket(host, port)); } @Override public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { return patch(delegate.createSocket(address, port, localAddress, localPort)); } private Socket patch(Socket s) { if (s instanceof SSLSocket) { ((SSLSocket) s).setEnabledProtocols(TLS_V12_ONLY); } return s; } } public static OkHttpClient.Builder getClientBuilder() { OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(45, TimeUnit.SECONDS); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { try { SSLContext sc = SSLContext.getInstance("TLSv1.2"); sc.init(null, null, null); builder.sslSocketFactory( new Tls12SocketFactory(sc.getSocketFactory()), Util.platformTrustManager()); ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .tlsVersions(TlsVersion.TLS_1_2) .build(); List<ConnectionSpec> specs = new ArrayList<>(); specs.add(cs); specs.add(ConnectionSpec.COMPATIBLE_TLS); specs.add(ConnectionSpec.CLEARTEXT); builder.connectionSpecs(specs) .followRedirects(true) .followSslRedirects(true) .retryOnConnectionFailure(true) .cache(null); } catch (Exception e) { Log.e("OkHttpTLSCompat", "Error while setting TLS 1.2", e); } } return builder; } }
lgpl-3.0
tliron/sincerity
components/sincerity/source/com/threecrickets/sincerity/logging/MongoDbManager.java
8434
/** * Copyright 2011-2017 Three Crickets LLC. * <p> * The contents of this file are subject to the terms of the LGPL version 3.0: * http://www.gnu.org/copyleft/lesser.html * <p> * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly from Three Crickets * at http://threecrickets.com/ */ package com.threecrickets.sincerity.logging; import java.util.Date; import java.util.Map; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.ThreadContext.ContextStack; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.appender.AppenderLoggingException; import org.apache.logging.log4j.core.appender.ManagerFactory; import org.apache.logging.log4j.core.appender.db.AbstractDatabaseManager; import org.apache.logging.log4j.message.Message; import org.bson.Document; import com.mongodb.BasicDBList; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.MongoException; import com.mongodb.WriteConcern; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; /** * A Log4j database manager for MongoDB. * <p> * <b>Warning:</b> Because the MongoDB driver itself emits log messages, you * might cause recursion here that would lead to hangs and timeouts. The easiest * solution is to simply disable its logging via your Log4j configuration: just * set the <code>org.mongodb.driver</code> logger to level {@link Level#OFF}. * * @author Tal Liron */ public class MongoDbManager extends AbstractDatabaseManager { // // Static operations // /** * Creates a MongoDB manager for use within the {@link MongoDbAppender}, or * returns a suitable one if it already exists. * * @param name * The name of the manager, which should include connection details * and hashed passwords where possible. * @param bufferSize * The size of the log event buffer. * @param uri * The MongoDB URI (see {@link MongoClientURI}) (not used if "client" * is specified) * @param client * The MongoDB client (not used if "uri" is specified) * @param dbName * The MongoDB database name * @param collectionName * The MongoDB collection name * @param writeConcernName * The MongoDB write concern (see * {@link WriteConcern#valueOf(String)}) * @return a new or existing MongoDB manager as applicable. */ public static MongoDbManager getMongoDbManager( String name, int bufferSize, String uri, MongoClient client, String dbName, String collectionName, String writeConcernName ) { return AbstractDatabaseManager.getManager( name, new FactoryData( bufferSize, uri, client, dbName, collectionName, writeConcernName ), FACTORY ); } // ////////////////////////////////////////////////////////////////////////// // Protected // // Construction // protected MongoDbManager( String name, int bufferSize, String uri, MongoClient client, String databaseName, String collectionName, String writeConcernName ) { super( name, bufferSize ); this.uri = uri; this.client = client; this.databaseName = databaseName; this.collectionName = collectionName; this.writeConcernName = writeConcernName; } // // AbstractDatabaseManager // @Override protected void startupInternal() throws Exception { if( collection != null ) return; client = null; database = null; collection = null; MongoClientURI uri; try { if( this.uri == null ) uri = new MongoClientURI( this.uri ); else uri = new MongoClientURI( "mongodb://localhost:27017/" ); } catch( IllegalArgumentException x ) { throw new AppenderLoggingException( "Can't parse MongoDB uri: " + this.uri ); } try { client = new MongoClient( uri ); } catch( MongoException x ) { throw new AppenderLoggingException( "Can't create MongoDB client: " + uri ); } try { database = client.getDatabase( databaseName ); } catch( MongoException x ) { client.close(); client = null; throw new AppenderLoggingException( "Can't access MongoDB database: " + databaseName ); } try { collection = database.getCollection( collectionName ); } catch( MongoException x ) { client.close(); client = null; database = null; throw new AppenderLoggingException( "Can't access MongoDB collection: " + collectionName ); } if( writeConcernName != null ) { WriteConcern writeConcern = WriteConcern.valueOf( writeConcernName ); if( writeConcern == null ) throw new AppenderLoggingException( "Unsupported MongoDB write concern: " + writeConcernName ); collection = collection.withWriteConcern( writeConcern ); } } @Override protected void shutdownInternal() throws Exception { if( client != null ) client.close(); client = null; database = null; collection = null; } @Override protected void connectAndStart() { } @Override protected void writeInternal( LogEvent event ) { if( collection == null ) throw new AppenderLoggingException( "Not connected to MongoDB" ); Document o = new Document(); o.put( "timestamp", new Date( event.getTimeMillis() ) ); o.put( "logger", event.getLoggerName() ); Level level = event.getLevel(); if( level != null ) o.put( "level", level.name() ); Marker marker = event.getMarker(); if( marker != null ) o.put( "marker", marker.getName() ); Message message = event.getMessage(); if( message != null ) o.put( "message", message.getFormattedMessage() ); StackTraceElement eventSource = event.getSource(); if( eventSource != null ) { Document source = new Document(); source.put( "class", eventSource.getClassName() ); source.put( "method", eventSource.getMethodName() ); source.put( "file", eventSource.getFileName() ); source.put( "line", eventSource.getLineNumber() ); o.put( "source", source ); } Document thread = new Document(); thread.put( "name", event.getThreadName() ); Map<String, String> eventContextMap = event.getContextMap(); if( eventContextMap != null ) { Document contextMap = new Document(); for( Map.Entry<String, String> entry : eventContextMap.entrySet() ) contextMap.put( entry.getKey(), entry.getValue() ); thread.put( "contextMap", contextMap ); } ContextStack eventContextStack = event.getContextStack(); if( eventContextStack != null ) { BasicDBList contextStack = new BasicDBList(); for( String entry : eventContextStack ) contextStack.add( entry ); thread.put( "contextStack", contextStack ); } o.put( "thread", thread ); try { collection.insertOne( o ); } catch( MongoException e ) { throw new AppenderLoggingException( "Can't write to MongoDB", e ); } } @Override protected void commitAndClose() { } // ////////////////////////////////////////////////////////////////////////// // Private private static final MongoDbManagerFactory FACTORY = new MongoDbManagerFactory(); private final String uri; private final String databaseName; private final String collectionName; private final String writeConcernName; private MongoClient client; private MongoDatabase database; private MongoCollection<Document> collection; /** * Creates managers. */ private static final class MongoDbManagerFactory implements ManagerFactory<MongoDbManager, FactoryData> { @Override public MongoDbManager createManager( final String name, final FactoryData data ) { return new MongoDbManager( name, data.getBufferSize(), data.uri, data.client, data.dbName, data.collectionName, data.writeConcernName ); } } /** * Encapsulates data that {@link MongoDbManagerFactory} uses to create * managers. */ private static final class FactoryData extends AbstractDatabaseManager.AbstractFactoryData { protected FactoryData( final int bufferSize, String uri, MongoClient client, String dbName, String collectionName, String writeConcernName ) { super( bufferSize ); this.uri = uri; this.client = client; this.dbName = dbName; this.collectionName = collectionName; this.writeConcernName = writeConcernName; } private final String uri; private final MongoClient client; private final String dbName; private final String collectionName; private final String writeConcernName; } }
lgpl-3.0
rmage/gnvc-ims
stratchpad/org/apache/poi/hsmf/datatypes/StringChunk.java
4566
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.apache.poi.hsmf.datatypes; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import org.apache.poi.hsmf.datatypes.Types.MAPIType; import org.apache.poi.util.IOUtils; import org.apache.poi.util.StringUtil; /** * A Chunk made up of a single string. */ public class StringChunk extends Chunk { private static final String DEFAULT_ENCODING = "CP1252"; private String encoding7Bit = DEFAULT_ENCODING; private byte[] rawValue; private String value; /** * Creates a String Chunk. */ public StringChunk(String namePrefix, int chunkId, MAPIType type) { super(namePrefix, chunkId, type); } /** * Create a String Chunk, with the specified * type. */ public StringChunk(int chunkId, MAPIType type) { super(chunkId, type); } /** * Returns the Encoding that will be used to * decode any "7 bit" (non unicode) data. * Most files default to CP1252 */ public String get7BitEncoding() { return encoding7Bit; } /** * Sets the Encoding that will be used to * decode any "7 bit" (non unicode) data. * This doesn't appear to be stored anywhere * specific in the file, so you may need * to guess by looking at headers etc */ public void set7BitEncoding(String encoding) { this.encoding7Bit = encoding; // Re-read the String if we're a 7 bit one if(type == Types.ASCII_STRING) { parseString(); } } public void readValue(InputStream value) throws IOException { rawValue = IOUtils.toByteArray(value); parseString(); } private void parseString() { String tmpValue; if (type == Types.ASCII_STRING) { tmpValue = parseAs7BitData(rawValue, encoding7Bit); } else if (type == Types.UNICODE_STRING) { tmpValue = StringUtil.getFromUnicodeLE(rawValue); } else { throw new IllegalArgumentException("Invalid type " + type + " for String Chunk"); } // Clean up this.value = tmpValue.replace("\0", ""); } public void writeValue(OutputStream out) throws IOException { out.write(rawValue); } private void storeString() { if (type == Types.ASCII_STRING) { try { rawValue = value.getBytes(encoding7Bit); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Encoding not found - " + encoding7Bit, e); } } else if (type == Types.UNICODE_STRING) { rawValue = new byte[value.length()*2]; StringUtil.putUnicodeLE(value, rawValue, 0); } else { throw new IllegalArgumentException("Invalid type " + type + " for String Chunk"); } } /** * Returns the Text value of the chunk */ public String getValue() { return this.value; } public byte[] getRawValue() { return this.rawValue; } public void setValue(String str) { this.value = str; storeString(); } public String toString() { return this.value; } /** * Parses as non-unicode, supposedly 7 bit CP1252 data * and returns the string that that yields. */ protected static String parseAs7BitData(byte[] data) { return parseAs7BitData(data, DEFAULT_ENCODING); } /** * Parses as non-unicode, supposedly 7 bit data * and returns the string that that yields. */ protected static String parseAs7BitData(byte[] data, String encoding) { try { return new String(data, encoding); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Encoding not found - " + encoding, e); } } }
lgpl-3.0
TobiasMende/CASi
src/de/uniluebeck/imis/casi/simulation/model/mackActions/GoAndWorkOnDesktop.java
1654
/* CASi Context Awareness Simulation Software * Copyright (C) 2011 2012 Moritz Bürger, Marvin Frick, Tobias Mende * * This program is free software. It is licensed under the * GNU Lesser General Public License with one clarification. * * You should have received a copy of the * GNU Lesser General Public License along with this program. * See the LICENSE.txt file in this projects root folder or visit * <http://www.gnu.org/licenses/lgpl.html> for more details. */ package de.uniluebeck.imis.casi.simulation.model.mackActions; import de.uniluebeck.imis.casi.simulation.model.actionHandling.ComplexAction; import de.uniluebeck.imis.casi.simulation.model.actions.Move; import de.uniluebeck.imis.casi.simulation.model.mackComponents.Desktop; /** * This action lets an agent run to his desktop and work there for a given time * with given parameters * * @author Marvin Frick * */ public class GoAndWorkOnDesktop extends ComplexAction { /** * the serialization id */ private static final long serialVersionUID = 3732350423378040656L; /** * Creates a new workOnDesktop action after going to the agents desktop * * @param desktop * the desktop to go to * @param program * what program to work with * @param frequency * what frequency to work at * @param duration * the duration how long to work there */ public GoAndWorkOnDesktop(Desktop desktop, Desktop.Program program, Desktop.Frequency frequency, int duration) { super(); addSubAction(new Move(desktop)); addSubAction(new WorkOnDesktop(desktop, program, frequency, duration)); } }
lgpl-3.0
translab-cic/translab
translab-core/src/main/java/br/unb/translab/core/data/anac/vra/loader/AirlineDataLoader.java
2948
/** * Copyright (C) 2015 the original author or authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, * 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 br.unb.translab.core.data.anac.vra.loader; import io.dohko.jdbi.exceptions.AnyThrow; import java.io.File; import java.io.IOException; import java.util.List; import javax.annotation.Nonnull; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.WorkbookSettings; import jxl.read.biff.BiffException; import br.unb.translab.core.data.anac.vra.loader.DataLoader; import br.unb.translab.core.domain.Airline; import br.unb.translab.core.domain.repository.AirlineRepository; import static com.google.common.collect.Lists.*; import static com.google.common.base.Preconditions.*; import com.google.common.base.Function; public class AirlineDataLoader implements Function<File, List<Airline>>, DataLoader { private final AirlineRepository airlineRepository; public AirlineDataLoader(@Nonnull AirlineRepository repository) { this.airlineRepository = repository; } @Override public List<Airline> apply(@Nonnull File input) { checkNotNull(input); final List<Airline> airlines = newArrayList(); Workbook workbook = null; final WorkbookSettings settings = new WorkbookSettings(); settings.setEncoding(System.getProperty("anac.vra.data.encoding", System.getProperty("jxl.encoding", "ISO-8859-1"))); try { workbook = Workbook.getWorkbook(input, settings); Sheet sheet = workbook.getSheet(0); for (int i = 4; i < sheet.getRows(); i++) { Cell[] row = sheet.getRow(i); Airline airline = new Airline().setName(row[1].getContents().trim()).setOaci(row[0].getContents().trim()); airlines.add(airline); } } catch (BiffException | IOException exception) { AnyThrow.throwUncheked(exception); } finally { if (workbook != null) { workbook.close(); } } return airlines; } @Override public void load(File file) throws Exception { checkNotNull(file); this.airlineRepository.insert(this.apply(file)); } }
lgpl-3.0
SmithsModding/SmithsCore
src/com/smithsmodding/smithscore/util/common/Pair.java
4999
/* * Copyright (c) 2015. * * Copyrighted by SmithsModding according to the project License */ package com.smithsmodding.smithscore.util.common; import java.util.*; public class Pair<K, V> { K iObjectOne; V iObjectTwo; public Pair(K pItemOne, V pItemTwo) { iObjectOne = pItemOne; iObjectTwo = pItemTwo; } public K getKey() { return iObjectOne; } public V getValue() { return iObjectTwo; } /** * Returns a hash code value for the object. This method is * supported for the benefit of hash tables such as those provided by * {@link HashMap}. * <p/> * The general contract of {@code hashCode} is: * <ul> * <li>Whenever it is invoked on the same object more than once during * an execution of a Java application, the {@code hashCode} method * must consistently return the same integer, provided no information * used in {@code equals} comparisons on the object is modified. * This integer need not remain consistent from one execution of an * application to another execution of the same application. * <li>If two objects are equal according to the {@code equals(Object)} * method, then calling the {@code hashCode} method on each of * the two objects must produce the same integer result. * <li>It is <em>not</em> required that if two objects are unequal * according to the {@link Object#equals(Object)} * method, then calling the {@code hashCode} method on each of the * two objects must produce distinct integer results. However, the * programmer should be aware that producing distinct integer results * for unequal objects may improve the performance of hash tables. * </ul> * <p/> * As much as is reasonably practical, the hashCode method defined by * class {@code Object} does return distinct integers for distinct * objects. (This is typically implemented by converting the internal * address of the object into an integer, but this implementation * technique is not required by the * Java<font size="-2"><sup>TM</sup></font> programming language.) * * @return a hash code value for this object. * @see Object#equals(Object) * @see System#identityHashCode */ @Override public int hashCode() { return iObjectOne.hashCode() + iObjectTwo.hashCode(); } /** * Indicates whether some other object is "equal to" this one. * <p/> * The {@code equals} method implements an equivalence relation * on non-null object references: * <ul> * <li>It is <i>reflexive</i>: for any non-null reference value * {@code x}, {@code x.equals(x)} should return * {@code true}. * <li>It is <i>symmetric</i>: for any non-null reference values * {@code x} and {@code y}, {@code x.equals(y)} * should return {@code true} if and only if * {@code y.equals(x)} returns {@code true}. * <li>It is <i>transitive</i>: for any non-null reference values * {@code x}, {@code y}, and {@code z}, if * {@code x.equals(y)} returns {@code true} and * {@code y.equals(z)} returns {@code true}, then * {@code x.equals(z)} should return {@code true}. * <li>It is <i>consistent</i>: for any non-null reference values * {@code x} and {@code y}, multiple invocations of * {@code x.equals(y)} consistently return {@code true} * or consistently return {@code false}, provided no * information used in {@code equals} comparisons on the * objects is modified. * <li>For any non-null reference value {@code x}, * {@code x.equals(null)} should return {@code false}. * </ul> * <p/> * The {@code equals} method for class {@code Object} implements * the most discriminating possible equivalence relation on objects; * that is, for any non-null reference values {@code x} and * {@code y}, this method returns {@code true} if and only * if {@code x} and {@code y} refer to the same object * ({@code x == y} has the value {@code true}). * <p/> * Note that it is generally necessary to override the {@code hashCode} * method whenever this method is overridden, so as to maintain the * general contract for the {@code hashCode} method, which states * that equal objects must have equal hash codes. * * @param obj the reference object with which to compare. * @return {@code true} if this object is the same as the obj * argument; {@code false} otherwise. * @see #hashCode() * @see HashMap */ @Override public boolean equals(Object obj) { if (!(obj instanceof Pair)) return false; try { Pair<K, V> tOtherPair = (Pair<K, V>) obj; return tOtherPair.iObjectTwo.equals(iObjectTwo) && tOtherPair.iObjectOne.equals(iObjectOne); } catch (Exception ex) { return false; } } }
lgpl-3.0