code
stringlengths
5
1.04M
repo_name
stringlengths
7
108
path
stringlengths
6
299
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1.04M
package com.intuit.tank.httpclient4; /* * #%L * Intuit Tank Agent (apiharness) * %% * Copyright (C) 2011 - 2015 Intuit Inc. * %% * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * #L% */ import java.io.IOException; import java.io.InputStream; import java.net.SocketException; import java.net.UnknownHostException; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import javax.annotation.Nonnull; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.NameValuePair; import org.apache.http.auth.AuthScope; import org.apache.http.auth.NTCredentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.UserTokenHandler; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpOptions; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.cookie.ClientCookie; import org.apache.http.cookie.Cookie; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.intuit.tank.http.AuthCredentials; import com.intuit.tank.http.AuthScheme; import com.intuit.tank.http.BaseRequest; import com.intuit.tank.http.BaseResponse; import com.intuit.tank.http.TankCookie; import com.intuit.tank.http.TankHttpClient; import com.intuit.tank.http.TankHttpUtil; import com.intuit.tank.http.TankHttpUtil.PartHolder; import com.intuit.tank.logging.LogEventType; import com.intuit.tank.vm.settings.AgentConfig; public class TankHttpClient4 implements TankHttpClient { private static final Logger LOG = LogManager.getLogger(TankHttpClient4.class); private CloseableHttpClient httpclient; private HttpClientContext context; /** * no-arg constructor for client */ public TankHttpClient4() { RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(30000) .setConnectTimeout(30000) .setCircularRedirectsAllowed(true) .setAuthenticationEnabled(true) .setRedirectsEnabled(true) .setCookieSpec(CookieSpecs.STANDARD) .setMaxRedirects(100) .build(); // Make sure the same context is used to execute logically related // requests context = HttpClientContext.create(); context.setCredentialsProvider(new BasicCredentialsProvider()); context.setUserToken(UUID.randomUUID()); context.setCookieStore(new BasicCookieStore()); context.setRequestConfig(requestConfig); } public Object createHttpClient() { UserTokenHandler userTokenHandler = (httpContext) -> httpContext.getAttribute(HttpClientContext.USER_TOKEN); // default this implementation will create no more than than 2 concurrent connections per given route and no more 20 connections in total return HttpClients.custom() .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) .setUserTokenHandler(userTokenHandler) .evictIdleConnections(1L, TimeUnit.MINUTES) .evictExpiredConnections() .setMaxConnPerRoute(10240) .setMaxConnTotal(20480) .build(); } public void setHttpClient(Object httpClient) { if (httpClient instanceof CloseableHttpClient) { this.httpclient = (CloseableHttpClient) httpClient; } else { this.httpclient = (CloseableHttpClient) createHttpClient(); } } public void setConnectionTimeout(long connectionTimeout) { RequestConfig requestConfig = context.getRequestConfig().custom().setConnectTimeout((int) connectionTimeout).build(); context.setRequestConfig(requestConfig); } /* * (non-Javadoc) * * @see * com.intuit.tank.httpclient3.TankHttpClient#doGet(com.intuit.tank.http. * BaseRequest) */ @Override public void doGet(BaseRequest request) { HttpGet httpget = new HttpGet(request.getRequestUrl()); sendRequest(request, httpget, request.getBody()); } /* * (non-Javadoc) * * @see * com.intuit.tank.httpclient3.TankHttpClient#doPut(com.intuit.tank.http. * BaseRequest) */ @Override public void doPut(BaseRequest request) { HttpPut httpput = new HttpPut(request.getRequestUrl()); // Multiple calls can be expensive, so get it once String requestBody = request.getBody(); HttpEntity entity = new StringEntity(requestBody, ContentType.create(request.getContentType(), request.getContentTypeCharSet())); httpput.setEntity(entity); sendRequest(request, httpput, requestBody); } /* * (non-Javadoc) * * @see * com.intuit.tank.httpclient3.TankHttpClient#doDelete(com.intuit.tank.http. * BaseRequest) */ @Override public void doDelete(BaseRequest request) { HttpDelete httpdelete = new HttpDelete(request.getRequestUrl()); // Multiple calls can be expensive, so get it once String requestBody = request.getBody(); String type = request.getHeaderInformation().get("Content-Type"); if (StringUtils.isBlank(type)) { request.getHeaderInformation().put("Content-Type", "application/json"); } sendRequest(request, httpdelete, requestBody); } /* * (non-Javadoc) * * @see * com.intuit.tank.httpclient3.TankHttpClient#doOptions(com.intuit.tank.http. * BaseRequest) */ @Override public void doOptions(BaseRequest request) { HttpOptions httpoptions = new HttpOptions(request.getRequestUrl()); // Multiple calls can be expensive, so get it once String requestBody = request.getBody(); String type = request.getHeaderInformation().get("Content-Type"); if (StringUtils.isBlank(type)) { request.getHeaderInformation().put("Content-Type", "application/json"); } sendRequest(request, httpoptions, requestBody); } /* * (non-Javadoc) * * @see * com.intuit.tank.httpclient3.TankHttpClient#doPost(com.intuit.tank.http. * BaseRequest) */ @Override public void doPost(BaseRequest request) { HttpPost httppost = new HttpPost(request.getRequestUrl()); String requestBody = request.getBody(); HttpEntity entity = null; if (request.getContentType().toLowerCase().startsWith(BaseRequest.CONTENT_TYPE_MULTIPART)) { entity = buildParts(request); } else { entity = new StringEntity(requestBody, ContentType.create(request.getContentType(), request.getContentTypeCharSet())); } httppost.setEntity(entity); sendRequest(request, httppost, requestBody); } /* * (non-Javadoc) * * @see * com.intuit.tank.httpclient3.TankHttpClient#addAuth(com.intuit.tank.http. * AuthCredentials) */ @Override public void addAuth(AuthCredentials creds) { String host = (StringUtils.isBlank(creds.getHost()) || "*".equals(creds.getHost())) ? AuthScope.ANY_HOST : creds.getHost(); String realm = (StringUtils.isBlank(creds.getRealm()) || "*".equals(creds.getRealm())) ? AuthScope.ANY_REALM : creds.getRealm(); int port = NumberUtils.toInt(creds.getPortString(), AuthScope.ANY_PORT); String scheme = creds.getScheme() != null ? creds.getScheme().getRepresentation() : AuthScope.ANY_SCHEME; AuthScope scope = new AuthScope(host, port, realm, scheme); if (AuthScheme.NTLM == creds.getScheme()) { context.getCredentialsProvider().setCredentials(scope, new NTCredentials(creds.getUserName(), creds.getPassword(), "tank-test", creds.getRealm())); } else { context.getCredentialsProvider().setCredentials(scope, new UsernamePasswordCredentials(creds.getUserName(), creds.getPassword())); } } /* * (non-Javadoc) * * @see com.intuit.tank.httpclient3.TankHttpClient#clearSession() */ @Override public void clearSession() { context.getCookieStore().clear(); } /** * */ @Override public void setCookie(TankCookie tankCookie) { BasicClientCookie cookie = new BasicClientCookie(tankCookie.getName(), tankCookie.getValue()); // Set effective domain and path attributes cookie.setDomain(tankCookie.getDomain()); cookie.setPath(tankCookie.getPath()); // Set attributes exactly as sent by the server cookie.setAttribute(ClientCookie.PATH_ATTR, tankCookie.getPath()); cookie.setAttribute(ClientCookie.DOMAIN_ATTR, tankCookie.getDomain()); context.getCookieStore().addCookie(cookie); } @Override public void setProxy(String proxyhost, int proxyport) { if (StringUtils.isNotBlank(proxyhost)) { HttpHost proxy = new HttpHost(proxyhost, proxyport); RequestConfig requestConfig = context.getRequestConfig().custom().setProxy(proxy).build(); context.setRequestConfig(requestConfig); } else { RequestConfig requestConfig = context.getRequestConfig().custom().setProxy(null).build(); context.setRequestConfig(requestConfig); } } private void sendRequest(BaseRequest request, @Nonnull HttpRequestBase method, String requestBody) { long waitTime = 0L; String uri = method.getURI().toString(); LOG.debug(request.getLogUtil().getLogMessage("About to " + method.getMethod() + " request to " + uri + " with requestBody " + requestBody, LogEventType.Informational)); List<String> cookies = new ArrayList<String>(); if (context.getCookieStore().getCookies() != null) { cookies = context.getCookieStore().getCookies().stream().map(cookie -> "REQUEST COOKIE: " + cookie.toString()).collect(Collectors.toList()); } request.logRequest(uri, requestBody, method.getMethod(), request.getHeaderInformation(), cookies, false); setHeaders(request, method, request.getHeaderInformation()); long startTime = System.currentTimeMillis(); request.setTimestamp(new Date(startTime)); try ( CloseableHttpResponse response = httpclient.execute(method, context) ) { // read response body byte[] responseBody = new byte[0]; // check for no content headers if (response.getStatusLine().getStatusCode() != 203 && response.getStatusLine().getStatusCode() != 202 && response.getStatusLine().getStatusCode() != 204) { try ( InputStream is = response.getEntity().getContent() ) { responseBody = IOUtils.toByteArray(is); } catch (IOException | NullPointerException e) { LOG.warn(request.getLogUtil().getLogMessage("could not get response body: " + e)); } } waitTime = System.currentTimeMillis() - startTime; processResponse(responseBody, waitTime, request, response.getStatusLine().getReasonPhrase(), response.getStatusLine().getStatusCode(), response.getAllHeaders()); } catch (UnknownHostException uhex) { LOG.error(request.getLogUtil().getLogMessage("UnknownHostException to url: " + uri + " | error: " + uhex.toString(), LogEventType.IO), uhex); } catch (SocketException sex) { LOG.error(request.getLogUtil().getLogMessage("SocketException to url: " + uri + " | error: " + sex.toString(), LogEventType.IO), sex); } catch (Exception ex) { LOG.error(request.getLogUtil().getLogMessage("Could not do " + method.getMethod() + " to url " + uri + " | error: " + ex.toString(), LogEventType.IO), ex); throw new RuntimeException(ex); } finally { try { method.releaseConnection(); } catch (Exception e) { LOG.warn("Could not release connection: " + e, e); } if (method.getMethod().equalsIgnoreCase("post") && request.getLogUtil().getAgentConfig().getLogPostResponse()) { LOG.info(request.getLogUtil().getLogMessage( "Response from POST to " + request.getRequestUrl() + " got status code " + request.getResponse().getHttpCode() + " BODY { " + request.getResponse().getBody() + " }", LogEventType.Informational)); } } if (waitTime != 0) { doWaitDueToLongResponse(request, waitTime, uri); } } /** * Wait for the amount of time it took to get a response from the system if * the response time is over some threshold specified in the properties * file. This will ensure users don't bunch up together after a blip on the * system under test * * @param responseTime * - response time of the request; this will also be the time to * sleep * @param uri */ private void doWaitDueToLongResponse(BaseRequest request, long responseTime, String uri) { try { AgentConfig config = request.getLogUtil().getAgentConfig(); long maxAgentResponseTime = config.getMaxAgentResponseTime(); if (maxAgentResponseTime < responseTime) { long waitTime = Math.min(config.getMaxAgentWaitTime(), responseTime); LOG.warn(request.getLogUtil().getLogMessage("Response time to slow | delaying " + waitTime + " ms | url --> " + uri, LogEventType.Script)); Thread.sleep(waitTime); } } catch (InterruptedException e) { LOG.warn("Interrupted", e); } } /** * Process the response data */ private void processResponse(byte[] bResponse, long waitTime, BaseRequest request, String message, int httpCode, Header[] headers) { BaseResponse response = request.getResponse(); try { if (response == null) { // Get response header information String contentType = Arrays.stream(headers).filter( h -> "ContentType".equalsIgnoreCase(h.getName())).findFirst().map(NameValuePair::getValue).orElse(""); response = TankHttpUtil.newResponseObject(contentType); request.setResponse(response); } // Get response detail information response.setHttpMessage(message); response.setHttpCode(httpCode); // Get response header information for (Header header : headers) { response.setHeader(header.getName(), header.getValue()); } if (context.getCookieStore().getCookies() != null) { for (Cookie cookie : context.getCookieStore().getCookies()) { response.setCookie(cookie.getName(), cookie.getValue()); } } response.setResponseTime(waitTime); response.setResponseBody(bResponse); } catch (Exception ex) { LOG.warn("Unable to get response: " + ex.getMessage()); } finally { response.logResponse(); } } /** * Set all the header keys * * @param request * @param method * @param headerInformation */ @SuppressWarnings("rawtypes") private void setHeaders(BaseRequest request, HttpRequestBase method, HashMap<String, String> headerInformation) { try { Set set = headerInformation.entrySet(); for (Object aSet : set) { Map.Entry mapEntry = (Map.Entry) aSet; method.setHeader((String) mapEntry.getKey(), (String) mapEntry.getValue()); } } catch (Exception ex) { LOG.warn(request.getLogUtil().getLogMessage("Unable to set header: " + ex.getMessage(), LogEventType.System)); } } private HttpEntity buildParts(BaseRequest request) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (PartHolder h : TankHttpUtil.getPartsFromBody(request)) { if (h.getFileName() == null) { if (h.isContentTypeSet()) { builder.addTextBody(h.getPartName(), h.getBodyAsString(), ContentType.create(h.getContentType())); } else { builder.addTextBody(h.getPartName(), h.getBodyAsString()); } } else { if (h.isContentTypeSet()) { builder.addBinaryBody(h.getPartName(), h.getBody(), ContentType.create(h.getContentType()), h.getFileName()); } else { builder.addBinaryBody(h.getFileName(), h.getBody()); } } } return builder.build(); } }
intuit/Tank
agent/http_client_4/src/main/java/com/intuit/tank/httpclient4/TankHttpClient4.java
Java
epl-1.0
18,157
/******************************************************************************* * Copyright (c) 2001, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Jens Lukowski/Innoopract - initial renaming/restructuring * *******************************************************************************/ package org.eclipse.wst.sse.core.internal.cleanup; public interface StructuredContentCleanupHandler { IStructuredCleanupProcessor getCleanupProcessor(String contentType); void setCleanupProcessor(IStructuredCleanupProcessor cleanupProcessor, String contentType); }
ttimbul/eclipse.wst
bundles/org.eclipse.wst.sse.core/src/org/eclipse/wst/sse/core/internal/cleanup/StructuredContentCleanupHandler.java
Java
epl-1.0
884
package p; import java.io.IOException; import java.util.List; import java.util.Set; class A implements I{ /* (non-Javadoc) * @see p.I#m(java.util.Set) */ public List m(Set set) throws IOException{ return null; } }
maxeler/eclipse
eclipse.jdt.ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface/test6/out/A.java
Java
epl-1.0
224
/** * generated by Xtext 2.22.0 */ package com.wamas.ide.launching.lcDsl; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Feature With Version</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link com.wamas.ide.launching.lcDsl.FeatureWithVersion#getName <em>Name</em>}</li> * <li>{@link com.wamas.ide.launching.lcDsl.FeatureWithVersion#getVersion <em>Version</em>}</li> * </ul> * * @see com.wamas.ide.launching.lcDsl.LcDslPackage#getFeatureWithVersion() * @model * @generated */ public interface FeatureWithVersion extends EObject { /** * Returns the value of the '<em><b>Name</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Name</em>' attribute. * @see #setName(String) * @see com.wamas.ide.launching.lcDsl.LcDslPackage#getFeatureWithVersion_Name() * @model * @generated */ String getName(); /** * Sets the value of the '{@link com.wamas.ide.launching.lcDsl.FeatureWithVersion#getName <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Name</em>' attribute. * @see #getName() * @generated */ void setName(String value); /** * Returns the value of the '<em><b>Version</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Version</em>' attribute. * @see #setVersion(String) * @see com.wamas.ide.launching.lcDsl.LcDslPackage#getFeatureWithVersion_Version() * @model * @generated */ String getVersion(); /** * Sets the value of the '{@link com.wamas.ide.launching.lcDsl.FeatureWithVersion#getVersion <em>Version</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Version</em>' attribute. * @see #getVersion() * @generated */ void setVersion(String value); } // FeatureWithVersion
mduft/lcdsl
com.wamas.ide.launching/src-gen/com/wamas/ide/launching/lcDsl/FeatureWithVersion.java
Java
epl-1.0
2,070
/** * Copyright (c) 2016-2022 by the respective copyright holders. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package com.zsmartsystems.zigbee.zcl.clusters.iasace; import java.util.List; import javax.annotation.Generated; import com.zsmartsystems.zigbee.zcl.ZclFieldDeserializer; import com.zsmartsystems.zigbee.zcl.ZclFieldSerializer; import com.zsmartsystems.zigbee.zcl.protocol.ZclCommandDirection; import com.zsmartsystems.zigbee.zcl.protocol.ZclDataType; /** * Bypass Response value object class. * <p> * Cluster: <b>IAS ACE</b>. Command ID 0x07 is sent <b>FROM</b> the server. * This command is a <b>specific</b> command used for the IAS ACE cluster. * <p> * Provides the response of the security panel to the request from the IAS ACE client to bypass * zones via a Bypass command. * <p> * Code is auto-generated. Modifications may be overwritten! */ @Generated(value = "com.zsmartsystems.zigbee.autocode.ZigBeeCodeGenerator", date = "2020-12-25T10:11:19Z") public class BypassResponse extends ZclIasAceCommand { /** * The cluster ID to which this command belongs. */ public static int CLUSTER_ID = 0x0501; /** * The command ID. */ public static int COMMAND_ID = 0x07; /** * Bypass Result command message field. * <p> * An array of Zone IDs for each zone requested to be bypassed via the Bypass command where X * is equal to the value of the Number of Zones field. The order of results for Zone IDs shall * be the same as the order of Zone IDs sent in the Bypass command by the IAS ACE client. */ private List<Integer> bypassResult; /** * Default constructor. * * @deprecated from release 1.3.0. Use the parameterised constructor instead of the default constructor and setters. */ @Deprecated public BypassResponse() { clusterId = CLUSTER_ID; commandId = COMMAND_ID; genericCommand = false; commandDirection = ZclCommandDirection.SERVER_TO_CLIENT; } /** * Constructor providing all required parameters. * * @param bypassResult {@link List<Integer>} Bypass Result */ public BypassResponse( List<Integer> bypassResult) { clusterId = CLUSTER_ID; commandId = COMMAND_ID; genericCommand = false; commandDirection = ZclCommandDirection.SERVER_TO_CLIENT; this.bypassResult = bypassResult; } /** * Gets Bypass Result. * <p> * An array of Zone IDs for each zone requested to be bypassed via the Bypass command where X * is equal to the value of the Number of Zones field. The order of results for Zone IDs shall * be the same as the order of Zone IDs sent in the Bypass command by the IAS ACE client. * * @return the Bypass Result */ public List<Integer> getBypassResult() { return bypassResult; } /** * Sets Bypass Result. * <p> * An array of Zone IDs for each zone requested to be bypassed via the Bypass command where X * is equal to the value of the Number of Zones field. The order of results for Zone IDs shall * be the same as the order of Zone IDs sent in the Bypass command by the IAS ACE client. * * @param bypassResult the Bypass Result * @deprecated as of 1.3.0. Use the parameterised constructor instead to ensure that all mandatory fields are provided. */ @Deprecated public void setBypassResult(final List<Integer> bypassResult) { this.bypassResult = bypassResult; } @Override public void serialize(final ZclFieldSerializer serializer) { serializer.serialize(bypassResult, ZclDataType.N_X_UNSIGNED_8_BIT_INTEGER); } @Override public void deserialize(final ZclFieldDeserializer deserializer) { bypassResult = (List<Integer>) deserializer.deserialize(ZclDataType.N_X_UNSIGNED_8_BIT_INTEGER); } @Override public String toString() { final StringBuilder builder = new StringBuilder(49); builder.append("BypassResponse ["); builder.append(super.toString()); builder.append(", bypassResult="); builder.append(bypassResult); builder.append(']'); return builder.toString(); } }
zsmartsystems/com.zsmartsystems.zigbee
com.zsmartsystems.zigbee/src/main/java/com/zsmartsystems/zigbee/zcl/clusters/iasace/BypassResponse.java
Java
epl-1.0
4,478
/******************************************************************************* * Copyright (c) 2005-2008, G. Weirich and Elexis * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * G. Weirich - initial implementation * *******************************************************************************/ package ch.elexis.core.ui.actions; import java.util.Hashtable; import java.util.Vector; import org.eclipse.core.runtime.jobs.IJobManager; import org.eclipse.core.runtime.jobs.ILock; import org.eclipse.core.runtime.jobs.Job; import ch.elexis.core.ui.actions.BackgroundJob.BackgroundJobListener; import ch.rgw.tools.ExHandler; /** * Ein Sammelbecken für Background-Jobs. Der JobPool steuert den Ablauf der Jobs: Er achtet darauf, * dass derselbe Job nicht mehrmals gleichzeitig gestartet wird, und dass nicht zuviele Jobs * parallel laufen. Dafür können Jobs in eine Warteschlange eingereiht werden, wo sie nacheinander * abgearbeitet werden. Die Priorität der Jobs wird aus org.eclipse.core.runtime.jobs.Job entnommen. * Die Werte bedeuten: * <ul> * <li>Job.INTERACTIVE: Höchste Priorität, nur für kurzlaufende Jobs, die ummittelbare Auswirkung * auf die Benutzeroberfläche haben.</li> * <li>Job.SHORT: Hohe Priorität, für Jobs die höchstens ein bis zwei Sekunden laufen, und auf die * der Anwender wartet</li> * <li>Job.LONG: Mittlere Priorität für Jobs, die mehrere Sekunden lang laufen, und die deshalb die * Benutzeroberfläche nicht beeinträchtigen sollen</li> * <li>Job.DECORATE; Niedrigste Priorität für allgemeine Hintergrundjobs, die nur laufen, wenn sonst * nichts zu tun ist</li> * </ul> * * @see BackgroundJob * @author gerry * * @deprecated Neuer Code sollte das Eclipse Job API verwenden * @see BackgroundJob */ @Deprecated public class JobPool implements BackgroundJobListener { private Hashtable<String, BackgroundJob> pool = new Hashtable<String, BackgroundJob>(); private Vector<String> running = new Vector<String>(); private Vector<String> waiting = new Vector<String>(); private Vector<String> queued = new Vector<String>(); private ILock changeLock; private static JobPool thePool; private JobPool(){ IJobManager jobman = Job.getJobManager(); changeLock = jobman.newLock(); } public void dispose(){ for (BackgroundJob job : pool.values()) { try { if (job.cancel() == false) { job.getThread().interrupt(); } } catch (Throwable t) { ExHandler.handle(t); } } } /** * Den JobPool erzeugen bzw. holen. Es soll nur einen geben, deswegen als Singleton * implementiert */ public static JobPool getJobPool(){ if (thePool == null) { thePool = new JobPool(); } return thePool; } /** * Einen neuen Job hinzufügen. Ein Job bleibt im Pool bis zum Programmende. Er hat entweder den * Status running, waiting oder queued. Jobs, die waiting oder queued sind, brauchen keine * Systemressourcen. addJob lässt den Job zunächst im status waiting * * @param job * der Job * @return true wenn erfolgreich, false wenn dieser Job oder ein Job gleichen Namens schon im * Pool ist oder bei einem sonstigen Fehler. */ public boolean addJob(BackgroundJob job){ try { changeLock.acquire(); if (pool.get(job.getJobname()) != null) { return false; } job.addListener(this); pool.put(job.getJobname(), job); waiting.add(job.getJobname()); return true; } catch (Exception ex) { ExHandler.handle(ex); return false; } finally { changeLock.release(); } } /** * Einen Job anhand seines Namens finden * * @param name * Name des Jobs * @return den Job oder null, wenn nicht vorhanden. */ public BackgroundJob getJob(String name){ BackgroundJob ret = pool.get(name); return ret; } /** * Einen Job starten * * @param name * Name des Jobs * @param priority * gewpnschte Priorität (Job.INTERACTIVE bis JOB.DECORATIONS) * @return true wenn der Job gestartet wurde, d.h. er läuft dann noch bei Rückkehr dieser * Funktion. false, wenn der Job schon lief, oder wenn er nicht gefunden wurde. */ public boolean activate(String name, int priority){ try { changeLock.acquire(); if (waiting.remove(name) == true) { BackgroundJob job = pool.get(name); if (job == null) { return false; } running.add(name); job.setPriority(priority); job.schedule(); return true; } return false; } catch (Exception ex) { ExHandler.handle(ex); return false; } finally { changeLock.release(); } } /** * Einen Job in die Warteschlange setzen. Er wird gestartet, sobald ein eventuell schon * laufender Job beendet ist. * * @param name * Name des Jobs */ public void queue(String name){ try { changeLock.acquire(); if (running.isEmpty()) { activate(name, Job.BUILD); } else { queued.add(name); } } catch (Exception ex) { ExHandler.handle(ex); } finally { changeLock.release(); } } /** * Diese Funktion ist für internen Gebrauch. Organisation der Warteschlange */ @Override public void jobFinished(BackgroundJob j){ try { changeLock.acquire(); running.remove(j.getJobname()); waiting.add(j.getJobname()); if (!queued.isEmpty()) { String nextJob = queued.remove(0); activate(nextJob, Job.BUILD); } } catch (Exception e) { ExHandler.handle(e); } finally { changeLock.release(); } } }
elexis/elexis-3-core
bundles/ch.elexis.core.ui/src/ch/elexis/core/ui/actions/JobPool.java
Java
epl-1.0
5,725
/* * 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.solr.client.solrj.response; import org.apache.solr.common.util.NamedList; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Encapsulates responses from SpellCheckComponent * * * @since solr 1.3 */ public class SpellCheckResponse { private boolean correctlySpelled; private List<Collation> collations; private List<Suggestion> suggestions = new ArrayList<>(); Map<String, Suggestion> suggestionMap = new LinkedHashMap<>(); public SpellCheckResponse(NamedList<Object> spellInfo) { @SuppressWarnings("unchecked") NamedList<Object> sugg = (NamedList<Object>) spellInfo.get("suggestions"); if (sugg == null) { correctlySpelled = true; return; } for (int i = 0; i < sugg.size(); i++) { String n = sugg.getName(i); @SuppressWarnings("unchecked") Suggestion s = new Suggestion(n, (NamedList<Object>) sugg.getVal(i)); suggestionMap.put(n, s); suggestions.add(s); } Boolean correctlySpelled = (Boolean) spellInfo.get("correctlySpelled"); if (correctlySpelled != null) { this.correctlySpelled = correctlySpelled; } @SuppressWarnings("unchecked") NamedList<Object> coll = (NamedList<Object>) spellInfo.get("collations"); if (coll != null) { // The 'collationInternalRank' values are ignored so we only care 'collation's. List<Object> collationInfo = coll.getAll("collation"); collations = new ArrayList<>(collationInfo.size()); for (Object o : collationInfo) { if (o instanceof String) { collations.add(new Collation() .setCollationQueryString((String) o)); } else if (o instanceof NamedList) { @SuppressWarnings("unchecked") NamedList<Object> expandedCollation = (NamedList<Object>) o; String collationQuery = (String) expandedCollation.get("collationQuery"); long hits = ((Number) expandedCollation.get("hits")).longValue(); @SuppressWarnings("unchecked") NamedList<String> misspellingsAndCorrections = (NamedList<String>) expandedCollation.get("misspellingsAndCorrections"); Collation collation = new Collation(); collation.setCollationQueryString(collationQuery); collation.setNumberOfHits(hits); for (int ii = 0; ii < misspellingsAndCorrections.size(); ii++) { String misspelling = misspellingsAndCorrections.getName(ii); String correction = misspellingsAndCorrections.getVal(ii); collation.addMisspellingsAndCorrection(new Correction( misspelling, correction)); } collations.add(collation); } else { throw new AssertionError( "Should get Lists of Strings or List of NamedLists here."); } } } } public boolean isCorrectlySpelled() { return correctlySpelled; } public List<Suggestion> getSuggestions() { return suggestions; } public Map<String, Suggestion> getSuggestionMap() { return suggestionMap; } public Suggestion getSuggestion(String token) { return suggestionMap.get(token); } public String getFirstSuggestion(String token) { Suggestion s = suggestionMap.get(token); if (s==null || s.getAlternatives().isEmpty()) return null; return s.getAlternatives().get(0); } /** * <p> * Return the first collated query string. For convenience and backwards-compatibility. Use getCollatedResults() for full data. * </p> * @return first collated query string */ public String getCollatedResult() { return collations==null || collations.size()==0 ? null : collations.get(0).collationQueryString; } /** * <p> * Return all collations. * Will include # of hits and misspelling-to-correction details if "spellcheck.collateExtendedResults was true. * </p> * @return all collations */ public List<Collation> getCollatedResults() { return collations; } public static class Suggestion { private String token; private int numFound; private int startOffset; private int endOffset; private int originalFrequency; private List<String> alternatives = new ArrayList<>(); private List<Integer> alternativeFrequencies; @SuppressWarnings({"rawtypes"}) public Suggestion(String token, NamedList<Object> suggestion) { this.token = token; for (int i = 0; i < suggestion.size(); i++) { String n = suggestion.getName(i); if ("numFound".equals(n)) { numFound = (Integer) suggestion.getVal(i); } else if ("startOffset".equals(n)) { startOffset = (Integer) suggestion.getVal(i); } else if ("endOffset".equals(n)) { endOffset = (Integer) suggestion.getVal(i); } else if ("origFreq".equals(n)) { originalFrequency = (Integer) suggestion.getVal(i); } else if ("suggestion".equals(n)) { @SuppressWarnings("unchecked") List list = (List)suggestion.getVal(i); if (list.size() > 0 && list.get(0) instanceof NamedList) { // extended results detected @SuppressWarnings("unchecked") List<NamedList> extended = (List<NamedList>)list; alternativeFrequencies = new ArrayList<>(); for (NamedList nl : extended) { alternatives.add((String)nl.get("word")); alternativeFrequencies.add((Integer)nl.get("freq")); } } else { @SuppressWarnings("unchecked") List<String> alts = (List<String>) list; alternatives.addAll(alts); } } } } public String getToken() { return token; } public int getNumFound() { return numFound; } public int getStartOffset() { return startOffset; } public int getEndOffset() { return endOffset; } public int getOriginalFrequency() { return originalFrequency; } /** The list of alternatives */ public List<String> getAlternatives() { return alternatives; } /** The frequencies of the alternatives in the corpus, or null if this information was not returned */ public List<Integer> getAlternativeFrequencies() { return alternativeFrequencies; } } public static class Collation { private String collationQueryString; private List<Correction> misspellingsAndCorrections = new ArrayList<>(); private long numberOfHits; public long getNumberOfHits() { return numberOfHits; } public void setNumberOfHits(long numberOfHits) { this.numberOfHits = numberOfHits; } public String getCollationQueryString() { return collationQueryString; } public Collation setCollationQueryString(String collationQueryString) { this.collationQueryString = collationQueryString; return this; } public List<Correction> getMisspellingsAndCorrections() { return misspellingsAndCorrections; } public Collation addMisspellingsAndCorrection(Correction correction) { this.misspellingsAndCorrections.add(correction); return this; } } public static class Correction { private String original; private String correction; public Correction(String original, String correction) { this.original = original; this.correction = correction; } public String getOriginal() { return original; } public void setOriginal(String original) { this.original = original; } public String getCorrection() { return correction; } public void setCorrection(String correction) { this.correction = correction; } } }
DavidGutknecht/elexis-3-base
bundles/org.apache.solr/src/org/apache/solr/client/solrj/response/SpellCheckResponse.java
Java
epl-1.0
8,627
/* // This software is subject to the terms of the Eclipse Public License v1.0 // Agreement, available at the following URL: // http://www.eclipse.org/legal/epl-v10.html. // You must accept the terms of that agreement to use this software. // // Copyright (C) 2007-2009 Pentaho // All Rights Reserved. */ package mondrian.olap; import java.util.ArrayList; import java.util.List; /** * Implementation of {@link Role} which combines the privileges of several * roles and has the superset of their privileges. * * @see mondrian.olap.RoleImpl#union(java.util.List) * * @author jhyde * @since Nov 26, 2007 */ class UnionRoleImpl implements Role { private final List<Role> roleList; /** * Creates a UnionRoleImpl. * * @param roleList List of constituent roles */ UnionRoleImpl(List<Role> roleList) { this.roleList = new ArrayList<Role>(roleList); } public Access getAccess(Schema schema) { Access access = Access.NONE; for (Role role : roleList) { access = max(access, role.getAccess(schema)); if (access == Access.ALL) { break; } } return access; } /** * Returns the larger of two enum values. Useful if the enums are sorted * so that more permissive values come after less permissive values. * * @param t1 First value * @param t2 Second value * @return larger of the two values */ private static <T extends Enum<T>> T max(T t1, T t2) { if (t1.ordinal() > t2.ordinal()) { return t1; } else { return t2; } } public Access getAccess(Cube cube) { Access access = Access.NONE; for (Role role : roleList) { access = max(access, role.getAccess(cube)); if (access == Access.ALL) { break; } } return access; } public Access getAccess(Dimension dimension) { Access access = Access.NONE; for (Role role : roleList) { access = max(access, role.getAccess(dimension)); if (access == Access.ALL) { break; } } return access; } public Access getAccess(Hierarchy hierarchy) { Access access = Access.NONE; for (Role role : roleList) { access = max(access, role.getAccess(hierarchy)); if (access == Access.ALL) { break; } } return access; } public HierarchyAccess getAccessDetails(final Hierarchy hierarchy) { List<HierarchyAccess> list = new ArrayList<HierarchyAccess>(); for (Role role : roleList) { final HierarchyAccess accessDetails = role.getAccessDetails(hierarchy); if (accessDetails != null) { list.add(accessDetails); } } // If none of the roles call out access details, we shouldn't either. if (list.isEmpty()) { return null; } HierarchyAccess hierarchyAccess = new UnionHierarchyAccessImpl(hierarchy, list); if (list.size() > 5) { hierarchyAccess = new RoleImpl.CachingHierarchyAccess(hierarchyAccess); } return hierarchyAccess; } public Access getAccess(Level level) { Access access = Access.NONE; for (Role role : roleList) { access = max(access, role.getAccess(level)); if (access == Access.ALL) { break; } } return access; } public Access getAccess(Member member) { assert member != null; HierarchyAccess hierarchyAccess = getAccessDetails(member.getHierarchy()); if (hierarchyAccess != null) { return hierarchyAccess.getAccess(member); } return getAccess(member.getDimension()); } public Access getAccess(NamedSet set) { Access access = Access.NONE; for (Role role : roleList) { access = max(access, role.getAccess(set)); if (access == Access.ALL) { break; } } return access; } public boolean canAccess(OlapElement olapElement) { for (Role role : roleList) { if (role.canAccess(olapElement)) { return true; } } return false; } /** * Implementation of {@link mondrian.olap.Role.HierarchyAccess} that * gives access to an object if any one of the constituent hierarchy * accesses has access to that object. */ private class UnionHierarchyAccessImpl implements HierarchyAccess { private final List<HierarchyAccess> list; /** * Creates a UnionHierarchyAccessImpl. * * @param hierarchy Hierarchy * @param list List of underlying hierarchy accesses */ UnionHierarchyAccessImpl( Hierarchy hierarchy, List<HierarchyAccess> list) { Util.discard(hierarchy); this.list = list; } public Access getAccess(Member member) { Access access = Access.NONE; final int roleCount = roleList.size(); for (int i = 0; i < roleCount; i++) { Role role = roleList.get(i); access = max(access, role.getAccess(member)); if (access == Access.ALL) { break; } } return access; } public int getTopLevelDepth() { int access = Integer.MAX_VALUE; for (HierarchyAccess hierarchyAccess : list) { access = Math.min( access, hierarchyAccess.getTopLevelDepth()); if (access == 0) { break; } } return access; } public int getBottomLevelDepth() { int access = -1; for (HierarchyAccess hierarchyAccess : list) { access = Math.max( access, hierarchyAccess.getBottomLevelDepth()); } return access; } public RollupPolicy getRollupPolicy() { RollupPolicy rollupPolicy = RollupPolicy.HIDDEN; for (HierarchyAccess hierarchyAccess : list) { rollupPolicy = max( rollupPolicy, hierarchyAccess.getRollupPolicy()); if (rollupPolicy == RollupPolicy.FULL) { break; } } return rollupPolicy; } public boolean hasInaccessibleDescendants(Member member) { for (HierarchyAccess hierarchyAccess : list) { switch (hierarchyAccess.getAccess(member)) { case NONE: continue; case CUSTOM: return true; case ALL: if (!hierarchyAccess.hasInaccessibleDescendants(member)) { return false; } } } return true; } } } // End UnionRoleImpl.java
rfellows/mondrian
src/main/mondrian/olap/UnionRoleImpl.java
Java
epl-1.0
7,440
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.nest.test; import static org.openhab.binding.nest.internal.NestBindingConstants.*; import static org.openhab.binding.nest.internal.rest.NestStreamingRestClient.*; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; /** * The {@link NestTestApiServlet} mocks the Nest API during tests. * * @author Wouter Born - Increase test coverage */ public class NestTestApiServlet extends HttpServlet { private static final long serialVersionUID = -5414910055159062745L; private static final String NEW_LINE = "\n"; private static final String UPDATE_PATHS[] = { NEST_CAMERA_UPDATE_PATH, NEST_SMOKE_ALARM_UPDATE_PATH, NEST_STRUCTURE_UPDATE_PATH, NEST_THERMOSTAT_UPDATE_PATH }; private final Logger logger = LoggerFactory.getLogger(NestTestApiServlet.class); private class SseEvent { private String name; private String data; public SseEvent(String name) { this.name = name; } public SseEvent(String name, String data) { this.name = name; this.data = data; } public String getData() { return data; } public String getName() { return name; } public boolean hasData() { return data != null && !data.isEmpty(); } } private final Map<String, Map<String, String>> nestIdPropertiesMap = new ConcurrentHashMap<>(); private final Map<Thread, Queue<SseEvent>> listenerQueues = new ConcurrentHashMap<>(); private final ThreadLocal<PrintWriter> threadLocalWriter = new ThreadLocal<>(); private final Gson gson = new GsonBuilder().create(); public void closeConnections() { Set<Thread> threads = listenerQueues.keySet(); listenerQueues.clear(); threads.forEach(thread -> thread.interrupt()); } public void reset() { nestIdPropertiesMap.clear(); } public void queueEvent(String eventName) { SseEvent event = new SseEvent(eventName); listenerQueues.forEach((thread, queue) -> queue.add(event)); } public void queueEvent(String eventName, String data) { SseEvent event = new SseEvent(eventName, data); listenerQueues.forEach((thread, queue) -> queue.add(event)); } @SuppressWarnings("resource") private void writeEvent(SseEvent event) { logger.debug("Writing {} event", event.getName()); PrintWriter writer = threadLocalWriter.get(); writer.write("event: "); writer.write(event.getName()); writer.write(NEW_LINE); if (event.hasData()) { for (String dataLine : event.getData().split(NEW_LINE)) { writer.write("data: "); writer.write(dataLine); writer.write(NEW_LINE); } } writer.write(NEW_LINE); writer.flush(); } private void writeEvent(String eventName) { writeEvent(new SseEvent(eventName)); } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ArrayBlockingQueue<SseEvent> queue = new ArrayBlockingQueue<>(10); listenerQueues.put(Thread.currentThread(), queue); response.setContentType("text/event-stream"); response.setCharacterEncoding("UTF-8"); response.flushBuffer(); logger.debug("Opened event stream to {}:{}", request.getRemoteHost(), request.getRemotePort()); PrintWriter writer = response.getWriter(); threadLocalWriter.set(writer); writeEvent(OPEN); while (listenerQueues.containsKey(Thread.currentThread()) && !writer.checkError()) { try { SseEvent event = queue.poll(KEEP_ALIVE_MILLIS, TimeUnit.MILLISECONDS); if (event != null) { writeEvent(event); } else { writeEvent(KEEP_ALIVE); } } catch (InterruptedException e) { logger.debug("Evaluating loop conditions after interrupt"); } } listenerQueues.remove(Thread.currentThread()); threadLocalWriter.remove(); writer.close(); logger.debug("Closed event stream to {}:{}", request.getRemoteHost(), request.getRemotePort()); } @Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Received put request: {}", request); String uri = request.getRequestURI(); String nestId = getNestIdFromURI(uri); if (nestId == null) { logger.error("Unsupported URI: {}", uri); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } InputStreamReader reader = new InputStreamReader(request.getInputStream()); Map<String, String> propertiesUpdate = gson.fromJson(reader, new TypeToken<Map<String, String>>() { }.getType()); Map<String, String> properties = getOrCreateProperties(nestId); properties.putAll(propertiesUpdate); gson.toJson(propertiesUpdate, response.getWriter()); response.setStatus(HttpServletResponse.SC_OK); } private String getNestIdFromURI(String uri) { for (String updatePath : UPDATE_PATHS) { if (uri.startsWith(updatePath)) { return uri.replaceAll(updatePath, ""); } } return null; } private Map<String, String> getOrCreateProperties(String nestId) { Map<String, String> properties = nestIdPropertiesMap.get(nestId); if (properties == null) { properties = new HashMap<>(); nestIdPropertiesMap.put(nestId, properties); } return properties; } public String getNestIdPropertyState(String nestId, String propertyName) { Map<String, String> properties = nestIdPropertiesMap.get(nestId); return properties == null ? null : properties.get(propertyName); } }
MikeJMajor/openhab2-addons-dlinksmarthome
itests/org.openhab.binding.nest.tests/src/main/java/org/openhab/binding/nest/test/NestTestApiServlet.java
Java
epl-1.0
7,121
/** * Copyright (c) 2010-2015, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.ihc.ws; import org.openhab.binding.ihc.ws.datatypes.WSBaseDataType; import org.openhab.binding.ihc.ws.datatypes.WSControllerState; import org.openhab.binding.ihc.ws.datatypes.WSFile; import org.openhab.binding.ihc.ws.datatypes.WSProjectInfo; /** * Class to handle IHC / ELKO LS Controller's controller service. * * Controller service is used to fetch information from the controller. * E.g. Project file or controller status. * * @author Pauli Anttila * @since 1.5.0 */ public class IhcControllerService extends IhcHttpsClient { private static String emptyQuery = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<soapenv:Body>" + "</soapenv:Body>" + "</soapenv:Envelope>"; private String url; IhcControllerService(String host, int timeout) { url = "https://" + host + "/ws/ControllerService"; super.setRequestTimeout(timeout); super.setConnectTimeout(timeout); } /** * Query project information from the controller. * * @return project information. * @throws IhcExecption */ public synchronized WSProjectInfo getProjectInfo() throws IhcExecption { openConnection(url); setRequestProperty("SOAPAction", "getProjectInfo"); String response = sendQuery(emptyQuery); closeConnection(); WSProjectInfo projectInfo = new WSProjectInfo(); projectInfo.encodeData(response); return projectInfo; } /** * Query number of segments project contains. * * @return number of segments. */ public synchronized int getProjectNumberOfSegments() throws IhcExecption { openConnection(url); setRequestProperty("SOAPAction", "getIHCProjectNumberOfSegments"); String response = sendQuery(emptyQuery); closeConnection(); String numberOfSegments = WSBaseDataType.parseValue(response, "/SOAP-ENV:Envelope/SOAP-ENV:Body/ns1:getIHCProjectNumberOfSegments1"); return Integer.parseInt(numberOfSegments); } /** * Query segmentation size. * * @return segmentation size in bytes. */ public synchronized int getProjectSegmentationSize() throws IhcExecption { openConnection(url); setRequestProperty("SOAPAction", "getIHCProjectSegmentationSize"); String response = sendQuery(emptyQuery); closeConnection(); String segmentationSize = WSBaseDataType.parseValue(response, "/SOAP-ENV:Envelope/SOAP-ENV:Body/ns1:getIHCProjectSegmentationSize1"); return Integer.parseInt(segmentationSize); } /** * Query project segment data. * * @param index * segments index. * @param major * project major revision number. * @param minor * project minor revision number. * @return segments data. */ public synchronized WSFile getProjectSegment(int index, int major, int minor) throws IhcExecption { final String soapQuery = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<soap:Body>" + " <ns1:getIHCProjectSegment1 xmlns:ns1=\"utcs\" xsi:type=\"xsd:int\">%s</ns1:getIHCProjectSegment1>" + " <ns2:getIHCProjectSegment2 xmlns:ns2=\"utcs\" xsi:type=\"xsd:int\">%s</ns2:getIHCProjectSegment2>" + " <ns3:getIHCProjectSegment3 xmlns:ns3=\"utcs\" xsi:type=\"xsd:int\">%s</ns3:getIHCProjectSegment3>" + "</soap:Body>" + "</soap:Envelope>"; String query = String.format(soapQuery, index, major, minor); openConnection(url); setRequestProperty("SOAPAction", "getIHCProjectSegment"); String response = sendQuery(query); closeConnection(); WSFile file = new WSFile(); file.encodeData(response); return file; } /** * Query controller current state. * * @return controller's current state. */ public synchronized WSControllerState getControllerState() throws IhcExecption { openConnection(url); setRequestProperty("SOAPAction", "getState"); String response = sendQuery(emptyQuery); closeConnection(); WSControllerState controllerState = new WSControllerState(); controllerState.encodeData(response); return controllerState; } /** * Wait controller state change notification. * * @param previousState * Previous controller state. * @param timeoutInSeconds * How many seconds to wait notifications. * @return current controller state. */ public synchronized WSControllerState waitStateChangeNotifications( WSControllerState previousState, int timeoutInSeconds) throws IhcExecption { final String soapQuery = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<soapenv:Header/>" + "<soapenv:Body>" + " <ns1:waitForControllerStateChange1 xmlns:ns1=\"utcs\" xsi:type=\"ns1:WSControllerState\">" + " <ns1:state xsi:type=\"xsd:string\">%s</ns1:state>" + " </ns1:waitForControllerStateChange1>" + " <ns2:waitForControllerStateChange2 xmlns:ns2=\"utcs\" xsi:type=\"xsd:int\">%s</ns2:waitForControllerStateChange2>" + "</soapenv:Body>" + "</soapenv:Envelope>"; String query = String.format(soapQuery, previousState.getState(), timeoutInSeconds); openConnection(url); setRequestProperty("SOAPAction", "waitForControllerStateChange"); setRequestTimeout(getRequestTimeout() + timeoutInSeconds * 1000); String response = sendQuery(query); closeConnection(); WSControllerState controllerState = new WSControllerState(); controllerState.encodeData(response); return controllerState; } }
taimos/openhab
bundles/binding/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/ws/IhcControllerService.java
Java
epl-1.0
6,079
/******************************************************************************* * Copyright (c) 2012 University of Luxembourg and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Max E. Kramer - initial API and implementation ******************************************************************************/ package edu.kit.ipd.sdq.vitruvius.framework.util.datatypes; /** * A 4-tuple. * * @param <A> * the type of the first element * @param <B> * the type of the second element * @param <C> * the type of the third element * @param <D> * the type of the fourth element * @author Max E. Kramer */ public class Quadruple<A, B, C, D> extends Triple<A, B, C> { /** The fourth element. */ private final D fourth; /** * Constructs a new Quadruple using the given first, second, third and fourth element. * * @param first * the first element * @param second * the second element * @param third * the third element * @param fourth * the fourth element */ public Quadruple(final A first, final B second, final C third, final D fourth) { super(first, second, third); this.fourth = fourth; } @Override public String toString() { return "Quadruple [first=" + this.getFirst() + ", second=" + this.getSecond() + ", third=" + this.getThird() + ", fourth=" + this.getFourth() + "]"; } /** * @return the fourth element. */ public D getFourth() { return this.fourth; } @Override public int hashCode() { final int firstSecondAndThird = super.hashCode(); final int fourth = this.getFourth() == null ? 0 : this.getFourth().hashCode(); return firstSecondAndThird + (2 * 2 * 37 * fourth); } }
Cooperate-Project/PlantUMLPrinterParser
bundles/edu.kit.ipd.sdq.vitruvius.framework.util/src/edu/kit/ipd/sdq/vitruvius/framework/util/datatypes/Quadruple.java
Java
epl-1.0
2,169
/* * 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.prowidesoftware.swift.model.field; import java.io.Serializable; import org.apache.commons.lang.StringUtils; import com.prowidesoftware.swift.model.*; import com.prowidesoftware.swift.utils.SwiftFormatUtils; /** * Field 242<br /><br /> * * validation pattern: 1!a<br /> * parser pattern: S<br /> * components pattern: S<br /> * * <h1>Components Data types</h1> * <ul> * <li>component1: <code>String</code></li> * </ul> * * <em>NOTE: this source code has been generated from template</em> * * @author www.prowidesoftware.com * */ @SuppressWarnings("unused") public class Field242 extends Field implements Serializable { private static final long serialVersionUID = 1L; /** * Constant with the field name 242 */ public static final String NAME = "242"; /** * same as NAME, intended to be clear when using static imports */ public static final String F_242 = "242"; public static final String PARSER_PATTERN ="S"; public static final String COMPONENTS_PATTERN = "S"; /** * Create a Tag with this field name and the given value. * Shorthand for <code>new Tag(NAME, value)</code> * @see #NAME * @since 7.5 */ public static Tag tag(final String value) { return new Tag(NAME, value); } /** * Create a Tag with this field name and an empty string as value * Shorthand for <code>new Tag(NAME, "")</code> * @see #NAME * @since 7.5 */ public static Tag emptyTag() { return new Tag(NAME, ""); } /** * Default constructor */ public Field242() { super(1); } /** * Creates the field parsing the parameter value into fields' components * @param value */ public Field242(String value) { this(); setComponent1(value); } /** * Serializes the fields' components into the single string value (SWIFT format) */ @Override public String getValue() { final StringBuilder result = new StringBuilder(); result.append(StringUtils.trimToEmpty(getComponent1())); return result.toString(); } /** * Get the component1 * @return the component1 */ public String getComponent1() { return getComponent(1); } /** * Same as getComponent(1) */ @Deprecated public java.lang.String getComponent1AsString() { return getComponent(1); } /** * Get the Status Code (component1). * @return the Status Code from component1 */ public String getStatusCode() { return getComponent(1); } /** * Set the component1. * @param component1 the component1 to set */ public Field242 setComponent1(String component1) { setComponent(1, component1); return this; } /** * Set the Status Code (component1). * @param component1 the Status Code to set */ public Field242 setStatusCode(String component1) { setComponent(1, component1); return this; } /** * Given a component number it returns true if the component is optional, * regardless of the field being mandatory in a particular message.<br /> * Being the field's value conformed by a composition of one or several * internal component values, the field may be present in a message with * a proper value but with some of its internal components not set. * * @param component component number, first component of a field is referenced as 1 * @return true if the component is optional for this field, false otherwise */ @Override public boolean isOptional(int component) { return false; } /** * Returns true if the field is a GENERIC FIELD as specified by the standard. * * @return true if the field is generic, false otherwise */ @Override public boolean isGeneric() { return false; } public String componentsPattern() { return COMPONENTS_PATTERN; } public String parserPattern() { return PARSER_PATTERN; } /** * @deprecated use constant Field242 */ @Override public String getName() { return NAME; } /** * Get the first occurrence form the tag list or null if not found. * @returns null if not found o block is null or empty * @param block may be null or empty */ public static Field242 get(final SwiftTagListBlock block) { if (block == null || block.isEmpty()) { return null; } return (Field242) block.getFieldByName(NAME); } /** * Get the first instance of Field242 in the given message. * @param msg may be empty or null * @returns null if not found or msg is empty or null * @see */ public static Field242 get(final SwiftMessage msg) { if (msg == null || msg.getBlock4()==null || msg.getBlock4().isEmpty()) return null; return get(msg.getBlock4()); } /** * Get a list of all occurrences of the field Field242 in the given message * an empty list is returned if none found. * @param msg may be empty or null in which case an empty list is returned * @see */ public static java.util.List<Field242> getAll(final SwiftMessage msg) { if (msg == null || msg.getBlock4()==null || msg.getBlock4().isEmpty()) return null; return getAll(msg.getBlock4()); } /** * Get a list of all occurrences of the field Field242 from the given block * an empty list is returned if none found. * * @param block may be empty or null in which case an empty list is returned */ public static java.util.List<Field242> getAll(final SwiftTagListBlock block) { if (block == null || block.isEmpty()) { return null; } final Field[] arr = block.getFieldsByName(NAME); if (arr != null && arr.length>0) { final java.util.ArrayList<Field242> result = new java.util.ArrayList<Field242>(arr.length); for (final Field f : arr) { result.add((Field242) f); } return result; } return java.util.Collections.emptyList(); } }
hellonico/wife
src/com/prowidesoftware/swift/model/field/Field242.java
Java
epl-1.0
6,275
/** * * $Id$ */ package WTSpec.validation; /** * A sample validator interface for {@link WTSpec.WTCOutput}. * This doesn't really do anything, and it's not a real EMF artifact. * It was generated by the org.eclipse.emf.examples.generator.validator plug-in to illustrate how EMF's code generator can be extended. * This can be disabled with -vmargs -Dorg.eclipse.emf.examples.generator.validator=false. */ public interface WTCOutputValidator { boolean validate(); }
FTSRG/mondo-collab-framework
archive/mondo-access-control/CollaborationIncQuery/WTSpec/src/WTSpec/validation/WTCOutputValidator.java
Java
epl-1.0
477
package SCJPTestFri1; class SuperHotel { public int bookings; public void book() { bookings++; } } public class Quest8 extends SuperHotel { public void book() { bookings--; } public void book(int size) { book(); super.book(); bookings += size; } public static void main(String args[]) { Quest8 hotel = new Quest8(); hotel.book(2); System.out.print(hotel.bookings); } }
ShubhankarRaj/JavaCodingFolder
Eclipse Workspace/myProject/src/SCJPTestFri1/Quest8.java
Java
epl-1.0
501
package com.odcgroup.process.diagram.custom.properties.sections; import com.odcgroup.process.model.ProcessPackage; import com.odcgroup.workbench.editors.properties.section.AbstractPropertiesSection; import com.odcgroup.workbench.editors.properties.widgets.SimpleGroupWidget; import com.odcgroup.workbench.editors.properties.widgets.SimpleTextWidget; public class ProcessGeneralSection extends AbstractPropertiesSection { /* (non-Javadoc) * @see com.odcgroup.workbench.editors.properties.section.AbstractPropertiesSection#configureProperties() */ protected void configureProperties() { setUseThreeFourthLayout(true); SimpleGroupWidget group = new SimpleGroupWidget(null); SimpleTextWidget pageflowName = new SimpleTextWidget(ProcessPackage.eINSTANCE.getProcess_DisplayName(), "Display Name"); pageflowName.setFillHorizontal(true); group.addPropertyFeature(pageflowName); SimpleTextWidget pageflowDesc = new SimpleTextWidget(ProcessPackage.eINSTANCE.getProcess_Comment(), "Comment"); pageflowDesc.setMultiline(true); group.addPropertyFeature(pageflowDesc); this.addPropertyFeature(group); } }
debabratahazra/DS
designstudio/components/process/ui/com.odcgroup.process.editor.diagram/src/main/java/com/odcgroup/process/diagram/custom/properties/sections/ProcessGeneralSection.java
Java
epl-1.0
1,148
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.lifx.internal.listener; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.lifx.internal.LifxLightState; import org.openhab.binding.lifx.internal.dto.Effect; import org.openhab.binding.lifx.internal.dto.PowerState; import org.openhab.binding.lifx.internal.dto.SignalStrength; import org.openhab.binding.lifx.internal.fields.HSBK; import org.openhab.core.library.types.PercentType; /** * The {@link LifxLightStateListener} is notified when the properties of a {@link LifxLightState} change. * * @author Wouter Born - Initial contribution */ @NonNullByDefault public interface LifxLightStateListener { /** * Called when the colors property changes. * * @param oldColors the old colors value * @param newColors the new colors value */ void handleColorsChange(HSBK[] oldColors, HSBK[] newColors); /** * Called when the power state property changes. * * @param oldPowerState the old power state value * @param newPowerState the new power state value */ void handlePowerStateChange(@Nullable PowerState oldPowerState, PowerState newPowerState); /** * Called when the infrared property changes. * * @param oldInfrared the old infrared value * @param newInfrared the new infrared value */ void handleInfraredChange(@Nullable PercentType oldInfrared, PercentType newInfrared); /** * Called when the signal strength property changes. * * @param oldSignalStrength the old signal strength value * @param newSignalStrength the new signal strength value */ void handleSignalStrengthChange(@Nullable SignalStrength oldSignalStrength, SignalStrength newSignalStrength); /** * Called when the tile effect changes. * * @param oldEffect the old tile effect value * @param newEffect new tile effectvalue */ void handleTileEffectChange(@Nullable Effect oldEffect, Effect newEffect); }
paulianttila/openhab2
bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/listener/LifxLightStateListener.java
Java
epl-1.0
2,421
/* * Copyright 2016 Axel Faust * * Licensed under the Eclipse Public License (EPL), Version 1.0 (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of the License at * * https://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package de.axelfaust.alfresco.enhScriptEnv.common.script.locator; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import org.alfresco.util.PropertyCheck; import org.alfresco.util.VersionNumber; import de.axelfaust.alfresco.enhScriptEnv.common.script.ReferenceScript; import de.axelfaust.alfresco.enhScriptEnv.common.script.registry.AppliesForVersionCondition; import de.axelfaust.alfresco.enhScriptEnv.common.script.registry.CompositeCondition; import de.axelfaust.alfresco.enhScriptEnv.common.script.registry.FallsInVersionRangeCondition; import de.axelfaust.alfresco.enhScriptEnv.common.script.registry.ScriptRegistry; import de.axelfaust.alfresco.enhScriptEnv.common.script.registry.ScriptSelectionCondition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Axel Faust */ public abstract class RegisteredScriptLocator<BaseScript, Script extends ReferenceScript> extends AbstractScriptLocator<Script> { protected static final String FALLBACK_CHAIN = "fallbackChain"; protected static final String CONDITIONS = "conditions"; protected static final String VERSION = "version"; protected static final String COMMUNITY = "community"; protected static final String APPLIES_FROM = "appliesFrom"; protected static final String APPLIES_TO = "appliesTo"; protected static final String APPLIES_FROM_EXCLUSIVE = "appliesFromExclusive"; protected static final String APPLIES_TO_EXCLUSIVE = "appliesToExclusive"; private static final Logger LOGGER = LoggerFactory.getLogger(RegisteredScriptLocator.class); protected ScriptRegistry<BaseScript> scriptRegistry; /** * {@inheritDoc} */ @Override public void afterPropertiesSet() { super.afterPropertiesSet(); PropertyCheck.mandatory(this, "scriptRegistry", this.scriptRegistry); } /** * * {@inheritDoc} */ @Override public final Script resolveLocation(final ReferenceScript referenceLocation, final String locationValue) { final Script result; result = this.lookupScriptInRegistry(locationValue, null); return result; } /** * * {@inheritDoc} */ @Override public Script resolveLocation(final ReferenceScript referenceLocation, final String locationValue, final Map<String, Object> resolutionParameters) { final Script script; // we currently don't support any parameters, so just pass to default implementation if (resolutionParameters != null) { final Collection<ScriptSelectionCondition> conditions = this.extractSelectionConditions(resolutionParameters); if (conditions != null && !conditions.isEmpty()) { Script locatedScript = null; for (final ScriptSelectionCondition condition : conditions) { locatedScript = this.lookupScriptInRegistry(locationValue, condition); if (locatedScript != null) { break; } } script = locatedScript; } else { LOGGER.info( "Unable to determine selection condition for resolution of path {} from reference location {} - parameters provided {}", new Object[] { locationValue, referenceLocation, resolutionParameters }); script = this.resolveLocation(referenceLocation, locationValue); } } else { script = this.resolveLocation(referenceLocation, locationValue); } return script; } /** * @param scriptRegistry * the scriptRegistry to set */ public final void setScriptRegistry(final ScriptRegistry<BaseScript> scriptRegistry) { this.scriptRegistry = scriptRegistry; } protected Script lookupScriptInRegistry(final String locationValue, final ScriptSelectionCondition condition) { final Script result; if (!locationValue.contains("@")) { // no @ in location value => global script final BaseScript baseScript = condition == null ? this.scriptRegistry.getScript(locationValue) : this.scriptRegistry.getScript( locationValue, condition); if (baseScript != null) { result = this.convert(baseScript); } else { result = null; } } else { final String[] fragments = locationValue.split("@"); if (fragments.length == 2) { final String scriptName = fragments[0]; final String subRegistry = fragments[1]; final BaseScript baseScript = condition == null ? this.scriptRegistry.getScript(scriptName, subRegistry) : this.scriptRegistry.getScript(scriptName, subRegistry, condition); if (baseScript != null) { result = this.convert(baseScript); } else { result = null; } } else { throw new IllegalArgumentException("Too many occurences of '@' in location value"); } } return result; } protected Collection<ScriptSelectionCondition> extractSelectionConditions(final Map<?, ?> parameters) { final Collection<ScriptSelectionCondition> conditions; if (parameters.containsKey(FALLBACK_CHAIN)) { final Object fallbackChainCandidate = parameters.get(FALLBACK_CHAIN); if (fallbackChainCandidate instanceof List<?>) { conditions = new ArrayList<ScriptSelectionCondition>(); for (final Object element : (List<?>) fallbackChainCandidate) { if (element instanceof Map<?, ?>) { final Map<?, ?> conditionParameters = (Map<?, ?>) element; final ScriptSelectionCondition selectionCondition = this.extractSelectionCondition(conditionParameters); if (selectionCondition != null) { conditions.add(selectionCondition); } } } } else { final ScriptSelectionCondition selectionCondition = this.extractSelectionCondition(parameters); if (selectionCondition != null) { conditions = Collections.singletonList(selectionCondition); } else { conditions = Collections.emptyList(); } } } else { final ScriptSelectionCondition selectionCondition = this.extractSelectionCondition(parameters); if (selectionCondition != null) { conditions = Collections.singletonList(selectionCondition); } else { conditions = Collections.emptyList(); } } return conditions; } protected ScriptSelectionCondition extractSelectionCondition(final Map<?, ?> parameters) { final ScriptSelectionCondition multiCondition = this.extractCompositeCondition(parameters); final ScriptSelectionCondition versionCondition = this.extractVersionCondition(parameters); final ScriptSelectionCondition versionRangeCondition = this.extractVersionRangeCondition(parameters); final List<ScriptSelectionCondition> conditions = new ArrayList<ScriptSelectionCondition>(); if (multiCondition != null) { conditions.add(multiCondition); } if (versionCondition != null) { conditions.add(versionCondition); } if (versionRangeCondition != null) { conditions.add(versionRangeCondition); } final ScriptSelectionCondition condition; if (conditions.isEmpty()) { condition = null; } else if (conditions.size() == 1) { condition = conditions.get(0); } else { condition = new CompositeCondition(conditions); } return condition; } protected ScriptSelectionCondition extractVersionCondition(final Map<?, ?> parameters) { final ScriptSelectionCondition versionCondition; if (parameters.containsKey(VERSION)) { final Object versionNumberObj = parameters.get(VERSION); if (versionNumberObj instanceof String) { final VersionNumber versionNumber = new VersionNumber((String) versionNumberObj); Boolean community = Boolean.valueOf(this.isCommunityEdition()); if (parameters.containsKey(COMMUNITY)) { final Object communityObj = parameters.get(COMMUNITY); if (communityObj == null) { community = null; } else { community = Boolean.valueOf(toBoolean(communityObj)); } } versionCondition = new AppliesForVersionCondition(versionNumber, community); } else { versionCondition = null; } } else { versionCondition = null; } return versionCondition; } protected ScriptSelectionCondition extractVersionRangeCondition(final Map<?, ?> parameters) { final ScriptSelectionCondition versionRangeCondition; if (parameters.containsKey(APPLIES_FROM) || parameters.containsKey(APPLIES_TO)) { final Object appliesFromObj = parameters.get(APPLIES_FROM); final Object appliesToObj = parameters.get(APPLIES_TO); if (appliesFromObj instanceof String || appliesToObj instanceof String) { final VersionNumber appliesFrom = appliesFromObj instanceof String ? new VersionNumber((String) appliesFromObj) : null; final VersionNumber appliesTo = appliesToObj instanceof String ? new VersionNumber((String) appliesToObj) : null; final Object appliesFromExclusiveObj = parameters.get(APPLIES_FROM_EXCLUSIVE); final Object appliesToExclusiveObj = parameters.get(APPLIES_TO_EXCLUSIVE); final boolean appliesFromExclusive = toBoolean(appliesFromExclusiveObj); final boolean appliesToExclusive = toBoolean(appliesToExclusiveObj); Boolean community = Boolean.valueOf(this.isCommunityEdition()); if (parameters.containsKey(COMMUNITY)) { final Object communityObj = parameters.get(COMMUNITY); if (communityObj == null) { community = null; } else { community = Boolean.valueOf(toBoolean(communityObj)); } } versionRangeCondition = new FallsInVersionRangeCondition(appliesFrom, appliesFromExclusive, appliesTo, appliesToExclusive, community); } else { versionRangeCondition = null; } } else { versionRangeCondition = null; } return versionRangeCondition; } protected ScriptSelectionCondition extractCompositeCondition(final Map<?, ?> parameters) { final ScriptSelectionCondition compositeCondition; if (parameters.containsKey(CONDITIONS)) { final Object conditionsObj = parameters.get(CONDITIONS); if (conditionsObj instanceof Map<?, ?>) { // just a single condition object => not a real composite compositeCondition = this.extractSelectionCondition((Map<?, ?>) conditionsObj); } else if (conditionsObj instanceof Collection<?>) { final Collection<ScriptSelectionCondition> conditions = new HashSet<ScriptSelectionCondition>(); for (final Object element : (Collection<?>) conditionsObj) { if (element instanceof Map<?, ?>) { final ScriptSelectionCondition singleCondition = this.extractSelectionCondition((Map<?, ?>) element); if (singleCondition != null) { conditions.add(singleCondition); } } else { throw new IllegalArgumentException("Condition collection element not supported: " + element.toString()); } } if (conditions.isEmpty()) { // not a condition at all compositeCondition = null; } else if (conditions.size() == 1) { // just a single condition object => not a real composite compositeCondition = conditions.iterator().next(); } else { compositeCondition = new CompositeCondition(conditions); } } else { throw new IllegalArgumentException("Condition object not supported: " + conditionsObj.toString()); } } else { compositeCondition = null; } return compositeCondition; } protected static boolean toBoolean(final Object boolParameter) { boolean result = false; if (boolParameter instanceof Boolean) { result = ((Boolean) boolParameter).booleanValue(); } else if (boolParameter instanceof String) { result = Boolean.parseBoolean((String) boolParameter); } return result; } /** * Converts a basic script instance to the expected locator result script instance type. * * @param baseScript * the base script instance to convert * @return the converted script instance */ abstract protected Script convert(BaseScript baseScript); protected boolean isCommunityEdition() { // by default, we treat any unknown environment as "community edition" return true; }; }
AFaust/alfresco-enhanced-script-environment
framework/common/src/main/java/de/axelfaust/alfresco/enhScriptEnv/common/script/locator/RegisteredScriptLocator.java
Java
epl-1.0
15,796
package com.xored.q7.quality.mockups.emf.edit; import java.util.ArrayList; import org.eclipse.emf.edit.ui.dnd.LocalTransfer; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.ListViewer; import org.eclipse.jface.viewers.ViewerDropAdapter; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSourceAdapter; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.dnd.TransferData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import com.xored.q7.quality.mockups.issues.BaseMockupPart; public class QS3036_DragAndDropWithLocalTransfer extends BaseMockupPart { @Override public Control construct(Composite parent) { GridLayoutFactory.swtDefaults().numColumns(2).applyTo(parent); Label label = new Label(parent, SWT.NONE); label.setText("Drag different items from right to left."); GridDataFactory.fillDefaults().span(2, 1).applyTo(label); final ListViewer tree1 = new ListViewer(parent); GridDataFactory.fillDefaults().grab(true, true).applyTo(tree1.getControl()); tree1.setContentProvider(new ArrayContentProvider()); tree1.setLabelProvider(new LabelProvider()); tree1.addDragSupport(DND.DROP_MOVE, new Transfer[] { LocalTransfer.getInstance() }, new DragSourceAdapter() { @Override public void dragSetData(DragSourceEvent event) { event.data = ((IStructuredSelection) tree1.getSelection()).toList(); }}); final String[] sourceData = new String[]{"First", "Second", "Third"}; tree1.setInput(sourceData); final ListViewer tree2 = new ListViewer(parent); GridDataFactory.fillDefaults().grab(true, true).applyTo(tree2.getControl()); tree2.setContentProvider(new ArrayContentProvider()); tree2.setLabelProvider(new LabelProvider()); final ArrayList<String> targetData = new ArrayList<String>(); tree2.setInput(targetData); tree2.addDropSupport(DND.DROP_MOVE | DND.DROP_COPY, new Transfer[] {LocalTransfer.getInstance() }, new ViewerDropAdapter(tree2) { @Override public boolean performDrop(Object data) { Iterable<?> dataList = (Iterable<?>) data; for (Object datum: dataList) { targetData.add((String)datum); } tree2.refresh(); return true; } @Override public boolean validateDrop(Object target, int operation, TransferData transferType) { return true; } }); return parent; } }
xored/q7.quality.mockups
plugins/com.xored.q7.quality.mockups.emf/src/com/xored/q7/quality/mockups/emf/edit/QS3036_DragAndDropWithLocalTransfer.java
Java
epl-1.0
2,888
/* * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.protocol.bgp.linkstate.attribute; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Charsets; import com.google.common.collect.Multimap; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.buffer.Unpooled; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import org.opendaylight.protocol.bgp.linkstate.attribute.sr.SrNodeAttributesParser; import org.opendaylight.protocol.bgp.linkstate.spi.TlvUtil; import org.opendaylight.protocol.util.BitArray; import org.opendaylight.protocol.util.ByteArray; import org.opendaylight.protocol.util.Ipv4Util; import org.opendaylight.protocol.util.Ipv6Util; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.Ipv4RouterIdentifier; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.Ipv6RouterIdentifier; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.IsisAreaIdentifier; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.NodeFlagBits; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.ProtocolId; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.TopologyIdentifier; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.path.attribute.LinkStateAttribute; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.path.attribute.link.state.attribute.NodeAttributesCase; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.path.attribute.link.state.attribute.NodeAttributesCaseBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.path.attribute.link.state.attribute.node.attributes._case.NodeAttributes; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.path.attribute.link.state.attribute.node.attributes._case.NodeAttributesBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.node.state.SrAlgorithm; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.node.state.SrCapabilities; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @VisibleForTesting public final class NodeAttributesParser { private static final Logger LOG = LoggerFactory.getLogger(NodeAttributesParser.class); private NodeAttributesParser() { throw new UnsupportedOperationException(); } private static final int FLAGS_SIZE = 8; // node flag bits private static final int OVERLOAD_BIT = 0; private static final int ATTACHED_BIT = 1; private static final int EXTERNAL_BIT = 2; private static final int ABBR_BIT = 3; private static final int ROUTER_BIT = 4; private static final int V6_BIT = 5; /* Node Attribute TLVs */ private static final int NODE_FLAG_BITS = 1024; private static final int NODE_OPAQUE = 1025; private static final int DYNAMIC_HOSTNAME = 1026; private static final int ISIS_AREA_IDENTIFIER = 1027; /* Segment routing TLVs */ private static final int SR_CAPABILITIES = 1034; private static final int SR_ALGORITHMS = 1035; /** * Parse Node Attributes. * * @param attributes key is the tlv type and value is the value of the tlv * @param protocolId to differentiate parsing methods * @return {@link LinkStateAttribute} */ static LinkStateAttribute parseNodeAttributes(final Multimap<Integer, ByteBuf> attributes, final ProtocolId protocolId) { final List<TopologyIdentifier> topologyMembership = new ArrayList<>(); final List<IsisAreaIdentifier> areaMembership = new ArrayList<>(); final NodeAttributesBuilder builder = new NodeAttributesBuilder(); for (final Entry<Integer, ByteBuf> entry : attributes.entries()) { final int key = entry.getKey(); final ByteBuf value = entry.getValue(); LOG.trace("Node attribute TLV {}", key); switch (key) { case TlvUtil.MULTI_TOPOLOGY_ID: parseTopologyId(topologyMembership, value); break; case NODE_FLAG_BITS: final BitArray flags = BitArray.valueOf(value, FLAGS_SIZE); builder.setNodeFlags(new NodeFlagBits(flags.get(OVERLOAD_BIT), flags.get(ATTACHED_BIT), flags.get (EXTERNAL_BIT), flags.get(ABBR_BIT), flags.get(ROUTER_BIT), flags.get(V6_BIT))); LOG.debug("Parsed Overload bit: {}, attached bit: {}, external bit: {}, area border router: {}.", flags.get(OVERLOAD_BIT), flags.get(ATTACHED_BIT), flags.get(EXTERNAL_BIT), flags.get(ABBR_BIT)); break; case NODE_OPAQUE: if (LOG.isDebugEnabled()) { LOG.debug("Ignoring opaque value: {}.", ByteBufUtil.hexDump(value)); } break; case DYNAMIC_HOSTNAME: builder.setDynamicHostname(new String(ByteArray.readAllBytes(value), Charsets.US_ASCII)); LOG.debug("Parsed Node Name {}", builder.getDynamicHostname()); break; case ISIS_AREA_IDENTIFIER: final IsisAreaIdentifier ai = new IsisAreaIdentifier(ByteArray.readAllBytes(value)); areaMembership.add(ai); LOG.debug("Parsed AreaIdentifier {}", ai); break; case TlvUtil.LOCAL_IPV4_ROUTER_ID: final Ipv4RouterIdentifier ip4 = new Ipv4RouterIdentifier(Ipv4Util.addressForByteBuf(value)); builder.setIpv4RouterId(ip4); LOG.debug("Parsed IPv4 Router Identifier {}", ip4); break; case TlvUtil.LOCAL_IPV6_ROUTER_ID: final Ipv6RouterIdentifier ip6 = new Ipv6RouterIdentifier(Ipv6Util.addressForByteBuf(value)); builder.setIpv6RouterId(ip6); LOG.debug("Parsed IPv6 Router Identifier {}", ip6); break; case SR_CAPABILITIES: final SrCapabilities caps = SrNodeAttributesParser.parseSrCapabilities(value, protocolId); builder.setSrCapabilities(caps); LOG.debug("Parsed SR Capabilities {}", caps); break; case SR_ALGORITHMS: final SrAlgorithm algs = SrNodeAttributesParser.parseSrAlgorithms(value); builder.setSrAlgorithm(algs); LOG.debug("Parsed SR Algorithms {}", algs); break; default: LOG.warn("TLV {} is not a valid node attribute, ignoring it", key); } } LOG.trace("Finished parsing Node Attributes."); builder.setTopologyIdentifier(topologyMembership); builder.setIsisAreaId(areaMembership); return new NodeAttributesCaseBuilder().setNodeAttributes(builder.build()).build(); } private static void parseTopologyId(final List<TopologyIdentifier> topologyMembership, final ByteBuf value) { while (value.isReadable()) { final TopologyIdentifier topId = new TopologyIdentifier(value.readUnsignedShort() & TlvUtil.TOPOLOGY_ID_OFFSET); topologyMembership.add(topId); LOG.debug("Parsed Topology Identifier: {}", topId); } } static void serializeNodeAttributes(final NodeAttributesCase nodeAttributesCase, final ByteBuf byteAggregator) { LOG.trace("Started serializing Node Attributes"); final NodeAttributes nodeAttributes = nodeAttributesCase.getNodeAttributes(); serializeTopologyId(nodeAttributes.getTopologyIdentifier(), byteAggregator); serializeNodeFlagBits(nodeAttributes.getNodeFlags(), byteAggregator); if (nodeAttributes.getDynamicHostname() != null) { TlvUtil.writeTLV(DYNAMIC_HOSTNAME, Unpooled.wrappedBuffer(Charsets.UTF_8.encode(nodeAttributes.getDynamicHostname())), byteAggregator); } final List<IsisAreaIdentifier> isisList = nodeAttributes.getIsisAreaId(); if (isisList != null) { for (final IsisAreaIdentifier isisAreaIdentifier : isisList) { TlvUtil.writeTLV(ISIS_AREA_IDENTIFIER, Unpooled.wrappedBuffer(isisAreaIdentifier.getValue()), byteAggregator); } } if (nodeAttributes.getIpv4RouterId() != null) { TlvUtil.writeTLV(TlvUtil.LOCAL_IPV4_ROUTER_ID, Ipv4Util.byteBufForAddress(nodeAttributes.getIpv4RouterId()), byteAggregator); } if (nodeAttributes.getIpv6RouterId() != null) { TlvUtil.writeTLV(TlvUtil.LOCAL_IPV6_ROUTER_ID, Ipv6Util.byteBufForAddress(nodeAttributes.getIpv6RouterId()), byteAggregator); } if (nodeAttributes.getSrCapabilities() != null) { final ByteBuf capBuffer = Unpooled.buffer(); SrNodeAttributesParser.serializeSrCapabilities(nodeAttributes.getSrCapabilities(), capBuffer); TlvUtil.writeTLV(SR_CAPABILITIES, capBuffer, byteAggregator); } if (nodeAttributes.getSrAlgorithm() != null) { final ByteBuf capBuffer = Unpooled.buffer(); SrNodeAttributesParser.serializeSrAlgorithms(nodeAttributes.getSrAlgorithm(), capBuffer); TlvUtil.writeTLV(SR_ALGORITHMS, capBuffer, byteAggregator); } LOG.trace("Finished serializing Node Attributes"); } private static void serializeTopologyId(final List<TopologyIdentifier> topList, final ByteBuf byteAggregator) { if (topList != null) { final ByteBuf mpIdBuf = Unpooled.buffer(); for (final TopologyIdentifier topologyIdentifier : topList) { mpIdBuf.writeShort(topologyIdentifier.getValue()); } TlvUtil.writeTLV(TlvUtil.MULTI_TOPOLOGY_ID, mpIdBuf, byteAggregator); } } private static void serializeNodeFlagBits(final NodeFlagBits nodeFlagBits, final ByteBuf byteAggregator) { if (nodeFlagBits != null) { final ByteBuf nodeFlagBuf = Unpooled.buffer(1); final BitArray flags = new BitArray(FLAGS_SIZE); flags.set(OVERLOAD_BIT, nodeFlagBits.isOverload()); flags.set(ATTACHED_BIT, nodeFlagBits.isAttached()); flags.set(EXTERNAL_BIT, nodeFlagBits.isExternal()); flags.set(ABBR_BIT, nodeFlagBits.isAbr()); flags.set(ROUTER_BIT, nodeFlagBits.isRouter()); flags.set(V6_BIT, nodeFlagBits.isV6()); flags.toByteBuf(nodeFlagBuf); TlvUtil.writeTLV(NODE_FLAG_BITS, nodeFlagBuf, byteAggregator); } } }
inocybe/odl-bgpcep
bgp/linkstate/src/main/java/org/opendaylight/protocol/bgp/linkstate/attribute/NodeAttributesParser.java
Java
epl-1.0
11,249
/* * This file is part of the Jikes RVM project (http://jikesrvm.org). * * This file is licensed to You under the Common Public License (CPL); * You may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.opensource.org/licenses/cpl1.0.php * * See the COPYRIGHT.txt file distributed with this work for information * regarding copyright ownership. */ package org.jikesrvm.runtime; import org.vmmagic.unboxed.Address; import org.vmmagic.unboxed.LocalAddress; /** * Facility for remapping object addresses across virtual machine address * spaces. Used by boot image writer to map local (jdk) objects into remote * (boot image) addresses. Used by debugger to map local (jdk) objects into * remote (debugee vm) addresses. * * See also VM_Magic.setObjectAddressRemapper() */ public interface VM_ObjectAddressRemapper { /** * Map an object to an address. * @param object in "local" virtual machine * @return its address in a foreign virtual machine */ <T> Address objectAsAddress(T object); /** * Map an object to an localaddress. * @param object in "local" virtual machine * @return its address in a foreign virtual machine */ <T> LocalAddress objectAsLocalAddress(T object); /** * Map an address to an object. * @param address value obtained from "objectAsAddress" * @return corresponding object */ Object addressAsObject(Address address); /** * Map an address to an object. * @param address value obtained from "objectAsLocalAddress" * @return corresponding object */ Object localAddressAsObject(LocalAddress address); }
rmcilroy/HeraJVM
rvm/src/org/jikesrvm/runtime/VM_ObjectAddressRemapper.java
Java
epl-1.0
1,683
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ /** @author Andrew McCallum <a href="mailto:[email protected]">[email protected]</a> */ package cc.mallet.util; import java.util.*; public class Randoms extends java.util.Random { public Randoms (int seed) { super(seed); } public Randoms () { super(); } /** Return random integer from Poission with parameter lambda. * The mean of this distribution is lambda. The variance is lambda. */ public synchronized int nextPoisson(double lambda) { int i,j,v=-1; double l=Math.exp(-lambda),p; p=1.0; while (p>=l) { p*=nextUniform(); v++; } return v; } /** Return nextPoisson(1). */ public synchronized int nextPoisson() { return nextPoisson(1); } /** Return a random boolean, equally likely to be true or false. */ public synchronized boolean nextBoolean() { return (next(32) & 1 << 15) != 0; } /** Return a random boolean, with probability p of being true. */ public synchronized boolean nextBoolean(double p) { double u=nextUniform(); if(u < p) return true; return false; } /** Return a random BitSet with "size" bits, each having probability p of being true. */ public synchronized BitSet nextBitSet (int size, double p) { BitSet bs = new BitSet (size); for (int i = 0; i < size; i++) if (nextBoolean (p)) { bs.set (i); } return bs; } /** Return a random double in the range 0 to 1, inclusive, uniformly sampled from that range. * The mean of this distribution is 0.5. The variance is 1/12. */ public synchronized double nextUniform() { long l = ((long)(next(26)) << 27) + next(27); return l / (double)(1L << 53); } /** Return a random double in the range a to b, inclusive, uniformly sampled from that range. * The mean of this distribution is (b-a)/2. The variance is (b-a)^2/12 */ public synchronized double nextUniform(double a,double b) { return a + (b-a)*nextUniform(); } /** Draw a single sample from multinomial "a". */ public synchronized int nextDiscrete (double[] a) { double b = 0, r = nextUniform(); for (int i = 0; i < a.length; i++) { b += a[i]; if (b > r) { return i; } } return a.length-1; } /** draw a single sample from (unnormalized) multinomial "a", with normalizing factor "sum". */ public synchronized int nextDiscrete (double[] a, double sum) { double b = 0, r = nextUniform() * sum; for (int i = 0; i < a.length; i++) { b += a[i]; if (b > r) { return i; } } return a.length-1; } private double nextGaussian; private boolean haveNextGaussian = false; /** Return a random double drawn from a Gaussian distribution with mean 0 and variance 1. */ public synchronized double nextGaussian() { if (!haveNextGaussian) { double v1=nextUniform(),v2=nextUniform(); double x1,x2; x1=Math.sqrt(-2*Math.log(v1))*Math.cos(2*Math.PI*v2); x2=Math.sqrt(-2*Math.log(v1))*Math.sin(2*Math.PI*v2); nextGaussian=x2; haveNextGaussian=true; return x1; } else { haveNextGaussian=false; return nextGaussian; } } /** Return a random double drawn from a Gaussian distribution with mean m and variance s2. */ public synchronized double nextGaussian(double m,double s2) { return nextGaussian()*Math.sqrt(s2)+m; } // generate Gamma(1,1) // E(X)=1 ; Var(X)=1 /** Return a random double drawn from a Gamma distribution with mean 1.0 and variance 1.0. */ public synchronized double nextGamma() { return nextGamma(1,1,0); } /** Return a random double drawn from a Gamma distribution with mean alpha and variance 1.0. */ public synchronized double nextGamma(double alpha) { return nextGamma(alpha,1,0); } /* Return a sample from the Gamma distribution, with parameter IA */ /* From Numerical "Recipes in C", page 292 */ public synchronized double oldNextGamma (int ia) { int j; double am, e, s, v1, v2, x, y; assert (ia >= 1) ; if (ia < 6) { x = 1.0; for (j = 1; j <= ia; j++) x *= nextUniform (); x = - Math.log (x); } else { do { do { do { v1 = 2.0 * nextUniform () - 1.0; v2 = 2.0 * nextUniform () - 1.0; } while (v1 * v1 + v2 * v2 > 1.0); y = v2 / v1; am = ia - 1; s = Math.sqrt (2.0 * am + 1.0); x = s * y + am; } while (x <= 0.0); e = (1.0 + y * y) * Math.exp (am * Math.log (x/am) - s * y); } while (nextUniform () > e); } return x; } /** Return a random double drawn from a Gamma distribution with mean alpha*beta and variance alpha*beta^2. */ public synchronized double nextGamma(double alpha, double beta) { return nextGamma(alpha,beta,0); } /** Return a random double drawn from a Gamma distribution with mean alpha*beta+lamba and variance alpha*beta^2. */ public synchronized double nextGamma(double alpha,double beta,double lambda) { double gamma=0; if (alpha <= 0 || beta <= 0) { throw new IllegalArgumentException ("alpha and beta must be strictly positive."); } if (alpha < 1) { double b,p; boolean flag=false; b=1+alpha*Math.exp(-1); while(!flag) { p=b*nextUniform(); if (p>1) { gamma=-Math.log((b-p)/alpha); if (nextUniform()<=Math.pow(gamma,alpha-1)) flag=true; } else { gamma=Math.pow(p,1/alpha); if (nextUniform()<=Math.exp(-gamma)) flag=true; } } } else if (alpha == 1) { gamma = -Math.log (nextUniform ()); } else { double y = -Math.log (nextUniform ()); while (nextUniform () > Math.pow (y * Math.exp (1 - y), alpha - 1)) y = -Math.log (nextUniform ()); gamma = alpha * y; } return beta*gamma+lambda; } /** Return a random double drawn from an Exponential distribution with mean 1 and variance 1. */ public synchronized double nextExp() { return nextGamma(1,1,0); } /** Return a random double drawn from an Exponential distribution with mean beta and variance beta^2. */ public synchronized double nextExp(double beta) { return nextGamma(1,beta,0); } /** Return a random double drawn from an Exponential distribution with mean beta+lambda and variance beta^2. */ public synchronized double nextExp(double beta,double lambda) { return nextGamma(1,beta,lambda); } /** Return a random double drawn from an Chi-squarted distribution with mean 1 and variance 2. * Equivalent to nextChiSq(1) */ public synchronized double nextChiSq() { return nextGamma(0.5,2,0); } /** Return a random double drawn from an Chi-squared distribution with mean df and variance 2*df. */ public synchronized double nextChiSq(int df) { return nextGamma(0.5*(double)df,2,0); } /** Return a random double drawn from an Chi-squared distribution with mean df+lambda and variance 2*df. */ public synchronized double nextChiSq(int df,double lambda) { return nextGamma(0.5*(double)df,2,lambda); } /** Return a random double drawn from a Beta distribution with mean a/(a+b) and variance ab/((a+b+1)(a+b)^2). */ public synchronized double nextBeta(double alpha,double beta) { if (alpha <= 0 || beta <= 0) { throw new IllegalArgumentException ("alpha and beta must be strictly positive."); } if (alpha == 1 && beta == 1) { return nextUniform (); } else if (alpha >= 1 && beta >= 1) { double A = alpha - 1, B = beta - 1, C = A + B, L = C * Math.log (C), mu = A / C, sigma = 0.5 / Math.sqrt (C); double y = nextGaussian (), x = sigma * y + mu; while (x < 0 || x > 1) { y = nextGaussian (); x = sigma * y + mu; } double u = nextUniform (); while (Math.log (u) >= A * Math.log (x / A) + B * Math.log ((1 - x) / B) + L + 0.5 * y * y) { y = nextGaussian (); x = sigma * y + mu; while (x < 0 || x > 1) { y = nextGaussian (); x = sigma * y + mu; } u = nextUniform (); } return x; } else { double v1 = Math.pow (nextUniform (), 1 / alpha), v2 = Math.pow (nextUniform (), 1 / beta); while (v1 + v2 > 1) { v1 = Math.pow (nextUniform (), 1 / alpha); v2 = Math.pow (nextUniform (), 1 / beta); } return v1 / (v1 + v2); } } /** Wrap this instance as a java random, so it can be passed to legacy methods. * All methods of the returned java.util.Random object will affect the state of * this object, as well. */ @Deprecated // This should no longer be necessary, since Randoms is now a subclass of java.util.random anyway public java.util.Random asJavaRandom () { return new java.util.Random () { protected int next (int bits) { return cc.mallet.util.Randoms.this.next (bits); } }; } public static void main (String[] args) { // Prints the nextGamma() and oldNextGamma() distributions to // System.out for testing/comparison. Randoms r = new Randoms(); final int resolution = 60; int[] histogram1 = new int[resolution]; int[] histogram2 = new int[resolution]; int scale = 10; for (int i = 0; i < 10000; i++) { double x = 4; int index1 = ((int)(r.nextGamma(x)/scale * resolution)) % resolution; int index2 = ((int)(r.oldNextGamma((int)x)/scale * resolution)) % resolution; histogram1[index1]++; histogram2[index2]++; } for (int i = 0; i < resolution; i++) { for (int y = 0; y < histogram1[i]/scale; y++) System.out.print("*"); System.out.print("\n"); for (int y = 0; y < histogram2[i]/scale; y++) System.out.print("-"); System.out.print("\n"); } } }
lazycrazyowl/jules-mallet-2
src/main/java/cc/mallet/util/Randoms.java
Java
epl-1.0
10,233
// -----BEGIN DISCLAIMER----- /******************************************************************************* * Copyright (c) 2011, 2021 JCrypTool Team and Contributors * * All rights reserved. This program and the accompanying materials are made * available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ // -----END DISCLAIMER----- package org.jcryptool.crypto.flexiprovider.algorithms.ui.dynamic.composites; import java.util.ArrayList; import java.util.List; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import org.jcryptool.core.logging.utils.LogUtil; import org.jcryptool.crypto.flexiprovider.algorithms.FlexiProviderAlgorithmsPlugin; import org.jcryptool.crypto.flexiprovider.algorithms.ui.dynamic.IInputArea; import org.jcryptool.crypto.flexiprovider.algorithms.ui.wizards.blockcipher.ModeParameterSpecPage; import de.flexiprovider.api.SecureRandom; import de.flexiprovider.common.util.ByteUtils; public class FixedModeParameterArea implements IInputArea, Listener { private static final List<String> hexValues = new ArrayList<String>(16); static { hexValues.add(0, "0"); //$NON-NLS-1$ hexValues.add(1, "1"); //$NON-NLS-1$ hexValues.add(2, "2"); //$NON-NLS-1$ hexValues.add(3, "3"); //$NON-NLS-1$ hexValues.add(4, "4"); //$NON-NLS-1$ hexValues.add(5, "5"); //$NON-NLS-1$ hexValues.add(6, "6"); //$NON-NLS-1$ hexValues.add(7, "7"); //$NON-NLS-1$ hexValues.add(8, "8"); //$NON-NLS-1$ hexValues.add(9, "9"); //$NON-NLS-1$ hexValues.add(10, "A"); //$NON-NLS-1$ hexValues.add(11, "B"); //$NON-NLS-1$ hexValues.add(12, "C"); //$NON-NLS-1$ hexValues.add(13, "D"); //$NON-NLS-1$ hexValues.add(14, "E"); //$NON-NLS-1$ hexValues.add(15, "F"); //$NON-NLS-1$ } /** Mode block size in bytes */ private int size = -1; private Text ivText; private Button rndButton; private Label disclaimerLabel; private ModeParameterSpecPage page; public void setModeParameterSpecPage(ModeParameterSpecPage page) { LogUtil.logInfo("setting page"); //$NON-NLS-1$ this.page = page; LogUtil.logInfo("page set"); //$NON-NLS-1$ } public FixedModeParameterArea(Composite parent) { LogUtil.logInfo("setting layout"); //$NON-NLS-1$ GridData gridData2 = new GridData(); gridData2.horizontalSpan = 2; gridData2.grabExcessHorizontalSpace = true; GridData gridData1 = new GridData(); gridData1.horizontalSpan = 2; gridData1.grabExcessHorizontalSpace = true; GridData gridData = new GridData(); gridData.horizontalAlignment = GridData.FILL; gridData.grabExcessHorizontalSpace = true; gridData.verticalAlignment = GridData.CENTER; GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 2; Label descriptionLabel = new Label(parent, SWT.NONE); descriptionLabel.setText(Messages.FixedModeParameterArea_0); descriptionLabel.setLayoutData(gridData1); ivText = new Text(parent, SWT.BORDER); ivText.setLayoutData(gridData); ivText.addListener(SWT.Modify, this); ivText.addVerifyListener(new VerifyListener() { @Override public void verifyText(VerifyEvent e) { if (page != null) { page.setComplete(false); } if (e.character != SWT.BS && e.character != SWT.DEL) { String origInput = ivText.getText(); LogUtil.logInfo("origInputLength: " + origInput.length()); //$NON-NLS-1$ LogUtil.logInfo("size*2 : " + size * 2); //$NON-NLS-1$ if (!codeManipulation) { e.text = e.text.toUpperCase(); if (!hexValues.contains(e.text)) { e.doit = false; if (page != null) { page.setComplete(true); } } else if ((origInput.length() + 1) > (size * 2)) { e.doit = false; if (page != null) { page.setComplete(true); } } } } } }); rndButton = new Button(parent, SWT.NONE); rndButton.setText(Messages.FixedModeParameterArea_1); rndButton.addListener(SWT.Selection, this); disclaimerLabel = new Label(parent, SWT.NONE); disclaimerLabel.setText(NLS.bind(Messages.FixedModeParameterArea_2, (size * 8))); disclaimerLabel.setLayoutData(gridData2); parent.setLayout(gridLayout); LogUtil.logInfo("layout set"); //$NON-NLS-1$ } private boolean codeManipulation = false; @Override public void handleEvent(Event event) { if (event.widget.equals(rndButton)) { codeManipulation = true; if (size > 0) { String rndString = ByteUtils.toHexString(generateRandomValue(size)); ivText.setText(rndString.toUpperCase()); codeManipulation = false; if (page != null) { page.setComplete(true); } } } } @Override public Object getValue() { if (ivText == null || ivText.getText().equals("")) { //$NON-NLS-1$ return new byte[0]; } else { return ByteUtils.fromHexString(ivText.getText()); } } @Override public void setValue(Object value) { if (value instanceof Integer) { codeManipulation = true; size = (Integer) value; LogUtil.logInfo("setting size: " + size + "!"); //$NON-NLS-1$ //$NON-NLS-2$ disclaimerLabel.setText(NLS.bind(Messages.FixedModeParameterArea_3, (size * 8))); ivText.setText(""); //$NON-NLS-1$ codeManipulation = false; } else { LogUtil.logInfo("wrong type"); //$NON-NLS-1$ } } /** * Generates a random value of the given byte length.<br> * Uses this plugin's standard secure random instance. * * @param length The byte length of the random value * @return The random value as a byte array */ private byte[] generateRandomValue(int length) { byte[] result = new byte[length]; SecureRandom sr = FlexiProviderAlgorithmsPlugin.getSecureRandom(); sr.nextBytes(result); return result; } }
jcryptool/core
org.jcryptool.crypto.flexiprovider.algorithms/src/org/jcryptool/crypto/flexiprovider/algorithms/ui/dynamic/composites/FixedModeParameterArea.java
Java
epl-1.0
7,249
// The MIT License (MIT) // // Copyright (c) 2015 Arian Fornaris // // 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 phasereditor.inspect.core.examples; import java.util.ArrayList; import java.util.List; import phasereditor.inspect.core.IPhaserCategory; public class ExampleCategoryModel implements IPhaserCategory { private String _name; private List<ExampleModel> _examples; public ExampleCategoryModel(String name) { super(); _name = name; _examples = new ArrayList<>(); } @Override public String getName() { return _name; } @Override public List<ExampleModel> getTemplates() { return _examples; } public void addExample(ExampleModel exampleModel) { _examples.add(exampleModel); } @Override public String getDescription() { return "Groups the Phaser examples."; } }
boniatillo-com/PhaserEditor
source/phasereditor/phasereditor.inspect.core/src/phasereditor/inspect/core/examples/ExampleCategoryModel.java
Java
epl-1.0
1,838
/** * Copyright (c) 2015 itemis AG (http://www.itemis.eu) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.xtext.example.statemachine.graphiti.features; import org.eclipse.graphiti.features.IFeatureProvider; import org.eclipse.graphiti.features.context.IAddConnectionContext; import org.eclipse.graphiti.features.context.IAddContext; import org.eclipse.graphiti.features.impl.AbstractAddFeature; import org.eclipse.graphiti.mm.algorithms.Polyline; import org.eclipse.graphiti.mm.algorithms.styles.Color; import org.eclipse.graphiti.mm.pictograms.Anchor; import org.eclipse.graphiti.mm.pictograms.Diagram; import org.eclipse.graphiti.mm.pictograms.FreeFormConnection; import org.eclipse.graphiti.mm.pictograms.PictogramElement; import org.eclipse.graphiti.services.Graphiti; import org.eclipse.graphiti.services.IGaService; import org.eclipse.graphiti.services.IPeCreateService; import org.eclipse.graphiti.util.IColorConstant; import org.eclipse.xtext.xbase.lib.Extension; import org.xtext.example.statemachine.statemachine.Transition; @SuppressWarnings("all") public class AddTransitionFeature extends AbstractAddFeature { @Extension private final IPeCreateService _iPeCreateService = Graphiti.getPeCreateService(); @Extension private final IGaService _iGaService = Graphiti.getGaService(); public AddTransitionFeature(final IFeatureProvider fp) { super(fp); } @Override public boolean canAdd(final IAddContext context) { boolean _and = false; if (!(context instanceof IAddConnectionContext)) { _and = false; } else { Object _newObject = context.getNewObject(); _and = (_newObject instanceof Transition); } return _and; } @Override public PictogramElement add(final IAddContext context) { final IAddConnectionContext addConContext = ((IAddConnectionContext) context); Object _newObject = context.getNewObject(); final Transition addedTransition = ((Transition) _newObject); Diagram _diagram = this.getDiagram(); final FreeFormConnection connection = this._iPeCreateService.createFreeFormConnection(_diagram); Anchor _sourceAnchor = addConContext.getSourceAnchor(); connection.setStart(_sourceAnchor); Anchor _targetAnchor = addConContext.getTargetAnchor(); connection.setEnd(_targetAnchor); final Polyline polyline = this._iGaService.createPolyline(connection); Color _manageColor = this.manageColor(IColorConstant.DARK_GRAY); polyline.setForeground(_manageColor); this.link(connection, addedTransition); return connection; } }
spoenemann/xtext-gef
org.xtext.example.statemachine.graphiti/xtend-gen/org/xtext/example/statemachine/graphiti/features/AddTransitionFeature.java
Java
epl-1.0
2,791
<<<<<<< HEAD package week1exercise.day2; import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class SendMail { public static void main(String [] args) { // Recipient's email ID needs to be mentioned. String to = "[email protected]"; // Sender's email ID needs to be mentioned String from = "[email protected]"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); properties.put("mail.transport.protocol", "smtp"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.host", "smtp.gmail.com"); //properties.put("mail.smtp.user", "[email protected]"); //properties.put("mail.smtp.password", "mymail2014"); properties.put("mail.smtp.port", 25); properties.put("mail.smtp.socketFactory.port", 25); properties.put("mail.smtp.auth", "true"); // Get the default Session object. Session session = Session.getDefaultInstance(properties, new GMailAuthenticator("[email protected]", "mymail2014" )); try{ // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject("Java Rocks!"); // Now set the actual message message.setText("I sent this from my IDE"); // Send message Transport.send(message); System.out.println("Sent message successfully...."); }catch (MessagingException mex) { mex.printStackTrace(); } } } ======= package week1exercise.day2; import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class SendMail { public static void main(String [] args) { // Recipient's email ID needs to be mentioned. String to = "[email protected]"; // Sender's email ID needs to be mentioned String from = "[email protected]"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); properties.put("mail.transport.protocol", "smtp"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.host", "smtp.gmail.com"); //properties.put("mail.smtp.user", "[email protected]"); //properties.put("mail.smtp.password", "mymail2014"); properties.put("mail.smtp.port", 25); properties.put("mail.smtp.socketFactory.port", 25); properties.put("mail.smtp.auth", "true"); // Get the default Session object. Session session = Session.getDefaultInstance(properties, new GMailAuthenticator("[email protected]", "mymail2014" )); try{ // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject("Java Rocks!"); // Now set the actual message message.setText("I sent this from my IDE"); // Send message Transport.send(message); System.out.println("Sent message successfully...."); }catch (MessagingException mex) { mex.printStackTrace(); } } } >>>>>>> a0d16c50b58db7fd4c91f21d228ec42f4562aaec
motlhodigmailcom/JavaBasic
SBSA2015JDA/src/week1exercise/day2/SendMail.java
Java
epl-1.0
4,260
/** * Receipt逻辑类 * @author JaneLDQ * @date 2014/11/14 */ package businesslogic.paymentbl; import java.rmi.RemoteException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import po.PaymentPO; import po.TransferLineItemPO; import util.DocumentStatus; import util.DocumentType; import util.ResultMessage; import util.Time; import vo.AccountVO; import vo.PaymentVO; import vo.TransferLineItemVO; import businesslogic.accountbl.Account; import businesslogic.customerbl.Customer; import dataservice.datafactoryservice.DataFactoryImpl; public class Receipt { public String createId(){ Date date=new Date(); SimpleDateFormat myFmt=new SimpleDateFormat("yyyyMMdd"); String time=myFmt.format(date); ArrayList<PaymentVO> presentList=show(); if(presentList.isEmpty()){ return "SKD-"+time+"-00001"; }else{ String max=presentList.get(presentList.size()-1).id; String day=max.substring(4,max.length()-5); if(day.compareTo(time)<0){ return "SKD-"+time+"-00001"; } String oldMax=max.substring(max.length()-5); int maxInt=Integer.parseInt(oldMax); String pattern="00000"; java.text.DecimalFormat df = new java.text.DecimalFormat(pattern); String maxStr=df.format(maxInt+1); return "SKD-"+time+"-"+maxStr; } } public ResultMessage add(PaymentVO vo){ vo.time=Time.getCurrentTime(); vo.id=createId(); try { DataFactoryImpl.getInstance().getPaymentData().insert(voToPo(vo)); } catch (RemoteException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } return ResultMessage.SUCCESS; } public ArrayList<PaymentVO> show(){ ArrayList<PaymentVO> result=new ArrayList<PaymentVO>(); ArrayList<PaymentPO> temp=new ArrayList<PaymentPO>(); try { temp=DataFactoryImpl.getInstance().getPaymentData().show(); } catch (RemoteException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } for(int i=0;i<temp.size();i++){ if(temp.get(i).getDocumentType()==DocumentType.RECEIPT.ordinal()) result.add(poToVo(temp.get(i))); } return result; } public ArrayList<PaymentVO> findByTime(String time1,String time2){ ArrayList<PaymentVO> result=new ArrayList<PaymentVO>(); ArrayList<PaymentPO> temp=new ArrayList<PaymentPO>(); try { time1=Time.jdugeTime1(time1); time2=Time.jdugeTime2(time2); temp=DataFactoryImpl.getInstance().getPaymentData().findByTime(time1, time2); } catch (RemoteException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } for(int i=0;i<temp.size();i++){ if(temp.get(i).getDocumentType()==DocumentType.RECEIPT.ordinal()){ result.add(poToVo(temp.get(i))); } } return result; } public ArrayList<PaymentVO> findByStatus(int status){ ArrayList<PaymentVO> result=new ArrayList<PaymentVO>(); ArrayList<PaymentPO> temp=new ArrayList<PaymentPO>(); try { temp=DataFactoryImpl.getInstance().getPaymentData().findByStatus(status); } catch (RemoteException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } for(int i=0;i<temp.size();i++){ if(temp.get(i).getDocumentType()==DocumentType.RECEIPT.ordinal()){ result.add(poToVo(temp.get(i))); } } return result; } public ArrayList<PaymentVO> findById(String id){ ArrayList<PaymentVO> result=new ArrayList<PaymentVO>(); ArrayList<PaymentPO> temp=new ArrayList<PaymentPO>(); try { temp=DataFactoryImpl.getInstance().getPaymentData().findById(id); } catch (RemoteException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } for(int i=0;i<temp.size();i++){ if(temp.get(i).getDocumentType()==DocumentType.RECEIPT.ordinal()){ result.add(poToVo(temp.get(i))); } } return result; } public ArrayList<PaymentVO> findByCustomer(String customerId){ ArrayList<PaymentVO> result=new ArrayList<PaymentVO>(); ArrayList<PaymentPO> temp=new ArrayList<PaymentPO>(); try { temp=DataFactoryImpl.getInstance().getPaymentData().findByCustomer(customerId); } catch (RemoteException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } for(int i=0;i<temp.size();i++){ if(temp.get(i).getDocumentType()==DocumentType.RECEIPT.ordinal()){ result.add(poToVo(temp.get(i))); } } return result; } public ArrayList<PaymentVO> findByOperator(String operator){ ArrayList<PaymentVO> result=new ArrayList<PaymentVO>(); ArrayList<PaymentPO> temp=new ArrayList<PaymentPO>(); try { temp=DataFactoryImpl.getInstance().getPaymentData().findByOperator(operator); } catch (RemoteException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } for(int i=0;i<temp.size();i++){ if(temp.get(i).getDocumentType()==DocumentType.RECEIPT.ordinal()){ result.add(poToVo(temp.get(i))); } } return result; } public ResultMessage approve(ArrayList<TransferLineItemVO> transferlist,String id,String customerId,double total){ Account a=new Account(); Customer c=new Customer(); for(int i=0;i<transferlist.size();i++){ AccountVO temp; temp = a.findByAccount(transferlist.get(i).bankAccount); temp.balance=temp.balance+transferlist.get(i).account; a.update(temp); } c.updateByReceipt(customerId, total); return ResultMessage.SUCCESS; } //红冲付款单,减少客户应收,减少公司账户金额 public void writeoff(PaymentVO vo){ Account a=new Account(); Customer c=new Customer(); for(int i=0;i<vo.transferList.size();i++){ AccountVO temp; temp = a.findByAccount(vo.transferList.get(i).bankAccount); temp.balance=temp.balance-vo.transferList.get(i).account; a.update(temp); } c.updateByReceipt(vo.customerId,-vo.total); } public ResultMessage update(PaymentVO vo){ try { DataFactoryImpl.getInstance().getPaymentData().update(voToPo(vo)); } catch (RemoteException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } return ResultMessage.SUCCESS; } public PaymentPO voToPo(PaymentVO vo){ ArrayList<TransferLineItemPO> transferList=voListTOpoList(vo.transferList); PaymentPO result=new PaymentPO(vo.id,vo.time,vo.customerId,vo.customerName, vo.operatorId,transferList,vo.total,vo.approvalState.ordinal(),vo.isWriteOff, vo.canWriteOff,vo.documentType.ordinal()); return result; } public ArrayList<TransferLineItemPO> voListTOpoList(ArrayList<TransferLineItemVO> transferList){ ArrayList<TransferLineItemPO> result=new ArrayList<TransferLineItemPO>(); for(int i=0;i<transferList.size();i++){ TransferLineItemVO temp=transferList.get(i); if(temp.remark==null||temp.remark.equals("")) temp.remark="无"; result.add(new TransferLineItemPO(temp.name,temp.bankAccount,temp.account,temp.remark)); } return result; } public PaymentVO poToVo(PaymentPO po){ ArrayList<TransferLineItemVO> transferList=poListTOvoList(po.getTransferList()); PaymentVO result=new PaymentVO(po.getId(),po.getTime(),po.getCustomerId(), po.getCustomerName(),po.getOperatorId(),transferList,po.getTotal(), DocumentStatus.values()[po.getApprovalStatus()],po.isWriteOff(), po.isCanWriteOff(),DocumentType.values()[po.getDocumentType()]); return result; } public ArrayList<TransferLineItemVO> poListTOvoList(ArrayList<TransferLineItemPO> transferList){ ArrayList<TransferLineItemVO> result=new ArrayList<TransferLineItemVO>(); for(int i=0;i<transferList.size();i++){ TransferLineItemPO temp=transferList.get(i); result.add(new TransferLineItemVO(temp.getName(), temp.getBankAccount(),temp.getAccount(),temp.getRemark())); } return result; } public PaymentVO getById(String id){ PaymentVO result=null; try { result=poToVo(DataFactoryImpl.getInstance().getPaymentData().getById(id)); } catch (RemoteException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } return result; } }
vboar/ERPClient
src/businesslogic/paymentbl/Receipt.java
Java
epl-1.0
7,887
package com.odcgroup.integrationfwk.ui.t24connectivity; import java.util.HashMap; import java.util.List; import java.util.Map; public class T24Cache { private static T24Cache t24Cache; public static T24Cache getT24Cache() { if (t24Cache == null) { t24Cache = new T24Cache(); return t24Cache; } else { return t24Cache; } } private final Map<String, StudioProjectCache> fullT24Cache = new HashMap<String, StudioProjectCache>(); private T24Cache() { } public void addApplicationList(List<String> applicationList, String projectName) { StudioProjectCache studioProjectCache = getT24Cache(projectName); if (studioProjectCache != null) { studioProjectCache.setApplicationList(applicationList); } else { studioProjectCache = new StudioProjectCache(); studioProjectCache.setApplicationList(applicationList); addT24Cache(projectName, studioProjectCache); } } public void addApplicationVersion(List<String> applicationVersion, String projectName) { StudioProjectCache studioProjectCache = getT24Cache(projectName); if (studioProjectCache != null) { studioProjectCache.setApplicationVersionList(applicationVersion); } else { studioProjectCache = new StudioProjectCache(); studioProjectCache.setApplicationVersionList(applicationVersion); addT24Cache(projectName, studioProjectCache); } } public void addExitPoint(List<String> exitPoint, String projectName) { StudioProjectCache studioProjectCache = getT24Cache(projectName); if (studioProjectCache != null) { studioProjectCache.setExitPoint(exitPoint); } else { studioProjectCache = new StudioProjectCache(); studioProjectCache.setExitPoint(exitPoint); addT24Cache(projectName, studioProjectCache); } } public void addOverrides(List<String> overrides, String projectName) { StudioProjectCache studioProjectCache = getT24Cache(projectName); if (studioProjectCache != null) { studioProjectCache.setOverrides(overrides); } else { studioProjectCache = new StudioProjectCache(); studioProjectCache.setOverrides(overrides); addT24Cache(projectName, studioProjectCache); } } private void addT24Cache(String projectName, StudioProjectCache studioProjectCache) { fullT24Cache.put(projectName, studioProjectCache); } /** * Helps to add the given list of tsa services into cache using the given * project name. * * @param tsaServiceList * @param projectName */ public void addTSAServiceList(List<String> tsaServiceList, String projectName) { StudioProjectCache studioProjectCache = getT24Cache(projectName); if (studioProjectCache == null) { studioProjectCache = new StudioProjectCache(); } studioProjectCache.setTsaServiceList(tsaServiceList); addT24Cache(projectName, studioProjectCache); } public void addVersionList(List<String> versionList, String projectName) { StudioProjectCache studioProjectCache = getT24Cache(projectName); if (studioProjectCache != null) { studioProjectCache.setVersionList(versionList); } else { studioProjectCache = new StudioProjectCache(); studioProjectCache.setVersionList(versionList); addT24Cache(projectName, studioProjectCache); } } /** * Helps to clear the cache data for respective given project name. * * @param projectName * - name of the project. */ public void clearCache(String projectName) { fullT24Cache.remove(projectName); } public List<String> getApplicationList(String projectName) { StudioProjectCache studioProjectCache = getT24Cache(projectName); if (studioProjectCache == null) { return null; } if (studioProjectCache.getApplicationList() != null) { return studioProjectCache.getApplicationList(); } return null; } public List<String> getApplicationVersionList(String projectName) { StudioProjectCache studioProjectCache = getT24Cache(projectName); if (studioProjectCache == null) { return null; } if (studioProjectCache.getApplicationVersionList() != null) { return studioProjectCache.getApplicationVersionList(); } return null; } public List<String> getExitPointList(String projectName) { StudioProjectCache studioProjectCache = getT24Cache(projectName); if (studioProjectCache == null) { return null; } if (studioProjectCache.getExitPoint() != null) { return studioProjectCache.getExitPoint(); } return null; } public List<String> getOverridesList(String projectName) { StudioProjectCache studioProjectCache = getT24Cache(projectName); if (studioProjectCache == null) { return null; } if (studioProjectCache.getOverrides() != null) { return studioProjectCache.getOverrides(); } return null; } private StudioProjectCache getT24Cache(String projectName) { return fullT24Cache.get(projectName); } /** * Helps to get the TSA services list associated with given project cache. * * @param projectName * @return list of TSA Services. */ public List<String> getTsaServicesList(String projectName) { StudioProjectCache studioProjectCache = getT24Cache(projectName); if (studioProjectCache == null) { return null; } return studioProjectCache.getTsaServiceList(); } public List<String> getVersionList(String projectName) { StudioProjectCache studioProjectCache = getT24Cache(projectName); if (studioProjectCache == null) { return null; } if (studioProjectCache.getVersionList() != null) { return studioProjectCache.getVersionList(); } return null; } }
debabratahazra/DS
designstudio/components/integrationfwk/ui/com.odcgroup.integrationfwk/src/com/odcgroup/integrationfwk/ui/t24connectivity/T24Cache.java
Java
epl-1.0
5,479
package com.yancy.support.pojo; import java.sql.Timestamp; /** * Reports entity. @author MyEclipse Persistence Tools */ public class Reports implements java.io.Serializable { // Fields private Integer id; private Integer userId; private Integer reportDefinitionId; private Timestamp startTime; private Timestamp endTime; private String path; private Timestamp createdAt; private Timestamp updatedAt; // Constructors /** default constructor */ public Reports() { } /** minimal constructor */ public Reports(Timestamp createdAt, Timestamp updatedAt) { this.createdAt = createdAt; this.updatedAt = updatedAt; } /** full constructor */ public Reports(Integer userId, Integer reportDefinitionId, Timestamp startTime, Timestamp endTime, String path, Timestamp createdAt, Timestamp updatedAt) { this.userId = userId; this.reportDefinitionId = reportDefinitionId; this.startTime = startTime; this.endTime = endTime; this.path = path; this.createdAt = createdAt; this.updatedAt = updatedAt; } // Property accessors public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public Integer getUserId() { return this.userId; } public void setUserId(Integer userId) { this.userId = userId; } public Integer getReportDefinitionId() { return this.reportDefinitionId; } public void setReportDefinitionId(Integer reportDefinitionId) { this.reportDefinitionId = reportDefinitionId; } public Timestamp getStartTime() { return this.startTime; } public void setStartTime(Timestamp startTime) { this.startTime = startTime; } public Timestamp getEndTime() { return this.endTime; } public void setEndTime(Timestamp endTime) { this.endTime = endTime; } public String getPath() { return this.path; } public void setPath(String path) { this.path = path; } public Timestamp getCreatedAt() { return this.createdAt; } public void setCreatedAt(Timestamp createdAt) { this.createdAt = createdAt; } public Timestamp getUpdatedAt() { return this.updatedAt; } public void setUpdatedAt(Timestamp updatedAt) { this.updatedAt = updatedAt; } }
yancykim/support
src/com/yancy/support/pojo/Reports.java
Java
epl-1.0
2,174
/* COPYRIGHT-ENEA-SRC-R2 * ************************************************************************** * Copyright (C) 2010 by Enea Software AB. * All rights reserved. * * This Software is furnished under a software license agreement and * may be used only in accordance with the terms of such agreement. * Any other use or reproduction is prohibited. No title to and * ownership of the Software is hereby transferred. * * PROPRIETARY NOTICE * This Software consists of confidential information. * Trade secret law and copyright law protect this Software. * The above notice of copyright on this Software does not indicate * any actual or intended publication of such Software. ************************************************************************** * COPYRIGHT-END */ package com.ose.system; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import com.ose.system.Target.MonitorHandler; import com.ose.system.service.monitor.Monitor; import com.ose.system.service.monitor.MonitorStatus; /** * This class represents an OSE segment and is a node in the hierarchical OSE * system model tree structure. * <p> * A segment has pools, heaps, and blocks as children nodes and a target as * parent node. A segment can be started, stopped, and killed. * * @see com.ose.system.SystemModelNode * @see com.ose.system.OseObject */ public class Segment extends OseObject implements SystemModelNode { /* Internal field read/write lock. */ private final Object lock = new Object(); /* Killed status. */ private boolean killed; /* Parent. */ private final Target target; /* Segment info. */ private final String name; private final int segmentNumber; private int numSignalsAttached; // Not used private boolean masMapped; /* Pools (synchronized list). */ private final List pools; /* Heaps (synchronized list). */ private final List heaps; /* Blocks (synchronized list). */ private final List blocks; /** * Create a new segment object. * * @param target the target. * @param name the segment name. * @param id the segment ID. * @param segmentNumber the segment number. * @param numSignalsAttached the number of attached signals. * @param masMapped whether the segment has MAS mapped regions or not. */ Segment(Target target, String name, int id, int segmentNumber, int numSignalsAttached, boolean masMapped) { super(id); if ((target == null) || (name == null)) { throw new NullPointerException(); } this.target = target; this.name = name; this.segmentNumber = segmentNumber; this.numSignalsAttached = numSignalsAttached; this.masMapped = masMapped; pools = Collections.synchronizedList(new ArrayList()); heaps = Collections.synchronizedList(new ArrayList()); blocks = Collections.synchronizedList(new ArrayList()); } /** * Change the mutable properties of this segment. * * @param numSignalsAttached the number of attached signals. * @param masMapped whether the segment has MAS mapped regions or not. * @return true if any of the mutable properties of this segment were changed, * false otherwise. */ boolean change(int numSignalsAttached, boolean masMapped) { synchronized (lock) { boolean changed = ((this.numSignalsAttached != numSignalsAttached) || (this.masMapped != masMapped)); this.numSignalsAttached = numSignalsAttached; this.masMapped = masMapped; return changed; } } /** * Add a pool to this segment. * * @param pool the pool to add. */ void addPool(Pool pool) { pools.add(pool); } /** * Remove a pool from this segment. * * @param pool the pool to remove. */ void removePool(Pool pool) { pools.remove(pool); } /** * Add a heap to this segment. * * @param heap the heap to add. */ void addHeap(Heap heap) { heaps.add(heap); } /** * Remove a heap from this segment. * * @param heap the heap to remove. */ void removeHeap(Heap heap) { heaps.remove(heap); } /** * Add a block to this segment. * * @param block the block to add. */ void addBlock(Block block) { blocks.add(block); } /** * Remove a block from this segment. * * @param block the block to remove. */ void removeBlock(Block block) { blocks.remove(block); } /** * Determine whether this segment is killed or not. * * @return true if this segment is killed, false otherwise. * @see com.ose.system.SystemModelNode#isKilled() */ public boolean isKilled() { synchronized (lock) { return killed; } } /** * Mark this segment and all its pools, heaps, and blocks as killed. * * @see com.ose.system.OseObject#setKilled() */ void setKilled() { setKilled(true); } /** * Mark this segment and all its pools, heaps, and blocks as killed. * * @param self true if a change event should be fired for this node. */ void setKilled(boolean self) { synchronized (lock) { if (killed) { return; } killed = true; } target.removeId(getId()); for (Iterator i = pools.iterator(); i.hasNext();) { Pool pool = (Pool) i.next(); pool.setKilled(false); } SystemModel.getInstance().fireNodesChanged(this, pools); for (Iterator i = heaps.iterator(); i.hasNext();) { Heap heap = (Heap) i.next(); heap.setKilled(false); } SystemModel.getInstance().fireNodesChanged(this, heaps); for (Iterator i = blocks.iterator(); i.hasNext();) { Block block = (Block) i.next(); block.setKilled(false); } SystemModel.getInstance().fireNodesChanged(this, blocks); if (self) { SystemModel.getInstance().fireNodesChanged(target, Collections.singletonList(this)); } } /** * Determine whether all of the given immutable segment properties are * identical to the ones of this segment. * * @param id ID of a segment. * @param name name of a segment. * @param segmentNumber segment number of a segment. * @return true if all of the given immutable segment properties matches this * segment, false otherwise. */ boolean matches(int id, String name, int segmentNumber) { // Final fields, no synchronization needed. boolean result = false; result = ((getId() == id) && (this.name.equals(name)) && (this.segmentNumber == segmentNumber)); return result; } /** * Return the parent target object. * * @return the parent target object. */ public Target getTarget() { // Final field, no synchronization needed. return target; } /** * Return the name of this segment. * * @return the name of this segment. */ public String getName() { // Final field, no synchronization needed. return name; } /** * Return the segment number of this segment. * * @return the segment number of this segment. */ public int getSegmentNumber() { // Final field, no synchronization needed. return segmentNumber; } /** * Return the number of signals attached to this segment. * * @return the number of signals attached to this segment. */ public int getNumSignalsAttached() { synchronized (lock) { return numSignalsAttached; } } /** * Determine whether this segment has any MAS mapped memory regions or not. * * @return true if this segment has any MAS mapped memory regions, false * otherwise. */ public boolean isMasMapped() { synchronized (lock) { return masMapped; } } /** * Return an array of the pools in this segment (never null). A new array * is created and returned for each call. * * @return an array of the pools in this segment (never null). */ public Pool[] getPools() { return (Pool[]) pools.toArray(new Pool[0]); } /** * Return an array of the heaps in this segment (never null). A new array * is created and returned for each call. * * @return an array of the heaps in this segment (never null). */ public Heap[] getHeaps() { return (Heap[]) heaps.toArray(new Heap[0]); } /** * Return an array of the blocks in this segment (never null). A new array * is created and returned for each call. * * @return an array of the blocks in this segment (never null). */ public Block[] getBlocks() { return (Block[]) blocks.toArray(new Block[0]); } /** * Return the internal list of the pools in this segment (never null). * * @return the internal list of the pools in this segment (never null). * @see Pool */ List getPoolList() { return pools; } /** * Return the internal list of the heaps in this segment (never null). * * @return the internal list of the heaps in this segment (never null). * @see Heap */ List getHeapList() { return heaps; } /** * Return the internal list of the blocks in this segment (never null). * * @return the internal list of the blocks in this segment (never null). * @see Block */ List getBlockList() { return blocks; } /** * Return the parent target object. * * @return the parent target object. * @see com.ose.system.SystemModelNode#getParent() */ public SystemModelNode getParent() { return getTarget(); } /** * Return an array of the children pools, heaps, and blocks in this segment. * A new array is created and returned for each call. * * @return an array of the children pools, heaps, and blocks in this segment. * @see com.ose.system.SystemModelNode#getChildren() * @see Pool * @see Heap * @see Block */ public SystemModelNode[] getChildren() { SystemModelNode[] poolsArray = getPools(); SystemModelNode[] heapsArray = getHeaps(); SystemModelNode[] blocksArray = getBlocks(); int poolsLength = poolsArray.length; int heapsLength = heapsArray.length; int blocksLength = blocksArray.length; SystemModelNode[] children = new SystemModelNode[poolsLength + heapsLength + blocksLength]; System.arraycopy(poolsArray, 0, children, 0, poolsLength); System.arraycopy(heapsArray, 0, children, poolsLength, heapsLength); System.arraycopy(blocksArray, 0, children, poolsLength + heapsLength, blocksLength); return children; } /** * Determine whether this node is a leaf node or not. A segment object is not * a leaf node and always returns false. * * @return false since a segment object is not a leaf node. * @see com.ose.system.SystemModelNode#isLeaf() */ public boolean isLeaf() { return false; } /** * This method has no effect on a segment since a segment has no lazily * initialized properties. * * @param progressMonitor the progress monitor used for cancellation. * @throws IOException if an I/O exception occurred. */ public void initLazyProperties(IProgressMonitor progressMonitor) throws IOException { // Nothing to do. } /** * Update this segment and its pools, heaps, and blocks. If recursive is * true, also update the children nodes of the pool nodes, heap nodes, and * block nodes and so on; i.e. recursivly update the branch in the tree that * is rooted in this segment node. * * @param progressMonitor the progress monitor used for cancellation. * @param recursive whether or not to recursivly update the whole * branch in the tree that is rooted in this segment node. * @throws IOException if an I/O exception occurred; parent target is * automatically disconnected. * @throws ServiceException if the monitor service reported an error. * @throws OperationCanceledException if the operation was interrupted or * cancelled; parent target is automatically disconnected. * @see com.ose.system.SystemModelNode#update(org.eclipse.core.runtime.IProgressMonitor, * boolean) */ public void update(IProgressMonitor progressMonitor, boolean recursive) throws IOException { if (progressMonitor == null) { throw new NullPointerException(); } synchronized (target) { if (!isKilled()) { MonitorHandler monitorHandler = target.getMonitorHandler(); monitorHandler.getSegmentInfoRequest(progressMonitor, this, 1, Monitor.MONITOR_SCOPE_ID, getId()); if (target.hasPoolSupport()) { monitorHandler.getPoolInfoRequest(progressMonitor, this, Monitor.MONITOR_SCOPE_SEGMENT_ID, getId()); } if (target.hasHeapSupport()) { monitorHandler.getHeapInfoRequest(progressMonitor, this, Monitor.MONITOR_SCOPE_SEGMENT_ID, getId()); for (Iterator i = heaps.iterator(); i.hasNext();) { Heap heap = (Heap) i.next(); if (!heap.isKilled()) { heap.updateLazyProperties(progressMonitor); } } } if (target.hasBlockSupport()) { monitorHandler.getBlockInfoRequest(progressMonitor, this, Monitor.MONITOR_SCOPE_SEGMENT_ID, getId()); for (Iterator i = blocks.iterator(); i.hasNext();) { Block block = (Block) i.next(); if (!block.isKilled()) { block.updateLazyProperties(progressMonitor); } } if (recursive) { if (target.hasProcessSupport()) { monitorHandler.getProcessInfoRequest(progressMonitor, this, 1, Monitor.MONITOR_SCOPE_SEGMENT_ID, getId()); } for (Iterator i = blocks.iterator(); i.hasNext();) { Block block = (Block) i.next(); if (!block.isKilled()) { for (Iterator j = block.getProcessList().iterator(); j.hasNext();) { Process process = (Process) j.next(); if (!process.isKilled()) { process.updateLazyProperties(progressMonitor); } } } } } } } } } /** * This method has no effect on a segment since a segment has no lazily * initialized properties. * * @param progressMonitor the progress monitor used for cancellation. * @throws IOException if an I/O exception occurred. */ void updateLazyProperties(IProgressMonitor progressMonitor) throws IOException { // Nothing to do. } /** * Clean this segment, i.e. recursivly remove all nodes marked as killed in * the branch in the tree that is rooted in this segment node. * * @see com.ose.system.SystemModelNode#clean() */ public void clean() { synchronized (target) { if (isKilled()) { target.removeSegment(this); SystemModel.getInstance().fireNodesRemoved(target, Collections.singletonList(this)); } cleanChildren(); } } /** * Clean the pools, heaps, and blocks of this segment recursivly. */ void cleanChildren() { synchronized (target) { List removedChildren = new ArrayList(); List originalBlocks = new ArrayList(blocks); for (Iterator i = pools.iterator(); i.hasNext();) { Pool pool = (Pool) i.next(); if (pool.isKilled()) { i.remove(); removedChildren.add(pool); } } for (Iterator i = heaps.iterator(); i.hasNext();) { Heap heap = (Heap) i.next(); if (heap.isKilled()) { i.remove(); removedChildren.add(heap); } } for (Iterator i = blocks.iterator(); i.hasNext();) { Block block = (Block) i.next(); if (block.isKilled()) { i.remove(); removedChildren.add(block); } } if (!removedChildren.isEmpty()) { SystemModel.getInstance().fireNodesRemoved(this, removedChildren); } for (Iterator i = originalBlocks.iterator(); i.hasNext();) { Block block = (Block) i.next(); block.cleanChildren(); } } } /** * Start this segment if possible. If successful, this segment is recursivly * updated so that itself and its pools, heaps, and blocks are up-to-date. * * @param progressMonitor the progress monitor used for cancellation. * @throws IOException if an I/O exception occurred; parent target is * automatically disconnected. * @throws ServiceException if the monitor service reported an error. * @throws OperationCanceledException if the operation was interrupted or * cancelled; parent target is automatically disconnected. */ public void start(IProgressMonitor progressMonitor) throws IOException { if (progressMonitor == null) { throw new NullPointerException(); } synchronized (target) { update(progressMonitor, true); if (!isKilled()) { if (isStartable()) { target.getMonitorHandler().startScopeRequest(progressMonitor, Monitor.MONITOR_SCOPE_SEGMENT_ID, getId()); update(progressMonitor, true); } else { // Compensate for a missing condition check in the monitor. throw new ServiceException(Target.SERVICE_MONITOR_ID, MonitorStatus.MONITOR_STATUS_CANCELLED, "An attempt was made to start a segment that is not stopped."); } } } } /** * Determine whether this segment can be started or not. * * @return true if this segment can be started, false otherwise. */ boolean isStartable() { synchronized (blocks) { for (Iterator i = blocks.iterator(); i.hasNext();) { Block block = (Block) i.next(); if (!block.isKilled() && !block.isStartable()) { return false; } } } return true; } /** * Stop this segment if possible. If successful, this segment is recursivly * updated so that itself and its pools, heaps, and blocks are up-to-date. * * @param progressMonitor the progress monitor used for cancellation. * @throws IOException if an I/O exception occurred; parent target is * automatically disconnected. * @throws ServiceException if the monitor service reported an error. * @throws OperationCanceledException if the operation was interrupted or * cancelled; parent target is automatically disconnected. */ public void stop(IProgressMonitor progressMonitor) throws IOException { if (progressMonitor == null) { throw new NullPointerException(); } synchronized (target) { if (!isKilled()) { target.getMonitorHandler().stopScopeRequest(progressMonitor, Monitor.MONITOR_SCOPE_SEGMENT_ID, getId()); update(progressMonitor, true); } } } /** * Kill this segment if possible. If successful, this segment is recursivly * updated so that itself and its pools, heaps, and blocks are up-to-date. * * @param progressMonitor the progress monitor used for cancellation. * @throws IOException if an I/O exception occurred; parent target is * automatically disconnected. * @throws ServiceException if the monitor service reported an error. * @throws OperationCanceledException if the operation was interrupted or * cancelled; parent target is automatically disconnected. */ public void kill(IProgressMonitor progressMonitor) throws IOException { if (progressMonitor == null) { throw new NullPointerException(); } synchronized (target) { if (!isKilled()) { target.getMonitorHandler().killScopeRequest(progressMonitor, Monitor.MONITOR_SCOPE_SEGMENT_ID, getId()); update(progressMonitor, true); } } } /** * Check the state of this segment object. If recursive is true, recursivly * check the state of all nodes in the branch in the tree that is rooted in * this segment node. * * @param recursive whether or not to recursivly check the state of all * nodes in the branch in the tree that is rooted in this segment node. * @throws IllegalStateException if this segment object is not in a * consistent state or, if recursive is true, if any node in the branch in * the tree that is rooted in this segment node is not in a consistent state. */ public void checkState(boolean recursive) throws IllegalStateException { // Final fields, no synchronization needed. if (target == null) { throw new IllegalStateException("Target is null."); } if (name == null) { throw new IllegalStateException("Name is null."); } // segmentNumber can be anything. // numSignalsAttached can be anything. // masMapped can be anything. if (pools == null) { throw new IllegalStateException("Pools is null."); } if (heaps == null) { throw new IllegalStateException("Heaps is null."); } if (blocks == null) { throw new IllegalStateException("Blocks is null."); } if (recursive) { synchronized (pools) { for (Iterator i = pools.iterator(); i.hasNext();) { Pool pool = (Pool) i.next(); pool.checkState(recursive); } } synchronized (heaps) { for (Iterator i = heaps.iterator(); i.hasNext();) { Heap heap = (Heap) i.next(); heap.checkState(recursive); } } synchronized (blocks) { for (Iterator i = blocks.iterator(); i.hasNext();) { Block block = (Block) i.next(); block.checkState(recursive); } } } } /** * Return a string representation of this segment object. The returned string * is of the form "&lt;segment-name&gt; (&lt;segment-id&gt;)", where * segment-id is in hexadecimal form. * * @return a string representation of this segment object. * @see java.lang.Object#toString() */ public String toString() { // Final fields, no synchronization needed. return (name + " (0x" + Integer.toHexString(getId()).toUpperCase() + ")"); } }
debabratahazra/OptimaLA
Optima/com.ose.system/src/com/ose/system/Segment.java
Java
epl-1.0
24,458
package samples.javafx.shape; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; /** * How to use shape.<br> * <img alt="image" src="./doc-files/ShapeApp1Simple.png"> * @author sakamoto * */ public class ShapeApp1Simple extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) throws Exception { Group root = new Group(); Circle circle1 = new Circle(160, 160, 120); Circle circle2 = new Circle(100, 120, 20); Circle circle3 = new Circle(160, 120, 20); Rectangle rectangle = new Rectangle(100, 160, 60, 20); circle1.setFill(Color.LINEN); circle2.setFill(Color.BLACK); circle3.setFill(Color.BLACK); rectangle.setFill(Color.RED); root.getChildren().add(circle1); root.getChildren().add(circle2); root.getChildren().add(circle3); root.getChildren().add(rectangle); Scene scene = new Scene(root, 400, 400); stage.setScene(scene); stage.show(); } }
shinsakamoto/practice-javafx
src/samples/javafx/shape/ShapeApp1Simple.java
Java
epl-1.0
1,249
/** * generated by Xtext */ package org.eclipse.xtext.validation.csvalidationtest; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Unassigned Action2 Sub1</b></em>'. * <!-- end-user-doc --> * * * @see org.eclipse.xtext.validation.csvalidationtest.CsvalidationtestPackage#getUnassignedAction2Sub1() * @model * @generated */ public interface UnassignedAction2Sub1 extends UnassignedAction3 { } // UnassignedAction2Sub1
miklossy/xtext-core
org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/validation/csvalidationtest/UnassignedAction2Sub1.java
Java
epl-1.0
459
/****************************************************************************** * * Copyright 2021 Paphus Solutions Inc. * * Licensed under the Eclipse Public License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.botlibre.web.rest; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import org.botlibre.web.Site; import com.braintreegateway.BraintreeGateway; import com.braintreegateway.Environment; /** * DTO for XML Braintree options. */ @XmlRootElement(name="braintree") @XmlAccessorType(XmlAccessType.FIELD) public class BraintreeConfig extends Config{ @XmlAttribute public String customerId; @XmlAttribute public String planId; @XmlAttribute public String nonce; @XmlAttribute public String subId; public static BraintreeGateway gateway = new BraintreeGateway( Environment.PRODUCTION, Site.BRAINTREE_MERCHANT_ID, Site.BRAINTREE_PUBLIC_KEY, Site.BRAINTREE_PRIVATE_KEY ); }
BOTlibre/BOTlibre
botlibre-web/source/org/botlibre/web/rest/BraintreeConfig.java
Java
epl-1.0
1,679
/******************************************************************************* * Copyright (c) 2000, 2007 IBM Corporation and others. All rights reserved. This program and the * accompanying materials are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html Contributors: IBM Corporation - initial API and * implementation *******************************************************************************/ package net.certiv.fluent.dt.ui.editor.text.hover; import org.eclipse.ui.IEditorPart; import net.certiv.dsl.core.DslCore; import net.certiv.dsl.core.preferences.IPrefsManager; import net.certiv.dsl.ui.DslUI; import net.certiv.dsl.ui.editor.text.hover.DslSourceHover; import net.certiv.fluent.dt.core.FluentCore; import net.certiv.fluent.dt.ui.FluentUI; /** Provides source as hover info for Fluent elements. */ public class SourceHover extends DslSourceHover { public SourceHover(IEditorPart editor, IPrefsManager store) { super(editor, store); } @Override public DslUI getDslUI() { return FluentUI.getDefault(); } @Override public DslCore getDslCore() { return FluentCore.getDefault(); } }
grosenberg/fluentmark
net.certiv.fluent.dt.ui/src/main/java/net/certiv/fluent/dt/ui/editor/text/hover/SourceHover.java
Java
epl-1.0
1,239
/* ****************************************************************************** * Copyright (c) 2006-2012 XMind Ltd. and others. * * This file is a part of XMind 3. XMind releases 3 and * above are dual-licensed under the Eclipse Public License (EPL), * which is available at http://www.eclipse.org/legal/epl-v10.html * and the GNU Lesser General Public License (LGPL), * which is available at http://www.gnu.org/licenses/lgpl.html * See http://www.xmind.net/license.html for details. * * Contributors: * XMind Ltd. - initial API and implementation *******************************************************************************/ package org.xmind.ui.resources; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.jface.resource.ColorDescriptor; import org.eclipse.jface.resource.ColorRegistry; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.resource.LocalResourceManager; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; /** * * @author Frank Shaka */ public class ColorUtils { private ColorUtils() { } /** * @deprecated Use {@link LocalResourceManager} */ public static Color getColor(String key, RGB rgb) { if (key == null) { key = toString(rgb); if (key == null) return null; } ColorRegistry reg = JFaceResources.getColorRegistry(); if (!reg.hasValueFor(key)) { if (rgb == null) { rgb = toRGB(key); if (rgb == null) return null; } reg.put(key, rgb); } return reg.get(key); } /** * @deprecated Use {@link LocalResourceManager} */ public static Color getColor(RGB rgb) { return getColor(null, rgb); } /** * @deprecated Use {@link LocalResourceManager} */ public static Color getColor(String s) { return getColor(s, null); } /** * @deprecated Use {@link LocalResourceManager} */ public static Color getColor(int r, int g, int b) { return getColor(new RGB(r, g, b)); } /** * @deprecated Use {@link LocalResourceManager} */ public static Color getRelative(RGB source, int dr, int dg, int db) { return getColor( new RGB(source.red + dr, source.green + dg, source.blue + db)); } /** * @deprecated Use {@link LocalResourceManager} */ public static Color getRelative(Color c, int dr, int dg, int db) { return getRelative(c.getRGB(), dr, dg, db); } public static ColorDescriptor toDescriptor(String s) { return ColorDescriptor.createFrom(toRGB(s)); } private static final Pattern PATTERN_RGBA = Pattern.compile( "rgb\\s*\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*(,\\s*(\\d+)\\s*)?\\)"); //$NON-NLS-1$ public static RGB toRGB(String s) { if (s == null) return null; if (s.startsWith("#")) { //$NON-NLS-1$ int n; try { n = Integer.parseInt(s.substring(1), 16); } catch (NumberFormatException e) { return null; } if (s.length() == 4) { return splitShortRGB(n); } else if (s.length() == 7) { return splitRGB(n); } return null; } Matcher m = PATTERN_RGBA.matcher(s); if (m.matches()) { int r = Integer.parseInt(m.group(1), 10); int g = Integer.parseInt(m.group(2), 10); int b = Integer.parseInt(m.group(3), 10); // currently alpha value is not honored by RGB return new RGB(r, g, b); } return null; } public static String toString(RGB rgb) { if (rgb == null) return null; return String.format("#%06X", merge(rgb)); //$NON-NLS-1$ } public static String toString(Color color) { return color == null ? null : toString(color.getRGB()); } public static String toString(int r, int g, int b) { return String.format("#%06X", merge(r, g, b)); //$NON-NLS-1$ } public static int merge(int r, int g, int b) { return ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff); } public static int merge(RGB rgb) { return merge(rgb.red, rgb.green, rgb.blue); } public static int merge(Color color) { return merge(color.getRGB()); } public static RGB split(int rgb) { return splitRGB(rgb); } private static RGB splitRGB(int rgb) { int r = (rgb >> 16) & 0xff; int g = (rgb >> 8) & 0xff; int b = rgb & 0xff; return new RGB(r, g, b); } private static RGB splitShortRGB(int rgb) { int r = ((rgb >> 8) & 0xf) * 17; int g = ((rgb >> 4) & 0xf) * 17; int b = (rgb & 0xf) * 17; return new RGB(r, g, b); } /** * @deprecated Use {@link LocalResourceManager} */ public static Color darker(Color c) { return getColor(darker(c.getRGB())); } public static RGB darker(RGB rgb) { return new RGB(rgb.red * 2 / 3, rgb.green * 2 / 3, rgb.blue * 2 / 3); } /** * @deprecated Use {@link LocalResourceManager} */ public static Color lighter(Color c) { return getColor(lighter(c.getRGB())); } public static RGB lighter(RGB rgb) { return new RGB(rgb.red + (255 - rgb.red) / 2, rgb.green + (255 - rgb.green) / 2, rgb.blue + (255 - rgb.blue) / 2); } /** * @deprecated Use {@link LocalResourceManager} */ public static Color gradientLighter(Color c) { return getColor(gradientLighter(c.getRGB())); } public static RGB gradientLighter(RGB rgb) { return new RGB(rgb.red + (255 - rgb.red) * 5 / 7, rgb.green + (255 - rgb.green) * 5 / 7, rgb.blue + (255 - rgb.blue) * 5 / 7); } /** * @deprecated Use {@link LocalResourceManager} */ public static Color gray(Color c) { return getColor(gray(c.getRGB())); } public static RGB gray(RGB rgb) { int l = lightness(rgb); return new RGB(l, l, l); } // public static Color foreground(Color back) { // return (back.getRed() < 128 && back.getGreen() < 128 && back.getBlue() < 128) ? ColorConstants.white // : ColorConstants.black; // } private static final int min = 0x60; private static final int max = 0xac; private static final int t = max - min; private static final RGB[] rainbowColors = new RGB[] { new RGB(0xac, 0x60, 0x60), new RGB(0xac, 0xac, 0x60), new RGB(0x60, 0xac, 0x60), new RGB(0x60, 0xac, 0xac), new RGB(0x60, 0x60, 0xac), new RGB(0xac, 0x60, 0xac) }; public static RGB getRainbow(int index, int total) { return rainbowColors[index % 6]; } /** * @deprecated Use {@link LocalResourceManager} */ public static Color getRainbowColor(int index, int total) { return getColor(getRainbow(index, total)); } /** * @deprecated Use {@link LocalResourceManager} */ public static Color getRainbowColor2(int index, int total) { total = Math.abs(total); if (index < 0) index = index % total + total; else if (index >= total) index = index % total; double step = t * 6.0 / total; int f = (int) (step * index); if (f >= 0 && f < t) return getColor(max, min + f, min); if (f >= t && f < t * 2) return getColor(max + t - f, max, min); if (f >= t * 2 && f < t * 3) return getColor(min, max, min + f - t * 2); if (f >= t * 3 && f < t * 4) return getColor(min, max + t * 3 - f, max); if (f >= t * 4 && f < t * 5) return getColor(min + f - t * 4, min, max); return getColor(max, min, max + t * 5 - f); } public static int lightness(Color c) { return lightness(c.getRed(), c.getGreen(), c.getBlue()); } public static int lightness(RGB rgb) { return lightness(rgb.red, rgb.green, rgb.blue); } /** * Lightness = 0.3R + 0.59G + 0.11B * * @param r * @param g * @param b * @return */ public static int lightness(int r, int g, int b) { return (int) (r * 0.3 + g * 0.59 + b * 0.11); } }
nickmain/xmind
bundles/org.xmind.ui.toolkit/src/org/xmind/ui/resources/ColorUtils.java
Java
epl-1.0
8,874
package Tile; import End.Screen; import End.Sprite; public class WallTile extends Tile { public WallTile(Sprite sprite) { super(sprite); } public boolean solid(){ return true; } public void render(int x, int y, Screen screen){ screen.renderTile(x << 4 , y << 4, this); } }
SBe/-PROZ-
Model/WallTile.java
Java
epl-1.0
307
/******************************************************************************* * Copyright (c) 2016 UT-Battelle, LLC. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Robert Smith *******************************************************************************/ package org.eclipse.eavp.tests.viz.service.javafx.mesh.datatypes; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.eclipse.eavp.viz.modeling.Edge; import org.eclipse.eavp.viz.modeling.base.BasicController; import org.eclipse.eavp.viz.modeling.base.BasicMesh; import org.eclipse.eavp.viz.modeling.base.BasicView; import org.eclipse.eavp.viz.modeling.properties.MeshCategory; import org.eclipse.eavp.viz.modeling.properties.MeshProperty; import org.eclipse.eavp.viz.service.javafx.mesh.datatypes.FXEdgeController; import org.eclipse.eavp.viz.service.javafx.mesh.datatypes.FXLinearEdgeView; import org.eclipse.eavp.viz.service.mesh.datastructures.MeshEditorMeshProperty; import org.junit.Ignore; import org.junit.Test; /** * A class for testing the functionality of the FXEdgeController * * @author Robert Smith * */ public class FXEdgeControllerTester { /** * Check that FXEdgeControllers can be properly cloned. */ @Test @Ignore public void checkClone() { // Create a cloned FXShape and check that it is identical to the // original Edge mesh = new Edge(); FXEdgeController edge = new FXEdgeController(mesh, new FXLinearEdgeView(mesh)); edge.setProperty(MeshProperty.INNER_RADIUS, "Property"); Object clone = edge.clone(); // A view's clone does not necessarily equal the original, as JavaFX // classes lack an equals() function assertTrue(edge instanceof FXEdgeController); } /** * Check that the controller propagates properties changes to its children * correctly. */ @Test public void checkProperties() { // Create an edge for testing Edge mesh = new Edge(); FXEdgeController edge = new FXEdgeController(mesh, new BasicView()); // Give a child entity to the edge BasicController child = new BasicController(new BasicMesh(), new BasicView()); edge.addEntityToCategory(child, MeshCategory.VERTICES); // Set the Constructing property. This change should be mirrored in the // edge's children. edge.setProperty(MeshEditorMeshProperty.UNDER_CONSTRUCTION, "True"); assertTrue("True".equals( child.getProperty(MeshEditorMeshProperty.UNDER_CONSTRUCTION))); // Set the Selected property. This changed should be mirrored in the // edge's children edge.setProperty(MeshProperty.SELECTED, "True"); assertTrue("True".equals(child.getProperty(MeshProperty.SELECTED))); // Set a different property. This change should not be reflected in the // child edge.setProperty(MeshProperty.INNER_RADIUS, "Property"); assertFalse("Property" .equals(child.getProperty(MeshProperty.INNER_RADIUS))); } }
eclipse/eavp
org.eclipse.eavp.tests.viz.service.javafx.mesh/src/org/eclipse/eavp/tests/viz/service/javafx/mesh/datatypes/FXEdgeControllerTester.java
Java
epl-1.0
3,209
/******************************************************************************* * Copyright (c) 2008 The Eclipse Foundation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * The Eclipse Foundation - initial API and implementation *******************************************************************************/ package ca.ubc.cs.commandrecommender.usagedata.ui.preview; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.ui.forms.widgets.FormText; import ca.ubc.cs.commandrecommender.usagedata.gathering.events.UsageDataEvent; import ca.ubc.cs.commandrecommender.usagedata.recording.UsageDataRecordingActivator; import ca.ubc.cs.commandrecommender.usagedata.recording.filtering.FilterChangeListener; import ca.ubc.cs.commandrecommender.usagedata.recording.filtering.FilterUtils; import ca.ubc.cs.commandrecommender.usagedata.recording.filtering.PreferencesBasedFilter; import ca.ubc.cs.commandrecommender.usagedata.recording.storage.IEventStorageConverter; import ca.ubc.cs.commandrecommender.usagedata.recording.storage.StorageConverterException; import ca.ubc.cs.commandrecommender.usagedata.recording.uploading.UploadParameters; import ca.ubc.cs.commandrecommender.usagedata.ui.Activator; import com.ibm.icu.text.DateFormat; public class UploadPreview { private final UploadParameters parameters; TableViewer viewer; Job contentJob; List<UsageDataEventWrapper> events = Collections.synchronizedList(new ArrayList<UsageDataEventWrapper>()); private static final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); private UsageDataTableViewerColumn includeColumn; private UsageDataTableViewerColumn whatColumn; private UsageDataTableViewerColumn kindColumn; private UsageDataTableViewerColumn descriptionColumn; private UsageDataTableViewerColumn bundleIdColumn; private UsageDataTableViewerColumn bundleVersionColumn; private UsageDataTableViewerColumn timestampColumn; private Color colorGray; private Color colorBlack; private Image xImage; private Cursor busyCursor; Button removeFilterButton; private Button eclipseOnlyButton; private Button addFilterButton; public UploadPreview(UploadParameters parameters) { this.parameters = parameters; } public Control createControl(final Composite parent) { allocateResources(parent); Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout()); createDescriptionText(composite); createEventsTable(composite); createEclipseOnlyButton(composite); createButtons(composite); /* * Bit of a crazy idea. Add a paint listener that will * start the job of actually populating the page when * the composite is exposed. If the instance is created * in a wizard, it won't start populating until the user * actually switches to the page. */ final PaintListener paintListener = new PaintListener() { boolean called = false; // Don't need to synchronize since this will only ever be called in the UI thread. public void paintControl(PaintEvent e) { if (called) return; called = true; startContentJob(); } }; composite.addPaintListener(paintListener); return composite; } /* * This method allocates the resources used by the receiver. * It installs a dispose listener on parent so that when * the parent is disposed, the allocated resources will be * deallocated. */ private void allocateResources(Composite parent) { colorGray = parent.getDisplay().getSystemColor(SWT.COLOR_GRAY); colorBlack = parent.getDisplay().getSystemColor(SWT.COLOR_BLACK); busyCursor = parent.getDisplay().getSystemCursor(SWT.CURSOR_WAIT); xImage = Activator.getDefault().getImageDescriptor("/icons/x.png").createImage(parent.getDisplay()); //$NON-NLS-1$ parent.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { xImage.dispose(); } }); } private void createDescriptionText(Composite parent) { FormText text = new FormText(parent, SWT.NONE); text.setImage("x", xImage); //$NON-NLS-1$ text.setText(Messages.UploadPreview_2, true, false); GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, false); layoutData.widthHint = 500; text.setLayoutData(layoutData); } private void createEventsTable(Composite parent) { viewer = new TableViewer(parent, SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); viewer.getTable().setHeaderVisible(true); viewer.getTable().setLinesVisible(false); GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, true); layoutData.widthHint = 500; viewer.getTable().setLayoutData(layoutData); createIncludeColumn(); createWhatColumn(); createKindColumn(); createDescriptionColumn(); createBundleIdColumn(); createBundleVersionColumn(); createTimestampColumn(); timestampColumn.setSortColumn(); viewer.setContentProvider(new IStructuredContentProvider() { public void dispose() { } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } @SuppressWarnings("unchecked") public Object[] getElements(Object input) { if (input instanceof List) { return (Object[]) ((List<UsageDataEventWrapper>)input).toArray(new Object[((List<UsageDataEventWrapper>)input).size()]); } return new Object[0]; } }); /* * Add a FilterChangeListener to the filter; if the filter changes, we need to * refresh the display. The dispose listener, added to the table will clean * up the FilterChangeListener when the table is disposed. */ final FilterChangeListener filterChangeListener = new FilterChangeListener() { public void filterChanged() { for (UsageDataEventWrapper event : events) { event.resetCaches(); } viewer.refresh(); } }; parameters.getUserDefinedFilter().addFilterChangeListener(filterChangeListener); viewer.getTable().addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { parameters.getUserDefinedFilter().removeFilterChangeListener(filterChangeListener); } }); // Initially, we have nothing. viewer.setInput(events); } private void createIncludeColumn() { includeColumn = new UsageDataTableViewerColumn(SWT.CENTER); includeColumn.setLabelProvider(new UsageDataColumnProvider() { @Override public Image getImage(UsageDataEventWrapper event) { if (!event.isIncludedByFilter()) return xImage; return null; } }); } private void createWhatColumn() { whatColumn = new UsageDataTableViewerColumn(SWT.LEFT); whatColumn.setText(Messages.UploadPreview_3); whatColumn.setLabelProvider(new UsageDataColumnProvider() { @Override public String getText(UsageDataEventWrapper event) { return event.getWhat(); } }); } private void createKindColumn() { kindColumn = new UsageDataTableViewerColumn(SWT.LEFT); kindColumn.setText(Messages.UploadPreview_4); kindColumn.setLabelProvider(new UsageDataColumnProvider() { @Override public String getText(UsageDataEventWrapper event) { return event.getKind(); } }); } private void createDescriptionColumn() { descriptionColumn = new UsageDataTableViewerColumn(SWT.LEFT); descriptionColumn.setText(Messages.UploadPreview_5); descriptionColumn.setLabelProvider(new UsageDataColumnProvider() { @Override public String getText(UsageDataEventWrapper event) { return event.getDescription(); } }); } private void createBundleIdColumn() { bundleIdColumn = new UsageDataTableViewerColumn(SWT.LEFT); bundleIdColumn.setText(Messages.UploadPreview_6); bundleIdColumn.setLabelProvider(new UsageDataColumnProvider() { @Override public String getText(UsageDataEventWrapper event) { return event.getBundleId(); } }); } private void createBundleVersionColumn() { bundleVersionColumn = new UsageDataTableViewerColumn(SWT.LEFT); bundleVersionColumn.setText(Messages.UploadPreview_7); bundleVersionColumn.setLabelProvider(new UsageDataColumnProvider() { @Override public String getText(UsageDataEventWrapper event) { return event.getBundleVersion(); } }); } private void createTimestampColumn() { timestampColumn = new UsageDataTableViewerColumn(SWT.LEFT); timestampColumn.setText(Messages.UploadPreview_8); timestampColumn.setLabelProvider(new UsageDataColumnProvider() { @Override public String getText(UsageDataEventWrapper event) { return dateFormat.format(new Date(event.getWhen())); } }); timestampColumn.setSorter(new Comparator<UsageDataEventWrapper>() { public int compare(UsageDataEventWrapper event1, UsageDataEventWrapper event2) { if (event1.getWhen() == event2.getWhen()) return 0; return event1.getWhen() > event2.getWhen() ? 1 : -1; } }); } private void createButtons(Composite parent) { Composite buttons = new Composite(parent, SWT.NONE); GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, false); buttons.setLayoutData(layoutData); buttons.setLayout(new RowLayout()); createAddFilterButton(buttons); createRemoveFilterButton(buttons); final FilterChangeListener filterChangeListener = new FilterChangeListener() { public void filterChanged() { updateButtons(); } }; parameters.getUserDefinedFilter().addFilterChangeListener(filterChangeListener); parent.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { parameters.getUserDefinedFilter().removeFilterChangeListener(filterChangeListener); } }); updateButtons(); } private void createEclipseOnlyButton(Composite buttons) { eclipseOnlyButton = new Button(buttons, SWT.CHECK); eclipseOnlyButton.setText(Messages.UploadPreview_9); eclipseOnlyButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ((PreferencesBasedFilter)parameters.getUserDefinedFilter()).setEclipseOnly(eclipseOnlyButton.getSelection()); } }); } private void updateButtons() { if (parameters.getUserDefinedFilter() instanceof PreferencesBasedFilter) { PreferencesBasedFilter filter = (PreferencesBasedFilter)parameters.getUserDefinedFilter(); if (filter.isEclipseOnly()) { eclipseOnlyButton.setSelection(true); addFilterButton.setEnabled(false); removeFilterButton.setEnabled(false); } else { eclipseOnlyButton.setSelection(false); addFilterButton.setEnabled(true); removeFilterButton.setEnabled(filter.getFilterPatterns().length > 0); } } } private void createAddFilterButton(Composite parent) { if (parameters.getUserDefinedFilter() instanceof PreferencesBasedFilter) { addFilterButton = new Button(parent, SWT.PUSH); addFilterButton.setText(Messages.UploadPreview_10); addFilterButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { new AddFilterDialog((PreferencesBasedFilter)parameters.getUserDefinedFilter()).prompt(viewer.getTable().getShell(), getFilterSuggestion()); } }); } } private void createRemoveFilterButton(Composite parent) { if (parameters.getUserDefinedFilter() instanceof PreferencesBasedFilter) { removeFilterButton = new Button(parent, SWT.PUSH); removeFilterButton.setText(Messages.UploadPreview_11); removeFilterButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { new RemoveFilterDialog((PreferencesBasedFilter)parameters.getUserDefinedFilter()).prompt(viewer.getTable().getShell()); } }); } } // TODO Return a more interesting suggestion based on the selection. String getFilterSuggestion() { IStructuredSelection selection = (IStructuredSelection) viewer.getSelection(); if (selection != null) { if (selection.size() == 1) { return getFilterSuggestionBasedOnSingleSelection(selection); } if (selection.size() > 1) { return getFilterSuggestionBasedOnMultipleSelection(selection); } } return FilterUtils.getDefaultFilterSuggestion(); } String getFilterSuggestionBasedOnSingleSelection( IStructuredSelection selection) { return ((UsageDataEventWrapper)selection.getFirstElement()).getBundleId(); } String getFilterSuggestionBasedOnMultipleSelection(IStructuredSelection selection) { String[] names = new String[selection.size()]; int index = 0; for (Object event : selection.toArray()) { names[index++] = ((UsageDataEventWrapper)event).getBundleId(); } return FilterUtils.getFilterSuggestionBasedOnBundleIds(names); } /** * This method starts the job that populates the list of * events. */ synchronized void startContentJob() { if (contentJob != null) return; contentJob = new Job("Generate Usage Data Upload Preview") { //$NON-NLS-1$ @Override protected IStatus run(IProgressMonitor monitor) { setTableCursor(busyCursor); obtainData(monitor); setTableCursor(null); if (monitor.isCanceled()) return Status.CANCEL_STATUS; return Status.OK_STATUS; } private void setTableCursor(final Cursor cursor) { if (isDisposed()) return; getDisplay().syncExec(new Runnable() { public void run() { if (isDisposed()) return; viewer.getTable().setCursor(cursor); } }); } }; contentJob.setPriority(Job.LONG); contentJob.schedule(); } protected void obtainData(IProgressMonitor monitor) { IEventStorageConverter converter = UsageDataRecordingActivator.getDefault().getStorageConverter(); List<UsageDataEvent> events; try { events = converter.readEvents(); monitor.beginTask("Loading Data", events.size()); ArrayList<UsageDataEventWrapper> wrappers = new ArrayList<UsageDataEventWrapper>(); for (UsageDataEvent event : events) { wrappers.add(new UsageDataEventWrapper(parameters, event)); monitor.worked(1); } addEvents(wrappers); } catch (StorageConverterException e) { Activator.getDefault().log(IStatus.WARNING, e, "An error occurred while reading the usage data."); } finally { monitor.done(); } } boolean isDisposed() { if (viewer == null) return true; if (viewer.getTable() == null) return true; return viewer.getTable().isDisposed(); } /* * This method adds the list of events to the master list maintained * by the instance. It also updates the table. */ void addEvents(List<UsageDataEventWrapper> newEvents) { if (isDisposed()) return; events.addAll(newEvents); final Object[] array = (Object[]) newEvents.toArray(new Object[newEvents.size()]); getDisplay().syncExec(new Runnable() { public void run() { if (isDisposed()) return; viewer.add(array); resizeColumns(array); } }); } private Display getDisplay() { return viewer.getTable().getDisplay(); } /* * Oddly enough, this method resizes the columns. In order to figure out how * wide to make the columns, we need to use a GC (specifically, the * {@link GC#textExtent(String)} method). To avoid creating too many of * them, we create one in this method and pass it into the helper method * {@link #resizeColumn(GC, UsageDataTableViewerColumn)} which does most of * the heavy lifting. * * This method must be run in the UI Thread. */ void resizeColumns(final Object[] events) { if (isDisposed()) return; GC gc = new GC(getDisplay()); gc.setFont(viewer.getTable().getFont()); resizeColumn(gc, includeColumn, events); resizeColumn(gc, whatColumn, events); resizeColumn(gc, kindColumn, events); resizeColumn(gc, bundleIdColumn, events); resizeColumn(gc, bundleVersionColumn, events); resizeColumn(gc, descriptionColumn, events); resizeColumn(gc, timestampColumn, events); gc.dispose(); } void resizeColumn(GC gc, UsageDataTableViewerColumn column, Object[] events) { column.resize(gc, events); } /** * The {@link UsageDataTableViewerColumn} provides a level of abstraction * for building table columns specifically for the table displaying * instances of {@link UsageDataEventWrapper}. Instances automatically know how to * sort themselves (ascending only) with help from the label provider. This * behaviour can be overridden by providing an alternative * {@link Comparator}. */ class UsageDataTableViewerColumn { private TableViewerColumn column; private UsageDataColumnProvider usageDataColumnProvider; /** * The default comparator knows how to compare objects based on the * string value returned for each instance by the * {@link UsageDataColumnProvider#getText(UsageDataEventWrapper)} * method. */ private Comparator<UsageDataEventWrapper> comparator = new Comparator<UsageDataEventWrapper>() { public int compare(UsageDataEventWrapper event1, UsageDataEventWrapper event2) { if (usageDataColumnProvider == null) return 0; String text1 = usageDataColumnProvider.getText(event1); String text2 = usageDataColumnProvider.getText(event2); if (text1 == null && text2 == null) return 0; if (text1 == null) return -1; if (text2 == null) return 1; return text1.compareTo(text2); } }; private ViewerSorter sorter = new ViewerSorter() { @Override public int compare(Viewer viewer, Object object1, Object object2) { return comparator.compare((UsageDataEventWrapper)object1, (UsageDataEventWrapper)object2); } }; private SelectionListener selectionListener = new SelectionAdapter() { /** * When the column is selected (clicked on by the * the user, sort the table based on the value * presented in that column. */ @Override public void widgetSelected(SelectionEvent e) { setSortColumn(); } }; public UsageDataTableViewerColumn(int style) { column = new TableViewerColumn(viewer, style); initialize(); } public void setSortColumn() { getTable().setSortColumn(getColumn()); getTable().setSortDirection(SWT.DOWN); viewer.setSorter(sorter); } private void initialize() { getColumn().addSelectionListener(selectionListener); getColumn().setWidth(25); } // // DeferredContentProvider getContentProvider() { // return (DeferredContentProvider)viewer.getContentProvider(); // } TableColumn getColumn() { return column.getColumn(); } Table getTable() { return viewer.getTable(); } public void setSorter(Comparator<UsageDataEventWrapper> comparator) { // TODO May need to handle the case when the active comparator is changed. this.comparator = comparator; } public void resize(GC gc, Object[] objects) { int width = usageDataColumnProvider.getMaximumWidth(gc, objects) + 20; width = Math.max(getColumn().getWidth(), width); getColumn().setWidth(width); } public void setLabelProvider(UsageDataColumnProvider usageDataColumnProvider) { this.usageDataColumnProvider = usageDataColumnProvider; column.setLabelProvider(usageDataColumnProvider); } public void setWidth(int width) { getColumn().setWidth(width); } public void setText(String text) { getColumn().setText(text); } } /** * The {@link UsageDataColumnProvider} is a column label provider * that includes some convenience methods. */ abstract class UsageDataColumnProvider extends ColumnLabelProvider { /** * This convenience method is used to determine an appropriate * width for the column based on the collection of event objects. * The returned value is the maximum width (in pixels) of the * text the receiver associates with each of the events. The * events are provided as Object[] because converting them to * {@link UsageDataEventWrapper}[] would be an unnecessary expense. * * @param gc a {@link GC} loaded with the font used to display the events. * @param events an array of {@link UsageDataEventWrapper} instances. * @return the width of the widest event */ public int getMaximumWidth(GC gc, Object[] events) { int width = 0; for (Object event : events) { Point extent = gc.textExtent(getText(event)); int x = extent.x; Image image = getImage(event); if (image != null) x += image.getBounds().width; if (x > width) width = x; } return width; } /** * This method provides a foreground colour for the cell. * The cell will be black if the filter includes the * includes the provided {@link UsageDataEvent}, or gray if the filter * excludes it. */ @Override public Color getForeground(Object element) { if (((UsageDataEventWrapper)element).isIncludedByFilter()) { return colorBlack; } else { return colorGray; } } @Override public String getText(Object element) { return getText((UsageDataEventWrapper)element); } @Override public Image getImage(Object element) { return getImage((UsageDataEventWrapper)element); } public String getText(UsageDataEventWrapper element) { return ""; //$NON-NLS-1$ } public Image getImage(UsageDataEventWrapper element) { return null; } } }
ubc-cs-spl/command-recommender
plugins/ca.ubc.cs.commandrecommender.usagedata.ui/src/ca/ubc/cs/commandrecommender/usagedata/ui/preview/UploadPreview.java
Java
epl-1.0
23,516
/* * IronJacamar, a Java EE Connector Architecture implementation * Copyright 2014, 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 Eclipse Public License 1.0 as * published by the Free Software Foundation. * * 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 Eclipse * Public License for more details. * * You should have received a copy of the Eclipse 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.ironjacamar.core; import org.jboss.logging.BasicLogger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; import static org.jboss.logging.Logger.Level.ERROR; import static org.jboss.logging.Logger.Level.WARN; /** * The core logger. * * Message ids ranging from 000000 to 009999 inclusively. */ @MessageLogger(projectCode = "IJ2") public interface CoreLogger extends BasicLogger { // WORK MANAGER (200) /** * SecurityContext setup failed * @param description throwable description * @param t The exception */ @LogMessage(level = ERROR) @Message(id = 201, value = "SecurityContext setup failed: %s") public void securityContextSetupFailed(String description, @Cause Throwable t); /** * SecurityContext setup failed since CallbackSecurity was null */ @LogMessage(level = ERROR) @Message(id = 202, value = "SecurityContext setup failed since CallbackSecurity was null") public void securityContextSetupFailedCallbackSecurityNull(); // CORE (300) /** * Error during beforeCompletion * @param cl AbstractConnectionListener instance * @param t The exception */ @LogMessage(level = WARN) @Message(id = 314, value = "Error during beforeCompletion: %s") public void beforeCompletionErrorOccured(Object cl, @Cause Throwable t); /** * Active handles * @param pool The name of the pool * @param number The number of active handles */ @LogMessage(level = ERROR) @Message(id = 315, value = "Pool %s has %d active handles") public void activeHandles(String pool, int number); /** * Active handle * @param handle The handle * @param e The trace */ @LogMessage(level = ERROR) @Message(id = 316, value = "Handle allocation: %s") public void activeHandle(Object handle, @Cause Exception e); /** * TxConnectionListener boundary * @param e The trace */ @LogMessage(level = ERROR) @Message(id = 317, value = "Transaction boundary") public void txConnectionListenerBoundary(@Cause Exception e); // NAMING (700) /** * Exception during unbind * @param t The exception */ @LogMessage(level = WARN) @Message(id = 701, value = "Exception during unbind") public void exceptionDuringUnbind(@Cause Throwable t); // RECOVERY (900) /** * Error during connection close * @param t The exception */ @LogMessage(level = WARN) @Message(id = 901, value = "Error during connection close") public void exceptionDuringConnectionClose(@Cause Throwable t); /** * Error during inflow crash recovery * @param rar The resource adapter class name * @param as The activation spec * @param t The exception */ @LogMessage(level = ERROR) @Message(id = 902, value = "Error during inflow crash recovery for '%s' (%s)") public void exceptionDuringCrashRecoveryInflow(String rar, Object as, @Cause Throwable t); /** * Error creating Subject for crash recovery * @param jndiName The JNDI name * @param reason The reason * @param t The exception */ @LogMessage(level = ERROR) @Message(id = 903, value = "Error creating Subject for crash recovery: %s (%s)") public void exceptionDuringCrashRecoverySubject(String jndiName, String reason, @Cause Throwable t); /** * No security domain defined for crash recovery * @param jndiName The JNDI name */ @LogMessage(level = WARN) @Message(id = 904, value = "No security domain defined for crash recovery: %s") public void noCrashRecoverySecurityDomain(String jndiName); /** * Subject for crash recovery was null * @param jndiName The JNDI name */ @LogMessage(level = WARN) @Message(id = 905, value = "Subject for crash recovery was null: %s") public void nullSubjectCrashRecovery(String jndiName); /** * Error during crash recovery * @param jndiName The JNDI name * @param reason The reason * @param t The exception */ @LogMessage(level = ERROR) @Message(id = 906, value = "Error during crash recovery: %s (%s)") public void exceptionDuringCrashRecovery(String jndiName, String reason, @Cause Throwable t); // SECURITY (1000) /** * No users.properties were found */ @LogMessage(level = WARN) @Message(id = 1001, value = "No users.properties were found") public void noUsersPropertiesFound(); /** * Error while loading users.properties * @param t The exception */ @LogMessage(level = ERROR) @Message(id = 1002, value = "Error while loading users.properties") public void errorWhileLoadingUsersProperties(@Cause Throwable t); /** * No roles.properties were found */ @LogMessage(level = WARN) @Message(id = 1003, value = "No roles.properties were found") public void noRolesPropertiesFound(); /** * Error while loading roles.properties * @param t The exception */ @LogMessage(level = ERROR) @Message(id = 1004, value = "Error while loading roles.properties") public void errorWhileLoadingRolesProperties(@Cause Throwable t); /** * No callback.properties were found */ @LogMessage(level = WARN) @Message(id = 1005, value = "No callback.properties were found") public void noCallbackPropertiesFound(); /** * Error while loading callback.properties * @param t The exception */ @LogMessage(level = ERROR) @Message(id = 1006, value = "Error while loading callback.properties") public void errorWhileLoadingCallbackProperties(@Cause Throwable t); // TRANSCATION (1100) /** * Prepare called on a local tx */ @LogMessage(level = WARN) @Message(id = 1101, value = "Prepare called on a local tx. Use of local transactions on a JTA " + "transaction with more than one branch may result in inconsistent data in some cases of failure") public void prepareCalledOnLocaltx(); }
jesperpedersen/ironjacamar
core/src/main/java/org/ironjacamar/core/CoreLogger.java
Java
epl-1.0
6,999
/****************************************************************************** * Copyright (c) 2000-2016 Ericsson Telecom AB * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.eclipse.titan.designer.wizards.projectFormat; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import org.eclipse.core.filesystem.URIUtil; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.QualifiedName; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Text; import org.eclipse.titan.common.logging.ErrorReporter; import org.eclipse.titan.designer.properties.data.ProjectBuildPropertyData; /** * @author Kristof Szabados * */ class TITANProjectExportMainPage extends WizardPage { private final IStructuredSelection selection; private Text projectFileText; private Button projectFileSelectionButton; /** * Project file path in string format, e.g C:/MyFolder/myFile or /home/MyFolder/myFile or myFile */ private String projectFile = null; private IProject project = null; private BasicProjectSelectorListener generalListener = new BasicProjectSelectorListener(); protected class BasicProjectSelectorListener implements ModifyListener, SelectionListener { @Override public void modifyText(final ModifyEvent e) { Object source = e.getSource(); if (source == projectFileText) { handleProjectFileModified(); } } @Override public void widgetDefaultSelected(final SelectionEvent e) { //Do nothing } @Override public void widgetSelected(final SelectionEvent e) { Object source = e.getSource(); if (source == projectFileSelectionButton) { handleProjectFileButtonSelected(); } } } public TITANProjectExportMainPage(final String name, final IStructuredSelection selection) { super(name); this.selection = selection; } public String getProjectFilePath() { return projectFile; } @Override public void createControl(final Composite parent) { Composite pageComposite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); pageComposite.setLayout(layout); GridData data = new GridData(GridData.FILL); data.grabExcessHorizontalSpace = true; pageComposite.setLayoutData(data); check(projectFile); createProjectFileEditor(pageComposite); setControl(pageComposite); } /** * Check the current setup, whether it is allowed to do the exportation * or not. * * @param filePath * the path of the file as it is seen now. * */ private boolean check(final String filePath) { project = null; if (selection == null) { setErrorMessage("A project must be selected for the export wizard to work."); return false; } if (selection.size() != 1) { setErrorMessage("Exactly 1 project has to be selected"); return false; } List<?> selectionList = selection.toList(); if (!(selectionList.get(0) instanceof IProject)) { setErrorMessage("A project has to be selected"); return false; } project = (IProject) selectionList.get(0); if (filePath != null) { IPath projectFilePath = Path.fromOSString(filePath); if (!projectFilePath.isValidPath(filePath)) { setErrorMessage("The provided file path does not seem to be valid on this platform"); return false; } } return true; } protected void createProjectFileEditor(final Composite parent) { Font font = parent.getFont(); Group group = new Group(parent, SWT.NONE); group.setText("Target project file:"); GridData gd = new GridData(GridData.FILL_HORIZONTAL); group.setLayoutData(gd); GridLayout layout = new GridLayout(); layout.numColumns = 2; group.setLayout(layout); group.setFont(font); projectFileText = new Text(group, SWT.SINGLE | SWT.BORDER); gd = new GridData(GridData.FILL_HORIZONTAL); projectFileText.setLayoutData(gd); projectFileText.setFont(font); projectFileText.addModifyListener(generalListener); if(project != null) { projectFileText.setText(project.getName() + ".tpd"); //default value try { // if this project is imported, the location of the source tpd is stored in loadLocation, // if this project is not imported then loadLocation == null and the new default tpd will be defined // in the current project folder in the current workspace //URI string or path string:: String loadLocation = project.getPersistentProperty(new QualifiedName(ProjectBuildPropertyData.QUALIFIER, ProjectBuildPropertyData.LOAD_LOCATION)); if (loadLocation != null) { URI projectFileURI = new URI(loadLocation); IPath projectFilePath = URIUtil.toPath(projectFileURI); if(projectFilePath != null) { projectFileText.setText(projectFilePath.toString());//bugfix by ethbaat // FIXME: toOSString() ??? } } else if(project.getLocation() != null){ projectFileText.setText(project.getLocation().append(project.getName() + ".tpd").toOSString()); //FIXME: toString() ??? } } catch (CoreException e) { ErrorReporter.logExceptionStackTrace(e); } catch (URISyntaxException e) { //bad loadLocation input: ErrorReporter.logExceptionStackTrace(e); } } projectFileSelectionButton = new Button(group, SWT.PUSH); projectFileSelectionButton.setText("Browse.."); projectFileSelectionButton.setLayoutData(new GridData()); projectFileSelectionButton.addSelectionListener(generalListener); } protected void handleProjectFileButtonSelected() { FileDialog dialog = new FileDialog(getShell()); IPath path = new Path(projectFileText.getText()); dialog.setFileName(path.lastSegment()); dialog.setFilterExtensions(new String[] { "*.tpd" }); final String file = dialog.open(); if (file != null) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { projectFileText.setText(file); } }); } if (check(file)) { projectFile = file; } } protected void handleProjectFileModified() { String temp = projectFileText.getText(); if (check(temp)) { projectFile = temp; } } }
eroslevi/titan.EclipsePlug-ins
org.eclipse.titan.designer/src/org/eclipse/titan/designer/wizards/projectFormat/TITANProjectExportMainPage.java
Java
epl-1.0
7,050
/* * Copyright 2012 PRODYNA AG * * Licensed under the Eclipse Public License (EPL), Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/eclipse-1.0.php or * http://www.nabucco.org/License.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.nabucco.framework.importing.ui.rcp.list.importjob.view.label; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.swt.graphics.Image; import org.nabucco.framework.importing.facade.datatype.ImportJob; /** * ImportJobListViewOwnerLabelProvider * * @author Undefined */ public class ImportJobListViewOwnerLabelProvider implements ILabelProvider { /** Constructs a new ImportJobListViewOwnerLabelProvider instance. */ public ImportJobListViewOwnerLabelProvider() { super(); } @Override public Image getImage(Object arg0) { return null; } @Override public String getText(Object arg0) { String result = ""; if ((arg0 instanceof ImportJob)) { ImportJob importJob = ((ImportJob) arg0); result = ((importJob.getOwner() != null) ? importJob.getOwner().toString() : ""); } return result; } @Override public void addListener(ILabelProviderListener arg0) { } @Override public void dispose() { } @Override public boolean isLabelProperty(Object arg0, String arg1) { return false; } @Override public void removeListener(ILabelProviderListener arg0) { } }
NABUCCO/org.nabucco.framework.importing
org.nabucco.framework.importing.ui.rcp/src/main/gen/org/nabucco/framework/importing/ui/rcp/list/importjob/view/label/ImportJobListViewOwnerLabelProvider.java
Java
epl-1.0
1,955
package de.ptb.epics.eve.data.scandescription.errors; import de.ptb.epics.eve.data.scandescription.AbstractPostscanBehavior; /** * This class describes a model error of a postscan. * * @author Stephan Rehfeld <stephan.rehfeld (-at-) ptb.de> * */ public class PostscanError implements IModelError { private final AbstractPostscanBehavior postscanBahavior; private final PostscanErrorTypes errorType; /** * This constructor creates a new error for a postscan. * * @param postscanBahavior The postscan. Must not be 'null' * @param errorType The error type. Must not be 'null'! */ public PostscanError(final AbstractPostscanBehavior postscanBahavior, final PostscanErrorTypes errorType) { if (postscanBahavior == null) { throw new IllegalArgumentException( "The parameter 'postscanBahavior' must not be null!"); } if (errorType == null) { throw new IllegalArgumentException( "The parameter 'errorType' must not be null!"); } this.postscanBahavior = postscanBahavior; this.errorType = errorType; } /** * This method returns the postscan where the error occurred. * * @return The postscan where the error occurred. Never returns 'null'. */ public AbstractPostscanBehavior getPostscanBahavior() { return this.postscanBahavior; } /** * This method return the type of the error. * * @return The type of the error. Never returns 'null'. */ public PostscanErrorTypes getErrorType() { return this.errorType; } /** * {@inheritDoc} */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((errorType == null) ? 0 : errorType.hashCode()); result = prime * result + ((postscanBahavior == null) ? 0 : postscanBahavior .hashCode()); return result; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } PostscanError other = (PostscanError) obj; if (errorType == null) { if (other.errorType != null) { return false; } } else if (!errorType.equals(other.errorType)) { return false; } if (postscanBahavior == null) { if (other.postscanBahavior != null) { return false; } } else if (!postscanBahavior.equals(other.postscanBahavior)) { return false; } return true; } /** * {@inheritDoc} */ @Override public String toString() { return "PostscanError [errorType=" + errorType + ", postscanBahavior=" + postscanBahavior + "]"; } /** * {@inheritDoc} */ @Override public String getErrorMessage() { return "Error in postscan " + this.postscanBahavior + " because " + this.errorType; } /** * {@inheritDoc} */ @Override public String getErrorName() { return "Postscan Error"; } }
eveCSS/eveCSS
bundles/de.ptb.epics.eve.data/src/de/ptb/epics/eve/data/scandescription/errors/PostscanError.java
Java
epl-1.0
2,870
/******************************************************************************* * Copyright (c) 2011, 2016 Eurotech and/or its affiliates * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech *******************************************************************************/ package org.eclipse.kura.net.modem; import java.util.List; import org.eclipse.kura.KuraException; import org.eclipse.kura.net.NetInterface; /** * Network interface for modems. */ public interface ModemInterface<T extends ModemInterfaceAddress> extends NetInterface<T> { /** * Reports ppp interface number for this modem * * @return ppp interface number as {@link int} */ public int getPppNum(); /** * Reports identifier string for this modem * * @return modem identifier as {@link String} */ public String getModemIdentifier(); /** * Reports modem's model * * @return model, null if not known */ public String getModel(); /** * Returns modem's manufacturer identification * * @return manufacturer, null if not known */ public String getManufacturer(); /** * Answers modem's serial number * * @return ESN, null if not known */ public String getSerialNumber(); /** * Reports modem's revision identification * * @return array of revision ID's, null if not known */ public String[] getRevisionId(); /** * Reports network technology (e.g. EVDO, HSDPA, etc) * * @return - network technology as <code>ModemTechnologyType</code> */ public List<ModemTechnologyType> getTechnologyTypes(); /** * Reports if modem is powered on * * @return * true - modem is on <br> * false - modem is off */ public boolean isPoweredOn(); /** * Reports modem's power mode. (e.g. ONLINE, OFFLINE, LOW_POWER) * * @return modem power mode */ public ModemPowerMode getPowerMode(); /** * Return's the associated ModemDevice for this modem * * @return <code>ModemDevice</code> */ public ModemDevice getModemDevice(); /** * Reports if GPS is supported * * @return * @return * true - GPS is supported <br> * false - GPS is not supported */ public boolean isGpsSupported(); }
rohitdubey12/kura
kura/org.eclipse.kura.api/src/main/java/org/eclipse/kura/net/modem/ModemInterface.java
Java
epl-1.0
2,621
/******************************************************************************* * Copyright (c) 2011, 2020 Eurotech and/or its affiliates * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech *******************************************************************************/ package org.eclipse.kura.linux.net.modem; import org.eclipse.kura.usb.UsbDevice; public class SupportedUsbModemsInfo { private SupportedUsbModemsInfo() { } public static SupportedUsbModemInfo getModem(UsbDevice usbDevice) { if (usbDevice == null) { return null; } return getModem(usbDevice.getVendorId(), usbDevice.getProductId(), usbDevice.getProductName()); } @Deprecated public static SupportedUsbModemInfo getModem(String vendorId, String productId, String productName) { if (vendorId == null || productId == null) { return null; } for (SupportedUsbModemInfo modem : SupportedUsbModemInfo.values()) { if (vendorId.equals(modem.getVendorId()) && productId.equals(modem.getProductId()) && (modem.getProductName().isEmpty() || productName.equals(modem.getProductName()))) { return modem; } } return null; } @Deprecated public static boolean isSupported(String vendorId, String productId, String productName) { return SupportedUsbModems.isSupported(vendorId, productId, productName); } public static boolean isSupported(UsbDevice usbDevice) { return SupportedUsbModems.isSupported(usbDevice); } }
nicolatimeus/kura
kura/org.eclipse.kura.linux.net/src/main/java/org/eclipse/kura/linux/net/modem/SupportedUsbModemsInfo.java
Java
epl-1.0
1,826
package com.zoneol.qxcar.fragment.index; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.zoneol.qxcar.R; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * to handle interaction events. * Use the {@link IndexControlTearFragment#newInstance} factory method to * create an instance of this fragment. */ public class IndexControlTearFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; // private OnFragmentInteractionListener mListener; /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment IndexControlTearFragment. */ // TODO: Rename and change types and number of parameters public static IndexControlTearFragment newInstance(String param1, String param2) { IndexControlTearFragment fragment = new IndexControlTearFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } public IndexControlTearFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_index_control_tear, container, false); } // // TODO: Rename method, update argument and hook method into UI event // public void onButtonPressed(Uri uri) { // if (mListener != null) { // mListener.onFragmentInteraction(uri); // } // } // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // try { // mListener = (OnFragmentInteractionListener) activity; // } catch (ClassCastException e) { // throw new ClassCastException(activity.toString() // + " must implement OnFragmentInteractionListener"); // } // } // // @Override // public void onDetach() { // super.onDetach(); // mListener = null; // } // // /** // * This interface must be implemented by activities that contain this // * fragment to allow an interaction in this fragment to be communicated // * to the activity and potentially other fragments contained in that // * activity. // * <p/> // * See the Android Training lesson <a href= // * "http://developer.android.com/training/basics/fragments/communicating.html" // * >Communicating with Other Fragments</a> for more information. // */ // public interface OnFragmentInteractionListener { // // TODO: Update argument type and name // public void onFragmentInteraction(Uri uri); // } }
shaolongmin/QXZoneolCar
app/src/main/java/com/zoneol/qxcar/fragment/index/IndexControlTearFragment.java
Java
epl-1.0
3,696
package org.jboss.shrinkwrap.descriptor.impl.orm21; import org.jboss.shrinkwrap.descriptor.api.Child; import org.jboss.shrinkwrap.descriptor.api.orm21.PrePersist; import org.jboss.shrinkwrap.descriptor.spi.node.Node; /** * This class implements the <code> pre-persist </code> xsd type * @author <a href="mailto:[email protected]">Ralf Battenfeld</a> * @author <a href="mailto:[email protected]">Andrew Lee Rubinger</a> */ public class PrePersistImpl<T> implements Child<T>, PrePersist<T> { // -------------------------------------------------------------------------------------|| // Instance Members // -------------------------------------------------------------------------------------|| private T t; private Node childNode; // -------------------------------------------------------------------------------------|| // Constructor // -------------------------------------------------------------------------------------|| public PrePersistImpl(T t, String nodeName, Node node) { this.t = t; this.childNode = node.createChild(nodeName); } public PrePersistImpl(T t, String nodeName, Node node, Node childNode) { this.t = t; this.childNode = childNode; } public T up() { return t; } // --------------------------------------------------------------------------------------------------------|| // ClassName: PrePersist ElementName: xsd:string ElementType : description // MaxOccurs: - isGeneric: true isAttribute: false isEnum: false isDataType: true // --------------------------------------------------------------------------------------------------------|| /** * Sets the <code>description</code> element * @param description the value for the element <code>description</code> * @return the current instance of <code>PrePersist<T></code> */ public PrePersist<T> description(String description) { childNode.getOrCreate("description").text(description); return this; } /** * Returns the <code>description</code> element * @return the node defined for the element <code>description</code> */ public String getDescription() { return childNode.getTextValueForPatternName("description"); } /** * Removes the <code>description</code> element * @return the current instance of <code>PrePersist<T></code> */ public PrePersist<T> removeDescription() { childNode.removeChildren("description"); return this; } // --------------------------------------------------------------------------------------------------------|| // ClassName: PrePersist ElementName: xsd:string ElementType : method-name // MaxOccurs: - isGeneric: true isAttribute: true isEnum: false isDataType: true // --------------------------------------------------------------------------------------------------------|| /** * Sets the <code>method-name</code> attribute * @param methodName the value for the attribute <code>method-name</code> * @return the current instance of <code>PrePersist<T></code> */ public PrePersist<T> methodName(String methodName) { childNode.attribute("method-name", methodName); return this; } /** * Returns the <code>method-name</code> attribute * @return the value defined for the attribute <code>method-name</code> */ public String getMethodName() { return childNode.getAttribute("method-name"); } /** * Removes the <code>method-name</code> attribute * @return the current instance of <code>PrePersist<T></code> */ public PrePersist<T> removeMethodName() { childNode.removeAttribute("method-name"); return this; } }
forge/javaee-descriptors
impl/src/main/java/org/jboss/shrinkwrap/descriptor/impl/orm21/PrePersistImpl.java
Java
epl-1.0
3,774
package edu.buffalo.cse.jive.model.slicing; import java.util.BitSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import edu.buffalo.cse.jive.lib.StringTools; import edu.buffalo.cse.jive.lib.TypeTools; import edu.buffalo.cse.jive.model.IContourModel.IContextContour; import edu.buffalo.cse.jive.model.IContourModel.IContourMember; import edu.buffalo.cse.jive.model.IContourModel.IMethodContour; import edu.buffalo.cse.jive.model.IEventModel.IAssignEvent; import edu.buffalo.cse.jive.model.IEventModel.IDestroyObjectEvent; import edu.buffalo.cse.jive.model.IEventModel.IFieldAssignEvent; import edu.buffalo.cse.jive.model.IEventModel.IFieldReadEvent; import edu.buffalo.cse.jive.model.IEventModel.IInitiatorEvent; import edu.buffalo.cse.jive.model.IEventModel.IJiveEvent; import edu.buffalo.cse.jive.model.IEventModel.IMethodCallEvent; import edu.buffalo.cse.jive.model.IEventModel.IMethodEnteredEvent; import edu.buffalo.cse.jive.model.IEventModel.IMethodReturnedEvent; import edu.buffalo.cse.jive.model.IEventModel.IMethodTerminatorEvent; import edu.buffalo.cse.jive.model.IEventModel.INewObjectEvent; import edu.buffalo.cse.jive.model.IEventModel.ISystemStartEvent; import edu.buffalo.cse.jive.model.IEventModel.ITerminatorEvent; import edu.buffalo.cse.jive.model.IEventModel.IThreadStartEvent; import edu.buffalo.cse.jive.model.IEventModel.ITypeLoadEvent; import edu.buffalo.cse.jive.model.IEventModel.IVarDeleteEvent; import edu.buffalo.cse.jive.model.IExecutionModel; import edu.buffalo.cse.jive.model.IExecutionModel.IProgramSlice; import edu.buffalo.cse.jive.model.IModel.IContourReference; import edu.buffalo.cse.jive.model.IModel.IMethodContourReference; import edu.buffalo.cse.jive.model.IModel.IThreadValue; import edu.buffalo.cse.jive.model.IModel.IValue; import edu.buffalo.cse.jive.model.IStaticModel.IDataNode; import edu.buffalo.cse.jive.model.IStaticModel.ITypeNode; import edu.buffalo.cse.jive.model.IStaticModel.NodeKind; import edu.buffalo.cse.jive.model.IStaticModel.NodeModifier; import edu.buffalo.cse.jive.model.IStaticModel.NodeOrigin; /** * One instance of this class is shared across all method slices. This guarantees that the same set * of fields is tracked by all method slices and, therefore, the effects of every method slice on * the currently used static and instance fields is visible across all method slices. * * TODO: reduce the cyclomatic complexity across and nested block depth. */ public final class ProgramSlice implements IProgramSlice { /** * Exceptions currently relevant to the slice. This set is important for exceptions propagating * across method slices. */ private final Set<IValue> chaseExceptions; /** * Fields currently relevant to the slice. An assignment to a field in this set results in the * removal of the field from the set. The fields used in the assignment must be added to this set; * local variables used in the assignment must be added to the variable set of the respective * method slice. * * A field assignment can occur on any method of any thread. Hence, the entire trace must be * traversed-- no method call should be skipped even if it appears otherwise irrelevant to a * particular branch of the slice computation. */ private final Set<IContourMember> chaseFields; /** * Static and instance contours, each corresponding to the execution context of some method call * or field used in the slice. This set is used to determine if a given constructor or class * initializer is relevant to the slice. */ private final Set<IContextContour> contexts; /** * Maps each MethodCallEvent to the respective MethodEnteredEvent in order to construct a * consistent reduced execution model. */ private final Map<IJiveEvent, IJiveEvent> enteredEvents; /** * Keeps track of the enums that have been seen and processed. The purpose of this data structure * is to support correct processing of the spurious enum reads after the initialization of all * enum constants. */ private final Map<ITypeNode, Set<IDataNode>> enums; /** * Set of event identifiers that actually belong to the slice. */ private final BitSet eventSet; /** * Determines if this slice should include the snapshot thread. */ private boolean hasSnapshot; /** * Fields and variables ever used in the slice. This is an append-only set derived as follows-- * every time a field is added to the set of chase fields, it is also added to the this set. * However, while fields may be removed from the set of chase fields they are never removed from * this set. This set also includes local variables and arguments that were relevant at any point * in the slice computation. */ private final Set<IContourMember> members; /** * The slicing criterion must be an assign event. */ private final IAssignEvent initial; /** * <pre> * Method contours corresponding to method calls relevant to the program slice. A method call is * relevant if at least one of the following holds: * * a) it appears on the right hand side (RHS) of a relevant assignment AND * * 1) the call is top-level OR * * 2) the call appears in a relevant argument position of a relevant method call OR * * 3) the call is a qualifier of a relevant method call, field use, or field def; * * b) the field chase set is modified by the respective method slice * * c) it is the caller of a relevant method call (relevance for scaffolding purposes) * </pre> */ private final Set<IMethodContour> methods; /** * A map of threads to completed method slices that returned to out-of-model. An out-of-model * context cannot process a completed slice, hence this map allows delayed processing of this * slice. */ private final Map<IThreadValue, MethodSlice> pendingCompleted; /** * A map of threads to out-of-model calls (from in-model). This allows for processing delayed * completed slices. */ private final Map<IThreadValue, IMethodCallEvent> pendingOutOfModel; /** * Maps each MethodTerminatorEvent to the respective MethodReturnedEvent in order to construct a * consistent reduced execution model. */ private final Map<IJiveEvent, IJiveEvent> returnedEvents; /** * Method slices are stacked similarly to method calls during execution. The stack of method * slices contains all currently active slice computations, mirroring the call stacks at every * instant of execution. The method slice being currently processed for a thread is always the * slice at the top of the corresponding stack. */ private final Map<IThreadValue, Stack<MethodSlice>> slices; /** * Value chaining for relevant slice members. This is necessary because contour members will be * updated in a sliced execution using sliced events only. These events must, thus, refer to the * values used in the slice. */ private final Map<IContourMember, IAssignEvent> valueChain; public ProgramSlice(final IAssignEvent initial) { this.chaseExceptions = TypeTools.newHashSet(); this.chaseFields = TypeTools.newHashSet(); this.contexts = TypeTools.newHashSet(); this.enteredEvents = TypeTools.newHashMap(); this.enums = TypeTools.newHashMap(); this.eventSet = new BitSet(); this.hasSnapshot = false; this.initial = initial; this.members = TypeTools.newHashSet(); this.methods = TypeTools.newHashSet(); this.pendingCompleted = TypeTools.newHashMap(); this.pendingOutOfModel = TypeTools.newHashMap(); this.returnedEvents = TypeTools.newHashMap(); this.slices = TypeTools.newLinkedHashMap(); this.valueChain = TypeTools.newHashMap(); } /** * When a *relevant* assignment is detected, it is associated with the respective contour member * as its last assignment. */ public void chainValueDef(final IAssignEvent event) { final IContourMember member = event.member(); if (valueChain.containsKey(member)) { final IAssignEvent value = valueChain.get(member); // last operation on this member was a DEF if (value != null) { // associate the original assignment with this member (old value) valueChain.get(member).setLastAssignment(event); } // last operation on this member was a USE else { // associate the member with the assignment valueChain.put(member, event); // local variables referencing contours if (event.newValue().isContourReference() && member.schema().kind() == NodeKind.NK_VARIABLE) { final IContextContour context = (IContextContour) ((IContourReference) event.newValue()) .contour(); if (context != null) { // System.err.println("CONTEXT_FOR_LOCAL[" + context + "]"); addContext(context); } } } } } /** * When a *relevant* delete is detected, it is associated with the respective contour member as * its last assignment. A delete is like assigning the uninitialized value to a local. */ void chainValueDel(final IVarDeleteEvent event) { final IContourMember member = event.member(); if (valueChain.containsKey(member)) { IAssignEvent ae = valueChain.get(member); if (ae != null) { // associate an uninitialized value with the member's assign event ae.setLastAssignment(event); System.err.println("Setting unassigned value for: " + member.name()); } } } public void chainValueUse(final IContourMember member) { // unconditionally add the member so that it can keep track of assignments valueChain.put(member, null); } @Override public Set<IContextContour> contexts() { return this.contexts; } @Override public List<IJiveEvent> events() { final List<IJiveEvent> result = TypeTools.newArrayList(eventSet.cardinality()); for (int i = eventSet.nextSetBit(0); i >= 0; i = eventSet.nextSetBit(i + 1)) { /** * DO NOT lookup-- get the actual event! */ final IJiveEvent e = initial.model().store().lookupRawEvent(i); result.add(e); } return result; } public IAssignEvent initialEvent() { return initial; } @Override public Set<IContourMember> members() { return this.members; } @Override public Set<IMethodContour> methods() { return this.methods; } @Override public IExecutionModel model() { return initial.model(); } @Override public String toString() { return StringTools.sliceToString(this); } /** * Adds the given method call event to the slice, will all relevant structural events-- entered, * terminator, and returned. Additionally, adds all methods in the call stack that supports the * given call event. */ private void addMethod(final IMethodCallEvent event) { // add the method call if it is in the slice's context if (event.eventId() < initial.eventId()) { // initiator IInitiatorEvent start = event; // scaffolding while (start != null && !eventSet.get((int) start.eventId())) { // System.err.println("(+) " + start.toString()); // relevant initiator eventSet.set((int) start.eventId()); // method call if (start instanceof IMethodCallEvent && (isInModel((IMethodCallEvent) start) || (hasSnapshot && isSnapshotEvent(start)) || (start .executionContext() != null && start.execution().schema().modifiers() .contains(NodeModifier.NM_CONSTRUCTOR)))) { // method contour and the respective context contour if (start.execution() != null) { methods.add(start.execution()); addContext(start.execution().parent()); } // relevant method entered final IJiveEvent entered = enteredEvents.remove(start); if (entered != null && entered.eventId() < initial.eventId()) { // System.err.println("(+) " + entered.toString()); // relevant method entered eventSet.set((int) entered.eventId()); } } // terminator final ITerminatorEvent terminator = start.terminator(); if (terminator != null && terminator.eventId() < initial.eventId()) { // System.err.println("(+) " + terminator.toString()); // relevant terminator eventSet.set((int) terminator.eventId()); // method returned final IJiveEvent returned = returnedEvents.remove(terminator); if (returned != null && returned.eventId() < initial.eventId()) { // System.err.println("(+) " + returned.toString()); // relevant method returned eventSet.set((int) returned.eventId()); } } // traverse back start = start.parent(); } } } private MethodSlice createSlice(final Stack<MethodSlice> stack, final IJiveEvent event, final MethodSlice completed) { if (event == initial) { final MethodSlice slice = new MethodSlice(event, this, null, getMethod( (IMethodCallEvent) event.parent(), true)); // push the new method slice onto the proper stack stack.push(slice); slice.sliceInitiated(); return slice; } // parent slice (may not correspond to the caller method) final MethodSlice parent = stack.isEmpty() ? null : stack.peek(); // create a slice only for in-model targets if (event.parent() instanceof IMethodCallEvent && isInModel((IMethodCallEvent) event.parent())) { final MethodSlice slice = new MethodSlice(event, this, parent, getMethod( (IMethodCallEvent) event.parent(), false)); // push the new method slice onto the proper stack stack.push(slice); /** * A non-null pending out-of-model call indicates that the completed slice is not relevant to * the new slice. */ final MethodSlice pending = pendingCompleted.remove(event.thread()); final IMethodCallEvent outOfModelCall = pendingOutOfModel.remove(event.thread()); if (pending != null && completed != null) { throw new IllegalStateException( "Cannot have both a pending completed method slice and a newly completed method slice."); } if (pending != null) { // if (outOfModelCall == null) { // System.err.println("in --> out (return with pending slice) --> out+ --> in."); // } // check whether this is an in-model sibling or ancestor IJiveEvent pendingEvent = pending.initialEvent(); while (pendingEvent != null && pendingEvent != event) { pendingEvent = pendingEvent.parent(); } final boolean isSibling = (pendingEvent != event); if (isSibling) { System.err .println("in (1) --> out+/(pending slice)/out+ --> in (2), (1) and (2) are siblings."); } else { System.err .println("in (1) --> out+/(pending slice)/out+ --> in (2), (1) and (2) are ancestor/descendant."); } System.err.println("(*) Initiating with a pending method slice and out-of-model call!"); slice.sliceInitiated(isSibling ? null : pending, outOfModelCall, true); } else { slice.sliceInitiated(completed, null, false); } return slice; } /** * An out-of-model target leaves the completed method slice orphaned. Instead of dropping it, we * record the slice for later use. */ else { if (completed != null) { pendingCompleted.put(event.thread(), completed); } // pending in-model to out-of-model call-- the first out-of-model target and last out-of-model // caller are known if (event.parent() instanceof IMethodCallEvent && event.parent().parent() instanceof IMethodCallEvent && isInModel((IMethodCallEvent) event.parent().parent())) { pendingOutOfModel.put(event.thread(), (IMethodCallEvent) event.parent()); } } return null; } private IMethodContour getMethod(final IMethodCallEvent call, final boolean isInitial) { if (call.target() instanceof IMethodContourReference) { return ((IMethodContourReference) call.target()).contour(); } if (isInitial && call.target().toString().contains("access$") && call.target().toString().contains("SYNTHETIC") && call.parent() instanceof IMethodCallEvent) { // System.err.println("SYNTHETIC_ACCESSOR_RESOLVED_FOR_PROGRAM_SLICE"); return getMethod((IMethodCallEvent) call.parent(), true); } return null; } private void handleMethodCall(final Stack<MethodSlice> stack, final IMethodCallEvent event) { // the top of the stack must contain the completed method slice final MethodSlice completed = stack.pop(); // allow the slice to complete its computation completed.done(event); // retrieve the terminator final IMethodTerminatorEvent terminator = event.terminator(); // update the program slice with the completed method slice if (completed.isRelevant()) { // add the method context, its call stack, and all relevant contexts addMethod(event); // add all events in the completed method slice eventSet.or(completed.events()); } else { enteredEvents.remove(event); if (terminator != null) { returnedEvents.remove(terminator); } } // if this was the last method slice on the stack, create a slice for the caller method if (stack.isEmpty()) { createSlice(stack, event, completed); } } private void handleSnapshot(final IJiveEvent event) { // chased field if (event instanceof IFieldAssignEvent && hasChaseField((IFieldAssignEvent) event)) { handleFieldDef((IFieldAssignEvent) event); hasSnapshot = true; } // the snapshot has become relevant else if (hasSnapshot && event instanceof IMethodCallEvent) { addMethod((IMethodCallEvent) event); } } /** * Type load and new events are handled by the structural handler. */ private void handleStructural(final IJiveEvent event) { // the event is relevant if the the new contour is one of the slice's contexts if (event instanceof INewObjectEvent && contexts.contains(((INewObjectEvent) event).newContour())) { // System.err.println("(+) " + event.toString()); eventSet.set((int) event.eventId()); // make sure the snapshot is included, if relevant hasSnapshot = hasSnapshot || isSnapshotEvent(event); /** * If a New Object is relevant, its destroy event might also be relevant-- namely, it should * be in the slice if the destruction happens before the initial event. Undoing a destroy is * recreating the object in its final state whereas undoing a create is removing the object in * its initial state. */ final long oid = ((INewObjectEvent) event).newContour().oid(); final IJiveEvent de = model().store().lookupDestroyEvent(oid); if (de != null && de.eventId() < initial.eventId()) { eventSet.set((int) de.eventId()); } } // the event is relevant if the the new contour is one of the slice's contexts else if (event instanceof ITypeLoadEvent && contexts.contains(((ITypeLoadEvent) event).newContour())) { // System.err.println("(+) " + event.toString()); eventSet.set((int) event.eventId()); // make sure the snapshot is included, if relevant hasSnapshot = hasSnapshot || isSnapshotEvent(event); } } private boolean isInModel(final IMethodCallEvent event) { return event.inModel() && event.execution().schema().origin() == NodeOrigin.NO_AST; } private boolean isSnapshotEvent(final IJiveEvent event) { return event.thread().id() == -1 && event.thread().name().contains("JIVE Snapshot"); } private boolean isStructuralEvent(final IJiveEvent event) { return event instanceof INewObjectEvent || event instanceof IDestroyObjectEvent || event instanceof ITypeLoadEvent || event instanceof ISystemStartEvent || event instanceof IThreadStartEvent; } /** * Returns a non-null, possibly empty stack of method slices associated with the event's thread. */ private Stack<MethodSlice> lookupSliceStack(final IJiveEvent event) { if (slices.get(event.thread()) == null) { slices.put(event.thread(), new Stack<MethodSlice>()); } return slices.get(event.thread()); } /** * Returns the prior event in the trace. * * POSSIBLE IMPROVEMENT: If the set of currently chased fields is empty, this method could skip * events from threads with no outstanding method slice, since such threads cannot possibly affect * the slice computation and threads do not share local variables. */ private IJiveEvent priorEvent(final IJiveEvent event) { // not an event if (event == null) { return null; } // no prior event if (event.eventId() <= 1) { return null; } // return the prior event final IJiveEvent prior = event.prior(); initial.model().temporalState().rollback(); // ((ExecutionModel) initial.model()).transactionLog().rollback(); return prior; } /** * Adds the context to the set of relevant contexts. For instance contours, all inherited contours * are included and so are the respective static contours. */ void addContext(final IContextContour context) { // System.err.println("ADD_CONTEXT[" + context + "]"); IContextContour contour = context; while (contour != null && !contexts.contains(contour)) { contexts.add(contour); contour = contour.parent(); } // for instance contours, add the respective static contours if (context != null && !context.isStatic()) { addContext(context.schema().lookupStaticContour()); } } /** * Adds the exception to the set of chase exceptions. */ void addException(final IValue exception) { chaseExceptions.add(exception); } /** * Adds the contour member to the set of relevant members. For members that reference contours, * the respective contour is also added as a relevant context. */ void addMember(final IContourMember member) { if (member != null) { members.add(member); // if the member value is a contour reference, it is relevant if (member.value().isContourReference()) { addContext((IContextContour) ((IContourReference) member.value()).contour()); } } } /** * For each event in the trace, processes the event in the the appropriate method slice. If no * method slice exists yet for the current event, a new one is created and push it onto the stack * of method slices for the corresponding thread. * * The computation of the program slice is split across the program slicer, the method slicer, and * the line slicer. */ public void computeSlice() { // the initial event to process IJiveEvent event = initial; // while there are events to process while (event != null) { // structural events are processed separately if (isStructuralEvent(event)) { handleStructural(event); } else if (isSnapshotEvent(event)) { handleSnapshot(event); } else { // always handle returned events if (event instanceof IMethodReturnedEvent) { returnedEvents.put(((IMethodReturnedEvent) event).terminator(), event); } else if (event instanceof IMethodEnteredEvent) { // the initiator has already been marked as relevant if (event.parent() != null && eventSet.get((int) event.parent().eventId())) { eventSet.set((int) event.eventId()); } else { enteredEvents.put(event.parent(), event); } } // retrieve the current event's slice stack (creates an empty one if necessary) final Stack<MethodSlice> stack = lookupSliceStack(event); if (stack.isEmpty()) { // the slice initiated method processes the event final MethodSlice top = createSlice(stack, event, null); // could not create a top method slice, move on to the prior event if (top == null) { event = priorEvent(event); continue; } } // a method call event marks the completion of the computation of a method slice else if (event instanceof IMethodCallEvent) { if (isInModel((IMethodCallEvent) event)) { handleMethodCall(stack, (IMethodCallEvent) event); } } // first ever event on this method must be a method terminator event (exit or throw) else if (event instanceof IMethodTerminatorEvent && ((IMethodTerminatorEvent) event).framePopped()) { // terminator of out-of-model method calls-- no slice to create if (!isInModel(((IMethodTerminatorEvent) event).parent())) { final IMethodContour c = ((IMethodTerminatorEvent) event).parent().execution(); if (c != null && c.schema().modifiers().contains(NodeModifier.NM_CONSTRUCTOR)) { if (contexts.contains(c.parent())) { addMethod((IMethodCallEvent) event.parent()); } } event = priorEvent(event); continue; } // create a method slice for the called method createSlice(stack, event, null); } // event on an existing method slice else { // retrieve the method slice corresponding to the event final MethodSlice slice = stack.peek(); // delegate event processing to the slice slice.processEvent(event); } } // move to the prior event event = priorEvent(event); } } public BitSet eventSet() { return eventSet; } /** * Tries to remove the enum constant from the appropriate set in the enums map. */ boolean handleEnumConstant(final IDataNode enumConstant) { final Set<IDataNode> constants = enums.get(enumConstant.parent()); return constants != null && constants.remove(enumConstant); } /** * Creates a populated entry for the given enum in the enums map. */ void handleEnumDeclaration(final ITypeNode enumNode) { if (!enums.containsKey(enumNode)) { final Set<IDataNode> constants = TypeTools.newHashSet(); for (final IDataNode c : enumNode.dataMembers().values()) { if (c.modifiers().contains(NodeModifier.NM_ENUM_CONSTANT)) { constants.add(c); } } enums.put(enumNode, constants); } } /** * Called when a field definition is found. A field definition always removes the field from the * chase set. The fields used in this assignment (directly or transitively) must be added to the * uses set. Once the method return the field is no longer on the chase set. The method returns * true only if the field was in the chased field set. */ boolean handleFieldDef(final IFieldAssignEvent def) { if (chaseFields.remove(def.member()) || (def.contour().schema().kind() == NodeKind.NK_ARRAY && isRelevantContext(def.contour()))) // if (chaseFields.remove(def.member())) { // chain this field def chainValueDef(def); // add the event to the slice eventSet.set((int) def.eventId()); // add the field to the model members.add(def.member()); // add the field's context contour to the model addContext(def.contour()); // if the new value is a contour reference, it is relevant if (def.newValue().isContourReference()) { addContext((IContextContour) ((IContourReference) def.newValue()).contour()); } // the definition is relevant return true; } // the definition is not relevant return false; } /** * Called when a member is used in a definition. */ void handleFieldUse(final IContextContour context, final IContourMember member) { // chain this field use chainValueUse(member); // chase the field use chaseFields.add(member); if (member.name().equals("rank")) { System.err.println(context.signature() + ".rank::" + member.hashCode()); } // add this member to the model members.add(member); // add the field's context contour to the model addContext(context); } /** * Called when a field assignment is used to define a slicing criterion. */ void handleFieldUse(final IFieldAssignEvent use) { // chain this field use chainValueUse(use.member()); // add the event to the slice eventSet.set((int) use.eventId()); // chase the field use chaseFields.add(use.member()); if (use.member().name().equals("rank")) { System.err.println(use.contour().signature() + ".rank::" + use.member().hashCode()); } // add this member to the model members.add(use.member()); // add the field's context contour to the model addContext(use.contour()); } /** * Called when a field use is relevant to the ongoing computation of the relevant uses of a field * or variable assignment. */ void handleFieldUse(final IFieldReadEvent use) { // chain this field use chainValueUse(use.member()); // add the event to the slice eventSet.set((int) use.eventId()); // chase the field use chaseFields.add(use.member()); // add the field to the model addMember(use.member()); // add the field's context contour to the model addContext(use.contour()); } boolean hasChaseField(final IFieldAssignEvent event) { //final IContextContour context = event.contour(); final IContourMember member = event.member(); return chaseFields.contains(member); // return chaseFields.contains(member) // || (context.schema().kind() == NodeKind.NK_ARRAY && isRelevantContext(context)); } boolean hasException(final IValue exception) { return chaseExceptions.contains(exception); } boolean isRelevantContext(final IContextContour context) { return context != null && contexts.contains(context); } }
UBPL/jive
edu.buffalo.cse.jive.model.slicing/src/edu/buffalo/cse/jive/model/slicing/ProgramSlice.java
Java
epl-1.0
30,844
package kenijey.harshenuniverse.base; public abstract class BaseItemRendererActive<T extends BaseTileEntityHarshenSingleItemInventoryActive> extends BaseItemRenderer<T> { @Override protected float getMovementSpeed(T te) { return te.isActive() ? te.getActiveTimer() / 10f: 1f; } }
kenijey/harshencastle
src/main/java/kenijey/harshenuniverse/base/BaseItemRendererActive.java
Java
epl-1.0
288
/* * Copyright (c) [2012] - [2017] Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation */ package com.codenvy.auth.sso.client.deploy; import com.google.inject.servlet.ServletModule; /** * Install sso client servlets. * * @author Sergii Kabashniuk */ public class SsoClientServletModule extends ServletModule { @Override protected void configureServlets() { serve("/_sso/client/logout").with(com.codenvy.auth.sso.client.SSOLogoutServlet.class); } }
codenvy/codenvy
wsmaster/codenvy-hosted-sso-client/src/main/java/com/codenvy/auth/sso/client/deploy/SsoClientServletModule.java
Java
epl-1.0
746
/******************************************************************************* * Copyright (c) 2012-2015 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.git.impl.nativegit; /** * @author <a href="mailto:[email protected]">Eugene Voevodin</a> */ public class UserCredential { public static final UserCredential EMPTY_CREDENTIALS = new UserCredential("", "", ""); private final String userName; private final String password; private final String providerId; public UserCredential(String userName, String password, String providerId) { this.userName = userName; this.password = password; this.providerId = providerId; } public String getUserName() { return userName; } public String getPassword() { return password; } public String getProviderId() { return providerId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserCredential that = (UserCredential)o; if (password != null ? !password.equals(that.password) : that.password != null) return false; if (providerId != null ? !providerId.equals(that.providerId) : that.providerId != null) return false; if (userName != null ? !userName.equals(that.userName) : that.userName != null) return false; return true; } @Override public int hashCode() { int result = userName != null ? userName.hashCode() : 0; result = 31 * result + (password != null ? password.hashCode() : 0); result = 31 * result + (providerId != null ? providerId.hashCode() : 0); return result; } @Override public String toString() { final StringBuilder sb = new StringBuilder("UserCredential{"); sb.append("userName='").append(userName).append('\''); sb.append(", password='").append(password).append('\''); sb.append(", providerId='").append(providerId).append('\''); sb.append('}'); return sb.toString(); } }
vitaliy0922/cop_che-core
che-core-git-impl-native/src/main/java/org/eclipse/che/git/impl/nativegit/UserCredential.java
Java
epl-1.0
2,490
/******************************************************************************* * Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.config; /** * Hint values. * * The class defines boolean values used by some EclipseLink query hints. * * <p>JPA Query Hint Usage: * * <p><code>query.setHint(QueryHints.REFRESH, HintValues.TRUE);</code> * <p>or * <p><code>@QueryHint(name=QueryHints.REFRESH, value=HintValues.TRUE)</code> * * <p>Hint values are case-insensitive. * * @see QueryHints */ public class HintValues { public static final String TRUE = "True"; public static final String FALSE = "False"; public static final String PERSISTENCE_UNIT_DEFAULT = "PersistenceUnitDefault"; }
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/config/HintValues.java
Java
epl-1.0
1,376
package mx.com.cinepolis.digital.booking.commons.to; import java.util.Date; import mx.com.cinepolis.digital.booking.commons.utils.CinepolisUtils; import org.apache.commons.lang.builder.ToStringBuilder; /** * Transfer object for Incomes * * @author gsegura */ public class IncomeTO extends CatalogTO { /** * */ private static final long serialVersionUID = -5315574981870322377L; private TheaterTO theater; private WeekTO week; private BookingTO booking; private EventTO event; private ScreenTO screen; private String dateStr; private String timeStr; private Date date; private double income; private int tickets; private int exhibitionWeek; /** * @return the theater */ public TheaterTO getTheater() { return theater; } /** * @param theater the theater to set */ public void setTheater( TheaterTO theater ) { this.theater = theater; } /** * @return the movie */ public EventTO getEvent() { return event; } /** * @param movie the movie to set */ public void setEvent( EventTO event ) { this.event = event; } /** * @return the screen */ public ScreenTO getScreen() { return screen; } /** * @param screen the screen to set */ public void setScreen( ScreenTO screen ) { this.screen = screen; } /** * @return the dateStr */ public String getDateStr() { return dateStr; } /** * @param dateStr the dateStr to set */ public void setDateStr( String dateStr ) { this.dateStr = dateStr; } /** * @return the timeStr */ public String getTimeStr() { return timeStr; } /** * @param timeStr the timeStr to set */ public void setTimeStr( String timeStr ) { this.timeStr = timeStr; } /** * @return the date */ public Date getDate() { return CinepolisUtils.enhancedClone( date ); } /** * @param date the date to set */ public void setDate( Date date ) { this.date = CinepolisUtils.enhancedClone( date ); } /** * @return the income */ public double getIncome() { return income; } /** * @param income the income to set */ public void setIncome( double income ) { this.income = income; } /** * @return the tickets */ public int getTickets() { return tickets; } /** * @param tickets the tickets to set */ public void setTickets( int tickets ) { this.tickets = tickets; } /** * @return the week */ public WeekTO getWeek() { return week; } /** * @param week the week to set */ public void setWeek( WeekTO week ) { this.week = week; } /** * @return the booking */ public BookingTO getBooking() { return booking; } /** * @param booking the booking to set */ public void setBooking( BookingTO booking ) { this.booking = booking; } /** * @return the exhibitionWeek */ public int getExhibitionWeek() { return exhibitionWeek; } /** * @param exhibitionWeek the exhibitionWeek to set */ public void setExhibitionWeek( int exhibitionWeek ) { this.exhibitionWeek = exhibitionWeek; } @Override public String toString() { return new ToStringBuilder( this ).append( "id", this.getId() ).append( "booking", this.booking ) .append( "theater", this.theater ).append( "screen", this.screen ).append( "week", this.week ) .append( "event", this.event ).append( "income", this.income ).append( "date", this.dateStr ) .append( "show", this.timeStr ).append( "tickets", this.tickets ).toString(); } }
sidlors/digital-booking
digital-booking-commons/src/main/java/mx/com/cinepolis/digital/booking/commons/to/IncomeTO.java
Java
epl-1.0
3,653
/******************************************************************************* * Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * dclarke - Dynamic Persistence * http://wiki.eclipse.org/EclipseLink/Development/Dynamic * (https://bugs.eclipse.org/bugs/show_bug.cgi?id=200045) * mnorman - tweaks to work from Ant command-line, * get database properties from System, etc. * ******************************************************************************/ package org.eclipse.persistence.testing.tests.dynamic.simple.sequencing; //JUnit4 imports import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; //EclipseLink imports import org.eclipse.persistence.dynamic.DynamicClassLoader; import org.eclipse.persistence.dynamic.DynamicHelper; import org.eclipse.persistence.dynamic.DynamicTypeBuilder; import org.eclipse.persistence.internal.sessions.AbstractSession; import org.eclipse.persistence.sequencing.UnaryTableSequence; //domain-specific (testing) imports import static org.eclipse.persistence.testing.tests.dynamic.DynamicTestingHelper.createSession; public class UnaryTableSequencingTestSuite extends BaseSequencingTestSuite { @BeforeClass public static void setUp() { session = createSession(); dynamicHelper = new DynamicHelper(session); DynamicClassLoader dcl = dynamicHelper.getDynamicClassLoader(); Class<?> dynamicType = dcl.createDynamicClass("simple.sequencing." + ENTITY_TYPE); DynamicTypeBuilder typeBuilder = new DynamicTypeBuilder(dynamicType, null, TABLE_NAME); typeBuilder.setPrimaryKeyFields("SID"); typeBuilder.addDirectMapping("id", int.class, "SID"); typeBuilder.addDirectMapping("value1", String.class, "VAL_1"); // configureSequencing UnaryTableSequence sequence = new UnaryTableSequence(SEQ_TABLE_NAME); sequence.setCounterFieldName("SEQ_VALUE"); sequence.setPreallocationSize(5); ((AbstractSession)session).getProject().getLogin().setDefaultSequence(sequence); sequence.onConnect(session.getPlatform()); typeBuilder.configureSequencing(sequence, SEQ_TABLE_NAME, "SID"); dynamicHelper.addTypes(true, true, typeBuilder.getType()); } @AfterClass public static void tearDown() { session.executeNonSelectingSQL("DROP TABLE " + TABLE_NAME); session.executeNonSelectingSQL("DROP TABLE " + SEQ_TABLE_NAME); session.logout(); session = null; dynamicHelper = null; } @After public void clearSimpleTypeInstances() throws Exception { session.executeNonSelectingSQL("DELETE FROM " + TABLE_NAME); session.executeNonSelectingSQL("UPDATE " + SEQ_TABLE_NAME + " SET SEQ_VALUE = 0"); session.getSequencingControl().resetSequencing(); session.getSequencingControl().initializePreallocated(); } }
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/dynamic/simple/sequencing/UnaryTableSequencingTestSuite.java
Java
epl-1.0
3,449
package sample.nested; /** * Created by kotseto on 5/28/17. */ public class Book { private final String title; public Book(String title) { this.title = title; } }
kotse/junit5-hacking
junit5-sample/src/main/java/sample/nested/Book.java
Java
epl-1.0
187
package net.did2memo.remote.launch; import org.eclipse.jface.viewers.CheckboxTreeViewer; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.dialogs.FilteredTree; import org.eclipse.ui.dialogs.PatternFilter; public class ClasspathFilteredTree extends FilteredTree { public ClasspathFilteredTree(Composite parent, int treeStyle, PatternFilter filter, boolean useNewLook) { super(parent, treeStyle, filter, useNewLook); } @Override protected TreeViewer doCreateTreeViewer(Composite parent, int style) { // TODO Auto-generated method stub // return super.doCreateTreeViewer(parent, style); return new CheckboxTreeViewer(parent, style); } }
did2/remote-exec-plugin
net.did2memo.remote/src/net/did2memo/remote/launch/ClasspathFilteredTree.java
Java
epl-1.0
710
package main; import com.google.common.collect.Lists; import my.traits.C; public class Main { public static void main(String[] args) { CInterface c = new C(); System.out.println(c.m()); System.out.println(new C().m()); System.out.println( new C(Lists.newArrayList ("first", "second", "third")) .m()); } }
LorenzoBettini/xtraitj
xtraitj.example.examples/src/main/Main.java
Java
epl-1.0
333
/** * Copyright (c) 2019, 2020 Eurotech and/or its affiliates and others * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech */ package org.eclipse.kura.internal.driver.ble.xdk; import static java.util.Objects.isNull; import static java.util.Objects.requireNonNull; import static org.eclipse.kura.channel.ChannelFlag.FAILURE; import static org.eclipse.kura.channel.ChannelFlag.SUCCESS; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.eclipse.kura.KuraBluetoothIOException; import org.eclipse.kura.KuraException; import org.eclipse.kura.bluetooth.le.BluetoothLeAdapter; import org.eclipse.kura.bluetooth.le.BluetoothLeDevice; import org.eclipse.kura.bluetooth.le.BluetoothLeService; import org.eclipse.kura.channel.ChannelFlag; import org.eclipse.kura.channel.ChannelRecord; import org.eclipse.kura.channel.ChannelStatus; import org.eclipse.kura.channel.listener.ChannelListener; import org.eclipse.kura.configuration.ConfigurableComponent; import org.eclipse.kura.driver.ChannelDescriptor; import org.eclipse.kura.driver.Driver; import org.eclipse.kura.driver.PreparedRead; import org.eclipse.kura.type.DataType; import org.eclipse.kura.type.TypedValue; import org.eclipse.kura.type.TypedValues; import org.eclipse.kura.util.base.TypeUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class XdkDriver implements Driver, ConfigurableComponent { private static final Logger logger = LoggerFactory.getLogger(XdkDriver.class); private static final int TIMEOUT = 5; private static final String INTERRUPTED_EX = "Interrupted Exception"; private static final byte MESSAGE_ONE = 0x01; private static final byte MESSAGE_TWO = 0x02; private int configSampleRate; private boolean enableQuaternion; private XdkOptions options; private BluetoothLeService bluetoothLeService; private BluetoothLeAdapter bluetoothLeAdapter; private Map<String, Xdk> xdkMap; private Set<SensorListener> sensorListeners; protected synchronized void bindBluetoothLeService(final BluetoothLeService bluetoothLeService) { if (isNull(this.bluetoothLeService)) { this.bluetoothLeService = bluetoothLeService; } } protected synchronized void unbindBluetoothLeService(final BluetoothLeService bluetoothLeService) { if (this.bluetoothLeService == bluetoothLeService) { this.bluetoothLeService = null; } } protected synchronized void activate(final Map<String, Object> properties) { logger.debug("Activating BLE Xdk Driver..."); this.xdkMap = new HashMap<>(); this.sensorListeners = new HashSet<>(); doUpdate(properties); logger.debug("Activating BLE Xdk Driver... Done"); } protected synchronized void deactivate() { logger.debug("Deactivating BLE Xdk Driver..."); doDeactivate(); logger.debug("Deactivating BLE Xdk Driver... Done"); } public synchronized void updated(final Map<String, Object> properties) { logger.debug("Updating BLE Xdk Driver..."); doDeactivate(); doUpdate(properties); logger.debug("Updating BLE Xdk Driver... Done"); } private void doDeactivate() { if (this.bluetoothLeAdapter != null && this.bluetoothLeAdapter.isDiscovering()) { try { this.bluetoothLeAdapter.stopDiscovery(); } catch (KuraException e) { logger.error("Failed to stop discovery", e); } } try { disconnect(); } catch (ConnectionException e) { logger.error("Disconnection failed", e); } this.bluetoothLeAdapter = null; } private void doUpdate(Map<String, Object> properties) { extractProperties(properties); this.enableQuaternion = this.options.isEnableRotationQuaternion(); this.configSampleRate = 1000 / this.options.isConfigSampleRate(); this.bluetoothLeAdapter = this.bluetoothLeService.getAdapter(this.options.getBluetoothInterfaceName()); if (this.bluetoothLeAdapter != null) { logger.info("Bluetooth adapter interface => {}", this.options.getBluetoothInterfaceName()); if (!this.bluetoothLeAdapter.isPowered()) { logger.info("Enabling bluetooth adapter..."); this.bluetoothLeAdapter.setPowered(true); waitFor(1000); } logger.info("Bluetooth adapter address => {}", this.bluetoothLeAdapter.getAddress()); } else { logger.info("Bluetooth adapter {} not found.", this.options.getBluetoothInterfaceName()); } } @Override public void connect() throws ConnectionException { // connect to all Xdk in the map for (Entry<String, Xdk> entry : this.xdkMap.entrySet()) { if (!entry.getValue().isConnected()) { connect(entry.getValue()); } } } private void connect(Xdk xdk) throws ConnectionException { xdk.connect(); if (xdk.isConnected()) { xdk.init(); xdk.startSensor(this.enableQuaternion, this.configSampleRate); } } @Override public void disconnect() throws ConnectionException { // disconnect Xdk for (Entry<String, Xdk> entry : this.xdkMap.entrySet()) { if (entry.getValue().isConnected()) { entry.getValue().disconnect(); } } this.xdkMap.clear(); } private void extractProperties(final Map<String, Object> properties) { requireNonNull(properties, "Properties cannot be null"); this.options = new XdkOptions(properties); } @Override public ChannelDescriptor getChannelDescriptor() { return new XdkChannelDescriptor(); } public static Optional<TypedValue<?>> getTypedValue(final DataType expectedValueType, final Object containedValue) { try { switch (expectedValueType) { case LONG: return Optional.of(TypedValues.newLongValue((long) Double.parseDouble(containedValue.toString()))); case FLOAT: return Optional.of(TypedValues.newFloatValue(Float.parseFloat(containedValue.toString()))); case DOUBLE: return Optional.of(TypedValues.newDoubleValue(Double.parseDouble(containedValue.toString()))); case INTEGER: return Optional.of(TypedValues.newIntegerValue((int) Double.parseDouble(containedValue.toString()))); case BOOLEAN: return Optional.of(TypedValues.newBooleanValue(Boolean.parseBoolean(containedValue.toString()))); case STRING: return Optional.of(TypedValues.newStringValue(containedValue.toString())); case BYTE_ARRAY: return Optional.of(TypedValues.newByteArrayValue(TypeUtil.objectToByteArray(containedValue))); default: return Optional.empty(); } } catch (final Exception ex) { logger.error("Error while converting the retrieved value to the defined typed", ex); return Optional.empty(); } } private void runReadRequest(XdkRequestInfo requestInfo) { ChannelRecord record = requestInfo.channelRecord; try { Xdk xdk = getXdk(requestInfo.xdkAddress); if (xdk.isConnected()) { /* Read the data */ Object readResult = getReadResult(requestInfo.sensorName, xdk); final Optional<TypedValue<?>> typedValue = getTypedValue(requestInfo.dataType, readResult); if (!typedValue.isPresent()) { record.setChannelStatus(new ChannelStatus(FAILURE, "Error while converting the retrieved value to the defined typed", null)); record.setTimestamp(System.currentTimeMillis()); return; } record.setValue(typedValue.get()); record.setChannelStatus(new ChannelStatus(SUCCESS)); record.setTimestamp(System.currentTimeMillis()); } else { record.setChannelStatus(new ChannelStatus(FAILURE, "Unable to Connect...", null)); record.setTimestamp(System.currentTimeMillis()); } } catch (KuraBluetoothIOException | ConnectionException e) { record.setChannelStatus(new ChannelStatus(ChannelFlag.FAILURE, "Xdk Read Operation Failed", null)); record.setTimestamp(System.currentTimeMillis()); logger.warn(e.getMessage()); } } private Object getReadResult(SensorName sensorName, Xdk xdk) throws KuraBluetoothIOException { switch (sensorName) { // High Priority Data case ACCELERATION_X: return xdk.readHighData()[0]; case ACCELERATION_Y: return xdk.readHighData()[1]; case ACCELERATION_Z: return xdk.readHighData()[2]; case GYROSCOPE_X: return xdk.readHighData()[3]; case GYROSCOPE_Y: return xdk.readHighData()[4]; case GYROSCOPE_Z: return xdk.readHighData()[5]; // Low Priority Data - Message 1 case LIGHT: return xdk.readLowData(MESSAGE_ONE)[0]; case NOISE: return xdk.readLowData(MESSAGE_ONE)[1]; case PRESSURE: return xdk.readLowData(MESSAGE_ONE)[2]; case TEMPERATURE: return xdk.readLowData(MESSAGE_ONE)[3]; case HUMIDITY: return xdk.readLowData(MESSAGE_ONE)[4]; case SD_CARD_DETECT_STATUS: return xdk.readLowData(MESSAGE_ONE)[5]; case BUTTON_STATUS: return xdk.readLowData(MESSAGE_ONE)[6]; // Low Priority Data - Message 2 case MAGNETIC_X: return xdk.readLowData(MESSAGE_TWO)[0]; case MAGNETIC_Y: return xdk.readLowData(MESSAGE_TWO)[1]; case MAGNETIC_Z: return xdk.readLowData(MESSAGE_TWO)[2]; case MAGNETOMETER_RESISTANCE: return xdk.readLowData(MESSAGE_TWO)[3]; case LED_STATUS: return xdk.readLowData(MESSAGE_TWO)[4]; case VOLTAGE_LEM: return xdk.readLowData(MESSAGE_TWO)[5]; case QUATERNION_M: return xdk.readHighData()[6]; case QUATERNION_X: return xdk.readHighData()[7]; case QUATERNION_Y: return xdk.readHighData()[8]; case QUATERNION_Z: return xdk.readHighData()[9]; default: throw new KuraBluetoothIOException("Read is unsupported for sensor " + sensorName.toString()); } } private Xdk getXdk(String xdkAddress) throws KuraBluetoothIOException, ConnectionException { requireNonNull(xdkAddress); if (!this.xdkMap.containsKey(xdkAddress)) { Future<BluetoothLeDevice> future = this.bluetoothLeAdapter.findDeviceByAddress(TIMEOUT, xdkAddress); BluetoothLeDevice device = null; try { device = future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error("Get Xdk {} failed", xdkAddress, e); } catch (ExecutionException e) { logger.error("Get Xdk {} failed", xdkAddress, e); } if (device != null) { this.xdkMap.put(xdkAddress, new Xdk(device)); } else { throw new KuraBluetoothIOException("Resource unavailable"); } } Xdk xdk = this.xdkMap.get(xdkAddress); if (!xdk.isConnected()) { connect(xdk); } xdk.init(); return xdk; } @Override public void read(final List<ChannelRecord> records) throws ConnectionException { for (final ChannelRecord record : records) { XdkRequestInfo.extract(record).ifPresent(this::runReadRequest); } } @Override public void registerChannelListener(final Map<String, Object> channelConfig, final ChannelListener listener) throws ConnectionException { try { Xdk xdk = getXdk(XdkChannelDescriptor.getXdkAddress(channelConfig)); if (xdk.isConnected()) { SensorListener sensorListener = getSensorListener(xdk, XdkChannelDescriptor.getSensorName(channelConfig).toString()); sensorListener.addChannelName((String) channelConfig.get("+name")); sensorListener.addDataType(DataType.getDataType((String) channelConfig.get("+value.type"))); sensorListener.addListener(listener); sensorListener.addSensorName(XdkChannelDescriptor.getSensorName(channelConfig)); registerNotification(sensorListener); } else { logger.warn("Listener registration failed: Xdk not connected"); } } catch (KuraBluetoothIOException | ConnectionException e) { logger.error("Listener registration failed", e); } } @Override public void unregisterChannelListener(ChannelListener listener) throws ConnectionException { Iterator<SensorListener> iterator = this.sensorListeners.iterator(); while (iterator.hasNext()) { SensorListener sensorListener = iterator.next(); if (sensorListener.getListeners().contains(listener)) { if (sensorListener.getListeners().size() == 1) { unregisterNotification(sensorListener); iterator.remove(); } else { int index = sensorListener.getListeners().indexOf(listener); sensorListener.removeAll(index); } } } } @Override public void write(List<ChannelRecord> records) throws ConnectionException { throw new UnsupportedOperationException("Un supported operation."); } private static class XdkRequestInfo { private final DataType dataType; private final String xdkAddress; private final SensorName sensorName; private final ChannelRecord channelRecord; public XdkRequestInfo(final ChannelRecord channelRecord, final DataType dataType, final String xdkAddress, final SensorName sensorName) { this.dataType = dataType; this.xdkAddress = xdkAddress; this.sensorName = sensorName; this.channelRecord = channelRecord; } private static void fail(final ChannelRecord record, final String message) { record.setChannelStatus(new ChannelStatus(FAILURE, message, null)); record.setTimestamp(System.currentTimeMillis()); } public static Optional<XdkRequestInfo> extract(final ChannelRecord record) { final Map<String, Object> channelConfig = record.getChannelConfig(); final String xdkAddress; final SensorName sensorName; try { xdkAddress = XdkChannelDescriptor.getXdkAddress(channelConfig); } catch (final Exception e) { fail(record, "Error while retrieving Xdk address"); logger.error("Error retrieving Xdk Address", e); return Optional.empty(); } try { sensorName = XdkChannelDescriptor.getSensorName(channelConfig); } catch (final Exception e) { fail(record, "Error while retrieving sensor name"); logger.error("Error retrieving Sensor name", e); return Optional.empty(); } final DataType dataType = record.getValueType(); if (isNull(dataType)) { fail(record, "Error while retrieving value type"); return Optional.empty(); } return Optional.of(new XdkRequestInfo(record, dataType, xdkAddress, sensorName)); } } @Override public PreparedRead prepareRead(List<ChannelRecord> channelRecords) { requireNonNull(channelRecords, "Channel Record list cannot be null"); try (XdkPreparedRead preparedRead = new XdkPreparedRead()) { preparedRead.channelRecords = channelRecords; for (ChannelRecord record : channelRecords) { XdkRequestInfo.extract(record).ifPresent(preparedRead.requestInfos::add); } return preparedRead; } } private void registerNotification(SensorListener sensorListener) throws ConnectionException { if (!sensorListener.getXdk().isConnected()) { connect(sensorListener.getXdk()); } switch (sensorListener.getSensorType()) { case "ACCELERATION_X": case "ACCELERATION_Y": case "ACCELERATION_Z": case "GYROSCOPE_X": case "GYROSCOPE_Y": case "GYROSCOPE_Z": case "QUATERNION_M": case "QUATERNION_X": case "QUATERNION_Y": case "QUATERNION_Z": sensorListener.getXdk().disableHighNotifications(); sensorListener.getXdk().enableHighNotifications(SensorListener.getSensorConsumer(sensorListener)); break; case "LIGHT": case "NOISE": case "PRESSURE": case "TEMPERATURE": case "HUMIDITY": case "SD_CARD_DETECT_STATUS": case "BUTTON_STATUS": sensorListener.getXdk().disableLowNotifications(); sensorListener.getXdk().enableLowNotifications(SensorListener.getSensorConsumer(sensorListener), MESSAGE_ONE); break; case "MAGNETIC_X": case "MAGNETIC_Y": case "MAGNETIC_Z": case "MAGNETOMETER_RESISTENCE": case "LED_STATUS": case "VOLTAGE_LEM": sensorListener.getXdk().disableLowNotifications(); sensorListener.getXdk().enableLowNotifications(SensorListener.getSensorConsumer(sensorListener), MESSAGE_TWO); break; default: } } private void unregisterSensorNotification(SensorListener sensorListener) { if (sensorListener.getXdk().isHighNotifying()) { sensorListener.getXdk().disableHighNotifications(); } else if (sensorListener.getXdk().isLowNotifying()) { sensorListener.getXdk().disableLowNotifications(); } } private void unregisterNotification(SensorListener sensorListener) { if (sensorListener.getXdk().isConnected()) { unregisterSensorNotification(sensorListener); } else { logger.info("Listener unregistation failed: TiSensorTag not connected"); } } private class XdkPreparedRead implements PreparedRead { private final List<XdkRequestInfo> requestInfos = new ArrayList<>(); private List<ChannelRecord> channelRecords; @Override public synchronized List<ChannelRecord> execute() throws ConnectionException { for (XdkRequestInfo requestInfo : this.requestInfos) { runReadRequest(requestInfo); } return Collections.unmodifiableList(this.channelRecords); } @Override public List<ChannelRecord> getChannelRecords() { return Collections.unmodifiableList(this.channelRecords); } @Override public void close() { throw new UnsupportedOperationException("Un supported operation."); } } private SensorListener getSensorListener(Xdk xdk, String sensorType) { for (SensorListener listener : this.sensorListeners) { if (xdk == listener.getXdk() && sensorType.equals(listener.getSensorType())) { return listener; } } SensorListener sensorListener = new SensorListener(xdk, sensorType); this.sensorListeners.add(sensorListener); return sensorListener; } protected static void waitFor(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error(INTERRUPTED_EX, e); } } }
nicolatimeus/kura
kura/org.eclipse.kura.driver.ble.xdk/src/main/java/org/eclipse/kura/internal/driver/ble/xdk/XdkDriver.java
Java
epl-1.0
20,947
/* * Sonatype Nexus (TM) Open Source Version * Copyright (c) 2008-present Sonatype, Inc. * All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions. * * This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0, * which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html. * * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the * Eclipse Foundation. All other trademarks are the property of their respective owners. */ package org.sonatype.nexus.proxy.events; import org.sonatype.nexus.proxy.item.StorageItem; import org.sonatype.nexus.proxy.repository.Repository; /** * The event fired on item cache (will be followed by retrieve!) when overwrite of cached item does not happens * (create). * * @author cstamas * @since 2.0 */ public class RepositoryItemEventCacheCreate extends RepositoryItemEventCache { public RepositoryItemEventCacheCreate(final Repository repository, final StorageItem item) { super(repository, item); } }
scmod/nexus-public
components/nexus-core/src/main/java/org/sonatype/nexus/proxy/events/RepositoryItemEventCacheCreate.java
Java
epl-1.0
1,312
/******************************************************************************* * Copyright (c) 2008 Walter Harley * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * [email protected] - initial API and implementation * *******************************************************************************/ package org.eclipse.jdt.apt.pluggable.tests.annotations; /** * @since 3.5 */ public @interface LookAt {}
maxeler/eclipse
eclipse.jdt.core/org.eclipse.jdt.apt.pluggable.tests/src/org/eclipse/jdt/apt/pluggable/tests/annotations/LookAt.java
Java
epl-1.0
643
/* * Sonatype Nexus (TM) Open Source Version * Copyright (c) 2008-present Sonatype, Inc. * All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions. * * This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0, * which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html. * * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the * Eclipse Foundation. All other trademarks are the property of their respective owners. */ package org.sonatype.nexus.repository.metadata.validation; import org.sonatype.nexus.repository.metadata.MetadataHandlerException; public class ValidationException extends MetadataHandlerException { private static final long serialVersionUID = -8892632174114363043L; public ValidationException(String message) { super(message); } public ValidationException(String message, Throwable cause) { super(message, cause); } public ValidationException(Throwable cause) { super(cause); } }
scmod/nexus-public
components/nexus-repository-metadata-api/src/main/java/org/sonatype/nexus/repository/metadata/validation/ValidationException.java
Java
epl-1.0
1,296
/** * generated by Xtext */ package org.eclipse.xtext.parser.encoding.encodingTest.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.xtext.parser.encoding.encodingTest.EncodingTestPackage; import org.eclipse.xtext.parser.encoding.encodingTest.Word; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Word</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.eclipse.xtext.parser.encoding.encodingTest.impl.WordImpl#getValue <em>Value</em>}</li> * </ul> * * @generated */ public class WordImpl extends MinimalEObjectImpl.Container implements Word { /** * The default value of the '{@link #getValue() <em>Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getValue() * @generated * @ordered */ protected static final String VALUE_EDEFAULT = null; /** * The cached value of the '{@link #getValue() <em>Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getValue() * @generated * @ordered */ protected String value = VALUE_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected WordImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return EncodingTestPackage.Literals.WORD; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setValue(String newValue) { String oldValue = value; value = newValue; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, EncodingTestPackage.WORD__VALUE, oldValue, value)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case EncodingTestPackage.WORD__VALUE: return getValue(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case EncodingTestPackage.WORD__VALUE: setValue((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case EncodingTestPackage.WORD__VALUE: setValue(VALUE_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case EncodingTestPackage.WORD__VALUE: return VALUE_EDEFAULT == null ? value != null : !VALUE_EDEFAULT.equals(value); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (value: "); result.append(value); result.append(')'); return result.toString(); } } //WordImpl
miklossy/xtext-core
org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parser/encoding/encodingTest/impl/WordImpl.java
Java
epl-1.0
3,772
/******************************************************************************* * Copyright (c) 2010, 2012 Tasktop Technologies * Copyright (c) 2010, 2011 SpringSource, a division of VMware * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Tasktop Technologies - initial API and implementation ******************************************************************************/ package com.tasktop.c2c.server.profile.tests.service; import static org.junit.Assert.fail; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import com.tasktop.c2c.server.profile.service.ProfileService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({ "/applicationContext-hsql.xml", "/applicationContext-testSecurity.xml" }) @Transactional public class ProfileServiceSecurityTest { @Autowired private ProfileService profileService; @After public void after() { clearCredentials(); } private void clearCredentials() { SecurityContextHolder.getContext().setAuthentication(null); } @Test public void testCreateApplicationRequiresAuthentication() throws Exception { try { profileService.createProject(1L, null); fail("Expected authentication failure"); } catch (AuthenticationCredentialsNotFoundException e) { // expected } } @Test public void testGetApplicationRequiresAuthentication() throws Exception { try { profileService.getProject(null); fail("Expected authentication failure"); } catch (AuthenticationCredentialsNotFoundException e) { // expected } } @Test public void testGetProfileRequiresAuthentication() throws Exception { try { profileService.getProfile(null); fail("Expected authentication failure"); } catch (AuthenticationCredentialsNotFoundException e) { // expected } } @Test public void testGetProfileApplicationsRequiresAuthentication() throws Exception { try { profileService.getProfileProjects(null); fail("Expected authentication failure"); } catch (AuthenticationCredentialsNotFoundException e) { // expected } } @Test public void testGetProfileByEmailApplicationsRequiresAuthentication() throws Exception { try { profileService.getProfileByEmail(null); fail("Expected authentication failure"); } catch (AuthenticationCredentialsNotFoundException e) { // expected } } @Test public void testUpdateProfileByEmailApplicationsRequiresAuthentication() throws Exception { try { profileService.updateProfile(null); fail("Expected authentication failure"); } catch (AuthenticationCredentialsNotFoundException e) { // expected } } }
Tasktop/code2cloud.server
com.tasktop.c2c.server/com.tasktop.c2c.server.profile.server/src/test/java/com/tasktop/c2c/server/profile/tests/service/ProfileServiceSecurityTest.java
Java
epl-1.0
3,257
/** * Clase que representa el movimiento de un jugador. * Tiene un método para ejecutar el movimiento sobre la partida, y otro para deshacerlo. * Es una clase abstracta; habrá una clase no abstracta por cada tipo de juego soportado. */ package tp.pr3.logica; public abstract class Movimiento { protected int donde; protected Ficha color; protected Movimiento(int donde, Ficha color){ this.donde = donde; this.color = color; } /** * Devuelve el color del jugador al que pertenece el movimiento. * (Puede hacerse abstracto) * @return Color del jugador (coincide con el pasado al constructor). */ public abstract Ficha getJugador(); /** * Ejecuta el movimiento sobre el tablero que se recibe como par�metro. * Se puede dar por cierto que tablero recibido sigue las reglas del tipo de juego al que pertenece el movimiento. * En caso contrario, el comportamiento es indeterminado. * @param tab - Tablero sobre el que ejecutar el movimiento * @return true - Si todo fue bien. * Se devuelve false si el movimiento no puede ejecutarse sobre el tablero. */ public abstract boolean ejecutaMovimiento(Tablero tab); /** * Deshace el movimiento en el tablero recibido como parámetro. * Se puede dar por cierto que el movimiento se ejecutó sobre ese tablero; en caso contrario, el comportamiento es indeterminado. * Por lo tanto, es de suponer que el método siempre funcionará correctamente. * @param tab - Tablero de donde deshacer el movimiento. */ public abstract void undo(Tablero tab); /** * Devuleve la columna en la que se encuentra el movimiento. * @return donde - Columna en la que se encuentra el movimiento. */ public abstract int getDonde(); }
elzumbi/4EnRaya
tp/pr3/logica/Movimiento.java
Java
epl-1.0
1,715
package org.allmyinfo.xml.internal; import org.eclipse.jdt.annotation.NonNull; abstract class ChildState extends State { final @NonNull State parentState; ChildState(final @NonNull State parentState) { this.parentState = parentState; } }
sschafer/atomic
org.allmyinfo.xml/src/org/allmyinfo/xml/internal/ChildState.java
Java
epl-1.0
245
/* Copyright (C) 2003 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.grmm.util; import java.util.*; /** * Version of THashMap where every key is mapped to a list of objects. * <p> * The put method adds a value to the list associated with a key, without * removing any previous values. * The get method returns the list of all objects associated with key. * No effort is made to remove duplicates. * * Created: Dec 13, 2005 * * @author <A HREF="mailto:[email protected]>[email protected]</A> * @version $Id: THashMultiMap.java,v 1.1 2007/10/22 21:37:58 mccallum Exp $ */ public class THashMultiMap extends AbstractMap { // private THashMap backing; private HashMap backing; public THashMultiMap () { backing = new HashMap (); } public THashMultiMap (int initialCapacity) { backing = new HashMap (initialCapacity); } public Set entrySet () { return backing.entrySet (); // potentially inefficient } /** Adds <tt>key</tt> as a key with an empty list as a value. */ public void add (Object key) { backing.put (key, new ArrayList ()); } public Object get (Object o) { return (List) backing.get (o); } /** Adds <tt>value</tt> to the list of things mapped to by key. * @return The current list of values associated with key. * (N.B. This deviates from Map contract slightly! (Hopefully harmlessly)) */ public Object put (Object key, Object value) { List lst; if (!backing.keySet ().contains (key)) { lst = new ArrayList (); backing.put (key, lst); } else { lst = (List) backing.get (key); } lst.add (value); return lst; } // Serialization not yet supported }
cmoen/mallet
src/cc/mallet/grmm/util/THashMultiMap.java
Java
epl-1.0
2,067
package com.umeitime.common.tools; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; /** * @author: wlj * @Date: 2017-03-28 * @email: [email protected] * @desc: 文件工具类 */ public class FileUtils { public final static String FILE_SUFFIX_SEPARATOR = "."; /** * Read file * * @param filePath * @param charsetName * @return */ public static StringBuilder readFile(String filePath, String charsetName) { File file = new File(filePath); StringBuilder fileContent = new StringBuilder(""); if (file == null || !file.isFile()) { return null; } BufferedReader reader = null; try { InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName); reader = new BufferedReader(is); String line = null; while ((line = reader.readLine()) != null) { if (!fileContent.toString().equals("")) { fileContent.append("\r\n"); } fileContent.append(line); } return fileContent; } catch (IOException e) { throw new RuntimeException("IOException", e); } finally { IOUtils.close(reader); } } /** * Write file * * @param filePath * @param content * @param append * @return */ public static boolean writeFile(String filePath, String content, boolean append) { if (StringUtils.isEmpty(content)) { return false; } FileWriter fileWriter = null; try { makeDirs(filePath); fileWriter = new FileWriter(filePath, append); fileWriter.write(content); return true; } catch (IOException e) { throw new RuntimeException("IOException occurred. ", e); } finally { IOUtils.close(fileWriter); } } /** * write file, the string will be written to the begin of the file * * @param filePath * @param content * @return */ public static boolean writeFile(String filePath, String content) { return writeFile(filePath, content, false); } /** * Write file * * @param filePath * @param is * @return */ public static boolean writeFile(String filePath, InputStream is) { return writeFile(filePath, is, false); } /** * Write file * * @param filePath * @param is * @param append * @return */ public static boolean writeFile(String filePath, InputStream is, boolean append) { return writeFile(filePath != null ? new File(filePath) : null, is, append); } /** * Write file * * @param file * @param is * @return */ public static boolean writeFile(File file, InputStream is) { return writeFile(file, is, false); } /** * Write file * * @param file * @param is * @param append * @return */ public static boolean writeFile(File file, InputStream is, boolean append) { OutputStream o = null; try { makeDirs(file.getAbsolutePath()); o = new FileOutputStream(file, append); byte data[] = new byte[1024]; int length = -1; while ((length = is.read(data)) != -1) { o.write(data, 0, length); } o.flush(); return true; } catch (FileNotFoundException e) { throw new RuntimeException("FileNotFoundException", e); } catch (IOException e) { throw new RuntimeException("IOException", e); } finally { IOUtils.close(o); IOUtils.close(is); } } /** * Move file * * @param srcFilePath * @param destFilePath */ public static void moveFile(String srcFilePath, String destFilePath) throws FileNotFoundException { if (StringUtils.isEmpty(srcFilePath) || StringUtils.isEmpty(destFilePath)) { throw new RuntimeException("Both srcFilePath and destFilePath cannot be null."); } moveFile(new File(srcFilePath), new File(destFilePath)); } /** * Move file * * @param srcFile * @param destFile */ public static void moveFile(File srcFile, File destFile) throws FileNotFoundException { boolean rename = srcFile.renameTo(destFile); if (!rename) { copyFile(srcFile.getAbsolutePath(), destFile.getAbsolutePath()); deleteFile(srcFile.getAbsolutePath()); } } /** * Copy file * * @param srcFilePath * @param destFilePath * @return * @throws FileNotFoundException */ public static boolean copyFile(String srcFilePath, String destFilePath) { try { InputStream inputStream = new FileInputStream(srcFilePath); return writeFile(destFilePath, inputStream); }catch (Exception e){ return false; } } /** * rename file * * @param file * @param newFileName * @return */ public static boolean renameFile(File file, String newFileName) { File newFile = null; if (file.isDirectory()) { newFile = new File(file.getParentFile(), newFileName); } else { String temp = newFileName + file.getName().substring( file.getName().lastIndexOf('.')); newFile = new File(file.getParentFile(), temp); } if (file.renameTo(newFile)) { return true; } return false; } /** * Get file name without suffix * * @param filePath * @return */ public static String getFileNameWithoutSuffix(String filePath) { if (StringUtils.isEmpty(filePath)) { return filePath; } int suffix = filePath.lastIndexOf(FILE_SUFFIX_SEPARATOR); int fp = filePath.lastIndexOf(File.separator); if (fp == -1) { return (suffix == -1 ? filePath : filePath.substring(0, suffix)); } if (suffix == -1) { return filePath.substring(fp + 1); } return (fp < suffix ? filePath.substring(fp + 1, suffix) : filePath.substring(fp + 1)); } /** * Get file name * * @param filePath * @return */ public static String getFileName(String filePath) { if (StringUtils.isEmpty(filePath)) { return filePath; } int fp = filePath.lastIndexOf(File.separator); return (fp == -1) ? filePath : filePath.substring(fp + 1); } /** * Get folder name * * @param filePath * @return */ public static String getFolderName(String filePath) { if (StringUtils.isEmpty(filePath)) { return filePath; } int fp = filePath.lastIndexOf(File.separator); return (fp == -1) ? "" : filePath.substring(0, fp); } /** * Get suffix of file * * @param filePath * @return */ public static String getFileSuffix(String filePath) { if (StringUtils.isEmpty(filePath)) { return filePath; } int suffix = filePath.lastIndexOf(FILE_SUFFIX_SEPARATOR); int fp = filePath.lastIndexOf(File.separator); if (suffix == -1) { return ""; } return (fp >= suffix) ? "" : filePath.substring(suffix + 1); } /** * Create the directory * * @param filePath * @return */ public static boolean makeDirs(String filePath) { String folderName = getFolderName(filePath); if (StringUtils.isEmpty(folderName)) { return false; } File folder = new File(folderName); return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs(); } /** * Judge whether a file is exist * * @param filePath * @return */ public static boolean isFileExist(String filePath) { if (StringUtils.isEmpty(filePath)) { return false; } File file = new File(filePath); return (file.exists() && file.isFile()); } /** * Judge whether a folder is exist * * @param directoryPath * @return */ public static boolean isFolderExist(String directoryPath) { if (StringUtils.isEmpty(directoryPath)) { return false; } File dire = new File(directoryPath); return (dire.exists() && dire.isDirectory()); } /** * Delete file or folder * * @param path * @return */ public static boolean deleteFile(String path) { if (StringUtils.isEmpty(path)) { return true; } File file = new File(path); if (!file.exists()) { return true; } if (file.isFile()) { return file.delete(); } if (!file.isDirectory()) { return false; } if (file.isDirectory()) { for (File f : file.listFiles()) { if (f.isFile()) { f.delete(); } else if (f.isDirectory()) { deleteFile(f.getAbsolutePath()); } } } return file.delete(); } /** * Delete file or folder * * @param file * @return */ public static boolean deleteFile(File file) { if (!file.exists()) { return true; } if (file.isFile()) { return file.delete(); } if (!file.isDirectory()) { return false; } if (file.isDirectory()) { File[] childFile = file.listFiles(); if (childFile == null || childFile.length == 0) { return file.delete(); } for (File f : childFile) { deleteFile(f); } } return file.delete(); } /** * Get file size * * @param path * @return */ public static long getFileSize(String path) { if (StringUtils.isEmpty(path)) { return -1; } File file = new File(path); return (file.exists() && file.isFile() ? (int)(file.length() /1024)+1 : -1); } /** * Get folder size * * @param file * @return * @throws Exception */ public static long getFolderSize(File file) throws Exception { long size = 0; try { File[] fileList = file.listFiles(); for (int i = 0; i < fileList.length; i++) { if (fileList[i].isDirectory()) { size = size + getFolderSize(fileList[i]); } else { size = size + fileList[i].length(); } } } catch (Exception e) { e.printStackTrace(); } return size; } }
umeitime/common
common-library/src/main/java/com/umeitime/common/tools/FileUtils.java
Java
epl-1.0
11,414
/* WeirdX - Guess * * Copyright (C) 1999-2004 JCraft, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package com.jcraft.weirdx; import java.io.IOException; import java.net.Socket; /** * Socket for display. * * @author JCraft. * */ public interface DisplaySocket { /** * Initialize a display. * * @param display the display number. * @throws IOException if an I/O error occured at * during the initialization. */ public void init(int display) throws IOException; public Socket accept() throws IOException; /** * Close the display. * * @throws IOException if an I/O error occured. */ public void close() throws IOException; }
wrey75/Lynx
src/main/java/com/jcraft/weirdx/DisplaySocket.java
Java
gpl-2.0
1,329
/* * Copyright (C) 2018 Tobias Raatiniemi * * 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, version 2 of the License. * * 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 me.raatiniemi.worker.util; import android.content.Context; import android.view.inputmethod.InputMethodManager; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import timber.log.Timber; import static me.raatiniemi.worker.util.NullUtil.isNull; public class Keyboard { /** * Store the InputMethodManager. */ private static InputMethodManager inputMethodManager; private Keyboard() { } /** * Retrieve the InputMethodManager. * * @param context Context used to retrieve the InputMethodManager. * @return InputMethodManager if we're able to retrieve it, otherwise null. */ @Nullable private static InputMethodManager getInputMethodManager(@NonNull Context context) { // If we don't have the input method manager available, // we have to retrieve it from the context. if (isNull(inputMethodManager)) { try { inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); } catch (ClassCastException e) { Timber.w(e, "Unable to cast the Context.INPUT_METHOD_SERVICE to InputMethodManager"); } } return inputMethodManager; } /** * Forcing the keyboard to show. * * @param context Context used when showing the keyboard. */ public static void show(@NonNull Context context) { // Check that we have the input method manager available. InputMethodManager manager = getInputMethodManager(context); if (isNull(manager)) { Timber.w("Unable to retrieve the InputMethodManager"); return; } manager.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); } }
raatiniemi/worker
app/src/main/java/me/raatiniemi/worker/util/Keyboard.java
Java
gpl-2.0
2,440
package java.refactoring; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; class B implements ActionListener { JButton but1; JButton but2; B() { but1 = new JButton("foo1"); but1.setActionCommand("FOO"); but1.addActionListener(B.this); but2 = new JButton("foo2"); but2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("coucou2"); } }); } @Override public void actionPerformed(final ActionEvent e) { if (e.getActionCommand().equals("FOO")) { System.out.println("coucou1"); return ; } } }
diverse-project/InspectorGuidget
sources/InspectorGuidgetToolSuite/inspectorguidget.core/src/test/resources/java/refactoring/BRefactoredAnonOneCmd.java
Java
gpl-2.0
635
/** * This file is released under the GNU General Public License. * Refer to the COPYING file distributed with this package. * * Copyright (c) 2008-2009 WURFL-Pro srl */ package net.sourceforge.wurfl.wng.taglibs; import javax.servlet.jsp.JspException; import net.sourceforge.wurfl.wng.component.Component; import net.sourceforge.wurfl.wng.component.Header; import net.sourceforge.wurfl.wng.component.Text; import org.apache.commons.lang.StringUtils; /** * @author Asres Gizaw Fantayeneh * @version $Id: TextTag.java 1131 2009-03-26 15:25:54Z filippo.deluca $ */ public class TextTag extends ComponentTag { private static final long serialVersionUID = 10L; private String text; public void setText(String text) { this.text = text; } protected Component createComponent() { return new Text(); } protected void configureComponent(Component component) throws JspException { super.configureComponent(component); Text textComponent = (Text)component; if(StringUtils.isNotBlank(text)){ textComponent.setContent(text); } } protected void postConfigureComponent(Component component) throws JspException { Text textComponent = (Text)component; boolean isContentInbody = getBodyContent() != null && StringUtils.isNotBlank(getBodyContent().getString()); if(isContentInbody) { textComponent.setContent(getBodyContent().getString().trim()); } super.postConfigureComponent(component); } protected void addComponentToParent(Component component) throws JspException { Component parentComponent = getParentComponent(); Text textComponent = (Text) component; if(parentComponent instanceof Header){ Header parentHeader = (Header)parentComponent; parentHeader.setText(textComponent); } else { super.addComponentToParent(component); } } }
Karniyarik/karniyarik
karniyarik-wng/src/main/java/net/sourceforge/wurfl/wng/taglibs/TextTag.java
Java
gpl-2.0
1,825
/* Copyright (c) 2007 Pentaho Corporation. All rights reserved. * This software was developed by Pentaho Corporation and is provided under the terms * of the GNU Lesser General Public License, Version 2.1. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho * Data Integration. The Initial Developer is Pentaho Corporation. * * Software distributed under the GNU Lesser Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations.*/ package com.panet.imeta.core.exception; /** * This exception is used by the Database class. * * @author Matt * @since 9-12-2004 * */ public class KettleDatabaseException extends KettleException { public static final long serialVersionUID = 0x8D8EA0264F7A1C0FL; /** * Constructs a new throwable with null as its detail message. */ public KettleDatabaseException() { super(); } /** * Constructs a new throwable with the specified detail message. * @param message - the detail message. The detail message is saved for later retrieval by the getMessage() method. */ public KettleDatabaseException(String message) { super(message); } /** * Constructs a new throwable with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause). * @param cause the cause (which is saved for later retrieval by the getCause() method). (A null value is permitted, and indicates that the cause is nonexistent or unknown.) */ public KettleDatabaseException(Throwable cause) { super(cause); } /** * Constructs a new throwable with the specified detail message and cause. * @param message the detail message (which is saved for later retrieval by the getMessage() method). * @param cause the cause (which is saved for later retrieval by the getCause() method). (A null value is permitted, and indicates that the cause is nonexistent or unknown.) */ public KettleDatabaseException(String message, Throwable cause) { super(message, cause); } }
panbasten/imeta
imeta2.x/imeta-src/imeta-core/src/main/java/com/panet/imeta/core/exception/KettleDatabaseException.java
Java
gpl-2.0
2,313
package com.moozvine.detox.repackaged.org.json; /** * The <code>JSONString</code> interface allows a <code>toJSONString()</code> * method so that a class can change the behavior of * <code>JSONObject.toString()</code>, <code>JSONArray.toString()</code>, * and <code>JSONWriter.value(</code>Object<code>)</code>. The * <code>toJSONString</code> method will be used instead of the default behavior * of using the Object's <code>toString()</code> method and quoting the result. */ public interface JSONString { /** * The <code>toJSONString</code> method allows a class to produce its own JSON * serialization. * * @return A strictly syntactically correct JSON text. */ public String toJSONString(); }
richmartin/detox
src/main/java/com/moozvine/detox/repackaged/org/json/JSONString.java
Java
gpl-2.0
723
package it.gerard.minecraft.plugin.command; import com.google.common.collect.Iterables; import lombok.extern.slf4j.Slf4j; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Horse; import org.bukkit.entity.Player; /** * Created by gerard on 08/12/14. */ @Slf4j public class NameHorse implements CommandExecution { @Override public boolean go(CommandSender sender, Command command, Iterable<String> args) { if (sender instanceof Player) { Player me = (Player)sender; Horse horse = me.getWorld().spawn(me.getLocation(), Horse.class); horse.setCustomName(Iterables.getFirst(args, "Horse")); horse.setCustomNameVisible(true); return true; } else { log.warn("command is avaliable on players"); return false; } } }
CoderDojoMilano/coderdojo-minecraft-bukkit-plugins
gerard-plugin/src/main/java/it/gerard/minecraft/plugin/command/NameHorse.java
Java
gpl-2.0
886
package com.Doctor.Thief.nms; import net.minecraft.server.v1_7_R3.*; public class NullPlayerConnection extends PlayerConnection{ public NullPlayerConnection(MinecraftServer minecraftserver, NetworkManager networkmanager, EntityPlayer entityplayer) { super(minecraftserver, networkmanager, entityplayer); } @Override public void a(PacketPlayInWindowClick packet) { } @Override public void a(PacketPlayInTransaction packet) { } @Override public void a(PacketPlayInFlying packet) { } @Override public void a(PacketPlayInUpdateSign packet) { } @Override public void a(PacketPlayInBlockDig packet) { } @Override public void a(PacketPlayInBlockPlace packet) { } @Override public void disconnect(String s) { } @Override public void a(PacketPlayInHeldItemSlot packetplayinhelditemslot) { } @Override public void a(PacketPlayInChat packetplayinchat) { } @Override public void sendPacket(Packet packet) { } }
stopbox/Theif
com/Doctor/Thief/nms/NullPlayerConnection.java
Java
gpl-2.0
1,093
package com.itachi1706.Bukkit.SpeedChallenge.Gamemodes; import com.itachi1706.Bukkit.SpeedChallenge.Main; import com.itachi1706.Bukkit.SpeedChallenge.Utilities.ScoreboardHelper; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; /** * Created by Kenneth on 17/7/2015. * for SpeedChallenge in com.itachi1706.Bukkit.SpeedChallenge.Gamemodes */ public class EthoSpeedChallenge4 extends AbstractGamemode { private static ArrayList<Integer> checkCompleted = new ArrayList<Integer>(); private static int maxPts = 5; //Max points possible to get per player private static String challengeTitle = "The Colour Wheel (Etho's Speed Challenge)"; public static String getGMTitle(){ return challengeTitle; } public static void gmInfo(){ // List all information about the gamemode Bukkit.getServer().broadcastMessage(ChatColor.translateAlternateColorCodes('&', "&6==================================================")); Bukkit.getServer().broadcastMessage(ChatColor.translateAlternateColorCodes('&', "&4&l Etho's Speed Challenge")); Bukkit.getServer().broadcastMessage(ChatColor.translateAlternateColorCodes('&', "&4&l The Colour Wheel")); Bukkit.getServer().broadcastMessage(ChatColor.translateAlternateColorCodes('&', "&6==================================================")); Bukkit.getServer().broadcastMessage(ChatColor.translateAlternateColorCodes('&', "&3Based on the Speed Challenge recorded by &6Etho")); Bukkit.getServer().broadcastMessage(ChatColor.translateAlternateColorCodes('&', "&a&lObjectives")); Bukkit.getServer().broadcastMessage(ChatColor.translateAlternateColorCodes('&', "&bGet 1 of each colour of wool to complete this challenge!")); Bukkit.getServer().broadcastMessage(ChatColor.translateAlternateColorCodes('&', "&a")); Bukkit.getServer().broadcastMessage(ChatColor.translateAlternateColorCodes('&', "&6==================================================")); Bukkit.getServer().broadcastMessage(ChatColor.translateAlternateColorCodes('&', "&aTo check your current objectives, do &6/listobjectives")); } public static void checkInventory(){ checkCompleted.clear(); if (Main.gamePlayerList.size() == 0){ Bukkit.getLogger().info("INVALID - NO PLAYERS"); return; } for (int i = 0; i < Main.gamePlayerList.size(); i++){ Player p = Main.gamePlayerList.get(i); int check = checkObjective(p); checkCompleted.add(check); } int total = 0; for (int i = 0; i < checkCompleted.size(); i++){ total += checkCompleted.get(i); } if (total == (maxPts*Main.gamePlayerList.size())){ //Completed Bukkit.getServer().broadcastMessage("All players have completed the objective! Game ends now!"); Main.countdown = 0; } } public static int checkObjective(Player p){ //Basic Score int score = 0; Inventory i = p.getInventory(); //Check for the 16 wool colours if (checkWool(i)){ //Adds a Score score += 1; } if (checkOrangeWool(i)){ //Adds a Score score += 1; } if (checkMagentaWool(i)){ //Adds a Score score += 1; } if (checkLightBlueWool(i)){ //Adds a Score score += 1; } if (checkYellowWool(i)){ //Adds a Score score += 1; } if (checkLimeWool(i)){ //Adds a Score score += 1; } if (checkPinkWool(i)){ //Adds a Score score += 1; } if (checkGrayWool(i)){ //Adds a Score score += 1; } if (checkLightGrayWool(i)){ //Adds a Score score += 1; } if (checkCyanWool(i)){ //Adds a Score score += 1; } if (checkPurpleWool(i)){ //Adds a Score score += 1; } if (checkBlueWool(i)){ //Adds a Score score += 1; } if (checkBrownWool(i)){ //Adds a Score score += 1; } if (checkGreenWool(i)){ //Adds a Score score += 1; } if (checkRedWool(i)){ //Adds a Score score += 1; } if (checkBlackWool(i)){ //Adds a Score score += 1; } //End of it add score to player ScoreboardHelper.setScoreOfPlayer(p, score); return score; } //List all objectives for a player (for future command) public static void listObjectives(Player p){ ArrayList<String> check = new ArrayList<String>(); check.add(ChatColor.GOLD + "Objectives Check"); check.add("Legend: Green = " + ChatColor.GREEN + "Obtained" + ChatColor.RESET + ", Red = " + ChatColor.RED + "Unobtained"); check.add(""); Inventory i = p.getInventory(); //Check for the 16 wool colours if (checkWool(i)){ check.add(ChatColor.GREEN + "White Wool"); } else { check.add(ChatColor.RED + "White Wool"); } if (checkOrangeWool(i)){ check.add(ChatColor.GREEN + "Orange Wool"); } else { check.add(ChatColor.RED + "Orange Wool"); } if (checkMagentaWool(i)){ check.add(ChatColor.GREEN + "Magenta Wool"); } else { check.add(ChatColor.RED + "Magenta Wool"); } if (checkLightBlueWool(i)){ check.add(ChatColor.GREEN + "Light Blue Wool"); } else { check.add(ChatColor.RED + "Light Blue Wool"); } if (checkYellowWool(i)){ check.add(ChatColor.GREEN + "Yellow Wool"); } else { check.add(ChatColor.RED + "Yellow Wool"); } if (checkLimeWool(i)){ check.add(ChatColor.GREEN + "Lime Wool"); } else { check.add(ChatColor.RED + "Lime Wool"); } if (checkPinkWool(i)){ check.add(ChatColor.GREEN + "Pink Wool"); } else { check.add(ChatColor.RED + "Pink Wool"); } if (checkGrayWool(i)){ check.add(ChatColor.GREEN + "Gray Wool"); } else { check.add(ChatColor.RED + "Gray Wool"); } if (checkLightGrayWool(i)){ check.add(ChatColor.GREEN + "Light Gray Wool"); } else { check.add(ChatColor.RED + "Light Gray Wool"); } if (checkCyanWool(i)){ check.add(ChatColor.GREEN + "Cyan Wool"); } else { check.add(ChatColor.RED + "Cyan Wool"); } if (checkPurpleWool(i)){ check.add(ChatColor.GREEN + "Purple Wool"); } else { check.add(ChatColor.RED + "Purple Wool"); } if (checkBlueWool(i)){ check.add(ChatColor.GREEN + "Blue Wool"); } else { check.add(ChatColor.RED + "Blue Wool"); } if (checkBrownWool(i)){ check.add(ChatColor.GREEN + "Brown Wool"); } else { check.add(ChatColor.RED + "Brown Wool"); } if (checkGreenWool(i)){ check.add(ChatColor.GREEN + "Green Wool"); } else { check.add(ChatColor.RED + "Green Wool"); } if (checkRedWool(i)){ check.add(ChatColor.GREEN + "Red Wool"); } else { check.add(ChatColor.RED + "Red Wool"); } if (checkBlackWool(i)){ check.add(ChatColor.GREEN + "Black Wool"); } else { check.add(ChatColor.RED + "Black Wool"); } p.sendMessage(ChatColor.GOLD + "=================================================="); p.sendMessage(check.get(0)); p.sendMessage(check.get(1)); p.sendMessage(check.get(2)); for (int c = 3; c < check.size(); c++) if (c % 3 == 0){ if ((c + 1) >= check.size()){ //Only display 1 p.sendMessage(check.get(c)); } else if ((c+2) >= check.size()){ //Only displays 2 p.sendMessage(check.get(c) + ChatColor.RESET + " - " + check.get(c+1)); } else { //Displays 3 p.sendMessage(check.get(c) + ChatColor.RESET + " - " + check.get(c+1) + ChatColor.RESET + " - " + check.get(c+2)); } } p.sendMessage(ChatColor.GOLD + "=================================================="); } private static boolean checkWool(Inventory inv){ ItemStack item = new ItemStack(Material.WOOL); item.setDurability((short) 0); if (inv.containsAtLeast(item, 1)){ return true; } return false; } private static boolean checkOrangeWool(Inventory inv){ ItemStack item = new ItemStack(Material.WOOL); item.setDurability((short) 1); if (inv.containsAtLeast(item, 1)){ return true; } return false; } private static boolean checkMagentaWool(Inventory inv){ ItemStack item = new ItemStack(Material.WOOL); item.setDurability((short) 2); if (inv.containsAtLeast(item, 1)){ return true; } return false; } private static boolean checkLightBlueWool(Inventory inv){ ItemStack item = new ItemStack(Material.WOOL); item.setDurability((short) 3); if (inv.containsAtLeast(item, 1)){ return true; } return false; } private static boolean checkYellowWool(Inventory inv){ ItemStack item = new ItemStack(Material.WOOL); item.setDurability((short) 4); if (inv.containsAtLeast(item, 1)){ return true; } return false; } private static boolean checkLimeWool(Inventory inv){ ItemStack item = new ItemStack(Material.WOOL); item.setDurability((short) 5); if (inv.containsAtLeast(item, 1)){ return true; } return false; } private static boolean checkPinkWool(Inventory inv){ ItemStack item = new ItemStack(Material.WOOL); item.setDurability((short) 6); if (inv.containsAtLeast(item, 1)){ return true; } return false; } private static boolean checkGrayWool(Inventory inv){ ItemStack item = new ItemStack(Material.WOOL); item.setDurability((short) 7); if (inv.containsAtLeast(item, 1)){ return true; } return false; } private static boolean checkLightGrayWool(Inventory inv){ ItemStack item = new ItemStack(Material.WOOL); item.setDurability((short) 8); if (inv.containsAtLeast(item, 1)){ return true; } return false; } private static boolean checkCyanWool(Inventory inv){ ItemStack item = new ItemStack(Material.WOOL); item.setDurability((short) 9); if (inv.containsAtLeast(item, 1)){ return true; } return false; } private static boolean checkPurpleWool(Inventory inv){ ItemStack item = new ItemStack(Material.WOOL); item.setDurability((short) 10); if (inv.containsAtLeast(item, 1)){ return true; } return false; } private static boolean checkBlueWool(Inventory inv){ ItemStack item = new ItemStack(Material.WOOL); item.setDurability((short) 11); if (inv.containsAtLeast(item, 1)){ return true; } return false; } private static boolean checkBrownWool(Inventory inv){ ItemStack item = new ItemStack(Material.WOOL); item.setDurability((short) 12); if (inv.containsAtLeast(item, 1)){ return true; } return false; } private static boolean checkGreenWool(Inventory inv){ ItemStack item = new ItemStack(Material.WOOL); item.setDurability((short) 13); if (inv.containsAtLeast(item, 1)){ return true; } return false; } private static boolean checkRedWool(Inventory inv){ ItemStack item = new ItemStack(Material.WOOL); item.setDurability((short) 14); if (inv.containsAtLeast(item, 1)){ return true; } return false; } private static boolean checkBlackWool(Inventory inv){ ItemStack item = new ItemStack(Material.WOOL); item.setDurability((short) 15); if (inv.containsAtLeast(item, 1)){ return true; } return false; } }
itachi1706/Bukkit
SpeedChallenge/src/com/itachi1706/Bukkit/SpeedChallenge/Gamemodes/EthoSpeedChallenge4.java
Java
gpl-2.0
13,150
/* * Copyright (c) 2012-2013 Open Source Community - <http://www.peerfact.org> * Copyright (c) 2011-2012 University of Paderborn - UPB * Copyright (c) 2005-2011 KOM - Multimedia Communications Lab * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ package org.peerfact.impl.network.gnp; import static org.junit.Assert.assertEquals; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.peerfact.impl.network.gnp.geoip.IspLookupService; public class IspLookupTest { IspLookupService ls; @Before public void setUp() { ls = new IspLookupService("data/GeoIP/GeoIPISP.csv"); } @Test public void testLookup() { String result; // 33996344,33996351,"BT North Block Cambridge" result = ls.getISP(33996344); assertEquals(result, "BT North Block Cambridge"); result = ls.getISP(33996351); assertEquals(result, "BT North Block Cambridge"); // 67108864,83886079,"Level 3 Communications" result = ls.getISP(83886060); assertEquals(result, "Level 3 Communications"); // 1503657984,1503690751,"Skycom Nordic AB" result = ls.getISP(1503690743); assertEquals(result, "Skycom Nordic AB"); } @After public void tearDown() { // No implementation here (not sure why) by Thim // This text is here so that later on someone will find this. } }
flyroom/PeerfactSimKOM_Clone
test/org/peerfact/impl/network/gnp/IspLookupTest.java
Java
gpl-2.0
1,919
package client.thread.addFriendsThread; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import Windows_MainInterface.MainInterface; import common.message.*; /** * 2011年10月 * * 山东科技大学信息学院 版权所有 * * 联系邮箱:[email protected] * * Copyright © 1999-2012, sdust, All Rights Reserved * * @author 王昌帅,司吉峰,王松松 (计算机2009-5、6班) * */ public class sendAddRequestThread extends Thread { final int port = 10007; int localSysPort; Socket client; public int changed; public addMessage add; testMessage test; public sendAddRequestThread(addMessage add, int localSystemReceiverPort) throws UnknownHostException, IOException { super(); changed = 0; this.localSysPort = localSystemReceiverPort; this.add = new addMessage(add); this.client = new Socket(MainInterface.ip, port); start(); } public void run() { try { ObjectOutputStream oout = new ObjectOutputStream(client.getOutputStream()); oout.writeObject(add); ObjectInputStream oin = new ObjectInputStream(client.getInputStream()); test = new testMessage((testMessage) oin.readObject()); if (test.sign == 2) { sendAuthenticationThread sender = new sendAuthenticationThread(new authentication(add.myqqNum, add.qq, "wangchangshuai")); } else { Socket client = new Socket(InetAddress.getLocalHost(), localSysPort); ObjectOutputStream oou = new ObjectOutputStream(client.getOutputStream()); String text = ""; if (test.sign == 1) { text = "添加好友成功!"; } else { text = "对方设置不允许任何人加入!"; } oou.writeObject(new systemMessage(text)); } client.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
wangchangshuai/fei_Q
client/src/client/thread/addFriendsThread/sendAddRequestThread.java
Java
gpl-2.0
2,167
package com.austinv11.dartcraft2.init; import com.austinv11.dartcraft2.events.handlers.BucketHandler; import com.austinv11.dartcraft2.items.*; import com.austinv11.dartcraft2.reference.Reference; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidContainerRegistry; @GameRegistry.ObjectHolder(Reference.MOD_ID) public class ModItems { public static final ItemDC forceGem = new ItemForceGem(); public static final Item liquidForceBucket = new ItemLiquidForceBucket(ModFluids.liquidForce); public static final ItemDC clipboard = new ItemClipboard(); public static final ItemDC forceIngot = new ItemForceIngot(); public static final ItemDC forceNugget = new ItemForceNugget(); public static final ItemDC forceStick = new ItemForceStick(); public static final ItemDC forceRod = new ItemForceRod(); public static final ItemDC forceBelt = new ItemForceBelt(); public static final Item forceMitts = new ItemForceMitts(); public static final ItemGoldenPowerSource goldenPowerSource = new ItemGoldenPowerSource(); public static final ItemDC forcePack = new ItemForcePack(); public static final ItemDC upgradeTome = new ItemUpgradeTome(); public static void init() { GameRegistry.registerItem(forceGem, "forceGem"); GameRegistry.registerItem(liquidForceBucket, "liquidForceBucket"); FluidContainerRegistry.registerFluidContainer(ModFluids.liquidForce, new ItemStack(liquidForceBucket), new ItemStack(Items.bucket)); BucketHandler.buckets.put(ModBlocks.liquidForce, liquidForceBucket); GameRegistry.registerItem(clipboard, "clipboard"); GameRegistry.registerItem(forceIngot, "forceIngot"); GameRegistry.registerItem(forceNugget, "forceNugget"); GameRegistry.registerItem(forceRod, "forceRod"); GameRegistry.registerItem(forceStick, "forceStick"); GameRegistry.registerItem(forceBelt, "forceBelt"); GameRegistry.registerItem(forceMitts, "forceMitts"); GameRegistry.registerItem(goldenPowerSource, "goldenPowerSource"); GameRegistry.registerFuelHandler(goldenPowerSource); GameRegistry.registerItem(forcePack, "forcePack"); GameRegistry.registerItem(upgradeTome, "upgradeTome"); } }
austinv11/DartCraft2
src/main/java/com/austinv11/dartcraft2/init/ModItems.java
Java
gpl-2.0
2,286
package com.maxleap.cloudcode; import com.maxleap.cloudcode.processors.CCodeSimpleProcessor; import com.maxleap.domain.auth.LASPrincipal; import io.vertx.core.http.HttpServerResponse; import org.apache.http.util.Asserts; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Scheduler; import rx.schedulers.Schedulers; import javax.inject.Inject; import javax.inject.Singleton; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * User: yuyangning * Date: 8/11/14 * Time: 2:48 PM */ @Singleton public class CCodeExecutor { private static final Logger logger = LoggerFactory.getLogger(CCodeExecutor.class); private CCodeProcessor simpleProcessor; private final Scheduler scheduler; private CloudCodeRestClient cloudCodeRestClient; @Inject public CCodeExecutor(CloudCodeRestClient cloudCodeRestClient) { this.cloudCodeRestClient = cloudCodeRestClient; this.simpleProcessor = new CCodeSimpleProcessor(); scheduler = Schedulers.from(new ThreadPoolExecutor(80, 500, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(2000))); } public <T extends Object> T execute(CCodeEntity codeEntity,LASPrincipal userPrincipal) { return execute(codeEntity, simpleProcessor, null,userPrincipal); } public <T extends Object> T execute(CCodeEntity codeEntity,HttpServerResponse response,LASPrincipal userPrincipal) { return execute(codeEntity, simpleProcessor, response,userPrincipal); } /** * execute cloud code. * * @param codeEntity * @param processor * @return */ public <T extends Object> T execute(CCodeEntity codeEntity, CCodeProcessor processor,LASPrincipal userPrincipal) { return this.execute(codeEntity, processor,null,userPrincipal); } public <T extends Object> T execute(CCodeEntity codeEntity, CCodeProcessor processor,HttpServerResponse response,LASPrincipal userPrincipal) { validate(codeEntity);//validate input data. String result = cloudCodeRestClient.doPost("/" + codeEntity.getCategory().alias() + "/" + codeEntity.getName(), codeEntity.getParameters(), response, userPrincipal); return (T)processor.process(result); } /** * validate the input data. * * @param codeEntity */ public void validate(CCodeEntity codeEntity) { Asserts.notNull(codeEntity, "The codeEntity can't be null."); Asserts.notNull(codeEntity.getAppId(), "The codeEntity's appId can't be empty."); Asserts.notNull(codeEntity.getName(), "The codeEntity's name can't be empty."); Asserts.notNull(codeEntity.getCategory(), "The codeEntity's category can't be null."); } }
MaxLeap/MyBaaS
maxleap-baas-impl/src/main/java/com/maxleap/cloudcode/CCodeExecutor.java
Java
gpl-2.0
2,675
package v9; /** * Created by Eric on 1/12/2016. */ public class Item { private String title; private int playingTime; private boolean gotIT; private String comment; public Item() { } public Item(String title, int playingTime, boolean gotIT, String comment) { this.title = title; this.playingTime = playingTime; this.gotIT = gotIT; this.comment = comment; } public void print() { System.out.print(title); } }
echo1937/MyJavaExercise
javabasic/src/v9/Item.java
Java
gpl-2.0
496
/* * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.outerthoughts.javadoc.iframed.internal.toolkit.util; import java.util.*; import com.sun.javadoc.*; import com.outerthoughts.javadoc.iframed.internal.toolkit.*; /** * Process and manage grouping of packages, as specified by "-group" option on * the command line. * <p> * For example, if user has used -group option as * -group "Core Packages" "java.*" -group "CORBA Packages" "org.omg.*", then * the packages specified on the command line will be grouped according to their * names starting with either "java." or "org.omg.". All the other packages * which do not fall in the user given groups, are grouped in default group, * named as either "Other Packages" or "Packages" depending upon if "-group" * option used or not at all used respectively. * </p> * <p> * Also the packages are grouped according to the longest possible match of * their names with the grouping information provided. For example, if there * are two groups, like -group "Lang" "java.lang" and -group "Core" "java.*", * will put the package java.lang in the group "Lang" and not in group "Core". * </p> * * <p><b>This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice.</b> * * @author Atul M Dambalkar */ public class Group { /** * Map of regular expressions with the corresponding group name. */ private Map<String,String> regExpGroupMap = new HashMap<String,String>(); /** * List of regular expressions sorted according to the length. Regular * expression with longest length will be first in the sorted order. */ private List<String> sortedRegExpList = new ArrayList<String>(); /** * List of group names in the same order as given on the command line. */ private List<String> groupList = new ArrayList<String>(); /** * Map of non-regular expressions(possible package names) with the * corresponding group name. */ private Map<String,String> pkgNameGroupMap = new HashMap<String,String>(); /** * The global configuration information for this run. */ private final Configuration configuration; /** * Since we need to sort the keys in the reverse order(longest key first), * the compare method in the implementing class is doing the reverse * comparison. */ private static class MapKeyComparator implements Comparator<String> { public int compare(String key1, String key2) { return key2.length() - key1.length(); } } public Group(Configuration configuration) { this.configuration = configuration; } /** * Depending upon the format of the package name provided in the "-group" * option, generate two separate maps. There will be a map for mapping * regular expression(only meta character allowed is '*' and that is at the * end of the regular expression) on to the group name. And another map * for mapping (possible) package names(if the name format doesen't contain * meta character '*', then it is assumed to be a package name) on to the * group name. This will also sort all the regular expressions found in the * reverse order of their lengths, i.e. longest regular expression will be * first in the sorted list. * * @param groupname The name of the group from -group option. * @param pkgNameFormList List of the package name formats. */ public boolean checkPackageGroups(String groupname, String pkgNameFormList) { StringTokenizer strtok = new StringTokenizer(pkgNameFormList, ":"); if (groupList.contains(groupname)) { configuration.message.warning("doclet.Groupname_already_used", groupname); return false; } groupList.add(groupname); while (strtok.hasMoreTokens()) { String id = strtok.nextToken(); if (id.length() == 0) { configuration.message.warning("doclet.Error_in_packagelist", groupname, pkgNameFormList); return false; } if (id.endsWith("*")) { id = id.substring(0, id.length() - 1); if (foundGroupFormat(regExpGroupMap, id)) { return false; } regExpGroupMap.put(id, groupname); sortedRegExpList.add(id); } else { if (foundGroupFormat(pkgNameGroupMap, id)) { return false; } pkgNameGroupMap.put(id, groupname); } } Collections.sort(sortedRegExpList, new MapKeyComparator()); return true; } /** * Search if the given map has given the package format. * * @param map Map to be searched. * @param pkgFormat The pacakge format to search. * * @return true if package name format found in the map, else false. */ boolean foundGroupFormat(Map<String,?> map, String pkgFormat) { if (map.containsKey(pkgFormat)) { configuration.message.error("doclet.Same_package_name_used", pkgFormat); return true; } return false; } /** * Group the packages according the grouping information provided on the * command line. Given a list of packages, search each package name in * regular expression map as well as package name map to get the * corresponding group name. Create another map with mapping of group name * to the package list, which will fall under the specified group. If any * package doesen't belong to any specified group on the comamnd line, then * a new group named "Other Packages" will be created for it. If there are * no groups found, in other words if "-group" option is not at all used, * then all the packages will be grouped under group "Packages". * * @param packages Packages specified on the command line. */ public Map<String,List<PackageDoc>> groupPackages(PackageDoc[] packages) { Map<String,List<PackageDoc>> groupPackageMap = new HashMap<String,List<PackageDoc>>(); String defaultGroupName = (pkgNameGroupMap.isEmpty() && regExpGroupMap.isEmpty())? configuration.message.getText("doclet.Packages") : configuration.message.getText("doclet.Other_Packages"); // if the user has not used the default group name, add it if (!groupList.contains(defaultGroupName)) { groupList.add(defaultGroupName); } for (int i = 0; i < packages.length; i++) { PackageDoc pkg = packages[i]; String pkgName = pkg.name(); String groupName = pkgNameGroupMap.get(pkgName); // if this package is not explicitly assigned to a group, // try matching it to group specified by regular expression if (groupName == null) { groupName = regExpGroupName(pkgName); } // if it is in neither group map, put it in the default // group if (groupName == null) { groupName = defaultGroupName; } getPkgList(groupPackageMap, groupName).add(pkg); } return groupPackageMap; } /** * Search for package name in the sorted regular expression * list, if found return the group name. If not, return null. * * @param pkgName Name of package to be found in the regular * expression list. */ String regExpGroupName(String pkgName) { for (int j = 0; j < sortedRegExpList.size(); j++) { String regexp = sortedRegExpList.get(j); if (pkgName.startsWith(regexp)) { return regExpGroupMap.get(regexp); } } return null; } /** * For the given group name, return the package list, on which it is mapped. * Create a new list, if not found. * * @param map Map to be searched for gorup name. * @param groupname Group name to search. */ List<PackageDoc> getPkgList(Map<String,List<PackageDoc>> map, String groupname) { List<PackageDoc> list = map.get(groupname); if (list == null) { list = new ArrayList<PackageDoc>(); map.put(groupname, list); } return list; } /** * Return the list of groups, in the same order as specified * on the command line. */ public List<String> getGroupList() { return groupList; } }
arafalov/Javadoc-IFramed
src/main/java/com/outerthoughts/javadoc/iframed/internal/toolkit/util/Group.java
Java
gpl-2.0
9,901
/* * This Java file has been generated by smidump 0.4.5. Do not edit! * It is intended to be used within a Java AgentX sub-agent environment. * * $Id: TrapDestEntry.java 4432 2006-05-29 16:21:11Z strauss $ */ /** This class represents a Java AgentX (JAX) implementation of the table row trapDestEntry defined in RMON2-MIB. @version 1 @author smidump 0.4.5 @see AgentXTable, AgentXEntry */ import jax.AgentXOID; import jax.AgentXSetPhase; import jax.AgentXResponsePDU; import jax.AgentXEntry; public class TrapDestEntry extends AgentXEntry { protected int trapDestIndex = 0; protected byte[] trapDestCommunity = new byte[0]; protected byte[] undo_trapDestCommunity = new byte[0]; protected int trapDestProtocol = 0; protected int undo_trapDestProtocol = 0; protected byte[] trapDestAddress = new byte[0]; protected byte[] undo_trapDestAddress = new byte[0]; protected byte[] trapDestOwner = new byte[0]; protected byte[] undo_trapDestOwner = new byte[0]; protected int trapDestStatus = 0; protected int undo_trapDestStatus = 0; public TrapDestEntry(int trapDestIndex) { this.trapDestIndex = trapDestIndex; instance.append(trapDestIndex); } public int get_trapDestIndex() { return trapDestIndex; } public byte[] get_trapDestCommunity() { return trapDestCommunity; } public int set_trapDestCommunity(AgentXSetPhase phase, byte[] value) { switch (phase.getPhase()) { case AgentXSetPhase.TEST_SET: break; case AgentXSetPhase.COMMIT: undo_trapDestCommunity = trapDestCommunity; trapDestCommunity = new byte[value.length]; for(int i = 0; i < value.length; i++) trapDestCommunity[i] = value[i]; break; case AgentXSetPhase.UNDO: trapDestCommunity = undo_trapDestCommunity; break; case AgentXSetPhase.CLEANUP: undo_trapDestCommunity = null; break; default: return AgentXResponsePDU.PROCESSING_ERROR; } return AgentXResponsePDU.NO_ERROR; } public int get_trapDestProtocol() { return trapDestProtocol; } public int set_trapDestProtocol(AgentXSetPhase phase, int value) { switch (phase.getPhase()) { case AgentXSetPhase.TEST_SET: break; case AgentXSetPhase.COMMIT: undo_trapDestProtocol = trapDestProtocol; trapDestProtocol = value; break; case AgentXSetPhase.UNDO: trapDestProtocol = undo_trapDestProtocol; break; case AgentXSetPhase.CLEANUP: break; default: return AgentXResponsePDU.PROCESSING_ERROR; } return AgentXResponsePDU.NO_ERROR; } public byte[] get_trapDestAddress() { return trapDestAddress; } public int set_trapDestAddress(AgentXSetPhase phase, byte[] value) { switch (phase.getPhase()) { case AgentXSetPhase.TEST_SET: break; case AgentXSetPhase.COMMIT: undo_trapDestAddress = trapDestAddress; trapDestAddress = new byte[value.length]; for(int i = 0; i < value.length; i++) trapDestAddress[i] = value[i]; break; case AgentXSetPhase.UNDO: trapDestAddress = undo_trapDestAddress; break; case AgentXSetPhase.CLEANUP: undo_trapDestAddress = null; break; default: return AgentXResponsePDU.PROCESSING_ERROR; } return AgentXResponsePDU.NO_ERROR; } public byte[] get_trapDestOwner() { return trapDestOwner; } public int set_trapDestOwner(AgentXSetPhase phase, byte[] value) { switch (phase.getPhase()) { case AgentXSetPhase.TEST_SET: break; case AgentXSetPhase.COMMIT: undo_trapDestOwner = trapDestOwner; trapDestOwner = new byte[value.length]; for(int i = 0; i < value.length; i++) trapDestOwner[i] = value[i]; break; case AgentXSetPhase.UNDO: trapDestOwner = undo_trapDestOwner; break; case AgentXSetPhase.CLEANUP: undo_trapDestOwner = null; break; default: return AgentXResponsePDU.PROCESSING_ERROR; } return AgentXResponsePDU.NO_ERROR; } public int get_trapDestStatus() { return trapDestStatus; } public int set_trapDestStatus(AgentXSetPhase phase, int value) { switch (phase.getPhase()) { case AgentXSetPhase.TEST_SET: break; case AgentXSetPhase.COMMIT: undo_trapDestStatus = trapDestStatus; trapDestStatus = value; break; case AgentXSetPhase.UNDO: trapDestStatus = undo_trapDestStatus; break; case AgentXSetPhase.CLEANUP: break; default: return AgentXResponsePDU.PROCESSING_ERROR; } return AgentXResponsePDU.NO_ERROR; } }
vertexclique/travertine
libsmi/test/dumps/jax/TrapDestEntry.java
Java
gpl-2.0
5,239
package com.martinbrook.tesseractuhc.command; import org.bukkit.command.ConsoleCommandSender; import com.martinbrook.tesseractuhc.TesseractUHC; import com.martinbrook.tesseractuhc.UhcPlayer; import com.martinbrook.tesseractuhc.UhcSpectator; public class HealCommand extends UhcCommandExecutor { public HealCommand(TesseractUHC plugin) { super(plugin); } @Override protected String runAsAdmin(UhcSpectator sender, String[] args) { return run(args); } @Override protected String runAsConsole(ConsoleCommandSender sender, String[] args) { return run(args); } private String run(String[] args) { if (args.length == 0) { return (ERROR_COLOR + "Please specify player to heal, or * to heal all players"); } if (args[0].equals("*")) { for (UhcPlayer pl : match.getOnlinePlayers()) if (pl.heal()) pl.sendMessage(OK_COLOR + "You have been healed"); return (OK_COLOR + "Healed all players."); } UhcPlayer up = match.getPlayer(args[0]); if (up.isOnline()) { if (up.heal()) { up.sendMessage(OK_COLOR + "You have been healed"); return (OK_COLOR + "Healed " + up.getName()); } else { return (ERROR_COLOR + "Could not heal " + up.getName()); } } else { return (ERROR_COLOR + "Player " + args[0] + " is not online."); } } }
itsmartin/TesseractUHC
src/com/martinbrook/tesseractuhc/command/HealCommand.java
Java
gpl-2.0
1,296
package info.jbcs.minecraft.chisel; import cpw.mods.fml.client.event.ConfigChangedEvent; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.*; import cpw.mods.fml.common.event.FMLMissingMappingsEvent.MissingMapping; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.network.IGuiHandler; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.registry.EntityRegistry; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.GameRegistry.Type; import info.jbcs.minecraft.chisel.block.BlockCarvable; import info.jbcs.minecraft.chisel.client.gui.GuiChisel; import info.jbcs.minecraft.chisel.entity.EntityBallOMoss; import info.jbcs.minecraft.chisel.entity.EntityCloudInABottle; import info.jbcs.minecraft.chisel.inventory.ContainerChisel; import info.jbcs.minecraft.chisel.inventory.InventoryChiselSelection; import info.jbcs.minecraft.chisel.item.ItemBallOMoss; import info.jbcs.minecraft.chisel.item.ItemChisel; import info.jbcs.minecraft.chisel.item.ItemCloudInABottle; import info.jbcs.minecraft.chisel.world.GeneratorLimestone; import info.jbcs.minecraft.chisel.world.GeneratorMarble; import info.jbcs.minecraft.utilities.General; import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Configuration; import java.io.File; @Mod(modid = Chisel.MOD_ID, name = Chisel.MOD_NAME, version = "@MOD_VERSION@", guiFactory = "info.jbcs.minecraft.chisel.client.gui.GuiFactory"/*, dependencies = "after:ForgeMicroblock;"*/) public class Chisel { public static final String MOD_ID = "chisel"; public static final String MOD_NAME = "Chisel"; public static final String toolclass = "chisel"; public static ItemChisel chisel; // public static ItemChisel needle; public static ItemCloudInABottle itemCloudInABottle; public static ItemBallOMoss itemBallOMoss; public static CreativeTabs tabChisel; public static boolean multipartLoaded = false; public static final BlockCarvable.SoundType soundHolystoneFootstep = new BlockCarvable.SoundType("holystone", 1.0f, 1.0f); public static final BlockCarvable.SoundType soundTempleFootstep = new BlockCarvable.SoundType("dig.stone", MOD_ID+":step.templeblock", 1.0f, 1.0f); public static final BlockCarvable.SoundType soundMetalFootstep = new BlockCarvable.SoundType("metal", 1.0f, 1.0f); public static int RenderEldritchId; public static int RenderCTMId; public static int RenderCarpetId; @Instance(MOD_ID) public static Chisel instance; @SidedProxy(clientSide = "info.jbcs.minecraft.chisel.ClientProxy", serverSide = "info.jbcs.minecraft.chisel.CommonProxy") public static CommonProxy proxy; @EventHandler public void missingMapping(FMLMissingMappingsEvent event) { BlockNameConversion.init(); for(MissingMapping m : event.getAll()) { // as we catch ALL missing items, we only care about case-insensitive "chisel:" if (!m.name.toLowerCase().startsWith(MOD_ID)) continue; // This bug was introduced along with Chisel 1.5.2, and was fixed in 1.5.3. // Ice Stairs were called null.0-7 instead of other names, and Marble/Limestone stairs did not exist. // This fixes the bug. if(m.name.startsWith("null.") && m.name.length() == 6 && m.type == Type.BLOCK) { m.warn();//(Action.WARN); } // smashingrock was never finished, remove it silently from any 1.5.8+ game else if (m.name.equals("chisel:smashingrock")) { m.ignore(); } // Fix mapping of snakestoneSand, snakestoneStone, limestoneStairs, marbleStairs when loading an old (1.5.4) save else if(m.type == Type.BLOCK) { final Block block = BlockNameConversion.findBlock(m.name); if(block != null) { m.remap(block); FMLLog.getLogger().info("Remapping block " + m.name + " to " + General.getName(block)); } else FMLLog.getLogger().warn("Block " + m.name + " could not get remapped."); } else if(m.type == Type.ITEM) { final Item item = BlockNameConversion.findItem(m.name); if(item != null) { m.remap(item); FMLLog.getLogger().info("Remapping item " + m.name + " to " + General.getName(item)); } else FMLLog.getLogger().warn("Item " + m.name + " could not get remapped."); } } } @EventHandler public void preInit(FMLPreInitializationEvent event) { File configFile = event.getSuggestedConfigurationFile(); Configurations.configExists = configFile.exists(); Configurations.config = new Configuration(configFile); Configurations.config.load(); Configurations.refreshConfig(); tabChisel = new CreativeTabs("tabChisel") { @Override public Item getTabIconItem() { return chisel; } }; chisel = new ItemChisel(); GameRegistry.registerItem(chisel, "chisel"); if(Configurations.featureEnabled("cloud")) { itemCloudInABottle = (ItemCloudInABottle) new ItemCloudInABottle().setTextureName("Chisel:cloudinabottle").setCreativeTab(CreativeTabs.tabTools); EntityRegistry.registerModEntity(EntityCloudInABottle.class, "CloudInABottle", 1, this, 40, 1, true); GameRegistry.registerItem(itemCloudInABottle, "cloudinabottle"); } if(Configurations.featureEnabled("ballOfMoss")) { itemBallOMoss = (ItemBallOMoss) new ItemBallOMoss().setTextureName("Chisel:ballomoss").setCreativeTab(CreativeTabs.tabTools); EntityRegistry.registerModEntity(EntityBallOMoss.class, "BallOMoss", 2, this, 40, 1, true); GameRegistry.registerItem(itemBallOMoss, "ballomoss"); } ChiselBlocks.load(); proxy.preInit(); } @EventHandler public void init(FMLInitializationEvent event) { Crafting.init(); NetworkRegistry.INSTANCE.registerGuiHandler(this, new IGuiHandler() { @Override public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { return new ContainerChisel(player.inventory, new InventoryChiselSelection(null)); } @Override public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { return new GuiChisel(player.inventory, new InventoryChiselSelection(null)); } }); GameRegistry.registerWorldGenerator(new GeneratorMarble(ChiselBlocks.blockMarble, 32, Configurations.marbleAmount), 1000); GameRegistry.registerWorldGenerator(new GeneratorLimestone(ChiselBlocks.blockLimestone, 32, Configurations.limestoneAmount), 1000); proxy.init(); MinecraftForge.EVENT_BUS.register(this); FMLCommonHandler.instance().bus().register(instance); FMLInterModComms.sendMessage("Waila", "register", "info.jbcs.minecraft.chisel.Waila.register"); } @EventHandler public void postInit(FMLPostInitializationEvent event) { ChiselBlockCompatibility.loadModBlocks(); } @SubscribeEvent public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) { if(event.modID.equals("chisel")) { Configurations.refreshConfig(); } } }
EoD/Chisel
src/main/java/info/jbcs/minecraft/chisel/Chisel.java
Java
gpl-2.0
8,224
package com.refugiate.app.ui; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewTreeObserver; import android.view.Window; import android.view.animation.AccelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.Spinner; import android.widget.TextView; import com.refugiate.app.dao.clsConfiguracionSQL; import com.refugiate.app.dao.clsPersonaSQL; import com.refugiate.app.dao.clsReservaSQL; import com.refugiate.app.dao.clsSucursalSQL; import com.refugiate.app.entidades.clsConfiguracion; import com.refugiate.app.entidades.clsPersona; import com.refugiate.app.entidades.clsSucursal; import com.refugiate.app.fragment.cuenta.FragmentHistorial; import com.refugiate.app.fragment.cuenta.FragmentLogin; import com.refugiate.app.fragment.hoteles.FragmentListNombre; import com.refugiate.app.fragment.hoteles.FragmentMapa; import com.refugiate.app.fragment.cuenta.FragmentPerfil; import com.refugiate.app.fragment.cuenta.FragmentRegistro; import com.refugiate.app.fragment.cuenta.FragmentReservas; import com.refugiate.app.fragment.hoteles.FragmentReserva; import com.refugiate.app.fragment.hoteles.FragmentTab3; import com.refugiate.app.fragment.hoteles.FragmentTab4; import com.refugiate.app.utilidades.RecyclerView.Adapters.DrawerAdapter; import com.refugiate.app.utilidades.RecyclerView.Classes.DrawerItem; import com.refugiate.app.utilidades.RecyclerView.Utils.ItemClickSupport; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { FragmentManager fragmentManager; Toolbar toolbar; ActionBarDrawerToggle drawerToggle; DrawerLayout drawerLayout; View ViewSettingsIcon,ViewHelpIcon; TextView textViewName; FrameLayout frameLayoutSetting1; RelativeLayout relativeLayoutScrollViewChild; ScrollView scrollViewNavigationDrawerContent; ViewTreeObserver viewTreeObserverNavigationDrawerScrollView; ViewTreeObserver.OnScrollChangedListener onScrollChangedListener; RecyclerView recyclerViewDrawer1, recyclerViewDrawer2, recyclerViewDrawerSettings; RecyclerView.Adapter drawerAdapter1, drawerAdapter2, drawerAdapterSettings; ArrayList<DrawerItem> drawerItems1, drawerItems2, drawerItemsSettings; float drawerHeight, scrollViewHeight; LinearLayoutManager linearLayoutManager, linearLayoutManager2, linearLayoutManagerSettings; ItemClickSupport itemClickSupport1, itemClickSupport2, itemClickSupportSettings; TypedValue typedValueColorPrimary, typedValueTextColorPrimary, typedValueTextColorControlHighlight, typedValueColorBackground; int colorPrimary, textColorPrimary, colorControlHighlight, colorBackground; public Menu mOptionsMenu=null; public int mapa=0; public int registro=0; private clsPersona entidad; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); setupNavigationDrawer(); entidad= clsPersonaSQL.getSeleccionado(this); fragmentManager = this.getSupportFragmentManager(); getitemClickSupport1(0); } public void setupNavigationDrawer() { // Setup Navigation drawer drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout); // Setup Drawer Icon drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close); drawerLayout.setDrawerListener(drawerToggle); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); drawerToggle.syncState(); TypedValue typedValue = new TypedValue(); MainActivity.this.getTheme().resolveAttribute(R.attr.colorPrimaryDark, typedValue, true); final int color = typedValue.data; drawerLayout.setStatusBarBackgroundColor(color); textViewName = (TextView ) findViewById(R.id.textViewName); // textViewName.setText("sss"); ViewSettingsIcon = (View) findViewById(R.id.ViewSettingsIcon); ViewSettingsIcon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getItemClickSupportSettings(0); } }); ViewHelpIcon = (View) findViewById(R.id.ViewHelpIcon); ViewHelpIcon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getItemClickSupportSettings(1); } }); // Hide Settings and Feedback buttons when navigation drawer is scrolled hideNavigationDrawerSettingsAndFeedbackOnScroll(); // Setup RecyclerViews inside drawer setupNavigationDrawerRecyclerViews(); } private void hideNavigationDrawerSettingsAndFeedbackOnScroll() { scrollViewNavigationDrawerContent = (ScrollView) findViewById(R.id.scrollViewNavigationDrawerContent); relativeLayoutScrollViewChild = (RelativeLayout) findViewById(R.id.relativeLayoutScrollViewChild); frameLayoutSetting1 = (FrameLayout) findViewById(R.id.frameLayoutSettings1); viewTreeObserverNavigationDrawerScrollView = relativeLayoutScrollViewChild.getViewTreeObserver(); if (viewTreeObserverNavigationDrawerScrollView.isAlive()) { viewTreeObserverNavigationDrawerScrollView.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT > 16) { relativeLayoutScrollViewChild.getViewTreeObserver().removeOnGlobalLayoutListener(this); } else { relativeLayoutScrollViewChild.getViewTreeObserver().removeGlobalOnLayoutListener(this); } drawerHeight = relativeLayoutScrollViewChild.getHeight(); scrollViewHeight = scrollViewNavigationDrawerContent.getHeight(); if (drawerHeight > scrollViewHeight) { frameLayoutSetting1.setVisibility(View.VISIBLE); } if (drawerHeight < scrollViewHeight) { frameLayoutSetting1.setVisibility(View.GONE); } } }); } onScrollChangedListener = new ViewTreeObserver.OnScrollChangedListener() { @Override public void onScrollChanged() { scrollViewNavigationDrawerContent.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_MOVE: if (scrollViewNavigationDrawerContent.getScrollY() != 0) { frameLayoutSetting1.animate().translationY(frameLayoutSetting1 .getHeight()).setInterpolator(new AccelerateInterpolator(5f)).setDuration(400); } break; case MotionEvent.ACTION_UP: if (scrollViewNavigationDrawerContent.getScrollY() != 0) { frameLayoutSetting1.animate().translationY(frameLayoutSetting1 .getHeight()).setInterpolator(new AccelerateInterpolator(5f)).setDuration(400); } break; } return false; } }); if (scrollViewNavigationDrawerContent.getScrollY() == 0) { frameLayoutSetting1.animate().translationY(0) .setInterpolator(new DecelerateInterpolator(5f)).setDuration(600); } } }; scrollViewNavigationDrawerContent.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { ViewTreeObserver observer; switch (event.getAction()) { case MotionEvent.ACTION_MOVE: observer = scrollViewNavigationDrawerContent.getViewTreeObserver(); observer.addOnScrollChangedListener(onScrollChangedListener); break; case MotionEvent.ACTION_UP: observer = scrollViewNavigationDrawerContent.getViewTreeObserver(); observer.addOnScrollChangedListener(onScrollChangedListener); break; } return false; } }); } private void setupNavigationDrawerRecyclerViews() { // RecyclerView 1 recyclerViewDrawer1 = (RecyclerView) findViewById(R.id.recyclerViewDrawer1); linearLayoutManager = new LinearLayoutManager(MainActivity.this); recyclerViewDrawer1.setLayoutManager(linearLayoutManager); drawerItems1 = new ArrayList<>(); drawerItems1.add(new DrawerItem(getResources().getDrawable(R.drawable.ic_action_nombre),this.getString(R.string.lbl_item_dw_1_1))); drawerItems1.add(new DrawerItem(getResources().getDrawable(R.drawable.ic_action_ubigeo), this.getString(R.string.lbl_item_dw_1_2))); //drawerItems1.add(new DrawerItem(getResources().getDrawable(R.drawable.ic_action_mapa), this.getString(R.string.lbl_item_dw_1_3))); drawerAdapter1 = new DrawerAdapter(drawerItems1); recyclerViewDrawer1.setAdapter(drawerAdapter1); recyclerViewDrawer1.setMinimumHeight(convertDpToPx(96)); recyclerViewDrawer1.setHasFixedSize(true); // RecyclerView 2 recyclerViewDrawer2 = (RecyclerView) findViewById(R.id.recyclerViewDrawer2); linearLayoutManager2 = new LinearLayoutManager(MainActivity.this); recyclerViewDrawer2.setLayoutManager(linearLayoutManager2); drawerItems2 = new ArrayList<>(); drawerItems2.add(new DrawerItem(getResources().getDrawable(R.drawable.ic_action_perfil), this.getString(R.string.lbl_item_dw_2_1))); drawerItems2.add(new DrawerItem(getResources().getDrawable(R.drawable.ic_action_reservas), this.getString(R.string.lbl_item_dw_2_2))); drawerItems2.add(new DrawerItem(getResources().getDrawable(R.drawable.ic_action_historial), this.getString(R.string.lbl_item_dw_2_3))); drawerAdapter2 = new DrawerAdapter(drawerItems2); recyclerViewDrawer2.setAdapter(drawerAdapter2); recyclerViewDrawer2.setMinimumHeight(convertDpToPx(144)); recyclerViewDrawer2.setHasFixedSize(true); // RecyclerView Settings recyclerViewDrawerSettings = (RecyclerView) findViewById(R.id.recyclerViewDrawerSettings); linearLayoutManagerSettings = new LinearLayoutManager(MainActivity.this); recyclerViewDrawerSettings.setLayoutManager(linearLayoutManagerSettings); drawerItemsSettings = new ArrayList<>(); drawerItemsSettings.add(new DrawerItem(getResources().getDrawable(R.drawable.ic_action_action_settings),this.getString(R.string.action_settings))); drawerItemsSettings.add(new DrawerItem(getResources().getDrawable(R.drawable.ic_action_action_help),this.getString(R.string.action_about))); drawerAdapterSettings = new DrawerAdapter(drawerItemsSettings); recyclerViewDrawerSettings.setAdapter(drawerAdapterSettings); recyclerViewDrawerSettings.setMinimumHeight(convertDpToPx(96)); recyclerViewDrawerSettings.setHasFixedSize(true); // Why have I to calc recyclerView height? // Because recyclerView at this moment doesn't support wrap_content, this cause an height of 0 px // Get colorPrimary, textColorPrimary, colorControlHighlight and background to apply to selected items typedValueColorPrimary = new TypedValue(); getTheme().resolveAttribute(R.attr.colorPrimary, typedValueColorPrimary, true); colorPrimary = typedValueColorPrimary.data; typedValueTextColorPrimary = new TypedValue(); getTheme().resolveAttribute(android.R.attr.textColorPrimary, typedValueTextColorPrimary, true); textColorPrimary = typedValueTextColorPrimary.data; typedValueTextColorControlHighlight = new TypedValue(); getTheme().resolveAttribute(R.attr.colorControlHighlight, typedValueTextColorControlHighlight, true); colorControlHighlight = typedValueTextColorControlHighlight.data; typedValueColorBackground = new TypedValue(); getTheme().resolveAttribute(android.R.attr.colorBackground, typedValueColorBackground, true); colorBackground = typedValueColorBackground.data; // Set icons alpha at start final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { // Do something after some time for (int i = 0; i < recyclerViewDrawer1.getChildCount(); i++) { ImageView imageViewDrawerItemIcon = (ImageView) recyclerViewDrawer1.getChildAt(i).findViewById(R.id.imageViewDrawerItemIcon); TextView textViewDrawerItemTitle = (TextView) recyclerViewDrawer1.getChildAt(i).findViewById(R.id.textViewDrawerItemTitle); LinearLayout linearLayoutItem = (LinearLayout) recyclerViewDrawer1.getChildAt(i).findViewById(R.id.linearLayoutItem); if (i == 0) { imageViewDrawerItemIcon.setColorFilter(colorPrimary); if (Build.VERSION.SDK_INT > 15) { imageViewDrawerItemIcon.setImageAlpha(255); } else { imageViewDrawerItemIcon.setAlpha(255); } textViewDrawerItemTitle.setTextColor(colorPrimary); linearLayoutItem.setBackgroundColor(colorControlHighlight); } else { imageViewDrawerItemIcon.setColorFilter(textColorPrimary); if (Build.VERSION.SDK_INT > 15) { imageViewDrawerItemIcon.setImageAlpha(138); } else { imageViewDrawerItemIcon.setAlpha(138); } textViewDrawerItemTitle.setTextColor(textColorPrimary); linearLayoutItem.setBackgroundColor(colorBackground); } } for (int i = 0; i < recyclerViewDrawer2.getChildCount(); i++) { ImageView imageViewDrawerItemIcon = (ImageView) recyclerViewDrawer2.getChildAt(i).findViewById(R.id.imageViewDrawerItemIcon); TextView textViewDrawerItemTitle = (TextView) recyclerViewDrawer2.getChildAt(i).findViewById(R.id.textViewDrawerItemTitle); LinearLayout linearLayoutItem = (LinearLayout) recyclerViewDrawer2.getChildAt(i).findViewById(R.id.linearLayoutItem); imageViewDrawerItemIcon.setColorFilter(textColorPrimary); if (Build.VERSION.SDK_INT > 15) { imageViewDrawerItemIcon.setImageAlpha(138); } else { imageViewDrawerItemIcon.setAlpha(138); } textViewDrawerItemTitle.setTextColor(textColorPrimary); linearLayoutItem.setBackgroundColor(colorBackground); } for (int i = 0; i < recyclerViewDrawerSettings.getChildCount(); i++) { ImageView imageViewDrawerItemIcon = (ImageView) recyclerViewDrawerSettings.getChildAt(i).findViewById(R.id.imageViewDrawerItemIcon); TextView textViewDrawerItemTitle = (TextView) recyclerViewDrawerSettings.getChildAt(i).findViewById(R.id.textViewDrawerItemTitle); LinearLayout linearLayoutItem = (LinearLayout) recyclerViewDrawerSettings.getChildAt(i).findViewById(R.id.linearLayoutItem); imageViewDrawerItemIcon.setColorFilter(textColorPrimary); if (Build.VERSION.SDK_INT > 15) { imageViewDrawerItemIcon.setImageAlpha(138); } else { imageViewDrawerItemIcon.setAlpha(138); } textViewDrawerItemTitle.setTextColor(textColorPrimary); linearLayoutItem.setBackgroundColor(colorBackground); } ImageView imageViewSettingsIcon = (ImageView) findViewById(R.id.imageViewSettingsIcon); TextView textViewSettingsTitle = (TextView) findViewById(R.id.textViewSettingsTitle); imageViewSettingsIcon.setColorFilter(textColorPrimary); if (Build.VERSION.SDK_INT > 15) { imageViewSettingsIcon.setImageAlpha(138); } else { imageViewSettingsIcon.setAlpha(138); } textViewSettingsTitle.setTextColor(textColorPrimary); ImageView imageViewHelpIcon = (ImageView) findViewById(R.id.imageViewHelpIcon); TextView textViewHelpTitle = (TextView) findViewById(R.id.textViewHelpTitle); imageViewHelpIcon.setColorFilter(textColorPrimary); if (Build.VERSION.SDK_INT > 15) { imageViewHelpIcon.setImageAlpha(138); } else { imageViewHelpIcon.setAlpha(138); } textViewHelpTitle.setTextColor(textColorPrimary); } }, 250); itemClickSupport1 = ItemClickSupport.addTo(recyclerViewDrawer1); itemClickSupport1.setOnItemClickListener(new ItemClickSupport.OnItemClickListener() { @Override public void onItemClick(RecyclerView parent, View view, int position, long id) { for (int i = 0; i < recyclerViewDrawer1.getChildCount(); i++) { ImageView imageViewDrawerItemIcon = (ImageView) recyclerViewDrawer1.getChildAt(i).findViewById(R.id.imageViewDrawerItemIcon); TextView textViewDrawerItemTitle = (TextView) recyclerViewDrawer1.getChildAt(i).findViewById(R.id.textViewDrawerItemTitle); LinearLayout linearLayoutItem = (LinearLayout) recyclerViewDrawer1.getChildAt(i).findViewById(R.id.linearLayoutItem); if (i == position) { imageViewDrawerItemIcon.setColorFilter(colorPrimary); if (Build.VERSION.SDK_INT > 15) { imageViewDrawerItemIcon.setImageAlpha(255); } else { imageViewDrawerItemIcon.setAlpha(255); } textViewDrawerItemTitle.setTextColor(colorPrimary); linearLayoutItem.setBackgroundColor(colorControlHighlight); } else { imageViewDrawerItemIcon.setColorFilter(textColorPrimary); if (Build.VERSION.SDK_INT > 15) { imageViewDrawerItemIcon.setImageAlpha(138); } else { imageViewDrawerItemIcon.setAlpha(138); } textViewDrawerItemTitle.setTextColor(textColorPrimary); linearLayoutItem.setBackgroundColor(colorBackground); } } for (int i = 0; i < recyclerViewDrawer2.getChildCount(); i++) { ImageView imageViewDrawerItemIcon = (ImageView) recyclerViewDrawer2.getChildAt(i).findViewById(R.id.imageViewDrawerItemIcon); TextView textViewDrawerItemTitle = (TextView) recyclerViewDrawer2.getChildAt(i).findViewById(R.id.textViewDrawerItemTitle); LinearLayout linearLayoutItem = (LinearLayout) recyclerViewDrawer2.getChildAt(i).findViewById(R.id.linearLayoutItem); imageViewDrawerItemIcon.setColorFilter(textColorPrimary); if (Build.VERSION.SDK_INT > 15) { imageViewDrawerItemIcon.setImageAlpha(138); } else { imageViewDrawerItemIcon.setAlpha(138); } textViewDrawerItemTitle.setTextColor(textColorPrimary); linearLayoutItem.setBackgroundColor(colorBackground); } getitemClickSupport1(position); } }); itemClickSupport2 = ItemClickSupport.addTo(recyclerViewDrawer2); itemClickSupport2.setOnItemClickListener(new ItemClickSupport.OnItemClickListener() { @Override public void onItemClick(RecyclerView parent, View view, int position, long id) { for (int i = 0; i < recyclerViewDrawer2.getChildCount(); i++) { ImageView imageViewDrawerItemIcon = (ImageView) recyclerViewDrawer2.getChildAt(i).findViewById(R.id.imageViewDrawerItemIcon); TextView textViewDrawerItemTitle = (TextView) recyclerViewDrawer2.getChildAt(i).findViewById(R.id.textViewDrawerItemTitle); LinearLayout linearLayoutItem = (LinearLayout) recyclerViewDrawer2.getChildAt(i).findViewById(R.id.linearLayoutItem); if (i == position) { imageViewDrawerItemIcon.setColorFilter(colorPrimary); if (Build.VERSION.SDK_INT > 15) { imageViewDrawerItemIcon.setImageAlpha(255); } else { imageViewDrawerItemIcon.setAlpha(255); } textViewDrawerItemTitle.setTextColor(colorPrimary); linearLayoutItem.setBackgroundColor(colorControlHighlight); } else { imageViewDrawerItemIcon.setColorFilter(textColorPrimary); if (Build.VERSION.SDK_INT > 15) { imageViewDrawerItemIcon.setImageAlpha(138); } else { imageViewDrawerItemIcon.setAlpha(138); } textViewDrawerItemTitle.setTextColor(textColorPrimary); linearLayoutItem.setBackgroundColor(colorBackground); } } for (int i = 0; i < recyclerViewDrawer1.getChildCount(); i++) { ImageView imageViewDrawerItemIcon = (ImageView) recyclerViewDrawer1.getChildAt(i).findViewById(R.id.imageViewDrawerItemIcon); TextView textViewDrawerItemTitle = (TextView) recyclerViewDrawer1.getChildAt(i).findViewById(R.id.textViewDrawerItemTitle); LinearLayout linearLayoutItem = (LinearLayout) recyclerViewDrawer1.getChildAt(i).findViewById(R.id.linearLayoutItem); imageViewDrawerItemIcon.setColorFilter(textColorPrimary); if (Build.VERSION.SDK_INT > 15) { imageViewDrawerItemIcon.setImageAlpha(138); } else { imageViewDrawerItemIcon.setAlpha(138); } textViewDrawerItemTitle.setTextColor(textColorPrimary); linearLayoutItem.setBackgroundColor(colorBackground); } getitemClickSupport2(position); } }); itemClickSupportSettings = ItemClickSupport.addTo(recyclerViewDrawerSettings); itemClickSupportSettings.setOnItemClickListener(new ItemClickSupport.OnItemClickListener() { @Override public void onItemClick(RecyclerView parent, View view, int position, long id) { getItemClickSupportSettings(position); } }); } public int convertDpToPx(int dp) { // Get the screen's density scale final float scale = getResources().getDisplayMetrics().density; // Convert the dps to pixels, based on density scale return (int) (dp * scale + 0.5f); } public void setFragment(Fragment fragment) { fragmentManager.beginTransaction() .replace(R.id.content_frame, fragment) .commit(); drawerLayout.closeDrawers(); } public void getItemClickSupportSettings(int pos) { final Dialog dialog; drawerLayout.closeDrawers(); switch (pos) { case 0: dialog = new Dialog(this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.dialog_configuracion); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); final Spinner ComboTiempoActulizacion = (Spinner)dialog.findViewById(R.id.ComboTiempoActulizacion); final Spinner ComboTiempoPrevioReserva = (Spinner)dialog.findViewById(R.id.ComboTiempoPrevioReserva); final Spinner ComboTipoPropagandas = (Spinner)dialog.findViewById(R.id.ComboTipoPropagandas); final Spinner ComboRepetirTiempo = (Spinner)dialog.findViewById(R.id.ComboRepetirTiempo); final View ViewChbRepetir = (View)dialog.findViewById(R.id.ViewChbRepetir); final CheckBox chbRepetir = (CheckBox)dialog.findViewById(R.id.chbRepetir); final clsConfiguracion objConfiguracion= clsConfiguracionSQL.Buscar(this); String[] itensActulizacion=getResources().getStringArray(R.array.array_configuracion_tiempo_actulizacion); ArrayAdapter<String> adapterActulizacion = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,itensActulizacion); adapterActulizacion.setDropDownViewResource(android.R.layout.simple_list_item_checked); ComboTiempoActulizacion.setAdapter(adapterActulizacion); ComboTiempoActulizacion.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // tipoHabitacion=itens.get(position); if (position == 0) objConfiguracion.setTiempo_actulizacion(1); else if (position == 1) objConfiguracion.setTiempo_actulizacion(3); else if (position == 2) objConfiguracion.setTiempo_actulizacion(6); else if (position == 3) objConfiguracion.setTiempo_actulizacion(12); else if (position == 4) objConfiguracion.setTiempo_actulizacion(24); } public void onNothingSelected(AdapterView<?> parent) { //User selected same item. Nothing to do. } }); if(objConfiguracion.getTiempo_actulizacion()==1) ComboTiempoActulizacion.setSelection(0); else if(objConfiguracion.getTiempo_actulizacion()==3) ComboTiempoActulizacion.setSelection(1); else if(objConfiguracion.getTiempo_actulizacion()==6) ComboTiempoActulizacion.setSelection(2); else if(objConfiguracion.getTiempo_actulizacion()==12) ComboTiempoActulizacion.setSelection(3); else if(objConfiguracion.getTiempo_actulizacion()==24) ComboTiempoActulizacion.setSelection(4); String[] itensTiempoPrevioReserva=getResources().getStringArray(R.array.array_configuracion_tiempo_reserva); ArrayAdapter<String> adapterTiempoPrevioReserva = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,itensTiempoPrevioReserva); adapterTiempoPrevioReserva.setDropDownViewResource(android.R.layout.simple_list_item_checked); ComboTiempoPrevioReserva.setAdapter(adapterTiempoPrevioReserva); ComboTiempoPrevioReserva.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { objConfiguracion.setTiempo_previo_reserva(position + 1); } public void onNothingSelected(AdapterView<?> parent) { //User selected same item. Nothing to do. } }); ComboTiempoPrevioReserva.setSelection(objConfiguracion.getTiempo_previo_reserva() - 1); String[] itensTipoPropagandas=getResources().getStringArray(R.array.array_configuracion_tipo_propaganda); ArrayAdapter<String> adapterTipoPropagandas = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,itensTipoPropagandas); adapterTipoPropagandas.setDropDownViewResource(android.R.layout.simple_list_item_checked); ComboTipoPropagandas.setAdapter(adapterTipoPropagandas); ComboTipoPropagandas.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { objConfiguracion.setTipo_propagandas(position + 1); } public void onNothingSelected(AdapterView<?> parent) { //User selected same item. Nothing to do. } }); ComboTipoPropagandas.setSelection(objConfiguracion.getTipo_propagandas()-1); String[] itensRepetirTiempo=getResources().getStringArray(R.array.array_configuracion_tiempo_repetir); ArrayAdapter<String> adapterRepetirTiempo = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,itensRepetirTiempo); adapterRepetirTiempo.setDropDownViewResource(android.R.layout.simple_list_item_checked); ComboRepetirTiempo.setAdapter(adapterRepetirTiempo); ComboRepetirTiempo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { objConfiguracion.setRepetir_tiempo(position + 1); } public void onNothingSelected(AdapterView<?> parent) { //User selected same item. Nothing to do. } }); ComboRepetirTiempo.setSelection(objConfiguracion.getRepetir_tiempo() - 1); chbRepetir.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (chbRepetir.isChecked()) { ComboRepetirTiempo.setEnabled(true); ViewChbRepetir.setVisibility(View.VISIBLE); objConfiguracion.setRepetir(1); } else { ComboRepetirTiempo.setEnabled(false); ViewChbRepetir.setVisibility(View.GONE); objConfiguracion.setRepetir(2); } } }); if( objConfiguracion.getRepetir()==1) { ComboRepetirTiempo.setEnabled(true); ViewChbRepetir.setVisibility(View.VISIBLE); chbRepetir.setChecked(true); } else if( objConfiguracion.getRepetir()==2) { chbRepetir.setChecked(false); ComboRepetirTiempo.setEnabled(false); ViewChbRepetir.setVisibility(View.GONE); } Button btnAceptar = (Button) dialog.findViewById(R.id.btnAceptar); btnAceptar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); clsConfiguracionSQL.Agregar(MainActivity.this, objConfiguracion); } }); dialog.show(); break; case 1: break; default: break; } } public void getitemClickSupport1(int position) { if(mOptionsMenu!=null) mOptionsMenu.getItem(0).setVisible(false); switch (position) { case 0: mapa=1; setFragment(new FragmentListNombre()); //setFragment(new FragmentTab1()); break; case 1: mapa=0; setFragment(new FragmentMapa()); break; case 2: setFragment(new FragmentReserva()); break; default: break; } } public void getitemClickSupport2(int position) { if(mOptionsMenu!=null) mOptionsMenu.getItem(0).setVisible(false); entidad= clsPersonaSQL.getSeleccionado(this); switch (position) { case 0: if(entidad==null) { registro=0; FragmentLogin fragment = new FragmentLogin(); Bundle bundle = new Bundle(); bundle.putInt("fragment", 0); // use as per your need fragment.setArguments(bundle); setFragment(fragment); } else setFragment(new FragmentPerfil()); break; case 1: if(entidad==null) { registro=1; FragmentLogin fragment = new FragmentLogin(); Bundle bundle = new Bundle(); bundle.putInt("fragment",1); // use as per your need fragment.setArguments(bundle); setFragment(fragment); } else setFragment(new FragmentReservas()); break; case 2: if(entidad==null) { registro=2; FragmentLogin fragment = new FragmentLogin(); Bundle bundle = new Bundle(); bundle.putInt("fragment",2); // use as per your need fragment.setArguments(bundle); setFragment(fragment); } else setFragment(new FragmentHistorial()); break; default: break; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { AlertDialog.Builder alert; Fragment currentFrag = getSupportFragmentManager().findFragmentById(R.id.content_frame); if (currentFrag!=null) { switch (currentFrag.getClass().getSimpleName()) { case "FragmentMapa": case "FragmentListNombre": this.finish(); break; case "FragmentTab1": case "FragmentTab2": case "FragmentTab3": case "FragmentTab4": if(mapa==0) setFragment(new FragmentMapa()); else if(mapa==1) setFragment(new FragmentListNombre()); else if(mapa==2) setFragment(new FragmentReservas()); else if(mapa==3) setFragment(new FragmentHistorial()); mOptionsMenu.getItem(0).setVisible(false); break; case "FragmentLogin": if(registro==3) setFragment(new FragmentTab3()); else getitemClickSupport2(registro); break; case "FragmentReserva": alert = new AlertDialog.Builder(this); alert.setTitle(getString(R.string.alert_retroceder)); alert.setPositiveButton(getString(R.string.str_btnAceptar), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { setFragment(new FragmentTab3()); } }); alert.setNegativeButton(getString(R.string.str_btnCancelar), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); alert.show(); break; case "FragmentRegistro": alert = new AlertDialog.Builder(this); alert.setTitle(getString(R.string.alert_retroceder)); alert.setPositiveButton(getString(R.string.str_btnAceptar), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { FragmentLogin fragment = new FragmentLogin(); Bundle bundle = new Bundle(); bundle.putInt("fragment", registro); // use as per your need fragment.setArguments(bundle); setFragment(fragment); } }); alert.setNegativeButton(getString(R.string.str_btnCancelar), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); alert.show(); break; default: break; } } // this.finish(); return false; } return super.onKeyDown(keyCode, event); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); mOptionsMenu=menu; return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.telefono: clsSucursal objSucural= clsSucursalSQL.getSeleccionado(this); if(objSucural!=null) if(!objSucural.getTelefono().equals("") && !objSucural.getTelefono().equals(null)) { Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:" + objSucural.getTelefono())); startActivity(intent); } return true; case R.id.compartir: Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); sharingIntent.setType("text/plain"); sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, getString(R.string.compartir_sms)); startActivity(Intent.createChooser(sharingIntent,getString(R.string.compartir_via))); return true; case R.id.sesion: AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle(getString(R.string.alert_sesion)); alert.setPositiveButton(getString(R.string.str_btnAceptar), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { clsPersonaSQL.Borrar(MainActivity.this); clsReservaSQL.Borrar(MainActivity.this); mOptionsMenu.getItem(1).setVisible(false); getitemClickSupport1(0); } }); alert.setNegativeButton(getString(R.string.str_btnCancelar), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); alert.show(); return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { // TODO Auto-generated method stub menu.getItem(0).setVisible(false); if(entidad==null) menu.getItem(1).setVisible(false); return super.onPrepareOptionsMenu(menu); } }
marvindelarc/Refugiate
Proyecto Tesis/RefugiateApp/app/src/main/java/com/refugiate/app/ui/MainActivity.java
Java
gpl-2.0
42,960
package org.pilirion.nakaza.exception; /** * */ public class TooManyPlayersInGroup extends Exception { public TooManyPlayersInGroup(String message) { super(message); } }
balhar-jakub/nakaza
src/main/java/org/pilirion/nakaza/exception/TooManyPlayersInGroup.java
Java
gpl-2.0
199
//=== File Prolog=========================================================== // This code was developed as part of the open source regatta scoring // program, JavaScore. // // Version: $Id: ListenerList.java,v 1.4 2006/01/15 21:10:35 sandyg Exp $ // // Copyright Sandy Grosvenor, 2000-2015 // Email [email protected], www.gromurph.org/javascore // // OSI Certified Open Source Software (www.opensource.org) // This software is licensed under the GNU General Public License, // available at www.opensource.org/licenses/gpl-license.html //=== End File Prolog======================================================= package org.gromurph.util; /** * Modifies Vector to better support use in event listeners code * The problem with java.util.Vector in event listeners * is (a) in adding a listener, we do not want to add it if it already is in * the list, (b) in removing a listener, we want to remove all occurrences, and (most * critically) the selection should be based on a '==' comparison not the less * strict .equals(). * * By using a ListenerVector, the listener support code can stay simple (and * converting from java.util.Vector is as as easy as changing the declared class * and constructor names... and changing addElement to addListener, and removeElement to * removeListener (sorry bout that... addElement and removeElement are 'final' in Vector) */ public class ListenerList extends java.util.ArrayList<Object> { /** * adds an object to the list of listeners. This varies from * Vector.addElement() in that it (a) will not add the object * if it already is in the list (via an '==' comparison not * a .equals()) * * @param obj the object to be added to the vector */ public synchronized void addListener(Object obj) { for (int i = 0; i < size(); i++) { if (get(i) == obj) return; } // if we get here then it does not exist add( obj); } /** * removes an object from listener vector. This differs from * java.util.Vector.removeElement() in two ways: * (a) removes all occurences, (b) identifies the existence * via '==' not .equals() * * @param obj the object to be removed from the vector */ public synchronized void removeListener(Object obj) { for (int i = size()-1; i >= 0; i--) { if (get(i) == obj) remove(i); } } public synchronized Object[] getListenerList() { return toArray(); } } /** * $Log: ListenerList.java,v $ * Revision 1.4 2006/01/15 21:10:35 sandyg * resubmit at 5.1.02 * * Revision 1.2 2006/01/11 02:27:14 sandyg * updating copyright years * * Revision 1.1 2006/01/01 02:27:02 sandyg * preliminary submission to centralize code in a new module * * Revision 1.4.4.1 2005/11/01 02:36:02 sandyg * Java5 update - using generics * * Revision 1.4 2004/04/10 20:49:39 sandyg * Copyright year update * * Revision 1.3 2003/04/27 21:03:30 sandyg * lots of cleanup, unit testing for 4.1.1 almost complete * * Revision 1.2 2003/01/04 17:53:05 sandyg * Prefix/suffix overhaul * */
sgrosven/gromurph
Javascore/src/main/java/org/gromurph/util/ListenerList.java
Java
gpl-2.0
3,114
package net.kolls.railworld.opening; import java.awt.BorderLayout; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import net.kolls.railworld.RailSegment; import net.kolls.railworld.io.MetaData; import net.kolls.railworld.io.RWMMapFilter; import net.kolls.railworld.io.RWMReader; import net.kolls.railworld.io.YardMapFilter; import net.kolls.railworld.io.YardReader; import net.kolls.railworld.play.script.ScriptManager; import org.xml.sax.SAXException; /* * Copyright (C) 2010 Steve Kollmansberger * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /** * A class that loads maps and their images, along with other supporting data. * Includes functionality to prompt user to select a local file. * Instances of this class are created using factory methods which specify * how to get the map. * * The image won't be loaded right away. It will wait for the first call to * {@link #getImage()}. This allows uses of the map without the delay * of loading the image if it is not needed. * * @author Steve Kollmansberger */ public abstract class MapLoader { private RailSegment[] lines; private MetaData md; private String filename; /** * * @return Return the segments associated with the loaded map. */ public RailSegment[] getSegments() { return lines; } /** * * @return Return the metadata associated with the loaded map. */ public MetaData getMetaData() { return md; } /** * Loads another instance of this map from its original source (file or URL). * Returns the new MapLoader containing the fresh instance. * * @return A new MapLoader containing the freshly loaded data. * @throws IOException * @throws SAXException */ public abstract MapLoader loadAgain() throws IOException, SAXException; /** * Loads the map image on the first call; caches it for subsequent calls. * * @return The map image * @throws IOException If the map image cannot be loaded. */ public abstract BufferedImage getImage() throws IOException; /** * Protected constructor. To create an instance, need to use static * factory methods depending on how to acquire the data. * * Values given will be loaded; script manager will be null. * * @param la RailSegments * @param mmd MetaData * @param file the filename (not path) of the map file * */ protected MapLoader(RailSegment[] la, MetaData mmd, String file) { lines = la; md = mmd; filename = file; } /** * Popup a file chooser dialog to allow the user to select a map file * locally. * * @param scripts If provided, indicates that a {@link ScriptPanel} should * be shown allowing the user to choose scripts. The given script manager * (assumed to be empty when passed in; but will be cleared if not) * will then be loaded with the selected scripts. * @param directory Specifies the directory to start in. May be null. * @return A new MapLoader with the user selected map if one was selected, * null otherwise. * @throws IOException If the map selected by the user cannot be loaded. * @throws SAXException If the map selected by the user cannot be parsed. */ public static MapLoader loadFromUserPrompt(ScriptManager scripts, File directory) throws IOException, SAXException { final JFileChooser jfc = new JFileChooser(); jfc.addChoosableFileFilter(new YardMapFilter()); jfc.addChoosableFileFilter(new RWMMapFilter()); if (directory != null) jfc.setCurrentDirectory(directory); final ScriptPanel sp = new ScriptPanel(); final JPanel jsp = new JPanel(); jsp.setLayout(new BorderLayout()); jsp.add(new JLabel("Select Script(s) to Use"), BorderLayout.NORTH); jsp.add(sp, BorderLayout.CENTER); if (scripts != null) { /* jfc.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { String prop = e.getPropertyName(); if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) { File f = (File)e.getNewValue(); sp.setDirectory(f); } } }); */ jfc.setAccessory(jsp); } int rv = jfc.showOpenDialog(null); if (rv == JFileChooser.APPROVE_OPTION) { if (scripts != null) { scripts.clear(); for (int i = 0; i < sp.getScripts().length; i++) { scripts.add( sp.getScripts()[i] ); } } File file = jfc.getSelectedFile(); return loadFromFile(file); } return null; } /** * Loads the map from the given file. The map image must be in the same directory. * * @param file The file containing a compatible map to load, either in Rail World * or Yard Duty format. * @return The map loader containing the file data. * @throws IOException If the map cannot be loaded. * @throws SAXException If the map cannot be parsed. */ public static MapLoader loadFromFile(final File file) throws IOException, SAXException { String u = file.getName().toUpperCase(); RailSegment[] la = null; MetaData md = new MetaData(); if (u.endsWith(".RWM")) { // It's in the native XML format la = RWMReader.read(file, md); } if (u.endsWith(".YRD")) { // Yard duty format la = YardReader.read(file, md); } if (la == null) throw new IOException("Unknown file format"); final File imgfile = new File (file.getParentFile() + File.separator + md.imgfile); return new MapLoader(la, md, u) { private BufferedImage bi; @Override public BufferedImage getImage() throws IOException { if (bi != null) return bi; bi = ImageIO.read(imgfile); return bi; } @Override public MapLoader loadAgain() throws IOException, SAXException { return loadFromFile(file); } }; } /** * Loads the map from the given URL. The map image must be in the same directory. * * @param url The URL pointing to a compatible map to load, in Rail World * format. Yard Duty files cannot be loaded over URLs. * @return The map loader containing the file data. * @throws IOException If the map cannot be loaded. * @throws SAXException If the map cannot be parsed. */ public static MapLoader loadFromURL(final URL url) throws IOException, SAXException { String u = url.getPath().toUpperCase(); RailSegment[] la = null; MetaData md = new MetaData(); if (u.endsWith(".RWM")) { // It's in the native XML format la = RWMReader.read(url, md); } if (u.endsWith(".YRD")) { // Yard duty format // la = YardReader.read(url, md); throw new IOException("Yard duty files cannot be loaded via URLs"); } if (la == null) throw new IOException("Unknown file format"); final URL imgurl = new URL (url, md.imgfile); return new MapLoader(la, md, url.getPath().substring(url.getPath().lastIndexOf("/") + 1)) { private BufferedImage bi; @Override public BufferedImage getImage() throws IOException { if (bi != null) return bi; bi = ImageIO.read(imgurl); return bi; } @Override public MapLoader loadAgain() throws IOException, SAXException { return loadFromURL(url); } }; } /** * Find the filename (without path) of the map file. * * @return The filename, possibly in different capitalization than the actual file. */ public String getFilename() { System.out.println(filename); return filename; } @Override public String toString() { if (md == null) return ""; return md.title; } }
Neschur/railworld
src/net/kolls/railworld/opening/MapLoader.java
Java
gpl-2.0
8,220
package info.culebrasgis.calculadoradefechas; /** * By Culebras, Culebras GIS (www.culebrasgis.info) (https://github.com/culebras) * * Calculadora De Fechas is free software and is licensed under the GPL v2: * GNU GENERAL PUBLIC LICENSE Version 2, June 1991 * See LICENSE.md for more details. */ import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import org.joda.time.DateTime; import org.joda.time.Period; import org.joda.time.PeriodType; public class DiasDesdeActivity extends FragmentActivity { // variables private Button fechaUsuario; private TextView resultado; private Button reiniciar; private Button calcular; private Button volver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dias_desde); fechaUsuario = (Button) findViewById(R.id.buttonFechaUsuario); fechaUsuario.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DialogFragment newFragment = new DatePickerFragment(); newFragment.show(getSupportFragmentManager(), "datePicker"); } }); resultado = (TextView) findViewById(R.id.textViewResultado); volver = (Button) findViewById(R.id.buttonVolver); volver.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); reiniciar = (Button) findViewById(R.id.buttonReiniciar); reiniciar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { resultado.setText(R.string.resultado); fechaUsuario.setText(R.string.fecha); } }); calcular = (Button) findViewById(R.id.buttonCalcular); calcular.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { int dia, mes, anno; dia = Integer.parseInt(String.valueOf(fechaUsuario.getText()).substring(0,2)); mes = Integer.parseInt(String.valueOf(fechaUsuario.getText()).substring(3, 5)); anno = Integer.parseInt(String.valueOf(fechaUsuario.getText()).substring(6,10)); DateTime hoy = new DateTime(); DateTime fecha = new DateTime(anno, mes, dia, 0, 0); if (fecha.isAfter(hoy)) { // si el usuario mete una fecha posterior al día actual resultado.setText(R.string.fecha_anterior); } else { Period periodo = new Period(fecha, hoy, PeriodType.days()); resultado.setText(String.format(getString(R.string.resultado_dias_desde), periodo.getDays())); } } catch (Exception e) { resultado.setText(R.string.fecha_incorrecta); } } }); } }
culebras/CalculadoraDeFechas
CalculadoraDeFechas/src/main/java/info/culebrasgis/calculadoradefechas/DiasDesdeActivity.java
Java
gpl-2.0
3,355
package com.xuwakao.mixture.ui; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.xuwakao.mixture.R; /** * Created by xujiexing on 13-10-8. */ public class ArtistFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_planet, container, false); ((ImageView)rootView).setImageResource(R.drawable.earth); return rootView; } }
xuwakao/mixtureProject
mixture/src/main/java/com/xuwakao/mixture/ui/ArtistFragment.java
Java
gpl-2.0
651
package com.hm.tools.scan2clipboard; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
hm279/scan2clipboard
app/src/androidTest/java/com/hm/tools/scan2clipboard/ApplicationTest.java
Java
gpl-2.0
358
// Portions copyright 2002, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package libaries.util; // This code was converted from code at http://iharder.sourceforge.net/base64/ // Lots of extraneous features were removed. /* The original code said: * <p> * I am placing this code in the Public Domain. Do with it as you will. * This software comes with no guarantees or warranties but with * plenty of well-wishing instead! * Please visit * <a href="http://iharder.net/xmlizable">http://iharder.net/xmlizable</a> * periodically to check for updates or to contribute improvements. * </p> * * @author Robert Harder * @author [email protected] * @version 1.3 */ /** * Base64 converter class. This code is not a complete MIME encoder; * it simply converts binary data to base64 data and back. * * <p>Note {@link CharBase64} is a GWT-compatible implementation of this * class. */ public class Base64 { /** Specify encoding (value is {@code true}). */ public final static boolean ENCODE = true; /** Specify decoding (value is {@code false}). */ public final static boolean DECODE = false; /** The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN = (byte) '='; /** The new line character (\n) as a byte. */ private final static byte NEW_LINE = (byte) '\n'; /** * The 64 valid Base64 values. */ private final static byte[] ALPHABET = {(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/'}; /** * The 64 valid web safe Base64 values. */ private final static byte[] WEBSAFE_ALPHABET = {(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '-', (byte) '_'}; /** * Translates a Base64 value to either its 6-bit reconstruction value * or a negative number indicating some other meaning. **/ private final static byte[] DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9, -9, -9, // Decimal 44 - 46 63, // Slash at decimal 47 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9, -9, -9, // Decimal 62 - 64 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' -9, -9, -9, -9, -9 // Decimal 123 - 127 /* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }; /** The web safe decodabet */ private final static byte[] WEBSAFE_DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 44 62, // Dash '-' sign at decimal 45 -9, -9, // Decimal 46-47 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9, -9, -9, // Decimal 62 - 64 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' -9, -9, -9, -9, // Decimal 91-94 63, // Underscore '_' at decimal 95 -9, // Decimal 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' -9, -9, -9, -9, -9 // Decimal 123 - 127 /* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }; // Indicates white space in encoding private final static byte WHITE_SPACE_ENC = -5; // Indicates equals sign in encoding private final static byte EQUALS_SIGN_ENC = -1; /** Defeats instantiation. */ private Base64() { } /* ******** E N C O D I N G M E T H O D S ******** */ /** * Encodes up to three bytes of the array <var>source</var> * and writes the resulting four Base64 bytes to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accommodate <var>srcOffset</var> + 3 for * the <var>source</var> array or <var>destOffset</var> + 4 for * the <var>destination</var> array. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @param alphabet is the encoding alphabet * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4(byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset, byte[] alphabet) { // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index alphabet // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); switch (numSigBytes) { case 3: destination[destOffset] = alphabet[(inBuff >>> 18)]; destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = alphabet[(inBuff) & 0x3f]; return destination; case 2: destination[destOffset] = alphabet[(inBuff >>> 18)]; destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = EQUALS_SIGN; return destination; case 1: destination[destOffset] = alphabet[(inBuff >>> 18)]; destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = EQUALS_SIGN; destination[destOffset + 3] = EQUALS_SIGN; return destination; default: return destination; } // end switch } // end encode3to4 /** * Encodes a byte array into Base64 notation. * Equivalent to calling * {@code encodeBytes(source, 0, source.length)} * * @param source The data to convert * @since 1.4 */ public static String encode(byte[] source) { return encode(source, 0, source.length, ALPHABET, true); } /** * Encodes a byte array into web safe Base64 notation. * * @param source The data to convert * @param doPadding is {@code true} to pad result with '=' chars * if it does not fall on 3 byte boundaries */ public static String encodeWebSafe(byte[] source, boolean doPadding) { return encode(source, 0, source.length, WEBSAFE_ALPHABET, doPadding); } /** * Encodes a byte array into Base64 notation. * * @param source the data to convert * @param off offset in array where conversion should begin * @param len length of data to convert * @param alphabet the encoding alphabet * @param doPadding is {@code true} to pad result with '=' chars * if it does not fall on 3 byte boundaries * @since 1.4 */ public static String encode(byte[] source, int off, int len, byte[] alphabet, boolean doPadding) { byte[] outBuff = encode(source, off, len, alphabet, Integer.MAX_VALUE); int outLen = outBuff.length; // If doPadding is false, set length to truncate '=' // padding characters while (doPadding == false && outLen > 0) { if (outBuff[outLen - 1] != '=') { break; } outLen -= 1; } return new String(outBuff, 0, outLen); } /** * Encodes a byte array into Base64 notation. * * @param source the data to convert * @param off offset in array where conversion should begin * @param len length of data to convert * @param alphabet is the encoding alphabet * @param maxLineLength maximum length of one line. * @return the BASE64-encoded byte array */ public static byte[] encode(byte[] source, int off, int len, byte[] alphabet, int maxLineLength) { int lenDiv3 = (len + 2) / 3; // ceil(len / 3) int len43 = lenDiv3 * 4; byte[] outBuff = new byte[len43 // Main 4:3 + (len43 / maxLineLength)]; // New lines int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for (; d < len2; d += 3, e += 4) { // The following block of code is the same as // encode3to4( source, d + off, 3, outBuff, e, alphabet ); // but inlined for faster encoding (~20% improvement) int inBuff = ((source[d + off] << 24) >>> 8) | ((source[d + 1 + off] << 24) >>> 16) | ((source[d + 2 + off] << 24) >>> 24); outBuff[e] = alphabet[(inBuff >>> 18)]; outBuff[e + 1] = alphabet[(inBuff >>> 12) & 0x3f]; outBuff[e + 2] = alphabet[(inBuff >>> 6) & 0x3f]; outBuff[e + 3] = alphabet[(inBuff) & 0x3f]; lineLength += 4; if (lineLength == maxLineLength) { outBuff[e + 4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // end for: each piece of array if (d < len) { encode3to4(source, d + off, len - d, outBuff, e, alphabet); lineLength += 4; if (lineLength == maxLineLength) { // Add a last newline outBuff[e + 4] = NEW_LINE; e++; } e += 4; } assert (e == outBuff.length); return outBuff; } /* ******** D E C O D I N G M E T H O D S ******** */ /** * Decodes four bytes from array <var>source</var> * and writes the resulting bytes (up to three of them) * to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accommodate <var>srcOffset</var> + 4 for * the <var>source</var> array or <var>destOffset</var> + 3 for * the <var>destination</var> array. * This method returns the actual number of bytes that * were converted from the Base64 encoding. * * * @param source the array to convert * @param srcOffset the index where conversion begins * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @param decodabet the decodabet for decoding Base64 content * @return the number of decoded bytes converted * @since 1.3 */ private static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset, byte[] decodabet) { // Example: Dk== if (source[srcOffset + 2] == EQUALS_SIGN) { int outBuff = ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12); destination[destOffset] = (byte) (outBuff >>> 16); return 1; } else if (source[srcOffset + 3] == EQUALS_SIGN) { // Example: DkL= int outBuff = ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12) | ((decodabet[source[srcOffset + 2]] << 24) >>> 18); destination[destOffset] = (byte) (outBuff >>> 16); destination[destOffset + 1] = (byte) (outBuff >>> 8); return 2; } else { // Example: DkLE int outBuff = ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12) | ((decodabet[source[srcOffset + 2]] << 24) >>> 18) | ((decodabet[source[srcOffset + 3]] << 24) >>> 24); destination[destOffset] = (byte) (outBuff >> 16); destination[destOffset + 1] = (byte) (outBuff >> 8); destination[destOffset + 2] = (byte) (outBuff); return 3; } } // end decodeToBytes /** * Decodes data from Base64 notation. * * @param s the string to decode (decoded in default encoding) * @return the decoded data * @since 1.4 */ public static byte[] decode(String s) throws Base64DecoderException { byte[] bytes = s.getBytes(); return decode(bytes, 0, bytes.length); } /** * Decodes data from web safe Base64 notation. * Web safe encoding uses '-' instead of '+', '_' instead of '/' * * @param s the string to decode (decoded in default encoding) * @return the decoded data */ public static byte[] decodeWebSafe(String s) throws Base64DecoderException { byte[] bytes = s.getBytes(); return decodeWebSafe(bytes, 0, bytes.length); } /** * Decodes Base64 content in byte array format and returns * the decoded byte array. * * @param source The Base64 encoded data * @return decoded data * @since 1.3 * @throws Base64DecoderException */ public static byte[] decode(byte[] source) throws Base64DecoderException { return decode(source, 0, source.length); } /** * Decodes web safe Base64 content in byte array format and returns * the decoded data. * Web safe encoding uses '-' instead of '+', '_' instead of '/' * * @param source the string to decode (decoded in default encoding) * @return the decoded data */ public static byte[] decodeWebSafe(byte[] source) throws Base64DecoderException { return decodeWebSafe(source, 0, source.length); } /** * Decodes Base64 content in byte array format and returns * the decoded byte array. * * @param source the Base64 encoded data * @param off the offset of where to begin decoding * @param len the length of characters to decode * @return decoded data * @since 1.3 * @throws Base64DecoderException */ public static byte[] decode(byte[] source, int off, int len) throws Base64DecoderException { return decode(source, off, len, DECODABET); } /** * Decodes web safe Base64 content in byte array format and returns * the decoded byte array. * Web safe encoding uses '-' instead of '+', '_' instead of '/' * * @param source the Base64 encoded data * @param off the offset of where to begin decoding * @param len the length of characters to decode * @return decoded data */ public static byte[] decodeWebSafe(byte[] source, int off, int len) throws Base64DecoderException { return decode(source, off, len, WEBSAFE_DECODABET); } /** * Decodes Base64 content using the supplied decodabet and returns * the decoded byte array. * * @param source the Base64 encoded data * @param off the offset of where to begin decoding * @param len the length of characters to decode * @param decodabet the decodabet for decoding Base64 content * @return decoded data */ public static byte[] decode(byte[] source, int off, int len, byte[] decodabet) throws Base64DecoderException { int len34 = len * 3 / 4; byte[] outBuff = new byte[2 + len34]; // Upper limit on size of output int outBuffPosn = 0; byte[] b4 = new byte[4]; int b4Posn = 0; int i = 0; byte sbiCrop = 0; byte sbiDecode = 0; for (i = 0; i < len; i++) { sbiCrop = (byte) (source[i + off] & 0x7f); // Only the low seven bits sbiDecode = decodabet[sbiCrop]; if (sbiDecode >= WHITE_SPACE_ENC) { // White space Equals sign or better if (sbiDecode >= EQUALS_SIGN_ENC) { // An equals sign (for padding) must not occur at position 0 or 1 // and must be the last byte[s] in the encoded value if (sbiCrop == EQUALS_SIGN) { int bytesLeft = len - i; byte lastByte = (byte) (source[len - 1 + off] & 0x7f); if (b4Posn == 0 || b4Posn == 1) { throw new Base64DecoderException( "invalid padding byte '=' at byte offset " + i); } else if ((b4Posn == 3 && bytesLeft > 2) || (b4Posn == 4 && bytesLeft > 1)) { throw new Base64DecoderException( "padding byte '=' falsely signals end of encoded value " + "at offset " + i); } else if (lastByte != EQUALS_SIGN && lastByte != NEW_LINE) { throw new Base64DecoderException( "encoded value has invalid trailing byte"); } break; } b4[b4Posn++] = sbiCrop; if (b4Posn == 4) { outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet); b4Posn = 0; } } } else { throw new Base64DecoderException("Bad Base64 input character at " + i + ": " + source[i + off] + "(decimal)"); } } // Because web safe encoding allows non padding base64 encodes, we // need to pad the rest of the b4 buffer with equal signs when // b4Posn != 0. There can be at most 2 equal signs at the end of // four characters, so the b4 buffer must have two or three // characters. This also catches the case where the input is // padded with EQUALS_SIGN if (b4Posn != 0) { if (b4Posn == 1) { throw new Base64DecoderException("single trailing character at offset " + (len - 1)); } b4[b4Posn++] = EQUALS_SIGN; outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet); } byte[] out = new byte[outBuffPosn]; System.arraycopy(outBuff, 0, out, 0, outBuffPosn); return out; } }
DuongNTdev/StudyMovie
MyPrj/LE/app/src/main/java/libaries/util/Base64.java
Java
gpl-2.0
24,254
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest00313") public class BenchmarkTest00313 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // some code org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request ); String param = scr.getTheValue("foo"); javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie("SomeCookie","SomeValue"); cookie.setSecure(false); response.addCookie(cookie); } }
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest00313.java
Java
gpl-2.0
1,849
package br.com.soaexpert.services.credito.verificacao; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import br.com.soaexpert.domain.Empresa; /** * <p>Classe Java de anonymous complex type. * * <p>O seguinte fragmento do esquema especifica o conteúdo esperado contido dentro desta classe. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="empresa" type="{http://soaexpert.com.br/domain}Empresa"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "empresa" }) @XmlRootElement(name = "verificaCredito") public class VerificaCredito { @XmlElement(required = true) protected Empresa empresa; /** * Obtém o valor da propriedade empresa. * * @return * possible object is * {@link Empresa } * */ public Empresa getEmpresa() { return empresa; } /** * Define o valor da propriedade empresa. * * @param value * allowed object is * {@link Empresa } * */ public void setEmpresa(Empresa value) { this.empresa = value; } }
soaexpert/circuitbreaker
circuitbreaker-camel-services/src/main/java/br/com/soaexpert/services/credito/verificacao/VerificaCredito.java
Java
gpl-2.0
1,532
package org.madn3s.controller.fragments; import org.madn3s.controller.R; import org.madn3s.controller.R.drawable; import org.madn3s.controller.R.id; import org.madn3s.controller.R.layout; import org.madn3s.controller.R.menu; import org.madn3s.controller.R.string; import android.app.Activity; import android.app.ActionBar; import android.app.Fragment; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; /** * Fragment used for managing interactions for and presentation of a navigation drawer. * See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction"> * design guidelines</a> for a complete explanation of the behaviors implemented here. */ public class NavigationDrawerFragment extends Fragment { /** * Remember the position of the selected item. */ private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position"; /** * Per the design guidelines, you should show the drawer on launch until the user manually * expands it. This shared preference tracks this. */ private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned"; /** * A pointer to the current callbacks instance (the Activity). */ private NavigationDrawerCallbacks mCallbacks; /** * Helper component that ties the action bar to the navigation drawer. */ private ActionBarDrawerToggle mDrawerToggle; private DrawerLayout mDrawerLayout; private ListView mDrawerListView; private View mFragmentContainerView; private int mCurrentSelectedPosition = 0; private boolean mFromSavedInstanceState; private boolean mUserLearnedDrawer; public NavigationDrawerFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Read in the flag indicating whether or not the user has demonstrated awareness of the // drawer. See PREF_USER_LEARNED_DRAWER for details. SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false); if (savedInstanceState != null) { mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION); mFromSavedInstanceState = true; } // Select either the default item (0) or the last selected item. selectItem(mCurrentSelectedPosition); } @Override public void onActivityCreated (Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Indicate that this fragment would like to influence the set of actions in the action bar. setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mDrawerListView = (ListView) inflater.inflate( R.layout.fragment_navigation_drawer, container, false); mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectItem(position); } }); mDrawerListView.setAdapter(new ArrayAdapter<String>( getActionBar().getThemedContext(), android.R.layout.simple_list_item_activated_1, android.R.id.text1, new String[]{ getString(R.string.title_section1), getString(R.string.title_section2), getString(R.string.title_section3), })); mDrawerListView.setItemChecked(mCurrentSelectedPosition, true); return mDrawerListView; } public boolean isDrawerOpen() { return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView); } /** * Users of this fragment must call this method to set up the navigation drawer interactions. * * @param fragmentId The android:id of this fragment in its activity's layout. * @param drawerLayout The DrawerLayout containing this fragment's UI. */ public void setUp(int fragmentId, DrawerLayout drawerLayout) { mFragmentContainerView = getActivity().findViewById(fragmentId); mDrawerLayout = drawerLayout; // set a custom shadow that overlays the main content when the drawer opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // set up the drawer's list view with items and click listener ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); // ActionBarDrawerToggle ties together the the proper interactions // between the navigation drawer and the action bar app icon. mDrawerToggle = new ActionBarDrawerToggle( getActivity(), /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */ R.string.navigation_drawer_open, /* "open drawer" description for accessibility */ R.string.navigation_drawer_close /* "close drawer" description for accessibility */ ) { @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); if (!isAdded()) { return; } getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu() } @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); if (!isAdded()) { return; } if (!mUserLearnedDrawer) { // The user manually opened the drawer; store this flag to prevent auto-showing // the navigation drawer automatically in the future. mUserLearnedDrawer = true; SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(getActivity()); sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply(); } getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu() } }; // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer, // per the navigation drawer design guidelines. if (!mUserLearnedDrawer && !mFromSavedInstanceState) { mDrawerLayout.openDrawer(mFragmentContainerView); } // Defer code dependent on restoration of previous instance state. mDrawerLayout.post(new Runnable() { @Override public void run() { mDrawerToggle.syncState(); } }); mDrawerLayout.setDrawerListener(mDrawerToggle); } private void selectItem(int position) { mCurrentSelectedPosition = position; if (mDrawerListView != null) { mDrawerListView.setItemChecked(position, true); } if (mDrawerLayout != null) { mDrawerLayout.closeDrawer(mFragmentContainerView); } if (mCallbacks != null) { mCallbacks.onNavigationDrawerItemSelected(position); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mCallbacks = (NavigationDrawerCallbacks) activity; } catch (ClassCastException e) { throw new ClassCastException("Activity must implement NavigationDrawerCallbacks."); } } @Override public void onDetach() { super.onDetach(); mCallbacks = null; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Forward the new configuration the drawer toggle component. mDrawerToggle.onConfigurationChanged(newConfig); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // If the drawer is open, show the global app actions in the action bar. See also // showGlobalContextActionBar, which controls the top-left area of the action bar. if (mDrawerLayout != null && isDrawerOpen()) { inflater.inflate(R.menu.global, menu); showGlobalContextActionBar(); } super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } /** * Per the navigation drawer design guidelines, updates the action bar to show the global app * 'context', rather than just what's in the current screen. */ private void showGlobalContextActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setTitle(R.string.app_name); } private ActionBar getActionBar() { return getActivity().getActionBar(); } /** * Callbacks interface that all activities using this fragment must implement. */ public static interface NavigationDrawerCallbacks { /** * Called when an item in the navigation drawer is selected. */ void onNavigationDrawerItemSelected(int position); } }
fdefreitas/MADN3S
apps/VES/Apps/Android/MADN3SController/src/org/madn3s/controller/fragments/NavigationDrawerFragment.java
Java
gpl-2.0
10,654
/***************************************************************************** * Web3d.org Copyright (c) 2001 * Java Source * * This source is licensed under the GNU LGPL v2.1 * Please read http://www.gnu.org/copyleft/lgpl.html for more information * * This software comes with the standard NO WARRANTY disclaimer for any * purpose. Use it at your own risk. If there's a problem you get to fix it. * ****************************************************************************/ package org.web3d.vrml.renderer.mobile.nodes.navigation; // Standard imports import javax.vecmath.Vector4f; import javax.vecmath.Matrix4f; import javax.vecmath.Vector3f; // Application specific imports import org.web3d.vrml.nodes.VRMLNodeType; import org.web3d.vrml.renderer.common.nodes.navigation.BaseViewpoint; import org.web3d.vrml.renderer.mobile.nodes.MobileViewpointNodeType; import org.web3d.vrml.renderer.mobile.sg.SceneGraphObject; import org.web3d.vrml.renderer.mobile.sg.SGManager; import org.web3d.vrml.renderer.mobile.sg.TransformGroup; import org.web3d.vrml.renderer.mobile.sg.Viewpoint; /** * Mobile implementation of a Viewpoint node. * <p> * * Viewpoints cannot be shared using DEF/USE. They may be named as such for * Anchor purposes, but attempting to reuse them will cause an error. This * implementation does not provide any protection against USE of this node * and attempting to do so will result in exceptions - most * probably in the grouping node that includes this node. * * @author Alan Hudson * @version $Revision: 1.4 $ */ public class MobileViewpoint extends BaseViewpoint implements MobileViewpointNodeType { /** The transform group that holds the viewpoint */ private TransformGroup transform; /** The impl node */ private Viewpoint impl; // Use J3D classes for now till matrix classes are finished private Vector4f axis; private Vector3f trans; private Matrix4f implTrans; private Matrix4f mat; /** * Construct a default viewpoint instance */ public MobileViewpoint() { init(); } /** * Construct a new instance of this node based on the details from the * given node. If the node is not the same type, an exception will be * thrown. * * @param node The node to copy * @throws IllegalArgumentException The node is not the same type */ public MobileViewpoint(VRMLNodeType node) { super(node); init(); } //---------------------------------------------------------- // Methods from MobileVRMLNode class. //---------------------------------------------------------- /** * Get the OpenGL scene graph object representation of this node. This will * need to be cast to the appropriate parent type when being used. Default * implementation returns null. * * @return The OpenGL representation. */ public SceneGraphObject getSceneGraphObject() { return transform; } //---------------------------------------------------------- // Methods overriding BaseViewpoint //---------------------------------------------------------- /** * Convenience method to set the position of the viewpoint. * * @param pos The position vector to use */ protected void setPosition(float[] pos) { super.setPosition(pos); if (!inSetup) updateViewTrans(); } /** * Convenience method to set the orientation of the viewpoint. * * @param dir The orientation quaternion to use */ protected void setOrientation(float[] dir) { super.setOrientation(dir); if (!inSetup) updateViewTrans(); } //---------------------------------------------------------- // Methods required by the VRMLNodeType interface. //---------------------------------------------------------- /** * Notification that the construction phase of this node has finished. * If the node would like to do any internal processing, such as setting * up geometry, then go for it now. */ public void setupFinished() { if(!inSetup) return; super.setupFinished(); transform = new TransformGroup(); updateViewTrans(); transform.addChild(impl); inSetup = false; } //---------------------------------------------------------- // Methods internal to MobileViewpoint //---------------------------------------------------------- /** * Updates the TransformGroup fields from the VRML fields */ private void updateViewTrans() { axis = new Vector4f(vfOrientation[0], vfOrientation[1], vfOrientation[2],0); axis.rotationNormalize(); implTrans.identity(); implTrans.rotation(axis); trans = new Vector3f(vfPosition[0], vfPosition[1], -vfPosition[2]); implTrans.translate(trans); transform.setTransform(implTrans); } /** * Private, internal, common iniitialisation. */ private void init() { impl = new Viewpoint(); axis = new Vector4f(); trans = new Vector3f(); implTrans = new Matrix4f(); mat = new Matrix4f(); } // This should be part of the MobileViewpointNodeType public Viewpoint getView() { return impl; } }
Norkart/NK-VirtualGlobe
Xj3D/src/java/org/web3d/vrml/renderer/mobile/nodes/navigation/MobileViewpoint.java
Java
gpl-2.0
5,437
/* * 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 algoritmoscepc; /** * * @author Manuel Angel Muñoz S */ public class AlgoritmosCepc { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here } }
gwmifero/algos.cepc
AlgoritmosCepc/src/algoritmoscepc/AlgoritmosCepc.java
Java
gpl-2.0
470
package de.superioz.moo.api.database.object; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface DbKey { /** * This value specifies the key of one field inside the database<br> * Example: If you have playerData and the field is named 'name' but you want * to name it 'lastName', then just add a @DbKey(name = 'lastName') to the field and done. * * @return The key */ String key() default ""; }
Superioz/MooProject
api/src/main/java/de/superioz/moo/api/database/object/DbKey.java
Java
gpl-2.0
626
/* The GNU General Public License (GPL) Version 1, November 2012 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Copyright (c) 2012, Mani Sarkar <[email protected]> All rights reserved. DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. This code is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 only, as published by the Free Software Foundation. Oracle designates this particular file as subject to the "Classpath" exception as provided by Oracle in the LICENSE file that accompanied this code. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License version 2 for more details (a copy is included in the LICENSE file that accompanied this code). You should have received a copy of the GNU General Public License version 2 along with this work; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.ljc.adoptojdk.ClassContributorRetriever; import static org.ljc.adoptojdk.database.DatabaseOfOpenJDKContributors.CONTRIBUTOR_NAME; import static org.ljc.adoptojdk.database.DatabaseOfOpenJDKContributors.FULLY_QUALIFIED_CLASS_NAME; import org.ljc.adoptojdk.className.FullyQualifiedClassName; import org.ljc.adoptojdk.className.NotAFullyQualifiedClassNameException; import org.ljc.adoptojdk.database.DatabaseOfOpenJDKContributors; /* The GNU General Public License (GPL) Version 1, November 2012 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Copyright (c) 2012, Mani Sarkar <[email protected]> All rights reserved. DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. This code is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 only, as published by the Free Software Foundation. Oracle designates this particular file as subject to the "Classpath" exception as provided by Oracle in the LICENSE file that accompanied this code. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License version 2 for more details (a copy is included in the LICENSE file that accompanied this code). You should have received a copy of the GNU General Public License version 2 along with this work; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ public class ContributorRetriever { public static final String CLASS_OWNER_SWITCH = "-co"; private String fullyQualifiedClassName; private DatabaseOfOpenJDKContributors dbOpenJDKContributors; private String[] classContributorDetails; public ContributorRetriever(DatabaseOfOpenJDKContributors dbOpenJDKContributors, String inClassName) throws NotAFullyQualifiedClassNameException { if (inClassName == null) { throw new NullPointerException(); } this.dbOpenJDKContributors = dbOpenJDKContributors; fullyQualifiedClassName = getFullyQualifiedClassName(inClassName); classContributorDetails = getContributorDetails(); } public final String[] getContributorDetails() { String[] dbRecord = {}; dbRecord = dbOpenJDKContributors.findRecordBy(FULLY_QUALIFIED_CLASS_NAME, fullyQualifiedClassName); return dbRecord; } public final String getContributorName() { String ownerName = ""; if ((classContributorDetails != null) && (classContributorDetails.length > 0)) { ownerName = classContributorDetails[CONTRIBUTOR_NAME]; } return ownerName; } public final String getFullyQualifiedClassName(String paramClassName) throws NotAFullyQualifiedClassNameException { return new FullyQualifiedClassName(paramClassName).getFullyQualifiedClassName(); } }
neomatrix369/OpenJDKProductivityTool
src/main/java/org/ljc/adoptojdk/ClassContributorRetriever/ContributorRetriever.java
Java
gpl-2.0
4,484
package Graphics.Relief; import org.lwjgl.input.Keyboard; import org.lwjgl.util.vector.Vector3f; import Data.Chunk; import Data.DataManager; import Data.Hoopla; import Data.Map; import Data.Player; import Engine.GlControlPanel; import Engine.Camera.HelicopterCamera; import Engine.Models.Mesh; import Events.EventsHandler; import Events.HelicopterCamera.HelicopterCameraMoveBackListener; import Events.HelicopterCamera.HelicopterCameraMoveFrontListener; import Events.HelicopterCamera.HelicopterCameraRotateLeftListener; import Events.HelicopterCamera.HelicopterCameraRotateRightListener; import Graphics.AGraphicChunk; import Graphics.AGraphicPlayer; import Graphics.AView; public class ReliefView extends AView { private Mesh chunksBorders; public ReliefView() { super(); camera = new HelicopterCamera(); camera.setPosition(0.0f, 0.0f, 20.0f); this.prepareEventsHandler(); } @Override public void initData(int longer, int larger) { super.initData(longer, larger); camera.setPosition(longer / 2 * Chunk.SIZE, larger / 2 * Chunk.SIZE); chunksBorders = null; } public void select() { super.select(); GlControlPanel.getInstance().setDepthMask(true); GlControlPanel.getInstance().setTexture2D(false); } @Override protected AGraphicChunk createGraphicChunk(int x, int y, Chunk chunk) { return (new ReliefGraphicChunk(x, y, chunk)); } @Override protected AGraphicPlayer createGraphicPlayer(Player player) { return (new ReliefGraphicPlayer(player)); } @Override public void displayChunks(long elapsedTime) { this.displaySomeChunks(elapsedTime, new ReliefChunkSorter(camera)); if (chunksBorders != null) { chunksBorders.draw(); } } private void addHooplaToBrodersMeshVertices(float vertices[], float colors[], Hoopla hoopla, int x, int y, int index) { Vector3f color; float height; color = hoopla.getGroundType().getColor(); height = hoopla.getHeight() / 10.0f; if (height < 0.0f) { height = 0.0f; } vertices[index + 0] = x; vertices[index + 1] = y; vertices[index + 2] = height; colors[index + 0] = color.x; colors[index + 1] = color.y; colors[index + 2] = color.z; } private void addChunkToBordersMeshVertices(float vertices[], float colors[], Map map, int chunkX, int chunkY, int index, boolean borderX, boolean borderY) { int x, y; int toAddX, toAddY; Hoopla hoopla; toAddX = chunkX * Chunk.SIZE; toAddY = chunkY * Chunk.SIZE; if (borderY == false) { for (x = 0; x < Chunk.SIZE; ++x) { hoopla = map.getChunk(chunkX, chunkY).getHoopla(x, Chunk.SIZE - 1); this.addHooplaToBrodersMeshVertices(vertices, colors, hoopla, x + toAddX, Chunk.SIZE - 1 + toAddY, index); index += 3; hoopla = map.getChunk(chunkX, chunkY + 1).getHoopla(x, 0); this.addHooplaToBrodersMeshVertices(vertices, colors, hoopla, x + toAddX, Chunk.SIZE + toAddY, index); index += 3; } if (borderX == false) { hoopla = map.getChunk(chunkX + 1, chunkY).getHoopla(0, Chunk.SIZE - 1); this.addHooplaToBrodersMeshVertices(vertices, colors, hoopla, Chunk.SIZE + toAddX, Chunk.SIZE - 1 + toAddY, index); index += 3; hoopla = map.getChunk(chunkX + 1, chunkY + 1).getHoopla(0, 0); this.addHooplaToBrodersMeshVertices(vertices, colors, hoopla, Chunk.SIZE + toAddX, Chunk.SIZE + toAddY, index); index += 3; } } if (borderX == false) { for (y = 0; y < Chunk.SIZE; ++y) { hoopla = map.getChunk(chunkX, chunkY).getHoopla(Chunk.SIZE - 1, y); this.addHooplaToBrodersMeshVertices(vertices, colors, hoopla, Chunk.SIZE - 1 + toAddX, y + toAddY, index); index += 3; hoopla = map.getChunk(chunkX + 1, chunkY).getHoopla(0, y); this.addHooplaToBrodersMeshVertices(vertices, colors, hoopla, Chunk.SIZE + toAddX, y + toAddY, index); index += 3; } if (borderY == false) { hoopla = map.getChunk(chunkX, chunkY + 1).getHoopla(Chunk.SIZE - 1, 0); this.addHooplaToBrodersMeshVertices(vertices, colors, hoopla, Chunk.SIZE - 1 + toAddX, Chunk.SIZE + toAddY, index); index += 3; hoopla = map.getChunk(chunkX + 1, chunkY + 1).getHoopla(0, 0); this.addHooplaToBrodersMeshVertices(vertices, colors, hoopla, Chunk.SIZE + toAddX, Chunk.SIZE + toAddY, index); index += 3; } } } private void addChunkToBordersMeshIndices(int[] indices, int index, boolean borderX, boolean borderY) { int i; int x, y; if (borderX == false) { x = Chunk.SIZE; if (borderY) { --x; } for (i = 0; i < x; ++i) { indices[index + 0] = 0 + index / 3; indices[index + 1] = 1 + index / 3; indices[index + 2] = 2 + index / 3; indices[index + 3] = 3 + index / 3; indices[index + 4] = 1 + index / 3; indices[index + 5] = 2 + index / 3; index += 6; } index += 6; } if (borderY == false) { y = Chunk.SIZE; if (borderX) { --y; } for (i = 0; i < y; ++i) { indices[index + 0] = 0 + index / 3; indices[index + 1] = 1 + index / 3; indices[index + 2] = 2 + index / 3; indices[index + 3] = 3 + index / 3; indices[index + 4] = 1 + index / 3; indices[index + 5] = 2 + index / 3; index += 6; } } } private void createChunksBorders(Map map) { float vertices[]; float colors[]; int indices[]; int casesNumber; int x, y; int vertexIndex, indicesIndex; casesNumber = map.getChunksNumber() * (Chunk.SIZE + Chunk.SIZE + 2); vertices = new float[2 * 3 * casesNumber]; colors = new float[2 * 3 * casesNumber]; indices = new int[6 * casesNumber]; vertexIndex = 0; indicesIndex = 0; for (x = 0; x < map.getLonger(); ++x) { for (y = 0; y < map.getLarger(); ++y) { this.addChunkToBordersMeshVertices(vertices, colors, map, x, y, vertexIndex, x == map.getLonger() - 1, y == map.getLarger() - 1); this.addChunkToBordersMeshIndices(indices, indicesIndex, x == map.getLonger() - 1, y == map.getLarger() - 1); vertexIndex += 6 * (Chunk.SIZE + Chunk.SIZE + 2); indicesIndex += 6 * (Chunk.SIZE + Chunk.SIZE + 2); } } chunksBorders = new Mesh(); chunksBorders.addVertices(vertices); chunksBorders.addColors(colors); chunksBorders.addIndices(indices); chunksBorders.build(); } @Override public void manageData(long elapsedTime) { Map map; super.manageData(elapsedTime); if (chunksBorders == null) { map = DataManager.getInstance().getMap(); if (map != null && map.isReady()) { this.createChunksBorders(map); } } } private void prepareEventsHandler() { eventsHandler = new EventsHandler(); eventsHandler.addKeyboardEvent(Keyboard.KEY_UP, new HelicopterCameraMoveFrontListener(camera)); eventsHandler.addKeyboardEvent(Keyboard.KEY_DOWN, new HelicopterCameraMoveBackListener(camera)); eventsHandler.addKeyboardEvent(Keyboard.KEY_RIGHT, new HelicopterCameraRotateRightListener(camera)); eventsHandler.addKeyboardEvent(Keyboard.KEY_LEFT, new HelicopterCameraRotateLeftListener(camera)); } }
Aracthor/super_zappy
graphic/java/src/Graphics/Relief/ReliefView.java
Java
gpl-2.0
7,070
package br.com.arvus.sws.chart.flot.ChartModels; import br.com.arvus.sws.chart.flot.FlotBaseChart; import br.com.arvus.sws.chart.flot.FlotConfiguration; import br.com.arvus.sws.chart.flot.FlotSeriesItem; import java.util.List; /** * Created by vinicius on 23/04/14. */ public final class FlotStackedBarChart extends FlotBaseChart { public FlotStackedBarChart(String title) { super(title); } public FlotStackedBarChart(String title, String unit) { super(title, unit); } public FlotStackedBarChart(String title, String unit, List<FlotSeriesItem> series) { super(title, unit, series); } @Override protected void setup() { FlotConfiguration configuration = new FlotConfiguration(); configuration.setName("bars"); //mostrar as barras FlotConfiguration subConfiguration = new FlotConfiguration(); subConfiguration.setName("show"); subConfiguration.setValue("true"); configuration.addSubConfiguration(subConfiguration); //alinhar barras ao centro do valor de X subConfiguration = new FlotConfiguration(); subConfiguration.setName("align"); subConfiguration.setValue("\"center\""); configuration.addSubConfiguration(subConfiguration); //largura das barras subConfiguration = new FlotConfiguration(); subConfiguration.setName("barWidth"); subConfiguration.setValue("12*24*60*60*10"); configuration.addSubConfiguration(subConfiguration); //cores sólidas subConfiguration = new FlotConfiguration(); subConfiguration.setName("fillColor"); configuration.addSubConfiguration(subConfiguration); FlotConfiguration subSubConfiguration = new FlotConfiguration(); subSubConfiguration.setName("colors"); subSubConfiguration.setValue("[{ opacity: 1 }, { opacity: 0.8 }]"); subConfiguration.addSubConfiguration(subSubConfiguration); this.addConfiguration(configuration); this.addConfiguration(configuration); configuration = new FlotConfiguration(); configuration.setName("series"); //barras empilhadas subConfiguration = new FlotConfiguration(); subConfiguration.setName("stack"); subConfiguration.setValue("true"); configuration.addSubConfiguration(subConfiguration); this.addConfiguration(configuration); } }
viniciuscr/flotChart
ChartModels/FlotStackedBarChart.java
Java
gpl-2.0
2,457