repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
ndexbio/ndex-object-model
src/main/java/org/ndexbio/cxio/aspects/readers/CyVisualPropertiesFragmentReader.java
3330
package org.ndexbio.cxio.aspects.readers; import java.io.IOException; import java.util.Iterator; import java.util.Map.Entry; import org.ndexbio.cxio.aspects.datamodels.CyVisualPropertiesElement; import org.ndexbio.cxio.aspects.datamodels.Mapping; import org.ndexbio.cxio.core.interfaces.AspectElement; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; public final class CyVisualPropertiesFragmentReader extends AbstractFragmentReader { public static CyVisualPropertiesFragmentReader createInstance() { return new CyVisualPropertiesFragmentReader(); } private CyVisualPropertiesFragmentReader() { super(); } @Override public final String getAspectName() { return CyVisualPropertiesElement.ASPECT_NAME; } @Override public final AspectElement readElement(final ObjectNode o) throws IOException { CyVisualPropertiesElement vpe; if (o.has(CyVisualPropertiesElement.APPLIES_TO) && (o.has(CyVisualPropertiesElement.VIEW))) { vpe = new CyVisualPropertiesElement(ParserUtils.getTextValueRequired(o, CyVisualPropertiesElement.PROPERTIES_OF), ParserUtils.getTextValueAsLong(o, CyVisualPropertiesElement.APPLIES_TO), ParserUtils.getTextValueAsLong(o, CyVisualPropertiesElement.VIEW)); } else if (o.has(CyVisualPropertiesElement.APPLIES_TO)) { vpe = new CyVisualPropertiesElement(ParserUtils.getTextValueRequired(o, CyVisualPropertiesElement.PROPERTIES_OF), ParserUtils.getTextValueAsLong(o, CyVisualPropertiesElement.APPLIES_TO),null /*ParserUtils.getTextValueAsLong(o, CyVisualPropertiesElement.APPLIES_TO)*/); } else { vpe = new CyVisualPropertiesElement(ParserUtils.getTextValueRequired(o, CyVisualPropertiesElement.PROPERTIES_OF)); } if (o.has(CyVisualPropertiesElement.PROPERTIES)) { final Iterator<Entry<String, JsonNode>> it = o.get(CyVisualPropertiesElement.PROPERTIES).fields(); if (it != null) { while (it.hasNext()) { final Entry<String, JsonNode> kv = it.next(); vpe.putProperty(kv.getKey(), kv.getValue().asText()); } } } if (o.has(CyVisualPropertiesElement.DEPENDENCIES)) { final Iterator<Entry<String, JsonNode>> it = o.get(CyVisualPropertiesElement.DEPENDENCIES).fields(); if (it != null) { while (it.hasNext()) { final Entry<String, JsonNode> kv = it.next(); vpe.putDependency(kv.getKey(), kv.getValue().asText()); } } } if (o.has(CyVisualPropertiesElement.MAPPINGS)) { final Iterator<Entry<String, JsonNode>> it = o.get(CyVisualPropertiesElement.MAPPINGS).fields(); if (it != null) { while (it.hasNext()) { final Entry<String, JsonNode> kv = it.next(); vpe.putMapping(kv.getKey(), kv.getValue().get(Mapping.TYPE).asText(), kv.getValue().get(Mapping.DEFINITION).asText()); } } } return vpe; } }
bsd-3-clause
Team-2502/RobotCode2013
src/com/team2502/robot2013/commands/vision/VisionUpdate.java
1193
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.team2502.robot2013.commands.vision; import com.team2502.robot2013.commands.CommandBase; import com.team2502.robot2013.subsystems.Vision.VisionTarget; /** * * @author josh */ public class VisionUpdate extends CommandBase { private int frameDelay; public VisionUpdate() { requires(vision); frameDelay = 1000; } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { if (System.currentTimeMillis() - vision.lastFrame() >= frameDelay) { VisionTarget [] targets = vision.processFrame(); if (targets.length > 0) { frameDelay = 300; } else { frameDelay = 1000; } } } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
bsd-3-clause
fresskarma/tinyos-1.x
tools/java/net/tinyos/surge/util/Hex.java
2292
// $Id: Hex.java,v 1.2 2003/10/07 21:46:05 idgay Exp $ /* tab:4 * "Copyright (c) 2000-2003 The Regents of the University of California. * All rights reserved. * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose, without fee, and without written agreement is * hereby granted, provided that the above copyright notice, the following * two paragraphs and the author appear in all copies of this software. * * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS." * * Copyright (c) 2002-2003 Intel Corporation * All rights reserved. * * This file is distributed under the terms in the attached INTEL-LICENSE * file. If you do not find these files, copies can be found by writing to * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, * 94704. Attention: Intel License Inquiry. */ /** * @author Wei Hong */ package net.tinyos.surge.util; //the following class is used only to translate from hex to dec public class Hex{ public static final String[] hex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"}; public static String toHex(int i) { int q = i/16; int r = i % 16; return (hex[q] + hex[r]); } public static String toHex(byte[] bytes) { return toHex(bytes, bytes.length); } public static String toHex(byte[] bytes, int length) { String result =""; for (int i = 0; i < length; i++) { byte b = bytes[i]; int h = ((b & 0xf0) >> 4); int l = (b & 0x0f); result += hex[h] + hex[l] + " "; } return result; } }
bsd-3-clause
vtkio/vtk
src/main/java/vtk/resourcemanagement/view/TemplateLanguageDecoratorComponent.java
6496
/* Copyright (c) 2009, University of Oslo, Norway * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the University of Oslo nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package vtk.resourcemanagement.view; import java.io.StringReader; import java.io.Writer; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import vtk.resourcemanagement.ComponentDefinition; import vtk.text.html.HtmlPageParser; import vtk.text.tl.Context; import vtk.text.tl.DirectiveHandler; import vtk.text.tl.Node; import vtk.text.tl.NodeList; import vtk.text.tl.TemplateHandler; import vtk.text.tl.TemplateParser; import vtk.web.decorating.DecoratorRequest; import vtk.web.decorating.DecoratorResponse; import vtk.web.decorating.DynamicDecoratorTemplate; import vtk.web.decorating.components.AbstractDecoratorComponent; import vtk.web.decorating.components.DecoratorComponentException; public class TemplateLanguageDecoratorComponent extends AbstractDecoratorComponent { private String namespace; private ComponentDefinition definition; private String modelKey; private NodeList nodeList; private HtmlPageParser htmlParser; private List<DirectiveHandler> directiveHandlers; private static Logger logger = LoggerFactory.getLogger(TemplateLanguageDecoratorComponent.class); private Date compileTime; public TemplateLanguageDecoratorComponent(String namespace, ComponentDefinition definition, String modelKey, List<DirectiveHandler> directiveHandlers, HtmlPageParser htmlParser) throws Exception { this.namespace = namespace; this.definition = definition; this.modelKey = modelKey; this.htmlParser = htmlParser; this.directiveHandlers = directiveHandlers; compile(); } private void compile() throws Exception { if (this.compileTime == null || this.compileTime.getTime() < this.definition.getLastModified().getTime()) { new TemplateParser( new StringReader(definition.getDefinition()), directiveHandlers, new TemplateHandler() { @Override public void success(NodeList result) { nodeList = result; compileTime = new Date(); } @Override public void error(final String message, final int line) { NodeList err = new NodeList(); err.add(new Node() { @Override public boolean render(Context ctx, Writer out) throws Exception { out.write("Error compiling component " + getName() + ": line " + line + ": " + message); return true; } }); nodeList = err; compileTime = new Date(); } }).parse();; } } @Override public void render(DecoratorRequest request, DecoratorResponse response) throws Exception { try { compile(); Context ctx = createContext(request); Writer writer = response.getWriter(); this.nodeList.render(ctx, writer); writer.flush(); writer.close(); } catch (Throwable t) { logger.info("Error rendering component '" + getName() + "'", t); throw new DecoratorComponentException("Error rendering component '" + getName() + "': " + t.getMessage(), t); } } private Context createContext(DecoratorRequest request) { Context ctx = new Context(request.getLocale()); if (this.modelKey != null) { ctx.define(this.modelKey, request.getMvcModel(), true); } for (String param : this.definition.getParameters()) { Object value = request.getRawParameter(param); ctx.define(param, value, true); } ctx.setAttribute(DynamicDecoratorTemplate.SERVLET_REQUEST_CONTEXT_ATTR, request.getServletRequest()); return ctx; } @Override protected String getDescriptionInternal() { return null; } @Override protected Map<String, String> getParameterDescriptionsInternal() { Map<String, String> result = new HashMap<>(); for (String param : this.definition.getParameters()) { result.put(param, "#parameter"); } return result; } @Override public String getName() { return this.definition.getName(); } @Override public String getNamespace() { return this.namespace; } }
bsd-3-clause
turn/sorcerer
src/main/java/com/turn/sorcerer/config/impl/SorcererAbstractModule.java
4595
/* * Copyright (c) 2015, Turn Inc. All Rights Reserved. * Use of this source code is governed by a BSD-style license that can be found * in the LICENSE file. */ package com.turn.sorcerer.config.impl; import com.turn.sorcerer.module.ModuleType; import com.turn.sorcerer.pipeline.Pipeline; import com.turn.sorcerer.pipeline.type.PipelineType; import com.turn.sorcerer.status.StatusStorage; import com.turn.sorcerer.status.impl.HDFSStatusStorage; import com.turn.sorcerer.status.impl.ZookeeperStatusStorage; import com.turn.sorcerer.status.type.impl.HDFSStatusStorageType; import com.turn.sorcerer.status.type.impl.ZookeeperStatusStorageType; import com.turn.sorcerer.task.Task; import com.turn.sorcerer.task.type.TaskType; import com.turn.sorcerer.util.email.EmailType; import java.util.Map; import com.google.common.collect.Maps; import com.google.inject.AbstractModule; import com.google.inject.multibindings.Multibinder; import com.google.inject.name.Names; /** * Sorcerer Guice abstract module * * @author tshiou */ public class SorcererAbstractModule extends AbstractModule { private Map<String, TaskType> tasks = Maps.newHashMap(); private Map<String, Class<? extends Task>> taskClasses = Maps.newHashMap(); private Map<String, PipelineType> pipelines = Maps.newHashMap(); private Map<String, Class<? extends Pipeline>> pipelineClasses = Maps.newHashMap(); private ModuleType module; protected SorcererAbstractModule( Map<String, TaskType> tasks, Map<String, Class<? extends Task>> taskClasses, Map<String, PipelineType> pipelines, Map<String, Class<? extends Pipeline>> pipelineClasses, ModuleType module ) { this.tasks = tasks; this.taskClasses = taskClasses; this.pipelines = pipelines; this.pipelineClasses = pipelineClasses; this.module = module; } @Override protected void configure() { // Task // Bind task types annotated by their name for (Map.Entry<String, TaskType> entry : tasks.entrySet()) { bind(TaskType.class).annotatedWith(Names.named(entry.getKey())) .toInstance(entry.getValue()); } // Bind task classes for (Map.Entry<String, Class<? extends Task>> entry : taskClasses.entrySet()) { bind(Task.class).annotatedWith(Names.named(entry.getKey())) .to(entry.getValue()); } for (Map.Entry<String, PipelineType> entry : pipelines.entrySet()) { // Bind pipeline type bind(PipelineType.class).annotatedWith(Names.named(entry.getKey())) .toInstance(entry.getValue()); } // Bind pipeline classes for (Map.Entry<String, Class<? extends Pipeline>> entry : pipelineClasses.entrySet()) { bind(Pipeline.class).annotatedWith(Names.named(entry.getKey())) .to(entry.getValue()); } // Bind module and configurations bind(ModuleType.class).toInstance(module); // Pipelines to run Multibinder<PipelineType> pipelineSet = Multibinder.newSetBinder(binder(), PipelineType.class); for (String pipelineName : module.getPipelines()) { pipelineSet.addBinding().toInstance(pipelines.get(pipelineName)); } bind(EmailType.class).toInstance(module.getAdminEmail()); bind(StatusStorage.class).to(module.getStorage().getStorageClass()); if (module.getStorage().getClass() == HDFSStatusStorageType.class) { bind(String.class).annotatedWith(HDFSStatusStorage.HDFSStorageRoot.class) .toInstance(((HDFSStatusStorageType) module.getStorage()).getRoot()); } else if (module.getStorage().getClass() == ZookeeperStatusStorageType.class) { bindZookeeperStorage(); } } private void bindZookeeperStorage() { bind(String.class).annotatedWith(ZookeeperStatusStorage.StorageRoot.class) .toInstance(((ZookeeperStatusStorageType) module.getStorage()).getRoot()); bind(String.class).annotatedWith(ZookeeperStatusStorage.ConnectionString.class) .toInstance(((ZookeeperStatusStorageType) module.getStorage()).getConnectionString()); bind(Integer.class).annotatedWith(Names.named(ZookeeperStatusStorage.SESSION_TIMEOUT)) .toInstance(((ZookeeperStatusStorageType) module.getStorage()).getSessionTimeout()); bind(Integer.class).annotatedWith(Names.named(ZookeeperStatusStorage.CONNECTION_TIMEOUT)) .toInstance(((ZookeeperStatusStorageType) module.getStorage()).getConnectionTimeout()); bind(Integer.class).annotatedWith(Names.named(ZookeeperStatusStorage.RETRY_DURATION)) .toInstance(((ZookeeperStatusStorageType) module.getStorage()).getRetryDuration()); bind(Integer.class).annotatedWith(Names.named(ZookeeperStatusStorage.RETRY_INTERVAL)) .toInstance(((ZookeeperStatusStorageType) module.getStorage()).getRetryInterval()); } }
bsd-3-clause
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/arch/repositories/filters/internal/EnumFilterConnector.java
2326
/* * Copyright (c) 2004-2021, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.arch.repositories.filters.internal; import org.hisp.dhis.android.core.arch.repositories.collection.BaseRepository; import org.hisp.dhis.android.core.arch.repositories.collection.internal.BaseRepositoryFactory; import org.hisp.dhis.android.core.arch.repositories.scope.RepositoryScope; public final class EnumFilterConnector<R extends BaseRepository, E extends Enum<E>> extends BaseAbstractFilterConnector<R, E> { EnumFilterConnector(BaseRepositoryFactory<R> repositoryFactory, RepositoryScope scope, String key) { super(repositoryFactory, scope, key); } String wrapValue(E value) { return "'" + value.name() + "'"; } }
bsd-3-clause
qsardb/qsardb-editor
src/main/java/org/qsardb/editor/validator/ValidationLevel.java
2649
/* * Copyright (c) 2015 University of Tartu */ package org.qsardb.editor.validator; import java.util.*; import javax.swing.SwingWorker; import org.qsardb.cargo.pmml.*; import org.qsardb.cargo.rds.*; import org.qsardb.model.*; import org.qsardb.validation.*; public enum ValidationLevel { BASIC, INTERMEDIATE, ADVANCED, STRUCTURE; public void validate(Qdb qdb, MessageCollector collector, String[] values, SwingWorker sw) { List<Validator<?>> validators = prepareValidators(values, sw); ValidateArchiveView.pbar.setValue(0); float n = validators.size(); float i = 0; for(Validator<?> validator : validators){ if (sw.isCancelled()) { return; } validator.setCollector(collector); i++; try { validator.run(qdb); } finally { validator.setCollector(null); } ValidateArchiveView.pbar.setValue((int) ((int) i / n * 100)); } } private List<Validator<?>> prepareValidators(String[] values, SwingWorker sw) { List<Validator<?>> result = new ArrayList<Validator<?>>(); if(BASIC.compareTo(this) <= 0){ result.add(new ArchiveValidator()); result.add(new BasicContainerValidator()); result.add(new CompoundValidator(Scope.LOCAL)); result.add(new PropertyValidator(Scope.LOCAL)); result.add(new DescriptorValidator(Scope.LOCAL)); result.add(new ModelValidator(Scope.LOCAL)); result.add(new PredictionValidator(Scope.LOCAL)); result.add(new PredictionRegistryValidator()); result.add(new BasicCargoValidator(1024 * 1024){ @Override public int getLimit(Cargo<?> cargo){ Container container = cargo.getContainer(); if(container instanceof Model){ String id = cargo.getId(); if((RDSCargo.ID).equals(id) || (PMMLCargo.ID).equals(id)){ return 10 * 1024 * 1024; } } return super.getLimit(cargo); } }); result.add(new ValuesValidator()); //result.add(new UCUMValidator()); result.add(new ReferencesValidator()); result.add(new PMMLValidator()); result.add(new BibTeXValidator()); result.add(new BODOValidator()); } if(INTERMEDIATE.compareTo(this) <= 0){ result.add(new CompoundValidator(Scope.GLOBAL)); result.add(new PropertyValidator(Scope.GLOBAL)); result.add(new DescriptorValidator(Scope.GLOBAL)); result.add(new ModelValidator(Scope.GLOBAL)); result.add(new PredictionValidator(Scope.GLOBAL)); } if(ADVANCED.compareTo(this) <= 0){ result.add(new PredictionReproducibilityValidator()); } if (STRUCTURE.compareTo(this) <= 0) { result = new ArrayList<Validator<?>>(); result.add(new StructureValidator(Scope.GLOBAL, values, sw)); } return result; } }
bsd-3-clause
KingBowser/hatter-source-code
commons-log/log4j/src/main/java/me/hatter/tools/commons/log/impl/Log4jLogTool.java
1442
package me.hatter.tools.commons.log.impl; import me.hatter.tools.commons.log.LogTool; import org.apache.log4j.Logger; public class Log4jLogTool implements LogTool { private Logger logger; public Log4jLogTool(Logger logger) { this.logger = logger; } public boolean isTraceEnable() { return logger.isTraceEnabled(); } public boolean isDebugEnable() { return logger.isDebugEnabled(); } public boolean isInfoEnable() { return logger.isInfoEnabled(); } public boolean isWarnEnable() { return true; } public void trace(String message) { logger.trace(message); } public void trace(String message, Throwable t) { logger.trace(message, t); } public void debug(String message) { logger.debug(message); } public void debug(String message, Throwable t) { logger.debug(message, t); } public void info(String message) { logger.info(message); } public void info(String message, Throwable t) { logger.info(message, t); } public void warn(String message) { logger.warn(message); } public void warn(String message, Throwable t) { logger.warn(message, t); } public void error(String message) { logger.error(message); } public void error(String message, Throwable t) { logger.error(message, t); } }
bsd-3-clause
arthurgwatidzo/dhis2-android-sdk
app/src/main/java/org/hisp/dhis/android/sdk/network/RepoManager.java
6766
/* * Copyright (c) 2015, University of Oslo * * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.sdk.network; import android.util.Log; import com.crashlytics.android.Crashlytics; import com.facebook.stetho.okhttp.StethoInterceptor; import com.squareup.okhttp.HttpUrl; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import org.hisp.dhis.android.sdk.controllers.DhisController; import org.hisp.dhis.android.sdk.utils.StringConverter; import java.io.IOException; import java.net.HttpURLConnection; import java.util.concurrent.TimeUnit; import retrofit.ErrorHandler; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.OkClient; import retrofit.converter.ConversionException; import retrofit.converter.Converter; import retrofit.converter.JacksonConverter; import static com.squareup.okhttp.Credentials.basic; public final class RepoManager { static final int DEFAULT_CONNECT_TIMEOUT_MILLIS = 60 * 1000; // 60s static final int DEFAULT_READ_TIMEOUT_MILLIS = 60 * 1000; // 60s static final int DEFAULT_WRITE_TIMEOUT_MILLIS = 60 * 1000; // 60s private RepoManager() { // no instances } public static DhisApi createService(HttpUrl serverUrl, Credentials credentials) { RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint(provideServerUrl(serverUrl)) .setConverter(provideJacksonConverter()) .setClient(provideOkClient(credentials)) .setErrorHandler(new RetrofitErrorHandler()) .setLogLevel(RestAdapter.LogLevel.BASIC) .build(); return restAdapter.create(DhisApi.class); } private static String provideServerUrl(HttpUrl httpUrl) { return httpUrl.newBuilder() .addPathSegment("api") .build().toString(); } private static Converter provideJacksonConverter() { return new JacksonConverter(DhisController.getInstance().getObjectMapper()); } private static OkClient provideOkClient(Credentials credentials) { return new OkClient(provideOkHttpClient(credentials)); } public static OkHttpClient provideOkHttpClient(Credentials credentials) { OkHttpClient client = new OkHttpClient(); client.networkInterceptors().add(new StethoInterceptor()); client.interceptors().add(provideInterceptor(credentials)); client.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); client.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); client.setWriteTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); return client; } private static Interceptor provideInterceptor(Credentials credentials) { return new AuthInterceptor(credentials.getUsername(), credentials.getPassword()); } private static class AuthInterceptor implements Interceptor { private final String mUsername; private final String mPassword; public AuthInterceptor(String username, String password) { mUsername = username; mPassword = password; } @Override public Response intercept(Chain chain) throws IOException { String base64Credentials = basic(mUsername, mPassword); Request request = chain.request() .newBuilder() .addHeader("Authorization", base64Credentials) .build(); Log.d("RepoManager",request.toString()); Response response = chain.proceed(request); if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED && DhisController.getInstance().isUserLoggedIn()) { DhisController.getInstance().invalidateSession(); } return response; } } private static class RetrofitErrorHandler implements ErrorHandler { @Override public Throwable handleError(RetrofitError cause) { Log.d("RepoManager", "there was an error.." + cause.getKind().name()); try { String body = new StringConverter().fromBody(cause.getResponse().getBody(), String.class); Log.e("RepoManager", body); } catch (ConversionException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); } APIException apiException = APIException.fromRetrofitError(cause); switch (apiException.getKind()) { case CONVERSION: case UNEXPECTED: { Crashlytics.logException(cause.getCause()); break; } case HTTP: if(apiException.getResponse().getStatus() >= 500) { Crashlytics.logException(cause.getCause()); } else if(apiException.getResponse().getStatus() == 409) { Crashlytics.logException(cause.getCause()); } } return apiException; } } }
bsd-3-clause
myGrid/t2-server-jar
src/test/java/uk/org/taverna/server/client/TestServer.java
3470
/* * Copyright (c) 2010-2013 The University of Manchester, UK. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the names of The University of Manchester nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package uk.org.taverna.server.client; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; import java.net.URI; import java.util.Collection; import org.junit.AfterClass; import org.junit.Test; public class TestServer extends TestBase { @Test public void testServer() { Server server = new Server(serverURI); assertNotNull("Server instance", server); Server other = new Server(serverURI); assertNotNull("Other Server instance", other); assertNotSame("Server objects should not be the same", other, server); URI uri = server.getURI(); assertEquals(serverURI, uri); } @Test public void testServerRunCreationAndCaching() { Server server = new Server(serverURI); byte[] workflow = loadResource(WKF_PASS_FILE); Collection<Run> runs = server.getRuns(user1); int number = runs.size(); Run run = server.createRun(workflow, user1); // Make sure that the run cache changes size when runs are added and // deleted. This also checks that run deletions do not cause any // exceptions when removing things from the cache. runs = server.getRuns(user1); assertTrue("One more run", number == (runs.size() - 1)); run.delete(); runs = server.getRuns(user1); assertTrue("One less run", number == runs.size()); } @Test(expected = ServerAtCapacityException.class) public void testServerLimits() { Server server = new Server(serverURI); int limit = server.getRunLimit(user1); byte[] workflow = loadResource(WKF_PASS_FILE); // Add 1 here so we are sure to go over the limit! for (int i = 0; i < (limit + 1); i++) { server.createRun(workflow, user1); } } @AfterClass public static void deleteAll() { Server server = new Server(serverURI); server.deleteAllRuns(user1); } }
bsd-3-clause
mikandi/fresco
fbcore/src/main/gen/com/facebook/fbcore/BuildConfig.java
261
/*___Generated_by_IDEA___*/ package com.facebook.fbcore; /* This stub is only used by the IDE. It is NOT the BuildConfig class actually packed into the APK */ public final class BuildConfig { public final static boolean DEBUG = Boolean.parseBoolean(null); }
bsd-3-clause
bill-baumgartner/datasource
datasource-identifiers/src/main/java/edu/ucdenver/ccp/datasource/identifiers/other/AsrpId.java
2119
package edu.ucdenver.ccp.datasource.identifiers.other; /* * #%L * Colorado Computational Pharmacology's common module * %% * Copyright (C) 2012 - 2014 Regents of the University of Colorado * %% * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the Regents of the University of Colorado nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * #L% */ import edu.ucdenver.ccp.datasource.identifiers.DataSource; import edu.ucdenver.ccp.datasource.identifiers.StringDataSourceIdentifier; /** * * @author Colorado Computational Pharmacology, UC Denver; ccpsupport@ucdenver.edu * */ public class AsrpId extends StringDataSourceIdentifier { public AsrpId(String resourceID) { super(resourceID, DataSource.ASRP); } }
bsd-3-clause
dhaunac/fictional-spoon
src/game/control/ScreenDecorator.java
564
package game.control; public abstract class ScreenDecorator extends Screen { protected Screen decoratedScreen; public ScreenDecorator(Screen decoratedScreen) { this.decoratedScreen = decoratedScreen; group = decoratedScreen.group; scene = decoratedScreen.scene; nodes = decoratedScreen.nodes; gcs = decoratedScreen.gcs; } @Override public void tick(int ticks) { decoratedScreen.tick(ticks); } @Override public void render() { decoratedScreen.render(); } }
mit
steakdown/barbapapa
app/src/main/java/com/barbapapateam/barbapapa/Database.java
3673
package com.barbapapateam.barbapapa; import android.content.Context; import java.util.Hashtable; import java.util.LinkedList; /** * Created by hugo on 17/04/17. */ public class Database { static LinkedList<Beer> beers; static LinkedList<Command> commands; static boolean initialized = false; private static Hashtable<String, Integer> imageIDs; private static Beer beerForCommand; public static Beer lastBeerOrdered = null; static void initDb(Context context) { imageIDs = new Hashtable<String, Integer>(); imageIDs.put("Kwak", R.drawable.kwak); imageIDs.put("Delirium", R.drawable.delirium); imageIDs.put("Tripel Karmeliet", R.drawable.karmeliet); imageIDs.put("Leffe", R.drawable.leffe); imageIDs.put("Desperados", R.drawable.desperados); imageIDs.put("Kriek", R.drawable.kriek); imageIDs.put("Punk", R.drawable.punk); imageIDs.put("Cuvée des Trolls", R.drawable.trolls); imageIDs.put("1664 Blanc", R.drawable.seize); imageIDs.put("Pêcheresse", R.drawable.pecheresse); imageIDs.put("Elephant", R.drawable.elephant); imageIDs.put("Kronenbourg", R.drawable.kronenbourg); imageIDs.put("Grimbergen Blanche", R.drawable.blanche); imageIDs.put("Grimbergen Double Ambrée", R.drawable.grim_ambree); imageIDs.put("Superbock", R.drawable.superbock); imageIDs.put("San Miguel", R.drawable.sanmiguel); imageIDs.put("Asahi", R.drawable.asahi); imageIDs.put("Brahma", R.drawable.brahma); imageIDs.put("Pilsen Urquell", R.drawable.pilsner_urquell); imageIDs.put("Hoegaarden", R.drawable.hoegaarden); imageIDs.put("Angelus", R.drawable.angelus); imageIDs.put("Duchesse Anne", R.drawable.duchesse_anne); imageIDs.put("Goudale", R.drawable.goudale); imageIDs.put("Queue de charrue", R.drawable.queue_de_charrue); imageIDs.put("Pietra", R.drawable.pietra); imageIDs.put("Bush triple", R.drawable.bush_triple_ambree); imageIDs.put("Orval", R.drawable.orval); imageIDs.put("Big Job", R.drawable.big_job); imageIDs.put("Carolus", R.drawable.carolus); imageIDs.put("Duvel", R.drawable.triple_hop_duvel); imageIDs.put("Fruit défendu", R.drawable.fruit_defendu); imageIDs.put("Gauloise brune", R.drawable.gauloise_brune); imageIDs.put("Mort subite", R.drawable.mort_subite); imageIDs.put("Queue de charrue rouge", R.drawable.queue_rouge); imageIDs.put("BrewDog 5AM saint", R.drawable.fiveam_saint); imageIDs.put("Faro", R.drawable.faro); imageIDs.put("Gueuze", R.drawable.gueuze); imageIDs.put("BrewDog Jet Black Heart", R.drawable.jet_black_heart); imageIDs.put("Page 24", R.drawable.page_24); imageIDs.put("Vezelay Stout", R.drawable.vezelay); imageIDs.put("Kasteel Donker", R.drawable.kasteel_donker); imageIDs.put("Franziskaner", R.drawable.franziskaner); imageIDs.put("La bête", R.drawable.la_bete); beers = Utils.getBeersFromJSON("beers.json", context); commands = new LinkedList<>(); initialized = true; } static void pushCommand(Beer beer, int beerCount, String clientName) { Command c = new Command(beer, beerCount, clientName); commands.push(c); } static int getImageIdFromName(String name) { return imageIDs.get(name); } public static void setBeerForCommand(Beer beer) { beerForCommand = beer; } public static Beer getBeerForCommand() { return beerForCommand; } }
mit
selvasingh/azure-sdk-for-java
sdk/storage/azure-storage-queue/src/main/java/com/azure/storage/queue/implementation/models/ServiceGetStatisticsHeaders.java
4427
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.storage.queue.implementation.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.DateTimeRfc1123; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import java.time.OffsetDateTime; /** * Defines headers for GetStatistics operation. */ @JacksonXmlRootElement(localName = "Service-GetStatistics-Headers") @Fluent public final class ServiceGetStatisticsHeaders { /* * This header uniquely identifies the request that was made and can be * used for troubleshooting the request. */ @JsonProperty(value = "x-ms-request-id") private String requestId; /* * Indicates the version of the Queue service used to execute the request. * This header is returned for requests made against version 2009-09-19 and * above. */ @JsonProperty(value = "x-ms-version") private String version; /* * UTC date/time value generated by the service that indicates the time at * which the response was initiated */ @JsonProperty(value = "Date") private DateTimeRfc1123 dateProperty; /* * The errorCode property. */ @JsonProperty(value = "x-ms-error-code") private String errorCode; /** * Get the requestId property: This header uniquely identifies the request * that was made and can be used for troubleshooting the request. * * @return the requestId value. */ public String getRequestId() { return this.requestId; } /** * Set the requestId property: This header uniquely identifies the request * that was made and can be used for troubleshooting the request. * * @param requestId the requestId value to set. * @return the ServiceGetStatisticsHeaders object itself. */ public ServiceGetStatisticsHeaders setRequestId(String requestId) { this.requestId = requestId; return this; } /** * Get the version property: Indicates the version of the Queue service * used to execute the request. This header is returned for requests made * against version 2009-09-19 and above. * * @return the version value. */ public String getVersion() { return this.version; } /** * Set the version property: Indicates the version of the Queue service * used to execute the request. This header is returned for requests made * against version 2009-09-19 and above. * * @param version the version value to set. * @return the ServiceGetStatisticsHeaders object itself. */ public ServiceGetStatisticsHeaders setVersion(String version) { this.version = version; return this; } /** * Get the dateProperty property: UTC date/time value generated by the * service that indicates the time at which the response was initiated. * * @return the dateProperty value. */ public OffsetDateTime getDateProperty() { if (this.dateProperty == null) { return null; } return this.dateProperty.getDateTime(); } /** * Set the dateProperty property: UTC date/time value generated by the * service that indicates the time at which the response was initiated. * * @param dateProperty the dateProperty value to set. * @return the ServiceGetStatisticsHeaders object itself. */ public ServiceGetStatisticsHeaders setDateProperty(OffsetDateTime dateProperty) { if (dateProperty == null) { this.dateProperty = null; } else { this.dateProperty = new DateTimeRfc1123(dateProperty); } return this; } /** * Get the errorCode property: The errorCode property. * * @return the errorCode value. */ public String getErrorCode() { return this.errorCode; } /** * Set the errorCode property: The errorCode property. * * @param errorCode the errorCode value to set. * @return the ServiceGetStatisticsHeaders object itself. */ public ServiceGetStatisticsHeaders setErrorCode(String errorCode) { this.errorCode = errorCode; return this; } }
mit
diedertimmers/oxAuth
Server/src/main/java/org/xdi/oxauth/register/ws/rs/RegisterRestWebService.java
7875
/* * oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ package org.xdi.oxauth.register.ws.rs; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.annotations.ApiParam; import com.wordnik.swagger.annotations.ApiResponse; import com.wordnik.swagger.annotations.ApiResponses; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; /** * Provides interface for register REST web services. * * @author Javier Rojas Blum * @author Yuriy Zabrovarnyy * @version 0.1, 01.11.2012 */ @Path("/oxauth") @Api(value = "/oxauth", description = "The Client Registration Endpoint is an OAuth 2.0 Protected Resource through which a new Client registration can be requested. The OpenID Provider MAY require an Initial Access Token that is provisioned out-of-band (in a manner that is out of scope for this specification) to restrict registration requests to only authorized Clients or developers.") public interface RegisterRestWebService { /** * In order for an OpenID Connect client to utilize OpenID services for a user, the client needs to register with * the OpenID Provider to acquire a client ID and shared secret. * * @param requestParams request parameters * @param authorization authorization * @param httpRequest http request object * @param securityContext An injectable interface that provides access to security related information. * @return response */ @POST @Path("/register") @Produces({MediaType.APPLICATION_JSON}) @ApiOperation( value = "Registers new client dynamically.", notes = "Registers new client dynamically.", response = Response.class ) @ApiResponses(value = { @ApiResponse(code = 400, message = "invalid_request\n" + "The request is missing a required parameter, includes an unsupported parameter or parameter value, repeats the same parameter, uses more than one method for including an access token, or is otherwise malformed. The resource server SHOULD respond with the HTTP 400 (Bad Request) status code."), @ApiResponse(code = 400, message = "invalid_redirect_uri\n" + "The value of one or more redirect_uris is invalid. "), @ApiResponse(code = 400, message = "invalid_client_metadata\n" + "The value of one of the Client Metadata fields is invalid and the server has rejected this request. Note that an Authorization Server MAY choose to substitute a valid value for any requested parameter of a Client's Metadata."), @ApiResponse(code = 302, message = "access_denies\n" + "The authorization server denied the request.") }) Response requestRegister( @ApiParam(value = "Request parameters as JSON object with data described by Connect Client Registration Specification. ", required = true) String requestParams, @HeaderParam("Authorization") String authorization, @Context HttpServletRequest httpRequest, @Context SecurityContext securityContext); /** * This operation updates the Client Metadata for a previously registered client. * * @param requestParams request parameters * @param clientId client id * @param authorization Access Token that is used at the Client Configuration Endpoint * @param httpRequest http request object * @param securityContext An injectable interface that provides access to security related information. * @return response */ @PUT @Path("register") @Produces({MediaType.APPLICATION_JSON}) @ApiOperation( value = "Updates client info.", notes = "Updates client info.", response = Response.class, responseContainer = "JSON" ) @ApiResponses(value = { @ApiResponse(code = 400, message = "invalid_request\n" + "The request is missing a required parameter, includes an unsupported parameter or parameter value, repeats the same parameter, uses more than one method for including an access token, or is otherwise malformed. The resource server SHOULD respond with the HTTP 400 (Bad Request) status code."), @ApiResponse(code = 400, message = "invalid_redirect_uri\n" + "The value of one or more redirect_uris is invalid. "), @ApiResponse(code = 400, message = "invalid_client_metadata\n" + "The value of one of the Client Metadata fields is invalid and the server has rejected this request. Note that an Authorization Server MAY choose to substitute a valid value for any requested parameter of a Client's Metadata."), @ApiResponse(code = 302, message = "access_denies\n" + "The authorization server denied the request.") }) Response requestClientUpdate( @ApiParam(value = "Request parameters as JSON object with data described by Connect Client Registration Specification. ", required = true) String requestParams, @QueryParam("client_id") @ApiParam(value = "Client ID that identifies client that must be updated by this request.", required = true) String clientId, @HeaderParam("Authorization") String authorization, @Context HttpServletRequest httpRequest, @Context SecurityContext securityContext); /** * This operation retrieves the Client Metadata for a previously registered client. * * @param clientId Unique Client identifier. * @param securityContext An injectable interface that provides access to security related information. * @return response */ @GET @Path("/register") @Produces({MediaType.APPLICATION_JSON}) @ApiOperation( value = "Reads client info.", notes = "Reads client info.", response = Response.class, responseContainer = "JSON" ) @ApiResponses(value = { @ApiResponse(code = 400, message = "invalid_request\n" + "The request is missing a required parameter, includes an unsupported parameter or parameter value, repeats the same parameter, uses more than one method for including an access token, or is otherwise malformed. The resource server SHOULD respond with the HTTP 400 (Bad Request) status code."), @ApiResponse(code = 400, message = "invalid_redirect_uri\n" + "The value of one or more redirect_uris is invalid. "), @ApiResponse(code = 400, message = "invalid_client_metadata\n" + "The value of one of the Client Metadata fields is invalid and the server has rejected this request. Note that an Authorization Server MAY choose to substitute a valid value for any requested parameter of a Client's Metadata."), @ApiResponse(code = 302, message = "access_denies\n" + "The authorization server denied the request.") }) Response requestClientRead( @QueryParam("client_id") @ApiParam(value = "Client ID that identifies client.", required = true) String clientId, @HeaderParam("Authorization") String authorization, @Context HttpServletRequest httpRequest, @Context SecurityContext securityContext); }
mit
navalev/azure-sdk-for-java
sdk/network/mgmt-v2019_08_01/src/main/java/com/microsoft/azure/management/network/v2019_08_01/VpnDeviceScriptParameters.java
2389
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2019_08_01; import com.fasterxml.jackson.annotation.JsonProperty; /** * Vpn device configuration script generation parameters. */ public class VpnDeviceScriptParameters { /** * The vendor for the vpn device. */ @JsonProperty(value = "vendor") private String vendor; /** * The device family for the vpn device. */ @JsonProperty(value = "deviceFamily") private String deviceFamily; /** * The firmware version for the vpn device. */ @JsonProperty(value = "firmwareVersion") private String firmwareVersion; /** * Get the vendor for the vpn device. * * @return the vendor value */ public String vendor() { return this.vendor; } /** * Set the vendor for the vpn device. * * @param vendor the vendor value to set * @return the VpnDeviceScriptParameters object itself. */ public VpnDeviceScriptParameters withVendor(String vendor) { this.vendor = vendor; return this; } /** * Get the device family for the vpn device. * * @return the deviceFamily value */ public String deviceFamily() { return this.deviceFamily; } /** * Set the device family for the vpn device. * * @param deviceFamily the deviceFamily value to set * @return the VpnDeviceScriptParameters object itself. */ public VpnDeviceScriptParameters withDeviceFamily(String deviceFamily) { this.deviceFamily = deviceFamily; return this; } /** * Get the firmware version for the vpn device. * * @return the firmwareVersion value */ public String firmwareVersion() { return this.firmwareVersion; } /** * Set the firmware version for the vpn device. * * @param firmwareVersion the firmwareVersion value to set * @return the VpnDeviceScriptParameters object itself. */ public VpnDeviceScriptParameters withFirmwareVersion(String firmwareVersion) { this.firmwareVersion = firmwareVersion; return this; } }
mit
DevOpsDistilled/OpERP
OpERP/src/main/java/devopsdistilled/operp/server/data/repo/commons/ContactInfoRepository.java
337
package devopsdistilled.operp.server.data.repo.commons; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import devopsdistilled.operp.server.data.entity.commons.ContactInfo; @Repository public interface ContactInfoRepository extends JpaRepository<ContactInfo, Long> { }
mit
takzhanov/java-game-server
src/main/java/io/github/takzhanov/game/service/SaxHandler.java
1730
package io.github.takzhanov.game.service; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * @author v.chibrikov * <p> * Пример кода для курса на https://stepic.org/ * <p> * Описание курса и лицензия: https://github.com/vitaly-chibrikov/stepic_java_webserver */ @SuppressWarnings("UnusedDeclaration") public class SaxHandler extends DefaultHandler { private static final String CLASSNAME = "class"; private String element = null; private Object object = null; public void startDocument() throws SAXException { System.out.println("Start document"); } public void endDocument() throws SAXException { System.out.println("End document "); } public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (!qName.equals(CLASSNAME)) { element = qName; } else { String className = attributes.getValue(0); System.out.println("Class name: " + className); object = ReflectionHelper.createInstance(className); } } public void endElement(String uri, String localName, String qName) throws SAXException { element = null; } public void characters(char ch[], int start, int length) throws SAXException { if (element != null) { String value = new String(ch, start, length); System.out.println(element + " = " + value); ReflectionHelper.setFieldValue(object, element, value); } } public Object getObject() { return object; } }
mit
mauriciotogneri/watch-face-sectors
common/src/main/java/com/mauriciotogneri/watchfacesectors/Preferences.java
1694
package com.mauriciotogneri.watchfacesectors; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Base64; public class Preferences { private final SharedPreferences sharedPreferences; private static Preferences instance; private static final String KEY_PROFILE = "KEY_PROFILE"; private Preferences(Context context) { this.sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); } public static synchronized Preferences getInstance(Context context) { if (instance == null) { instance = new Preferences(context); } return instance; } @SuppressLint("CommitPrefEdits") private void save(String key, byte[] value) { String stringValue = Base64.encodeToString(value, Base64.DEFAULT); sharedPreferences.edit().putString(key, stringValue).commit(); } private byte[] get(String key) { String stringValue = sharedPreferences.getString(key, null); return (stringValue != null) ? Base64.decode(stringValue, Base64.DEFAULT) : null; } public synchronized void saveProfile(Profile profile) { save(KEY_PROFILE, Serializer.serialize(profile)); } public synchronized Profile getProfile() { byte[] data = get(KEY_PROFILE); if (data != null) { Profile profile = Serializer.deserialize(data); return (profile != null) ? profile : new Profile(); } else { return new Profile(); } } }
mit
metamx/d8a-conjure
src/main/java/io/d8a/conjure/DoubleSpec.java
572
package io.d8a.conjure; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class DoubleSpec extends Spec{ @JsonCreator public DoubleSpec( @JsonProperty("count") int count, @JsonProperty("cardinality") int cardinality, @JsonProperty("name") String name ){ super(count, cardinality, name); } @Override public CardinalityNode createNewNode(String name, int cardinality){ return new DoubleCardinalityNode(name, cardinality); } }
mit
color-coding/ibas-framework
bobas.businessobjectscommon/src/main/java/org/colorcoding/ibas/bobas/core/IPropertyInfo.java
302
package org.colorcoding.ibas.bobas.core; /** * 属性信息 */ public interface IPropertyInfo<P> { /** * 属性名称 */ String getName(); /** * 索引 */ int getIndex(); /** * 值的类型 */ java.lang.Class<?> getValueType(); /** * 默认值 */ P getDefaultValue(); }
mit
treejames/JMD
src/org/apache/bcel/classfile/ConstantMethodref.java
2146
/* * Copyright 2000-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.bcel.classfile; import java.io.DataInputStream; import java.io.IOException; import org.apache.bcel.Constants; /** * This class represents a constant pool reference to a method. * * @version $Id: ConstantMethodref.java 386056 2006-03-15 11:31:56Z tcurdt $ * @author <A HREF="mailto:m.dahm@gmx.de">M. Dahm</A> */ public final class ConstantMethodref extends ConstantCP { /** * Initialize from another object. */ public ConstantMethodref(ConstantMethodref c) { super(Constants.CONSTANT_Methodref, c.getClassIndex(), c.getNameAndTypeIndex()); } /** * Initialize instance from file data. * * @param file input stream * @throws IOException */ ConstantMethodref(DataInputStream file) throws IOException { super(Constants.CONSTANT_Methodref, file); } /** * @param class_index Reference to the class containing the method * @param name_and_type_index and the method signature */ public ConstantMethodref(int class_index, int name_and_type_index) { super(Constants.CONSTANT_Methodref, class_index, name_and_type_index); } /** * Called by objects that are traversing the nodes of the tree implicitely * defined by the contents of a Java class. I.e., the hierarchy of methods, * fields, attributes, etc. spawns a tree of objects. * * @param v Visitor object */ public void accept( Visitor v ) { v.visitConstantMethodref(this); } }
mit
navalev/azure-sdk-for-java
sdk/mediaservices/mgmt-v2019_05_01_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2019_05_01_preview/JobState.java
1795
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.mediaservices.v2019_05_01_preview; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for JobState. */ public final class JobState extends ExpandableStringEnum<JobState> { /** Static value Canceled for JobState. */ public static final JobState CANCELED = fromString("Canceled"); /** Static value Canceling for JobState. */ public static final JobState CANCELING = fromString("Canceling"); /** Static value Error for JobState. */ public static final JobState ERROR = fromString("Error"); /** Static value Finished for JobState. */ public static final JobState FINISHED = fromString("Finished"); /** Static value Processing for JobState. */ public static final JobState PROCESSING = fromString("Processing"); /** Static value Queued for JobState. */ public static final JobState QUEUED = fromString("Queued"); /** Static value Scheduled for JobState. */ public static final JobState SCHEDULED = fromString("Scheduled"); /** * Creates or finds a JobState from its string representation. * @param name a name to look for * @return the corresponding JobState */ @JsonCreator public static JobState fromString(String name) { return fromString(name, JobState.class); } /** * @return known JobState values */ public static Collection<JobState> values() { return values(JobState.class); } }
mit
arminnh/Telecom-Distr.Systems-Project
distributed-systems/build-your-own-middleware/src/server/RemoteReferenceModule.java
984
package server; import java.util.HashMap; import java.util.Map; /* * We will first create the RemoteReferenceModule class on the server side. * Its most important function is to keep track of the server objects * that have been registered in the platform. */ public class RemoteReferenceModule { //remote object reference table Map<String, Object> remoteObjects = new HashMap<String, Object>(); public String register(Object remoteObject) { String name = remoteObject.getClass().getSimpleName(); if (remoteObjects.containsKey(name)) { // refuse to store more than one object of the same type, since we're using the singleton pattern return name; } remoteObjects.put(name, remoteObject); System.out.println("RemoteReferenceModule registered: " + name); return name; } public Object retrieve(String remoteObjectName) { System.out.println("RemoteReferenceModule.retrieve: " + remoteObjectName); return remoteObjects.get(remoteObjectName); } }
mit
overleaf/writelatex-git-bridge
src/main/java/uk/ac/ic/wlgitbridge/util/BiConsumerT.java
219
package uk.ac.ic.wlgitbridge.util; /** * BiConsumer interface that allows checked exceptions. */ @FunctionalInterface public interface BiConsumerT<T, U, E extends Throwable> { void accept(T t, U u) throws E; }
mit
dittma75/compiler-design
wolf_compiler/submission/wolf/src/wolf/SemanticTypeCheck.java
27080
package wolf; import wolf.interfaces.EscapeChar; import java.util.ArrayList; import java.util.List; import java.util.Stack; import wolf.enums.*; import wolf.interfaces.*; import wolf.node.*; /** * Type Checking * * @author Kevin Dittmar * @author William Ezekiel * @version Apr 10, 2016 */ public class SemanticTypeCheck implements Visitor { List<SymbolTable> tables; SymbolTable program_table; SymbolTable current_def_table; Stack<String> last_table_names; List<SymbolTable> lambda_table_list; WolfFunction main_function; public SemanticTypeCheck(List<SymbolTable> tables, SymbolTable program_table, List<SymbolTable> lambda_table_list) { this.tables = tables; this.program_table = this.current_def_table = program_table; last_table_names = new Stack<>(); this.lambda_table_list = lambda_table_list; } /** * Visit a program * * @param n a program * @return the given program */ @Override public Object visit(Program n) { for (Def def : n.def_list) { last_table_names.push(current_def_table.table_name); current_def_table = getTableWithName(def.def_name.identifier.getText()); def.accept(this); current_def_table = getTableWithName(last_table_names.pop()); } main_function = n.function; n.function.accept(this); System.out.println("Type Checking Completed Successfully!"); return n; } /** * Visit a definition * * @param n a definition object (Def) * @return the return type of the function definition */ @Override public Type visit(Def n) { Type actual_type = (Type) n.function.accept(this); Type expected_type = n.type; if (!expected_type.equals(actual_type)) { String def_name = n.def_name.identifier.getText(); TypeErrorReporter.mismatchDefType( actual_type, expected_type, def_name); } return expected_type; } /** * Visit a function signature * * @param n a signature (Sig) * @return null, nothing to do in SemanticTypeCheck */ @Override public Type visit(Sig n) { // do nothing, return null return null; } /** * Visit a signature argument. * * @param n is the SigArg to visit * @return null, nothing to do in SemanticTypeCheck */ @Override public Type visit(SigArg n) { //do nothing, return null return null; } /** * Visit a user function. * * @param n a user function * @return the return type of the user function */ @Override public Type visit(UserFunc n) { Type type; if (n.user_func_name instanceof Identifier) { Identifier id = (Identifier) n.user_func_name; last_table_names.push(current_def_table.table_name); current_def_table = getTableWithName(id.identifier.getText()); type = (Type) n.user_func_name.accept(this); n.setType(type); n.arg_list.accept(this); current_def_table = getTableWithName(last_table_names.pop()); } else if (n.user_func_name instanceof WolfLambda) { //Save the current scope. last_table_names.push(current_def_table.table_name); //Get the lambda and its corresponding table. WolfLambda lambda = (WolfLambda) n.user_func_name; current_def_table = lambda_table_list.get(lambda.getId()); //Check the lambda's arguments. n.arg_list.accept(this); //Reset the scope current_def_table = getTableWithName(last_table_names.pop()); //Get the lambda's return type type = visitLambda((WolfLambda) n.user_func_name); n.setType(type); } else { throw new IllegalArgumentException("Invalid UserFunc"); } return type; } /** * Visit a branch * * @param n a branch * @return the return type of the branch */ @Override public Type visit(Branch n) { Type cond_type = (Type) n.condition.accept(this); if (!cond_type.equals(new Type(FlatType.INTEGER))) { TypeErrorReporter.mismatchBranchCondition(cond_type); } Type trueType = (Type) n.true_branch.accept(this); n.true_branch.setType(trueType); Type falseType = (Type) n.false_branch.accept(this); n.false_branch.setType(falseType); if (!(trueType.equals(falseType))) { TypeErrorReporter.mismatchBranchTrueFalse(trueType, falseType); } return trueType; } /** * Visit a lambda in the WOLF language * * @param n a lambda object (WolfLambda) * @return type of lambda */ @Override public Type visit(WolfLambda n) { if (n.sig != null) { n.sig.accept(this); } SymbolTable lambda_table = lambda_table_list.get(n.getId()); SymbolTable parent_table = lambda_table.parent_table; last_table_names.add(current_def_table.table_name); current_def_table = lambda_table; if (n.function != null) { n.function.accept(this); } current_def_table = getTableWithName(last_table_names.pop()); Type type = parent_table.symbol_table.get( lambda_table.table_name ).table_value.type; n.setType(type); return type; } /** * Visit a fold function * * @param n a fold function * @return the return type of the fold */ @Override public Type visit(Fold n) { n.fold_symbol.accept(this); Type type = (Type) n.fold_body.accept(this); n.setType(type); return type; } /** * Visit a fold symbol * * @param n a fold symbol * @return null, never needed in SemanticTypeCheck */ @Override public Type visit(FoldSymbol n) { // do nothing, return null return null; } /** * Visit a fold body * * @param n a fold body * @return the return type of the fold */ @Override public Type visit(FoldBody n) { Object type_object = n.bin_op.accept(this); Type arg_type = (Type) n.list_argument.accept(this); if (!arg_type.is_list) { TypeErrorReporter.noListArgument("Fold", arg_type); } //There's a single valid type for the operation. if (type_object instanceof Type) { Type valid_type = (Type) type_object; if (valid_type.equals(new Type(arg_type.flat_type))) { return arg_type; } } //The operation supports several different types else if (type_object instanceof List) { List<Type> valid_types = (List<Type>) type_object; if (valid_types.contains(new Type(arg_type.flat_type))) { return new Type(arg_type.flat_type); } } throw new UnsupportedOperationException( n.bin_op + " does not accept " + arg_type); } /** * Visit a mapping function in the WOLF language * * @param n a mapping function object (WolfMap) * @return the return type of the map */ @Override public Type visit(WolfMap n) { Object type_object = n.unary_op.accept(this); Type arg_type = (Type) n.list_argument.accept(this); if (!arg_type.is_list) { TypeErrorReporter.noListArgument("Map", arg_type); } //There's a single valid type for the operation. if (type_object instanceof Type) { Type valid_type = (Type) type_object; if (valid_type.equals(new Type(arg_type.flat_type))) { Type type = new Type(arg_type.flat_type); n.setType(type); return type; } } //The operation supports several different types else if (type_object instanceof List) { List<Type> valid_types = (List<Type>) type_object; if (valid_types.contains(new Type(arg_type.flat_type))) { n.setType(arg_type); return arg_type; } } throw new UnsupportedOperationException( n.unary_op + " does not accept " + arg_type); } /** * Visit a list of arguments for a list. * * @param n a list of arguments for a list (ListArgs) * @return the type of the list. */ @Override public Type visit(ListArgsList n) { Type type = null; for (Arg arg : n.getArgList()) { Type next_type = (Type) arg.accept(this); if (type != null && !type.equals(next_type)) { throw new IllegalArgumentException("List has multiple types: " + type.toString() + " and " + next_type.toString()); } type = next_type; arg.setType(type); } return type; } /** * Visit a list of arguments. * * @param n a list of arguments (Args) * @return null, the type returned does not matter. */ @Override public Type visit(ArgsList n) { List<Type> actualArgFormat = new ArrayList(); for (Arg arg : n.getArgList()) { Type type = (Type) arg.accept(this); actualArgFormat.add(type); arg.setType(type); } List<Type> expectedArgFormat = current_def_table.getArgFormat(); //Must have same number of arguments AND argument types //must be the same if (!actualArgFormat.equals(expectedArgFormat)) { TypeErrorReporter.mismatchArgumentFormat(actualArgFormat, expectedArgFormat, current_def_table.table_name); } return null; } /** * Visit a native unary operator that can have either list or non-list * arguments depending on the operation. * * @param n a native unary * @return the type the native unary should return */ public Type visit(NativeUnary n) { Type arg_type = (Type) n.arg.accept(this); n.setType(arg_type); switch (n.unary_op) { case NEG: if (!arg_type.isNumeric()) { System.err.println("Invalid Argument " + arg_type + " for " + "~. Expecting Integer or Float."); return null; } return arg_type; case LOGICAL_NOT: if (arg_type.flat_type != FlatType.INTEGER) { System.err.println("Invalid Argument " + arg_type + " for " + "!. Expecting Integer."); return null; } return arg_type; case IDENTITY: case PRINT: return arg_type; default: System.err.println("Invalid Native Unary Operation"); return null; } } /** * Visit a native unary operator that has a list argument. * * @param n a native list unary * @return the type the native list unary should return */ @Override public Type visit(NativeListUnary n) { Type arg_type = (Type) n.list_argument.accept(this); Type return_type = null; switch (n.list_unary_op) { case HEAD: if (!arg_type.is_list) { TypeErrorReporter.mismatchErrorListUnary( n.list_argument, arg_type, n.list_unary_op.toString(), null ); } return_type = new Type(arg_type.flat_type); n.setType(return_type); return return_type; case TAIL: if (!arg_type.is_list) { TypeErrorReporter.mismatchErrorListUnary( n.list_argument, arg_type, n.list_unary_op.toString(), null ); } n.setType(arg_type); return arg_type; case REVERSE: if (!arg_type.is_list) { TypeErrorReporter.mismatchErrorListUnary( n.list_argument, arg_type, n.list_unary_op.toString(), null ); } n.setType(arg_type); return arg_type; case LAST: if (!arg_type.is_list) { TypeErrorReporter.mismatchErrorListUnary( n.list_argument, arg_type, n.list_unary_op.toString(), null ); } return_type = new Type(arg_type.flat_type); n.setType(return_type); return return_type; case LENGTH: if (!arg_type.is_list) { TypeErrorReporter.mismatchErrorListUnary( n.list_argument, arg_type, n.list_unary_op.toString(), null ); } return_type = new Type(FlatType.INTEGER); n.setType(return_type); return return_type; default: System.err.println("Invalid Native List Unary Operation"); return null; } } /** * Visit a native binary operator that can have either list or non-list * arguments depending on the operation. * * @param n a native binary * @return the type the native binary should return */ @Override public Type visit(NativeBinary n) { Type left_type = (Type) n.arg_left.accept(this); Type right_type = (Type) n.arg_right.accept(this); boolean areSameType = (left_type.equals(right_type) || (left_type.isNumeric() && right_type.isNumeric())); Type return_type = null; switch (n.binary_op) { case PLUS: case MINUS: if (!areSameType) { TypeErrorReporter.mismatchArgTypes( n.arg_left, left_type, n.arg_right, right_type ); } return_type = determineReturnType(left_type, right_type); n.setType(return_type); return return_type; case MULT: case DIV: case MOD: if (!left_type.isNumeric() || !right_type.isNumeric()) { ArrayList<Type> types = new ArrayList<>(); types.add(new Type(FlatType.INTEGER)); types.add(new Type(FlatType.FLOAT)); TypeErrorReporter.mismatchErrorBinary( n.arg_left, left_type, n.arg_right, right_type, n.binary_op.toString(), types ); } return_type = determineReturnType(left_type, right_type); n.setType(return_type); return return_type; case LT: case GT: case LTE: case GTE: if (!left_type.isNumeric() || !right_type.isNumeric()) { ArrayList<Type> types = new ArrayList<>(); types.add(new Type(FlatType.INTEGER)); types.add(new Type(FlatType.FLOAT)); TypeErrorReporter.mismatchErrorBinary( n.arg_left, left_type, n.arg_right, right_type, n.binary_op.toString(), types); } return_type = new Type(FlatType.INTEGER); n.setType(return_type); return return_type; case AND: case OR: case XOR: if (left_type.flat_type != FlatType.INTEGER || right_type.flat_type != FlatType.INTEGER) { ArrayList<Type> types = new ArrayList<>(); types.add(new Type(FlatType.INTEGER)); TypeErrorReporter.mismatchErrorBinary( n.arg_left, left_type, n.arg_right, right_type, n.binary_op.toString(), types); } return_type = new Type(FlatType.INTEGER); n.setType(return_type); return return_type; case EQUAL: case NOT_EQUAL: return_type = new Type(FlatType.INTEGER); n.setType(return_type); return return_type; default: System.err.println("Invalid Binary Operator!"); return null; } } /** * Visit a native binary that one non-list and one list argument * * @param n a native list binary * @return the type the native list binary should return */ @Override public Type visit(NativeListBinary n) { Type arg_type = (Type) n.arg.accept(this); Type list_type = (Type) n.list_argument.accept(this); switch (n.binary_op) { case APPEND: case PREPEND: if (!list_type.is_list || !arg_type.flat_type.equals(list_type.flat_type)) { List<Type> list_types = new ArrayList<>(); list_types.add(list_type); List<Type> arg_types = new ArrayList<>(); arg_types.add(new Type(list_type.flat_type)); TypeErrorReporter.mismatchErrorBinaryList( n.arg, arg_type, n.list_argument, list_type, n.binary_op.toString(), arg_types, list_types ); } n.setType(list_type); return list_type; default: System.err.println("Invalid Native List Binary Operation!"); return null; } } /** * Visit an identifier * * @param n an identifier * @return the type of the identifier An identifier can be anything, it * depends on the context of the function. Identifiers are only used for * user-defined functions and their parameters, which have user-specified * types */ @Override public Type visit(Identifier n) { TableValue tv = null; Binding binding = current_def_table.lookup(n); if (binding == null) { binding = getTableWithName(last_table_names.peek()).lookup(n); } if (binding == null) { SymbolTable parent = current_def_table.parent_table; while (parent != null && tv == null) { binding = parent.lookup(n); if (binding == null) { parent = parent.parent_table; } else { tv = binding.table_value; } } } else { tv = binding.table_value; } if (tv == null) { return null; } return tv.type; } /** * Visit a float literal * * @param n a float literal * @return the FLOAT type */ public Type visit(FloatLiteral n) { return new Type(FlatType.FLOAT); } /** * Visit an integer literal * * @param n an integer literal * @return the INTEGER type */ @Override public Type visit(IntLiteral n) { return new Type(FlatType.INTEGER); } /** * Visit a list in the WOLF language * * @param n a list object (WolfList) * @return the X_LIST type where X is either FLOAT, INTEGER, or STRING, or * null if the list is empty. */ @Override public Type visit(WolfList n) { Type list_type = null; for (ListElement element : n.list_elements) { Type element_type = (Type) element.accept(this); if (list_type != null) { if (!element_type.equals(list_type)) { TypeErrorReporter.mismatchListItemWithListType( element, element_type, list_type); } } else { // set list type on first element list_type = element_type; } } if (list_type == null) { return null; } Type return_type = new Type(list_type.flat_type, true); n.setType(return_type); return return_type; } /** * Visit a string in the WOLF language * * @param n a string object (WolfString) * @return the STRING type */ @Override public Type visit(WolfString n) { for (StringMiddle sm : n.string) { sm.accept(this); } Type return_type = new Type(FlatType.STRING); n.setType(return_type); return return_type; } /** * Visit a string body * * @param n a string body * @return null, no use in SemanticTypeCheck */ @Override public Type visit(StringBody n) { // do nothing, return null return null; } /** * Visit a string escape sequence * * @param n a string escape sequence * @return null, no use in SemanticTypeCheck */ @Override public Type visit(StringEscapeSeq n) { // do nothing, return null return null; } /** * Visit a native binary operator. * * @param n the native binary operator * @return a list of valid types for the operator. */ @Override public List<Type> visit(NativeBinOp n) { List<Type> valid_types = new ArrayList(); Class token_class = n.getTokenClass(); valid_types.add(new Type(FlatType.INTEGER)); if (!token_class.equals(TXor.class) && !token_class.equals(TOr.class) && !token_class.equals(TAnd.class) && !token_class.equals(TNotEqual.class) && !token_class.equals(TEqual.class) && !token_class.equals(TGte.class) && !token_class.equals(TLte.class) && !token_class.equals(TGt.class) && !token_class.equals(TLt.class)) { valid_types.add(new Type(FlatType.FLOAT)); if (!token_class.equals(TMod.class) && !token_class.equals(TDiv.class) && !token_class.equals(TMult.class)) { valid_types.add(new Type(FlatType.STRING)); if (!token_class.equals(TPlus.class) && !token_class.equals(TMinus.class)) { return null; } } } return valid_types; } /** * Visit a native unary operator. * * @param n the native unary operator * @return a list of valid types for the operator. */ @Override public List<Type> visit(NativeUnaryOp n) { List<Type> valid_types = new ArrayList<>(); Class token_class = n.getTokenClass(); valid_types.add(new Type(FlatType.INTEGER)); if (!token_class.equals(TLogicalNot.class)) { valid_types.add(new Type(FlatType.FLOAT)); if (!token_class.equals(TNeg.class)) { valid_types.add(new Type(FlatType.STRING)); if (!token_class.equals(TPrint.class) && !token_class.equals(TIdentity.class)) { return null; } } } return valid_types; } /** * Get a table from the table list based on its name. * * @param name the table name * @return the table with the given name or null if none exists. */ public SymbolTable getTableWithName(String name) { for (SymbolTable table : tables) { if (table.table_name.equals(name)) { return table; } } return null; } /** * Get a table from the list of lambda tables. * * @param name the table name * @return the table with the given name or null if none exists. */ public SymbolTable getLambdaTableWithName(String name) { for (SymbolTable table : lambda_table_list) { if (table.table_name.equals(name)) { return table; } } return null; } /** * Saves current table state, changes to lambda scope, visits lambda, and * then returns to the original scope before returning the type. * * @param lambda * @return the type of the lambda */ private Type visitLambda(WolfLambda lambda) { last_table_names.push(current_def_table.table_name); current_def_table = lambda_table_list.get(lambda.getId()); Type return_type = visit(lambda); current_def_table = getTableWithName(last_table_names.pop()); return return_type; } /** * @param n is the type to visit * @return null because Type has no purpose here. */ @Override public Type visit(Type n) { return null; } /** * Note: Actual type of InputArg is not available until runtime, so there is * extra type-checking to do later. * * @param n is an input argument * @return the type of the input argument */ @Override public Type visit(InputArg n) { WolfFunction owner = n.getOwningFunction(); while (owner != null) { if (owner == main_function) { return n.type; } owner = owner.getOwningFunction(); } throw new IllegalArgumentException( "Command line arguments can only be used in the main function." ); } /** * Used to determine the return type for binary operators * * @param left is the type of the left arg * @param right is the type of the right arg * @return the return type */ private Type determineReturnType(Type left, Type right) { // String takes precedence over numbers if (left.flat_type.equals(FlatType.STRING)) { return left; } else if (right.flat_type.equals(FlatType.STRING)) { return right; // Integers take precedence over floats } else if (left.flat_type.equals(FlatType.INTEGER)) { return left; } else if (right.flat_type.equals(FlatType.INTEGER)) { return right; // Both types are floats, so returning either returns the float type. } else { return left; } } }
mit
nantoka/ocr_sudoku
src/org/opencv/core/TermCriteria.java
2843
package org.opencv.core; /** * <p>Template class defining termination criteria for iterative algorithms.</p> * * @see <a href="http://docs.opencv.org/modules/core/doc/basic_structures.html#termcriteria">org.opencv.core.TermCriteria</a> */ public class TermCriteria { /** * The maximum number of iterations or elements to compute */ public static final int COUNT = 1; /** * The maximum number of iterations or elements to compute */ public static final int MAX_ITER = COUNT; /** * The desired accuracy threshold or change in parameters at which the iterative algorithm is terminated. */ public static final int EPS = 2; public int type; public int maxCount; public double epsilon; /** * Termination criteria for iterative algorithms. * * @param type * the type of termination criteria: COUNT, EPS or COUNT + EPS. * @param maxCount * the maximum number of iterations/elements. * @param epsilon * the desired accuracy. */ public TermCriteria(int type, int maxCount, double epsilon) { this.type = type; this.maxCount = maxCount; this.epsilon = epsilon; } /** * Termination criteria for iterative algorithms. */ public TermCriteria() { this(0, 0, 0.0); } public TermCriteria(double[] vals) { set(vals); } public void set(double[] vals) { if (vals != null) { type = vals.length > 0 ? (int) vals[0] : 0; maxCount = vals.length > 1 ? (int) vals[1] : 0; epsilon = vals.length > 2 ? (double) vals[2] : 0; } else { type = 0; maxCount = 0; epsilon = 0; } } public TermCriteria clone() { return new TermCriteria(type, maxCount, epsilon); } @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(type); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(maxCount); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(epsilon); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof TermCriteria)) return false; TermCriteria it = (TermCriteria) obj; return type == it.type && maxCount == it.maxCount && epsilon == it.epsilon; } @Override public String toString() { if (this == null) return "null"; return "{ type: " + type + ", maxCount: " + maxCount + ", epsilon: " + epsilon + "}"; } }
mit
dafe/Sentiment
news-linker/src/main/generated/com/gofish/sentiment/newslinker/NewsLinkerServiceVertxEBProxy.java
5887
/* * Copyright 2014 Red Hat, Inc. * * Red Hat licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.gofish.sentiment.newslinker; import com.gofish.sentiment.newslinker.NewsLinkerService; import io.vertx.core.eventbus.DeliveryOptions; import io.vertx.core.Vertx; import io.vertx.core.Future; import io.vertx.core.json.JsonObject; import io.vertx.core.json.JsonArray; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.function.Function; import io.vertx.serviceproxy.ProxyHelper; import io.vertx.serviceproxy.ServiceException; import io.vertx.serviceproxy.ServiceExceptionMessageCodec; import com.gofish.sentiment.newslinker.NewsLinkerService; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; /* Generated Proxy code - DO NOT EDIT @author Roger the Robot */ @SuppressWarnings({"unchecked", "rawtypes"}) public class NewsLinkerServiceVertxEBProxy implements NewsLinkerService { private Vertx _vertx; private String _address; private DeliveryOptions _options; private boolean closed; public NewsLinkerServiceVertxEBProxy(Vertx vertx, String address) { this(vertx, address, null); } public NewsLinkerServiceVertxEBProxy(Vertx vertx, String address, DeliveryOptions options) { this._vertx = vertx; this._address = address; this._options = options; try { this._vertx.eventBus().registerDefaultCodec(ServiceException.class, new ServiceExceptionMessageCodec()); } catch (IllegalStateException ex) {} } public void linkEntities(JsonObject document, Handler<AsyncResult<JsonObject>> resultHandler) { if (closed) { resultHandler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed"))); return; } JsonObject _json = new JsonObject(); _json.put("document", document); DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions(); _deliveryOptions.addHeader("action", "linkEntities"); _vertx.eventBus().<JsonObject>send(_address, _json, _deliveryOptions, res -> { if (res.failed()) { resultHandler.handle(Future.failedFuture(res.cause())); } else { resultHandler.handle(Future.succeededFuture(res.result().body())); } }); } public void getTimeout(Handler<AsyncResult<Long>> timeoutHandler) { if (closed) { timeoutHandler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed"))); return; } JsonObject _json = new JsonObject(); DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions(); _deliveryOptions.addHeader("action", "getTimeout"); _vertx.eventBus().<Long>send(_address, _json, _deliveryOptions, res -> { if (res.failed()) { timeoutHandler.handle(Future.failedFuture(res.cause())); } else { timeoutHandler.handle(Future.succeededFuture(res.result().body())); } }); } public void setTimeout(Long delay) { if (closed) { throw new IllegalStateException("Proxy is closed"); } JsonObject _json = new JsonObject(); _json.put("delay", delay); DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions(); _deliveryOptions.addHeader("action", "setTimeout"); _vertx.eventBus().send(_address, _json, _deliveryOptions); } private List<Character> convertToListChar(JsonArray arr) { List<Character> list = new ArrayList<>(); for (Object obj: arr) { Integer jobj = (Integer)obj; list.add((char)(int)jobj); } return list; } private Set<Character> convertToSetChar(JsonArray arr) { Set<Character> set = new HashSet<>(); for (Object obj: arr) { Integer jobj = (Integer)obj; set.add((char)(int)jobj); } return set; } private <T> Map<String, T> convertMap(Map map) { if (map.isEmpty()) { return (Map<String, T>) map; } Object elem = map.values().stream().findFirst().get(); if (!(elem instanceof Map) && !(elem instanceof List)) { return (Map<String, T>) map; } else { Function<Object, T> converter; if (elem instanceof List) { converter = object -> (T) new JsonArray((List) object); } else { converter = object -> (T) new JsonObject((Map) object); } return ((Map<String, T>) map).entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, converter::apply)); } } private <T> List<T> convertList(List list) { if (list.isEmpty()) { return (List<T>) list; } Object elem = list.get(0); if (!(elem instanceof Map) && !(elem instanceof List)) { return (List<T>) list; } else { Function<Object, T> converter; if (elem instanceof List) { converter = object -> (T) new JsonArray((List) object); } else { converter = object -> (T) new JsonObject((Map) object); } return (List<T>) list.stream().map(converter).collect(Collectors.toList()); } } private <T> Set<T> convertSet(List list) { return new HashSet<T>(convertList(list)); } }
mit
mxpxgx/InCense
src/edu/incense/android/sensor/WifiConnectionSensor.java
6395
/** * */ package edu.incense.android.sensor; import java.util.List; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.WifiLock; import android.provider.Settings; import android.util.Log; import edu.incense.android.datatask.data.Data; import edu.incense.android.datatask.data.WifiData; /** * @author mxpxgx * */ public class WifiConnectionSensor extends Sensor { public final static String TAG = "WifiConnectionSensor"; public final static String ATT_ISCONNECTED = "isConnected"; private boolean connected; private WifiConfiguration connectedConfig; private WifiInfo connectedWifiInfo; private WifiManager wifiManager; public WifiConnectionSensor(Context context) { super(context); setName("WiFi"); // WifiManager initiation String service = Context.WIFI_SERVICE; wifiManager = (WifiManager) context.getSystemService(service); // Initiate other attributes connectedConfig = null; connectedWifiInfo = null; } @Override public void start() { super.start(); setSensing(true); enableWifi(); connectedConfig = getConnectedConfig(); if (connectedConfig != null) { connectedWifiInfo = wifiManager.getConnectionInfo(); setConnected(true); } else { // Generate empty data Data newData = new WifiData(); newData.getExtras().putBoolean(ATT_ISCONNECTED, false); currentData = newData; } registerBroadcastReceivers(); forceWifiToStayOn(); } @Override public void stop() { super.stop(); setSensing(false); unregisterBroadcastReceivers(); disableWifi(); letWifiToTurnOff(); } private WifiLock wifiLock; private void forceWifiToStayOn(){ // Set WiFi sleep policy to never Settings.System.putInt(getContext().getContentResolver(), Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_NEVER); WifiLock wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL , "MyWifiLock"); if(!wifiLock.isHeld()){ wifiLock.acquire(); } } private void letWifiToTurnOff(){ // Set WiFi sleep policy to default Settings.System.putInt(getContext().getContentResolver(), Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT); wifiLock.release(); } /** * Enable wifi, if needed */ boolean wasEnabled = false; private void enableWifi() { wasEnabled = wifiManager.isWifiEnabled(); if (!wasEnabled) { if (wifiManager.getWifiState() != WifiManager.WIFI_STATE_ENABLING) { wifiManager.setWifiEnabled(true); } } } private void disableWifi() { if (wifiManager.isWifiEnabled() && !wasEnabled) { if (wifiManager.getWifiState() != WifiManager.WIFI_STATE_DISABLING) { wifiManager.setWifiEnabled(false); } } } private void registerBroadcastReceivers() { // Register connection monitor IntentFilter intentFilter2 = new IntentFilter( ConnectivityManager.CONNECTIVITY_ACTION); getContext().registerReceiver(this.connectionMonitor, intentFilter2); } private void unregisterBroadcastReceivers() { getContext().unregisterReceiver(this.connectionMonitor); } /** * Gets the ssid of the currently connected access point * * @param ssid * @return */ private WifiConfiguration getConnectedConfig() { List<WifiConfiguration> configList = wifiManager.getConfiguredNetworks(); for (WifiConfiguration config : configList) { Log.d(TAG, config.SSID + ", status: " + config.status); if (config.status == WifiConfiguration.Status.CURRENT) { return config; } } return null; } private void setConnected(boolean connected) { if (connectedWifiInfo != null) { this.connected = connected; Data newData = new WifiData(connectedWifiInfo); newData.getExtras().putBoolean(ATT_ISCONNECTED, connected); currentData = newData; } } private boolean isConnected() { return connected; } /** * This BroadcastReceiver checks if the WiFi connection was lost or * established. */ private BroadcastReceiver connectionMonitor = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals( android.net.ConnectivityManager.CONNECTIVITY_ACTION)) { NetworkInfo netInfo = (NetworkInfo) intent .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); NetworkInfo.State state = netInfo.getState(); boolean disconnected = (state == NetworkInfo.State.DISCONNECTED || state == NetworkInfo.State.SUSPENDED); boolean isWifi = (netInfo.getType() == ConnectivityManager.TYPE_WIFI); if (isConnected() && disconnected && isWifi) { Log.d(TAG, "WiFi connection lost!"); setConnected(false); // Toast.makeText(context, "WiFi connection lost", // Toast.LENGTH_LONG).show(); //TODO should try to reconnect } if (!isConnected() && !disconnected && isWifi) { Log.d(TAG, "WiFi connection established!"); connectedWifiInfo = wifiManager.getConnectionInfo(); setConnected(true); // Toast.makeText(context, "WiFi connection established", // Toast.LENGTH_LONG).show(); } } } }; }
mit
pietermartin/sqlg
sqlg-core/src/main/java/org/umlg/sqlg/structure/SqlgIoRegistryV1.java
736
package org.umlg.sqlg.structure; import org.apache.tinkerpop.gremlin.structure.io.AbstractIoRegistry; import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONIo; import org.apache.tinkerpop.gremlin.structure.io.gryo.GryoIo; /** * Date: 2015/05/07 * Time: 8:05 PM */ public class SqlgIoRegistryV1 extends AbstractIoRegistry { private static final SqlgIoRegistryV1 INSTANCE = new SqlgIoRegistryV1(); private SqlgIoRegistryV1() { final SqlgSimpleModuleV1 sqlgSimpleModuleV1 = new SqlgSimpleModuleV1(); register(GraphSONIo.class, null, sqlgSimpleModuleV1); register(GryoIo.class, RecordId.class, null); } public static SqlgIoRegistryV1 instance() { return INSTANCE; } }
mit
selvasingh/azure-sdk-for-java
sdk/network/mgmt-v2019_07_01/src/main/java/com/microsoft/azure/management/network/v2019_07_01/VirtualRouterPeering.java
6384
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2019_07_01; import com.microsoft.azure.arm.model.HasInner; import com.microsoft.azure.management.network.v2019_07_01.implementation.VirtualRouterPeeringInner; import com.microsoft.azure.arm.model.Indexable; import com.microsoft.azure.arm.model.Refreshable; import com.microsoft.azure.arm.model.Updatable; import com.microsoft.azure.arm.model.Appliable; import com.microsoft.azure.arm.model.Creatable; import com.microsoft.azure.arm.resources.models.HasManager; import com.microsoft.azure.management.network.v2019_07_01.implementation.NetworkManager; /** * Type representing VirtualRouterPeering. */ public interface VirtualRouterPeering extends HasInner<VirtualRouterPeeringInner>, Indexable, Refreshable<VirtualRouterPeering>, Updatable<VirtualRouterPeering.Update>, HasManager<NetworkManager> { /** * @return the etag value. */ String etag(); /** * @return the id value. */ String id(); /** * @return the name value. */ String name(); /** * @return the peerAsn value. */ Long peerAsn(); /** * @return the peerIp value. */ String peerIp(); /** * @return the provisioningState value. */ ProvisioningState provisioningState(); /** * @return the type value. */ String type(); /** * The entirety of the VirtualRouterPeering definition. */ interface Definition extends DefinitionStages.Blank, DefinitionStages.WithVirtualRouter, DefinitionStages.WithCreate { } /** * Grouping of VirtualRouterPeering definition stages. */ interface DefinitionStages { /** * The first stage of a VirtualRouterPeering definition. */ interface Blank extends WithVirtualRouter { } /** * The stage of the virtualrouterpeering definition allowing to specify VirtualRouter. */ interface WithVirtualRouter { /** * Specifies resourceGroupName, virtualRouterName. * @param resourceGroupName The name of the resource group * @param virtualRouterName The name of the Virtual Router * @return the next definition stage */ WithCreate withExistingVirtualRouter(String resourceGroupName, String virtualRouterName); } /** * The stage of the virtualrouterpeering definition allowing to specify Id. */ interface WithId { /** * Specifies id. * @param id Resource ID * @return the next definition stage */ WithCreate withId(String id); } /** * The stage of the virtualrouterpeering definition allowing to specify Name. */ interface WithName { /** * Specifies name. * @param name Gets name of the peering unique to VirtualRouter. This name can be used to access the resource * @return the next definition stage */ WithCreate withName(String name); } /** * The stage of the virtualrouterpeering definition allowing to specify PeerAsn. */ interface WithPeerAsn { /** * Specifies peerAsn. * @param peerAsn Peer ASN * @return the next definition stage */ WithCreate withPeerAsn(Long peerAsn); } /** * The stage of the virtualrouterpeering definition allowing to specify PeerIp. */ interface WithPeerIp { /** * Specifies peerIp. * @param peerIp Peer IP * @return the next definition stage */ WithCreate withPeerIp(String peerIp); } /** * The stage of the definition which contains all the minimum required inputs for * the resource to be created (via {@link WithCreate#create()}), but also allows * for any other optional settings to be specified. */ interface WithCreate extends Creatable<VirtualRouterPeering>, DefinitionStages.WithId, DefinitionStages.WithName, DefinitionStages.WithPeerAsn, DefinitionStages.WithPeerIp { } } /** * The template for a VirtualRouterPeering update operation, containing all the settings that can be modified. */ interface Update extends Appliable<VirtualRouterPeering>, UpdateStages.WithId, UpdateStages.WithName, UpdateStages.WithPeerAsn, UpdateStages.WithPeerIp { } /** * Grouping of VirtualRouterPeering update stages. */ interface UpdateStages { /** * The stage of the virtualrouterpeering update allowing to specify Id. */ interface WithId { /** * Specifies id. * @param id Resource ID * @return the next update stage */ Update withId(String id); } /** * The stage of the virtualrouterpeering update allowing to specify Name. */ interface WithName { /** * Specifies name. * @param name Gets name of the peering unique to VirtualRouter. This name can be used to access the resource * @return the next update stage */ Update withName(String name); } /** * The stage of the virtualrouterpeering update allowing to specify PeerAsn. */ interface WithPeerAsn { /** * Specifies peerAsn. * @param peerAsn Peer ASN * @return the next update stage */ Update withPeerAsn(Long peerAsn); } /** * The stage of the virtualrouterpeering update allowing to specify PeerIp. */ interface WithPeerIp { /** * Specifies peerIp. * @param peerIp Peer IP * @return the next update stage */ Update withPeerIp(String peerIp); } } }
mit
selvasingh/azure-sdk-for-java
sdk/network/mgmt-v2019_02_01/src/main/java/com/microsoft/azure/management/network/v2019_02_01/ApplicationGatewayRedirectType.java
1830
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2019_02_01; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for ApplicationGatewayRedirectType. */ public final class ApplicationGatewayRedirectType extends ExpandableStringEnum<ApplicationGatewayRedirectType> { /** Static value Permanent for ApplicationGatewayRedirectType. */ public static final ApplicationGatewayRedirectType PERMANENT = fromString("Permanent"); /** Static value Found for ApplicationGatewayRedirectType. */ public static final ApplicationGatewayRedirectType FOUND = fromString("Found"); /** Static value SeeOther for ApplicationGatewayRedirectType. */ public static final ApplicationGatewayRedirectType SEE_OTHER = fromString("SeeOther"); /** Static value Temporary for ApplicationGatewayRedirectType. */ public static final ApplicationGatewayRedirectType TEMPORARY = fromString("Temporary"); /** * Creates or finds a ApplicationGatewayRedirectType from its string representation. * @param name a name to look for * @return the corresponding ApplicationGatewayRedirectType */ @JsonCreator public static ApplicationGatewayRedirectType fromString(String name) { return fromString(name, ApplicationGatewayRedirectType.class); } /** * @return known ApplicationGatewayRedirectType values */ public static Collection<ApplicationGatewayRedirectType> values() { return values(ApplicationGatewayRedirectType.class); } }
mit
selvasingh/azure-sdk-for-java
sdk/network/mgmt-v2019_04_01/src/main/java/com/microsoft/azure/management/network/v2019_04_01/LoadBalancerSku.java
1124
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2019_04_01; import com.fasterxml.jackson.annotation.JsonProperty; /** * SKU of a load balancer. */ public class LoadBalancerSku { /** * Name of a load balancer SKU. Possible values include: 'Basic', * 'Standard'. */ @JsonProperty(value = "name") private LoadBalancerSkuName name; /** * Get name of a load balancer SKU. Possible values include: 'Basic', 'Standard'. * * @return the name value */ public LoadBalancerSkuName name() { return this.name; } /** * Set name of a load balancer SKU. Possible values include: 'Basic', 'Standard'. * * @param name the name value to set * @return the LoadBalancerSku object itself. */ public LoadBalancerSku withName(LoadBalancerSkuName name) { this.name = name; return this; } }
mit
Willie1234/Inforvellor-master
src/main/java/com/njyb/gbdbase/service/common/engines/impl/MultiHscodeMarkService.java
1671
package com.njyb.gbdbase.service.common.engines.impl; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.njyb.gbdbase.model.datasearch.common.DataReportSumModel; import com.njyb.gbdbase.model.datasearch.common.ReportPropertiesModel; import com.njyb.gbdbase.service.common.componet.report.ReportSumaryCmp; import com.njyb.gbdbase.service.common.componet.report.componet.chagemap.IListChangeMapFormat; import com.njyb.gbdbase.service.common.engine.util.ParamEnumUtil; import com.njyb.gbdbase.service.common.engines.IMultiHscodeMarkService; import com.njyb.gbdbase.service.common.engines.IReportDetailService; /** * 获取多海关编码备注信息 * @author 贾红平 * */ @Service public class MultiHscodeMarkService extends ReportSumaryCmp implements IMultiHscodeMarkService { @Autowired private IListChangeMapFormat mapFormat; @Autowired private IReportDetailService detailService; @Autowired ReportPropertiesModel report; /** * 获取多海关编码备注的详细信息 */ @SuppressWarnings("static-access") @Override public List<DataReportSumModel> getMultiHscodeMarkInfo(String value, String country,String reportType) { List<DataReportSumModel>list=detailService.buildReportSumList(value, reportType, country); Map<String, List<DataReportSumModel>>map=mapFormat.changeListForMap(list, ParamEnumUtil.multi_hscode.name(), report.getReportFieldMap(), true); List<DataReportSumModel>hslist=super.getDataReportSumModels(map, ParamEnumUtil.multi_hscode.name(), country, report.getReportFieldMap()); return hslist; } }
mit
darshanhs90/Java-Coding
src/April2021PrepLeetcode/_1200MinimumAbsoluteDifference.java
458
package April2021PrepLeetcode; import java.util.List; public class _1200MinimumAbsoluteDifference { public static void main(String[] args) { System.out.println(minimumAbsDifference(new int[] { 4, 2, 1, 3 })); System.out.println(minimumAbsDifference(new int[] { 1, 3, 6, 10, 15 })); System.out.println(minimumAbsDifference(new int[] { 3, 8, -10, 23, 19, -4, -14, 27 })); } public static List<List<Integer>> minimumAbsDifference(int[] arr) { } }
mit
psyco4j/shardy
src/main/java/maniac/lee/shardy/sqlparser/ISqlParser.java
454
package maniac.lee.shardy.sqlparser; import maniac.lee.shardy.SqlParseException; import java.util.List; /** * Created by lipeng on 16/2/4. */ public interface ISqlParser { void init(String sql) throws SqlParseException; String getTableName(); SqlType getType(); List<String> getWhereColumns(); boolean setTableName(String tableName); List<ColumnValue> getColumns(); String toSql(); String getSqlOriginal(); }
mit
Riggs333/schemaspy
src/main/java/org/schemaspy/view/HtmlConstraintsPage.java
2290
/* * This file is a part of the SchemaSpy project (http://schemaspy.org). * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 John Currier * * SchemaSpy 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. * * SchemaSpy is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.schemaspy.view; import org.schemaspy.model.Database; import org.schemaspy.model.ForeignKeyConstraint; import org.schemaspy.model.Table; import org.schemaspy.util.LineWriter; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.List; /** * The page that lists all of the constraints in the schema * * @author John Currier */ public class HtmlConstraintsPage extends HtmlFormatter { private static HtmlConstraintsPage instance = new HtmlConstraintsPage(); /** * Singleton: Don't allow instantiation */ private HtmlConstraintsPage() { } /** * Singleton accessor * * @return the singleton instance */ public static HtmlConstraintsPage getInstance() { return instance; } public void write(Database database, List<ForeignKeyConstraint> constraints, Collection<Table> tables, File outputDir) throws IOException { HashMap<String, Object> scopes = new HashMap<String, Object>(); scopes.put("constraints", constraints); scopes.put("tables", tables); scopes.put("paginationEnabled",database.getConfig().isPaginationEnabled()); MustacheWriter mw = new MustacheWriter( outputDir, scopes, getPathToRoot(), database.getName(), false); mw.write("constraint.html", "constraints.html", "constraint.js"); } }
mit
code-disaster/steamworks4j
java-wrapper/src/main/java/com/codedisaster/steamworks/SteamID.java
1366
package com.codedisaster.steamworks; public class SteamID extends SteamNativeHandle { private static final long InvalidSteamID = getInvalidSteamID(); public SteamID() { super(InvalidSteamID); } public SteamID(SteamID steamID) { super(steamID.handle); } /** * This constructor is package-private to not invite user applications to persist and recover ID values * manually. Instead, Steamworks API functions should always be used to obtain valid steam IDs. * <p> * If you need to serialize IDs, e.g. for client/server communication, use the static functions * {@link SteamNativeHandle#getNativeHandle(SteamNativeHandle)} and {@link SteamID#createFromNativeHandle(long)} * instead. */ SteamID(long id) { super(id); } public boolean isValid() { return isValid(handle); } public int getAccountID() { return (int) (handle % (1L << 32)); } /** * Creates a SteamID instance from a long value previously obtained by * {@link SteamNativeHandle#getNativeHandle(SteamNativeHandle)}. */ public static SteamID createFromNativeHandle(long id) { return new SteamID(id); } // @off /*JNI #include <steam_api.h> */ private static native boolean isValid(long handle); /* return CSteamID((uint64) handle).IsValid(); */ private static native long getInvalidSteamID(); /* return k_steamIDNil.ConvertToUint64(); */ }
mit
darshanhs90/Java-InterviewPrep
src/TopCoder/SRM148CeyKaps.java
781
package TopCoder; /* * SRM 148 Div2 * Link:https://community.topcoder.com/stat?c=problem_statement&pm=1740&rd=4545 */ public class SRM148CeyKaps { public static void main(String[] args) { System.out.println(decipher("AAAAA", new String[]{"A:B","B:C","A:D"})); System.out.println(decipher("ABCDE", new String[]{"A:B","B:C","C:D","D:E","E:A"})); System.out.println(decipher("IHWSIOTCHEDMYKEYCAPSARWUND", new String[]{"W:O","W:I"})); } public static String decipher(String typed, String[] switches){ for (int i = 0; i < switches.length; i++) { String splitString[]=switches[i].split(":"); typed=typed.replace(splitString[0], "-"); typed=typed.replace(splitString[1],splitString[0]); typed=typed.replace("-",splitString[1]); } return typed; } }
mit
navalev/azure-sdk-for-java
sdk/apimanagement/mgmt-v2018_06_01_preview/src/main/java/com/microsoft/azure/management/apimanagement/v2018_06_01_preview/BackendContract.java
11644
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.apimanagement.v2018_06_01_preview; import com.microsoft.azure.arm.model.HasInner; import com.microsoft.azure.management.apimanagement.v2018_06_01_preview.implementation.BackendContractInner; import com.microsoft.azure.arm.model.Indexable; import com.microsoft.azure.arm.model.Creatable; import com.microsoft.azure.arm.model.Updatable; import com.microsoft.azure.arm.model.Appliable; import com.microsoft.azure.arm.resources.models.HasManager; import com.microsoft.azure.management.apimanagement.v2018_06_01_preview.implementation.ApiManagementManager; /** * Type representing BackendContract. */ public interface BackendContract extends HasInner<BackendContractInner>, Indexable, Updatable<BackendContract.Update>, HasManager<ApiManagementManager> { /** * @return the credentials value. */ BackendCredentialsContract credentials(); /** * @return the description value. */ String description(); /** * @return the id value. */ String id(); /** * @return the name value. */ String name(); /** * @return the properties value. */ BackendProperties properties(); /** * @return the protocol value. */ BackendProtocol protocol(); /** * @return the proxy value. */ BackendProxyContract proxy(); /** * @return the resourceId value. */ String resourceId(); /** * @return the title value. */ String title(); /** * @return the tls value. */ BackendTlsProperties tls(); /** * @return the type value. */ String type(); /** * @return the url value. */ String url(); /** * The entirety of the BackendContract definition. */ interface Definition extends DefinitionStages.Blank, DefinitionStages.WithResourceGroupName, DefinitionStages.WithServiceName, DefinitionStages.WithIfMatch, DefinitionStages.WithProtocol, DefinitionStages.WithUrl, DefinitionStages.WithCreate { } /** * Grouping of BackendContract definition stages. */ interface DefinitionStages { /** * The first stage of a BackendContract definition. */ interface Blank extends WithResourceGroupName { } /** * The stage of the backendcontract definition allowing to specify ResourceGroupName. */ interface WithResourceGroupName { /** * Specifies resourceGroupName. * @param resourceGroupName The name of the resource group * @return the next definition stage */ WithServiceName withResourceGroupName(String resourceGroupName); } /** * The stage of the backendcontract definition allowing to specify ServiceName. */ interface WithServiceName { /** * Specifies serviceName. * @param serviceName The name of the API Management service * @return the next definition stage */ WithIfMatch withServiceName(String serviceName); } /** * The stage of the backendcontract definition allowing to specify IfMatch. */ interface WithIfMatch { /** * Specifies ifMatch. * @param ifMatch ETag of the Entity. Not required when creating an entity, but required when updating an entity * @return the next definition stage */ WithProtocol withIfMatch(String ifMatch); } /** * The stage of the backendcontract definition allowing to specify Protocol. */ interface WithProtocol { /** * Specifies protocol. * @param protocol Backend communication protocol. Possible values include: 'http', 'soap' * @return the next definition stage */ WithUrl withProtocol(BackendProtocol protocol); } /** * The stage of the backendcontract definition allowing to specify Url. */ interface WithUrl { /** * Specifies url. * @param url Runtime Url of the Backend * @return the next definition stage */ WithCreate withUrl(String url); } /** * The stage of the backendcontract definition allowing to specify Credentials. */ interface WithCredentials { /** * Specifies credentials. * @param credentials Backend Credentials Contract Properties * @return the next definition stage */ WithCreate withCredentials(BackendCredentialsContract credentials); } /** * The stage of the backendcontract definition allowing to specify Description. */ interface WithDescription { /** * Specifies description. * @param description Backend Description * @return the next definition stage */ WithCreate withDescription(String description); } /** * The stage of the backendcontract definition allowing to specify Properties. */ interface WithProperties { /** * Specifies properties. * @param properties Backend Properties contract * @return the next definition stage */ WithCreate withProperties(BackendProperties properties); } /** * The stage of the backendcontract definition allowing to specify Proxy. */ interface WithProxy { /** * Specifies proxy. * @param proxy Backend Proxy Contract Properties * @return the next definition stage */ WithCreate withProxy(BackendProxyContract proxy); } /** * The stage of the backendcontract definition allowing to specify ResourceId. */ interface WithResourceId { /** * Specifies resourceId. * @param resourceId Management Uri of the Resource in External System. This url can be the Arm Resource Id of Logic Apps, Function Apps or Api Apps * @return the next definition stage */ WithCreate withResourceId(String resourceId); } /** * The stage of the backendcontract definition allowing to specify Title. */ interface WithTitle { /** * Specifies title. * @param title Backend Title * @return the next definition stage */ WithCreate withTitle(String title); } /** * The stage of the backendcontract definition allowing to specify Tls. */ interface WithTls { /** * Specifies tls. * @param tls Backend TLS Properties * @return the next definition stage */ WithCreate withTls(BackendTlsProperties tls); } /** * The stage of the definition which contains all the minimum required inputs for * the resource to be created (via {@link WithCreate#create()}), but also allows * for any other optional settings to be specified. */ interface WithCreate extends Creatable<BackendContract>, DefinitionStages.WithCredentials, DefinitionStages.WithDescription, DefinitionStages.WithProperties, DefinitionStages.WithProxy, DefinitionStages.WithResourceId, DefinitionStages.WithTitle, DefinitionStages.WithTls { } } /** * The template for a BackendContract update operation, containing all the settings that can be modified. */ interface Update extends Appliable<BackendContract>, UpdateStages.WithIfMatch, UpdateStages.WithCredentials, UpdateStages.WithDescription, UpdateStages.WithProperties, UpdateStages.WithProxy, UpdateStages.WithResourceId, UpdateStages.WithTitle, UpdateStages.WithTls { } /** * Grouping of BackendContract update stages. */ interface UpdateStages { /** * The stage of the backendcontract update allowing to specify IfMatch. */ interface WithIfMatch { /** * Specifies ifMatch. * @param ifMatch ETag of the Entity. Not required when creating an entity, but required when updating an entity * @return the next update stage */ Update withIfMatch(String ifMatch); } /** * The stage of the backendcontract update allowing to specify Credentials. */ interface WithCredentials { /** * Specifies credentials. * @param credentials Backend Credentials Contract Properties * @return the next update stage */ Update withCredentials(BackendCredentialsContract credentials); } /** * The stage of the backendcontract update allowing to specify Description. */ interface WithDescription { /** * Specifies description. * @param description Backend Description * @return the next update stage */ Update withDescription(String description); } /** * The stage of the backendcontract update allowing to specify Properties. */ interface WithProperties { /** * Specifies properties. * @param properties Backend Properties contract * @return the next update stage */ Update withProperties(BackendProperties properties); } /** * The stage of the backendcontract update allowing to specify Proxy. */ interface WithProxy { /** * Specifies proxy. * @param proxy Backend Proxy Contract Properties * @return the next update stage */ Update withProxy(BackendProxyContract proxy); } /** * The stage of the backendcontract update allowing to specify ResourceId. */ interface WithResourceId { /** * Specifies resourceId. * @param resourceId Management Uri of the Resource in External System. This url can be the Arm Resource Id of Logic Apps, Function Apps or Api Apps * @return the next update stage */ Update withResourceId(String resourceId); } /** * The stage of the backendcontract update allowing to specify Title. */ interface WithTitle { /** * Specifies title. * @param title Backend Title * @return the next update stage */ Update withTitle(String title); } /** * The stage of the backendcontract update allowing to specify Tls. */ interface WithTls { /** * Specifies tls. * @param tls Backend TLS Properties * @return the next update stage */ Update withTls(BackendTlsProperties tls); } } }
mit
hpsa/hp-application-automation-tools-plugin
src/test/java/com/hp/application/automation/tools/octane/configuration/ConfigurationActionFactoryTest.java
2425
/* * Copyright 2017 Hewlett-Packard Development Company, L.P. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.hp.application.automation.tools.octane.configuration; import com.hp.application.automation.tools.octane.tests.ExtensionUtil; import hudson.matrix.Axis; import hudson.matrix.AxisList; import hudson.matrix.MatrixConfiguration; import hudson.matrix.MatrixProject; import hudson.model.FreeStyleProject; import org.junit.Assert; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import java.io.IOException; public class ConfigurationActionFactoryTest { @ClassRule static final public JenkinsRule jenkins = new JenkinsRule(); private ConfigurationActionFactory configurationActionFactory; @Before public void initialize() { configurationActionFactory = ExtensionUtil.getInstance(jenkins, ConfigurationActionFactory .class); } @Test public void testMatrixJob() throws IOException { MatrixProject matrixProject = jenkins.createProject(MatrixProject.class, "ConfigurationActionFactoryTest.testMatrixJob"); //jenkins.createMatrixProject("ConfigurationActionFactoryTest.testMatrixJob"); matrixProject.setAxes(new AxisList(new Axis("OS", "Linux", "Windows"))); Assert.assertEquals(1, configurationActionFactory.createFor(matrixProject).size()); for (MatrixConfiguration configuration: matrixProject.getItems()) { Assert.assertEquals(0, configurationActionFactory.createFor(configuration).size()); } } @Test public void testFreeStyleJob() throws IOException { FreeStyleProject project = jenkins.createFreeStyleProject("ConfigurationActionFactoryTest.testFreeStyleJob"); Assert.assertEquals(1, configurationActionFactory.createFor(project).size()); } }
mit
jaredstehler/jsoup
src/main/java/org/jsoup/nodes/Attribute.java
4801
package org.jsoup.nodes; import org.jsoup.helper.Validate; import java.util.Arrays; import java.util.Map; /** A single key + value attribute. Keys are trimmed and normalised to lower-case. @author Jonathan Hedley, jonathan@hedley.net */ public class Attribute implements Map.Entry<String, String>, Cloneable { private static final String[] booleanAttributes = { "allowfullscreen", "async", "autofocus", "checked", "compact", "declare", "default", "defer", "disabled", "formnovalidate", "hidden", "inert", "ismap", "itemscope", "multiple", "muted", "nohref", "noresize", "noshade", "novalidate", "nowrap", "open", "readonly", "required", "reversed", "seamless", "selected", "sortable", "truespeed", "typemustmatch" }; private String key; private String value; /** * Create a new attribute from unencoded (raw) key and value. * @param key attribute key * @param value attribute value * @see #createFromEncoded */ public Attribute(String key, String value) { Validate.notEmpty(key); Validate.notNull(value); this.key = key.trim().toLowerCase(); this.value = value; } /** Get the attribute key. @return the attribute key */ public String getKey() { return key; } /** Set the attribute key. Gets normalised as per the constructor method. @param key the new key; must not be null */ public void setKey(String key) { Validate.notEmpty(key); this.key = key.trim().toLowerCase(); } /** Get the attribute value. @return the attribute value */ public String getValue() { return value; } /** Set the attribute value. @param value the new attribute value; must not be null */ public String setValue(String value) { Validate.notNull(value); String old = this.value; this.value = value; return old; } /** Get the HTML representation of this attribute; e.g. {@code href="index.html"}. @return HTML */ public String html() { StringBuilder accum = new StringBuilder(); html(accum, (new Document("")).outputSettings()); return accum.toString(); } protected void html(StringBuilder accum, Document.OutputSettings out) { accum.append(key); if (!shouldCollapseAttribute(out)) { accum.append("=\""); Entities.escape(accum, value, out, true, false, false); accum.append('"'); } } /** Get the string representation of this attribute, implemented as {@link #html()}. @return string */ @Override public String toString() { return html(); } /** * Create a new Attribute from an unencoded key and a HTML attribute encoded value. * @param unencodedKey assumes the key is not encoded, as can be only run of simple \w chars. * @param encodedValue HTML attribute encoded value * @return attribute */ public static Attribute createFromEncoded(String unencodedKey, String encodedValue) { String value = Entities.unescape(encodedValue, true); return new Attribute(unencodedKey, value); } protected boolean isDataAttribute() { return key.startsWith(Attributes.dataPrefix) && key.length() > Attributes.dataPrefix.length(); } /** * Collapsible if it's a boolean attribute and value is empty or same as name * * @param out Outputsettings * @return Returns whether collapsible or not */ protected final boolean shouldCollapseAttribute(Document.OutputSettings out) { return ("".equals(value) || value.equalsIgnoreCase(key)) && out.syntax() == Document.OutputSettings.Syntax.html && Arrays.binarySearch(booleanAttributes, key) >= 0; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Attribute)) return false; Attribute attribute = (Attribute) o; if (key != null ? !key.equals(attribute.key) : attribute.key != null) return false; return !(value != null ? !value.equals(attribute.value) : attribute.value != null); } @Override public int hashCode() { int result = key != null ? key.hashCode() : 0; result = 31 * result + (value != null ? value.hashCode() : 0); return result; } @Override public Attribute clone() { try { return (Attribute) super.clone(); // only fields are immutable strings key and value, so no more deep copy required } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } }
mit
Suseika/inflectible
src/test/java/org/tendiwa/inflectible/antlr/parsed/ParsedVocabularyTest.java
2954
/** * The MIT License (MIT) * * Copyright (c) 2015 Georgy Vlasov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.tendiwa.inflectible.antlr.parsed; import com.google.common.base.Joiner; import java.io.IOException; import java.util.Collections; import org.apache.commons.io.IOUtils; import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Test; import org.tendiwa.inflectible.ValidatedConcept; import org.tendiwa.inflectible.implementations.English; /** * Unit tests for {@link ParsedVocabulary}. * @author Georgy Vlasov (suseika@tendiwa.org) * @version $Id$ * @since 0.1.0 */ public final class ParsedVocabularyTest { /** * ParsedVocabulary can parse input streams and create lexemes from markup. * @throws Exception If fails */ @Test public void findsWords() throws Exception { final ParsedVocabulary bundle = this.englishVocabulary(); MatcherAssert.assertThat( bundle.hasLexeme(new ValidatedConcept("DRAGON")), CoreMatchers.equalTo(true) ); } /** * Creates a small vocabulary for {@link English} language. * @return Vocabulary for {@link English} * @throws IOException If can't read the vocabulary input stream */ private ParsedVocabulary englishVocabulary() throws IOException { return new ParsedVocabulary( new English().grammar(), Collections.singletonList( IOUtils.toInputStream( Joiner.on('\n').join( "DRAGON (Noun) {", " dragon <Sing>", " dragons <Plur>", "}", "BEE (Noun) {", " bee <Sing>", " bees <Plur>", "} " ) ) ) ); } }
mit
hpe-idol/find
webapp/idol/src/main/java/com/hp/autonomy/frontend/find/idol/web/IdolErrorResponse.java
738
/* * Copyright 2015-2017 Hewlett Packard Enterprise Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ package com.hp.autonomy.frontend.find.idol.web; import com.hp.autonomy.frontend.find.core.web.ErrorResponse; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; @Getter @EqualsAndHashCode(callSuper = true) class IdolErrorResponse extends ErrorResponse { private final String backendErrorCode; @Setter private Boolean isUserError = false; IdolErrorResponse(final String message, final String backendErrorCode) { super(message); this.backendErrorCode = backendErrorCode; } }
mit
georghinkel/ttc2017smartGrids
solutions/eMoflon/rgse.ttc17.metamodels.src/src/gluemodel/COSEM/COSEMObjects/impl/SAPAssignmentCurrentImpl.java
887
/** */ package gluemodel.COSEM.COSEMObjects.impl; import gluemodel.COSEM.COSEMObjects.COSEMObjectsPackage; import gluemodel.COSEM.COSEMObjects.SAPAssignmentCurrent; import gluemodel.COSEM.InterfaceClasses.impl.SAPAssignmentImpl; import org.eclipse.emf.ecore.EClass; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>SAP Assignment Current</b></em>'. * <!-- end-user-doc --> * * @generated */ public class SAPAssignmentCurrentImpl extends SAPAssignmentImpl implements SAPAssignmentCurrent { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected SAPAssignmentCurrentImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return COSEMObjectsPackage.eINSTANCE.getSAPAssignmentCurrent(); } } //SAPAssignmentCurrentImpl
mit
BBN-E/bue-common-open
common-core-open/src/main/java/com/bbn/bue/common/serialization/jackson/JacksonSerializationM.java
3274
package com.bbn.bue.common.serialization.jackson; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.datatype.guava.GuavaModule; import com.fasterxml.jackson.module.guice.GuiceAnnotationIntrospector; import com.fasterxml.jackson.module.guice.GuiceInjectableValues; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provides; import com.google.inject.multibindings.Multibinder; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Set; import javax.inject.Qualifier; /** * Provides a {@link com.bbn.bue.common.serialization.jackson.JacksonSerializer.Builder} * whose resulting {@link JacksonSerializer} knows about Guice bindings. The resulting * {@code Builder} may be safely modified. */ public final class JacksonSerializationM extends AbstractModule { @Override protected void configure() { final Key<Module> jacksonModulesKey = jacksonModulesKey(); final Multibinder<Module> jacksonModulesBinder = Multibinder.newSetBinder(binder(), jacksonModulesKey).permitDuplicates(); // go ahead and add two modules we always use, by default jacksonModulesBinder.addBinding().to(BUECommonOpenModule.class); jacksonModulesBinder.addBinding().toInstance(new GuavaModule()); } private static final Key<Module> JACKSON_MODULES_KEY = Key.get(Module.class, JacksonModulesP.class); /** * Users can bind to this key with a {@link Multibinder} to guarantee Jackson modules are added. */ public static Key<Module> jacksonModulesKey() { return JACKSON_MODULES_KEY; } @Provides public JacksonSerializer.Builder getJacksonSerializer(Injector injector, @JacksonModulesP Set<Module> jacksonModules) { final JacksonSerializer.Builder ret = JacksonSerializer.builder().withInjectionBindings(new GuiceAnnotationIntrospector(), new GuiceInjectableValues(injector)); for (final Module jacksonModule : jacksonModules) { ret.registerModule(jacksonModule); } // we block this module from being installed if found on the classpath because it breaks // our normal Guice injection during deserialization. This shouldn't be a problem because // things which use this (like Jersey) don't use JacksonSerializer.Builder to get their // deserializers anyway. If it's ever a problem, we can provide an optional to disable it. ret.blockModuleClassName("com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule"); return ret; } @Override public int hashCode() { // some arbitrary prime number return 1500450271; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } return true; } /** * Bind to this with a multibinder to specify Jackson modules which should be installed * into injected serialziers and deserializers */ @Qualifier @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @interface JacksonModulesP {} }
mit
Natito/POSAdminV2
src/com/puntodeventa/services/DAO/CategoryDAO.java
2188
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.puntodeventa.services.DAO; import com.puntodeventa.global.Util.ValidacionForms; import com.puntodeventa.mvc.Model.Category; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.hibernate.HibernateException; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.Transaction; /** * * @author Nato */ public class CategoryDAO { static final Logger LOG = Logger.getLogger(CategoryDAO.class.getName()); ValidacionForms vali = new ValidacionForms(); private Session session; private Transaction tx; //Metodo: Inicializa la operacion para procesos en la base de datos private void iniciaOperacion() throws HibernateException{ session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); } // Metodo: Obtenemos el error que podria ocacionar an cada metodo private void manejaException(HibernateException he)throws HibernateException{ tx.rollback(); throw new HibernateException ("Ocurrio un error en la capa de acceso a datos. Error: " + he.getMessage()); } /** * Metodo que devuelve una categoria */ public Category selectCategory(String id_category){ LOG.log(Level.INFO, "selectCategory()"); Category category = null; try{ this.iniciaOperacion(); category = (Category) session.get(Category.class, id_category); }catch(HibernateException he){ this.manejaException(he); throw he; }finally{ session.close(); } return category; } public List<Category> listCategory(){ LOG.log(Level.INFO, "listCategory()"); List<Category> listCategory = null; try{ this.iniciaOperacion(); final SQLQuery sql = session.createSQLQuery("SELECT * FROM vt.CATEGORY ORDER BY ID_CATEGORY").addEntity(Category.class); listCategory = sql.list(); }finally{ session.close(); } return listCategory; } }
mit
Mazdallier/Aura-Cascade
src/api/java/cofh/api/energy/IEnergyReceiver.java
1097
package cofh.api.energy; import net.minecraftforge.common.util.ForgeDirection; /** * Implement this interface on Tile Entities which should receive energy, generally storing it in one or more internal {@link IEnergyStorage} objects. * <p> * A reference implementation is provided {@link TileEnergyHandler}. * * @author King Lemming * */ public interface IEnergyReceiver extends IEnergyConnection { /** * Add energy to an IEnergyReceiver, internal distribution is left entirely to the IEnergyReceiver. * * @param from Orientation the energy is received from. * @param maxReceive Maximum amount of energy to receive. * @param simulate If TRUE, the charge will only be simulated. * @return Amount of energy that was (or would have been, if simulated) received. */ int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate); /** * Returns the amount of energy currently stored. */ int getEnergyStored(ForgeDirection from); /** * Returns the maximum amount of energy that can be stored. */ int getMaxEnergyStored(ForgeDirection from); }
mit
selvasingh/azure-sdk-for-java
sdk/network/mgmt-v2019_08_01/src/main/java/com/microsoft/azure/management/network/v2019_08_01/implementation/LocationAvailableDelegationModelImpl.java
1384
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2019_08_01.implementation; import com.microsoft.azure.management.network.v2019_08_01.LocationAvailableDelegationModel; import com.microsoft.azure.arm.model.implementation.WrapperImpl; import rx.Observable; import java.util.List; class LocationAvailableDelegationModelImpl extends WrapperImpl<AvailableDelegationInner> implements LocationAvailableDelegationModel { private final NetworkManager manager; LocationAvailableDelegationModelImpl(AvailableDelegationInner inner, NetworkManager manager) { super(inner); this.manager = manager; } @Override public NetworkManager manager() { return this.manager; } @Override public List<String> actions() { return this.inner().actions(); } @Override public String id() { return this.inner().id(); } @Override public String name() { return this.inner().name(); } @Override public String serviceName() { return this.inner().serviceName(); } @Override public String type() { return this.inner().type(); } }
mit
rchumarin/java-course-ee
Hibernate/part1/GS_Hibernate_HQL1/src/main/java/edu/javacourse/hibernate/Region.java
1408
package edu.javacourse.hibernate; import javax.persistence.*; import java.io.Serializable; import java.util.List; @Entity @Table(name = "jc_region") @NamedQueries( { @NamedQuery(name = "Region.MyQueryName", query = "from Region") } ) public class Region implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "region_id") private Long regionId; @Column(name = "region_name", nullable = true) private String regionName; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "region") @OrderBy(value = "cityName") private List<City> cityList; public Region() { } public Region(String regionName) { this.regionName = regionName; } public Long getRegionId() { return regionId; } public void setRegionId(Long regionId) { this.regionId = regionId; } public String getRegionName() { return regionName; } public void setRegionName(String regionName) { this.regionName = regionName; } public List<City> getCityList() { return cityList; } public void setCityList(List<City> cityList) { this.cityList = cityList; } @Override public String toString() { return "Region{" + "regionId=" + regionId + ", regionName=" + regionName + '}'; } }
mit
Limjunghwa/wholeba_android
src/com/banana/banana/setting/GmailSender.java
4232
package com.banana.banana.setting; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; //import java.net.PasswordAuthentication; import java.security.Security; import java.util.Properties; import javax.activation.DataHandler; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.activation.DataSource; import javax.mail.PasswordAuthentication; import android.os.AsyncTask; import javax.mail.Message; public class GmailSender extends javax.mail.Authenticator { private String mailhost = "smtp.gmail.com"; private String user; private String password; private Session session; MimeMessage message; static { Security.addProvider(new JSSEProvider()); } public GmailSender(String user, String password) { this.user = user; this.password = password; Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.host", mailhost); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.quitwait", "false"); session = Session.getDefaultInstance(props, this); } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, password); } public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception { try { message = new MimeMessage(session); DataHandler handler = new DataHandler(new ByteArrayDataSource( body.getBytes(), "text/plain")); message.setSender(new InternetAddress(sender)); message.setSubject(subject); message.setDataHandler(handler); if (recipients.indexOf(',') > 0) { message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients)); } else { message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients)); new tesetAsynTastk().execute(null, null, null); } } catch (Exception e) { } } class tesetAsynTastk extends AsyncTask <Void, Void, Void> { @Override protected synchronized void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... params) { try { Transport.send(message); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); } } public class ByteArrayDataSource implements DataSource { private byte[] data; private String type; public ByteArrayDataSource(byte[] data, String type) { super(); this.data = data; this.type = type; } public ByteArrayDataSource(byte[] data) { super(); this.data = data; } public void setType(String type) { this.type = type; } public String getContentType() { if (type == null) return "application/octet-stream"; else return type; } public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(data); } public String getName() { return "ByteArrayDataSource"; } public OutputStream getOutputStream() throws IOException { throw new IOException("Not Supported"); } } }
mit
JeffRisberg/BING01
proxies/com/microsoft/bingads/campaignmanagement/DeleteTargetFromAdGroupRequest.java
1537
package com.microsoft.bingads.campaignmanagement; 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; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="AdGroupId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "adGroupId" }) @XmlRootElement(name = "DeleteTargetFromAdGroupRequest") public class DeleteTargetFromAdGroupRequest { @XmlElement(name = "AdGroupId") protected Long adGroupId; /** * Gets the value of the adGroupId property. * * @return * possible object is * {@link Long } * */ public Long getAdGroupId() { return adGroupId; } /** * Sets the value of the adGroupId property. * * @param value * allowed object is * {@link Long } * */ public void setAdGroupId(Long value) { this.adGroupId = value; } }
mit
binghuo365/csustRepo
trunk/src/com/yunstudio/dao/PermissonDao.java
137
package com.yunstudio.dao; import com.yunstudio.entity.RepPermission; public interface PermissonDao extends BaseDao<RepPermission>{ }
mit
mattparks/Flounder-Engine
src/flounder/noise/ClassicNoise.java
6979
package flounder.noise; /** * Classic Perlin noise in 3D. */ public class ClassicNoise { private static final int GRAD_3[][] = {{1, 1, 0}, {-1, 1, 0}, {1, -1, 0}, {-1, -1, 0}, {1, 0, 1}, {-1, 0, 1}, {1, 0, -1}, {-1, 0, -1}, {0, 1, 1}, {0, -1, 1}, {0, 1, -1}, {0, -1, -1}}; private static final int P[] = {151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180}; // To remove the need for index wrapping, float the permutation table length. private static final int PERM[] = {151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180, 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180}; private int seed; public ClassicNoise(int seed) { this.seed = seed; } public float noise(float x) { return noise(x, 0.0f, 0.0f); } public float noise(float x, float y) { return noise(x, y, 0.0f); } // Classic Perlin noise, 3D version. public float noise(float x, float y, float z) { // Find unit grid cell containing point. int X = fastfloor(x); int Y = fastfloor(y); int Z = fastfloor(z); // Get relative xyz coordinates of point within that cell. x = x - X; y = y - Y; z = z - Z; // Wrap the integer cells at 255 (smaller integer period can be introduced here). X = X & 255; Y = Y & 255; Z = Z & 255; // Calculate a set of eight hashed gradient indices. int gi000 = PERM[X + PERM[Y + PERM[Z]]] % 12; int gi001 = PERM[X + PERM[Y + PERM[Z + 1]]] % 12; int gi010 = PERM[X + PERM[Y + 1 + PERM[Z]]] % 12; int gi011 = PERM[X + PERM[Y + 1 + PERM[Z + 1]]] % 12; int gi100 = PERM[X + 1 + PERM[Y + PERM[Z]]] % 12; int gi101 = PERM[X + 1 + PERM[Y + PERM[Z + 1]]] % 12; int gi110 = PERM[X + 1 + PERM[Y + 1 + PERM[Z]]] % 12; int gi111 = PERM[X + 1 + PERM[Y + 1 + PERM[Z + 1]]] % 12; // The gradients of each corner are now: // g000 = GRAD_3[gi000]; // g001 = GRAD_3[gi001]; // g010 = GRAD_3[gi010]; // g011 = GRAD_3[gi011]; // g100 = GRAD_3[gi100]; // g101 = GRAD_3[gi101]; // g110 = GRAD_3[gi110]; // g111 = GRAD_3[gi111]; // Calculate noise contributions from each of the eight corners. float n000 = dot(GRAD_3[gi000], x, y, z); float n100 = dot(GRAD_3[gi100], x - 1, y, z); float n010 = dot(GRAD_3[gi010], x, y - 1, z); float n110 = dot(GRAD_3[gi110], x - 1, y - 1, z); float n001 = dot(GRAD_3[gi001], x, y, z - 1); float n101 = dot(GRAD_3[gi101], x - 1, y, z - 1); float n011 = dot(GRAD_3[gi011], x, y - 1, z - 1); float n111 = dot(GRAD_3[gi111], x - 1, y - 1, z - 1); // Compute the fade curve value for each of x, y, z. float u = fade(x); float v = fade(y); float w = fade(z); // Interpolate along x the contributions from each of the corners. float nx00 = mix(n000, n100, u); float nx01 = mix(n001, n101, u); float nx10 = mix(n010, n110, u); float nx11 = mix(n011, n111, u); // Interpolate the four results along y. float nxy0 = mix(nx00, nx10, v); float nxy1 = mix(nx01, nx11, v); // Interpolate the two last results along z. return (float) mix(nxy0, nxy1, w); } public int getSeed() { return seed; } public void setSeed(int seed) { this.seed = seed; } // This method is a *lot* faster than using (int)Math.floor(x) private static int fastfloor(float x) { return x > 0 ? (int) x : (int) x - 1; } private static float dot(int g[], float x, float y, float z) { return g[0] * x + g[1] * y + g[2] * z; } private static float mix(float a, float b, float t) { return (1 - t) * a + t * b; } private static float fade(float t) { return t * t * t * (t * (t * 6 - 15) + 10); } }
mit
zalando/riptide
riptide-logbook/src/main/java/org/zalando/riptide/logbook/package-info.java
124
@ParametersAreNonnullByDefault package org.zalando.riptide.logbook; import javax.annotation.ParametersAreNonnullByDefault;
mit
Azure/azure-sdk-for-java
sdk/resourcemanagerhybrid/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/implementation/DeploymentSlotBaseImpl.java
20320
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.resourcemanager.appservice.implementation; import com.azure.core.util.FluxUtil; import com.azure.resourcemanager.appservice.models.AppSetting; import com.azure.resourcemanager.appservice.models.ConnectionString; import com.azure.resourcemanager.appservice.models.CsmPublishingProfileOptions; import com.azure.resourcemanager.appservice.models.CsmSlotEntity; import com.azure.resourcemanager.appservice.models.DeploymentSlotBase; import com.azure.resourcemanager.appservice.models.HostnameBinding; import com.azure.resourcemanager.appservice.models.MSDeploy; import com.azure.resourcemanager.appservice.models.PublishingProfile; import com.azure.resourcemanager.appservice.models.WebAppBase; import com.azure.resourcemanager.appservice.models.WebAppSourceControl; import com.azure.resourcemanager.appservice.fluent.models.ConnectionStringDictionaryInner; import com.azure.resourcemanager.appservice.fluent.models.IdentifierInner; import com.azure.resourcemanager.appservice.fluent.models.MSDeployStatusInner; import com.azure.resourcemanager.appservice.fluent.models.SiteAuthSettingsInner; import com.azure.resourcemanager.appservice.fluent.models.SiteConfigResourceInner; import com.azure.resourcemanager.appservice.fluent.models.SiteInner; import com.azure.resourcemanager.appservice.fluent.models.SiteLogsConfigInner; import com.azure.resourcemanager.appservice.fluent.models.SitePatchResourceInner; import com.azure.resourcemanager.appservice.fluent.models.SiteSourceControlInner; import com.azure.resourcemanager.appservice.fluent.models.SlotConfigNamesResourceInner; import com.azure.resourcemanager.appservice.fluent.models.StringDictionaryInner; import com.azure.resourcemanager.resources.fluentcore.model.Indexable; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import reactor.core.publisher.Mono; import com.azure.resourcemanager.resources.fluentcore.utils.PagedConverter; /** The implementation for DeploymentSlot. */ abstract class DeploymentSlotBaseImpl< FluentT extends WebAppBase, FluentImplT extends DeploymentSlotBaseImpl<FluentT, FluentImplT, ParentImplT, FluentWithCreateT, FluentUpdateT>, ParentImplT extends AppServiceBaseImpl<?, ?, ?, ?>, FluentWithCreateT, FluentUpdateT> extends WebAppBaseImpl<FluentT, FluentImplT> implements DeploymentSlotBase<FluentT>, DeploymentSlotBase.Update<FluentT> { private final ParentImplT parent; private final String name; WebAppBase configurationSource; DeploymentSlotBaseImpl( String name, SiteInner innerObject, SiteConfigResourceInner siteConfig, SiteLogsConfigInner logConfig, final ParentImplT parent) { super(name.replaceAll(".*/", ""), innerObject, siteConfig, logConfig, parent.manager()); this.name = name.replaceAll(".*/", ""); this.parent = parent; innerModel().withServerFarmId(parent.appServicePlanId()); innerModel().withLocation(regionName()); } @Override public String name() { return name; } @Override public Map<String, HostnameBinding> getHostnameBindings() { return getHostnameBindingsAsync().block(); } @Override @SuppressWarnings("unchecked") public Mono<Map<String, HostnameBinding>> getHostnameBindingsAsync() { return PagedConverter.mapPage(this .manager() .serviceClient() .getWebApps() .listHostnameBindingsSlotAsync(resourceGroupName(), parent().name(), name()), hostNameBindingInner -> new HostnameBindingImpl<FluentT, FluentImplT>( hostNameBindingInner, (FluentImplT) DeploymentSlotBaseImpl.this)) .collectList() .map( hostNameBindings -> Collections .<String, HostnameBinding>unmodifiableMap( hostNameBindings .stream() .collect( Collectors .toMap( binding -> binding.name().replace(name() + "/", ""), Function.identity())))); } @Override public PublishingProfile getPublishingProfile() { return getPublishingProfileAsync().block(); } public Mono<PublishingProfile> getPublishingProfileAsync() { return FluxUtil .collectBytesInByteBufferStream( manager() .serviceClient() .getWebApps() .listPublishingProfileXmlWithSecretsSlotAsync( resourceGroupName(), this.parent().name(), name(), new CsmPublishingProfileOptions())) .map(bytes -> new PublishingProfileImpl(new String(bytes, StandardCharsets.UTF_8), this)); } @Override public void start() { startAsync().block(); } @Override public Mono<Void> startAsync() { return manager() .serviceClient() .getWebApps() .startSlotAsync(resourceGroupName(), this.parent().name(), name()) .then(refreshAsync()) .then(Mono.empty()); } @Override public void stop() { stopAsync().block(); } @Override public Mono<Void> stopAsync() { return manager() .serviceClient() .getWebApps() .stopSlotAsync(resourceGroupName(), this.parent().name(), name()) .then(refreshAsync()) .then(Mono.empty()); } @Override public void restart() { restartAsync().block(); } @Override public Mono<Void> restartAsync() { return manager() .serviceClient() .getWebApps() .restartSlotAsync(resourceGroupName(), this.parent().name(), name()) .then(refreshAsync()) .then(Mono.empty()); } @SuppressWarnings("unchecked") public FluentImplT withBrandNewConfiguration() { this.siteConfig = null; return (FluentImplT) this; } @SuppressWarnings("unchecked") public FluentImplT withConfigurationFromDeploymentSlot(FluentT slot) { this.siteConfig = ((WebAppBaseImpl) slot).siteConfig; configurationSource = slot; return (FluentImplT) this; } Mono<Indexable> submitAppSettings() { return Mono .justOrEmpty(configurationSource) .flatMap( webAppBase -> { if (!isInCreateMode()) { return DeploymentSlotBaseImpl.super.submitAppSettings(); } return webAppBase .getAppSettingsAsync() .flatMap( stringAppSettingMap -> { for (AppSetting appSetting : stringAppSettingMap.values()) { if (appSetting.sticky()) { withStickyAppSetting(appSetting.key(), appSetting.value()); } else { withAppSetting(appSetting.key(), appSetting.value()); } } return DeploymentSlotBaseImpl.super.submitAppSettings(); }); }) .switchIfEmpty(DeploymentSlotBaseImpl.super.submitAppSettings()); } Mono<Indexable> submitConnectionStrings() { return Mono .justOrEmpty(configurationSource) .flatMap( webAppBase -> { if (!isInCreateMode()) { return DeploymentSlotBaseImpl.super.submitConnectionStrings(); } return webAppBase .getConnectionStringsAsync() .flatMap( stringConnectionStringMap -> { for (ConnectionString connectionString : stringConnectionStringMap.values()) { if (connectionString.sticky()) { withStickyConnectionString( connectionString.name(), connectionString.value(), connectionString.type()); } else { withConnectionString( connectionString.name(), connectionString.value(), connectionString.type()); } } return DeploymentSlotBaseImpl.super.submitConnectionStrings(); }); }) .switchIfEmpty(DeploymentSlotBaseImpl.super.submitConnectionStrings()); } public ParentImplT parent() { return this.parent; } @Override Mono<SiteInner> createOrUpdateInner(SiteInner site) { return manager() .serviceClient() .getWebApps() .createOrUpdateSlotAsync(resourceGroupName(), this.parent().name(), name(), site); } @Override Mono<SiteInner> updateInner(SitePatchResourceInner siteUpdate) { return manager() .serviceClient() .getWebApps() .updateSlotAsync(resourceGroupName(), this.parent().name(), name(), siteUpdate); } @Override Mono<SiteInner> getInner() { return manager().serviceClient().getWebApps().getSlotAsync(resourceGroupName(), this.parent().name(), name()); } @Override Mono<SiteConfigResourceInner> getConfigInner() { return manager().serviceClient().getWebApps() .getConfigurationSlotAsync(resourceGroupName(), parent().name(), name()); } @Override Mono<SiteConfigResourceInner> createOrUpdateSiteConfig(SiteConfigResourceInner siteConfig) { return manager() .serviceClient() .getWebApps() .createOrUpdateConfigurationSlotAsync(resourceGroupName(), this.parent().name(), name(), siteConfig); } @Override Mono<Void> deleteHostnameBinding(String hostname) { return manager() .serviceClient() .getWebApps() .deleteHostnameBindingSlotAsync(resourceGroupName(), parent().name(), name(), hostname); } @Override Mono<StringDictionaryInner> listAppSettings() { return manager() .serviceClient() .getWebApps() .listApplicationSettingsSlotAsync(resourceGroupName(), parent().name(), name()); } @Override Mono<StringDictionaryInner> updateAppSettings(StringDictionaryInner inner) { return manager() .serviceClient() .getWebApps() .updateApplicationSettingsSlotAsync(resourceGroupName(), parent().name(), name(), inner); } @Override Mono<ConnectionStringDictionaryInner> listConnectionStrings() { return manager().serviceClient().getWebApps() .listConnectionStringsSlotAsync(resourceGroupName(), parent().name(), name()); } @Override Mono<ConnectionStringDictionaryInner> updateConnectionStrings(ConnectionStringDictionaryInner inner) { return manager() .serviceClient() .getWebApps() .updateConnectionStringsSlotAsync(resourceGroupName(), parent().name(), name(), inner); } @Override Mono<SlotConfigNamesResourceInner> listSlotConfigurations() { return manager().serviceClient().getWebApps() .listSlotConfigurationNamesAsync(resourceGroupName(), parent().name()); } @Override Mono<SlotConfigNamesResourceInner> updateSlotConfigurations(SlotConfigNamesResourceInner inner) { return manager() .serviceClient() .getWebApps() .updateSlotConfigurationNamesAsync(resourceGroupName(), parent().name(), inner); } @Override Mono<SiteSourceControlInner> createOrUpdateSourceControl(SiteSourceControlInner inner) { return manager() .serviceClient() .getWebApps() .createOrUpdateSourceControlSlotAsync(resourceGroupName(), parent().name(), name(), inner); } @Override public void swap(String slotName) { swapAsync(slotName).block(); } @Override public Mono<Void> swapAsync(String slotName) { return manager() .serviceClient() .getWebApps() .swapSlotAsync( resourceGroupName(), this.parent().name(), name(), new CsmSlotEntity().withTargetSlot(slotName)) .then(refreshAsync()) .then(Mono.empty()); } @Override public void applySlotConfigurations(String slotName) { applySlotConfigurationsAsync(slotName).block(); } @Override public Mono<Void> applySlotConfigurationsAsync(String slotName) { return manager() .serviceClient() .getWebApps() .applySlotConfigurationSlotAsync( resourceGroupName(), this.parent().name(), name(), new CsmSlotEntity().withTargetSlot(slotName)) .then(refreshAsync()) .then(Mono.empty()); } @Override public void resetSlotConfigurations() { resetSlotConfigurationsAsync().block(); } @Override public Mono<Void> resetSlotConfigurationsAsync() { return manager() .serviceClient() .getWebApps() .resetSlotConfigurationSlotAsync(resourceGroupName(), this.parent().name(), name()) .then(refreshAsync()) .then(Mono.empty()); } @Override Mono<Void> deleteSourceControl() { return manager() .serviceClient() .getWebApps() .deleteSourceControlSlotAsync(resourceGroupName(), parent().name(), name()) .then(refreshAsync()) .then(Mono.empty()); } @Override Mono<SiteAuthSettingsInner> updateAuthentication(SiteAuthSettingsInner inner) { return manager() .serviceClient() .getWebApps() .updateAuthSettingsSlotAsync(resourceGroupName(), parent().name(), name(), inner); } @Override Mono<SiteAuthSettingsInner> getAuthentication() { return manager().serviceClient().getWebApps() .getAuthSettingsSlotAsync(resourceGroupName(), parent().name(), name()); } @Override Mono<MSDeployStatusInner> createMSDeploy(MSDeploy msDeployInner) { return parent() .manager() .serviceClient() .getWebApps() .createMSDeployOperationAsync(parent().resourceGroupName(), parent().name(), msDeployInner); } @Override public WebAppSourceControl getSourceControl() { return getSourceControlAsync().block(); } @Override public Mono<WebAppSourceControl> getSourceControlAsync() { return manager() .serviceClient() .getWebApps() .getSourceControlSlotAsync(resourceGroupName(), parent().name(), name()) .map( siteSourceControlInner -> new WebAppSourceControlImpl<>(siteSourceControlInner, DeploymentSlotBaseImpl.this)); } @Override public byte[] getContainerLogs() { return getContainerLogsAsync().block(); } @Override public Mono<byte[]> getContainerLogsAsync() { return FluxUtil .collectBytesInByteBufferStream( manager() .serviceClient() .getWebApps() .getWebSiteContainerLogsSlotAsync(resourceGroupName(), parent().name(), name())); } @Override public byte[] getContainerLogsZip() { return getContainerLogsZipAsync().block(); } @Override public Mono<byte[]> getContainerLogsZipAsync() { return FluxUtil .collectBytesInByteBufferStream( manager().serviceClient().getWebApps() .getContainerLogsZipSlotAsync(resourceGroupName(), parent().name(), name())); } @Override Mono<SiteLogsConfigInner> updateDiagnosticLogsConfig(SiteLogsConfigInner siteLogsConfigInner) { return manager() .serviceClient() .getWebApps() .updateDiagnosticLogsConfigSlotAsync(resourceGroupName(), parent().name(), name(), siteLogsConfigInner); } @Override public void verifyDomainOwnership(String certificateOrderName, String domainVerificationToken) { verifyDomainOwnershipAsync(certificateOrderName, domainVerificationToken).block(); } @Override public Mono<Void> verifyDomainOwnershipAsync(String certificateOrderName, String domainVerificationToken) { IdentifierInner identifierInner = new IdentifierInner().withValue(domainVerificationToken); return manager() .serviceClient() .getWebApps() .createOrUpdateDomainOwnershipIdentifierSlotAsync( resourceGroupName(), parent().name(), name(), certificateOrderName, identifierInner) .then(Mono.empty()); } @Override public FluentImplT withRuntime(String runtime) { return withAppSetting(SETTING_FUNCTIONS_WORKER_RUNTIME, runtime); } @Override public FluentImplT withRuntimeVersion(String version) { return withAppSetting(SETTING_FUNCTIONS_EXTENSION_VERSION, version.startsWith("~") ? version : "~" + version); } @Override public FluentImplT withLatestRuntimeVersion() { return withRuntimeVersion("latest"); } @Override public FluentImplT withPublicDockerHubImage(String imageAndTag) { cleanUpContainerSettings(); if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } setAppFrameworkVersion(String.format("DOCKER|%s", imageAndTag)); return withAppSetting(SETTING_DOCKER_IMAGE, imageAndTag); } @Override public FluentImplT withPrivateDockerHubImage(String imageAndTag) { return withPublicDockerHubImage(imageAndTag); } @Override public FluentImplT withPrivateRegistryImage(String imageAndTag, String serverUrl) { imageAndTag = Utils.smartCompletionPrivateRegistryImage(imageAndTag, serverUrl); cleanUpContainerSettings(); if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } setAppFrameworkVersion(String.format("DOCKER|%s", imageAndTag)); withAppSetting(SETTING_DOCKER_IMAGE, imageAndTag); return withAppSetting(SETTING_REGISTRY_SERVER, serverUrl); } @Override public FluentImplT withCredentials(String username, String password) { withAppSetting(SETTING_REGISTRY_USERNAME, username); return withAppSetting(SETTING_REGISTRY_PASSWORD, password); } @Override @SuppressWarnings("unchecked") public FluentImplT withStartUpCommand(String startUpCommand) { if (siteConfig == null) { siteConfig = new SiteConfigResourceInner(); } siteConfig.withAppCommandLine(startUpCommand); return (FluentImplT) this; } protected void cleanUpContainerSettings() { if (siteConfig != null && siteConfig.linuxFxVersion() != null) { siteConfig.withLinuxFxVersion(null); } if (siteConfig != null && siteConfig.windowsFxVersion() != null) { siteConfig.withWindowsFxVersion(null); } // Docker Hub withoutAppSetting(SETTING_DOCKER_IMAGE); withoutAppSetting(SETTING_REGISTRY_SERVER); withoutAppSetting(SETTING_REGISTRY_USERNAME); withoutAppSetting(SETTING_REGISTRY_PASSWORD); } }
mit
dmitriyvolk/mesos-presentation
sqrt/sqrt-client/src/main/java/net/dmitriyvolk/demo/sqrt/client/SqrtClientMain.java
606
package net.dmitriyvolk.demo.sqrt.client; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @EnableAutoConfiguration @ComponentScan @EnableEurekaClient public class SqrtClientMain { public static void main(String[] args) { SpringApplication.run(SqrtClientMain.class, args).getBean(SqrtClient.class).run(); } }
mit
SonarBeserk/Privileges
src/main/java/net/krinsoft/privileges/commands/DemoteCommand.java
1253
package net.krinsoft.privileges.commands; import net.krinsoft.privileges.Privileges; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.permissions.PermissionDefault; import java.util.List; /** * @author krinsdeath */ public class DemoteCommand extends GroupCommand { public DemoteCommand(Privileges plugin) { super(plugin); setName("Privileges: Demote"); setCommandUsage("/demote [user]"); setArgRange(1, 1); addKey("privileges demote"); addKey("priv demote"); addKey("demote"); addKey("dem"); setPermission("privileges.demote", "Allows the sender to demote other users.", PermissionDefault.OP); } @Override public void runCommand(CommandSender sender, List<String> args) { OfflinePlayer target = plugin.getServer().getOfflinePlayer(args.get(0)); if (target == null) { sender.sendMessage(ChatColor.RED + "The target '" + ChatColor.DARK_RED + args.get(0) + ChatColor.RED + "' doesn't exist."); return; } plugin.getGroupManager().demote(sender, target); } }
mit
lakshmi-nair/mozu-java
mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/customer/accounts/CustomerContactUrl.java
4865
/** * This code was auto-generated by a Codezu. * * Changes to this file may cause incorrect behavior and will be lost if * the code is regenerated. */ package com.mozu.api.urls.commerce.customer.accounts; import com.mozu.api.MozuUrl; import com.mozu.api.utils.UrlFormatter; import org.joda.time.DateTime; public class CustomerContactUrl { /** * Get Resource Url for GetAccountContact * @param accountId Unique identifier of the customer account. * @param contactId Unique identifer of the customer account contact being updated. * @param responseFields Use this field to include those fields which are not included by default. * @return String Resource Url */ public static MozuUrl getAccountContactUrl(Integer accountId, Integer contactId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/customer/accounts/{accountId}/contacts/{contactId}?responseFields={responseFields}"); formatter.formatUrl("accountId", accountId); formatter.formatUrl("contactId", contactId); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; } /** * Get Resource Url for GetAccountContacts * @param accountId Unique identifier of the customer account. * @param filter A set of expressions that consist of a field, operator, and value and represent search parameter syntax when filtering results of a query. Valid operators include equals (eq), does not equal (ne), greater than (gt), less than (lt), greater than or equal to (ge), less than or equal to (le), starts with (sw), or contains (cont). For example - "filter=IsDisplayed+eq+true" * @param pageSize The number of results to display on each page when creating paged results from a query. The maximum value is 200. * @param responseFields Use this field to include those fields which are not included by default. * @param sortBy * @param startIndex * @return String Resource Url */ public static MozuUrl getAccountContactsUrl(Integer accountId, String filter, Integer pageSize, String responseFields, String sortBy, Integer startIndex) { UrlFormatter formatter = new UrlFormatter("/api/commerce/customer/accounts/{accountId}/contacts?startIndex={startIndex}&pageSize={pageSize}&sortBy={sortBy}&filter={filter}&responseFields={responseFields}"); formatter.formatUrl("accountId", accountId); formatter.formatUrl("filter", filter); formatter.formatUrl("pageSize", pageSize); formatter.formatUrl("responseFields", responseFields); formatter.formatUrl("sortBy", sortBy); formatter.formatUrl("startIndex", startIndex); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; } /** * Get Resource Url for AddAccountContact * @param accountId Unique identifier of the customer account. * @param responseFields Use this field to include those fields which are not included by default. * @return String Resource Url */ public static MozuUrl addAccountContactUrl(Integer accountId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/customer/accounts/{accountId}/contacts?responseFields={responseFields}"); formatter.formatUrl("accountId", accountId); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; } /** * Get Resource Url for UpdateAccountContact * @param accountId Unique identifier of the customer account. * @param contactId Unique identifer of the customer account contact being updated. * @param responseFields Use this field to include those fields which are not included by default. * @return String Resource Url */ public static MozuUrl updateAccountContactUrl(Integer accountId, Integer contactId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/customer/accounts/{accountId}/contacts/{contactId}?responseFields={responseFields}"); formatter.formatUrl("accountId", accountId); formatter.formatUrl("contactId", contactId); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; } /** * Get Resource Url for DeleteAccountContact * @param accountId Unique identifier of the customer account. * @param contactId Unique identifer of the customer account contact being updated. * @return String Resource Url */ public static MozuUrl deleteAccountContactUrl(Integer accountId, Integer contactId) { UrlFormatter formatter = new UrlFormatter("/api/commerce/customer/accounts/{accountId}/contacts/{contactId}"); formatter.formatUrl("accountId", accountId); formatter.formatUrl("contactId", contactId); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; } }
mit
dbuxo/CommandHelper
src/main/java/com/laytonsmith/core/events/Prefilters.java
10417
package com.laytonsmith.core.events; import com.laytonsmith.PureUtilities.Common.ReflectionUtils; import com.laytonsmith.abstraction.MCLocation; import com.laytonsmith.core.ObjectGenerator; import com.laytonsmith.core.Static; import com.laytonsmith.core.constructs.CBoolean; import com.laytonsmith.core.constructs.CDouble; import com.laytonsmith.core.constructs.CInt; import com.laytonsmith.core.constructs.CString; import com.laytonsmith.core.constructs.Construct; import com.laytonsmith.core.constructs.Target; import com.laytonsmith.core.exceptions.ConfigRuntimeException; import com.laytonsmith.core.exceptions.PrefilterNonMatchException; import com.laytonsmith.core.functions.Exceptions.ExceptionType; import java.util.Map; /** * * */ public final class Prefilters { private Prefilters(){} public enum PrefilterType{ /** * Item matches are fuzzy matches for item notation. Red wool and black wool * will match. Essentially, this match ignores the item's data value when * comparing. */ ITEM_MATCH, /** * Checks if indexes 'x', 'y', 'z' and 'world' (or 0, 1, 2, 3) of a location array match. * The location is matched via block matching, for instance if the array's x parameter is 1, 1.3 will match. */ LOCATION_MATCH, /** * Simple boolean match. */ BOOLEAN_MATCH, /** * String matches are just exact string matches. */ STRING_MATCH, /** * Math match parses numbers out and checks to see if the numbers * are equivalent. i.e. 1.0 does equal 1. */ MATH_MATCH, /** * Regexes allow for more complex matching. A full blown regular expression * is accepted as the argument. */ REGEX, /** * An expression allows for more complex numerical matching. Similar to a regex, * but designed for numerical values. This requires WorldEdit in plugins, lib, * or in the server root to function. */ EXPRESSION, /** * A macro expression allows for either an exact string match, or a regular expression, * or an expression. It is parsed according to the format of the prefilter. In * general, this should be used most often for things that are not definitively * another type, so as to give scripts more flexibility. */ MACRO } public static void match(Map<String, Construct> map, String key, String actualValue, PrefilterType type) throws PrefilterNonMatchException{ match(map, key, new CString(actualValue, Target.UNKNOWN), type); } public static void match(Map<String, Construct> map, String key, int actualValue, PrefilterType type) throws PrefilterNonMatchException{ match(map, key, new CInt(actualValue, Target.UNKNOWN), type); } public static void match(Map<String, Construct> map, String key, double actualValue, PrefilterType type) throws PrefilterNonMatchException{ match(map, key, new CDouble(actualValue, Target.UNKNOWN), type); } public static void match(Map<String, Construct> map, String key, boolean actualValue, PrefilterType type) throws PrefilterNonMatchException { match(map, key, CBoolean.get(actualValue), type); } public static void match(Map<String, Construct> map, String key, MCLocation actualValue, PrefilterType type) throws PrefilterNonMatchException { match(map, key, ObjectGenerator.GetGenerator().location(actualValue, false), type); } /** * Given a prototype and the actual user provided value, determines if it matches. * If it doesn't, it throws an exception. If the value is not provided, or it does * match, it returns void, which means that the test passed, and the event matches. */ public static void match(Map<String, Construct> map, String key, Construct actualValue, PrefilterType type) throws PrefilterNonMatchException{ if(map.containsKey(key)){ switch(type){ case ITEM_MATCH: ItemMatch(map.get(key), actualValue); break; case STRING_MATCH: StringMatch(map.get(key).val(), actualValue.val()); break; case MATH_MATCH: MathMatch(map.get(key), actualValue); break; case EXPRESSION: ExpressionMatch(MathReplace(key, map.get(key), actualValue), actualValue); break; case REGEX: RegexMatch(map.get(key), actualValue); break; case MACRO: MacroMatch(key, map.get(key), actualValue); break; case BOOLEAN_MATCH: BooleanMatch(map.get(key), actualValue); break; case LOCATION_MATCH: LocationMatch(map.get(key), actualValue); break; } } } private static void ItemMatch(Construct item1, Construct item2) throws PrefilterNonMatchException{ String i1 = item1.val(); String i2 = item2.val(); if(item1.val().contains(":")){ String[] split = item1.val().split(":"); i1 = split[0].trim(); } if(item2.val().contains(":")){ String[] split = item2.val().split(":"); i2 = split[0].trim(); } if(!i1.trim().equalsIgnoreCase(i2.trim())){ throw new PrefilterNonMatchException(); } } private static void BooleanMatch(Construct bool1, Construct bool2) throws PrefilterNonMatchException { if (Static.getBoolean(bool1) != Static.getBoolean(bool2)) { throw new PrefilterNonMatchException(); } } private static void LocationMatch(Construct location1, Construct location2) throws PrefilterNonMatchException { MCLocation l1 = ObjectGenerator.GetGenerator().location(location1, null, location1.getTarget()); MCLocation l2 = ObjectGenerator.GetGenerator().location(location2, null, Target.UNKNOWN); if ((!l1.getWorld().equals(l2.getWorld())) || (l1.getBlockX() != l2.getBlockX()) || (l1.getBlockY() != l2.getBlockY()) || (l1.getBlockZ() != l2.getBlockZ())) { throw new PrefilterNonMatchException(); } } private static void StringMatch(String string1, String string2) throws PrefilterNonMatchException{ if(!string1.equals(string2)){ throw new PrefilterNonMatchException(); } } private static void MathMatch(Construct one, Construct two) throws PrefilterNonMatchException{ try{ double dOne = Static.getNumber(one, Target.UNKNOWN); double dTwo = Static.getNumber(two, Target.UNKNOWN); if(dOne != dTwo){ throw new PrefilterNonMatchException(); } } catch(ConfigRuntimeException e){ throw new PrefilterNonMatchException(); } } private static void ExpressionMatch(Construct expression, Construct dvalue) throws PrefilterNonMatchException{ if(expression.val().matches("\\(.*\\)")){ String exp = expression.val().substring(1, expression.val().length() - 1); boolean inequalityMode = false; if(exp.contains("<") || exp.contains(">") || exp.contains("==")){ inequalityMode = true; } String eClass = "com.sk89q.worldedit.internal.expression.Expression"; String errClass = "com.sk89q.worldedit.internal.expression.ExpressionException"; Class eClazz, errClazz; try { eClazz = Class.forName(eClass); errClazz = Class.forName(errClass); } catch (ClassNotFoundException cnf) { throw new ConfigRuntimeException("You are missing a required dependency: " + eClass, ExceptionType.PluginInternalException, expression.getTarget(), cnf); } try { Object e = ReflectionUtils.invokeMethod(eClazz, null, "compile", new Class[]{String.class}, new Object[]{exp}); double val = (double) ReflectionUtils.invokeMethod(eClazz, e, "evaluate"); if (inequalityMode) { if (val == 0) { throw new PrefilterNonMatchException(); } } else { if (val != Static.getDouble(dvalue, Target.UNKNOWN)) { throw new PrefilterNonMatchException(); } } } catch (ReflectionUtils.ReflectionException rex) { if (rex.getCause().getClass().isAssignableFrom(errClazz)) { throw new ConfigRuntimeException("Your expression was invalidly formatted", ExceptionType.PluginInternalException, expression.getTarget(), rex.getCause()); } else { throw new ConfigRuntimeException(rex.getMessage(), ExceptionType.PluginInternalException, expression.getTarget(), rex.getCause()); } } } else { throw new ConfigRuntimeException("Prefilter expecting expression type, and \"" + expression.val() + "\" does not follow expression format. " + "(Did you surround it in parenthesis?)", ExceptionType.FormatException, expression.getTarget()); } } private static void RegexMatch(Construct expression, Construct value) throws PrefilterNonMatchException{ if(expression.val().matches("/.*/")){ String exp = expression.val().substring(1, expression.val().length() - 1); if(!value.val().matches(exp)){ throw new PrefilterNonMatchException(); } } else { throw new ConfigRuntimeException("Prefilter expecting regex type, and \"" + expression.val() + "\" does not follow regex format", ExceptionType.FormatException, expression.getTarget()); } } private static void MacroMatch(String key, Construct expression, Construct value) throws PrefilterNonMatchException{ if(expression.val().matches("\\(.*\\)")){ ExpressionMatch(MathReplace(key, expression, value), value); } else if(expression.val().matches("/.*/")){ RegexMatch(expression, value); } else { StringMatch(expression.val(), value.val()); } } private static Construct MathReplace(String key, Construct expression, Construct value){ return new CString(expression.val().replaceAll(key, value.val()), expression.getTarget()); } }
mit
mallowigi/material-theme-jetbrains
src/main/java/com/chrisrm/idea/ui/MTPasswordFieldUI.java
7338
/* * The MIT License (MIT) * * Copyright (c) 2018 Chris Magnussen and Elior Boukhobza * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * */ package com.chrisrm.idea.ui; import com.intellij.openapi.ui.GraphicsConfig; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.IconLoader; import com.intellij.util.ui.JBInsets; import com.intellij.util.ui.JBUI; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.border.Border; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicPasswordFieldUI; import javax.swing.text.JTextComponent; import java.awt.*; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; /** * @author Konstantin Bulenkov */ public final class MTPasswordFieldUI extends BasicPasswordFieldUI implements Condition { /** * The JComponent for this MTPasswordUI */ private final JPasswordField passwordField; /** * Adapter for mouse clicks */ private MyMouseAdapter myMouseAdapter; /** * Adapter for Field focus */ private FocusAdapter myFocusAdapter; /** * Flag setting echoChar for this password field */ private boolean echoCharIsSet = true; private MTPasswordFieldUI(final JPasswordField passwordField) { this.passwordField = passwordField; } public static ComponentUI createUI(final JComponent c) { return new MTPasswordFieldUI((JPasswordField) c); } @Override public void installListeners() { final MTPasswordFieldUI ui = this; myFocusAdapter = new MyFocusAdapter(); passwordField.addFocusListener(myFocusAdapter); myMouseAdapter = new MyMouseAdapter(ui); passwordField.addMouseListener(myMouseAdapter); } @Override public boolean value(final Object o) { if (o instanceof MouseEvent) { final MouseEvent me = (MouseEvent) o; if (getActionUnder(me.getPoint()) != null) { if (me.getID() == MouseEvent.MOUSE_CLICKED) { SwingUtilities.invokeLater(() -> myMouseAdapter.mouseClicked(me)); } return true; } } return false; } @Override protected void uninstallListeners() { passwordField.removeFocusListener(myFocusAdapter); passwordField.removeMouseListener(myMouseAdapter); } @Override protected void paintBackground(final Graphics graphics) { final Graphics2D g = (Graphics2D) graphics; final JTextComponent c = getComponent(); final Container parent = c.getParent(); if (c.isOpaque() && parent != null) { g.setColor(parent.getBackground()); g.fillRect(0, 0, c.getWidth(), c.getHeight()); } final Border border = c.getBorder(); if (border instanceof MTTextBorder) { if (c.isEnabled() && c.isEditable()) { g.setColor(c.getBackground()); } final int width = c.getWidth(); final int height = c.getHeight(); final Insets i = border.getBorderInsets(c); if (c.hasFocus()) { final GraphicsConfig config = new GraphicsConfig(g); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); g.fillRoundRect(i.left - JBUI.scale(5), i.top - JBUI.scale(2), width - i.left - i.right + JBUI.scale(10), height - i.top - i.bottom + JBUI.scale(6), JBUI.scale(5), JBUI.scale(5)); // Paint the preview icon final Point p = getPreviewIconCoord(); final String path = echoCharIsSet ? "/icons/mt/eye.svg" : "/icons/mt/eye-off.svg"; final Icon searchIcon = IconLoader.findIcon(path, MTPasswordFieldUI.class, true); searchIcon.paintIcon(null, g, p.x, p.y); config.restore(); } else { g.fillRect(i.left - JBUI.scale(5), i.top - JBUI.scale(2), width - i.left - i.right + JBUI.scale(12), height - i.top - i .bottom + JBUI.scale(6)); } } else { super.paintBackground(g); } } /** * Return the action under the mouse location * * @param p coordinate of the mouse event location * @return the PasswordActions if the event is under the given offset */ private PasswordActions getActionUnder(@NotNull final Point p) { final int off = JBUI.scale(8); final Point point = new Point(p.x - off, p.y - off); if (point.distance(getPreviewIconCoord()) <= off) { return PasswordActions.PREVIEW; } return null; } private Rectangle getDrawingRect() { final JComponent c = passwordField; final JBInsets i = JBInsets.create(c.getInsets()); final int x = i.right - JBUI.scale(4) - JBUI.scale(16 * 2); final int y = i.top - JBUI.scale(3); final int w = c.getWidth() - i.width() + JBUI.scale(16 * 2 + 7 * 2 - 5); int h = c.getBounds().height - i.height() + JBUI.scale(4 * 2 - 3); if (h % 2 == 1) { h++; } return new Rectangle(x, y, w, h); } private Point getPreviewIconCoord() { final Rectangle r = getDrawingRect(); return new Point(r.x + r.width - JBUI.scale(16), r.y + (r.height - JBUI.scale(16)) / 2); } public enum PasswordActions { PREVIEW } private class MyMouseAdapter extends MouseAdapter { private final MTPasswordFieldUI myUi; MyMouseAdapter(final MTPasswordFieldUI ui) { myUi = ui; } @Override public void mouseClicked(final MouseEvent e) { final PasswordActions action = myUi.getActionUnder(e.getPoint()); if (action != null) { switch (action) { case PREVIEW: if (echoCharIsSet) { passwordField.setEchoChar('\0'); echoCharIsSet = false; } else { passwordField.setEchoChar((char) 0x2022); echoCharIsSet = true; } break; default: break; } } e.consume(); } } private class MyFocusAdapter extends FocusAdapter { @Override public void focusGained(final FocusEvent e) { passwordField.repaint(); } @Override public void focusLost(final FocusEvent e) { passwordField.repaint(); } } }
mit
tcsiwula/java_code
classes/cs345/code_examples/lip_book/parsing/memoize/BacktrackLexer.java
2179
/*** * Excerpted from "Language Implementation Patterns", * published by The Pragmatic Bookshelf. * Copyrights apply to this code. It may not be used to create training material, * courses, books, articles, and the like. Contact us if you are in doubt. * We make no guarantees that this code is fit for any purpose. * Visit http://www.pragmaticprogrammer.com/titles/tpdsl for more book information. ***/ public class BacktrackLexer extends Lexer { public static int NAME = 2; public static int COMMA = 3; public static int LBRACK = 4; public static int RBRACK = 5; public static int EQUALS = 6; public static String[] tokenNames = { "n/a", "<EOF>", "NAME", ",", "[", "]", "=" }; public String getTokenName(int x) { return BacktrackLexer.tokenNames[x]; } public BacktrackLexer(String input) { super(input); } boolean isLETTER() { return (c>='a'&&c<='z') || (c>='A'&&c<='Z'); } public Token nextToken() { while ( c!=EOF ) { switch ( c ) { case ' ': case '\t': case '\n': case '\r': WS(); continue; case ',' : consume(); return new Token(COMMA, ","); case '[' : consume(); return new Token(LBRACK, "["); case ']' : consume(); return new Token(RBRACK, "]"); case '=' : consume(); return new Token(EQUALS, "="); default: if ( isLETTER() ) return name(); throw new Error("invalid character: "+c); } } return new Token(EOF_TYPE,"<EOF>"); } /** name : LETTER+ ; // name is sequence of >=1 letter */ Token name() { StringBuilder buf = new StringBuilder(); while ( isLETTER() ) { buf.append(c); LETTER(); } return new Token(NAME, buf.toString()); } /** LETTER : 'a'..'z'|'A'..'Z'; // define what a letter is (\w) */ void LETTER() { if ( isLETTER() ) consume(); else throw new Error("expecting LETTER; found "+c); } /** WS : (' '|'\t'|'\n'|'\r')* ; // ignore any whitespace */ void WS() { while ( c==' ' || c=='\t' || c=='\n' || c=='\r' ) advance(); } }
mit
maciej7777/PrometheeDiviz
plotClassAssignments-png/src/pl/poznan/put/promethee/components/PaintComponent.java
8065
package pl.poznan.put.promethee.components; import pl.poznan.put.promethee.xmcda.InputsHandler; import javax.imageio.*; import java.awt.geom.RoundRectangle2D; import java.awt.image.*; import java.awt.*; import java.io.*; /** * Created by Maciej Uniejewski on 2016-12-30. */ public class PaintComponent { private static int width = 1; private static int height = 1; private PaintComponent() { } public static byte[] drawImage(InputsHandler.Inputs inputs) { byte[] bytes = null; int categoriesNumber = inputs.getCategoriesIds().size(); BufferedImage tmpImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Color gray = new Color(184, 184, 184); Graphics2D tmpGraphic = tmpImage.createGraphics(); Font font = new Font("TimesRoman", Font.BOLD, 16); tmpGraphic.setFont(font); tmpGraphic.setColor(Color.black); int maxAlternativeWidth = 0; FontMetrics metrics = tmpGraphic.getFontMetrics(font); for (int i = 0; i < inputs.getAlternativesIds().size(); i++) { String alternativeId = inputs.getAlternativesIds().get(i); if (maxAlternativeWidth < metrics.stringWidth(alternativeId)) { maxAlternativeWidth = metrics.stringWidth(alternativeId); } } int maxCategoryWidth = 0; for (int j = 0; j < inputs.getCategoriesIds().size(); j++) { String categoryId = inputs.getCategoriesIds().get(j); if (maxCategoryWidth < metrics.stringWidth(categoryId)) { maxCategoryWidth = metrics.stringWidth(categoryId); } } int categoryWidth = Math.max(60, maxCategoryWidth+10); int moveRight = 80 + maxAlternativeWidth; height = 100 * inputs.getAlternativesIds().size(); width = categoryWidth * categoriesNumber + moveRight + 20; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = image.createGraphics(); g2d.setFont(font); g2d.setColor(Color.white); g2d.fillRect(0, 0, width, height); for (int i = 0; i < inputs.getAlternativesIds().size(); i++) { g2d.setColor(Color.black); int y = ((100 - metrics.getHeight()) / 2) + metrics.getAscent() + i*100; g2d.drawString(inputs.getAlternativesIds().get(i), 20, y); String alternativeId = inputs.getAlternativesIds().get(i); String lowerId = inputs.getAssignments().get(alternativeId).get("LOWER"); String upperId = inputs.getAssignments().get(alternativeId).get("UPPER"); int lowerBound = inputs.getCategoriesRanking().get(lowerId); int upperBound = inputs.getCategoriesRanking().get(upperId); for (int j = lowerBound - 1; j < upperBound; j++) { g2d.setColor(gray); g2d.fillRect(moveRight+categoryWidth*j, 100*i+20, categoryWidth, 60); } for (int k = 0; k < inputs.getCategoriesIds().size(); k++) { String categoryId = inputs.getCategoriesIds().get(k); g2d.setColor(Color.black); int x = moveRight + categoryWidth*k + (categoryWidth - metrics.stringWidth(categoryId)) / 2; y = ((100 - metrics.getHeight()) / 2) + metrics.getAscent() + i*100; g2d.drawString(categoryId, x, y); g2d.drawLine(moveRight + k *categoryWidth, i*100 + 20, moveRight + k *categoryWidth, i*100 + 80); } g2d.drawLine(moveRight + categoriesNumber *categoryWidth, i*100 + 20, moveRight + categoriesNumber *categoryWidth, i*100 + 80); g2d.setColor(Color.black); g2d.drawLine(moveRight, i*100 + 20, moveRight + categoriesNumber*categoryWidth, i*100 + 20); g2d.drawLine(moveRight, i*100 + 80, moveRight + categoriesNumber*categoryWidth, i*100 + 80); } g2d.dispose(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "jpg", baos); bytes = baos.toByteArray(); } catch (IOException e) { e.printStackTrace(); } return bytes; } public static byte[] drawImageVersion2(InputsHandler.Inputs inputs) { byte[] bytes = null; int categoriesNumber = inputs.getCategoriesIds().size(); int alternativesNumber = inputs.getAlternativesIds().size(); BufferedImage tmpImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D tmpGraphic = tmpImage.createGraphics(); Font font = new Font("TimesRoman", Font.BOLD, 16); tmpGraphic.setFont(font); tmpGraphic.setColor(Color.black); int maxAlternativeWidth = 0; FontMetrics metrics = tmpGraphic.getFontMetrics(font); for (int i = 0; i < inputs.getAlternativesIds().size(); i++) { String alternativeId = inputs.getAlternativesIds().get(i); if (maxAlternativeWidth < metrics.stringWidth(alternativeId)) { maxAlternativeWidth = metrics.stringWidth(alternativeId); } } int maxCategoryWidth = 0; for (int j = 0; j < inputs.getCategoriesIds().size(); j++) { String categoryId = inputs.getCategoriesIds().get(j); if (maxCategoryWidth < metrics.stringWidth(categoryId)) { maxCategoryWidth = metrics.stringWidth(categoryId); } } int categoryWidth = Math.max(60, maxCategoryWidth+10); int moveRight = 80 + maxAlternativeWidth; height = 70 * inputs.getAlternativesIds().size() + 60; width = categoryWidth * categoriesNumber + moveRight + 20; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = image.createGraphics(); g2d.setFont(font); g2d.setColor(Color.white); g2d.fillRect(0, 0, width, height); Stroke normal = new BasicStroke(3); Stroke dashed = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{9}, 0); for (int k = 0; k < inputs.getCategoriesIds().size(); k++) { String categoryId = inputs.getCategoriesIds().get(k); g2d.setColor(Color.black); int x = moveRight + categoryWidth*k + (categoryWidth - metrics.stringWidth(categoryId)) / 2; int y = ((40 - metrics.getHeight()) / 2) + metrics.getAscent(); g2d.drawString(categoryId, x, y); g2d.setStroke(dashed); if (k != 0) { g2d.drawLine(moveRight + k * categoryWidth, 0, moveRight + k * categoryWidth, alternativesNumber * 100 + 60); } } for (int i = 0; i < inputs.getAlternativesIds().size(); i++) { g2d.setColor(Color.black); int y = ((70 - metrics.getHeight()) / 2) + metrics.getAscent() + i*70 + 40; g2d.drawString(inputs.getAlternativesIds().get(i), 20, y); String alternativeId = inputs.getAlternativesIds().get(i); String lowerId = inputs.getAssignments().get(alternativeId).get("LOWER"); String upperId = inputs.getAssignments().get(alternativeId).get("UPPER"); int lowerBound = inputs.getCategoriesRanking().get(lowerId); int upperBound = inputs.getCategoriesRanking().get(upperId); g2d.setStroke(normal); RoundRectangle2D roundedRectangle = new RoundRectangle2D.Float(moveRight + categoryWidth*(lowerBound-1), 70 * i + 50, categoryWidth * (upperBound - lowerBound + 1), 50, 10, 10); g2d.draw(roundedRectangle); } g2d.dispose(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "jpg", baos); bytes = baos.toByteArray(); } catch (IOException e) { e.printStackTrace(); } return bytes; } }
mit
zaoying/EChartsAnnotation
src/cn/edu/gdut/zaoying/Option/xAxis/splitArea/areaStyle/OpacityNumber.java
352
package cn.edu.gdut.zaoying.Option.xAxis.splitArea.areaStyle; 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 OpacityNumber { double value() default 0; }
mit
JeffRisberg/BING01
src/test/java/com/microsoft/bingads/v10/api/test/operations/bulk_download_operation/BulkDownloadOperationTest.java
1929
package com.microsoft.bingads.v10.api.test.operations.bulk_download_operation; import com.microsoft.bingads.AuthorizationData; import com.microsoft.bingads.PasswordAuthentication; import com.microsoft.bingads.v10.api.test.operations.FakeApiTest; import com.microsoft.bingads.v10.bulk.ArrayOfKeyValuePairOfstringstring; import com.microsoft.bingads.v10.bulk.BulkDownloadOperation; import com.microsoft.bingads.v10.bulk.GetBulkDownloadStatusResponse; import com.microsoft.bingads.v10.bulk.IBulkService; public class BulkDownloadOperationTest extends FakeApiTest { protected IBulkService service; private static AuthorizationData createUserData() { AuthorizationData authorizationData = new AuthorizationData(); authorizationData.setAuthentication(new PasswordAuthentication("user", "pass")); authorizationData.setAccountId(123L); authorizationData.setCustomerId(456L); authorizationData.setDeveloperToken("dev"); return authorizationData; } protected BulkDownloadOperation createBulkDownloadOperation(Integer statusCheckIntervalInMs) { BulkDownloadOperation operation = new BulkDownloadOperation("request123", createUserData()); if (statusCheckIntervalInMs != null) { operation.setStatusPollIntervalInMilliseconds(statusCheckIntervalInMs); } return operation; } protected GetBulkDownloadStatusResponse createStatusResponse(Integer percentComplete, String status, String resultFileUrl) { GetBulkDownloadStatusResponse response = new GetBulkDownloadStatusResponse(); response.setForwardCompatibilityMap(new ArrayOfKeyValuePairOfstringstring()); response.setPercentComplete(percentComplete); response.setRequestStatus(status); response.setResultFileUrl(resultFileUrl); return response; } public BulkDownloadOperationTest() { super(); } }
mit
unchartedsoftware/aperture-tiles
annotation-service/src/main/java/com/oculusinfo/annotation/filter/impl/ScriptableFilterFactory.java
2294
/* * Copyright (c) 2014 Oculus Info Inc. * http://www.oculusinfo.com/ * * Released under the MIT License. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.oculusinfo.annotation.filter.impl; import com.oculusinfo.annotation.filter.AnnotationFilter; import com.oculusinfo.factory.ConfigurableFactory; import com.oculusinfo.factory.properties.StringProperty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; public class ScriptableFilterFactory extends ConfigurableFactory<AnnotationFilter> { private static final Logger LOGGER = LoggerFactory.getLogger(ScriptableFilterFactory.class); public static StringProperty SCRIPT_STRING = new StringProperty("script", "The javascript script string that evaluates to a boolean based off a single annotation", null); public ScriptableFilterFactory(ConfigurableFactory<?> parent, List<String> path) { super("scriptable", AnnotationFilter.class, parent, path); addProperty(SCRIPT_STRING); } @Override protected AnnotationFilter create() { try { String script = getPropertyValue(SCRIPT_STRING); return new ScriptableFilter(script); } catch (Exception e) { LOGGER.error("Error trying to create ScriptableFilter", e); } return null; } }
mit
Kiandr/CrackingCodingInterview
java/Ch 16. Moderate/Q16_12_XML_Encoding/QuestionOO.java
1343
package Q16_12_XML_Encoding; public class QuestionOO { public static void encode(String v, StringBuilder sb) { v = v.replace("0", "\\0"); sb.append(v); sb.append(" "); } public static void encodeEnd(StringBuilder sb) { sb.append("0"); sb.append(" "); } public static void encode(Attribute attr, StringBuilder sb) { encode(attr.getTagCode(), sb); encode(attr.value, sb); } public static void encode(Element root, StringBuilder sb) { encode(root.getNameCode(), sb); for (Attribute a : root.attributes) { encode(a, sb); } encodeEnd(sb); if (root.value != null && root.value != "") { encode(root.value, sb); } else { for (Element e : root.children) { encode(e, sb); } } encodeEnd(sb); } public static String encodeToString(Element root) { StringBuilder sb = new StringBuilder(); encode(root, sb); return sb.toString(); } public static void main(String args[]) { Element root = new Element("family"); Attribute a1 = new Attribute("lastName", "mcdowell"); Attribute a2 = new Attribute("state", "CA"); root.insert(a1); root.insert(a2); Element child = new Element("person", "Some Message"); Attribute a3 = new Attribute("firstName", "Gayle"); child.insert(a3); root.insert(child); String s = encodeToString(root); System.out.println(s); } }
mit
navalev/azure-sdk-for-java
sdk/network/mgmt-v2019_04_01/src/main/java/com/microsoft/azure/management/network/v2019_04_01/VirtualNetworkGatewaySkuTier.java
3220
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2019_04_01; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for VirtualNetworkGatewaySkuTier. */ public final class VirtualNetworkGatewaySkuTier extends ExpandableStringEnum<VirtualNetworkGatewaySkuTier> { /** Static value Basic for VirtualNetworkGatewaySkuTier. */ public static final VirtualNetworkGatewaySkuTier BASIC = fromString("Basic"); /** Static value HighPerformance for VirtualNetworkGatewaySkuTier. */ public static final VirtualNetworkGatewaySkuTier HIGH_PERFORMANCE = fromString("HighPerformance"); /** Static value Standard for VirtualNetworkGatewaySkuTier. */ public static final VirtualNetworkGatewaySkuTier STANDARD = fromString("Standard"); /** Static value UltraPerformance for VirtualNetworkGatewaySkuTier. */ public static final VirtualNetworkGatewaySkuTier ULTRA_PERFORMANCE = fromString("UltraPerformance"); /** Static value VpnGw1 for VirtualNetworkGatewaySkuTier. */ public static final VirtualNetworkGatewaySkuTier VPN_GW1 = fromString("VpnGw1"); /** Static value VpnGw2 for VirtualNetworkGatewaySkuTier. */ public static final VirtualNetworkGatewaySkuTier VPN_GW2 = fromString("VpnGw2"); /** Static value VpnGw3 for VirtualNetworkGatewaySkuTier. */ public static final VirtualNetworkGatewaySkuTier VPN_GW3 = fromString("VpnGw3"); /** Static value VpnGw1AZ for VirtualNetworkGatewaySkuTier. */ public static final VirtualNetworkGatewaySkuTier VPN_GW1AZ = fromString("VpnGw1AZ"); /** Static value VpnGw2AZ for VirtualNetworkGatewaySkuTier. */ public static final VirtualNetworkGatewaySkuTier VPN_GW2AZ = fromString("VpnGw2AZ"); /** Static value VpnGw3AZ for VirtualNetworkGatewaySkuTier. */ public static final VirtualNetworkGatewaySkuTier VPN_GW3AZ = fromString("VpnGw3AZ"); /** Static value ErGw1AZ for VirtualNetworkGatewaySkuTier. */ public static final VirtualNetworkGatewaySkuTier ER_GW1AZ = fromString("ErGw1AZ"); /** Static value ErGw2AZ for VirtualNetworkGatewaySkuTier. */ public static final VirtualNetworkGatewaySkuTier ER_GW2AZ = fromString("ErGw2AZ"); /** Static value ErGw3AZ for VirtualNetworkGatewaySkuTier. */ public static final VirtualNetworkGatewaySkuTier ER_GW3AZ = fromString("ErGw3AZ"); /** * Creates or finds a VirtualNetworkGatewaySkuTier from its string representation. * @param name a name to look for * @return the corresponding VirtualNetworkGatewaySkuTier */ @JsonCreator public static VirtualNetworkGatewaySkuTier fromString(String name) { return fromString(name, VirtualNetworkGatewaySkuTier.class); } /** * @return known VirtualNetworkGatewaySkuTier values */ public static Collection<VirtualNetworkGatewaySkuTier> values() { return values(VirtualNetworkGatewaySkuTier.class); } }
mit
seleniumQuery/seleniumQuery-demos
src/main/java/plugin/SizerPlugin.java
1134
/* * Copyright (c) 2017 seleniumQuery authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package plugin; import io.github.seleniumquery.SeleniumQueryObject; import io.github.seleniumquery.functions.as.SeleniumQueryPlugin; public class SizerPlugin { public static final SeleniumQueryPlugin<SizerPlugin> SIZER = SizerPlugin::new; private SeleniumQueryObject seleniumQueryObject; private SizerPlugin(SeleniumQueryObject seleniumQueryObject) { this.seleniumQueryObject = seleniumQueryObject; } public int gimmeTheSize() { return this.seleniumQueryObject.get().size(); } }
mit
CentralsoftTrain2016/DailyMiniTestSupport
DailyMiniTestSupport/src/domain/value/id/ChoiceID.java
203
package domain.value.id; import java.math.BigDecimal; public class ChoiceID extends ID{ public ChoiceID(String choiceID) { super(choiceID); } public ChoiceID(BigDecimal id) { super(id); } }
cc0-1.0
kgibm/open-liberty
dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/view/facelets/tag/ui/LegacyIncludeHandler.java
10816
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.myfaces.view.facelets.tag.ui; import java.io.IOException; import java.net.URL; import java.util.Collection; import javax.el.ELException; import javax.el.ValueExpression; import javax.el.VariableMapper; import javax.faces.FacesException; import javax.faces.application.ProjectStage; import javax.faces.application.StateManager; import javax.faces.component.UIComponent; import javax.faces.event.PhaseId; import javax.faces.view.facelets.FaceletContext; import javax.faces.view.facelets.FaceletException; import javax.faces.view.facelets.TagAttribute; import javax.faces.view.facelets.TagConfig; import javax.faces.view.facelets.TagHandler; import org.apache.myfaces.shared.util.ClassUtils; import org.apache.myfaces.view.facelets.AbstractFaceletContext; import org.apache.myfaces.view.facelets.FaceletCompositionContext; import org.apache.myfaces.view.facelets.el.VariableMapperWrapper; import org.apache.myfaces.view.facelets.tag.ComponentContainerHandler; import org.apache.myfaces.view.facelets.tag.TagHandlerUtils; import org.apache.myfaces.view.facelets.tag.jsf.ComponentSupport; /** * The include tag can point at any Facelet which might use the composition tag, * component tag, or simply be straight XHTML/XML. It should be noted that the * src path does allow relative path names, but they will always be resolved * against the original Facelet requested. * * The include tag can be used in conjunction with multiple &lt;ui:param/&gt; * tags to pass EL expressions/values to the target page. * * NOTE: This implementation is provided for compatibility reasons and * it is considered faulty. It is enabled using * org.apache.myfaces.STRICT_JSF_2_FACELETS_COMPATIBILITY web config param. * Don't use it if EL expression caching is enabled. * * @author Jacob Hookom * @version $Id: LegacyIncludeHandler.java 1576792 2014-03-12 15:57:38Z lu4242 $ */ //@JSFFaceletTag(name="ui:include", bodyContent="JSP") public final class LegacyIncludeHandler extends TagHandler implements ComponentContainerHandler { private static final String ERROR_PAGE_INCLUDE_PATH = "javax.faces.error.xhtml"; private static final String ERROR_FACELET = "META-INF/rsc/myfaces-dev-error-include.xhtml"; /** * A literal or EL expression that specifies the target Facelet that you * would like to include into your document. */ //@JSFFaceletAttribute( // className="javax.el.ValueExpression", // deferredValueType="java.lang.String", // required=true) private final TagAttribute src; private final LegacyParamHandler[] _params; /** * @param config */ public LegacyIncludeHandler(TagConfig config) { super(config); this.src = this.getRequiredAttribute("src"); Collection<LegacyParamHandler> params = TagHandlerUtils.findNextByType(nextHandler, LegacyParamHandler.class); if (!params.isEmpty()) { int i = 0; _params = new LegacyParamHandler[params.size()]; for (LegacyParamHandler handler : params) { _params[i++] = handler; } } else { _params = null; } } /* * (non-Javadoc) * * @see javax.faces.view.facelets.FaceletHandler#apply(javax.faces.view.facelets.FaceletContext, javax.faces.component.UIComponent) */ public void apply(FaceletContext ctx, UIComponent parent) throws IOException, FacesException, FaceletException, ELException { AbstractFaceletContext actx = (AbstractFaceletContext) ctx; FaceletCompositionContext fcc = FaceletCompositionContext.getCurrentInstance(ctx); String path; boolean markInitialState = false; if (!src.isLiteral()) { String uniqueId = actx.generateUniqueFaceletTagId(fcc.startComponentUniqueIdSection(), tagId); //path = getSrcValue(actx, fcc, parent, uniqueId); String restoredPath = (String) ComponentSupport.restoreInitialTagState(ctx, fcc, parent, uniqueId); if (restoredPath != null) { // If is not restore view phase, the path value should be // evaluated and if is not equals, trigger markInitialState stuff. if (!PhaseId.RESTORE_VIEW.equals(ctx.getFacesContext().getCurrentPhaseId())) { path = this.src.getValue(ctx); if (path == null || path.length() == 0) { return; } if (!path.equals(restoredPath)) { markInitialState = true; } } else { path = restoredPath; } } else { //No state restored, calculate path path = this.src.getValue(ctx); } ComponentSupport.saveInitialTagState(ctx, fcc, parent, uniqueId, path); } else { path = this.src.getValue(ctx); } try { if (path == null || path.length() == 0) { return; } VariableMapper orig = ctx.getVariableMapper(); ctx.setVariableMapper(new VariableMapperWrapper(orig)); try { //Only ui:param could be inside ui:include. //this.nextHandler.apply(ctx, null); URL url = null; boolean oldMarkInitialState = false; Boolean isBuildingInitialState = null; // if we are in ProjectStage Development and the path equals "javax.faces.error.xhtml" // we should include the default error page if (ctx.getFacesContext().isProjectStage(ProjectStage.Development) && ERROR_PAGE_INCLUDE_PATH.equals(path)) { url =ClassUtils.getResource(ERROR_FACELET); } if (markInitialState) { //set markInitialState flag oldMarkInitialState = fcc.isMarkInitialState(); fcc.setMarkInitialState(true); isBuildingInitialState = (Boolean) ctx.getFacesContext().getAttributes().put( StateManager.IS_BUILDING_INITIAL_STATE, Boolean.TRUE); } try { if (_params != null) { // ui:include defines a new TemplateContext, but ui:param EL expressions // defined inside should be built before the new context is setup, to // apply then after. The final effect is EL expressions will be resolved // correctly when nested ui:params with the same name or based on other // ui:params are used. String[] names = new String[_params.length]; ValueExpression[] values = new ValueExpression[_params.length]; for (int i = 0; i < _params.length; i++) { names[i] = _params[i].getName(ctx); values[i] = _params[i].getValue(ctx); } //actx.pushTemplateContext(new TemplateContextImpl()); for (int i = 0; i < _params.length; i++) { _params[i].apply(ctx, parent, names[i], values[i]); } } else { //actx.pushTemplateContext(new TemplateContextImpl()); } if (url == null) { ctx.includeFacelet(parent, path); } else { ctx.includeFacelet(parent, url); } } finally { if (markInitialState) { //unset markInitialState flag if (isBuildingInitialState == null) { ctx.getFacesContext().getAttributes().remove( StateManager.IS_BUILDING_INITIAL_STATE); } else { ctx.getFacesContext().getAttributes().put( StateManager.IS_BUILDING_INITIAL_STATE, isBuildingInitialState); } fcc.setMarkInitialState(oldMarkInitialState); } //actx.popTemplateContext(); } } finally { ctx.setVariableMapper(orig); } } finally { if (!src.isLiteral()) { fcc.endComponentUniqueIdSection(); } } if (!src.isLiteral() && fcc.isUsingPSSOnThisView() && fcc.isRefreshTransientBuildOnPSS() && !fcc.isRefreshingTransientBuild()) { //Mark the parent component to be saved and restored fully. ComponentSupport.markComponentToRestoreFully(ctx.getFacesContext(), parent); } if (!src.isLiteral() && fcc.isDynamicComponentSection()) { ComponentSupport.markComponentToRefreshDynamically(ctx.getFacesContext(), parent); } } }
epl-1.0
devaqsa1994/Design-Patterns
EnemyAdapter/src/adaptor/dp/com/EnemyTank.java
570
package adaptor.dp.com; import java.util.Random; public class EnemyTank { Random generator = new Random(); public void fireWeapon() { int attackDamage = generator.nextInt(10) + 1; System.out.println("Enemy Tank Does " + attackDamage + " Damage"); } public void driveForward() { int movement = generator.nextInt(5) + 1; System.out.println("Enemy Tank moves " + movement + " spaces"); } public void assignDriver(String driverName) { System.out.println(driverName + " is driving the tank"); } }
epl-1.0
kgibm/open-liberty
dev/com.ibm.ws.jaxrs.2.0_fat/test-applications/security/src/com/ibm/ws/jaxrs/fat/security/annotations/MethodLevelAllAnnotations.java
1206
/******************************************************************************* * Copyright (c) 2019 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.jaxrs.fat.security.annotations; import javax.annotation.security.DenyAll; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; /** * A sample resource that demonstrates * Method level All security annotations at the same time */ @Path(value = "/MethodAllAnnotations") public class MethodLevelAllAnnotations { @GET @Produces(value = "text/plain") @PermitAll @DenyAll @RolesAllowed({ "Role1" }) public String getMessage() { return "remotely inaccessible to all through method level DenyAll"; } }
epl-1.0
kgibm/open-liberty
dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/el/CompositeELResolver.java
3746
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.myfaces.el; import java.beans.FeatureDescriptor; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; import javax.el.ELContext; import javax.el.ELResolver; /** * @author Mathias Broekelmann (latest modification by $Author: struberg $) * @version $Revision: 1188235 $ $Date: 2011-10-24 17:09:33 +0000 (Mon, 24 Oct 2011) $ */ public class CompositeELResolver extends javax.el.CompositeELResolver { private Collection<ELResolver> _elResolvers; @Override public Iterator<FeatureDescriptor> getFeatureDescriptors(final ELContext context, final Object base) { Collection<ELResolver> resolvers = _elResolvers; if (resolvers == null) { resolvers = Collections.emptyList(); } return new CompositeIterator(context, base, resolvers.iterator()); } /** * @param elResolver */ @Override public final synchronized void add(final ELResolver elResolver) { super.add(elResolver); if (_elResolvers == null) { _elResolvers = new ArrayList<ELResolver>(); } _elResolvers.add(elResolver); } private static class CompositeIterator implements Iterator<FeatureDescriptor> { private final ELContext _context; private final Object _base; private final Iterator<ELResolver> _elResolvers; private FeatureDescriptor _nextFD; private Iterator<FeatureDescriptor> _currentFDIter; public CompositeIterator(final ELContext context, final Object base, final Iterator<ELResolver> elResolvers) { _context = context; _base = base; _elResolvers = elResolvers; } public boolean hasNext() { if (_nextFD != null) { return true; } if (_currentFDIter != null) { while (_nextFD == null && _currentFDIter.hasNext()) { _nextFD = _currentFDIter.next(); } } if (_nextFD == null) { if (_elResolvers.hasNext()) { _currentFDIter = _elResolvers.next().getFeatureDescriptors(_context, _base); } else { return false; } } return hasNext(); } public FeatureDescriptor next() { if (!hasNext()) { throw new NoSuchElementException(); } FeatureDescriptor next = _nextFD; _nextFD = null; return next; } public void remove() { throw new UnsupportedOperationException(); } } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.ssl/src/com/ibm/ws/ssl/core/TraceNLSHelper.java
2158
/******************************************************************************* * Copyright (c) 1997, 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 com.ibm.ws.ssl.core; import com.ibm.ejs.ras.TraceNLS; /** * Helper class for interacting with an NLS translation bundle. * * @author IBM Corporation * @version WAS 7.0 * @since WAS 7.0 */ public class TraceNLSHelper { private static final TraceNLS tnls = TraceNLS.getTraceNLS(TraceNLSHelper.class, "com.ibm.ws.ssl.resources.ssl"); private static TraceNLSHelper thisClass = null; /** * Access the singleton instance of this class. * * @return TraceNLSHelper */ public static TraceNLSHelper getInstance() { if (thisClass == null) { thisClass = new TraceNLSHelper(); } return thisClass; } private TraceNLSHelper() { // do nothing } /** * Look for a translated message using the input key. If it is not found, then * the provided default string is returned. * * @param key * @param defaultString * @return String */ public String getString(String key, String defaultString) { if (tnls != null) return tnls.getString(key, defaultString); return defaultString; } /** * Look for a translated message using the input key. If it is not found, then * the provided default string is returned. * * @param key * @param args * @param defaultString * @return String */ public String getFormattedMessage(String key, Object[] args, String defaultString) { if (tnls != null) return tnls.getFormattedMessage(key, args, defaultString); return defaultString; } }
epl-1.0
unverbraucht/kura
kura/org.eclipse.kura.core.test/src/test/java/org/eclipse/kura/core/test/AllCoreTests.java
4225
/******************************************************************************* * 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.core.test; import java.util.Dictionary; import org.eclipse.kura.data.DataService; import org.eclipse.kura.system.SystemService; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(Suite.class) @SuiteClasses({ DataServiceTest.class, CloudDeploymentHandlerTest.class, CloudServiceTest.class, CommURITest.class, ComponentConfigurationImplTest.class, ConfigurationServiceTest.class, NetUtilTest.class, NetworkServiceTest.class, SystemAdminServiceTest.class, SystemServiceTest.class, XmlUtilTest.class }) public class AllCoreTests { private static final Logger s_logger = LoggerFactory.getLogger(AllCoreTests.class); private static ConfigurationAdmin s_configAdmin; private static DataService s_dataService; private static SystemService s_sysService; public void setConfigAdmin(ConfigurationAdmin configAdmin) { s_configAdmin = configAdmin; } public void unsetConfigAdmin(ConfigurationAdmin configAdmin) { s_configAdmin = configAdmin; } public void setDataService(DataService dataService) { s_dataService = dataService; } public void unsetDataService(DataService dataService) { s_dataService = dataService; } public void setSystemService(SystemService sysService) { s_sysService = sysService; } public void unsetSystemService(SystemService sysService) { s_sysService = sysService; } @BeforeClass public static void setUpClass() throws Exception { s_logger.info("setUpClass..."); int waitCount = 10; while ((s_configAdmin == null || s_dataService == null) && waitCount > 0) { try { Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } waitCount--; s_logger.info("Waiting for ConfigAdmin and DataService " + waitCount + "..."); } if (s_configAdmin == null || s_dataService == null) { throw new Exception("ConfigAdmin and DataService not set."); } try { // update the settings Configuration mqttConfig = s_configAdmin.getConfiguration("org.eclipse.kura.core.data.transport.mqtt.MqttDataTransport"); Dictionary<String, Object> mqttProps = mqttConfig.getProperties(); mqttProps.put("broker-url", "mqtt://iot.eclipse.org:1883/"); mqttProps.put("topic.context.account-name", "guest"); mqttProps.put("username", "guest"); mqttProps.put("password", "welcome"); // cloudbees fails in getting the primary MAC address // we need to compensate for it. String clientId = "cloudbees-kura"; try { clientId = s_sysService.getPrimaryMacAddress(); } catch (Throwable t) { // ignore. } mqttProps.put("client-id", clientId); mqttConfig.update(mqttProps); Configuration dataConfig = s_configAdmin.getConfiguration("org.eclipse.kura.data.DataService"); Dictionary<String, Object> dataProps = dataConfig.getProperties(); dataProps.put("connect.auto-on-startup", false); dataConfig.update(dataProps); // waiting for the configuration to be applied try { Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { throw new Exception("Failed to reconfigure the broker settings - failing out", e); } // connect if (!s_dataService.isConnected()) { s_dataService.connect(); } } @AfterClass public static void tearDownClass() throws Exception { s_logger.info("tearDownClass..."); if (s_dataService.isConnected()) { s_dataService.disconnect(0); } } }
epl-1.0
menghanli/ice
org.eclipse.ice.reflectivity.ui/src/org/eclipse/ice/reflectivity/ui/ReflectivityFormEditor.java
4100
/******************************************************************************* * Copyright (c) 2015 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: * Initial API and implementation and/or initial documentation - Jay Jay Billings, * Jordan H. Deyton, Dasha Gorin, Alexander J. McCaskey, Taylor Patterson, * Claire Saunders, Matthew Wang, Anna Wojtowicz, Kasper Gammeltoft *******************************************************************************/ package org.eclipse.ice.reflectivity.ui; import org.eclipse.ice.client.widgets.ICEFormEditor; import org.eclipse.ice.datastructures.ICEObject.Component; import org.eclipse.ice.datastructures.ICEObject.ListComponent; import org.eclipse.ice.datastructures.form.DataComponent; import org.eclipse.ice.datastructures.form.ResourceComponent; import org.eclipse.ui.PartInitException; import org.eclipse.ui.views.properties.IPropertySheetPage; /** * The custom form editor for the reflectivity model. Should be used instead of * {@link ICEFormEditor} to display reflectivity models. * * @author Kasper Gammeltoft * */ public class ReflectivityFormEditor extends ICEFormEditor { /** * ID for Eclipse, used for the bundle's editor extension point. */ public static final String ID = "org.eclipse.ice.reflectivity.ui.ReflectivityFormEditor"; private ReflectivityPage reflectPage; /** * Adds the components of the model to the reflectivity page. * * @see org.eclipse.ice.client.widgets.ICEFormEditor#addPages() */ @Override protected void addPages() { // Loop over the DataComponents and get them into the map. This is the // same process as for the regular ICEFormEditor for (Component i : iceDataForm.getComponents()) { logger.info("ICEFormEditor Message: Adding component " + i.getName() + " " + i.getId()); i.accept(this); } // Get the components out if they were all properly set. if (!(componentMap.get("data").isEmpty()) && !(componentMap.get("list").isEmpty()) && !(componentMap.get("output").isEmpty())) { // Retrieve the data component DataComponent dataComp = (DataComponent) componentMap.get("data") .get(0); // Retrieve the output data component DataComponent outputComp = (DataComponent) componentMap.get("data") .get(1); // Retrieve the list component ListComponent listComp = (ListComponent) componentMap.get("list") .get(0); // Retrieve the resource component ResourceComponent resComp = (ResourceComponent) componentMap .get("output").get(0); // Create the reflectivity page. Use all of the components for the // Id. ReflectivityPage page = new ReflectivityPage( this, dataComp.getName() + listComp.getName() + resComp.getName() + outputComp.getName(), "Reflectivity Page"); // Set the resource component page for the resource view to know // where to open the resources (the VizResources) super.resourceComponentPage = page; // Add the viz service and the components to the reflectivity page. page.setResourceComponent(resComp); page.setDataComponent(dataComp); page.setList(listComp); page.setOutputComponent(outputComp); // Finally, try adding the page to the editor. try { addPage(page); } catch (PartInitException e) { // Catch the stack trace e.printStackTrace(); } // Finally set the global variable to reference later reflectPage = page; } } /** * Gets the specific adapter needed for the class given. Used to declare the * tabbed properties view */ @Override public Object getAdapter(Class adapter) { if (adapter == IPropertySheetPage.class && reflectPage != null) { return reflectPage.getAdapter(adapter); } return super.getAdapter(adapter); } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.monitor/src/com/ibm/websphere/monitor/annotation/Args.java
1161
/******************************************************************************* * Copyright (c) 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.websphere.monitor.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * For an entry or exit probe events, this will provide access to the method * arguments passed to the probed method. For before and method call probe * events, this will provide access to the arguments presented to the target * method. * <p> * The type of the parameter must be an {@code java.lang.Object[]}. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface Args {}
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.container.service.compat/src/com/ibm/ws/util/WSUtil.java
6701
/******************************************************************************* * Copyright (c) 2010, 2021 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.util; import java.util.ArrayList; import java.util.StringTokenizer; import com.ibm.ejs.ras.Tr; import com.ibm.ejs.ras.TraceComponent; public class WSUtil { // Using the same trace style as used by // com.ibm.ws.util.ThreadPool private static TraceComponent tc = Tr.register(WSUtil.class, "Runtime", "com.ibm.ws.runtime.runtime"); // rewrote method to improve perf (251221) @SuppressWarnings("unchecked") public static String resolveURI(String uriToResolve) { //Not much to resolve in this case if (uriToResolve == null) { return null; } int qindex = Integer.MAX_VALUE; String qstring = null; boolean parsedQuery = false; // begin 154268: part 1 // just to be safe.. convert "\" to "/" if (uriToResolve.indexOf('\\') != -1) { parsedQuery = true; int tmpindex = -1; if ((tmpindex = uriToResolve.indexOf('?')) != -1) { // need to remove query string first to avoid altering query params. qindex = tmpindex; qstring = uriToResolve.substring(qindex); uriToResolve = uriToResolve.substring(0, qindex); if (uriToResolve == null || uriToResolve.equals("")) { // no uri to resolve; return queryString untouched. return qstring; } } uriToResolve = uriToResolve.replace('\\', '/'); } // end 154268 // URI contains no metacharacters int tmpIndex = -1; int testIndex = -1; int resolveIndex = Integer.MAX_VALUE; // hold onto index of lowest match -- // later used to compare against // queryString index. // 258806: Reduction of one indexOf call in standard uri case if ((testIndex = uriToResolve.indexOf("/.")) != -1) { if ((tmpIndex = uriToResolve.indexOf("/../", testIndex)) != -1) { resolveIndex = tmpIndex; } if ((tmpIndex = uriToResolve.indexOf("/./", testIndex)) != -1) { resolveIndex = resolveIndex < tmpIndex ? resolveIndex : tmpIndex; } } if ((tmpIndex = uriToResolve.indexOf("//")) != -1) { resolveIndex = resolveIndex < tmpIndex ? resolveIndex : tmpIndex; } if (!parsedQuery) { if (resolveIndex == Integer.MAX_VALUE) { // no special characters. return uriToResolve; } if ((qindex = uriToResolve.indexOf('?')) != -1) { // need to check for query string. qstring = uriToResolve.substring(qindex); uriToResolve = uriToResolve.substring(0, qindex); if (uriToResolve == null || uriToResolve.equals("")) { // no uri to resolve; return queryString untouched. return qstring; } if (qindex <= resolveIndex) { // true if query string appears prior to special metacharacters // needing to be resolved. return uriToResolve + qstring; } } } else { if (qindex <= resolveIndex) { // true if query string appears prior to special metacharacters needing // to be resolved. if (qstring == null) { return uriToResolve; } else { return uriToResolve + qstring; } } } StringTokenizer uriParser = new StringTokenizer(uriToResolve, "/", false); String currentElement = null; @SuppressWarnings("rawtypes") ArrayList uriElements = new ArrayList(); while (uriParser.hasMoreTokens() == true) { currentElement = uriParser.nextToken(); if ((currentElement == null) || (currentElement.length() < 1)) { continue; } // Attempt to remove the last saved URI element from the list if (currentElement.equals("..") == true) { if (uriElements.size() < 1) { // URI is outside the current context // Start: Issue 17123: // "UPDATE ERROR OUTPUT TO MEET THE MESSAGING STANDARD" // // Per the issue, the current text is to be changed to a // generic message, and error details are to be written // to server logs. // throw new java.lang.IllegalArgumentException( // "The specified URI, " + uriToResolve + ", is invalid because" + // " it contains more references to parent directories (\"..\")" + // " than is possible."); if ( TraceComponent.isAnyTracingEnabled() && tc.isErrorEnabled() ) { Tr.error(tc, "Non-valid URI [ " + uriToResolve + " ]:" + " The URI contains too many parent directory elements (\"..\")."); } throw new IllegalArgumentException("Non-valid URI."); // End: Issue 17123 } uriElements.remove(uriElements.size() - 1); continue; } // Ignore, don't add to list of elements if (currentElement.equals(".") == true) { continue; } // Keep track of this URI element uriElements.add(currentElement); } // Build a String from the remaining elements of the passed URI StringBuffer resolvedURI = new StringBuffer(); int elementCount = uriElements.size(); for (int elementIndex = 0; elementIndex < elementCount; ++elementIndex) { resolvedURI.append("/" + (String) uriElements.get(elementIndex)); } if (qstring == null) { return resolvedURI.toString(); } else { return resolvedURI.toString() + qstring; } } }
epl-1.0
OpenLiberty/open-liberty
dev/io.openliberty.ws.jaxws.global.handler.internal_fat/test-applications/TransportSecurityProvider/src/com/ibm/ws/jaxws/transport/server/security/SayHelloService.java
823
/******************************************************************************* * Copyright (c) 2021 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.jaxws.transport.server.security; import javax.jws.WebService; @WebService(name = "SayHello", targetNamespace = "http://ibm.com/ws/jaxws/transport/security/should_not_used_interface/") public interface SayHelloService { String sayHello(String name); }
epl-1.0
muros-ct/kapua
org.eclipse.kapua.app.console/src/main/java/org/eclipse/kapua/app/console/shared/service/GwtSecurityTokenService.java
1027
/******************************************************************************* * Copyright (c) 2011, 2016 Eurotech and/or its affiliates and others * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech - initial API and implementation * *******************************************************************************/ package org.eclipse.kapua.app.console.shared.service; import org.eclipse.kapua.app.console.shared.model.GwtXSRFToken; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; /** * This is the XSRF service interface to obtain a valid securityToken. */ @RemoteServiceRelativePath("xsrf") public interface GwtSecurityTokenService extends RemoteService { public GwtXSRFToken generateSecurityToken(); }
epl-1.0
Charling-Huang/birt
viewer/org.eclipse.birt.report.viewer/birt/WEB-INF/classes/org/eclipse/birt/report/soapengine/api/JoinCondition.java
5888
/** * JoinCondition.java * * This file was auto-generated from WSDL * by the Apache Axis 1.2.1 Jun 14, 2005 (09:15:57 EDT) WSDL2Java emitter. */ package org.eclipse.birt.report.soapengine.api; public class JoinCondition implements java.io.Serializable { private java.lang.String leftExpr; private java.lang.String operator; private java.lang.String rightExpr; public JoinCondition() { } public JoinCondition( java.lang.String leftExpr, java.lang.String operator, java.lang.String rightExpr) { this.leftExpr = leftExpr; this.operator = operator; this.rightExpr = rightExpr; } /** * Gets the leftExpr value for this JoinCondition. * * @return leftExpr */ public java.lang.String getLeftExpr() { return leftExpr; } /** * Sets the leftExpr value for this JoinCondition. * * @param leftExpr */ public void setLeftExpr(java.lang.String leftExpr) { this.leftExpr = leftExpr; } /** * Gets the operator value for this JoinCondition. * * @return operator */ public java.lang.String getOperator() { return operator; } /** * Sets the operator value for this JoinCondition. * * @param operator */ public void setOperator(java.lang.String operator) { this.operator = operator; } /** * Gets the rightExpr value for this JoinCondition. * * @return rightExpr */ public java.lang.String getRightExpr() { return rightExpr; } /** * Sets the rightExpr value for this JoinCondition. * * @param rightExpr */ public void setRightExpr(java.lang.String rightExpr) { this.rightExpr = rightExpr; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof JoinCondition)) return false; JoinCondition other = (JoinCondition) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((this.leftExpr==null && other.getLeftExpr()==null) || (this.leftExpr!=null && this.leftExpr.equals(other.getLeftExpr()))) && ((this.operator==null && other.getOperator()==null) || (this.operator!=null && this.operator.equals(other.getOperator()))) && ((this.rightExpr==null && other.getRightExpr()==null) || (this.rightExpr!=null && this.rightExpr.equals(other.getRightExpr()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (getLeftExpr() != null) { _hashCode += getLeftExpr().hashCode(); } if (getOperator() != null) { _hashCode += getOperator().hashCode(); } if (getRightExpr() != null) { _hashCode += getRightExpr().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(JoinCondition.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("http://schemas.eclipse.org/birt", "JoinCondition")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("leftExpr"); elemField.setXmlName(new javax.xml.namespace.QName("http://schemas.eclipse.org/birt", "LeftExpr")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("operator"); elemField.setXmlName(new javax.xml.namespace.QName("http://schemas.eclipse.org/birt", "Operator")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("rightExpr"); elemField.setXmlName(new javax.xml.namespace.QName("http://schemas.eclipse.org/birt", "RightExpr")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.resource/src/com/ibm/ws/resource/internal/ResourceFactoryTracker.java
2552
/******************************************************************************* * Copyright (c) 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.resource.internal; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.service.component.ComponentContext; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; import com.ibm.wsspi.resource.ResourceFactory; public class ResourceFactoryTracker implements ServiceTrackerCustomizer<ResourceFactory, ResourceFactoryTrackerData> { private static final String FILTER = "(&" + "(" + Constants.OBJECTCLASS + "=" + ResourceFactory.class.getName() + ")" + "(" + ResourceFactory.JNDI_NAME + "=*)" + "(" + ResourceFactory.CREATES_OBJECT_CLASS + "=*)" + ")"; private ServiceTracker<ResourceFactory, ResourceFactoryTrackerData> tracker; public void activate(BundleContext context) throws InvalidSyntaxException { Filter filter = FrameworkUtil.createFilter(FILTER); tracker = new ServiceTracker<ResourceFactory, ResourceFactoryTrackerData>(context, filter, this); tracker.open(); } public void deactivate(ComponentContext cc) { tracker.close(); } @Override public ResourceFactoryTrackerData addingService(ServiceReference<ResourceFactory> ref) { ResourceFactoryTrackerData data = new ResourceFactoryTrackerData(ref.getBundle().getBundleContext()); data.register(ref); return data; } @Override public void modifiedService(ServiceReference<ResourceFactory> ref, ResourceFactoryTrackerData data) { data.modifed(ref); } @Override public void removedService(ServiceReference<ResourceFactory> ref, ResourceFactoryTrackerData data) { data.unregister(); } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.websphere.jsonsupport/src/com/ibm/websphere/jsonsupport/JSONFactory.java
1022
/******************************************************************************* * Copyright (c) 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.websphere.jsonsupport; import com.ibm.ws.jsonsupport.internal.JSONJacksonImpl; /** * */ public class JSONFactory { private static JSON json; public static synchronized JSON newInstance() throws JSONMarshallException { if (json == null) json = new JSONJacksonImpl(); return json; } public static JSON newInstance(JSONSettings settings) throws JSONMarshallException { return new JSONJacksonImpl(settings); } }
epl-1.0
devjunix/libjt400-java
jtopenlite/com/ibm/jtopenlite/database/AttributeScrollableCursorFlag.java
713
/////////////////////////////////////////////////////////////////////////////// // // JTOpenLite // // Filename: AttributeScrollableCursorFlag.java // // The source code contained herein is licensed under the IBM Public License // Version 1.0, which has been approved by the Open Source Initiative. // Copyright (C) 2011-2012 International Business Machines Corporation and // others. All rights reserved. // /////////////////////////////////////////////////////////////////////////////// package com.ibm.jtopenlite.database; interface AttributeScrollableCursorFlag { public int getScrollableCursorFlag(); public boolean isScrollableCursorFlagSet(); public void setScrollableCursorFlag(int value); }
epl-1.0
cemalkilic/che
plugins/plugin-orion/che-plugin-orion-editor/src/main/java/org/eclipse/che/ide/editor/orion/client/ContentAssistWidget.java
27892
/******************************************************************************* * Copyright (c) 2012-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.ide.editor.orion.client; import elemental.dom.Element; import elemental.dom.Node; import elemental.events.CustomEvent; import elemental.events.Event; import elemental.events.EventListener; import elemental.events.EventTarget; import elemental.events.KeyboardEvent; import elemental.events.MouseEvent; import elemental.html.HTMLCollection; import elemental.html.SpanElement; import elemental.html.Window; import com.google.gwt.core.client.Scheduler; import com.google.gwt.dom.client.Style; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.Widget; import com.google.inject.assistedinject.Assisted; import com.google.inject.assistedinject.AssistedInject; import org.eclipse.che.ide.api.editor.codeassist.Completion; import org.eclipse.che.ide.api.editor.codeassist.CompletionProposal; import org.eclipse.che.ide.api.editor.codeassist.CompletionProposalExtension; import org.eclipse.che.ide.api.editor.events.CompletionRequestEvent; import org.eclipse.che.ide.api.editor.text.LinearRange; import org.eclipse.che.ide.api.editor.texteditor.HandlesUndoRedo; import org.eclipse.che.ide.api.editor.texteditor.UndoableEditor; import org.eclipse.che.ide.editor.orion.client.jso.OrionKeyModeOverlay; import org.eclipse.che.ide.editor.orion.client.jso.OrionModelChangedEventOverlay; import org.eclipse.che.ide.editor.orion.client.jso.OrionPixelPositionOverlay; import org.eclipse.che.ide.editor.orion.client.jso.OrionTextViewOverlay; import org.eclipse.che.ide.ui.popup.PopupResources; import org.eclipse.che.ide.util.dom.Elements; import org.eclipse.che.ide.util.loging.Log; import java.util.List; import static elemental.css.CSSStyleDeclaration.Unit.PX; /** * @author Evgen Vidolob * @author Vitaliy Guliy * @author Kaloyan Raev */ public class ContentAssistWidget implements EventListener { /** * Custom event type. */ private static final String CUSTOM_EVT_TYPE_VALIDATE = "itemvalidate"; private static final String DOCUMENTATION = "documentation"; private static final int DOM_ITEMS_SIZE = 50; private final PopupResources popupResources; /** The related editor. */ private final OrionEditorWidget textEditor; private OrionKeyModeOverlay assistMode; /** The main element for the popup. */ private final Element popupElement; private final Element popupBodyElement; /** The list (ul) element for the popup. */ private final Element listElement; private final EventListener popupListener; private boolean visible = false; private boolean focused = false; private boolean insert = true; /** * The previously focused element. */ private Element selectedElement; private FlowPanel docPopup; private OrionTextViewOverlay.EventHandler<OrionModelChangedEventOverlay> handler; private List<CompletionProposal> proposals; @AssistedInject public ContentAssistWidget(final PopupResources popupResources, @Assisted final OrionEditorWidget textEditor, @Assisted OrionKeyModeOverlay assistMode) { this.popupResources = popupResources; this.textEditor = textEditor; this.assistMode = assistMode; popupElement = Elements.createDivElement(popupResources.popupStyle().popup()); Element headerElement = Elements.createDivElement(popupResources.popupStyle().header()); headerElement.setInnerText("Proposals:"); popupElement.appendChild(headerElement); popupBodyElement = Elements.createDivElement(popupResources.popupStyle().body()); popupElement.appendChild(popupBodyElement); listElement = Elements.createUListElement(); popupBodyElement.appendChild(listElement); docPopup = new FlowPanel(); docPopup.setStyleName(popupResources.popupStyle().popup()); docPopup.setSize("370px", "180px"); popupListener = evt -> { if (!(evt instanceof MouseEvent)) { return; } final MouseEvent mouseEvent = (MouseEvent)evt; final EventTarget target = mouseEvent.getTarget(); if (target instanceof Element) { final Element elementTarget = (Element)target; if (docPopup.isVisible() && (elementTarget.equals(docPopup.getElement()) || elementTarget.getParentElement().equals(docPopup.getElement()))) { return; } if (!ContentAssistWidget.this.popupElement.contains(elementTarget)) { hide(); evt.preventDefault(); } } }; handler = event -> { callCodeAssistTimer.cancel(); callCodeAssistTimer.schedule(250); }; } private Timer callCodeAssistTimer = new Timer() { @Override public void run() { textEditor.getDocument().getDocumentHandle().getDocEventBus().fireEvent(new CompletionRequestEvent()); } }; public void validateItem(boolean insert) { this.insert = insert; selectedElement.dispatchEvent(createValidateEvent(CUSTOM_EVT_TYPE_VALIDATE)); } /** * @param eventType * @return */ private native CustomEvent createValidateEvent(String eventType) /*-{ return new CustomEvent(eventType); }-*/; /** * Creates a new proposal item. * * @param index * of proposal */ private Element createProposalPopupItem(int index) { final CompletionProposal proposal = proposals.get(index); final Element element = Elements.createLiElement(popupResources.popupStyle().item()); element.setId(Integer.toString(index)); final Element icon = Elements.createDivElement(popupResources.popupStyle().icon()); if (proposal.getIcon() != null && proposal.getIcon().getSVGImage() != null) { icon.appendChild((Node)proposal.getIcon().getSVGImage().getElement()); } else if (proposal.getIcon() != null && proposal.getIcon().getImage() != null) { icon.appendChild((Node)proposal.getIcon().getImage().getElement()); } element.appendChild(icon); final SpanElement label = Elements.createSpanElement(popupResources.popupStyle().label()); label.setInnerHTML(proposal.getDisplayString()); element.appendChild(label); element.setTabIndex(1); final EventListener validateListener = evt -> applyProposal(proposal); element.addEventListener(Event.DBLCLICK, validateListener, false); element.addEventListener(CUSTOM_EVT_TYPE_VALIDATE, validateListener, false); element.addEventListener(Event.CLICK, event -> select(element), false); element.addEventListener(Event.FOCUS, this, false); element.addEventListener(DOCUMENTATION, new EventListener() { @Override public void handleEvent(Event event) { proposal.getAdditionalProposalInfo(new AsyncCallback<Widget>() { @Override public void onSuccess(Widget info) { if (info != null) { docPopup.clear(); docPopup.add(info); docPopup.getElement().getStyle().setOpacity(1); if (!docPopup.isAttached()) { final int x = popupElement.getOffsetLeft() + popupElement.getOffsetWidth() + 3; final int y = popupElement.getOffsetTop(); RootPanel.get().add(docPopup); updateMenuPosition(docPopup, x, y); } } else { docPopup.getElement().getStyle().setOpacity(0); } } @Override public void onFailure(Throwable e) { Log.error(getClass(), e); docPopup.getElement().getStyle().setOpacity(0); } }); } }, false); return element; } private void updateMenuPosition(FlowPanel popupMenu, int x, int y) { if (x + popupMenu.getOffsetWidth() > com.google.gwt.user.client.Window.getClientWidth()) { popupMenu.getElement().getStyle().setLeft(x - popupMenu.getOffsetWidth() - popupElement.getOffsetWidth() - 5, Style.Unit.PX); } else { popupMenu.getElement().getStyle().setLeft(x, Style.Unit.PX); } if (y + popupMenu.getOffsetHeight() > com.google.gwt.user.client.Window.getClientHeight()) { popupMenu.getElement().getStyle().setTop(y - popupMenu.getOffsetHeight() - popupElement.getOffsetHeight() - 3, Style.Unit.PX); } else { popupMenu.getElement().getStyle().setTop(y, Style.Unit.PX); } } private void addPopupEventListeners() { Elements.getDocument().addEventListener(Event.MOUSEDOWN, this.popupListener, false); textEditor.getTextView().addKeyMode(assistMode); // add key event listener on popup textEditor.getTextView().setAction("cheContentAssistCancel", () -> { hide(); return true; }); textEditor.getTextView().setAction("cheContentAssistApply", () -> { validateItem(true); return true; }); textEditor.getTextView().setAction("cheContentAssistPreviousProposal", () -> { selectPrevious(); return true; }); textEditor.getTextView().setAction("cheContentAssistNextProposal", () -> { selectNext(); return true; }); textEditor.getTextView().setAction("cheContentAssistNextPage", () -> { selectNextPage(); return true; }); textEditor.getTextView().setAction("cheContentAssistPreviousPage", () -> { selectPreviousPage(); return true; }); textEditor.getTextView().setAction("cheContentAssistEnd", () -> { selectLast(); return true; }); textEditor.getTextView().setAction("cheContentAssistHome", () -> { selectFirst(); return true; }); textEditor.getTextView().setAction("cheContentAssistTab", () -> { validateItem(false); return true; }); textEditor.getTextView().addEventListener("ModelChanging", handler); listElement.addEventListener(Event.KEYDOWN, this, false); popupBodyElement.addEventListener(Event.SCROLL, this, false); } private void removePopupEventListeners() { /* Remove popup listeners. */ textEditor.getTextView().removeKeyMode(assistMode); textEditor.getTextView().removeEventListener("ModelChanging", handler, false); // remove the keyboard listener listElement.removeEventListener(Event.KEYDOWN, this, false); // remove the scroll listener popupBodyElement.removeEventListener(Event.SCROLL, this, false); // remove the mouse listener Elements.getDocument().removeEventListener(Event.MOUSEDOWN, this.popupListener); } private void selectFirst() { scrollTo(0); updateIfNecessary(); select(getFirstItemInDOM()); } private void selectLast() { scrollTo(getTotalItems() - 1); updateIfNecessary(); select(getLastItemInDOM()); } private void select(int index) { select(getItem(index)); } private void selectPrevious() { Element previousElement = selectedElement.getPreviousElementSibling(); if (previousElement != null && previousElement == getExtraTopRow() && getExtraTopRow().isHidden()) { selectLast(); } else { selectOffset(-1); } } private void selectPreviousPage() { int offset = getItemsPerPage() - 1; selectOffset(-offset); } private void selectNext() { Element nextElement = selectedElement.getNextElementSibling(); if (nextElement != null && nextElement == getExtraBottomRow() && getExtraBottomRow().isHidden()) { selectFirst(); } else { selectOffset(1); } } private void selectNextPage() { int offset = getItemsPerPage() - 1; selectOffset(offset); } private void selectOffset(int offset) { int index = getItemId(selectedElement) + offset; index = Math.max(index, 0); index = Math.min(index, getTotalItems() - 1); if (!isItemInDOM(index)) { scrollTo(index); update(); } select(index); } private void select(Element element) { if (element == selectedElement) { return; } if (selectedElement != null) { selectedElement.removeAttribute("selected"); } selectedElement = element; selectedElement.setAttribute("selected", "true"); showDocTimer.cancel(); showDocTimer.schedule(docPopup.isAttached() ? 100 : 1500); if (selectedElement.getOffsetTop() < this.popupBodyElement.getScrollTop()) { selectedElement.scrollIntoView(true); } else if ((selectedElement.getOffsetTop() + selectedElement.getOffsetHeight()) > (this.popupBodyElement.getScrollTop() + this.popupBodyElement.getClientHeight())) { selectedElement.scrollIntoView(false); } } private Timer showDocTimer = new Timer() { @Override public void run() { if (selectedElement != null) { selectedElement.dispatchEvent(createValidateEvent(DOCUMENTATION)); } } }; /** * Displays assist popup relative to the current cursor position. * * @param proposals * proposals to display */ public void show(final List<CompletionProposal> proposals) { this.proposals = proposals; OrionTextViewOverlay textView = textEditor.getTextView(); OrionPixelPositionOverlay caretLocation = textView.getLocationAtOffset(textView.getCaretOffset()); caretLocation.setY(caretLocation.getY() + textView.getLineHeight()); caretLocation = textView.convert(caretLocation, "document", "page"); /** The fastest way to remove element children. Clear and add items. */ listElement.setInnerHTML(""); /* Display an empty popup when it is nothing to show. */ if (getTotalItems() == 0) { final Element emptyElement = Elements.createLiElement(popupResources.popupStyle().item()); emptyElement.setTextContent("No proposals"); listElement.appendChild(emptyElement); return; } /* Automatically apply the completion proposal if it only one. */ if (getTotalItems() == 1) { applyProposal(proposals.get(0)); return; } /* Reset popup dimensions and show. */ popupElement.getStyle().setLeft(caretLocation.getX(), PX); popupElement.getStyle().setTop(caretLocation.getY(), PX); popupElement.getStyle().setWidth("400px"); popupElement.getStyle().setHeight("200px"); popupElement.getStyle().setOpacity(1); Elements.getDocument().getBody().appendChild(this.popupElement); /* Add the top extra row. */ setExtraRowHeight(appendExtraRow(), 0); /* Add the popup items. */ for (int i = 0; i < Math.min(DOM_ITEMS_SIZE, getTotalItems()); i++) { listElement.appendChild(createProposalPopupItem(i)); } /* Add the bottom extra row. */ setExtraRowHeight(appendExtraRow(), Math.max(0, getTotalItems() - DOM_ITEMS_SIZE)); /* Correct popup position (wants to be refactored) */ final Window window = Elements.getWindow(); final int viewportWidth = window.getInnerWidth(); final int viewportHeight = window.getInnerHeight(); int spaceBelow = viewportHeight - caretLocation.getY(); if (this.popupElement.getOffsetHeight() > spaceBelow) { // Check if div is too large to fit above int spaceAbove = caretLocation.getY() - textView.getLineHeight(); if (this.popupElement.getOffsetHeight() > spaceAbove) { // Squeeze the div into the larger area if (spaceBelow > spaceAbove) { this.popupElement.getStyle().setProperty("maxHeight", spaceBelow + "px"); } else { this.popupElement.getStyle().setProperty("maxHeight", spaceAbove + "px"); this.popupElement.getStyle().setTop("0"); } } else { // Put the div above the line this.popupElement.getStyle() .setTop((caretLocation.getY() - this.popupElement.getOffsetHeight() - textView.getLineHeight()) + "px"); this.popupElement.getStyle().setProperty("maxHeight", spaceAbove + "px"); } } else { this.popupElement.getStyle().setProperty("maxHeight", spaceBelow + "px"); } if (caretLocation.getX() + this.popupElement.getOffsetWidth() > viewportWidth) { int leftSide = viewportWidth - this.popupElement.getOffsetWidth(); if (leftSide < 0) { leftSide = 0; } this.popupElement.getStyle().setLeft(leftSide + "px"); this.popupElement.getStyle().setProperty("maxWidth", (viewportWidth - leftSide) + "px"); } else { this.popupElement.getStyle().setProperty("maxWidth", viewportWidth + caretLocation.getX() + "px"); } /* Don't attach handlers twice. Visible popup must already have their attached. */ if (!visible) { addPopupEventListeners(); } /* Indicates the codeassist is visible. */ visible = true; focused = false; /* Update documentation popup position */ docPopup.getElement().getStyle() .setLeft(popupElement.getOffsetLeft() + popupElement.getOffsetWidth() + 3, Style.Unit.PX); docPopup.getElement().getStyle() .setTop(popupElement.getOffsetTop(), Style.Unit.PX); /* Select first row. */ selectFirst(); } /** * Hides the popup and displaying javadoc. */ public void hide() { textEditor.setFocus(); if (docPopup.isAttached()) { docPopup.getElement().getStyle().setOpacity(0); new Timer() { @Override public void run() { docPopup.removeFromParent(); } }.schedule(250); } popupElement.getStyle().setOpacity(0); new Timer() { @Override public void run() { // detach assist popup popupElement.getParentNode().removeChild(popupElement); // remove all items from popup element listElement.setInnerHTML(""); } }.schedule(250); visible = false; selectedElement = null; showDocTimer.cancel(); removePopupEventListeners(); } @Override public void handleEvent(Event evt) { if (Event.KEYDOWN.equalsIgnoreCase(evt.getType())) { final KeyboardEvent keyEvent = (KeyboardEvent)evt; switch (keyEvent.getKeyCode()) { case KeyCodes.KEY_ESCAPE: Scheduler.get().scheduleDeferred(() -> hide()); break; case KeyCodes.KEY_DOWN: selectNext(); evt.preventDefault(); break; case KeyCodes.KEY_UP: selectPrevious(); evt.preventDefault(); break; case KeyCodes.KEY_PAGEUP: selectPreviousPage(); evt.preventDefault(); break; case KeyCodes.KEY_PAGEDOWN: selectNextPage(); evt.preventDefault(); break; case KeyCodes.KEY_HOME: selectFirst(); break; case KeyCodes.KEY_END: selectLast(); break; case KeyCodes.KEY_ENTER: evt.preventDefault(); evt.stopImmediatePropagation(); validateItem(true); break; case KeyCodes.KEY_TAB: evt.preventDefault(); evt.stopImmediatePropagation(); validateItem(false); break; } } else if (Event.SCROLL.equalsIgnoreCase(evt.getType())) { updateIfNecessary(); } else if (Event.FOCUS.equalsIgnoreCase(evt.getType())) { focused = true; } } private void updateIfNecessary() { int scrollTop = popupBodyElement.getScrollTop(); int extraTopHeight = getExtraTopRow().getClientHeight(); if (scrollTop < extraTopHeight) { // the scroll bar is above the buffered area update(); } else if (scrollTop + popupBodyElement.getClientHeight() > extraTopHeight + getItemHeight() * DOM_ITEMS_SIZE) { // the scroll bar is below the buffered area update(); } } private void update() { int topVisibleItem = popupBodyElement.getScrollTop() / getItemHeight(); int topDOMItem = Math.max(0, topVisibleItem - (DOM_ITEMS_SIZE - getItemsPerPage()) / 2); int bottomDOMItem = Math.min(getTotalItems() - 1, topDOMItem + DOM_ITEMS_SIZE - 1); if (bottomDOMItem == getTotalItems() - 1) { topDOMItem = Math.max(0, bottomDOMItem - DOM_ITEMS_SIZE + 1); } // resize the extra top row setExtraRowHeight(getExtraTopRow(), topDOMItem); // replace the DOM items with new content based on the scroll position HTMLCollection nodes = listElement.getChildren(); for (int i = 0; i <= (bottomDOMItem - topDOMItem); i++) { Element newNode = createProposalPopupItem(topDOMItem + i); listElement.replaceChild(newNode, nodes.item(i + 1)); // check if the item is the selected if (newNode.getId().equals(selectedElement.getId())) { selectedElement = newNode; selectedElement.setAttribute("selected", "true"); } } // resize the extra bottom row setExtraRowHeight(getExtraBottomRow(), getTotalItems() - (bottomDOMItem + 1)); // ensure the keyboard focus is in the visible area if (focused) { getItem(topDOMItem + (bottomDOMItem - topDOMItem) / 2).focus(); } } /** * Uses to determine the autocompletion popup visibility. * * @return <b>true</b> if the popup is visible, otherwise returns <b>false</b> */ public boolean isVisible() { return visible; } public void showCompletionInfo() { if (visible && selectedElement != null) { selectedElement.dispatchEvent(createValidateEvent(DOCUMENTATION)); } } private void applyProposal(CompletionProposal proposal) { CompletionProposal.CompletionCallback callback = this::applyCompletion; if (proposal instanceof CompletionProposalExtension) { ((CompletionProposalExtension)proposal).getCompletion(insert, callback); } else { proposal.getCompletion(callback); } hide(); } private void applyCompletion(Completion completion) { textEditor.setFocus(); UndoableEditor undoableEditor = textEditor; HandlesUndoRedo undoRedo = undoableEditor.getUndoRedo(); try { if (undoRedo != null) { undoRedo.beginCompoundChange(); } completion.apply(textEditor.getDocument()); final LinearRange selection = completion.getSelection(textEditor.getDocument()); if (selection != null) { textEditor.getDocument().setSelectedRange(selection, true); } } catch (final Exception e) { Log.error(getClass(), e); } finally { if (undoRedo != null) { undoRedo.endCompoundChange(); } } } private Element getExtraTopRow() { return (listElement == null) ? null : listElement.getFirstElementChild(); } private Element getExtraBottomRow() { return (listElement == null) ? null : listElement.getLastElementChild(); } private Element getFirstItemInDOM() { Element extraTopRow = getExtraTopRow(); return (extraTopRow == null) ? null : extraTopRow.getNextElementSibling(); } private Element getLastItemInDOM() { Element extraBottomRow = getExtraBottomRow(); return (extraBottomRow == null) ? null : extraBottomRow.getPreviousElementSibling(); } private int getItemId(Element item) { return Integer.parseInt(item.getId()); } private Element getItem(int index) { return (Element)listElement.getChildren().namedItem(Integer.toString(index)); } private int getItemHeight() { Element item = getFirstItemInDOM(); return (item == null) ? 0 : item.getClientHeight(); } private Element appendExtraRow() { Element extraRow = Elements.createLiElement(); listElement.appendChild(extraRow); return extraRow; } private void setExtraRowHeight(Element extraRow, int items) { int height = items * getItemHeight(); extraRow.getStyle().setHeight(height + "px"); extraRow.setHidden(height <= 0); } private int getItemsPerPage() { return (int)Math.ceil((double)popupBodyElement.getClientHeight() / getItemHeight()); } private int getTotalItems() { return (proposals == null) ? 0 : proposals.size(); } private boolean isItemInDOM(int index) { return index >= getItemId(getFirstItemInDOM()) && index <= getItemId(getLastItemInDOM()); } private void scrollTo(int index) { int currentScrollTop = popupBodyElement.getScrollTop(); int newScrollTop = index * getItemHeight(); if (currentScrollTop < newScrollTop) { // the scrolling direction is from top to bottom, so show the item // at the bottom of the widget newScrollTop -= popupBodyElement.getClientHeight(); } popupBodyElement.setScrollTop(newScrollTop); } }
epl-1.0
kn1kn1/overtone-workspace
scbook/code/Ch 10 SwingOSC/SwingOSC/src/de/sciss/swingosc/SwingMenuItem.java
5016
/* * SwingMenuItem.java * SwingOSC * * Copyright (c) 2005-2009 Hanns Holger Rutz. All rights reserved. * * This software 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, june 1991 of the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License (gpl.txt) along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * * For further information, please contact Hanns Holger Rutz at * contact@sciss.de * * * Changelog: * 27-Jul-08 created */ package de.sciss.swingosc; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.util.Iterator; import javax.swing.AbstractButton; import javax.swing.Action; import javax.swing.KeyStroke; import de.sciss.common.BasicMenuFactory; import de.sciss.gui.MenuItem; public class SwingMenuItem extends MenuItem { private final DispatchAction action; public SwingMenuItem( String id, String text ) { // this( id, text, null, 0 ); // } // // public SwingMenuItem( String id, String text, String accel, int modifiers ) // { super( id, new DispatchAction( text )); // super( id, new DispatchAction( text, SwingMenuItem.createKeyStroke( accel, modifiers ))); // super( id, new DispatchAction( text, KeyStroke.getKeyStroke( KeyEvent.VK_A, InputEvent.META_MASK ))); action = (DispatchAction) this.getAction(); } public void addActionListener( ActionListener l ) { action.addActionListener( l ); } public void removeActionListener( ActionListener l ) { action.removeActionListener( l ); } public void setName( String name ) { SwingMenuItem.setName( this, name ); } public void setShortCut( String cut ) { SwingMenuItem.setShortCut( this, cut ); } protected static void setName( MenuItem mi, String name ) { mi.getAction().putValue( Action.NAME, name ); } // protected static KeyStroke createKeyStroke( String accel, int modifiers ) // { // if( (accel == null) || (accel.length() != 1) ) return null; // return createKeyStroke( accel.charAt( 0 ), modifiers ); // } // protected static KeyStroke createKeyStroke( String cut ) { final String[] elem = cut.split( "\\s" ); final StringBuffer sb = new StringBuffer(); final boolean altMeta = BasicMenuFactory.MENU_SHORTCUT != InputEvent.META_MASK; final int meta1 = BasicMenuFactory.MENU_SHORTCUT; final int meta2 = altMeta ? (InputEvent.CTRL_MASK | InputEvent.ALT_MASK) : InputEvent.CTRL_MASK; int modifiers = 0; for( int i = 0; i < elem.length; i++ ) { // System.out.println( "found '" + elem[ i ] + "'" ); if( elem[ i ].equals( "meta" )) { modifiers |= meta1; } else if( elem[ i ].equals( "shift" )) { modifiers |= InputEvent.SHIFT_MASK; } else if( elem[ i ].equals( "meta2" )) { modifiers |= meta2; } else if( elem[ i ].equals( "alt" )) { modifiers |= InputEvent.ALT_MASK; } else if( elem[ i ].equals( "ctrl" ) || elem[ i ].equals( "control" )) { modifiers |= InputEvent.CTRL_MASK; } else if( elem[ i ].equals( "altGraph" )) { modifiers |= InputEvent.ALT_GRAPH_MASK; } else { sb.append( elem[ i ].toUpperCase() ); } } if( (modifiers & InputEvent.SHIFT_MASK) != 0 ) { sb.insert( 0, "shift " ); } if( (modifiers & InputEvent.CTRL_MASK) != 0 ) { sb.insert( 0, "ctrl " ); } if( (modifiers & InputEvent.META_MASK) != 0 ) { sb.insert( 0, "meta " ); } if( (modifiers & InputEvent.ALT_MASK) != 0 ) { sb.insert( 0, "alt " ); } if( (modifiers & InputEvent.ALT_GRAPH_MASK) != 0 ) { sb.insert( 0, "altGraph " ); } // System.out.println( "now is '" + sb.toString() + "'" ); // !!! DOESN'T WORK SINCE THE STROKE IS "TYPED" NOT "PRESSED" // return KeyStroke.getKeyStroke( new Character( c ), modifiers ); // return KeyStroke.getKeyStroke( c, modifiers ); return KeyStroke.getKeyStroke( sb.toString() ); } protected static void setShortCut( MenuItem mi, String cut ) { final KeyStroke accel = createKeyStroke( cut ); final Action action = mi.getAction(); action.putValue( Action.ACCELERATOR_KEY, accel ); //System.out.println( "keyStroke : " + accel ); // this is a fucking stupid bug in swing: // the accelerator key is not taken after the menu item // has been created. the hack is to set its action to // null and then back to the action again for( Iterator iter = mi.getRealized(); iter.hasNext(); ) { final Realized r = (Realized) iter.next(); final AbstractButton b = (AbstractButton) r.c; b.setAction( null ); b.setAction( action ); } } }
epl-1.0
christ66/coverity-plugin
src/main/java/com/coverity/ws/v9/ComponentIdDataObj.java
1400
package com.coverity.ws.v9; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for componentIdDataObj complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="componentIdDataObj"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "componentIdDataObj", propOrder = { "name" }) public class ComponentIdDataObj { @XmlElement(required = true) protected String name; /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/schema/JmsTextBodyAccess.java
1035
/******************************************************************************* * Copyright (c) 2017 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 *******************************************************************************/ // Generated from C:\SIB\Code\WASX.SIB\dd\SIB\ws\code\sib.mfp.impl\src\com\ibm\ws\sib\mfp\schema\JmsTextBodySchema.schema: do not edit directly package com.ibm.ws.sib.mfp.schema; import com.ibm.ws.sib.mfp.jmf.impl.JSchema; public final class JmsTextBodyAccess { public final static JSchema schema = new JmsTextBodySchema(); public final static int BODY = 1; public final static int IS_BODY_EMPTY = 0; public final static int IS_BODY_DATA = 1; public final static int BODY_DATA_VALUE = 0; }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer.legacy_fat/test-applications/StatefulPassivationEJB.jar/src/com/ibm/ejb2x/base/pitt/ejb/BMEntity.java
1278
/******************************************************************************* * Copyright (c) 2002, 2019 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ejb2x.base.pitt.ejb; import java.rmi.RemoteException; import javax.ejb.EJBObject; /** * A simple bean managed entity bean to test container and * deployment tools. <p> * * @author Chriss Stephens * @version $Id: BMEntity.java,v 1.6 1999/11/30 20:10:24 chriss Exp $ */ public interface BMEntity extends EJBObject { /** * Increment the persistent counter associated with this entity bean * within the scope of a new transaction. <p> * * @return an <code>int</code> containing the value of the persistent * counter after the increment has completed. */ public int txNewIncrement() throws RemoteException; public int getNonpersistent() throws RemoteException; }
epl-1.0
trylimits/Eclipse-Postfix-Code-Completion
luna/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetEvaluator.java
7875
/******************************************************************************* * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.eval; import java.util.Map; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.compiler.*; import org.eclipse.jdt.internal.compiler.ClassFile; import org.eclipse.jdt.internal.compiler.Compiler; import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies; import org.eclipse.jdt.internal.compiler.ICompilerRequestor; import org.eclipse.jdt.internal.compiler.IProblemFactory; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader; import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException; import org.eclipse.jdt.internal.compiler.env.IBinaryType; import org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; /** * A code snippet evaluator compiles and returns class file for a code snippet. * Or it reports problems against the code snippet. */ @SuppressWarnings({ "rawtypes" }) public class CodeSnippetEvaluator extends Evaluator implements EvaluationConstants { /** * Whether the code snippet support classes should be found in the provided name environment * or on disk. */ static final boolean DEVELOPMENT_MODE = false; /** * The code snippet to evaluate. */ char[] codeSnippet; /** * The code snippet to generated compilation unit mapper */ CodeSnippetToCuMapper mapper; /** * Creates a new code snippet evaluator. */ CodeSnippetEvaluator(char[] codeSnippet, EvaluationContext context, INameEnvironment environment, Map options, IRequestor requestor, IProblemFactory problemFactory) { super(context, environment, options, requestor, problemFactory); this.codeSnippet = codeSnippet; } /** * @see org.eclipse.jdt.internal.eval.Evaluator */ protected void addEvaluationResultForCompilationProblem(Map resultsByIDs, CategorizedProblem problem, char[] cuSource) { CodeSnippetToCuMapper sourceMapper = getMapper(); int pbLineNumber = problem.getSourceLineNumber(); int evaluationType = sourceMapper.getEvaluationType(pbLineNumber); char[] evaluationID = null; switch(evaluationType) { case EvaluationResult.T_PACKAGE: evaluationID = this.context.packageName; // shift line number, source start and source end problem.setSourceLineNumber(1); problem.setSourceStart(0); problem.setSourceEnd(evaluationID.length - 1); break; case EvaluationResult.T_IMPORT: evaluationID = sourceMapper.getImport(pbLineNumber); // shift line number, source start and source end problem.setSourceLineNumber(1); problem.setSourceStart(0); problem.setSourceEnd(evaluationID.length - 1); break; case EvaluationResult.T_CODE_SNIPPET: evaluationID = this.codeSnippet; // shift line number, source start and source end problem.setSourceLineNumber(pbLineNumber - this.mapper.lineNumberOffset); problem.setSourceStart(problem.getSourceStart() - this.mapper.startPosOffset); problem.setSourceEnd(problem.getSourceEnd() - this.mapper.startPosOffset); break; case EvaluationResult.T_INTERNAL: evaluationID = cuSource; break; } EvaluationResult result = (EvaluationResult)resultsByIDs.get(evaluationID); if (result == null) { resultsByIDs.put(evaluationID, new EvaluationResult(evaluationID, evaluationType, new CategorizedProblem[] {problem})); } else { result.addProblem(problem); } } /** * @see org.eclipse.jdt.internal.eval.Evaluator */ protected char[] getClassName() { return CharOperation.concat(CODE_SNIPPET_CLASS_NAME_PREFIX, Integer.toString(EvaluationContext.CODE_SNIPPET_COUNTER + 1).toCharArray()); } /** * @see Evaluator */ Compiler getCompiler(ICompilerRequestor compilerRequestor) { Compiler compiler = null; if (!DEVELOPMENT_MODE) { // If we are not developping the code snippet support classes, // use a regular compiler and feed its lookup environment with // the code snippet support classes CompilerOptions compilerOptions = new CompilerOptions(this.options); compilerOptions.performMethodsFullRecovery = true; compilerOptions.performStatementsRecovery = true; compiler = new CodeSnippetCompiler( this.environment, DefaultErrorHandlingPolicies.exitAfterAllProblems(), compilerOptions, compilerRequestor, this.problemFactory, this.context, getMapper().startPosOffset, getMapper().startPosOffset + this.codeSnippet.length - 1); ((CodeSnippetParser) compiler.parser).lineSeparatorLength = this.context.lineSeparator.length(); // Initialize the compiler's lookup environment with the already compiled super classes IBinaryType binary = this.context.getRootCodeSnippetBinary(); if (binary != null) { compiler.lookupEnvironment.cacheBinaryType(binary, null /*no access restriction*/); } VariablesInfo installedVars = this.context.installedVars; if (installedVars != null) { ClassFile[] globalClassFiles = installedVars.classFiles; for (int i = 0; i < globalClassFiles.length; i++) { ClassFileReader binaryType = null; try { binaryType = new ClassFileReader(globalClassFiles[i].getBytes(), null); } catch (ClassFormatException e) { e.printStackTrace(); // Should never happen since we compiled this type } compiler.lookupEnvironment.cacheBinaryType(binaryType, null /*no access restriction*/); } } } else { // If we are developping the code snippet support classes, // use a wrapped environment so that if the code snippet classes are not found // then a default implementation is provided. CompilerOptions compilerOptions = new CompilerOptions(this.options); compilerOptions.performMethodsFullRecovery = true; compilerOptions.performStatementsRecovery = true; compiler = new Compiler( getWrapperEnvironment(), DefaultErrorHandlingPolicies.exitAfterAllProblems(), compilerOptions, compilerRequestor, this.problemFactory); } return compiler; } private CodeSnippetToCuMapper getMapper() { if (this.mapper == null) { char[] varClassName = null; VariablesInfo installedVars = this.context.installedVars; if (installedVars != null) { char[] superPackageName = installedVars.packageName; if (superPackageName != null && superPackageName.length != 0) { varClassName = CharOperation.concat(superPackageName, installedVars.className, '.'); } else { varClassName = installedVars.className; } } this.mapper = new CodeSnippetToCuMapper( this.codeSnippet, this.context.packageName, this.context.imports, getClassName(), varClassName, this.context.localVariableNames, this.context.localVariableTypeNames, this.context.localVariableModifiers, this.context.declaringTypeName, this.context.lineSeparator, CompilerOptions.versionToJdkLevel(this.options.get(JavaCore.COMPILER_COMPLIANCE)) ); } return this.mapper; } /** * @see org.eclipse.jdt.internal.eval.Evaluator */ protected char[] getSource() { return getMapper().cuSource; } /** * Returns an environment that wraps the client's name environment. * This wrapper always considers the wrapped environment then if the name is * not found, it search in the code snippet support. This includes the superclass * org.eclipse.jdt.internal.eval.target.CodeSnippet as well as the global variable classes. */ private INameEnvironment getWrapperEnvironment() { return new CodeSnippetEnvironment(this.environment, this.context); } }
epl-1.0
epsilonlabs/epsilon-static-analysis
org.eclipse.epsilon.haetae.eol.metamodel.visitor.printer/src/org/eclipse/epsilon/eol/visitor/printer/impl/ExecutableAnnotationPrinter.java
859
package org.eclipse.epsilon.eol.visitor.printer.impl; import org.eclipse.epsilon.eol.metamodel.ExecutableAnnotationStatement; import org.eclipse.epsilon.eol.metamodel.visitor.EolVisitorController; import org.eclipse.epsilon.eol.metamodel.visitor.ExecutableAnnotationStatementVisitor; import org.eclipse.epsilon.eol.visitor.printer.context.EOLPrinterContext; public class ExecutableAnnotationPrinter extends ExecutableAnnotationStatementVisitor<EOLPrinterContext, Object>{ @Override public Object visit(ExecutableAnnotationStatement executableAnnotationStatement, EOLPrinterContext context, EolVisitorController<EOLPrinterContext, Object> controller) { String result = "$" + controller.visit(executableAnnotationStatement.getName(), context) + " " + controller.visit(executableAnnotationStatement.getExpression(), context); return result; } }
epl-1.0
usethesource/rascal-value
src/main/java/io/usethesource/vallang/type/AliasType.java
18092
/******************************************************************************* * Copyright (c) 2007 IBM Corporation. * 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 Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation *******************************************************************************/ package io.usethesource.vallang.type; import java.util.Iterator; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.function.Function; import java.util.function.Supplier; import org.checkerframework.checker.nullness.qual.Nullable; import io.usethesource.vallang.IConstructor; import io.usethesource.vallang.IList; import io.usethesource.vallang.ISetWriter; import io.usethesource.vallang.IString; import io.usethesource.vallang.IValue; import io.usethesource.vallang.IValueFactory; import io.usethesource.vallang.exceptions.FactTypeUseException; import io.usethesource.vallang.type.TypeFactory.RandomTypesConfig; /** * A AliasType is a named for a type, i.e. a type alias that can be used to * abstract from types that have a complex structure. Since a * * @{link Type} represents a set of values, a AliasType is defined to be an * alias (because it represents the same set of values). * <p> * Detail: This API does not allow @{link IValue}'s of the basic types * (int, double, etc) to be tagged with a AliasType. Instead the * immediately surrounding structure, such as a set or a relation will * refer to the AliasType. */ /* package */ final class AliasType extends Type { private final String fName; private final Type fAliased; private final Type fParameters; /* package */ AliasType(String name, Type aliased) { fName = name; fAliased = aliased; fParameters = TypeFactory.getInstance().voidType(); } /* package */ AliasType(String name, Type aliased, Type parameters) { fName = name; fAliased = aliased; fParameters = parameters; } public static class Info implements TypeFactory.TypeReifier { @Override public Type getSymbolConstructorType() { return symbols().typeSymbolConstructor("alias", TF.stringType(), "name", TF.listType(symbols().symbolADT()), "parameters", symbols().symbolADT(), "aliased"); } @Override public Type fromSymbol(IConstructor symbol, TypeStore store, Function<IConstructor, Set<IConstructor>> grammar) { String name = ((IString) symbol.get("name")).getValue(); Type aliased = symbols().fromSymbol((IConstructor) symbol.get("aliased"), store, grammar); IList parameters = (IList) symbol.get("parameters"); // we expand the aliases here, but only if the // type parameters have been instantiated or there are none if (parameters.isEmpty()) { return aliased; } else { Type params = symbols().fromSymbols(parameters, store, grammar); return params.isOpen() ? TF.aliasTypeFromTuple(store, name, aliased, params) : aliased; } } @Override public IConstructor toSymbol(Type type, IValueFactory vf, TypeStore store, ISetWriter grammar, Set<IConstructor> done) { // we expand aliases away here! return type.getAliased().asSymbol(vf, store, grammar, done); } @Override public void asProductions(Type type, IValueFactory vf, TypeStore store, ISetWriter grammar, Set<IConstructor> done) { type.getAliased().asProductions(vf, store, grammar, done); type.getTypeParameters().asProductions(vf, store, grammar, done); } @Override public Type randomInstance(Supplier<Type> next, TypeStore store, RandomTypesConfig rnd) { // we don't generate aliases because we also never reify them if (!rnd.isWithAliases()) { return tf().randomType(store, rnd); } else { // TODO: could generate some type parameters as well return tf().aliasType(store, randomLabel(rnd), tf().randomType(store, rnd)); } } } @Override public TypeFactory.TypeReifier getTypeReifier() { return new Info(); } @Override public boolean isParameterized() { return !fParameters.isBottom(); } @Override public boolean isOpen() { return fParameters.isOpen() || fAliased.isOpen(); } @Override public boolean isAliased() { return true; } @Override public boolean isFixedWidth() { return fAliased.isFixedWidth(); } /** * @return the type parameters of the alias type, void when there are none */ @Override public Type getTypeParameters() { return fParameters; } @Override public String getName() { return fName; } @Override public Type getAliased() { return fAliased; } @Override protected boolean isSupertypeOf(Type type) { return type.isSubtypeOfAlias(this); } @Override public Type lub(Type other) { return other.lubWithAlias(this); } @Override public Type glb(Type type) { return type.glbWithAlias(this); } @Override protected Type lubWithAlias(Type type) { if (this == type) return this; if (getName().equals(type.getName())) { return TypeFactory.getInstance().aliasTypeFromTuple(new TypeStore(), type.getName(), getAliased().lub(type.getAliased()), getTypeParameters().lub(type.getTypeParameters())); } return getAliased().lub(type); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(fName); if (isParameterized()) { sb.append("["); int idx = 0; for (Type elemType : fParameters) { if (idx++ > 0) { sb.append(","); } sb.append(elemType.toString()); } sb.append("]"); } return sb.toString(); } @Override public int hashCode() { return 49991 + 49831 * fName.hashCode() + 67349 * fAliased.hashCode() + 1433 * fParameters.hashCode(); } @Override public boolean equals(@Nullable Object o) { if (o == null) { return false; } if (o == this) { return true; } if (o instanceof AliasType) { AliasType other = (AliasType) o; return fName.equals(other.fName) && fAliased == other.fAliased && fParameters == other.fParameters; } return false; } @Override public <T, E extends Throwable> T accept(ITypeVisitor<T, E> visitor) throws E { return visitor.visitAlias(this); } @Override public int getArity() { return fAliased.getArity(); } @Override public Type getBound() { return fAliased.getBound(); } @Override public Type getElementType() { return fAliased.getElementType(); } @Override public int getFieldIndex(String fieldName) { return fAliased.getFieldIndex(fieldName); } @Override public String getFieldName(int i) { return fAliased.getFieldName(i); } @Override public String getKeyLabel() { return fAliased.getKeyLabel(); } @Override public String getValueLabel() { return fAliased.getValueLabel(); } @Override public Type getFieldType(int i) { return fAliased.getFieldType(i); } @Override public Type getFieldType(String fieldName) { return fAliased.getFieldType(fieldName); } @Override public Type getFieldTypes() { return fAliased.getFieldTypes(); } @Override public Type getKeyType() { return fAliased.getKeyType(); } @Override public boolean isBottom() { return fAliased.isBottom(); } @Override public Type getValueType() { return fAliased.getValueType(); } @Override public Type compose(Type other) { return fAliased.compose(other); } @Override public boolean hasFieldNames() { return fAliased.hasFieldNames(); } @Override public boolean hasKeywordField(String fieldName, TypeStore store) { return fAliased.hasKeywordField(fieldName, store); } @Override public Type instantiate(Map<Type, Type> bindings) { if (isParameterized()) { // note how we do not declare the new alias anywhere. return TypeFactory.getInstance().getFromCache(new AliasType(fName, fAliased.instantiate(bindings), fParameters.instantiate(bindings))); } // if an alias is not parametrized, then instantiation should not have an effect. // if it would have an effect, then the alias type would contain an unbound type parameter // which is a bug we assume is absent here. return this; } @Override public boolean match(Type matched, Map<Type, Type> bindings) throws FactTypeUseException { return super.match(matched, bindings) && fAliased.match(matched, bindings); } @Override public Iterator<Type> iterator() { return fAliased.iterator(); } @Override public Type select(int... fields) { return fAliased.select(fields); } @Override public Type select(String... names) { return fAliased.select(names); } @Override public boolean hasField(String fieldName) { return fAliased.hasField(fieldName); } @Override public boolean hasField(String fieldName, TypeStore store) { return fAliased.hasField(fieldName, store); } @Override protected boolean isSubtypeOfReal(Type type) { return fAliased.isSubtypeOfReal(type); } @Override protected boolean isSubtypeOfInteger(Type type) { return fAliased.isSubtypeOfInteger(type); } @Override protected boolean isSubtypeOfRational(Type type) { return fAliased.isSubtypeOfRational(type); } @Override protected boolean isSubtypeOfList(Type type) { return fAliased.isSubtypeOfList(type); } @Override protected boolean isSubtypeOfMap(Type type) { return fAliased.isSubtypeOfMap(type); } @Override protected boolean isSubtypeOfNumber(Type type) { return fAliased.isSubtypeOfNumber(type); } @Override protected boolean isSubtypeOfSet(Type type) { return fAliased.isSubtypeOfSet(type); } @Override protected boolean isSubtypeOfSourceLocation(Type type) { return fAliased.isSubtypeOfSourceLocation(type); } @Override protected boolean isSubtypeOfString(Type type) { return fAliased.isSubtypeOfString(type); } @Override protected boolean isSubtypeOfNode(Type type) { return fAliased.isSubtypeOfNode(type); } @Override protected boolean isSubtypeOfConstructor(Type type) { return fAliased.isSubtypeOfConstructor(type); } @Override protected boolean isSubtypeOfAbstractData(Type type) { return fAliased.isSubtypeOfAbstractData(type); } @Override protected boolean isSubtypeOfTuple(Type type) { return fAliased.isSubtypeOfTuple(type); } @Override protected boolean isSubtypeOfFunction(Type type) { return fAliased.isSubtypeOfFunction(type); } @Override protected boolean isSubtypeOfVoid(Type type) { return fAliased.isSubtypeOfVoid(type); } @Override protected boolean isSubtypeOfBool(Type type) { return fAliased.isSubtypeOfBool(type); } @Override protected boolean isSubtypeOfExternal(Type type) { return fAliased.isSubtypeOfExternal(type); } @Override protected boolean isSubtypeOfDateTime(Type type) { return fAliased.isSubtypeOfDateTime(type); } @Override protected Type lubWithReal(Type type) { return fAliased.lubWithReal(type); } @Override protected Type lubWithInteger(Type type) { return fAliased.lubWithInteger(type); } @Override protected Type lubWithRational(Type type) { return fAliased.lubWithRational(type); } @Override protected Type lubWithList(Type type) { return fAliased.lubWithList(type); } @Override protected Type lubWithMap(Type type) { return fAliased.lubWithMap(type); } @Override protected Type lubWithNumber(Type type) { return fAliased.lubWithNumber(type); } @Override protected Type lubWithSet(Type type) { return fAliased.lubWithSet(type); } @Override protected Type lubWithSourceLocation(Type type) { return fAliased.lubWithSourceLocation(type); } @Override protected Type lubWithString(Type type) { return fAliased.lubWithString(type); } @Override protected Type lubWithNode(Type type) { return fAliased.lubWithNode(type); } @Override protected Type lubWithConstructor(Type type) { return fAliased.lubWithConstructor(type); } @Override protected Type lubWithAbstractData(Type type) { return fAliased.lubWithAbstractData(type); } @Override protected Type lubWithTuple(Type type) { return fAliased.lubWithTuple(type); } @Override protected Type lubWithFunction(Type type) { return fAliased.lubWithFunction(type); } @Override protected Type lubWithValue(Type type) { return fAliased.lubWithValue(type); } @Override protected Type lubWithVoid(Type type) { return fAliased.lubWithVoid(type); } @Override protected Type lubWithBool(Type type) { return fAliased.lubWithBool(type); } @Override protected Type lubWithExternal(Type type) { return fAliased.lubWithExternal(type); } @Override protected Type lubWithDateTime(Type type) { return fAliased.lubWithDateTime(type); } @Override protected boolean isSubtypeOfValue(Type type) { return true; } @Override protected Type glbWithReal(Type type) { return fAliased.glbWithReal(type); } @Override protected Type glbWithInteger(Type type) { return fAliased.glbWithInteger(type); } @Override protected Type glbWithRational(Type type) { return fAliased.glbWithRational(type); } @Override protected Type glbWithList(Type type) { return fAliased.glbWithList(type); } @Override protected Type glbWithMap(Type type) { return fAliased.glbWithMap(type); } @Override protected Type glbWithNumber(Type type) { return fAliased.glbWithNumber(type); } @Override protected Type glbWithSet(Type type) { return fAliased.glbWithSet(type); } @Override protected Type glbWithSourceLocation(Type type) { return fAliased.glbWithSourceLocation(type); } @Override protected Type glbWithString(Type type) { return fAliased.glbWithString(type); } @Override protected Type glbWithNode(Type type) { return fAliased.glbWithNode(type); } @Override protected Type glbWithConstructor(Type type) { return fAliased.glbWithConstructor(type); } @Override protected Type glbWithAlias(Type type) { if (this == type) return this; if (getName().equals(type.getName())) { return TypeFactory.getInstance().aliasTypeFromTuple(new TypeStore(), type.getName(), getAliased().glb(type.getAliased()), getTypeParameters().glb(type.getTypeParameters())); } return getAliased().glb(type); } @Override protected Type glbWithAbstractData(Type type) { return fAliased.glbWithAbstractData(type); } @Override protected Type glbWithTuple(Type type) { return fAliased.glbWithTuple(type); } @Override protected Type glbWithFunction(Type type) { return fAliased.glbWithFunction(type); } @Override protected Type glbWithValue(Type type) { return fAliased.glbWithValue(type); } @Override protected Type glbWithVoid(Type type) { return fAliased.glbWithVoid(type); } @Override protected Type glbWithBool(Type type) { return fAliased.glbWithBool(type); } @Override protected Type glbWithExternal(Type type) { return fAliased.glbWithExternal(type); } @Override protected Type glbWithDateTime(Type type) { return fAliased.glbWithDateTime(type); } @Override public Type getAbstractDataType() { return fAliased.getAbstractDataType(); } @Override public IValue randomValue(Random random, IValueFactory vf, TypeStore store, Map<Type, Type> typeParameters, int maxDepth, int maxBreadth) { return getAliased().randomValue(random, vf, store, typeParameters, maxDepth, maxBreadth); } @Override public boolean intersects(Type other) { return false; } @Override protected boolean intersectsWithReal(Type type) { return fAliased.intersectsWithReal(type); } @Override protected boolean intersectsWithInteger(Type type) { return fAliased.intersectsWithInteger(type); } @Override protected boolean intersectsWithRational(Type type) { return fAliased.intersectsWithRational(type); } @Override protected boolean intersectsWithList(Type type) { return fAliased.intersectsWithList(type); } @Override protected boolean intersectsWithMap(Type type) { return fAliased.intersectsWithMap(type); } @Override protected boolean intersectsWithNumber(Type type) { return fAliased.intersectsWithNumber(type); } @Override protected boolean intersectsWithSet(Type type) { return fAliased.intersectsWithSet(type); } @Override protected boolean intersectsWithSourceLocation(Type type) { return fAliased.intersectsWithSourceLocation(type); } @Override protected boolean intersectsWithString(Type type) { return fAliased.intersectsWithString(type); } @Override protected boolean intersectsWithNode(Type type) { return fAliased.intersectsWithNode(type); } @Override protected boolean intersectsWithConstructor(Type type) { return fAliased.intersectsWithConstructor(type); } @Override protected boolean intersectsWithAbstractData(Type type) { return fAliased.intersectsWithAbstractData(type); } @Override protected boolean intersectsWithTuple(Type type) { return fAliased.intersectsWithTuple(type); } @Override protected boolean intersectsWithFunction(Type type) { return fAliased.intersectsWithFunction(type); } @Override protected boolean intersectsWithValue(Type type) { return fAliased.intersectsWithValue(type); } @Override protected boolean intersectsWithVoid(Type type) { return fAliased.intersectsWithVoid(type); } @Override protected boolean intersectsWithBool(Type type) { return fAliased.intersectsWithBool(type); } @Override protected boolean intersectsWithExternal(Type type) { return fAliased.intersectsWithExternal(type); } @Override protected boolean intersectsWithDateTime(Type type) { return fAliased.intersectsWithDateTime(type); } }
epl-1.0
clinique/openhab2
bundles/org.openhab.io.hueemulation/src/main/java/org/openhab/io/hueemulation/internal/rest/StatusResource.java
9655
/** * Copyright (c) 2010-2019 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.io.hueemulation.internal.rest; import java.net.URI; import java.util.stream.Collectors; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.jupnp.UpnpService; import org.jupnp.controlpoint.ControlPoint; import org.jupnp.model.meta.Device; import org.jupnp.model.meta.DeviceDetails; import org.jupnp.model.meta.LocalDevice; import org.jupnp.model.meta.RemoteDevice; import org.jupnp.registry.Registry; import org.jupnp.registry.RegistryListener; import org.openhab.io.hueemulation.internal.ConfigStore; import org.openhab.io.hueemulation.internal.upnp.UpnpServer; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicyOption; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is used by the status REST API for troubleshoot purposes. * <p> * The UPNP announcement is tested, the /description.xml reachability is checked, * and some statistics are gathered. * * @author David Graeff - Initial contribution */ @Component(immediate = false, service = { StatusResource.class }, property = "com.eclipsesource.jaxrs.publish=false") @Path("") @NonNullByDefault public class StatusResource implements RegistryListener { @Reference(cardinality = ReferenceCardinality.OPTIONAL, policyOption = ReferencePolicyOption.GREEDY) protected @NonNullByDefault({}) UpnpServer discovery; @Reference protected @NonNullByDefault({}) ConfigStore cs; @Reference protected @NonNullByDefault({}) UpnpService upnpService; private enum upnpStatus { service_not_registered, service_registered_but_no_UPnP_traffic_yet, upnp_announcement_thread_not_running, any_device_but_not_this_one_found, success } private upnpStatus selfTestUpnpFound = upnpStatus.service_not_registered; private final Logger logger = LoggerFactory.getLogger(StatusResource.class); /** * This will register to the {@link UpnpService} registry to get notified of new UPNP devices and check all existing * devices if they match our UPNP announcement. */ public void startUpnpSelfTest() { Registry registry = upnpService.getRegistry(); if (registry == null) { logger.warn("upnp service registry is null!"); return; } selfTestUpnpFound = upnpStatus.service_registered_but_no_UPnP_traffic_yet; for (RemoteDevice device : registry.getRemoteDevices()) { remoteDeviceAdded(registry, device); } for (LocalDevice device : registry.getLocalDevices()) { localDeviceAdded(registry, device); } registry.addListener(this); ControlPoint controlPoint = upnpService.getControlPoint(); if (controlPoint != null) { controlPoint.search(); } } @GET @Path("status/link") @Produces("text/plain") public Response link(@Context UriInfo uri) { cs.setLinkbutton(!cs.ds.config.linkbutton, true, uri.getQueryParameters().containsKey("v1")); URI newuri = uri.getBaseUri().resolve("/api/status"); return Response.seeOther(newuri).build(); } private static String toYesNo(boolean b) { return b ? "yes" : "no"; } private static String TD(String s) { return "<td>" + s + "</td>"; } private static String TR(String s) { return "<tr>" + s + "</tr>"; } @GET @Path("status") @Produces("text/html") public String getStatus() { if (discovery == null) { // Optional service wiring return "UPnP Server service not started!"; } int httpPort = discovery.getDefaultport(); String format = "<html><body><h1>Self test</h1>" + // "<p>To access any links you need be in pairing mode!</p>" + // "<p>Pairing mode: %s (%s) <a href='%s/api/status/link'>Enable</a> | <a href='%s/api/status/link?V1=true'>Enable with bridge V1 emulation</a></p>" + // "%d published lights (see <a href='%s/api/testuser/lights'>%s/api/testuser/lights</a>)<br>" + // "%d published sensors (see <a href='%s/api/testuser/sensors'>%s/api/testuser/sensors</a>)<br>" + // "<h2>UPnP discovery test</h2>" + // "<p>%s</p>" + // "<table style='border:1px solid black'><tr><td>serial no</td><td>name</td></tr>%s</table>" + // "<h2>Reachability test</h2>" + // "<table style='border:1px solid black'><tr><td>URL</td><td>Responds?</td><td>Ours?</td></tr>%s</table>" + // "<h2>Users</h2><ul>%s</ul></body></html>"; final String users = cs.ds.config.whitelist.entrySet().stream().map(user -> "<li>" + user.getKey() + " <b>" + user.getValue().name + "</b> <small>" + user.getValue().lastUseDate + "</small>") .collect(Collectors.joining("\n")); final String url = "http://" + cs.ds.config.ipaddress + ":" + String.valueOf(httpPort); final String reachable = discovery.selfTests().stream() .map(entry -> TR(TD(entry.address) + TD(toYesNo(entry.reachable)) + TD(toYesNo(entry.isOurs)))) .collect(Collectors.joining("\n")); Registry registry = upnpService.getRegistry(); final String upnps; if (registry != null) { upnps = registry.getRemoteDevices().stream().map(device -> getDetails(device)) .map(details -> TR(TD(details.getSerialNumber()) + TD(details.getFriendlyName()))) .collect(Collectors.joining("\n")); } else { upnps = TR(TD("service not available") + TD("")); } if (!discovery.upnpAnnouncementThreadRunning()) { selfTestUpnpFound = upnpStatus.upnp_announcement_thread_not_running; } return String.format(format, cs.ds.config.linkbutton ? "On" : "Off", cs.getConfig().temporarilyEmulateV1bridge ? "V1" : "V2", url, url, // cs.ds.lights.size(), url, url, cs.ds.sensors.size(), url, url, // selfTestUpnpFound.name().replace('_', ' '), // upnps, reachable, users); } @NonNullByDefault({}) @Override public void remoteDeviceDiscoveryStarted(Registry registry, RemoteDevice device) { } @NonNullByDefault({}) @Override public void remoteDeviceDiscoveryFailed(Registry registry, RemoteDevice device, Exception ex) { } @NonNullByDefault({}) @Override public void remoteDeviceAdded(Registry registry, RemoteDevice device) { if (selfTestUpnpFound == upnpStatus.success) { return; } checkForDevice(getDetails(device)); } private static DeviceDetails getDetails(@Nullable Device<?, ?, ?> device) { if (device != null) { DeviceDetails details = device.getDetails(); if (details != null) { return details; } } return new DeviceDetails(null, "", null, null, "", null, null, null, null, null); } private void checkForDevice(DeviceDetails details) { selfTestUpnpFound = upnpStatus.any_device_but_not_this_one_found; try { if (cs.ds.config.bridgeid.equals(details.getSerialNumber())) { selfTestUpnpFound = upnpStatus.success; } } catch (Exception e) { // We really don't want the service to fail on any exception logger.warn("upnp service: adding services failed: {}", details.getFriendlyName(), e); } } @NonNullByDefault({}) @Override public void remoteDeviceUpdated(Registry registry, RemoteDevice device) { } @NonNullByDefault({}) @Override public void remoteDeviceRemoved(Registry registry, RemoteDevice device) { if (selfTestUpnpFound != upnpStatus.success || discovery.upnpAnnouncementThreadRunning()) { return; } DeviceDetails details = getDetails(device); String serialNo = details.getSerialNumber(); if (cs.ds.config.bridgeid.equals(serialNo)) { selfTestUpnpFound = upnpStatus.any_device_but_not_this_one_found; } } @NonNullByDefault({}) @Override public void localDeviceAdded(Registry registry, LocalDevice device) { if (selfTestUpnpFound == upnpStatus.success || discovery.upnpAnnouncementThreadRunning()) { return; } checkForDevice(getDetails(device)); } @NonNullByDefault({}) @Override public void localDeviceRemoved(Registry registry, LocalDevice device) { } @NonNullByDefault({}) @Override public void beforeShutdown(Registry registry) { } @Override public void afterShutdown() { selfTestUpnpFound = upnpStatus.service_not_registered; } }
epl-1.0
paulianttila/openhab2
bundles/org.openhab.binding.bsblan/src/main/java/org/openhab/binding/bsblan/internal/configuration/BsbLanParameterConfiguration.java
923
/** * 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.bsblan.internal.configuration; /** * The {@link BsbLanParameterConfiguration} is the class used to match the * thing configuration. * * @author Peter Schraffl - Initial contribution */ public class BsbLanParameterConfiguration { /** * Parameter Id (ProgNr) to query */ public Integer id; /** * Parameter Id (ProgNr) used for change requests. */ public Integer setId; /** * Command type used for change requests (INF or SET) */ public String setType; }
epl-1.0
Maarc/windup-as-a-service
windup_0_7/windup-metadata/src/main/java/org/jboss/windup/graph/profile/Spring25.java
1854
/* * JBoss, Home of Professional Open Source. * Copyright 2009, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.windup.graph.profile; import javassist.bytecode.ClassFile; /** * Spring 2.5 * * @author Jesper Pedersen <jesper.pedersen@jboss.org> */ public class Spring25 extends AbstractProfile { private static final String CLASS_SET = "spring25.clz.gz"; private static final String PROFILE_NAME = "Spring 2.5"; private static final String PROFILE_CODE = "spring25"; private static final String PROFILE_LOCATION = "spring.jar"; private static final int CLASSFILE_VERSION = ClassFile.JAVA_4; /** Constructor */ public Spring25() { super(CLASS_SET, PROFILE_NAME, CLASSFILE_VERSION, PROFILE_LOCATION); } @Override public String getProfileCode() { return PROFILE_CODE; } @Override protected String getProfileName() { return PROFILE_NAME; } }
epl-1.0
pecko/debrief
org.mwc.cmap.NarrativeViewer/src/de/kupzog/ktable/renderers/FixedCheckableCellRenderer.java
7073
/* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2014, PlanetMayo Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * 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. */ package de.kupzog.ktable.renderers; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Display; import de.kupzog.ktable.KTableModel; import de.kupzog.ktable.KTableSortComparator; import de.kupzog.ktable.KTableSortedModel; import de.kupzog.ktable.SWTX; /** * Renderer that paints cells as fixed (respecting all the flags used in * <code>FixedCellRenderer</code>). Instead of painting text and images, it * paings checked/unchecked signs representing boolean values. * * @author Lorenz Maierhofer <lorenz.maierhofer@logicmindguide.com> * @see de.kupzog.ktable.renderers.FixedCellRenderer */ public class FixedCheckableCellRenderer extends CheckableCellRenderer { // some default images: /** * Small arrow pointing down. Can be used when displaying a sorting * indicator. */ public static final Image IMAGE_ARROWDOWN = SWTX.loadImageResource(Display.getCurrent(), "/icons/arrow_down.gif"); /** Small arrow pointing up. Can be used when displaying a sorting indicator */ public static final Image IMAGE_ARROWUP = SWTX.loadImageResource(Display.getCurrent(), "/icons/arrow_up.gif"); public static final Color COLOR_FIXEDBACKGROUND = Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND); /** * A constructor that lets the caller specify the style. * * @param style * The style that should be used to paint. * <p> - Use SWT.FLAT for a flat look.<br> - Use SWT.PUSH for a * button-like look. (default) * <p> * The following additional indications can be activated: <br> - * INDICATION_FOCUS changes the background color if the fixed * cell has focus.<br> - INDICATION_FOCUS_ROW changes the * background color so that it machtes with normal cells in * rowselection mode.<br> - INDICATION_SORT shows the sort * direction when using a KTableSortedModel.<br> - * INDICATION_CLICKED shows a click feedback, if STYLE_PUSH is * specified. */ public FixedCheckableCellRenderer(int style) { super(style); m_Style |= STYLE_PUSH; } /** * Paint a box with or without a checked symbol. * * @see de.kupzog.ktable.KTableCellRenderer#drawCell(GC, Rectangle, int, * int, Object, boolean, boolean, boolean, KTableModel) */ public void drawCell(GC gc, Rectangle rect, int col, int row, Object content, boolean focus, boolean fixed, boolean clicked, KTableModel model) { // set up the colors: Color bgColor = getBackground(); Color bottomBorderColor = COLOR_LINE_DARKGRAY; Color rightBorderColor = COLOR_LINE_DARKGRAY; Color fgColor = getForeground(); if (focus && (m_Style & INDICATION_FOCUS) != 0) { bgColor = COLOR_FIXEDHIGHLIGHT; bottomBorderColor = COLOR_TEXT; rightBorderColor = COLOR_TEXT; } if (focus && (m_Style & INDICATION_FOCUS_ROW) != 0) { bgColor = COLOR_BGROWFOCUS; bottomBorderColor = COLOR_BGROWFOCUS; rightBorderColor = COLOR_BGROWFOCUS; fgColor = COLOR_FGROWFOCUS; } // STYLE_FLAT: if ((m_Style & STYLE_FLAT) != 0) { rect = drawDefaultSolidCellLine(gc, rect, bottomBorderColor, rightBorderColor); // draw content: drawCellContent(gc, rect, col, content, model, bgColor, fgColor, clicked); } else { // STYLE_PUSH drawCellButton(gc, rect, "", clicked && (m_Style & INDICATION_CLICKED) != 0); // push style border is drawn, exclude: rect.x += 2; rect.y += 2; rect.width -= 5; rect.height -= 5; // draw content: drawCellContent(gc, rect, col, content, model, bgColor, fgColor, clicked); } } /** * Check for sort indicator and delegate content drawing to * drawCellContent() */ private void drawCellContent(GC gc, Rectangle rect, int col, Object content, KTableModel model, Color bgColor, Color fgColor, boolean clicked) { Image indicator = null; int x = 0, y = 0; if ((m_Style & INDICATION_SORT) != 0 && model instanceof KTableSortedModel && ((KTableSortedModel) model).getSortColumn() == col) { int sort = ((KTableSortedModel) model).getSortState(); if (sort == KTableSortComparator.SORT_UP) indicator = IMAGE_ARROWDOWN; else if (sort == KTableSortComparator.SORT_DOWN) indicator = IMAGE_ARROWUP; if (indicator != null) { int contentLength = rect.x + 11 + gc.stringExtent(content.toString()).x; x = rect.x + rect.width - 8; if (contentLength < x) x = contentLength; else rect.width -= indicator.getBounds().width + 11; y = rect.y + rect.height / 2 - indicator.getBounds().height / 2; // do not draw if there is not enough space for the image: if (rect.width + 8 < indicator.getBounds().width) { rect.width += indicator.getBounds().width + 11; indicator = null; } } } drawCheckableImage(gc, rect, content, bgColor, clicked); // draw sort indicator: if (indicator != null) { gc.fillRectangle(x, y, indicator.getBounds().width, indicator.getBounds().height); gc.drawImage(indicator, x, y); } } /** * Draws the cell as a button. It is visibly clickable and contains a button * text. All line borders of the cell are overpainted - there will not be * any border between buttons. * * @param gc * The GC to use when painting. * @param rect * The cell area as given by KTable. (contains 1px bottom & right * offset) * @param text * The text to paint on the button. * @param pressed * Wether the button should be painted as clicked/pressed or not. */ protected void drawCellButton(GC gc, Rectangle rect, String text, boolean pressed) { rect.height += 1; rect.width += 1; gc.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_LIST_FOREGROUND)); if (pressed) { SWTX.drawButtonDown(gc, text, getAlignment(), null, getAlignment(), rect); } else { SWTX.drawButtonUp(gc, text, getAlignment(), null, getAlignment(), rect); } } /** * @return returns the currently set background color. If none was set, the * default value is returned. */ public Color getBackground() { if (m_bgColor != null) return m_bgColor; return COLOR_FIXEDBACKGROUND; } }
epl-1.0
gruppo4/quercus-upstream
modules/kernel/src/com/caucho/util/L10N.java
12872
/* * Copyright (c) 1998-2012 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.util; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; import java.util.Properties; /** * Localization */ public class L10N { private static final HashMap<String,Properties> _l10nMap = new HashMap<String,Properties>(); private Class<?> _cl; private Boolean _isMessageFileAvailable; private Boolean _isStringFileAvailable; private Properties _messages; private Properties _strings; public L10N(Class<?> cl) { _cl = cl; } public String l(String msg) { msg = getTranslated(msg); StringBuilder cb = new StringBuilder(); int length = msg.length(); int i = 0; while (i < length) { char ch = msg.charAt(i); if (ch != '{' || i + 2 >= length) { cb.append(ch); i++; } else { ch = msg.charAt(i + 1); if (ch == '{') { cb.append('{'); i += 2; } else if (ch == '{') { cb.append('{'); i += 2; } else { i = parseString(msg, i + 1, cb); } } } return cb.toString(); } public String l(String msg, long l) { return l(msg, String.valueOf(l)); } public String l(String msg, Object o) { msg = getTranslated(msg); StringBuilder cb = new StringBuilder(); int length = msg.length(); int i = 0; while (i < length) { char ch = msg.charAt(i); if (ch != '{' || i + 2 >= length) { cb.append(ch); i++; } else { ch = msg.charAt(i + 1); if (ch == '{') { cb.append('{'); i += 2; } else if (ch == '0') { cb.append(o); i += 3; } else if (ch == '{') { cb.append('{'); i += 2; } else { i = parseString(msg, i + 1, cb); } } } return cb.toString(); } public String l(String msg, Object o1, Object o2) { msg = getTranslated(msg); StringBuilder cb = new StringBuilder(); int length = msg.length(); int i = 0; while (i < length) { char ch = msg.charAt(i); if (ch != '{' || i + 2 >= length) { cb.append(ch); i++; } else { ch = msg.charAt(i + 1); if (ch == '{') { cb.append('{'); i += 2; } else if (ch == '0') { cb.append(o1); i += 3; } else if (ch == '1') { cb.append(o2); i += 3; } else if (ch == '{') { cb.append('{'); i += 2; } else { i = parseString(msg, i + 1, cb); } } } return cb.toString(); } public String l(String msg, Object o1, int i2) { return l(msg, o1, String.valueOf(i2)); } public String l(String msg, int i1, int i2) { return l(msg, String.valueOf(i1), String.valueOf(i2)); } public String l(String msg, Object o1, Object o2, Object o3) { msg = getTranslated(msg); StringBuilder cb = new StringBuilder(); int length = msg.length(); int i = 0; while (i < length) { char ch = msg.charAt(i); if (ch != '{' || i + 2 >= length) { cb.append(ch); i++; } else { ch = msg.charAt(i + 1); if (ch == '{') { cb.append('{'); i += 2; } else if (ch == '0') { cb.append(o1); i += 3; } else if (ch == '1') { cb.append(o2); i += 3; } else if (ch == '2') { cb.append(o3); i += 3; } else if (ch == '{') { cb.append('{'); i += 2; } else { i = parseString(msg, i + 1, cb); } } } return cb.toString(); } public String l(String msg, Object o1, Object o2, Object o3, Object o4) { msg = getTranslated(msg); StringBuilder cb = new StringBuilder(); int length = msg.length(); int i = 0; while (i < length) { char ch = msg.charAt(i); if (ch != '{' || i + 2 >= length) { cb.append(ch); i++; } else { ch = msg.charAt(i + 1); if (ch == '{') { cb.append('{'); i += 2; } else if (ch == '0') { cb.append(o1); i += 3; } else if (ch == '1') { cb.append(o2); i += 3; } else if (ch == '2') { cb.append(o3); i += 3; } else if (ch == '3') { cb.append(o4); i += 3; } else if (ch == '{') { cb.append('{'); i += 2; } else { i = parseString(msg, i + 1, cb); } } } return cb.toString(); } public String l(String msg, Object o1, Object o2, Object o3, Object o4, Object o5) { msg = getTranslated(msg); StringBuilder cb = new StringBuilder(); int length = msg.length(); int i = 0; while (i < length) { char ch = msg.charAt(i); if (ch != '{' || i + 2 >= length) { cb.append(ch); i++; } else { ch = msg.charAt(i + 1); if (ch == '{') { cb.append('{'); i += 2; } else if (ch == '0') { cb.append(o1); i += 3; } else if (ch == '1') { cb.append(o2); i += 3; } else if (ch == '2') { cb.append(o3); i += 3; } else if (ch == '3') { cb.append(o4); i += 3; } else if (ch == '4') { cb.append(o5); i += 3; } else if (ch == '{') { cb.append('{'); i += 2; } else { i = parseString(msg, i + 1, cb); } } } return cb.toString(); } public String l(String msg, Object o1, Object o2, Object o3, Object o4, Object o5, Object o6) { msg = getTranslated(msg); StringBuilder cb = new StringBuilder(); int length = msg.length(); int i = 0; while (i < length) { char ch = msg.charAt(i); if (ch != '{' || i + 2 >= length) { cb.append(ch); i++; } else { ch = msg.charAt(i + 1); if (ch == '{') { cb.append('{'); i += 2; } else if (ch == '0') { cb.append(o1); i += 3; } else if (ch == '1') { cb.append(o2); i += 3; } else if (ch == '2') { cb.append(o3); i += 3; } else if (ch == '3') { cb.append(o4); i += 3; } else if (ch == '4') { cb.append(o5); i += 3; } else if (ch == '5') { cb.append(o6); i += 3; } else if (ch == '{') { cb.append('{'); i += 2; } else { i = parseString(msg, i + 1, cb); } } } return cb.toString(); } public String l(String msg, Object ...objects) { msg = getTranslated(msg); return fillMessage(getStringMap(), msg, objects); } public static String fillMessage(String msg, Object ...objects) { return fillMessage(null, msg, objects); } public static String fillMessage(Properties stringMap, String msg, Object ...objects) { StringBuilder cb = new StringBuilder(); int length = msg.length(); int i = 0; while (i < length) { char ch = msg.charAt(i); if (ch != '{' || i + 2 >= length) { cb.append(ch); i++; } else { ch = msg.charAt(i + 1); if (ch == '{') { cb.append('{'); i += 2; } else if ('0' <= ch && ch <= '9') { int index = ch - '0'; Object value = objects[index]; if (value != null && (value instanceof Object[])) cb.append(Arrays.asList((Object[]) value)); else cb.append(objects[index]); i += 3; } else if (ch == '{') { cb.append('{'); i += 2; } else { i = parseString(msg, i + 1, cb, stringMap); } } } return cb.toString(); } private int parseString(String msg, int i, StringBuilder sb) { return parseString(msg, i, sb, getStringMap()); } private static int parseString(String msg, int i, StringBuilder sb, Properties stringMap) { StringBuilder arg = new StringBuilder(); int len = msg.length(); char ch; for (; i < len && (ch = msg.charAt(i)) != '}'; i++) { arg.append(ch); } // Properties stringMap = getStringMap(); if (stringMap != null) { String string = (String) stringMap.get(arg.toString()); if (string != null) { sb.append(string); return i + 1; } } sb.append('{'); sb.append(arg); return i; } private String getTranslated(String msg) { Properties messages = getMessageMap(); if (messages == null) return msg; String translated = (String) messages.get(msg); if (translated == null) { return msg; } else return translated; } private Properties getMessageMap() { if (_messages != null) return _messages; if (Boolean.FALSE.equals(_isMessageFileAvailable)) return null; String name = _cl.getName().replace('.', '/'); int p = name.lastIndexOf('/'); if (p > 0) name = name.substring(0, p); name = name + "/messages"; _messages = _l10nMap.get(name); if (_messages != null) { _isMessageFileAvailable = Boolean.TRUE; return _messages; } _messages = loadProperties(name); if (_messages != null) { _isMessageFileAvailable = Boolean.TRUE; _l10nMap.put(name, _messages); return _messages; } else { _isMessageFileAvailable = Boolean.FALSE; return null; } } private Properties getStringMap() { if (_strings != null) return _strings; if (Boolean.FALSE.equals(_isStringFileAvailable)) return null; String name = _cl.getName().replace('.', '/'); int p = name.lastIndexOf('/'); if (p > 0) name = name.substring(0, p); name = name + "/strings"; _strings = _l10nMap.get(name); if (_strings != null) { _isStringFileAvailable = Boolean.TRUE; return _strings; } _strings = loadProperties(name); if (_strings != null) { _isStringFileAvailable = Boolean.TRUE; _l10nMap.put(name, _strings); return _strings; } else { _isStringFileAvailable = Boolean.FALSE; return null; } } private Properties loadProperties(String name) { InputStream is = null; try { name = name + ".properties"; is = _cl.getClassLoader().getResourceAsStream(name); if (is != null) { Properties messages = new Properties(); messages.load(is); return messages; } } catch (Exception e) { e.printStackTrace(); // can't log in logging routines } finally { IoUtil.close(is); } return null; } }
gpl-2.0
oscarservice/oscar-old
src/main/java/oscar/oscarWorkflow/RHWorkFlow.java
4442
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package oscar.oscarWorkflow; import java.util.ArrayList; import java.util.Date; import java.util.Hashtable; import java.util.List; import org.oscarehr.util.MiscUtils; /** * Generic WorkFlow Description * @author jay */ public class RHWorkFlow implements WorkFlow { /** Creates a new instance of RHWorkFlow */ static final String WORKFLOWTYPE = "RH"; static Hashtable<String,WFState> states = null; static ArrayList<WFState> stateList = null; public RHWorkFlow() { states = new Hashtable<String,WFState>(); //TODO: CLEAN THIS UP WHEN THIS IS PROCESSED IN A XML FILE WFState wf1 = new WFState("1","No Appt made",""); WFState wf2 = new WFState("2","Appt Booked",""); WFState wf3 = new WFState("3","Injection 28",""); WFState wf4 = new WFState("4","Requires Another Injection",""); WFState wf5 = new WFState("5","Missed Appt","") ; WFState wf6 = new WFState("6","Follow up Appt Booked",""); WFState wfC = new WFState("C","Closed",""); states.put("1",wf1); states.put("2",wf2); states.put("3",wf3); states.put("4",wf4); states.put("5",wf5); states.put("C",wfC); stateList = new ArrayList<WFState>(); stateList.add(wf1); stateList.add(wf2); stateList.add(wf3); stateList.add(wf4); stateList.add(wf5); stateList.add(wfC); } public ArrayList getActiveWorkFlowList(String demographicNo) { WorkFlowState wfs = new WorkFlowState(); return wfs.getActiveWorkFlowList(RHWorkFlow.WORKFLOWTYPE,demographicNo); } public ArrayList getActiveWorkFlowList() { WorkFlowState wfs = new WorkFlowState(); return wfs.getActiveWorkFlowList(RHWorkFlow.WORKFLOWTYPE); } public String getState(String state) { MiscUtils.getLogger().debug("state: "+state); WFState wf = states.get(state); MiscUtils.getLogger().debug("wf "+wf); String ret = "None"; if (wf != null){ ret = wf.getName(); } return ret; } public List<WFState> getStates() { return stateList; } public int addToWorkFlow(String providerNo, String demographicNo, Date endDate){ WorkFlowState wfs = new WorkFlowState(); return wfs.addToWorkFlow(WorkFlowState.RHWORKFLOW,providerNo,demographicNo,endDate,WorkFlowState.INIT_STATE); } public WorkFlowInfo executeRules(Hashtable hashtable) { WorkFlowInfo wfi = new WorkFlowInfo(hashtable); WorkFlowDS wfDS = WorkFlowDSFactory.getWorkFlowDS("Rh_workflow.drl"); try{ wfi = wfDS.getMessages(wfi); }catch(Exception e){ MiscUtils.getLogger().error("Error", e); } return wfi; } public WorkFlowInfo executeRules(WorkFlowDS wfDS,Hashtable hashtable) { WorkFlowInfo wfi = new WorkFlowInfo(hashtable); try{ wfi = wfDS.getMessages(wfi); }catch(Exception e){ MiscUtils.getLogger().error("Error", e); } return wfi; } public WorkFlowDS getWorkFlowDS(){ return WorkFlowDSFactory.getWorkFlowDS("Rh_workflow.drl"); } public String getLink(String demographicNo,String workFlowId){ return "../form/forwardshortcutname.jsp?formname=RH Form&amp;demographic_no="+demographicNo; } }
gpl-2.0