code
stringlengths
5
1.04M
repo_name
stringlengths
7
108
path
stringlengths
6
299
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1.04M
package com.replash; import java.util.Set; public class DefaultCommandExecutor extends AbstractCommandExecutor { private final Set<CommandExecutorPlugin> commandExecutorPlugins; public DefaultCommandExecutor(CommandTextParser commandTextParser, CommandResolver commandResolver) { this(commandTextParser, commandResolver, ServiceLoaderUtils.load(CommandExecutorPlugin.class)); } public DefaultCommandExecutor(CommandTextParser commandTextParser, CommandResolver commandResolver, Set<CommandExecutorPlugin> commandExecutorPlugins) { super(commandResolver, commandTextParser); this.commandExecutorPlugins = commandExecutorPlugins; } @Override protected void executeCommand(CommandContext executionContext) throws ReplashCommandExecutionException { CommandExecutorPlugin matchingPlugin = null; if(!commandExecutorPlugins.isEmpty()) { BasicCommand basicCommand = executionContext.getCommand(); for (CommandExecutorPlugin commandExecutorPlugin : commandExecutorPlugins) { if(commandExecutorPlugin.canExecute(basicCommand)) { if(matchingPlugin != null) { throw new AmbiguousCommandExecutorPluginException(); } matchingPlugin = commandExecutorPlugin; } } } try { Console.setConsoleAdapter(executionContext.getRuntime().getConsoleAdapter()); if(matchingPlugin != null) { delegateToPlugin(executionContext, matchingPlugin); } else { executeCommandInternal(executionContext); } } catch (Exception e) { throw new ReplashCommandExecutionException(executionContext, e); } finally { Console.setConsoleAdapter(null); } } protected void executeCommandInternal(CommandContext commandContext) throws Exception { commandContext.getCommand().execute(commandContext); } protected void delegateToPlugin(CommandContext executionContext, CommandExecutorPlugin commandExecutorPlugin) throws Exception { commandExecutorPlugin.execute(executionContext); } }
replash/replash
core/src/main/java/com/replash/DefaultCommandExecutor.java
Java
apache-2.0
2,268
/* * 3D City Database - The Open Source CityGML Database * https://www.3dcitydb.org/ * * Copyright 2013 - 2021 * Chair of Geoinformatics * Technical University of Munich, Germany * https://www.lrg.tum.de/gis/ * * The 3D City Database is jointly developed with the following * cooperation partners: * * Virtual City Systems, Berlin <https://vc.systems/> * M.O.S.S. Computer Grafik Systeme GmbH, Taufkirchen <http://www.moss.de/> * * 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.citydb.config.project.database; public enum DatabaseSrsType { PROJECTED("Projected"), GEOGRAPHIC2D("Geographic2D"), GEOCENTRIC("Geocentric"), VERTICAL("Vertical"), ENGINEERING("Engineering"), COMPOUND("Compound"), GEOGENTRIC("Geogentric"), GEOGRAPHIC3D("Geographic3D"), UNKNOWN("n/a"); private final String value; DatabaseSrsType(String v) { value = v; } public String value() { return value; } public String toString() { return value; } }
3dcitydb/importer-exporter
impexp-config/src/main/java/org/citydb/config/project/database/DatabaseSrsType.java
Java
apache-2.0
1,548
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.greengrass.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * Connectivity information. * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/UpdateConnectivityInfo" target="_top">AWS * API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UpdateConnectivityInfoRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** A list of connectivity info. */ private java.util.List<ConnectivityInfo> connectivityInfo; /** The thing name. */ private String thingName; /** * A list of connectivity info. * * @return A list of connectivity info. */ public java.util.List<ConnectivityInfo> getConnectivityInfo() { return connectivityInfo; } /** * A list of connectivity info. * * @param connectivityInfo * A list of connectivity info. */ public void setConnectivityInfo(java.util.Collection<ConnectivityInfo> connectivityInfo) { if (connectivityInfo == null) { this.connectivityInfo = null; return; } this.connectivityInfo = new java.util.ArrayList<ConnectivityInfo>(connectivityInfo); } /** * A list of connectivity info. * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setConnectivityInfo(java.util.Collection)} or {@link #withConnectivityInfo(java.util.Collection)} if you * want to override the existing values. * </p> * * @param connectivityInfo * A list of connectivity info. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateConnectivityInfoRequest withConnectivityInfo(ConnectivityInfo... connectivityInfo) { if (this.connectivityInfo == null) { setConnectivityInfo(new java.util.ArrayList<ConnectivityInfo>(connectivityInfo.length)); } for (ConnectivityInfo ele : connectivityInfo) { this.connectivityInfo.add(ele); } return this; } /** * A list of connectivity info. * * @param connectivityInfo * A list of connectivity info. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateConnectivityInfoRequest withConnectivityInfo(java.util.Collection<ConnectivityInfo> connectivityInfo) { setConnectivityInfo(connectivityInfo); return this; } /** * The thing name. * * @param thingName * The thing name. */ public void setThingName(String thingName) { this.thingName = thingName; } /** * The thing name. * * @return The thing name. */ public String getThingName() { return this.thingName; } /** * The thing name. * * @param thingName * The thing name. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateConnectivityInfoRequest withThingName(String thingName) { setThingName(thingName); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getConnectivityInfo() != null) sb.append("ConnectivityInfo: ").append(getConnectivityInfo()).append(","); if (getThingName() != null) sb.append("ThingName: ").append(getThingName()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof UpdateConnectivityInfoRequest == false) return false; UpdateConnectivityInfoRequest other = (UpdateConnectivityInfoRequest) obj; if (other.getConnectivityInfo() == null ^ this.getConnectivityInfo() == null) return false; if (other.getConnectivityInfo() != null && other.getConnectivityInfo().equals(this.getConnectivityInfo()) == false) return false; if (other.getThingName() == null ^ this.getThingName() == null) return false; if (other.getThingName() != null && other.getThingName().equals(this.getThingName()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getConnectivityInfo() == null) ? 0 : getConnectivityInfo().hashCode()); hashCode = prime * hashCode + ((getThingName() == null) ? 0 : getThingName().hashCode()); return hashCode; } @Override public UpdateConnectivityInfoRequest clone() { return (UpdateConnectivityInfoRequest) super.clone(); } }
aws/aws-sdk-java
aws-java-sdk-greengrass/src/main/java/com/amazonaws/services/greengrass/model/UpdateConnectivityInfoRequest.java
Java
apache-2.0
5,978
package br.usp.each.saeg.code.forest.metaphor.assembler; import java.util.*; import javax.media.j3d.*; import javax.vecmath.*; import br.usp.each.saeg.code.forest.metaphor.*; import br.usp.each.saeg.code.forest.metaphor.Leaf; import br.usp.each.saeg.code.forest.metaphor.data.*; public class LeafAssembler { public static final float OUTSIDE = 1; private final Random random = new Random(); private List<Leaf> leaves = new ArrayList<Leaf>(); public LeafAssembler(LeafDistribution distr, Vector3d position, Trunk trunk, List<LeafData> data, Branch branch, ForestRestrictions restrictions) { Vector3d previous = null; for (int i = 0; i < data.size(); i++) { Transform3D tr = new Transform3D(); int leafSignal = 1; int angle; Vector3d translation; if (up(i)) { leafSignal = 1; if (left(branch.getSignal())) { angle = 30; } else { angle = 330; } tr.rotZ(Math.toRadians(angle)); tr.rotZ(Math.toRadians(angle + (random.nextBoolean() ? random.nextInt(10) : -random.nextInt(10)))); previous = translation = new Vector3d(position.getX() - (branch.getSignal() * (distr.getSize() / 2)) + (branch.getSignal() * distr.getOffset()) + branch.getSignal() * ((distr.getDistance()) * i), position.getY() + leafSignal * (trunk.getRadius() / 2), position.getZ()); } else { leafSignal = -1; if (left(branch.getSignal())) { angle = 130; } else { angle = 220; } translation = previous; tr.rotZ(Math.toRadians(angle)); tr.rotZ(Math.toRadians(angle +(random.nextBoolean() ? random.nextInt(10) : -random.nextInt(10)))); previous.setY(position.getY() + leafSignal * (trunk.getRadius() / 2) * OUTSIDE); } tr.setTranslation(translation); Leaf leaf = new Leaf(branch, trunk.getRadius(), data.get(i), restrictions, tr); leaves.add(leaf); } } public List<Leaf> getLeaves() { return leaves; } private boolean up(int i) { return i % 2 == 0; } private boolean left(int i) { return i < 0; } }
saeg/code-forest
code-forest-standalone/src/br/usp/each/saeg/code/forest/metaphor/assembler/LeafAssembler.java
Java
apache-2.0
2,472
/* * Copyright 2015-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.lastaflute.core.smartdeploy; import java.util.List; import org.lastaflute.core.smartdeploy.coins.CreatorPackageProvider; import org.lastaflute.core.smartdeploy.coins.CreatorStateChecker; import org.lastaflute.core.smartdeploy.exception.RepositoryExtendsActionException; import org.lastaflute.core.smartdeploy.exception.RepositoryWebReferenceException; import org.lastaflute.di.core.ComponentDef; import org.lastaflute.di.core.creator.RepositoryCreator; import org.lastaflute.di.naming.NamingConvention; /** * @author jflute * @since 0.8.3 (2020/07/01) */ public class RomanticRepositoryCreator extends RepositoryCreator { // =================================================================================== // Attribute // ========= protected final List<String> webPackagePrefixList; // not null, for check, e.g. 'org.docksidestage.app.web.' protected final CreatorPackageProvider packageProvider = new CreatorPackageProvider(); protected final CreatorStateChecker stateChecker = createCreatorStateChecker(); protected CreatorStateChecker createCreatorStateChecker() { return new CreatorStateChecker(); } // =================================================================================== // Constructor // =========== public RomanticRepositoryCreator(NamingConvention namingConvention) { super(namingConvention); webPackagePrefixList = deriveWebPackageList(namingConvention); } protected List<String> deriveWebPackageList(NamingConvention namingConvention) { return packageProvider.deriveWebPackageList(namingConvention); } // =================================================================================== // Component Def // ============= @Override public ComponentDef createComponentDef(Class<?> componentClass) { final ComponentDef componentDef = prepareComponentDef(componentClass); if (componentDef == null) { return null; } checkExtendsAction(componentDef); checkWebReference(componentDef); return componentDef; } // same as logic protected ComponentDef prepareComponentDef(Class<?> componentClass) { final ComponentDef dispatched = dispatchByEnv(componentClass); if (dispatched != null) { return dispatched; } return super.createComponentDef(componentClass); // null allowed } protected ComponentDef dispatchByEnv(Class<?> componentClass) { if (!ComponentEnvDispatcher.canDispatch(componentClass)) { // check before for performance return null; } final ComponentEnvDispatcher envDispatcher = createEnvDispatcher(); return envDispatcher.dispatch(componentClass); } protected ComponentEnvDispatcher createEnvDispatcher() { return new ComponentEnvDispatcher(getNamingConvention(), getInstanceDef(), getAutoBindingDef(), isExternalBinding(), getCustomizer(), getNameSuffix()); } // =================================================================================== // State Check // =========== protected void checkExtendsAction(ComponentDef componentDef) { stateChecker.checkExtendsAction(componentDef, getNameSuffix(), msg -> { return new RepositoryExtendsActionException(msg); }); } protected void checkWebReference(ComponentDef componentDef) { stateChecker.checkWebReference(componentDef, webPackagePrefixList, getNameSuffix(), msg -> { return new RepositoryWebReferenceException(msg); }); } }
lastaflute/lastaflute
src/main/java/org/lastaflute/core/smartdeploy/RomanticRepositoryCreator.java
Java
apache-2.0
4,839
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.zols.datastore.query; import java.util.List; import java.util.Map; public class AggregatedResults { private List<Map<String,Object>> buckets; private Page<Map<String, Object>> page; public List<Map<String, Object>> getBuckets() { return buckets; } public void setBuckets(List<Map<String, Object>> buckets) { this.buckets = buckets; } public Page<Map<String, Object>> getPage() { return page; } public void setPage(Page<Map<String, Object>> page) { this.page = page; } }
sathishk/zols
zols-datastore/src/main/java/org/zols/datastore/query/AggregatedResults.java
Java
apache-2.0
747
package de.turban.deadlock.tracer.runtime.display.ui.model; import com.google.common.collect.Lists; import de.turban.deadlock.tracer.runtime.IDeadlockDataResolver; import de.turban.deadlock.tracer.runtime.ILockCacheEntry; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; public class UiLock { private final String className; private final IDeadlockDataResolver resolver; private final ILockCacheEntry lockCache; UiLock(IDeadlockDataResolver resolver, ILockCacheEntry lockCache) { Objects.nonNull(resolver); Objects.nonNull(lockCache); this.resolver = resolver; this.lockCache = lockCache; className = getClassName(lockCache); } private String getClassName(ILockCacheEntry lockCache) { String lockClass = lockCache.getLockClass(); if (lockClass.startsWith("java.util.concurrent")) { if (lockCache.getLocationIds().length > 0) { StackTraceElement firstLocation = resolver.getLocationCache().getLocationById(lockCache.getLocationIds()[0]); lockClass = firstLocation.getClassName(); } } int idx = lockClass.lastIndexOf("."); if (idx > 0) { return lockClass.substring(idx + 1, lockClass.length()); } else { return lockClass; } } public List<UiLock> getDependentLocks() { List<UiLock> locks = Lists.newArrayList(); for (int id : getLockCache().getDependentLocks()) { ILockCacheEntry l = resolver.getLockCache().getLockById(id); locks.add(new UiLock(resolver, l)); } return locks; } public List<UiLock> getPossibleDeadLockWithLocks() { List<UiLock> locks = Lists.newArrayList(); for (int id : getLockCache().getDependentLocks()) { ILockCacheEntry l = resolver.getLockCache().getLockById(id); if (l.hasDependentLock(getLockCache().getId())) { locks.add(new UiLock(resolver, l)); } } return locks; } public ObservableList<String> getLocations() { List<String> list = Arrays .stream(lockCache.getLocationIds()) .mapToObj(id -> resolver.getLocationCache().getLocationById(id).toString()) .collect(Collectors.toList()); return FXCollections.observableList(list); } public ObservableList<String> getThreads() { List<String> list = Arrays .stream(lockCache.getThreadIds()) .mapToObj(id -> resolver.getThreadCache().getThreadDescriptionById(id)) .collect(Collectors.toList()); return FXCollections.observableList(list); } public ILockCacheEntry getLockCache() { return lockCache; } @Override public String toString() { return className + " (id: " + lockCache.getId() + ")"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UiLock uiLock = (UiLock) o; if (!resolver.equals(uiLock.resolver)) { return false; } return lockCache.equals(uiLock.lockCache); } @Override public int hashCode() { int result = resolver.hashCode(); result = 31 * result + lockCache.hashCode(); return result; } public IDeadlockDataResolver getResolver() { return resolver; } }
AndreasTu/jctrace
subprojects/jctrace-ui/src/main/java/de/turban/deadlock/tracer/runtime/display/ui/model/UiLock.java
Java
apache-2.0
3,626
package main.commonmethods; /** * Always override toString * * Weather or not you decide to specify the format, you should clearly document your intentions. * If you specify the format, you should do so precisely. For example, toString method to go with the PhoneNumber class. * @see PhoneNumber toString * If you decide not to specify a format, the docuementation comment should read something like this: * @see ToString toString * * Provide programmatic access to all of the information contained in the value returned by toString. * * Created by root on 6/21/16. */ public class ToString { /** * Returns a brief description of this potion. The exact details of the representation are unspecified and subject * to change, but the following may be regarded as typical: * * "[Potion #9: type=love, smell=turpentine, look=india ink]" * @return string representation */ @Override public String toString() { // ... return super.toString(); } }
michaelwong95/effectivejava
src/main/commonmethods/ToString.java
Java
apache-2.0
1,019
package com.emistoolbox.server.renderer.pdfreport.impl; import com.emistoolbox.common.renderer.pdfreport.EmisPdfReportConfig; import com.emistoolbox.common.renderer.pdfreport.PdfReportConfig; import com.emistoolbox.server.renderer.pdfreport.EmisPageGroup; import com.emistoolbox.server.renderer.pdfreport.EmisPdfPage; import com.emistoolbox.server.renderer.pdfreport.PdfPage; import com.emistoolbox.server.renderer.pdfreport.PdfReport; import java.util.ArrayList; import java.util.List; public class PdfReportImpl implements PdfReport { private EmisPdfReportConfig reportConfig; private List<EmisPdfPage> pages = new ArrayList<EmisPdfPage>(); private EmisPageGroup group = new PageGroupImpl(); public void addPage(EmisPdfPage page) { this.pages.add(page); } public List<EmisPdfPage> getPages() { return this.pages; } public int getPageCount() { return pages.size(); } public EmisPdfReportConfig getReportConfig() { return this.reportConfig; } public void setReportConfig(EmisPdfReportConfig reportConfig) { this.reportConfig = reportConfig; } @Override public EmisPageGroup getPageGroup() { return group; } @Override public void setPageGroup(EmisPageGroup group) { this.group = group; } }
emistoolbox/emistoolbox
core/src/com/emistoolbox/server/renderer/pdfreport/impl/PdfReportImpl.java
Java
apache-2.0
1,305
/* * Copyright 2015 Coastal and Marine Research Centre (CMRC), Beaufort, * Environmental Research Institute (ERI), University College Cork (UCC). * Yassine Lassoued <y.lassoued@gmail.com, y.lassoued@ucc.ie>. * * 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 ie.cmrc.smtx.etl.ext; import ie.cmrc.smtx.skos.model.SKOS; /** * A generic interface for data extractors. This interface is independent from the * data format and structure. * @author Yassine Lassoued */ public interface Extractor { /** * Loads the content of the extractor into a {@link ie.cmrc.skos.core.SKOS} * @param thesaurus {@link ie.cmrc.skos.core.SKOS} to load data into * @param inferInverseProperties If {@code true} the extractor will * infer all inverse object properties * @param inferSuperProperties If {@code true} the extractor will * infer all super object properties * @param inferTransitiveClosure If {@code true} the extractor will infer the * transitive closure of transitive relationships * @param incrementalSync If {@code true} the extractor will synchronise * the thesaurus every so often. This is useful for persistent thesauri. Using * incremental synchronisation on in memory thesauri will have no effect. * @return {@code true} if the extraction was successful, {@code false} otherwise */ public boolean extractDataToThesaurus(SKOS thesaurus, boolean inferInverseProperties, boolean inferSuperProperties, boolean inferTransitiveClosure, boolean incrementalSync); }
beaufort/semantix
semantix-etl/src/main/java/ie/cmrc/smtx/etl/ext/Extractor.java
Java
apache-2.0
2,059
package com.evolveum.midpoint.web.page.forgetpassword.dto; import java.io.Serializable; public class QuestionDTO implements Serializable { private String questionItself; private String answerOftheUser; public QuestionDTO(String question,String answer){ setAnswerOftheUser(answer); setQuestionItself(question); } private String getQuestionItself() { return questionItself; } private void setQuestionItself(String questionItself) { this.questionItself = questionItself; } private String getAnswerOftheUser() { return answerOftheUser; } private void setAnswerOftheUser(String answerOftheUser) { this.answerOftheUser = answerOftheUser; } }
arnost-starosta/midpoint
gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/dto/QuestionDTO.java
Java
apache-2.0
666
package crawler; public class URStruct { public String URL=""; public float IR=0; public URStruct(String U,float ir) { URL=U; IR=ir; } }
MAnbar/SearchEngine
Crawler/src/crawler/URStruct.java
Java
apache-2.0
200
package org.swtk.commons.dict.wordnet.indexbyid.instance.p0.p5; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.TreeMap; import org.swtk.common.dict.dto.wordnet.IndexNoun; import com.trimc.blogger.commons.utils.GsonUtils; public final class WordnetNounIndexIdInstance0572 { private static Map<String, Collection<IndexNoun>> map = new TreeMap<String, Collection<IndexNoun>>(); static { add("05720023", "{\"term\":\"aesthesis\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05720023\"]}"); add("05720023", "{\"term\":\"esthesis\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05720023\"]}"); add("05720023", "{\"term\":\"sensation\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"05659816\", \"14060962\", \"07530021\", \"09781932\", \"05720023\"]}"); add("05720023", "{\"term\":\"sense datum\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05720023\"]}"); add("05720023", "{\"term\":\"sense experience\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05720023\"]}"); add("05720023", "{\"term\":\"sense impression\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05720023\"]}"); add("05720373", "{\"term\":\"limen\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05720373\"]}"); add("05720373", "{\"term\":\"threshold\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"13926744\", \"03228389\", \"03228735\", \"05720373\", \"15293950\"]}"); add("05720506", "{\"term\":\"absolute threshold\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05720506\"]}"); add("05720645", "{\"term\":\"pain threshold\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05720645\"]}"); add("05720839", "{\"term\":\"difference limen\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05720839\"]}"); add("05720839", "{\"term\":\"difference threshold\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05720839\"]}"); add("05720839", "{\"term\":\"differential limen\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05720839\"]}"); add("05720839", "{\"term\":\"differential threshold\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05720839\"]}"); add("05721048", "{\"term\":\"jnd\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05721048\"]}"); add("05721048", "{\"term\":\"just-noticeable difference\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05721048\"]}"); add("05721294", "{\"term\":\"masking\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"03730689\", \"05721294\", \"01051609\"]}"); add("05721471", "{\"term\":\"vision\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"07303190\", \"05633248\", \"05721471\", \"05662207\", \"05776249\"]}"); add("05721471", "{\"term\":\"visual sensation\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05721471\"]}"); add("05721684", "{\"term\":\"odor\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05721684\", \"04987257\"]}"); add("05721684", "{\"term\":\"odour\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"04987257\", \"05721684\"]}"); add("05721684", "{\"term\":\"olfactory perception\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05721684\"]}"); add("05721684", "{\"term\":\"olfactory sensation\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05721684\"]}"); add("05721684", "{\"term\":\"smell\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"00884639\", \"05666448\", \"14549784\", \"04987257\", \"05721684\"]}"); add("05722108", "{\"term\":\"scent\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"04987257\", \"05722108\", \"05722413\"]}"); add("05722279", "{\"term\":\"musk\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05722279\", \"14870816\"]}"); add("05722413", "{\"term\":\"aroma\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05722413\", \"04987257\"]}"); add("05722413", "{\"term\":\"fragrance\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"04987712\", \"05722413\"]}"); add("05722413", "{\"term\":\"perfume\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"03922150\", \"05722413\"]}"); add("05722413", "{\"term\":\"scent\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"04987257\", \"05722108\", \"05722413\"]}"); add("05722692", "{\"term\":\"incense\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05722692\", \"14943145\"]}"); add("05722841", "{\"term\":\"fetor\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05722841\"]}"); add("05722841", "{\"term\":\"foetor\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05722841\"]}"); add("05722841", "{\"term\":\"malodor\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05722841\"]}"); add("05722841", "{\"term\":\"malodour\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05722841\"]}"); add("05722841", "{\"term\":\"mephitis\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"02448645\", \"05722841\", \"15060542\"]}"); add("05722841", "{\"term\":\"reek\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05722841\"]}"); add("05722841", "{\"term\":\"stench\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05722841\"]}"); add("05722841", "{\"term\":\"stink\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05722841\"]}"); add("05723097", "{\"term\":\"niff\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05723097\"]}"); add("05723097", "{\"term\":\"pong\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05723097\"]}"); add("05723230", "{\"term\":\"gustatory perception\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05723230\"]}"); add("05723230", "{\"term\":\"gustatory sensation\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05723230\"]}"); add("05723230", "{\"term\":\"taste\", \"synsetCount\":7, \"upperType\":\"NOUN\", \"ids\":[\"00884380\", \"05666071\", \"07594444\", \"07302729\", \"05757616\", \"07513449\", \"05723230\"]}"); add("05723230", "{\"term\":\"taste perception\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05723230\"]}"); add("05723230", "{\"term\":\"taste sensation\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05723230\"]}"); add("05723811", "{\"term\":\"flavor\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"05852809\", \"05723811\", \"14549784\"]}"); add("05723811", "{\"term\":\"flavour\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"05723811\", \"05852809\", \"14549784\"]}"); add("05723811", "{\"term\":\"nip\", \"synsetCount\":6, \"upperType\":\"NOUN\", \"ids\":[\"00843942\", \"05000286\", \"05022862\", \"05723811\", \"09738048\", \"13795390\"]}"); add("05723811", "{\"term\":\"relish\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"05723811\", \"07598006\", \"07507121\"]}"); add("05723811", "{\"term\":\"sapidity\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05003278\", \"05723811\"]}"); add("05723811", "{\"term\":\"savor\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05723811\"]}"); add("05723811", "{\"term\":\"savour\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05723811\"]}"); add("05723811", "{\"term\":\"smack\", \"synsetCount\":6, \"upperType\":\"NOUN\", \"ids\":[\"00134488\", \"00139419\", \"02840630\", \"04251975\", \"05723811\", \"07425345\"]}"); add("05723811", "{\"term\":\"tang\", \"synsetCount\":7, \"upperType\":\"NOUN\", \"ids\":[\"01406236\", \"01406354\", \"01407748\", \"01407891\", \"05723811\", \"08175819\", \"05000286\"]}"); add("05724289", "{\"term\":\"lemon\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"03661164\", \"05724289\", \"12732356\", \"04973720\", \"07765558\"]}"); add("05724409", "{\"term\":\"vanilla\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"05724409\", \"07844783\", \"12107056\"]}"); add("05724524", "{\"term\":\"sugariness\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05001905\", \"05724524\"]}"); add("05724524", "{\"term\":\"sweet\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"05001591\", \"05724524\", \"07612255\", \"07625449\", \"11346725\"]}"); add("05724524", "{\"term\":\"sweetness\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"04785869\", \"04987712\", \"05001591\", \"05724524\"]}"); add("05724691", "{\"term\":\"sour\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"05001060\", \"05724691\", \"07934268\"]}"); add("05724691", "{\"term\":\"sourness\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"04649414\", \"05001060\", \"05724691\"]}"); add("05724691", "{\"term\":\"tartness\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"04650754\", \"05001304\", \"05724691\"]}"); add("05724908", "{\"term\":\"acidity\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"05046680\", \"05724908\", \"05001060\"]}"); add("05724908", "{\"term\":\"acidulousness\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05724908\"]}"); add("05725062", "{\"term\":\"bitter\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"05002002\", \"05725062\", \"07905789\"]}"); add("05725062", "{\"term\":\"bitterness\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"05002002\", \"05725062\", \"04650754\", \"07564444\"]}"); add("05725213", "{\"term\":\"acridity\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"04787507\", \"05002278\", \"05725213\"]}"); add("05725289", "{\"term\":\"salinity\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05000782\", \"05725289\"]}"); add("05725289", "{\"term\":\"salt\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"05725289\", \"07164290\", \"07829083\", \"15035270\"]}"); add("05725289", "{\"term\":\"saltiness\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"05000591\", \"05725289\", \"07086878\"]}"); add("05725496", "{\"term\":\"astringence\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05725496\"]}"); add("05725496", "{\"term\":\"astringency\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05209302\", \"05725496\"]}"); add("05725694", "{\"term\":\"finish\", \"synsetCount\":9, \"upperType\":\"NOUN\", \"ids\":[\"00211367\", \"05725694\", \"07306035\", \"07347762\", \"07367976\", \"08585406\", \"14483408\", \"15292365\", \"04707990\"]}"); add("05725900", "{\"term\":\"flatness\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"04643310\", \"04963287\", \"05725900\", \"07083787\", \"05070518\"]}"); add("05726065", "{\"term\":\"mellowness\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"04663805\", \"04965479\", \"04996251\", \"05726065\", \"07569690\"]}"); add("05726201", "{\"term\":\"auditory sensation\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05726201\"]}"); add("05726201", "{\"term\":\"sound\", \"synsetCount\":8, \"upperType\":\"NOUN\", \"ids\":[\"09463090\", \"09469019\", \"07125755\", \"06288789\", \"07385893\", \"11501330\", \"05726201\", \"04988388\"]}"); add("05726503", "{\"term\":\"euphony\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05726503\"]}"); add("05726503", "{\"term\":\"music\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"01165019\", \"05726882\", \"00544270\", \"05726503\", \"07034009\"]}"); add("05726882", "{\"term\":\"music\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"01165019\", \"05726882\", \"00544270\", \"05726503\", \"07034009\"]}"); add("05727272", "{\"term\":\"piano music\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05727272\", \"06828479\"]}"); add("05727413", "{\"term\":\"music of the spheres\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05727413\"]}"); add("05727552", "{\"term\":\"pure tone\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05727552\"]}"); add("05727552", "{\"term\":\"tone\", \"synsetCount\":10, \"upperType\":\"NOUN\", \"ids\":[\"05218719\", \"06872106\", \"14568274\", \"05727552\", \"06878395\", \"04966407\", \"14549784\", \"04994869\", \"04994132\", \"07096765\"]}"); add("05727751", "{\"term\":\"harmonic\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"04995327\", \"05727751\"]}"); add("05727905", "{\"term\":\"first harmonic\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05727905\"]}"); add("05727905", "{\"term\":\"fundamental\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05727905\", \"07342658\"]}"); add("05727905", "{\"term\":\"fundamental frequency\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05727905\"]}"); add("05728040", "{\"term\":\"overtone\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05728040\", \"06618817\"]}"); add("05728040", "{\"term\":\"partial\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05728040\", \"06024402\"]}"); add("05728040", "{\"term\":\"partial tone\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05728040\"]}"); add("05728195", "{\"term\":\"dissonance\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"04991763\", \"05728195\", \"14005842\"]}"); add("05728195", "{\"term\":\"noise\", \"synsetCount\":6, \"upperType\":\"NOUN\", \"ids\":[\"04778571\", \"04830262\", \"07137438\", \"07444811\", \"05728195\", \"07402109\"]}"); add("05728195", "{\"term\":\"racket\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"04045857\", \"05728195\", \"00777440\", \"07405545\"]}"); add("05728468", "{\"term\":\"dub\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05728468\"]}"); add("05728549", "{\"term\":\"synaesthesia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05728549\"]}"); add("05728549", "{\"term\":\"synesthesia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05728549\"]}"); add("05728773", "{\"term\":\"chromaesthesia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05728773\"]}"); add("05728773", "{\"term\":\"chromesthesia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05728773\"]}"); add("05728966", "{\"term\":\"colored audition\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05728966\"]}"); add("05728966", "{\"term\":\"colored hearing\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05728966\"]}"); add("05729127", "{\"term\":\"somaesthesia\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05667701\", \"05729127\"]}"); add("05729127", "{\"term\":\"somatesthesia\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05667701\", \"05729127\"]}"); add("05729127", "{\"term\":\"somatic sensation\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05729127\"]}"); add("05729127", "{\"term\":\"somesthesia\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05667701\", \"05729127\"]}"); add("05729447", "{\"term\":\"feeling\", \"synsetCount\":6, \"upperType\":\"NOUN\", \"ids\":[\"05715665\", \"05730374\", \"05729447\", \"14549784\", \"05925333\", \"00026390\"]}"); add("05729675", "{\"term\":\"constriction\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"01152406\", \"05729675\", \"07328118\", \"13936007\"]}"); add("05729675", "{\"term\":\"tightness\", \"synsetCount\":5, \"upperType\":\"NOUN\", \"ids\":[\"04784179\", \"04840918\", \"05096011\", \"05729675\", \"14474006\"]}"); add("05729937", "{\"term\":\"skin perceptiveness\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05729937\"]}"); add("05729937", "{\"term\":\"tactility\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05729937\"]}"); add("05729937", "{\"term\":\"tactual sensation\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05729937\", \"05730374\"]}"); add("05729937", "{\"term\":\"touch perception\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05729937\"]}"); } private static void add(final String ID, final String JSON) { IndexNoun indexNoun = GsonUtils.toObject(JSON, IndexNoun.class); Collection<IndexNoun> list = (map.containsKey(ID)) ? map.get(ID) : new ArrayList<IndexNoun>(); list.add(indexNoun); map.put(ID, list); } public static Collection<IndexNoun> get(final String TERM) { return map.get(TERM); } public static boolean has(final String TERM) { return map.containsKey(TERM); } public static Collection<String> ids() { return map.keySet(); } }
torrances/swtk-commons
commons-dict-wordnet-indexbyid/src/main/java/org/swtk/commons/dict/wordnet/indexbyid/instance/p0/p5/WordnetNounIndexIdInstance0572.java
Java
apache-2.0
16,164
package org.jenkinsci.plugins.os_ci.model; import hudson.EnvVars; import hudson.Extension; import hudson.model.Describable; import hudson.model.Descriptor; import hudson.model.Hudson; import hudson.util.FormValidation; import org.jenkinsci.plugins.os_ci.repohandlers.OpenStackClient; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Copyright 2015 Cisco Systems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class OpenstackParameters implements Describable<OpenstackParameters> { // basic private final String openstackIP; // advanced private final String openstackTenant; private final String openstackPassword; private final String openstackUser; private final String nameservers; private final String privateNetworkID; private final String privateSubnetID; private final String keyPair; private final Map <String,String > additionalParams; private final PolicyParameters policyParameters; @DataBoundConstructor public OpenstackParameters(String openstackIP, String openstackTenant, String openstackPassword, String openstackUser, String privateNetworkID, String privateSubnetID, String keyPair, List<Entry> additionalParams,PolicyParameters policyParameters, String nameservers) { this.openstackIP = openstackIP; this.openstackTenant = openstackTenant; this.openstackPassword = openstackPassword; this.openstackUser = openstackUser; this.privateNetworkID = privateNetworkID; this.privateSubnetID = privateSubnetID; this.keyPair = keyPair; this.additionalParams = toMap(additionalParams); this.policyParameters = policyParameters; this.nameservers = nameservers; } public Map <String, String> getAdditionalParams() { return additionalParams; } public PolicyParameters getPolicyParameters() { return policyParameters; } @Override public String toString() { return "OpenstackParameters{" + "openstackIP='" + openstackIP + '\'' + ", openstackTenant='" + openstackTenant + '\'' + ", openstackPassword='" + openstackPassword + '\'' + ", openstackUser='" + openstackUser + '\'' + ", NameServers='" + nameservers + '\'' + ", privateNetworkID='" + privateNetworkID + '\'' + ", privateSubnetID='" + privateSubnetID + '\'' + ", keyPair='" + keyPair + '\'' + ", additionalParams=" + additionalParams + '}'; } public String getOpenstackIP() { return openstackIP; } public String getOpenstackTenant() { return openstackTenant; } public String getOpenstackPassword() { return openstackPassword; } public String getOpenstackUser() { return openstackUser; } public String getNameservers() { return nameservers; } public String getPrivateNetworkID() { return privateNetworkID; } public String getPrivateSubnetID() { return privateSubnetID; } public String getKeyPair() { return keyPair; } public Descriptor<OpenstackParameters> getDescriptor() { return Hudson.getInstance().getDescriptor(getClass()); } @Extension public static class DescriptorImpl extends Descriptor<OpenstackParameters> { @Override public String getDisplayName() { return "Openstack Parameters:"; } public FormValidation doTestOpenstackConnection(@QueryParameter("openstackIP") final String openstackIP, @QueryParameter("openstackUser") final String openstackUser, @QueryParameter("openstackPassword") final String openstackPassword, @QueryParameter("openstackTenant") final String openstackTenant) { try { OpenStackClient openStackClient = new OpenStackClient(null, openstackUser, openstackPassword, openstackTenant,"/v2.0/tokens",openstackIP,5000); load(); return FormValidation.ok("Success"); } catch (Exception e) { return FormValidation.error("Please check your Openstack credentials"); } } } public static class Entry { public String key, value; @DataBoundConstructor public Entry(String key, String value) { this.key = key; this.value = value; } } private static EnvVars toMap(List<Entry> entries) { EnvVars map = new EnvVars(); if (entries!=null) for (Entry entry: entries) map.put(entry.key,entry.value); return map; } }
foundation-runtime/jenkins-openstack-deployment-plugin
src/main/java/org/jenkinsci/plugins/os_ci/model/OpenstackParameters.java
Java
apache-2.0
5,533
package knoma.newsgroup; import knoma.newsgroup.experiments.RunnableExperiment; import knoma.newsgroup.util.CompressionUtil; import org.apache.commons.cli.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jboss.weld.environment.se.bindings.Parameters; import org.jboss.weld.environment.se.events.ContainerInitialized; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Observes; import javax.enterprise.inject.Any; import javax.enterprise.inject.Instance; import javax.inject.Inject; import java.io.File; import java.util.HashMap; import java.util.List; import static java.lang.System.getProperty; import static knoma.newsgroup.experiments.ExperimentLiteral.experimentType; /** * Created by gabriel on 01/11/15. */ @ApplicationScoped public class ApplicationStarter { private static final Logger logger = LogManager.getLogger(ApplicationStarter.class.getName()); @Inject @Any private Instance<RunnableExperiment> experiments; @Inject private Options cliOptions; @Inject private ConfigurationsProducer configurations; @Inject private DatasetDownloader downloader; @Inject private CompressionUtil compressionUtil; public void bootListener(@Observes ContainerInitialized event, @Parameters List<String> cmdLineArgs) throws Exception { CommandLineParser parser = new DefaultParser(); CommandLine commandLine = parser.parse(cliOptions, cmdLineArgs.toArray(new String[cmdLineArgs.size()])); if (commandLine.hasOption("--help") || !(commandLine.hasOption("dataset-dir") || commandLine.hasOption("download-dataset"))) { printHelp(); return; } if (commandLine.hasOption("dataset-dir")) { logger.info("Using dataset in {} dir", commandLine.getOptionValue("dataset-dir")); configurations.setDatasetDir(commandLine.getOptionValue("dataset-dir")); } if (commandLine.hasOption("download-dataset")) { String datasetFile = downloader.download(configurations.datasetUrl(), "20news-19997.tar.gz", getProperty("java.io.tmpdir"), false); logger.info("Extracting dataset {}", datasetFile); File uncompressedDir = compressionUtil.untar(new File(datasetFile), new File(new File(datasetFile).getParent())); configurations.setDatasetDir(uncompressedDir.getAbsolutePath()); } String stopwordsFile = downloader.download(configurations.stopWordsUrl(), "common-english-words.txt", getProperty("java.io.tmpdir"), true); configurations.setStopWordsFile(stopwordsFile); HashMap<String, String> configuration = new HashMap<>(); Option[] options = commandLine.getOptions(); for (Option option : options) { configuration.put(option.getLongOpt(), option.getValue()); } String experiment = configuration.keySet() .stream() .filter(parameter -> parameter.endsWith("-experiment")) .findFirst() .map(parameter -> parameter.replace("-experiment", "")) .orElse(null); if (experiment == null) { logger.error("Cannot find experiment"); printHelp(); return; } RunnableExperiment runnableExperiment = experiments.select(experimentType(experiment)).get(); if (runnableExperiment == null) { logger.info("No experiment found with name {}", experiment); printHelp(); return; } runnableExperiment.run(configuration); } private void printHelp() { HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(130); formatter.printHelp("20newsgroup [Options]", cliOptions); } }
gabriel-ozeas/ml-newsgroups-prediction
src/main/java/knoma/newsgroup/ApplicationStarter.java
Java
apache-2.0
3,867
/*** Copyright (c) 2016 CommonsWare, LLC 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.commonsware.cwac.netsecurity.test.pub.hurl; import android.os.Build; import com.commonsware.cwac.netsecurity.TrustManagerBuilder; public class UseDefaultTest extends SimpleHTTPSTest { @Override protected TrustManagerBuilder getBuilder() throws Exception { return(new TrustManagerBuilder().useDefault()); } // on N+, fail because of manifest config @Override protected boolean isPositiveTest() { return(Build.VERSION.SDK_INT<Build.VERSION_CODES.N); } }
commonsguy/cwac-netsecurity
netsecurity/src/androidTest/java/com/commonsware/cwac/netsecurity/test/pub/hurl/UseDefaultTest.java
Java
apache-2.0
1,062
/** * Copyright (c), Data Geekery GmbH, contact@datageekery.com * * 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.jooq.lambda.fi.util.function; import java.util.function.Consumer; import java.util.function.LongUnaryOperator; import org.jooq.lambda.Sneaky; import org.jooq.lambda.Unchecked; /** * A {@link LongUnaryOperator} that allows for checked exceptions. * * @author Lukas Eder */ @FunctionalInterface public interface CheckedLongUnaryOperator { /** * Applies this operator to the given operand. * * @param operand the operand * @return the operator result */ long applyAsLong(long operand) throws Throwable; /** * @see {@link Sneaky#longUnaryOperator(CheckedLongUnaryOperator)} */ static LongUnaryOperator sneaky(CheckedLongUnaryOperator operator) { return Sneaky.longUnaryOperator(operator); } /** * @see {@link Unchecked#longUnaryOperator(CheckedLongUnaryOperator)} */ static LongUnaryOperator unchecked(CheckedLongUnaryOperator operator) { return Unchecked.longUnaryOperator(operator); } /** * @see {@link Unchecked#longUnaryOperator(CheckedLongUnaryOperator, Consumer)} */ static LongUnaryOperator unchecked(CheckedLongUnaryOperator operator, Consumer<Throwable> handler) { return Unchecked.longUnaryOperator(operator, handler); } }
jOOQ/jOOL
jOOL-java-8/src/main/java/org/jooq/lambda/fi/util/function/CheckedLongUnaryOperator.java
Java
apache-2.0
1,903
/** * Copyright 2005 Cordys R&D B.V. * * This file is part of the Cordys File Connector. * * 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.cordys.coe.ac.fileconnector.methods; import com.cordys.coe.ac.fileconnector.ApplicationConfiguration; import com.cordys.coe.ac.fileconnector.IFileConnectorMethod; import com.cordys.coe.ac.fileconnector.ISoapRequestContext; import com.cordys.coe.ac.fileconnector.LogMessages; import com.cordys.coe.ac.fileconnector.exception.ConfigException; import com.cordys.coe.ac.fileconnector.exception.FileException; import com.cordys.coe.ac.fileconnector.utils.GeneralUtils; import com.cordys.coe.ac.fileconnector.utils.XmlUtils; import java.io.File; /** * Implements CreateDirectory SOAP method. * * @author psriniva */ public class CreateDirectoryMethod implements IFileConnectorMethod { /** * Contains the SOAP method name. */ public static final String METHOD_NAME = "CreateDirectory"; /** * New directory name request parameter. */ private static final String PARAM_NEWDIRNAME = "newDirectoryName"; /** * Full path for parent directory parameter. */ private static final String PARAM_PARENTDIRPATH = "parentDirectoryPath"; /** * Contains the FileConnector configuration. */ private ApplicationConfiguration acConfig; /** * @see com.cordys.coe.ac.fileconnector.IFileConnectorMethod#cleanup() */ public void cleanup() throws ConfigException { } /** * @see com.cordys.coe.ac.fileconnector.IFileConnectorMethod#initialize(com.cordys.coe.ac.fileconnector.ApplicationConfiguration) */ public boolean initialize(ApplicationConfiguration acConfig) throws ConfigException { this.acConfig = acConfig; return true; } /** * @see com.cordys.coe.ac.fileconnector.IFileConnectorMethod#onReset() */ public void onReset() { } /** * @see com.cordys.coe.ac.fileconnector.IFileConnectorMethod#process(com.cordys.coe.ac.fileconnector.ISoapRequestContext) */ public EResult process(ISoapRequestContext req) throws FileException { int requestNode = req.getRequestRootNode(); // Get the needed parameters from the SOAP request String sNewDirName = XmlUtils.getStringParameter(requestNode, PARAM_NEWDIRNAME, true); String sParentDirPath = XmlUtils.getStringParameter(requestNode, PARAM_PARENTDIRPATH, true); // Create File objects for the parent and new directory folders File fParentDir = new File(sParentDirPath); // Check if parent directory is listed in the allowed directories if (!acConfig.isFileAllowed(fParentDir)) { throw new FileException(LogMessages.PARENT_DIR_ACCESS_NOT_ALLOWED); } if (!fParentDir.exists()) { throw new FileException(LogMessages.PARENT_DIR_NOT_FOUND); } try { // Get the File which has full file path File fNewFullDir = GeneralUtils.getAbsoluteFile(sNewDirName, fParentDir); // if does not exist create the new directories if (!fNewFullDir.exists()) { fNewFullDir.mkdirs(); } } catch (Exception e) { throw new FileException(e,LogMessages.UNABLE_TO_CREATE_DIR); } return EResult.FINISHED; } /** * @see com.cordys.coe.ac.fileconnector.IFileConnectorMethod#getMethodName() */ public String getMethodName() { return METHOD_NAME; } }
MatthiasEberl/cordysfilecon
src/cws/FileConnector/com-cordys-coe/fileconnector/java/source/com/cordys/coe/ac/fileconnector/methods/CreateDirectoryMethod.java
Java
apache-2.0
4,340
/* * Copyright (C) 2017 Hazuki * * 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 jp.hazuki.yuzubrowser.legacy.utils; import android.content.Context; import android.util.TypedValue; import androidx.annotation.AttrRes; import androidx.annotation.ColorInt; import androidx.core.content.res.ResourcesCompat; public final class ThemeUtils { public static int getIdFromThemeRes(Context context, @AttrRes int id) { TypedValue outValue = new TypedValue(); context.getTheme().resolveAttribute(id, outValue, true); return outValue.resourceId; } @ColorInt public static int getColorFromThemeRes(Context context, @AttrRes int id) { return ResourcesCompat.getColor(context.getResources(), getIdFromThemeRes(context, id), context.getTheme()); } }
hazuki0x0/YuzuBrowser
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/utils/ThemeUtils.java
Java
apache-2.0
1,312
// Copyright 2013 Google Inc. All Rights Reserved. // // 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.google.api.ads.dfp.jaxws.utils.v201403; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import com.google.api.ads.dfp.jaxws.v201403.BooleanValue; import com.google.api.ads.dfp.jaxws.v201403.ColumnType; import com.google.api.ads.dfp.jaxws.v201403.Date; import com.google.api.ads.dfp.jaxws.v201403.DateTime; import com.google.api.ads.dfp.jaxws.v201403.DateTimeValue; import com.google.api.ads.dfp.jaxws.v201403.DateValue; import com.google.api.ads.dfp.jaxws.v201403.NumberValue; import com.google.api.ads.dfp.jaxws.v201403.ResultSet; import com.google.api.ads.dfp.jaxws.v201403.Row; import com.google.api.ads.dfp.jaxws.v201403.TextValue; import com.google.api.ads.dfp.jaxws.v201403.Value; import com.google.common.collect.Lists; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Test for {@link Pql}. * * @author Adam Rogal */ @RunWith(JUnit4.class) public class PqlTest { private static final String TIME_ZONE_ID1 = "Asia/Shanghai"; private ColumnType column1; private ColumnType column2; private ColumnType column3; private TextValue textValue1; private TextValue textValue2; private TextValue textValue3; private BooleanValue booleanValue1; private BooleanValue booleanValue2; private BooleanValue booleanValue3; private NumberValue numberValue1; private NumberValue numberValue2; private NumberValue numberValue3; private DateValue dateValue1; private DateTimeValue dateTimeValue1; private DateTime dateTime1; private Date date1; public PqlTest() {} @Before public void setUp() throws Exception { column1 = new ColumnType(); column1.setLabelName("column1"); column2 = new ColumnType(); column2.setLabelName("column2"); column3 = new ColumnType(); column3.setLabelName("column3"); textValue1 = new TextValue(); textValue1.setValue("value1"); textValue2 = new TextValue(); textValue2.setValue("value2"); textValue3 = new TextValue(); textValue3.setValue("value3"); booleanValue1 = new BooleanValue(); booleanValue1.setValue(false); booleanValue2 = new BooleanValue(); booleanValue2.setValue(true); booleanValue3 = new BooleanValue(); booleanValue3.setValue(false); numberValue1 = new NumberValue(); numberValue1.setValue("1"); numberValue2 = new NumberValue(); numberValue2.setValue("1.02"); numberValue3 = new NumberValue(); numberValue3.setValue("-1"); dateTime1 = new DateTime(); date1 = new Date(); date1.setYear(2012); date1.setMonth(12); date1.setDay(2); dateTime1.setDate(date1); dateTime1.setHour(12); dateTime1.setMinute(45); dateTime1.setSecond(0); dateTime1.setTimeZoneID(TIME_ZONE_ID1); dateTimeValue1 = new DateTimeValue(); dateTimeValue1.setValue(dateTime1); dateValue1 = new DateValue(); dateValue1.setValue(date1); } @Test public void testToString() { assertEquals("value1", Pql.toString(textValue1)); assertEquals("false", Pql.toString(booleanValue1)); assertEquals("1", Pql.toString(numberValue1)); assertEquals("2012-12-02T12:45:00+08:00", Pql.toString(dateTimeValue1)); assertEquals("2012-12-02", Pql.toString(dateValue1)); } @Test public void testToString_null() { assertEquals("", Pql.toString(new TextValue())); assertEquals("", Pql.toString(new BooleanValue())); assertEquals("", Pql.toString(new NumberValue())); assertEquals("", Pql.toString(new DateTimeValue())); assertEquals("", Pql.toString(new DateValue())); } @Test(expected = IllegalArgumentException.class) public void testToString_invalidValue() { Pql.toString(new MyValue()); } @Test public void testGetApiValue() { assertEquals("value1", Pql.getApiValue(textValue1)); assertEquals(false, Pql.getApiValue(booleanValue1)); assertEquals(1L, Pql.getApiValue(numberValue1)); assertEquals(1.02, Pql.getApiValue(numberValue2)); assertEquals(dateTime1, Pql.getApiValue(dateTimeValue1)); assertEquals(date1, Pql.getApiValue(dateValue1)); assertNull(Pql.getApiValue(new TextValue())); } @Test public void testGetNativeValue() { assertEquals("value1", Pql.getNativeValue(textValue1)); assertEquals(false, Pql.getNativeValue(booleanValue1)); assertEquals(1L, Pql.getNativeValue(numberValue1)); assertEquals(1.02, Pql.getNativeValue(numberValue2)); assertEquals(DateTimes.toDateTime(dateTimeValue1.getValue()), Pql.getNativeValue(dateTimeValue1)); assertEquals("2012-12-02", Pql.getNativeValue(dateValue1)); } @Test public void testCreateValue() { assertEquals("value1", ((TextValue) Pql.createValue("value1")).getValue()); assertEquals(false, ((BooleanValue) Pql.createValue(false)).isValue()); assertEquals("1", ((NumberValue) Pql.createValue(1)).getValue()); assertEquals("1", ((NumberValue) Pql.createValue(1L)).getValue()); assertEquals("1.02", ((NumberValue) Pql.createValue(1.02)).getValue()); assertEquals("2012-12-02T12:45:00+08:00", DateTimes.toStringWithTimeZone(((DateTimeValue) Pql.createValue(dateTime1)).getValue())); assertEquals("2012-12-02", DateTimes.toString(((DateValue) Pql.createValue(dateTime1.getDate())).getValue())); } @Test(expected = IllegalArgumentException.class) public void testCreateValue_invalidType() { Pql.createValue(new MyObject()); } @Test public void testCreateValue_null() { assertEquals(null, ((TextValue) Pql.createValue(null)).getValue()); } @Test public void testGetColumnLabels() { ResultSet resultSet = new ResultSet(); resultSet.getColumnTypes().addAll(Lists.newArrayList(column1, column2, column3)); assertEquals( Lists.newArrayList("column1", "column2", "column3"), Pql.getColumnLabels(resultSet)); } @Test public void testGetRowStringValues() { Row row = new Row(); row.getValues().addAll(Lists.newArrayList(textValue1, booleanValue1, numberValue2)); assertEquals(Lists.newArrayList("value1", "false", "1.02"), Pql.getRowStringValues(row)); } @Test public void testCombineResultSet() { Row row1 = new Row(); row1.getValues().addAll(Lists.newArrayList(textValue1, booleanValue1, numberValue1)); Row row2 = new Row(); row2.getValues().addAll(Lists.newArrayList(textValue2, booleanValue2, numberValue2)); Row row3 = new Row(); row3.getValues().addAll(Lists.newArrayList(textValue3, booleanValue3, numberValue3)); ResultSet resultSet1 = new ResultSet(); resultSet1.getColumnTypes().addAll(Lists.newArrayList(column1, column2, column3)); resultSet1.getRows().addAll(Lists.newArrayList(row1, row2)); ResultSet resultSet2 = new ResultSet(); resultSet2.getColumnTypes().addAll(Lists.newArrayList(column1, column2, column3)); resultSet2.getRows().addAll(Lists.newArrayList(row3)); ResultSet combinedResultSet = Pql.combineResultSets(resultSet1, resultSet2); assertEquals(3, combinedResultSet.getRows().size()); assertEquals( Lists.newArrayList(column1, column2, column3), combinedResultSet.getColumnTypes()); assertEquals(Lists.newArrayList(textValue1, booleanValue1, numberValue1), combinedResultSet.getRows().get(0).getValues()); assertEquals(Lists.newArrayList(textValue2, booleanValue2, numberValue2), combinedResultSet.getRows().get(1).getValues()); assertEquals(Lists.newArrayList(textValue3, booleanValue3, numberValue3), combinedResultSet.getRows().get(2).getValues()); } @Test(expected = IllegalArgumentException.class) public void testCombineResultSet_badColumns() { Row row1 = new Row(); row1.getValues().addAll(Lists.newArrayList(textValue1, booleanValue1, numberValue1)); Row row2 = new Row(); row2.getValues().addAll(Lists.newArrayList(textValue2, booleanValue2, numberValue2)); Row row3 = new Row(); row3.getValues().addAll(Lists.newArrayList(textValue3, booleanValue3)); ResultSet resultSet1 = new ResultSet(); resultSet1.getColumnTypes().addAll(Lists.newArrayList(column1, column2, column3)); resultSet1.getRows().addAll(Lists.newArrayList(row1, row2)); ResultSet resultSet2 = new ResultSet(); resultSet2.getColumnTypes().addAll(Lists.newArrayList(column1, column2)); resultSet2.getRows().addAll(Lists.newArrayList(row3)); Pql.combineResultSets(resultSet1, resultSet2); } private static class MyValue extends Value {} private static class MyObject extends Object {} }
nafae/developer
modules/dfp_appengine/src/test/java/com/google/api/ads/dfp/jaxws/utils/v201403/PqlTest.java
Java
apache-2.0
9,205
/* * Copyright 2020 LINE Corporation * * LINE Corporation 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: * * https://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.linecorp.centraldogma.server.internal.admin.auth; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.time.Duration; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.Test; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.linecorp.centraldogma.server.auth.Session; import com.linecorp.centraldogma.server.auth.SessionManager; class CachedSessionManagerTest { @Test void shouldOperateWithCache() { final Session session = new Session("id", "username", Duration.ofHours(1)); final Cache<String, Session> cache = spy(Caffeine.newBuilder().build()); final SessionManager delegate = mock(SessionManager.class); when(delegate.create(any())).thenReturn(CompletableFuture.completedFuture(null)); when(delegate.update(any())).thenReturn(CompletableFuture.completedFuture(null)); when(delegate.delete(any())).thenReturn(CompletableFuture.completedFuture(null)); final CachedSessionManager manager = new CachedSessionManager(delegate, cache); manager.create(session).join(); verify(cache).put(session.id(), session); assertThat(manager.get(session.id()).join()).isEqualTo(session); verify(cache).getIfPresent(session.id()); final Session updatedSession = new Session("id", "username", Duration.ofHours(1)); manager.update(updatedSession).join(); verify(cache).put(updatedSession.id(), updatedSession); // Called 2 times with the same ID. assertThat(manager.get(updatedSession.id()).join()).isEqualTo(updatedSession); verify(cache, times(2)).getIfPresent(updatedSession.id()); manager.delete(updatedSession.id()).join(); verify(cache).invalidate(updatedSession.id()); } }
line/centraldogma
server/src/test/java/com/linecorp/centraldogma/server/internal/admin/auth/CachedSessionManagerTest.java
Java
apache-2.0
2,775
/* Copyright (c) 2006-2007, Vladimir Nikic All rights reserved. Redistribution and use of this software 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. * The name of HtmlCleaner may not 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. You can contact Vladimir Nikic by sending e-mail to nikic_vladimir@yahoo.com. Please include the word "HtmlCleaner" in the subject line. */ package de.machmireinebook.epubeditor.htmlcleaner; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * <p>Common utilities.</p> * * Created by: Vladimir Nikic<br/> * Date: November, 2006. */ public class Utils { /** * Reads content from the specified URL with specified charset into string * @param url * @param charset * @throws IOException */ @Deprecated // Removing network I/O will make htmlcleaner better suited to a server environment which needs managed connections static CharSequence readUrl(URL url, String charset) throws IOException { StringBuilder buffer = new StringBuilder(1024); InputStream inputStream = url.openStream(); try { InputStreamReader reader = new InputStreamReader(inputStream, charset); char[] charArray = new char[1024]; int charsRead = 0; do { charsRead = reader.read(charArray); if (charsRead >= 0) { buffer.append(charArray, 0, charsRead); } } while (charsRead > 0); } finally { inputStream.close(); } return buffer; } /** * Escapes XML string. * @param s String to be escaped * @param props Cleaner properties affects escaping behaviour * @param isDomCreation Tells if escaped content will be part of the DOM */ public static String escapeXml(String s, CleanerProperties props, boolean isDomCreation) { boolean advanced = props.isAdvancedXmlEscape(); boolean recognizeUnicodeChars = props.isRecognizeUnicodeChars(); boolean translateSpecialEntities = props.isTranslateSpecialEntities(); boolean transResCharsToNCR = props.isTransResCharsToNCR(); boolean transSpecialEntitiesToNCR = props.isTransSpecialEntitiesToNCR(); return escapeXml(s, advanced, recognizeUnicodeChars, translateSpecialEntities, isDomCreation, transResCharsToNCR, transSpecialEntitiesToNCR); } /** * change notes: * 1) convert ascii characters encoded using &#xx; format to the ascii characters -- may be an attempt to slip in malicious html * 2) convert &#xxx; format characters to &quot; style representation if available for the character. * 3) convert html special entities to xml &#xxx; when outputing in xml * @param s * @param advanced * @param recognizeUnicodeChars * @param translateSpecialEntities * @param isDomCreation * @return * TODO Consider moving to CleanerProperties since a long list of params is misleading. */ public static String escapeXml(String s, boolean advanced, boolean recognizeUnicodeChars, boolean translateSpecialEntities, boolean isDomCreation, boolean transResCharsToNCR, boolean translateSpecialEntitiesToNCR) { if (s != null) { int len = s.length(); StringBuilder result = new StringBuilder(len); for (int i = 0; i < len; i++) { char ch = s.charAt(i); SpecialEntity code; if (ch == '&') { if ( (advanced || recognizeUnicodeChars) && (i < len-1) && (s.charAt(i+1) == '#') ) { i = convertToUnicode(s, isDomCreation, recognizeUnicodeChars, translateSpecialEntitiesToNCR, result, i+2); } else if ((translateSpecialEntities || advanced) && (code = SpecialEntities.INSTANCE.getSpecialEntity(s.substring(i, i+Math.min(10, len-i)))) != null) { if (translateSpecialEntities && code.isHtmlSpecialEntity()) { if (recognizeUnicodeChars) { result.append( (char)code.intValue() ); } else { result.append( code.getDecimalNCR() ); } i += code.getKey().length() + 1; } else if (advanced ) { result.append(transResCharsToNCR ? code.getDecimalNCR() : code.getEscaped(isDomCreation)); i += code.getKey().length()+1; } else { result.append(transResCharsToNCR ? getAmpNcr() : "&amp;"); } } else { result.append(transResCharsToNCR ? getAmpNcr() : "&amp;"); } } else if ((code = SpecialEntities.INSTANCE.getSpecialEntityByUnicode(ch)) != null ) { result.append(transResCharsToNCR ? code.getDecimalNCR() : code.getEscaped(isDomCreation)); } else { result.append(ch); } } return result.toString(); } return null; } private static String ampNcr; private static String getAmpNcr() { if (ampNcr == null) { ampNcr = SpecialEntities.INSTANCE.getSpecialEntityByUnicode('&').getDecimalNCR(); } return ampNcr; } private static final Pattern ASCII_CHAR = Pattern.compile("\\p{Print}"); /** * @param s * @param domCreation * @param recognizeUnicodeChars * @param translateSpecialEntitiesToNCR * @param result * @param i * @return */ private static int convertToUnicode(String s, boolean domCreation, boolean recognizeUnicodeChars, boolean translateSpecialEntitiesToNCR, StringBuilder result, int i) { StringBuilder unicode = new StringBuilder(); int charIndex = extractCharCode(s, i, true, unicode); if (unicode.length() > 0) { try { boolean isHex = unicode.substring(0,1).equals("x"); char unicodeChar = isHex ? (char)Integer.parseInt(unicode.substring(1), 16) : (char)Integer.parseInt(unicode.toString()); SpecialEntity specialEntity = SpecialEntities.INSTANCE.getSpecialEntityByUnicode(unicodeChar); if (unicodeChar == 0) { // null character &#0Peanut for example // just consume character & result.append("&amp;"); } else if ( specialEntity != null && // special characters that are always escaped. (!specialEntity.isHtmlSpecialEntity() // OR we are not outputting unicode characters as the characters ( they are staying escaped ) || !recognizeUnicodeChars)) { result.append(domCreation? specialEntity.getHtmlString(): (translateSpecialEntitiesToNCR? (isHex? specialEntity.getHexNCR(): specialEntity.getDecimalNCR()) : specialEntity.getEscapedXmlString())); } else if ( recognizeUnicodeChars ) { // output unicode characters as their actual byte code with the exception of characters that have special xml meaning. result.append( String.valueOf(unicodeChar)); } else if ( ASCII_CHAR.matcher(new String(new char[] { unicodeChar } )).find()) { // ascii printable character. this fancy escaping might be an attempt to slip in dangerous characters (i.e. spelling out <script> ) // by converting to printable characters we can more easily detect such attacks. result.append(String.valueOf(unicodeChar)); } else { result.append( "&#").append(unicode).append(";" ); } } catch (NumberFormatException e) { // should never happen now result.append("&amp;#").append(unicode).append(";" ); } } else { result.append("&amp;"); } return charIndex; } // TODO have pattern consume leading 0's and discard. public static Pattern HEX_STRICT = Pattern.compile("^([x|X][\\p{XDigit}]+)(;?)"); public static Pattern HEX_RELAXED = Pattern.compile("^0*([x|X][\\p{XDigit}]+)(;?)"); public static Pattern DECIMAL = Pattern.compile("^([\\p{Digit}]+)(;?)"); /** * <ul> * <li>(earlier code was failing on this) - &#138A; is converted by FF to 3 characters: &#138; + 'A' + ';'</li> * <li>&#0x138A; is converted by FF to 6? 7? characters: &#0 'x'+'1'+'3'+ '8' + 'A' + ';' * #0 is displayed kind of weird</li> * <li>&#x138A; is a single character</li> * </ul> * * @param s * @param charIndex * @param relaxedUnicode '&#0x138;' is treated like '&#x138;' * @param unicode * @return the index to continue scanning the source string -1 so normal loop incrementing skips the ';' */ private static int extractCharCode(String s, int charIndex, boolean relaxedUnicode, StringBuilder unicode) { int len = s.length(); CharSequence subSequence = s.subSequence(charIndex, Math.min(len,charIndex+15)); Matcher matcher; if( relaxedUnicode ) { matcher = HEX_RELAXED.matcher(subSequence); } else { matcher = HEX_STRICT.matcher(subSequence); } // silly note: remember calling find() twice finds second match :-) if (matcher.find() || ((matcher = DECIMAL.matcher(subSequence)).find())) { // -1 so normal loop incrementing skips the ';' charIndex += matcher.end() -1; unicode.append(matcher.group(1)); } return charIndex; } /** * Checks if specified character can be part of xml identifier (tag name of attribute name) * and is not standard identifier character. * @param ch Character to be checked * @return True if it can be part of xml identifier */ public static boolean isIdentifierHelperChar(char ch) { return ':' == ch || '.' == ch || '-' == ch || '_' == ch; } /** * Checks whether specified string can be valid tag name or attribute name in xml. * @param s String to be checked * @return True if string is valid xml identifier, false otherwise */ public static boolean isValidXmlIdentifier(String s) { if (s != null) { int len = s.length(); if (len == 0) { return false; } for (int i = 0; i < len; i++) { char ch = s.charAt(i); if ( (i == 0 && !Character.isUnicodeIdentifierStart(ch)) || (!Character.isUnicodeIdentifierStart(ch) && !Character.isDigit(ch) && !Utils.isIdentifierHelperChar(ch)) ) { return false; } } return true; } return false; } /** * @param o * @return True if specified string is null of contains only whitespace characters */ public static boolean isEmptyString(Object o) { if ( o == null ) { return true; } String s = o.toString(); String text = escapeXml(s, true, false, false, false, false, false); // TODO: doesn't escapeXml handle this? String last = text.replace(SpecialEntities.NON_BREAKABLE_SPACE, ' ').trim(); return last.length() == 0; } public static String[] tokenize(String s, String delimiters) { if (s == null) { return new String[] {}; } StringTokenizer tokenizer = new StringTokenizer(s, delimiters); String result[] = new String[tokenizer.countTokens()]; int index = 0; while (tokenizer.hasMoreTokens()) { result[index++] = tokenizer.nextToken(); } return result; } /** * @param name * @return For xml element name or attribute name returns prefix (part before :) or null if there is no prefix */ public static String getXmlNSPrefix(String name) { int colIndex = name.indexOf(':'); if (colIndex > 0) { return name.substring(0, colIndex); } return null; } /** * @param name * @return For xml element name or attribute name returns name after prefix (part after :) */ public static String getXmlName(String name) { int colIndex = name.indexOf(':'); if (colIndex > 0 && colIndex < name.length() - 1) { return name.substring(colIndex + 1); } return name; } static boolean isValidInt(String s, int radix) { try { Integer.parseInt(s, radix); return true; } catch (NumberFormatException e) { return false; } } static boolean isValidXmlChar(char ch) { return ((ch >= 0x20) && (ch <= 0xD7FF)) || (ch == 0x9) || (ch == 0xA) || (ch == 0xD) || ((ch >= 0xE000) && (ch <= 0xFFFD)) || ((ch >= 0x10000) && (ch <= 0x10FFFF)); } /** * Trims specified string from left. * @param s */ public static String ltrim(String s) { if (s == null) { return null; } int index = 0; int len = s.length(); while ( index < len && Character.isWhitespace(s.charAt(index)) ) { index++; } return (index >= len) ? "" : s.substring(index); } /** * Trims specified string from right. * @param s */ public static String rtrim(String s) { if (s == null) { return null; } int len = s.length(); int index = len; while ( index > 0 && Character.isWhitespace(s.charAt(index-1)) ) { index--; } return (index <= 0) ? "" : s.substring(0, index); } /** * Checks whether specified object's string representation is empty string (containing of only whitespaces). * @param object Object whose string representation is checked * @return true, if empty string, false otherwise */ public static boolean isWhitespaceString(Object object) { if (object != null) { String s = object.toString(); return s != null && "".equals(s.trim()); } return false; } }
finanzer/epubfx
src/main/java/de/machmireinebook/epubeditor/htmlcleaner/Utils.java
Java
apache-2.0
15,981
/** * Code contributed to the Learning Layers project * http://www.learning-layers.eu * Development is partly funded by the FP7 Programme of the European Commission under * Grant Agreement FP7-ICT-318209. * Copyright (c) 2014, Graz University of Technology - KTI (Knowledge Technologies Institute). * For a list of contributors see the AUTHORS file at the top-level directory of this distribution. * * 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 at.tugraz.sss.servs.entity.impl; import at.tugraz.sss.serv.datatype.par.SSCirclesGetPar; import at.tugraz.sss.serv.entity.api.SSEntityServerI; import at.tugraz.sss.serv.datatype.SSEntity; import at.tugraz.sss.serv.datatype.SSErr; import at.tugraz.sss.serv.util.*; import at.tugraz.sss.serv.datatype.*; import at.tugraz.sss.serv.datatype.par.*; import at.tugraz.sss.serv.reg.SSServErrReg; import at.tugraz.sss.serv.reg.*; import java.util.List; import java.util.Map; public class SSEntityUserRelationsGatherFct{ public static void getUserRelations( final SSServPar servPar, final List<String> allUsers, final Map<String, List<SSUri>> userRelations) throws SSErr{ try{ for(String user : allUsers){ final SSUri userUri = SSUri.get(user); SSEntityUserRelationsGatherFct.addRelationsForUserCircles( servPar, userRelations, userUri); } for(Map.Entry<String, List<SSUri>> usersPerUser : userRelations.entrySet()){ SSStrU.distinctWithoutNull2(usersPerUser.getValue()); } }catch(Exception error){ SSServErrReg.regErrThrow(error); } } private static void addRelationsForUserCircles( final SSServPar servPar, final Map<String, List<SSUri>> userRelations, final SSUri userUri) throws SSErr{ final String userStr = SSStrU.toStr(userUri); for(SSEntity circle : ((SSEntityServerI) SSServReg.getServ(SSEntityServerI.class)).circlesGet( new SSCirclesGetPar( servPar, userUri, userUri, null, null, false, //setEntities, true, //setUsers false, true, false))){ if(userRelations.containsKey(userStr)){ userRelations.get(userStr).addAll(SSUri.getDistinctNotNullFromEntities(circle.users)); }else{ userRelations.put(userStr, SSUri.getDistinctNotNullFromEntities(circle.users)); } } } }
learning-layers/SocialSemanticServer
servs/entity/entity.impl/src/main/java/at/tugraz/sss/servs/entity/impl/SSEntityUserRelationsGatherFct.java
Java
apache-2.0
3,014
/* * 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 de.unioninvestment.eai.portal.support.scripting; import groovy.lang.Closure; import groovy.sql.Sql; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import de.unioninvestment.eai.portal.portlet.crud.domain.database.ConnectionPoolFactory; import de.unioninvestment.eai.portal.portlet.crud.scripting.database.ExtendedSql; /** * * Closure für das Ausführen von SQL aus einem Script. * * @author max.hartmann * * @see {{@link Sql} */ public class SqlProvider extends Closure<ExtendedSql> { private static final long serialVersionUID = 1L; private final ConnectionPoolFactory factory; /** * Konstruktor mit Parametern. * * @param owner Besitzer des Closures * @param factory ConnectionPoolFactory */ public SqlProvider(Object owner, ConnectionPoolFactory factory) { super(owner); this.factory = factory; } /** * Closure-Aufruf. * * @param name DataSource-Kurzname oder vollständiger JNDI-NAME * @return Groovy-SQL * @throws NamingException wenn die DataSource nicht existiert */ public ExtendedSql doCall(String name) throws NamingException { DataSource dataSource; if (name.contains("/")) { InitialContext ic = new InitialContext(); dataSource = (DataSource) ic.lookup(name); } else { dataSource = factory.getPool(name).lookupDataSource(); } return new ExtendedSql(dataSource); } }
Union-Investment/Crud2Go
eai-portal-support-scripting/src/main/java/de/unioninvestment/eai/portal/support/scripting/SqlProvider.java
Java
apache-2.0
2,211
// // このファイルは、JavaTM Architecture for XML Binding(JAXB) Reference Implementation、v2.2.8-b130911.1802によって生成されました // <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>を参照してください // ソース・スキーマの再コンパイル時にこのファイルの変更は失われます。 // 生成日: 2015.08.14 時間 10:22:22 PM JST // package com.eitax.recall.amazon.xsd; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>anonymous complex typeのJavaクラス。 * * <p>次のスキーマ・フラグメントは、このクラス内に含まれる予期されるコンテンツを指定します。 * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://webservices.amazon.com/AWSECommerceService/2011-08-01}OperationRequest" minOccurs="0"/> * &lt;element ref="{http://webservices.amazon.com/AWSECommerceService/2011-08-01}Cart" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "operationRequest", "cart" }) @XmlRootElement(name = "CartCreateResponse") public class CartCreateResponse { @XmlElement(name = "OperationRequest") protected OperationRequest operationRequest; @XmlElement(name = "Cart") protected List<Cart> cart; /** * operationRequestプロパティの値を取得します。 * * @return * possible object is * {@link OperationRequest } * */ public OperationRequest getOperationRequest() { return operationRequest; } /** * operationRequestプロパティの値を設定します。 * * @param value * allowed object is * {@link OperationRequest } * */ public void setOperationRequest(OperationRequest value) { this.operationRequest = value; } /** * Gets the value of the cart property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the cart property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCart().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Cart } * * */ public List<Cart> getCart() { if (cart == null) { cart = new ArrayList<Cart>(); } return this.cart; } }
shokoro3434/test2
eitax-batch-aws/src/main/java/com/eitax/recall/amazon/xsd/CartCreateResponse.java
Java
apache-2.0
3,142
package com.google.api.ads.dfp.jaxws.v201306; import java.util.List; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; /** * * Provides methods for creating, updating, and retrieving * {@link UserTeamAssociation} objects. * <p> * UserTeamAssociation objects are used to add users to teams in order to define * access to entities such as companies, inventory and orders and to override * the team's access type to orders for a user. * </p> * * * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.4-b01 * Generated source version: 2.1 * */ @WebService(name = "UserTeamAssociationServiceInterface", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306") @XmlSeeAlso({ ObjectFactory.class }) public interface UserTeamAssociationServiceInterface { /** * * Creates a new {@code UserTeamAssociation}. * * The following fields are required: * <ul> * <li>{@link UserTeamAssociation#teamId}</li> * <li>{@link UserTeamAssociation#userId}</li> * </ul> * * @param userTeamAssociation the user team association to create * @return the user team association with its ID filled in * * * @param userTeamAssociation * @return * returns com.google.api.ads.dfp.jaxws.v201306.UserTeamAssociation * @throws ApiException_Exception */ @WebMethod @WebResult(name = "rval", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306") @RequestWrapper(localName = "createUserTeamAssociation", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306", className = "com.google.api.ads.dfp.jaxws.v201306.UserTeamAssociationServiceInterfacecreateUserTeamAssociation") @ResponseWrapper(localName = "createUserTeamAssociationResponse", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306", className = "com.google.api.ads.dfp.jaxws.v201306.UserTeamAssociationServiceInterfacecreateUserTeamAssociationResponse") public UserTeamAssociation createUserTeamAssociation( @WebParam(name = "userTeamAssociation", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306") UserTeamAssociation userTeamAssociation) throws ApiException_Exception ; /** * * Creates new {@link UserTeamAssociation} objects. * * @param userTeamAssociations the user team associations to create * @return the created user team associations with their IDs filled in * * * @param userTeamAssociations * @return * returns java.util.List<com.google.api.ads.dfp.jaxws.v201306.UserTeamAssociation> * @throws ApiException_Exception */ @WebMethod @WebResult(name = "rval", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306") @RequestWrapper(localName = "createUserTeamAssociations", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306", className = "com.google.api.ads.dfp.jaxws.v201306.UserTeamAssociationServiceInterfacecreateUserTeamAssociations") @ResponseWrapper(localName = "createUserTeamAssociationsResponse", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306", className = "com.google.api.ads.dfp.jaxws.v201306.UserTeamAssociationServiceInterfacecreateUserTeamAssociationsResponse") public List<UserTeamAssociation> createUserTeamAssociations( @WebParam(name = "userTeamAssociations", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306") List<UserTeamAssociation> userTeamAssociations) throws ApiException_Exception ; /** * * Returns the {@link UserTeamAssociation} uniquely identified by the given * user and team IDs. * * @param teamId the ID of the team, which must already exist * @param userId the ID of the user, which must already exist * @return the {@code UserTeamAssociation} uniquely identified by the * user and team IDs * * * @param userId * @param teamId * @return * returns com.google.api.ads.dfp.jaxws.v201306.UserTeamAssociation * @throws ApiException_Exception */ @WebMethod @WebResult(name = "rval", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306") @RequestWrapper(localName = "getUserTeamAssociation", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306", className = "com.google.api.ads.dfp.jaxws.v201306.UserTeamAssociationServiceInterfacegetUserTeamAssociation") @ResponseWrapper(localName = "getUserTeamAssociationResponse", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306", className = "com.google.api.ads.dfp.jaxws.v201306.UserTeamAssociationServiceInterfacegetUserTeamAssociationResponse") public UserTeamAssociation getUserTeamAssociation( @WebParam(name = "teamId", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306") Long teamId, @WebParam(name = "userId", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306") Long userId) throws ApiException_Exception ; /** * * Gets a {@link UserTeamAssociationPage} of {@link UserTeamAssociation} * objects that satisfy the given {@link Statement#query}. The following * fields are supported for filtering: * * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code userId}</td> * <td>{@link UserTeamAssociation#userId}</td> * </tr> * <tr> * <td>{@code teamId}</td> * <td>{@link UserTeamAssociation#teamId}</td> * </tr> * </table> * * @param filterStatement a Publisher Query Language statement used to filter * a set of user team associations * @return the user team associations that match the given filter * * * @param filterStatement * @return * returns com.google.api.ads.dfp.jaxws.v201306.UserTeamAssociationPage * @throws ApiException_Exception */ @WebMethod @WebResult(name = "rval", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306") @RequestWrapper(localName = "getUserTeamAssociationsByStatement", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306", className = "com.google.api.ads.dfp.jaxws.v201306.UserTeamAssociationServiceInterfacegetUserTeamAssociationsByStatement") @ResponseWrapper(localName = "getUserTeamAssociationsByStatementResponse", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306", className = "com.google.api.ads.dfp.jaxws.v201306.UserTeamAssociationServiceInterfacegetUserTeamAssociationsByStatementResponse") public UserTeamAssociationPage getUserTeamAssociationsByStatement( @WebParam(name = "filterStatement", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306") Statement filterStatement) throws ApiException_Exception ; /** * * Performs actions on {@link UserTeamAssociation} objects that match the * given {@link Statement#query}. * * @param userTeamAssociationAction the action to perform * @param filterStatement a Publisher Query Language statement used to filter * a set of user team associations * @return the result of the action performed * * * @param statement * @param userTeamAssociationAction * @return * returns com.google.api.ads.dfp.jaxws.v201306.UpdateResult * @throws ApiException_Exception */ @WebMethod @WebResult(name = "rval", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306") @RequestWrapper(localName = "performUserTeamAssociationAction", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306", className = "com.google.api.ads.dfp.jaxws.v201306.UserTeamAssociationServiceInterfaceperformUserTeamAssociationAction") @ResponseWrapper(localName = "performUserTeamAssociationActionResponse", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306", className = "com.google.api.ads.dfp.jaxws.v201306.UserTeamAssociationServiceInterfaceperformUserTeamAssociationActionResponse") public UpdateResult performUserTeamAssociationAction( @WebParam(name = "userTeamAssociationAction", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306") UserTeamAssociationAction userTeamAssociationAction, @WebParam(name = "statement", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306") Statement statement) throws ApiException_Exception ; /** * * Updates the specified {@link UserTeamAssociation}. * * @param userTeamAssociation the user team association to update * @return the updated user team association * * * @param userTeamAssociation * @return * returns com.google.api.ads.dfp.jaxws.v201306.UserTeamAssociation * @throws ApiException_Exception */ @WebMethod @WebResult(name = "rval", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306") @RequestWrapper(localName = "updateUserTeamAssociation", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306", className = "com.google.api.ads.dfp.jaxws.v201306.UserTeamAssociationServiceInterfaceupdateUserTeamAssociation") @ResponseWrapper(localName = "updateUserTeamAssociationResponse", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306", className = "com.google.api.ads.dfp.jaxws.v201306.UserTeamAssociationServiceInterfaceupdateUserTeamAssociationResponse") public UserTeamAssociation updateUserTeamAssociation( @WebParam(name = "userTeamAssociation", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306") UserTeamAssociation userTeamAssociation) throws ApiException_Exception ; /** * * Updates the specified {@link UserTeamAssociation} objects. * * @param userTeamAssociations the user team associations to update * @return the updated user team associations * * * @param userTeamAssociations * @return * returns java.util.List<com.google.api.ads.dfp.jaxws.v201306.UserTeamAssociation> * @throws ApiException_Exception */ @WebMethod @WebResult(name = "rval", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306") @RequestWrapper(localName = "updateUserTeamAssociations", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306", className = "com.google.api.ads.dfp.jaxws.v201306.UserTeamAssociationServiceInterfaceupdateUserTeamAssociations") @ResponseWrapper(localName = "updateUserTeamAssociationsResponse", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306", className = "com.google.api.ads.dfp.jaxws.v201306.UserTeamAssociationServiceInterfaceupdateUserTeamAssociationsResponse") public List<UserTeamAssociation> updateUserTeamAssociations( @WebParam(name = "userTeamAssociations", targetNamespace = "https://www.google.com/apis/ads/publisher/v201306") List<UserTeamAssociation> userTeamAssociations) throws ApiException_Exception ; }
nafae/developer
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201306/UserTeamAssociationServiceInterface.java
Java
apache-2.0
12,005
package com.topie.core.spring; import org.springframework.context.ApplicationContext; /** * 保存ApplicationContext的单例. */ public class ApplicationContextHolder { /** instance. */ private static ApplicationContextHolder instance = new ApplicationContextHolder(); /** ApplicationContext. */ private ApplicationContext applicationContext; /** * get ApplicationContext. * * @return ApplicationContext */ public ApplicationContext getApplicationContext() { return applicationContext; } /** * set ApplicationContext. * * @param applicationContext * ApplicationContext */ public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } /** * get instance. * * @return ApplicationContextHolder */ public static ApplicationContextHolder getInstance() { return instance; } }
topie/topie-oa
src/main/java/com/topie/core/spring/ApplicationContextHolder.java
Java
apache-2.0
995
/** * Copyright (C) 2006-2013 phloc systems * http://www.phloc.com * office[at]phloc[dot]com * * 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.phloc.commons.collections.multimap; import org.junit.Test; /** * Test class for class {@link MultiHashMapTreeSetBased}. * * @author Philip Helger */ public final class MultiHashMapTreeSetBasedTest extends AbstractMultiMapTestCase { @Test public void testAll () { IMultiMapSetBased <String, String> aMultiMap = new MultiHashMapTreeSetBased <String, String> (); testEmpty (aMultiMap); aMultiMap = new MultiHashMapTreeSetBased <String, String> (getKey1 (), getValue1 ()); testOne (aMultiMap); aMultiMap = new MultiHashMapTreeSetBased <String, String> (getKey1 (), getValueSet1 ()); testOne (aMultiMap); aMultiMap = new MultiHashMapTreeSetBased <String, String> (getMapSet1 ()); testOne (aMultiMap); } }
lsimons/phloc-schematron-standalone
phloc-commons/src/test/java/com/phloc/commons/collections/multimap/MultiHashMapTreeSetBasedTest.java
Java
apache-2.0
1,421
package com.github.mkopylec.errorest.handling.errordata.validation; import com.github.mkopylec.errorest.configuration.ErrorestProperties; import com.github.mkopylec.errorest.handling.errordata.ErrorData.ErrorDataBuilder; import com.github.mkopylec.errorest.handling.errordata.ErrorDataProvider; import com.github.mkopylec.errorest.response.Error; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; import static com.github.mkopylec.errorest.handling.errordata.ErrorData.ErrorDataBuilder.newErrorData; import static org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY; public abstract class BeanValidationErrorDataProvider<T extends Throwable> extends ErrorDataProvider<T> { public BeanValidationErrorDataProvider(ErrorestProperties errorestProperties) { super(errorestProperties); } protected ErrorDataBuilder buildErrorData(BindingResult result) { ErrorestProperties.BeanValidationError validationError = errorestProperties.getBeanValidationError(); ErrorDataBuilder builder = newErrorData() .withLoggingLevel(validationError.getLoggingLevel()) .withResponseStatus(UNPROCESSABLE_ENTITY); result.getAllErrors().forEach(objectError -> { Error error = createError(objectError); builder.addError(error); }); return builder; } protected Error createError(ObjectError error) { return new Error(error.getDefaultMessage(), "Invalid '" + getField(error) + "' value: " + getRejectedValue(error)); } protected String getField(ObjectError error) { return error instanceof FieldError ? ((FieldError) error).getField() : error.getObjectName(); } protected Object getRejectedValue(ObjectError error) { return error instanceof FieldError ? ((FieldError) error).getRejectedValue() : NOT_AVAILABLE_DATA; } }
mkopylec/errorest-spring-boot-starter
src/main/java/com/github/mkopylec/errorest/handling/errordata/validation/BeanValidationErrorDataProvider.java
Java
apache-2.0
1,975
package ru.stqa.pft.addressbook.test; import org.testng.Assert; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.model.ContactData; /** * Created by Сергей on 18.07.2017. */ public class ContactCreationTest extends TestBase { @Test public void testContactCreation() { int before = app.getContactHelper().getContactCount(); app.getNavigationHelper().gotoAddNewContact(); app.getContactHelper().createContact(new ContactData("w1", "w2", "w3", "w4", "w5", "w6", "w7", "w8", "w9", "w10", "w12", "w13", "w14", "w15", "w16", "w17", "w18", "w19", "w20","q1"), true); int after = app.getContactHelper().getContactCount(); Assert.assertEquals(after,before+1); } }
bent533/SoftwareTestingAoutomationJava
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/test/ContactCreationTest.java
Java
apache-2.0
714
// // このファイルは、JavaTM Architecture for XML Binding(JAXB) Reference Implementation、v2.2.8-b130911.1802によって生成されました // <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>を参照してください // ソース・スキーマの再コンパイル時にこのファイルの変更は失われます。 // 生成日: 2015.08.24 時間 02:38:24 AM JST // package com.eitax.recall.rest.ebay.shopping.xsd; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * * A generic histogram entry type. * * * <p>HistogramEntryType complex typeのJavaクラス。 * * <p>次のスキーマ・フラグメントは、このクラス内に含まれる予期されるコンテンツを指定します。 * * <pre> * &lt;complexType name="HistogramEntryType"> * &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" minOccurs="0"/> * &lt;element name="Count" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "HistogramEntryType", propOrder = { "name", "count" }) public class HistogramEntryType { @XmlElement(name = "Name") protected String name; @XmlElement(name = "Count") protected Integer count; /** * nameプロパティの値を取得します。 * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * nameプロパティの値を設定します。 * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * countプロパティの値を取得します。 * * @return * possible object is * {@link Integer } * */ public Integer getCount() { return count; } /** * countプロパティの値を設定します。 * * @param value * allowed object is * {@link Integer } * */ public void setCount(Integer value) { this.count = value; } }
shokoro3434/test2
eitax-batch-ebay/src/main/java/com/eitax/recall/rest/ebay/shopping/xsd/HistogramEntryType.java
Java
apache-2.0
2,604
package com.bbd.dafei.common.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 用户日志注解 * Created by wish on 2017/6/5. */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface UserLog { String value() default ""; }
wllpeter/red-alter
app/common/util/src/main/java/com/bbd/dafei/common/annotation/UserLog.java
Java
apache-2.0
393
package com.rodvar.esports.presentation; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.ButterKnife; /** * Created by rodrigo on 01/12/16. * Base adapter for this app. Resolves common problems related to MVP */ public abstract class BaseAdapter extends RecyclerView.Adapter { private final BasePresenter presenter; /** * @param presenter */ protected BaseAdapter(BasePresenter presenter) { this.presenter = presenter; } /** * @return layout resource id for this adapter */ protected abstract int getLayoutResId(); /** * @param v * @return decide view holder implementation */ protected abstract BaseAdapter.ViewHolder instantiateViewHolder(View v); protected BasePresenter getPresenter() { return presenter; } @Override public final RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(this.getLayoutResId(), parent, false); return this.instantiateViewHolder(v); } @Override public final void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { this.presenter.bind((ViewHolder) holder, position); } @Override public final int getItemCount() { return this.presenter.getItemCount(); } /** * Base ViewHolder. Provides butterknife auto binding */ public class ViewHolder extends RecyclerView.ViewHolder { protected ViewHolder(View rootView) { super(rootView); ButterKnife.bind(this, rootView); } } }
rodvar/esports
app/src/main/java/com/rodvar/esports/presentation/BaseAdapter.java
Java
apache-2.0
1,757
/* * 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.druid.query.datasourcemetadata; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.apache.druid.data.input.MapBasedInputRow; import org.apache.druid.jackson.DefaultObjectMapper; import org.apache.druid.java.util.common.DateTimes; import org.apache.druid.java.util.common.Intervals; import org.apache.druid.java.util.common.jackson.JacksonUtils; import org.apache.druid.query.DefaultGenericQueryMetricsFactory; import org.apache.druid.query.Druids; import org.apache.druid.query.GenericQueryMetricsFactory; import org.apache.druid.query.Query; import org.apache.druid.query.QueryContexts; import org.apache.druid.query.QueryPlus; import org.apache.druid.query.QueryRunner; import org.apache.druid.query.QueryRunnerFactory; import org.apache.druid.query.QueryRunnerTestHelper; import org.apache.druid.query.Result; import org.apache.druid.query.aggregation.CountAggregatorFactory; import org.apache.druid.segment.IncrementalIndexSegment; import org.apache.druid.segment.incremental.IncrementalIndex; import org.apache.druid.timeline.LogicalSegment; import org.joda.time.DateTime; import org.joda.time.Interval; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class DataSourceMetadataQueryTest { private static final ObjectMapper jsonMapper = new DefaultObjectMapper(); @Test public void testQuerySerialization() throws IOException { Query query = Druids.newDataSourceMetadataQueryBuilder() .dataSource("testing") .build(); String json = jsonMapper.writeValueAsString(query); Query serdeQuery = jsonMapper.readValue(json, Query.class); Assert.assertEquals(query, serdeQuery); } @Test public void testContextSerde() throws Exception { final DataSourceMetadataQuery query = Druids.newDataSourceMetadataQueryBuilder() .dataSource("foo") .intervals("2013/2014") .context( ImmutableMap.of( "priority", 1, "useCache", true, "populateCache", "true", "finalize", true ) ).build(); final ObjectMapper mapper = new DefaultObjectMapper(); final Query serdeQuery = mapper.readValue( mapper.writeValueAsBytes( mapper.readValue( mapper.writeValueAsString( query ), Query.class ) ), Query.class ); Assert.assertEquals(1, serdeQuery.getContextValue(QueryContexts.PRIORITY_KEY)); Assert.assertEquals(true, serdeQuery.getContextValue("useCache")); Assert.assertEquals("true", serdeQuery.getContextValue("populateCache")); Assert.assertEquals(true, serdeQuery.getContextValue("finalize")); Assert.assertEquals(true, serdeQuery.getContextBoolean("useCache", false)); Assert.assertEquals(true, serdeQuery.getContextBoolean("populateCache", false)); Assert.assertEquals(true, serdeQuery.getContextBoolean("finalize", false)); } @Test public void testMaxIngestedEventTime() throws Exception { final IncrementalIndex rtIndex = new IncrementalIndex.Builder() .setSimpleTestingIndexSchema(new CountAggregatorFactory("count")) .setMaxRowCount(1000) .buildOnheap(); final QueryRunner runner = QueryRunnerTestHelper.makeQueryRunner( (QueryRunnerFactory) new DataSourceMetadataQueryRunnerFactory( new DataSourceQueryQueryToolChest(DefaultGenericQueryMetricsFactory.instance()), QueryRunnerTestHelper.NOOP_QUERYWATCHER ), new IncrementalIndexSegment(rtIndex, "test"), null ); DateTime timestamp = DateTimes.nowUtc(); rtIndex.add( new MapBasedInputRow( timestamp.getMillis(), ImmutableList.of("dim1"), ImmutableMap.of("dim1", "x") ) ); DataSourceMetadataQuery dataSourceMetadataQuery = Druids.newDataSourceMetadataQueryBuilder() .dataSource("testing") .build(); Map<String, Object> context = new ConcurrentHashMap<>(); context.put(Result.MISSING_SEGMENTS_KEY, Lists.newArrayList()); Iterable<Result<DataSourceMetadataResultValue>> results = runner.run(QueryPlus.wrap(dataSourceMetadataQuery), context).toList(); DataSourceMetadataResultValue val = results.iterator().next().getValue(); DateTime maxIngestedEventTime = val.getMaxIngestedEventTime(); Assert.assertEquals(timestamp, maxIngestedEventTime); } @Test public void testFilterSegments() { GenericQueryMetricsFactory queryMetricsFactory = DefaultGenericQueryMetricsFactory.instance(); DataSourceQueryQueryToolChest toolChest = new DataSourceQueryQueryToolChest(queryMetricsFactory); List<LogicalSegment> segments = toolChest .filterSegments( null, Arrays.asList( new LogicalSegment() { @Override public Interval getInterval() { return Intervals.of("2012-01-01/P1D"); } }, new LogicalSegment() { @Override public Interval getInterval() { return Intervals.of("2012-01-01T01/PT1H"); } }, new LogicalSegment() { @Override public Interval getInterval() { return Intervals.of("2013-01-01/P1D"); } }, new LogicalSegment() { @Override public Interval getInterval() { return Intervals.of("2013-01-01T01/PT1H"); } }, new LogicalSegment() { @Override public Interval getInterval() { return Intervals.of("2013-01-01T02/PT1H"); } } ) ); Assert.assertEquals(segments.size(), 2); // should only have the latest segments. List<LogicalSegment> expected = Arrays.asList( new LogicalSegment() { @Override public Interval getInterval() { return Intervals.of("2013-01-01/P1D"); } }, new LogicalSegment() { @Override public Interval getInterval() { return Intervals.of("2013-01-01T02/PT1H"); } } ); for (int i = 0; i < segments.size(); i++) { Assert.assertEquals(expected.get(i).getInterval(), segments.get(i).getInterval()); } } @Test public void testResultSerialization() { final DataSourceMetadataResultValue resultValue = new DataSourceMetadataResultValue(DateTimes.of("2000-01-01T00Z")); final Map<String, Object> resultValueMap = new DefaultObjectMapper().convertValue( resultValue, JacksonUtils.TYPE_REFERENCE_MAP_STRING_OBJECT ); Assert.assertEquals( ImmutableMap.<String, Object>of("maxIngestedEventTime", "2000-01-01T00:00:00.000Z"), resultValueMap ); } @Test public void testResultDeserialization() { final Map<String, Object> resultValueMap = ImmutableMap.of( "maxIngestedEventTime", "2000-01-01T00:00:00.000Z" ); final DataSourceMetadataResultValue resultValue = new DefaultObjectMapper().convertValue( resultValueMap, DataSourceMetadataResultValue.class ); Assert.assertEquals(DateTimes.of("2000"), resultValue.getMaxIngestedEventTime()); } }
dkhwangbo/druid
processing/src/test/java/org/apache/druid/query/datasourcemetadata/DataSourceMetadataQueryTest.java
Java
apache-2.0
9,551
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * 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.optaplanner.core.impl.testdata.domain.solutionproperties; import java.util.List; import org.optaplanner.core.api.domain.solution.PlanningEntityCollectionProperty; import org.optaplanner.core.api.domain.solution.PlanningScore; import org.optaplanner.core.api.domain.solution.PlanningSolution; import org.optaplanner.core.api.domain.solution.drools.ProblemFactCollectionProperty; import org.optaplanner.core.api.domain.solution.drools.ProblemFactProperty; import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider; import org.optaplanner.core.api.score.buildin.simple.SimpleScore; import org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor; import org.optaplanner.core.impl.testdata.domain.TestdataEntity; import org.optaplanner.core.impl.testdata.domain.TestdataObject; import org.optaplanner.core.impl.testdata.domain.TestdataValue; @PlanningSolution public class TestdataProblemFactPropertySolution extends TestdataObject { public static SolutionDescriptor buildSolutionDescriptor() { return SolutionDescriptor.buildSolutionDescriptor(TestdataProblemFactPropertySolution.class, TestdataEntity.class); } private List<TestdataValue> valueList; private List<Object> otherProblemFactList; private Object extraObject; private List<TestdataEntity> entityList; private SimpleScore score; public TestdataProblemFactPropertySolution() { } public TestdataProblemFactPropertySolution(String code) { super(code); } @ValueRangeProvider(id = "valueRange") @ProblemFactCollectionProperty public List<TestdataValue> getValueList() { return valueList; } public void setValueList(List<TestdataValue> valueList) { this.valueList = valueList; } @ProblemFactCollectionProperty public List<Object> getOtherProblemFactList() { return otherProblemFactList; } public void setOtherProblemFactList(List<Object> otherProblemFactList) { this.otherProblemFactList = otherProblemFactList; } @ProblemFactProperty public Object getExtraObject() { return extraObject; } public void setExtraObject(Object extraObject) { this.extraObject = extraObject; } @PlanningEntityCollectionProperty public List<TestdataEntity> getEntityList() { return entityList; } public void setEntityList(List<TestdataEntity> entityList) { this.entityList = entityList; } @PlanningScore public SimpleScore getScore() { return score; } public void setScore(SimpleScore score) { this.score = score; } }
oskopek/optaplanner
optaplanner-core/src/test/java/org/optaplanner/core/impl/testdata/domain/solutionproperties/TestdataProblemFactPropertySolution.java
Java
apache-2.0
3,271
import org.junit.*; import static org.junit.Assert.*; import java.util.*; import java.util.stream.*; class Location { String type; public String getType() { return type; } } class LocationResponse { List<Location> locations = new ArrayList<>(); public List<Location> getLocations() { return locations; } } public class ExampleTestCase { @Test public void testCanary() { int x = 2+2; assertEquals(4, x); } @Test public void testExample() { var loc = new Location(); var list = List.of(loc, new Location(), new Location()); var locationResponse = new LocationResponse(); locationResponse.locations.addAll(list); locationResponse.getLocations() .stream() .map(location -> location.getType()) .forEach(t -> assertNull(t)); } }
codetojoy/easter_eggs_for_gradle
template/junit/src/test/java/ExampleTestCase.java
Java
apache-2.0
898
/* * Copyright 2021 Google LLC * * 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 * * https://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.google.cloud.texttospeech.v1; import com.google.api.core.BetaApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.texttospeech.v1.stub.TextToSpeechStub; import com.google.cloud.texttospeech.v1.stub.TextToSpeechStubSettings; import java.io.IOException; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Service Description: Service that implements Google Cloud Text-to-Speech API. * * <p>This class provides the ability to make remote calls to the backing service through method * calls that map to API methods. Sample code to get started: * * <pre>{@code * try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) { * String languageCode = "languageCode-2092349083"; * ListVoicesResponse response = textToSpeechClient.listVoices(languageCode); * } * }</pre> * * <p>Note: close() needs to be called on the TextToSpeechClient object to clean up resources such * as threads. In the example above, try-with-resources is used, which automatically calls close(). * * <p>The surface of this class includes several types of Java methods for each of the API's * methods: * * <ol> * <li>A "flattened" method. With this type of method, the fields of the request type have been * converted into function parameters. It may be the case that not all fields are available as * parameters, and not every API method will have a flattened method entry point. * <li>A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. * <li>A "callable" method. This type of method takes no parameters and returns an immutable API * callable object, which can be used to initiate calls to the service. * </ol> * * <p>See the individual methods for example code. * * <p>Many parameters require resource names to be formatted in a particular way. To assist with * these names, this class includes a format method for each type of name, and additionally a parse * method to extract the individual identifiers contained within names that are returned. * * <p>This class can be customized by passing in a custom instance of TextToSpeechSettings to * create(). For example: * * <p>To customize credentials: * * <pre>{@code * TextToSpeechSettings textToSpeechSettings = * TextToSpeechSettings.newBuilder() * .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)) * .build(); * TextToSpeechClient textToSpeechClient = TextToSpeechClient.create(textToSpeechSettings); * }</pre> * * <p>To customize the endpoint: * * <pre>{@code * TextToSpeechSettings textToSpeechSettings = * TextToSpeechSettings.newBuilder().setEndpoint(myEndpoint).build(); * TextToSpeechClient textToSpeechClient = TextToSpeechClient.create(textToSpeechSettings); * }</pre> * * <p>Please refer to the GitHub repository's samples for more quickstart code snippets. */ @Generated("by gapic-generator-java") public class TextToSpeechClient implements BackgroundResource { private final TextToSpeechSettings settings; private final TextToSpeechStub stub; /** Constructs an instance of TextToSpeechClient with default settings. */ public static final TextToSpeechClient create() throws IOException { return create(TextToSpeechSettings.newBuilder().build()); } /** * Constructs an instance of TextToSpeechClient, using the given settings. The channels are * created based on the settings passed in, or defaults for any settings that are not set. */ public static final TextToSpeechClient create(TextToSpeechSettings settings) throws IOException { return new TextToSpeechClient(settings); } /** * Constructs an instance of TextToSpeechClient, using the given stub for making calls. This is * for advanced usage - prefer using create(TextToSpeechSettings). */ @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public static final TextToSpeechClient create(TextToSpeechStub stub) { return new TextToSpeechClient(stub); } /** * Constructs an instance of TextToSpeechClient, using the given settings. This is protected so * that it is easy to make a subclass, but otherwise, the static factory methods should be * preferred. */ protected TextToSpeechClient(TextToSpeechSettings settings) throws IOException { this.settings = settings; this.stub = ((TextToSpeechStubSettings) settings.getStubSettings()).createStub(); } @BetaApi("A restructuring of stub classes is planned, so this may break in the future") protected TextToSpeechClient(TextToSpeechStub stub) { this.settings = null; this.stub = stub; } public final TextToSpeechSettings getSettings() { return settings; } @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public TextToSpeechStub getStub() { return stub; } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of Voice supported for synthesis. * * <p>Sample code: * * <pre>{@code * try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) { * String languageCode = "languageCode-2092349083"; * ListVoicesResponse response = textToSpeechClient.listVoices(languageCode); * } * }</pre> * * @param languageCode Optional. Recommended. * [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag. If not specified, the * API will return all supported voices. If specified, the ListVoices call will only return * voices that can be used to synthesize this language_code. For example, if you specify * `"en-NZ"`, all `"en-NZ"` voices will be returned. If you specify `"no"`, both * `"no-\\&#42;"` (Norwegian) and `"nb-\\&#42;"` (Norwegian Bokmal) voices will be returned. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListVoicesResponse listVoices(String languageCode) { ListVoicesRequest request = ListVoicesRequest.newBuilder().setLanguageCode(languageCode).build(); return listVoices(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of Voice supported for synthesis. * * <p>Sample code: * * <pre>{@code * try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) { * ListVoicesRequest request = * ListVoicesRequest.newBuilder().setLanguageCode("languageCode-2092349083").build(); * ListVoicesResponse response = textToSpeechClient.listVoices(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListVoicesResponse listVoices(ListVoicesRequest request) { return listVoicesCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of Voice supported for synthesis. * * <p>Sample code: * * <pre>{@code * try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) { * ListVoicesRequest request = * ListVoicesRequest.newBuilder().setLanguageCode("languageCode-2092349083").build(); * ApiFuture<ListVoicesResponse> future = * textToSpeechClient.listVoicesCallable().futureCall(request); * // Do something. * ListVoicesResponse response = future.get(); * } * }</pre> */ public final UnaryCallable<ListVoicesRequest, ListVoicesResponse> listVoicesCallable() { return stub.listVoicesCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Synthesizes speech synchronously: receive results after all text input has been processed. * * <p>Sample code: * * <pre>{@code * try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) { * SynthesisInput input = SynthesisInput.newBuilder().build(); * VoiceSelectionParams voice = VoiceSelectionParams.newBuilder().build(); * AudioConfig audioConfig = AudioConfig.newBuilder().build(); * SynthesizeSpeechResponse response = * textToSpeechClient.synthesizeSpeech(input, voice, audioConfig); * } * }</pre> * * @param input Required. The Synthesizer requires either plain text or SSML as input. * @param voice Required. The desired voice of the synthesized audio. * @param audioConfig Required. The configuration of the synthesized audio. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final SynthesizeSpeechResponse synthesizeSpeech( SynthesisInput input, VoiceSelectionParams voice, AudioConfig audioConfig) { SynthesizeSpeechRequest request = SynthesizeSpeechRequest.newBuilder() .setInput(input) .setVoice(voice) .setAudioConfig(audioConfig) .build(); return synthesizeSpeech(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Synthesizes speech synchronously: receive results after all text input has been processed. * * <p>Sample code: * * <pre>{@code * try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) { * SynthesizeSpeechRequest request = * SynthesizeSpeechRequest.newBuilder() * .setInput(SynthesisInput.newBuilder().build()) * .setVoice(VoiceSelectionParams.newBuilder().build()) * .setAudioConfig(AudioConfig.newBuilder().build()) * .build(); * SynthesizeSpeechResponse response = textToSpeechClient.synthesizeSpeech(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final SynthesizeSpeechResponse synthesizeSpeech(SynthesizeSpeechRequest request) { return synthesizeSpeechCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Synthesizes speech synchronously: receive results after all text input has been processed. * * <p>Sample code: * * <pre>{@code * try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) { * SynthesizeSpeechRequest request = * SynthesizeSpeechRequest.newBuilder() * .setInput(SynthesisInput.newBuilder().build()) * .setVoice(VoiceSelectionParams.newBuilder().build()) * .setAudioConfig(AudioConfig.newBuilder().build()) * .build(); * ApiFuture<SynthesizeSpeechResponse> future = * textToSpeechClient.synthesizeSpeechCallable().futureCall(request); * // Do something. * SynthesizeSpeechResponse response = future.get(); * } * }</pre> */ public final UnaryCallable<SynthesizeSpeechRequest, SynthesizeSpeechResponse> synthesizeSpeechCallable() { return stub.synthesizeSpeechCallable(); } @Override public final void close() { stub.close(); } @Override public void shutdown() { stub.shutdown(); } @Override public boolean isShutdown() { return stub.isShutdown(); } @Override public boolean isTerminated() { return stub.isTerminated(); } @Override public void shutdownNow() { stub.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return stub.awaitTermination(duration, unit); } }
googleapis/java-texttospeech
google-cloud-texttospeech/src/main/java/com/google/cloud/texttospeech/v1/TextToSpeechClient.java
Java
apache-2.0
12,307
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.medical.modules.cms.service; import java.util.Date; import java.util.List; import org.apache.commons.lang3.time.DateUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.google.common.collect.Lists; import com.medical.common.persistence.Page; import com.medical.common.service.CrudService; import com.medical.common.utils.CacheUtils; import com.medical.common.utils.StringUtils; import com.medical.modules.cms.dao.LinkDao; import com.medical.modules.cms.entity.Link; /** * 链接Service * @author ThinkGem * @version 2013-01-15 */ @Service @Transactional(readOnly = true) public class LinkService extends CrudService<LinkDao, Link> { @Transactional(readOnly = false) public Page<Link> findPage(Page<Link> page, Link link, boolean isDataScopeFilter) { // 更新过期的权重,间隔为“6”个小时 Date updateExpiredWeightDate = (Date)CacheUtils.get("updateExpiredWeightDateByLink"); if (updateExpiredWeightDate == null || (updateExpiredWeightDate != null && updateExpiredWeightDate.getTime() < new Date().getTime())){ dao.updateExpiredWeight(link); CacheUtils.put("updateExpiredWeightDateByLink", DateUtils.addHours(new Date(), 6)); } link.getSqlMap().put("dsf", dataScopeFilter(link.getCurrentUser(), "o", "u")); return super.findPage(page, link); } @Transactional(readOnly = false) public void delete(Link link, Boolean isRe) { //dao.updateDelFlag(id, isRe!=null&&isRe?Link.DEL_FLAG_NORMAL:Link.DEL_FLAG_DELETE); link.setDelFlag(isRe!=null&&isRe?Link.DEL_FLAG_NORMAL:Link.DEL_FLAG_DELETE); dao.delete(link); } /** * 通过编号获取内容标题 */ public List<Object[]> findByIds(String ids) { List<Object[]> list = Lists.newArrayList(); String[] idss = StringUtils.split(ids,","); if (idss.length>0){ List<Link> l = dao.findByIdIn(idss); for (Link e : l){ list.add(new Object[]{e.getId(),StringUtils.abbr(e.getTitle(),50)}); } } return list; } }
dingyifly/medical
src/main/java/com/medical/modules/cms/service/LinkService.java
Java
apache-2.0
2,146
package com.shitao.sys.controller; import java.io.PrintWriter; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.alibaba.fastjson.JSON; import com.shitao.common.utils.StringUtils; import com.shitao.sys.entity.Permission; import com.shitao.sys.entity.Role; import com.shitao.sys.service.SystemService; @Controller @RequestMapping(value = "/sys/role") public class RoleController { @Autowired private SystemService systemService; @RequestMapping(value = "roleindex") public String roleindex(HttpServletRequest req, HttpServletResponse re, Model model) { String rolename = req.getParameter("rolename"); List<Role> roles = systemService.getAllRole(rolename); model.addAttribute("roles", roles); return "modules/sys/roleindex"; } @RequestMapping(value = ("getRolePermissionJson")) @ResponseBody public void getRolePermissionJson(@RequestParam(required = true) String id, HttpServletResponse re) { Role role = systemService.getRole(id); re.setContentType("text/html;charset=UTF-8"); try { PrintWriter write = re.getWriter(); write.write(JSON.toJSONString(role)); write.close(); } catch (Exception e) { e.printStackTrace(); } return; } /** * * 2017年9月7日 * * @param roleid * @param re */ @RequestMapping(value = "getPermissions") @ResponseBody public void getPermissions(HttpServletResponse re) { // 所有权限 List<Permission> permissions = systemService.getAllPermission(); // 区分已有和没有的权限 Map<String, List<Permission>> result = new HashMap<String, List<Permission>>(); result.put("N", permissions); re.setContentType("text/html;charset=UTF-8"); try { PrintWriter write = re.getWriter(); write.write(JSON.toJSONString(result)); write.close(); } catch (Exception e) { e.printStackTrace(); } return; } @RequestMapping(value = "getFiltedPermission") @ResponseBody public void getFiltedPermission( @RequestParam(required = true) String roleid, HttpServletResponse re) { Role role = systemService.getRole(roleid); // 所有权限 List<Permission> permissions = systemService.getAllPermission(); // 角色的权限 List<Permission> roleP = role.getPermissions(); // 将所有权限去除角色已有的权限 for (int i = 0; i < roleP.size(); i++) { for (int j = 0; j < permissions.size(); j++) { if (roleP.get(i).getName().equals(permissions.get(j).getName())) { permissions.remove(j); break; } } } // 区分已有和没有的权限 Map<String, List<Permission>> result = new HashMap<String, List<Permission>>(); result.put("Y", roleP); result.put("N", permissions); re.setContentType("text/html;charset=UTF-8"); try { PrintWriter write = re.getWriter(); write.write(JSON.toJSONString(result)); write.close(); } catch (Exception e) { e.printStackTrace(); } return; } @RequestMapping(value = "updateRolePermission") public String updateRolePermission(HttpServletRequest req, HttpServletResponse re, Model model,RedirectAttributes redirectAttr) { String roleid = req.getParameter("roleid"); String[] permissions = req.getParameterValues("permission"); String rolename = req.getParameter("rolename"); Role role = new Role(roleid); role.setName(rolename); if (permissions != null) { List<Permission> list = new LinkedList<Permission>(); for (String item : permissions) { list.add((new Permission(item))); } role.setPermissions(list); } systemService.updateRolePermission(role); redirectAttr.addFlashAttribute("message", "修改成功"); return "redirect:/sys/role/roleindex"; } @RequestMapping(value = "addRolePermission") public String addRolePermission(HttpServletRequest req, HttpServletResponse re, Model model,RedirectAttributes redirectAttr) { String roleid = StringUtils.generalUUID(); String[] permissions = req.getParameterValues("permission"); String rolename = req.getParameter("rolename"); Role role = new Role(roleid); role.setName(rolename); if (permissions != null) { List<Permission> list = new LinkedList<Permission>(); for (String item : permissions) { list.add((new Permission(item))); } role.setPermissions(list); } systemService.addRolePermission(role); redirectAttr.addFlashAttribute("message", "修改成功"); return "redirect:/sys/role/roleindex"; } @RequestMapping(value="delete") public void delete(HttpServletRequest req,HttpServletResponse res) { String roleId = req.getParameter("roleId"); Role role = new Role(roleId); systemService.delRole(role); } }
csTaoo/springmvc-shiro
src/main/java/com/shitao/sys/controller/RoleController.java
Java
apache-2.0
5,341
//package javaapplication1; import java.awt.*; import javax.swing.*; import javax.swing.table.*; @SuppressWarnings("serial") class ProgressRenderer extends JProgressBar implements TableCellRenderer { public ProgressRenderer(int min, int max) { super(min, max); setBorderPainted(false); setValue(0); } public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { setValue((int) ((Float) value).floatValue()); return this; } }
jainamjb/IDM
ProgressRenderer.java
Java
apache-2.0
608
/*--------------------------------------------------- * 版权所有:北京光宇华在线科技有限责任公司 * 作者:bjkandy * 联系方式:kangruiwei@gyyx.cn * 版本号:2015年5月29日 * * 注意:本内容仅限于公司内部使用,禁止转发。 * ------------------------------------------------*/ package cn.gyyx.framework.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; /** * 字节流工具类 * @author bjkandy * @version 2015年5月29日 */ public class StreamUtils { final static int BUFFER_SIZE = 4096; /** * 将InputStream转换成String * * @param in * InputStream * @return String * @throws Exception * */ public static String InputStreamTOString(InputStream in) { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] data = new byte[BUFFER_SIZE]; String string = null; int count = 0; try { while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) { outStream.write(data, 0, count); } } catch (IOException e) { e.printStackTrace(); } data = null; try { string = new String(outStream.toByteArray(), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return string; } /** * 将InputStream转换成某种字符编码的String * * @param in * @param encoding * @return * @throws Exception */ public static String InputStreamTOString(InputStream in, String encoding) { String string = null; ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] data = new byte[BUFFER_SIZE]; int count = -1; try { while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) { outStream.write(data, 0, count); } } catch (IOException e) { e.printStackTrace(); } data = null; try { string = new String(outStream.toByteArray(), encoding); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return string; } /** * 将String转换成InputStream * * @param in * @return * @throws Exception */ public static InputStream StringTOInputStream(String in) throws Exception { ByteArrayInputStream is = new ByteArrayInputStream(in.getBytes("UTF-8")); return is; } /** * 将String转换成InputStream * * @param in * @return * @throws Exception */ public static byte[] StringTObyte(String in) { byte[] bytes = null; try { bytes = InputStreamTOByte(StringTOInputStream(in)); } catch (IOException e) { } catch (Exception e) { e.printStackTrace(); } return bytes; } /** * 将InputStream转换成byte数组 * * @param in * InputStream * @return byte[] * @throws IOException */ public static byte[] InputStreamTOByte(InputStream in) throws IOException { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] data = new byte[BUFFER_SIZE]; int count = -1; while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) { outStream.write(data, 0, count); } data = null; return outStream.toByteArray(); } /** * 将byte数组转换成InputStream * * @param in * @return * @throws Exception */ public static InputStream byteTOInputStream(byte[] in) throws Exception { ByteArrayInputStream is = new ByteArrayInputStream(in); return is; } /** * 将byte数组转换成String * * @param in * @return * @throws Exception */ public static String byteTOString(byte[] in) { InputStream is = null; try { is = byteTOInputStream(in); } catch (Exception e) { e.printStackTrace(); } return InputStreamTOString(is, "UTF-8"); } /** * 将byte数组转换成String * * @param in * @return * @throws Exception */ public static String getString(String in) { String is = null; try { is = byteTOString(StringTObyte(in)); } catch (Exception e) { e.printStackTrace(); } return is; } // InputStream 转换成byte[] public byte[] getBytes(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] b = new byte[BUFFER_SIZE]; int len = 0; while ((len = is.read(b, 0, BUFFER_SIZE)) != -1) { baos.write(b, 0, len); } baos.flush(); byte[] bytes = baos.toByteArray(); System.out.println(new String(bytes)); return bytes; } /** * 根据文件路径创建文件输入流处理 * 以字节为单位(非 unicode ) * @param path * @return */ public static FileInputStream getFileInputStream(String filepath) { FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(filepath); } catch (FileNotFoundException e) { System.out.print("错误信息:文件不存在"); e.printStackTrace(); } return fileInputStream; } /** * 根据文件对象创建文件输入流处理 * 以字节为单位(非 unicode ) * @param path * @return */ public static FileInputStream getFileInputStream(File file) { FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(file); } catch (FileNotFoundException e) { System.out.print("错误信息:文件不存在"); e.printStackTrace(); } return fileInputStream; } /** * 根据文件对象创建文件输出流处理 * 以字节为单位(非 unicode ) * @param file * @param append true:文件以追加方式打开,false:则覆盖原文件的内容 * @return */ public static FileOutputStream getFileOutputStream(File file,boolean append) { FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(file,append); } catch (FileNotFoundException e) { System.out.print("错误信息:文件不存在"); e.printStackTrace(); } return fileOutputStream; } /** * 根据文件路径创建文件输出流处理 * 以字节为单位(非 unicode ) * @param path * @param append true:文件以追加方式打开,false:则覆盖原文件的内容 * @return */ public static FileOutputStream getFileOutputStream(String filepath,boolean append) { FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(filepath,append); } catch (FileNotFoundException e) { System.out.print("错误信息:文件不存在"); e.printStackTrace(); } return fileOutputStream; } public static File getFile(String filepath) { return new File(filepath); } public static ByteArrayOutputStream getByteArrayOutputStream() { return new ByteArrayOutputStream(); } }
eastFu/gy4j-framework
gy4j-core/src/main/java/cn/gyyx/framework/util/StreamUtils.java
Java
apache-2.0
6,782
package com.fruit.web.service.system.listener; import com.fruit.core.persistence.IBaseDao; import com.fruit.web.model.Mail; public interface SystemEmailService extends IBaseDao<Mail, Integer> { public void send(String title,String content,String toAddress,String path,String type); }
LittleLazyCat/TXEYXXK
weixin_fruit/src/main/java/com/fruit/web/service/system/listener/SystemEmailService.java
Java
apache-2.0
288
/* * 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.cassandra.locator; import java.net.InetAddress; import java.util.*; public abstract class AbstractEndpointSnitch implements IEndpointSnitch { public abstract int compareEndpoints(InetAddress target, InetAddress a1, InetAddress a2); /** * Sorts the <tt>Collection</tt> of node addresses by proximity to the given address * @param address the address to sort by proximity to * @param unsortedAddress the nodes to sort * @return a new sorted <tt>List</tt> */ public List<InetAddress> getSortedListByProximity(InetAddress address, Collection<InetAddress> unsortedAddress) { List<InetAddress> preferred = new ArrayList<InetAddress>(unsortedAddress); sortByProximity(address, preferred); return preferred; } /** * Sorts the <tt>List</tt> of node addresses, in-place, by proximity to the given address * @param address the address to sort the proximity by * @param addresses the nodes to sort */ public void sortByProximity(final InetAddress address, List<InetAddress> addresses) { Collections.sort(addresses, new Comparator<InetAddress>() { public int compare(InetAddress a1, InetAddress a2) { return compareEndpoints(address, a1, a2); } }); } public void gossiperStarting() { // noop by default } }
bcoverston/apache-hosted-cassandra
src/java/org/apache/cassandra/locator/AbstractEndpointSnitch.java
Java
apache-2.0
2,225
/* * Copyright 2018 Google LLC. * * 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.google.cloud.tools.jib.configuration; import com.google.cloud.tools.jib.api.CacheDirectoryCreationException; import com.google.cloud.tools.jib.api.Credential; import com.google.cloud.tools.jib.api.CredentialRetriever; import com.google.cloud.tools.jib.api.ImageReference; import com.google.cloud.tools.jib.api.InvalidImageReferenceException; import com.google.cloud.tools.jib.api.LogEvent; import com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath; import com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer; import com.google.cloud.tools.jib.api.buildplan.ImageFormat; import com.google.cloud.tools.jib.api.buildplan.Port; import com.google.cloud.tools.jib.event.EventHandlers; import com.google.cloud.tools.jib.global.JibSystemProperties; import com.google.cloud.tools.jib.image.json.BuildableManifestTemplate; import com.google.cloud.tools.jib.image.json.OciManifestTemplate; import com.google.cloud.tools.jib.image.json.V22ManifestTemplate; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ListMultimap; import com.google.common.util.concurrent.MoreExecutors; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutorService; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.RestoreSystemProperties; import org.mockito.Mockito; /** Tests for {@link BuildContext}. */ public class BuildContextTest { @Rule public final RestoreSystemProperties systemPropertyRestorer = new RestoreSystemProperties(); private static BuildContext.Builder createBasicTestBuilder() { return BuildContext.builder() .setBaseImageConfiguration( ImageConfiguration.builder(Mockito.mock(ImageReference.class)).build()) .setTargetImageConfiguration( ImageConfiguration.builder(Mockito.mock(ImageReference.class)).build()) .setContainerConfiguration(ContainerConfiguration.builder().build()) .setBaseImageLayersCacheDirectory(Paths.get("ignored")) .setApplicationLayersCacheDirectory(Paths.get("ignored")); } @Test public void testBuilder() throws Exception { String expectedBaseImageServerUrl = "someserver"; String expectedBaseImageName = "baseimage"; String expectedBaseImageTag = "baseimagetag"; String expectedTargetServerUrl = "someotherserver"; String expectedTargetImageName = "targetimage"; String expectedTargetTag = "targettag"; Set<String> additionalTargetImageTags = ImmutableSet.of("tag1", "tag2", "tag3"); Set<String> expectedTargetImageTags = ImmutableSet.of("targettag", "tag1", "tag2", "tag3"); List<CredentialRetriever> credentialRetrievers = Collections.singletonList(() -> Optional.of(Credential.from("username", "password"))); Instant expectedCreationTime = Instant.ofEpochSecond(10000); List<String> expectedEntrypoint = Arrays.asList("some", "entrypoint"); List<String> expectedProgramArguments = Arrays.asList("arg1", "arg2"); Map<String, String> expectedEnvironment = ImmutableMap.of("key", "value"); Set<Port> expectedExposedPorts = ImmutableSet.of(Port.tcp(1000), Port.tcp(2000)); Map<String, String> expectedLabels = ImmutableMap.of("key1", "value1", "key2", "value2"); Class<? extends BuildableManifestTemplate> expectedTargetFormat = OciManifestTemplate.class; Path expectedApplicationLayersCacheDirectory = Paths.get("application/layers"); Path expectedBaseImageLayersCacheDirectory = Paths.get("base/image/layers"); List<FileEntriesLayer> expectedLayerConfigurations = Collections.singletonList( FileEntriesLayer.builder() .addEntry(Paths.get("sourceFile"), AbsoluteUnixPath.get("/path/in/container")) .build()); String expectedCreatedBy = "createdBy"; ListMultimap<String, String> expectedRegistryMirrors = ImmutableListMultimap.of("some.registry", "mirror1", "some.registry", "mirror2"); ImageConfiguration baseImageConfiguration = ImageConfiguration.builder( ImageReference.of( expectedBaseImageServerUrl, expectedBaseImageName, expectedBaseImageTag)) .build(); ImageConfiguration targetImageConfiguration = ImageConfiguration.builder( ImageReference.of( expectedTargetServerUrl, expectedTargetImageName, expectedTargetTag)) .setCredentialRetrievers(credentialRetrievers) .build(); ContainerConfiguration containerConfiguration = ContainerConfiguration.builder() .setCreationTime(expectedCreationTime) .setEntrypoint(expectedEntrypoint) .setProgramArguments(expectedProgramArguments) .setEnvironment(expectedEnvironment) .setExposedPorts(expectedExposedPorts) .setLabels(expectedLabels) .build(); BuildContext.Builder buildContextBuilder = BuildContext.builder() .setBaseImageConfiguration(baseImageConfiguration) .setTargetImageConfiguration(targetImageConfiguration) .setAdditionalTargetImageTags(additionalTargetImageTags) .setContainerConfiguration(containerConfiguration) .setApplicationLayersCacheDirectory(expectedApplicationLayersCacheDirectory) .setBaseImageLayersCacheDirectory(expectedBaseImageLayersCacheDirectory) .setTargetFormat(ImageFormat.OCI) .setEnablePlatformTags(true) .setAllowInsecureRegistries(true) .setLayerConfigurations(expectedLayerConfigurations) .setToolName(expectedCreatedBy) .setRegistryMirrors(expectedRegistryMirrors); BuildContext buildContext = buildContextBuilder.build(); Assert.assertEquals( expectedCreationTime, buildContext.getContainerConfiguration().getCreationTime()); Assert.assertEquals( expectedBaseImageServerUrl, buildContext.getBaseImageConfiguration().getImageRegistry()); Assert.assertEquals( expectedBaseImageName, buildContext.getBaseImageConfiguration().getImageRepository()); Assert.assertEquals( expectedBaseImageTag, buildContext.getBaseImageConfiguration().getImageQualifier()); Assert.assertEquals( expectedTargetServerUrl, buildContext.getTargetImageConfiguration().getImageRegistry()); Assert.assertEquals( expectedTargetImageName, buildContext.getTargetImageConfiguration().getImageRepository()); Assert.assertEquals( expectedTargetTag, buildContext.getTargetImageConfiguration().getImageQualifier()); Assert.assertEquals(expectedTargetImageTags, buildContext.getAllTargetImageTags()); Assert.assertEquals( Credential.from("username", "password"), buildContext .getTargetImageConfiguration() .getCredentialRetrievers() .get(0) .retrieve() .orElseThrow(AssertionError::new)); Assert.assertEquals( expectedProgramArguments, buildContext.getContainerConfiguration().getProgramArguments()); Assert.assertEquals( expectedEnvironment, buildContext.getContainerConfiguration().getEnvironmentMap()); Assert.assertEquals( expectedExposedPorts, buildContext.getContainerConfiguration().getExposedPorts()); Assert.assertEquals(expectedLabels, buildContext.getContainerConfiguration().getLabels()); Assert.assertEquals(expectedTargetFormat, buildContext.getTargetFormat()); Assert.assertEquals( expectedApplicationLayersCacheDirectory, buildContextBuilder.getApplicationLayersCacheDirectory()); Assert.assertEquals( expectedBaseImageLayersCacheDirectory, buildContextBuilder.getBaseImageLayersCacheDirectory()); Assert.assertEquals(expectedLayerConfigurations, buildContext.getLayerConfigurations()); Assert.assertEquals( expectedEntrypoint, buildContext.getContainerConfiguration().getEntrypoint()); Assert.assertEquals(expectedCreatedBy, buildContext.getToolName()); Assert.assertEquals(expectedRegistryMirrors, buildContext.getRegistryMirrors()); Assert.assertNotNull(buildContext.getExecutorService()); Assert.assertTrue(buildContext.getEnablePlatformTags()); } @Test public void testBuilder_default() throws CacheDirectoryCreationException { // These are required and don't have defaults. String expectedBaseImageServerUrl = "someserver"; String expectedBaseImageName = "baseimage"; String expectedBaseImageTag = "baseimagetag"; String expectedTargetServerUrl = "someotherserver"; String expectedTargetImageName = "targetimage"; String expectedTargetTag = "targettag"; ImageConfiguration baseImageConfiguration = ImageConfiguration.builder( ImageReference.of( expectedBaseImageServerUrl, expectedBaseImageName, expectedBaseImageTag)) .build(); ImageConfiguration targetImageConfiguration = ImageConfiguration.builder( ImageReference.of( expectedTargetServerUrl, expectedTargetImageName, expectedTargetTag)) .build(); BuildContext.Builder buildContextBuilder = BuildContext.builder() .setBaseImageConfiguration(baseImageConfiguration) .setTargetImageConfiguration(targetImageConfiguration) .setContainerConfiguration(ContainerConfiguration.builder().setUser("12345").build()) .setBaseImageLayersCacheDirectory(Paths.get("ignored")) .setApplicationLayersCacheDirectory(Paths.get("ignored")); BuildContext buildContext = buildContextBuilder.build(); Assert.assertEquals(ImmutableSet.of("targettag"), buildContext.getAllTargetImageTags()); Assert.assertEquals(V22ManifestTemplate.class, buildContext.getTargetFormat()); Assert.assertNotNull(buildContextBuilder.getApplicationLayersCacheDirectory()); Assert.assertEquals( Paths.get("ignored"), buildContextBuilder.getApplicationLayersCacheDirectory()); Assert.assertNotNull(buildContextBuilder.getBaseImageLayersCacheDirectory()); Assert.assertEquals( Paths.get("ignored"), buildContextBuilder.getBaseImageLayersCacheDirectory()); Assert.assertEquals("12345", buildContext.getContainerConfiguration().getUser()); Assert.assertEquals(Collections.emptyList(), buildContext.getLayerConfigurations()); Assert.assertEquals("jib", buildContext.getToolName()); Assert.assertEquals(0, buildContext.getRegistryMirrors().size()); Assert.assertFalse(buildContext.getEnablePlatformTags()); } @Test public void testBuilder_missingValues() throws CacheDirectoryCreationException { // Target image is missing try { BuildContext.builder() .setBaseImageConfiguration( ImageConfiguration.builder(Mockito.mock(ImageReference.class)).build()) .setBaseImageLayersCacheDirectory(Paths.get("ignored")) .setContainerConfiguration(ContainerConfiguration.builder().build()) .setApplicationLayersCacheDirectory(Paths.get("ignored")) .build(); Assert.fail("BuildContext should not be built with missing values"); } catch (IllegalStateException ex) { Assert.assertEquals("target image configuration is required but not set", ex.getMessage()); } // Two required fields missing try { BuildContext.builder() .setBaseImageLayersCacheDirectory(Paths.get("ignored")) .setApplicationLayersCacheDirectory(Paths.get("ignored")) .setContainerConfiguration(ContainerConfiguration.builder().build()) .build(); Assert.fail("BuildContext should not be built with missing values"); } catch (IllegalStateException ex) { Assert.assertEquals( "base image configuration and target image configuration are required but not set", ex.getMessage()); } // All required fields missing try { BuildContext.builder().build(); Assert.fail("BuildContext should not be built with missing values"); } catch (IllegalStateException ex) { Assert.assertEquals( "base image configuration, target image configuration, container configuration, base " + "image layers cache directory, and application layers cache directory are required " + "but not set", ex.getMessage()); } } @Test public void testBuilder_digestWarning() throws CacheDirectoryCreationException, InvalidImageReferenceException { EventHandlers mockEventHandlers = Mockito.mock(EventHandlers.class); BuildContext.Builder builder = createBasicTestBuilder().setEventHandlers(mockEventHandlers); builder .setBaseImageConfiguration( ImageConfiguration.builder( ImageReference.parse( "image@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")) .build()) .build(); Mockito.verify(mockEventHandlers, Mockito.never()).dispatch(LogEvent.warn(Mockito.anyString())); builder .setBaseImageConfiguration( ImageConfiguration.builder(ImageReference.parse("image:tag")).build()) .build(); Mockito.verify(mockEventHandlers) .dispatch( LogEvent.warn( "Base image 'image:tag' does not use a specific image digest - build may not be reproducible")); } @Test public void testClose_shutDownInternalExecutorService() throws IOException, CacheDirectoryCreationException { BuildContext buildContext = createBasicTestBuilder().build(); buildContext.close(); Assert.assertTrue(buildContext.getExecutorService().isShutdown()); } @Test public void testClose_doNotShutDownProvidedExecutorService() throws IOException, CacheDirectoryCreationException { ExecutorService executorService = MoreExecutors.newDirectExecutorService(); BuildContext buildContext = createBasicTestBuilder().setExecutorService(executorService).build(); buildContext.close(); Assert.assertSame(executorService, buildContext.getExecutorService()); Assert.assertFalse(buildContext.getExecutorService().isShutdown()); } @Test public void testGetUserAgent_unset() throws CacheDirectoryCreationException { BuildContext buildContext = createBasicTestBuilder().build(); String generatedUserAgent = buildContext.makeUserAgent(); Assert.assertEquals("jib null jib", generatedUserAgent); } @Test public void testGetUserAgent_withValues() throws CacheDirectoryCreationException { BuildContext buildContext = createBasicTestBuilder().setToolName("test-name").setToolVersion("test-version").build(); String generatedUserAgent = buildContext.makeUserAgent(); Assert.assertEquals("jib test-version test-name", generatedUserAgent); } @Test public void testGetUserAgentWithUpstreamClient() throws CacheDirectoryCreationException { System.setProperty(JibSystemProperties.UPSTREAM_CLIENT, "skaffold/0.34.0"); BuildContext buildContext = createBasicTestBuilder().setToolName("test-name").setToolVersion("test-version").build(); String generatedUserAgent = buildContext.makeUserAgent(); Assert.assertEquals("jib test-version test-name skaffold/0.34.0", generatedUserAgent); } }
GoogleContainerTools/jib
jib-core/src/test/java/com/google/cloud/tools/jib/configuration/BuildContextTest.java
Java
apache-2.0
16,322
/* * Copyright 2010 netling project <http://netling.org> * * 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.netling.ssh.userauth.password; import java.util.Arrays; /** Static utility method and factories */ public class PasswordUtils { /** * Blank out a character array * * @param pwd the character array */ public static void blankOut(char[] pwd) { if (pwd != null) Arrays.fill(pwd, ' '); } /** * @param password the password as a char[] * * @return the constructed {@link PasswordFinder} */ public static PasswordFinder createOneOff(final char[] password) { if (password == null) return null; else return new PasswordFinder() { @Override public char[] reqPassword(Resource<?> resource) { char[] cloned = password.clone(); blankOut(password); return cloned; } @Override public boolean shouldRetry(Resource<?> resource) { return false; } }; } }
rwinston/netling
src/main/java/org/netling/ssh/userauth/password/PasswordUtils.java
Java
apache-2.0
1,687
package com.ctrip.xpipe.redis.keeper; import com.ctrip.xpipe.api.endpoint.Endpoint; import com.ctrip.xpipe.redis.core.meta.KeeperState; import com.ctrip.xpipe.redis.core.meta.ShardStatus; import com.ctrip.xpipe.redis.keeper.RedisKeeperServer.PROMOTION_STATE; import java.io.IOException; import java.net.InetSocketAddress; /** * @author wenchao.meng * * Jun 8, 2016 */ public interface RedisKeeperServerState{ void becomeActive(InetSocketAddress masterAddress); void becomeBackup(InetSocketAddress masterAddress); void setShardStatus(ShardStatus shardStatus) throws IOException; Endpoint getMaster(); RedisKeeperServer getRedisKeeperServer(); void setPromotionState(PROMOTION_STATE promotionState, Object promitionInfo) throws IOException; void setPromotionState(PROMOTION_STATE promotionState) throws IOException; void initPromotionState(); boolean psync(RedisClient redisClient, String []args) throws Exception; KeeperState keeperState(); void setMasterAddress(InetSocketAddress masterAddress); boolean handleSlaveOf(); }
Yiiinsh/x-pipe
redis/redis-keeper/src/main/java/com/ctrip/xpipe/redis/keeper/RedisKeeperServerState.java
Java
apache-2.0
1,066
package org.joeyb.undercarriage.core.testing; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import org.joeyb.undercarriage.core.ApplicationBase; import org.joeyb.undercarriage.core.config.ConfigSection; import org.joeyb.undercarriage.core.config.ManualConfigContext; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExternalResource; import org.junit.rules.RuleChain; public class ApplicationTestRuleTests { private final ApplicationTestRule<ConfigSection, MockApplication> applicationTestRule = new ApplicationTestRule<>(MockApplication::new); @Rule public final RuleChain ruleChain = RuleChain.outerRule(new FakeTestRule(applicationTestRule)) .around(applicationTestRule); @Test public void applicationShouldBeConfiguredAndStartedButNotStopped() { assertThat(applicationTestRule.application()).isNotNull(); assertThat(applicationTestRule.application().isConfigured()).isTrue(); assertThat(applicationTestRule.application().isStarted()).isTrue(); assertThat(applicationTestRule.application().isStopped()).isFalse(); } /** * {@code FakeTestRule} is used to test the state of the {@link ApplicationTestRule} instance before and after the * test has executed. */ private static class FakeTestRule extends ExternalResource { private final ApplicationTestRule<ConfigSection, MockApplication> applicationTestRule; FakeTestRule(ApplicationTestRule<ConfigSection, MockApplication> applicationTestRule) { this.applicationTestRule = applicationTestRule; } @Override protected void before() throws Throwable { // Make sure the rule's application reference is null before the test has started. assertThat(applicationTestRule.application()).isNull(); } @Override protected void after() { // Make sure the rule's application reference is null after the test is over. assertThat(applicationTestRule.application()).isNull(); } } private static class MockApplication extends ApplicationBase<ConfigSection> { MockApplication() { super(new ManualConfigContext<>(mock(ConfigSection.class))); } } }
joeyb/undercarriage
core-testing/src/test/java/org/joeyb/undercarriage/core/testing/ApplicationTestRuleTests.java
Java
apache-2.0
2,339
// Copyright (C) 2016 The Android Open Source Project // // 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.google.gerrit.server.git; import com.google.common.base.Strings; import com.google.common.collect.ListMultimap; import com.google.gerrit.common.Nullable; import com.google.gerrit.extensions.api.changes.NotifyHandling; import com.google.gerrit.extensions.api.changes.RecipientType; import com.google.gerrit.extensions.restapi.ResourceConflictException; import com.google.gerrit.reviewdb.client.Account; import com.google.gerrit.reviewdb.client.Change; import com.google.gerrit.reviewdb.client.ChangeMessage; import com.google.gerrit.reviewdb.client.PatchSet; import com.google.gerrit.server.ChangeMessagesUtil; import com.google.gerrit.server.ChangeUtil; import com.google.gerrit.server.PatchSetUtil; import com.google.gerrit.server.extensions.events.ChangeAbandoned; import com.google.gerrit.server.mail.send.AbandonedSender; import com.google.gerrit.server.mail.send.ReplyToChangeSender; import com.google.gerrit.server.notedb.ChangeUpdate; import com.google.gerrit.server.update.BatchUpdateOp; import com.google.gerrit.server.update.ChangeContext; import com.google.gerrit.server.update.Context; import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AbandonOp implements BatchUpdateOp { private static final Logger log = LoggerFactory.getLogger(AbandonOp.class); private final AbandonedSender.Factory abandonedSenderFactory; private final ChangeMessagesUtil cmUtil; private final PatchSetUtil psUtil; private final ChangeAbandoned changeAbandoned; private final String msgTxt; private final NotifyHandling notifyHandling; private final ListMultimap<RecipientType, Account.Id> accountsToNotify; private final Account account; private Change change; private PatchSet patchSet; private ChangeMessage message; public interface Factory { AbandonOp create( @Assisted @Nullable Account account, @Assisted @Nullable String msgTxt, @Assisted NotifyHandling notifyHandling, @Assisted ListMultimap<RecipientType, Account.Id> accountsToNotify); } @Inject AbandonOp( AbandonedSender.Factory abandonedSenderFactory, ChangeMessagesUtil cmUtil, PatchSetUtil psUtil, ChangeAbandoned changeAbandoned, @Assisted @Nullable Account account, @Assisted @Nullable String msgTxt, @Assisted NotifyHandling notifyHandling, @Assisted ListMultimap<RecipientType, Account.Id> accountsToNotify) { this.abandonedSenderFactory = abandonedSenderFactory; this.cmUtil = cmUtil; this.psUtil = psUtil; this.changeAbandoned = changeAbandoned; this.account = account; this.msgTxt = Strings.nullToEmpty(msgTxt); this.notifyHandling = notifyHandling; this.accountsToNotify = accountsToNotify; } @Nullable public Change getChange() { return change; } @Override public boolean updateChange(ChangeContext ctx) throws OrmException, ResourceConflictException { change = ctx.getChange(); PatchSet.Id psId = change.currentPatchSetId(); ChangeUpdate update = ctx.getUpdate(psId); if (!change.getStatus().isOpen()) { throw new ResourceConflictException("change is " + ChangeUtil.status(change)); } patchSet = psUtil.get(ctx.getDb(), ctx.getNotes(), psId); change.setStatus(Change.Status.ABANDONED); change.setLastUpdatedOn(ctx.getWhen()); update.setStatus(change.getStatus()); message = newMessage(ctx); cmUtil.addChangeMessage(ctx.getDb(), update, message); return true; } private ChangeMessage newMessage(ChangeContext ctx) { StringBuilder msg = new StringBuilder(); msg.append("Abandoned"); if (!Strings.nullToEmpty(msgTxt).trim().isEmpty()) { msg.append("\n\n"); msg.append(msgTxt.trim()); } return ChangeMessagesUtil.newMessage(ctx, msg.toString(), ChangeMessagesUtil.TAG_ABANDON); } @Override public void postUpdate(Context ctx) throws OrmException { try { ReplyToChangeSender cm = abandonedSenderFactory.create(ctx.getProject(), change.getId()); if (account != null) { cm.setFrom(account.getId()); } cm.setChangeMessage(message.getMessage(), ctx.getWhen()); cm.setNotify(notifyHandling); cm.setAccountsToNotify(accountsToNotify); cm.send(); } catch (Exception e) { log.error("Cannot email update for change " + change.getId(), e); } changeAbandoned.fire(change, patchSet, account, msgTxt, ctx.getWhen(), notifyHandling); } }
gerrit-review/gerrit
java/com/google/gerrit/server/git/AbandonOp.java
Java
apache-2.0
5,197
/* * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. * * 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 serializer; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.StreamSerializer; import java.io.IOException; import java.util.PriorityQueue; public final class PriorityQueueSerializer implements StreamSerializer<PriorityQueue> { @Override public int getTypeId() { return SerializationConstants.PRIORITY_QUEUE; } @Override public void destroy() { } @Override public void write(ObjectDataOutput out, PriorityQueue queue) throws IOException { out.writeInt(queue.size()); out.writeObject(queue.comparator()); for (Object o : queue) { out.writeObject(o); } } @Override public PriorityQueue read(ObjectDataInput in) throws IOException { int size = in.readInt(); PriorityQueue res = new PriorityQueue(size, in.readObject()); for (int i = 0; i < size; i++) { res.add(in.readObject()); } return res; } }
viliam-durina/hazelcast-jet-code-samples
sliding-windows/src/main/java/serializer/PriorityQueueSerializer.java
Java
apache-2.0
1,662
package com.github.florent37.materialviewpager.worldmovies.sync; /** * Created by aaron on 2016/2/24. */ import android.content.Context; import android.text.TextUtils; import android.util.Log; import com.github.florent37.materialviewpager.worldmovies.BuildConfig; import com.github.florent37.materialviewpager.worldmovies.io.model.DataManifest; import com.github.florent37.materialviewpager.worldmovies.util.HashUtils; import com.github.florent37.materialviewpager.worldmovies.util.IOUtils; import com.github.florent37.materialviewpager.worldmovies.util.TimeUtils; import com.google.gson.Gson; import com.turbomanage.httpclient.BasicHttpClient; import com.turbomanage.httpclient.ConsoleRequestLogger; import com.turbomanage.httpclient.HttpResponse; import com.turbomanage.httpclient.RequestLogger; import java.io.File; import java.io.IOException; import java.net.HttpURLConnection; import java.util.HashSet; import java.util.List; import static com.github.florent37.materialviewpager.worldmovies.util.LogUtils.LOGD; import static com.github.florent37.materialviewpager.worldmovies.util.LogUtils.LOGE; import static com.github.florent37.materialviewpager.worldmovies.util.LogUtils.LOGW; import static com.github.florent37.materialviewpager.worldmovies.util.LogUtils.makeLogTag; /** * Helper class that fetches conference data from the remote server. */ public class RemoteConferenceDataFetcher { private static final String TAG = makeLogTag(SyncHelper.class); // The directory under which we cache our downloaded files private static String CACHE_DIR = "data_cache"; private Context mContext = null; // name of URL override file used for debug purposes private static final String URL_OVERRIDE_FILE_NAME = "iosched_manifest_url_override.txt"; // URL of the remote manifest file private String mManifestUrl = null; // timestamp of the manifest file on the server private String mServerTimestamp = null; // the set of cache files we have used -- we use this for cache cleanup. private HashSet<String> mCacheFilesToKeep = new HashSet<String>(); // total # of bytes downloaded (approximate) private long mBytesDownloaded = 0; // total # of bytes read from cache hits (approximate) private long mBytesReadFromCache = 0; public RemoteConferenceDataFetcher(Context context) { mContext = context; mManifestUrl = getManifestUrl(); } /** * Fetches data from the remote server. * * @param refTimestamp The timestamp of the data to use as a reference; if the remote data * is not newer than this timestamp, no data will be downloaded and * this method will return null. * * @return The data downloaded, or null if there is no data to download * @throws IOException if an error occurred during download. */ public String[] fetchConferenceDataIfNewer(String refTimestamp) throws IOException { if (TextUtils.isEmpty(mManifestUrl)) { LOGW(TAG, "Manifest URL is empty (remote sync disabled!)."); return null; } Log.d("0129", "fetchConferenceDataIfNewer"); BasicHttpClient httpClient = new BasicHttpClient(); httpClient.setRequestLogger(mQuietLogger); // Only download if data is newer than refTimestamp // Cloud Storage is very picky with the If-Modified-Since format. If it's in a wrong // format, it refuses to serve the file, returning 400 HTTP error. So, if the // refTimestamp is in a wrong format, we simply ignore it. But pay attention to this // warning in the log, because it might mean unnecessary data is being downloaded. if (!TextUtils.isEmpty(refTimestamp)) { if (TimeUtils.isValidFormatForIfModifiedSinceHeader(refTimestamp)) { httpClient.addHeader("If-Modified-Since", refTimestamp); } else { LOGW(TAG, "Could not set If-Modified-Since HTTP header. Potentially downloading " + "unnecessary data. Invalid format of refTimestamp argument: "+refTimestamp); } } HttpResponse response = httpClient.get(mManifestUrl, null); if (response == null) { LOGE(TAG, "Request for manifest returned null response."); throw new IOException("Request for data manifest returned null response."); } int status = response.getStatus(); if (status == HttpURLConnection.HTTP_OK) { LOGD(TAG, "Server returned HTTP_OK, so new data is available."); mServerTimestamp = getLastModified(response); LOGD(TAG, "Server timestamp for new data is: " + mServerTimestamp); String body = response.getBodyAsString(); if (TextUtils.isEmpty(body)) { LOGE(TAG, "Request for manifest returned empty data."); throw new IOException("Error fetching conference data manifest: no data."); } LOGD(TAG, "Manifest "+mManifestUrl+" read, contents: " + body); mBytesDownloaded += body.getBytes().length; return processManifest(body); } else if (status == HttpURLConnection.HTTP_NOT_MODIFIED) { // data on the server is not newer than our data LOGD(TAG, "HTTP_NOT_MODIFIED: data has not changed since " + refTimestamp); return null; } else { LOGE(TAG, "Error fetching conference data: HTTP status " + status); throw new IOException("Error fetching conference data: HTTP status " + status); } } // Returns the timestamp of the data downloaded from the server public String getServerDataTimestamp() { return mServerTimestamp; } /** * Returns the remote manifest file's URL. This is stored as a resource in the app, * but can be overriden by a file in the filesystem for debug purposes. * @return The URL of the remote manifest file. */ private String getManifestUrl() { Log.d("0219-end", "getManifestsUrl"); String manifestUrl = BuildConfig.SERVER_MANIFEST_ENDPOINT; // check for an override file File urlOverrideFile = new File(mContext.getFilesDir(), URL_OVERRIDE_FILE_NAME); if (urlOverrideFile.exists()) { try { String overrideUrl = IOUtils.readFileAsString(urlOverrideFile).trim(); LOGW(TAG, "Debug URL override active: " + overrideUrl); return overrideUrl; } catch (IOException ex) { return manifestUrl; } } else { return manifestUrl; } } /** * Fetches a file from the cache/network, from an absolute or relative URL. If the * file is available in our cache, we read it from there; if not, we will * download it from the network and cache it. * * @param url The URL to fetch the file from. The URL may be absolute or relative; if * relative, it will be considered to be relative to the manifest URL. * @return The contents of the file. * @throws IOException If an error occurs. */ private String fetchFile(String url) throws IOException { // If this is a relative url, consider it relative to the manifest URL if (!url.contains("://")) { if (TextUtils.isEmpty(mManifestUrl) || !mManifestUrl.contains("/")) { LOGE(TAG, "Could not build relative URL based on manifest URL."); return null; } int i = mManifestUrl.lastIndexOf('/'); url = mManifestUrl.substring(0, i) + "/" + url; } Log.d("0129", "fetchFile"); LOGD(TAG, "Attempting to fetch: " + sanitizeUrl(url)); // Check if we have it in our cache first String body = null; try { body = loadFromCache(url); if (!TextUtils.isEmpty(body)) { // cache hit mBytesReadFromCache += body.getBytes().length; mCacheFilesToKeep.add(getCacheKey(url)); return body; } } catch (IOException ex) { ex.printStackTrace(); LOGE(TAG, "IOException getting file from cache."); // proceed anyway to attempt to download it from the network } BasicHttpClient client = new BasicHttpClient(); client.setRequestLogger(mQuietLogger); // We don't have the file on cache, so download it LOGD(TAG, "Cache miss. Downloading from network: " + sanitizeUrl(url)); HttpResponse response = client.get(url, null); if (response == null) { throw new IOException("Request for URL " + sanitizeUrl(url) + " returned null response."); } LOGD(TAG, "HTTP response " + response.getStatus()); if (response.getStatus() == HttpURLConnection.HTTP_OK) { body = response.getBodyAsString(); if (TextUtils.isEmpty(body)) { throw new IOException("Got empty response when attempting to fetch " + sanitizeUrl(url) + url); } LOGD(TAG, "Successfully downloaded from network: " + sanitizeUrl(url)); mBytesDownloaded += body.getBytes().length; writeToCache(url, body); mCacheFilesToKeep.add(getCacheKey(url)); return body; } else { LOGE(TAG, "Failed to fetch from network: " + sanitizeUrl(url)); throw new IOException("Request for URL " + sanitizeUrl(url) + " failed with HTTP error " + response.getStatus()); } } /** * Returns the cache file where we store our cache of the response of the given URL. * @param url The URL for which to return the cache file. * @return The cache file. */ private File getCacheFile(String url) { String cacheKey = getCacheKey(url); return new File(mContext.getCacheDir() + File.separator + CACHE_DIR + File.separator + cacheKey); } // Creates the cache directory, if it doesn't exist yet private void createCacheDir() throws IOException { File dir = new File(mContext.getCacheDir() + File.separator + CACHE_DIR); if (!dir.exists() && !dir.mkdir()) { throw new IOException("Failed to mkdir: " + dir); } } /** * Loads our cached content corresponding to the given URL. * @param url The URL for which to load the cached response. * @return The cached response corresponding to the URL; or null if the given URL * does not exist in our cache. * @throws IOException If there is an error reading the cache. */ private String loadFromCache(String url) throws IOException { String cacheKey = getCacheKey(url); File cacheFile = getCacheFile(url); if (cacheFile.exists()) { LOGD(TAG, "Cache hit " + cacheKey + " for " + sanitizeUrl(url)); return IOUtils.readFileAsString(cacheFile); } else { LOGD(TAG, "Cache miss " + cacheKey + " for " + sanitizeUrl(url)); return null; } } /** * Writes a file to the cache. * @param url The URL from which the contents were retrieved. * @param body The contents retrieved from the given URL. * @throws IOException If there is a problem writing the file. */ private void writeToCache(String url, String body) throws IOException { String cacheKey = getCacheKey(url); File cacheFile = getCacheFile(url); createCacheDir(); IOUtils.writeToFile(body, cacheFile); LOGD(TAG, "Wrote to cache " + cacheKey + " --> " + sanitizeUrl(url)); } /** * Returns the cache key to be used to store the given URL. The cache key is the * file name under which the contents of the URL are stored. * @param url The URL. * @return The cache key (guaranteed to be a valid filename) */ private String getCacheKey(String url) { return HashUtils.computeWeakHash(url.trim()) + String.format("%04x", url.length()); } // Sanitize a URL for logging purposes (only the last component is left visible). private String sanitizeUrl(String url) { int i = url.lastIndexOf('/'); if (i >= 0 && i < url.length()) { return url.substring(0, i).replaceAll("[A-za-z]", "*") + url.substring(i); } else return url.replaceAll("[A-za-z]", "*"); } private static final String MANIFEST_FORMAT = "iosched-json-v1"; /** * Process the data manifest and download data files referenced from it. * @param manifestJson The JSON of the manifest file. * @return The contents of the set of files referenced from the manifest, or null * if none could be retrieved. * @throws IOException If an error occurs while retrieving information. */ private String[] processManifest(String manifestJson) throws IOException { LOGD(TAG, "Processing data manifest, length " + manifestJson.length()); DataManifest manifest = new Gson().fromJson(manifestJson, DataManifest.class); if (manifest.format == null || !manifest.format.equals(MANIFEST_FORMAT)) { LOGE(TAG, "Manifest has invalid format spec: " + manifest.format); throw new IOException("Invalid format spec on manifest:" + manifest.format); } if (manifest.data_files == null || manifest.data_files.length == 0) { LOGW(TAG, "Manifest does not list any files. Nothing done."); return null; } LOGD(TAG, "Manifest lists " + manifest.data_files.length + " data files."); String[] jsons = new String[manifest.data_files.length]; for (int i = 0; i < manifest.data_files.length; i++) { String url = manifest.data_files[i]; LOGD(TAG, "Processing data file: " + sanitizeUrl(url)); jsons[i] = fetchFile(url); if (TextUtils.isEmpty(jsons[i])) { LOGE(TAG, "Failed to fetch data file: " + sanitizeUrl(url)); throw new IOException("Failed to fetch data file " + sanitizeUrl(url)); } } LOGD(TAG, "Got " + jsons.length + " data files."); cleanUpCache(); return jsons; } // Delete unnecessary files from our cache private void cleanUpCache() { LOGD(TAG, "Starting cache cleanup, " + mCacheFilesToKeep.size() + " URLs to keep."); File dir = new File(mContext.getCacheDir() + File.separator + CACHE_DIR); if (!dir.exists()) { LOGD(TAG, "Cleanup complete (there is no cache)."); return; } int deleted = 0, kept = 0; for (File file : dir.listFiles()) { if (mCacheFilesToKeep.contains(file.getName())) { LOGD(TAG, "Cache cleanup: KEEEPING " + file.getName()); ++kept; } else { LOGD(TAG, "Cache cleanup: DELETING " + file.getName()); file.delete(); ++deleted; } } LOGD(TAG, "End of cache cleanup. " + kept + " files kept, " + deleted + " deleted."); } public long getTotalBytesDownloaded() { return mBytesDownloaded; } public long getTotalBytesReadFromCache() { return mBytesReadFromCache; } private String getLastModified(HttpResponse resp) { if (!resp.getHeaders().containsKey("Last-Modified")) { return ""; } List<String> s = resp.getHeaders().get("Last-Modified"); return s.isEmpty() ? "" : s.get(0); } /** * A type of ConsoleRequestLogger that does not log requests and responses. */ private RequestLogger mQuietLogger = new ConsoleRequestLogger(){ @Override public void logRequest(HttpURLConnection uc, Object content) throws IOException { } @Override public void logResponse(HttpResponse res) { } }; }
SIMPLYBOYS/WorldMoviesPro
sample/src/main/java/com/github/florent37/materialviewpager/worldmovies/sync/RemoteConferenceDataFetcher.java
Java
apache-2.0
16,147
package com.gmail.thelimeglass.Maps; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.map.MapCanvas; import org.bukkit.map.MapView; import org.bukkit.map.MinecraftFont; import org.eclipse.jdt.annotation.Nullable; import com.gmail.thelimeglass.Utils.Annotations.Config; import com.gmail.thelimeglass.Utils.Annotations.FullConfig; import com.gmail.thelimeglass.Utils.Annotations.Syntax; import ch.njol.skript.lang.Effect; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.util.Kleenean; @Syntax("draw text %string% at [coordinate[s]] [x] %number%(,| and) [y] %number% on [skellett] map %map%") @Config("Main.Maps") @FullConfig public class EffMapDrawText extends Effect { private Expression<String> string; private Expression<Number> x, y; private Expression<MapView> map; @SuppressWarnings("unchecked") @Override public boolean init(Expression<?>[] e, int matchedPattern, Kleenean isDelayed, ParseResult parser) { string = (Expression<String>) e[0]; x = (Expression<Number>) e[1]; y = (Expression<Number>) e[2]; map = (Expression<MapView>) e[3]; return true; } @Override public String toString(@Nullable Event paramEvent, boolean paramBoolean) { return "draw text %string% at [coordinate[s]] [x] %number%(,| and) [y] %number% on [skellett] map %map%"; } @Override protected void execute(Event e) { SkellettMapRenderer render = SkellettMapRenderer.getRenderer(map.getSingle(e)); if (render != null) { render.update(new MapRenderTask() { @Override public void render(MapView mapView, MapCanvas mapCanvas, Player player) { mapCanvas.drawText(x.getSingle(e).intValue(), y.getSingle(e).intValue(), MinecraftFont.Font, ChatColor.stripColor(string.getSingle(e))); } }); } } }
TheLimeGlass/Skellett
src/main/java/com/gmail/thelimeglass/Maps/EffMapDrawText.java
Java
apache-2.0
1,847
/* * Copyright 2007 The Kuali Foundation Licensed under the Educational Community * License, Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.opensource.org/licenses/ecl1.php 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.kuali.rice.krad.uif.component; import org.apache.commons.lang.StringUtils; import org.kuali.rice.krad.uif.UifConstants; import org.kuali.rice.krad.uif.view.View; import org.kuali.rice.krad.util.ObjectUtils; import java.io.Serializable; /** * Provides binding configuration for an DataBinding component (attribute or * collection) * * <p> * From the binding configuration the binding path is determined (if not * manually set) and used to set the path in the UI or to get the value from the * model * </p> * * @author Kuali Rice Team (rice.collab@kuali.org) */ public class BindingInfo extends ConfigurableBase implements Serializable { private static final long serialVersionUID = -7389398061672136091L; private boolean bindToForm; private boolean bindToMap; private String bindingName; private String bindByNamePrefix; private String bindingObjectPath; private String collectionPath; private String bindingPath; public BindingInfo() { super(); bindToForm = false; bindToMap = false; } /** * Sets up some default binding properties based on the view configuration * and the component's property name * * <p> * Sets the bindingName (if not set) to the given property name, and if the * binding object path has not been set uses the default binding object path * setup for the view * </p> * * @param view * - the view instance the component belongs to * @param propertyName * - name of the property (relative to the parent object) the * component binds to */ public void setDefaults(View view, String propertyName) { if (StringUtils.isBlank(bindingName)) { bindingName = propertyName; } if (StringUtils.isBlank(bindingObjectPath)) { bindingObjectPath = view.getDefaultBindingObjectPath(); } } /** * Path to the property on the model the component binds to. Uses standard * dot notation for nested properties. If the binding path was manually set * it will be returned as it is, otherwise the path will be formed by using * the binding object path and the bind prefix * * <p> * e.g. Property name 'foo' on a model would have binding path "foo", while * property name 'name' of the nested model property 'account' would have * binding path "account.name" * </p> * * @return String binding path */ public String getBindingPath() { if (StringUtils.isNotBlank(bindingPath)) { return bindingPath; } String formedBindingPath = ""; if (!bindToForm && StringUtils.isNotBlank(bindingObjectPath)) { formedBindingPath = bindingObjectPath; } if (StringUtils.isNotBlank(bindByNamePrefix)) { if (!bindByNamePrefix.startsWith("[") && StringUtils.isNotBlank(formedBindingPath)) { formedBindingPath += "."; } formedBindingPath += bindByNamePrefix; } if (bindToMap) { formedBindingPath += "['" + bindingName + "']"; } else { if (StringUtils.isNotBlank(formedBindingPath)) { formedBindingPath += "."; } formedBindingPath += bindingName; } return formedBindingPath; } /** * Returns the binding prefix string that can be used to setup the binding * on <code>DataBinding</code> components that are children of the component * that contains the <code>BindingInfo</code>. The binding prefix is formed * like the binding path but without including the object path * * @return String binding prefix for nested components */ public String getBindingPrefixForNested() { String bindingPrefix = ""; if (StringUtils.isNotBlank(bindByNamePrefix)) { bindingPrefix = bindByNamePrefix; } if (bindToMap) { bindingPrefix += "['" + bindingName + "']"; } else { if (StringUtils.isNotBlank(bindingPrefix)) { bindingPrefix += "."; } bindingPrefix += bindingName; } return bindingPrefix; } /** * Returns the binding path that is formed by taking the binding configuration * of this <code>BindingInfo</code> instance with the given property path as the * binding name. This can be used to get the binding path when just a property * name is given that is assumed to be on the same parent object of the field with * the configured binding info * * <p> * Special check is done for org.kuali.rice.krad.uif.UifConstants#NO_BIND_ADJUST_PREFIX prefix * on the property name which indicates the property path is the full path and should * not be adjusted. Also, if the property is prefixed with * org.kuali.rice.krad.uif.UifConstants#DATA_OBJECT_BIND_ADJUST_PREFIX, this indicates we should only append the * binding object path * </p> * * @param propertyPath - path for property to return full binding path for * @return String full binding path */ public String getPropertyAdjustedBindingPath(String propertyPath) { if (propertyPath.startsWith(UifConstants.NO_BIND_ADJUST_PREFIX)) { propertyPath = StringUtils.removeStart(propertyPath, UifConstants.NO_BIND_ADJUST_PREFIX); return propertyPath; } BindingInfo bindingInfoCopy = (BindingInfo) ObjectUtils.deepCopy(this); if (propertyPath.startsWith(UifConstants.DATA_OBJECT_BIND_ADJUST_PREFIX)) { bindingInfoCopy.setBindByNamePrefix(""); propertyPath = StringUtils.removeStart(propertyPath, UifConstants.DATA_OBJECT_BIND_ADJUST_PREFIX); } bindingInfoCopy.setBindingName(propertyPath); return bindingInfoCopy.getBindingPath(); } /** * Helper method for adding a path to the binding prefix * * @param bindPrefix - path to add */ public void addToBindByNamePrefix(String bindPrefix) { if (StringUtils.isNotBlank(bindByNamePrefix)) { bindByNamePrefix += "." + bindPrefix; } else { bindByNamePrefix = bindPrefix; } } /** * Setter for the binding path. Can be left blank in which the path will be * determined from the binding configuration * * @param bindingPath */ public void setBindingPath(String bindingPath) { this.bindingPath = bindingPath; } /** * Indicates whether the component binds directly to the form (that is its * bindingName gives a property available through the form), or whether is * binds through a nested form object. If bindToForm is false, it is assumed * the component binds to the object given by the form property whose path * is configured by bindingObjectPath. * * @return boolean true if component binds directly to form, false if it * binds to a nested object */ public boolean isBindToForm() { return this.bindToForm; } /** * Setter for the bind to form indicator * * @param bindToForm */ public void setBindToForm(boolean bindToForm) { this.bindToForm = bindToForm; } /** * Gives the name of the property that the component binds to. The name can * be nested but not the full path, just from the parent object or in the * case of binding directly to the form from the form object * * <p> * If blank this will be set from the name field of the component * </p> * * @return String name of the bind property */ public String getBindingName() { return this.bindingName; } /** * Setter for the bind property name * * @param bindingName */ public void setBindingName(String bindingName) { this.bindingName = bindingName; } /** * Prefix that will be used to form the binding path from the component * name. Typically used for nested collection properties * * @return String binding prefix */ public String getBindByNamePrefix() { return this.bindByNamePrefix; } /** * Setter for the prefix to use for forming the binding path by name * * @param bindByNamePrefix */ public void setBindByNamePrefix(String bindByNamePrefix) { this.bindByNamePrefix = bindByNamePrefix; } /** * If field is part of a collection field, gives path to collection * * <p> * This is used for metadata purposes when getting finding the attribute * definition from the dictionary and is not used in building the final * binding path * </p> * * @return String path to collection */ public String getCollectionPath() { return this.collectionPath; } /** * Setter for the field's collection path (if part of a collection) * * @param collectionPath */ public void setCollectionPath(String collectionPath) { this.collectionPath = collectionPath; } /** * For attribute fields that do not belong to the default form object (given * by the view), this field specifies the path to the object (on the form) * the attribute does belong to. * * <p> * e.g. Say we have an attribute field with property name 'number', that * belongs to the object given by the 'account' property on the form. The * form object path would therefore be set to 'account'. If the property * belonged to the object given by the 'document.header' property of the * form, the binding object path would be set to 'document.header'. Note if * the binding object path is not set for an attribute field (or any * <code>DataBinding</code> component), the binding object path configured * on the <code>View</code> will be used (unless bindToForm is set to true, * where is assumed the property is directly available from the form). * </p> * * @return String path to object from form */ public String getBindingObjectPath() { return this.bindingObjectPath; } /** * Setter for the object path on the form * * @param bindingObjectPath */ public void setBindingObjectPath(String bindingObjectPath) { this.bindingObjectPath = bindingObjectPath; } /** * Indicates whether the parent object for the property that we are binding * to is a Map. If true the binding path will be adjusted to use the map key * syntax * * @return boolean true if the property binds to a map, false if it does not */ public boolean isBindToMap() { return this.bindToMap; } /** * Setter for the bind to map indicator * * @param bindToMap */ public void setBindToMap(boolean bindToMap) { this.bindToMap = bindToMap; } }
sbower/kuali-rice-1
krad/krad-web-framework/src/main/java/org/kuali/rice/krad/uif/component/BindingInfo.java
Java
apache-2.0
12,075
/* * Copyright (C) 2012 The Android Open Source Project * * 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.android.inputmethod.keyboard.internal; import android.content.res.TypedArray; import com.android.inputmethod.latin.StringUtils; public abstract class KeyStyle { private final KeyboardTextsSet mTextsSet; public abstract String[] getStringArray(TypedArray a, int index); public abstract String getString(TypedArray a, int index); public abstract int getInt(TypedArray a, int index, int defaultValue); public abstract int getFlag(TypedArray a, int index); protected KeyStyle(final KeyboardTextsSet textsSet) { mTextsSet = textsSet; } protected String parseString(final TypedArray a, final int index) { if (a.hasValue(index)) { return KeySpecParser.resolveTextReference(a.getString(index), mTextsSet); } return null; } protected String[] parseStringArray(final TypedArray a, final int index) { if (a.hasValue(index)) { final String text = KeySpecParser.resolveTextReference(a.getString(index), mTextsSet); return StringUtils.parseCsvString(text); } return null; } }
slightfoot/android-kioskime
src/com/android/inputmethod/keyboard/internal/KeyStyle.java
Java
apache-2.0
1,738
import static org.junit.Assert.assertEquals; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import tester.annotations.Ex; import tester.annotations.Exercises; import tester.annotations.Points; @Forbidden({ "java." }) @NotForbidden({ "java.lang.Object", "java.lang.Integer" }) @Exercises({ @Ex(exID = "NotForbiddenInField", points = 12.5)}) public class UnitTest { @Rule public final PointsLogger pointsLogger = new PointsLogger(); @ClassRule public final static PointsSummary pointsSummary = new PointsSummary(); @Test(timeout=200) @Points(exID = "NotForbiddenInField", bonus = 47.11) public void test() { final ToTest t = new ToTest(); assertEquals(0, t.test()); } }
FAU-Inf2/AuDoscore
tests/notforbidden_in_field/junit/UnitTest.java
Java
apache-2.0
713
package io.github.atomfrede.gradle.plugins.crowdincli; import io.github.atomfrede.gradle.plugins.crowdincli.task.crowdin.CrowdinCliExtension; import io.github.atomfrede.gradle.plugins.crowdincli.task.download.CrowdinCliDownloadTask; import io.github.atomfrede.gradle.plugins.crowdincli.task.download.CrowdinCliUnzipTask; import org.gradle.api.Plugin; import org.gradle.api.Project; public class CrowdinCliPlugin implements Plugin<Project> { public static final String GROUP = "Crowdin"; @Override public void apply(Project project) { createCrowdinCliDownloadTask(project); project.getTasks().create(CrowdinCliUnzipTask.TASK_NAME, CrowdinCliUnzipTask.class); project.getExtensions().create("crowdinCli", CrowdinCliExtension.class, project); } private CrowdinCliDownloadTask createCrowdinCliDownloadTask(Project project) { CrowdinCliDownloadTask crowdinCliDownloadTask = project.getTasks().create(CrowdinCliDownloadTask.TASK_NAME, CrowdinCliDownloadTask.class); crowdinCliDownloadTask.setGroup(GROUP); crowdinCliDownloadTask.setDescription(CrowdinCliDownloadTask.DESCRIPTION); return crowdinCliDownloadTask; } }
atomfrede/gradle-crowdin-cli-plugin
src/main/java/io/github/atomfrede/gradle/plugins/crowdincli/CrowdinCliPlugin.java
Java
apache-2.0
1,200
package com.qiniu.pili.droid.streaming.demo.utils; import android.Manifest; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.os.Build; import java.util.ArrayList; import java.util.List; public class PermissionChecker { private static final int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124; private Activity mActivity; public PermissionChecker(Activity activity) { mActivity = activity; } /** * Check that all given permissions have been granted by verifying that each entry in the * given array is of the value {@link PackageManager#PERMISSION_GRANTED}. * * @see Activity#onRequestPermissionsResult(int, String[], int[]) */ private boolean verifyPermissions(int[] grantResults) { // At least one result must be checked. if (grantResults.length < 1){ return false; } // Verify that each required permission has been granted, otherwise return false. for (int result : grantResults) { if (result != PackageManager.PERMISSION_GRANTED) { return false; } } return true; } @TargetApi(Build.VERSION_CODES.M) public boolean checkPermission() { boolean ret = true; List<String> permissionsNeeded = new ArrayList<String>(); final List<String> permissionsList = new ArrayList<String>(); if (!addPermission(permissionsList, Manifest.permission.CAMERA)) { permissionsNeeded.add("CAMERA"); } if (!addPermission(permissionsList, Manifest.permission.RECORD_AUDIO)) { permissionsNeeded.add("MICROPHONE"); } if (!addPermission(permissionsList, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { permissionsNeeded.add("Write external storage"); } if (permissionsNeeded.size() > 0) { // Need Rationale String message = "You need to grant access to " + permissionsNeeded.get(0); for (int i = 1; i < permissionsNeeded.size(); i++) { message = message + ", " + permissionsNeeded.get(i); } // Check for Rationale Option if (!mActivity.shouldShowRequestPermissionRationale(permissionsList.get(0))) { showMessageOKCancel(message, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mActivity.requestPermissions(permissionsList.toArray(new String[permissionsList.size()]), REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS); } }); } else { mActivity.requestPermissions(permissionsList.toArray(new String[permissionsList.size()]), REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS); } ret = false; } return ret; } private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) { new AlertDialog.Builder(mActivity) .setMessage(message) .setPositiveButton("OK", okListener) .setNegativeButton("Cancel", null) .create() .show(); } @TargetApi(Build.VERSION_CODES.M) private boolean addPermission(List<String> permissionsList, String permission) { boolean ret = true; if (mActivity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { permissionsList.add(permission); ret = false; } return ret; } public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS) { if (verifyPermissions(grantResults)) { // all permissions granted } else { // some permissions denied Util.showToast(mActivity, "some permissions denied"); } } } }
pili-engineering/PLDroidCameraStreaming
PLDroidMediaStreamingDemo/app/src/main/java/com/qiniu/pili/droid/streaming/demo/utils/PermissionChecker.java
Java
apache-2.0
4,303
// ======================================================================== // Copyright (c) 2004-2009 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // You may elect to redistribute this code under either of these licenses. // ======================================================================== package org.eclipse.jetty.server; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Enumeration; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpGenerator; import org.eclipse.jetty.http.HttpURI; import org.eclipse.jetty.server.handler.HandlerWrapper; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.util.Attributes; import org.eclipse.jetty.util.AttributesMap; import org.eclipse.jetty.util.LazyList; import org.eclipse.jetty.util.MultiException; import org.eclipse.jetty.util.TypeUtil; import org.eclipse.jetty.util.URIUtil; import org.eclipse.jetty.util.component.Container; import org.eclipse.jetty.util.component.Destroyable; import org.eclipse.jetty.util.component.LifeCycle; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.ShutdownThread; import org.eclipse.jetty.util.thread.ThreadPool; /* ------------------------------------------------------------ */ /** Jetty HTTP Servlet Server. * This class is the main class for the Jetty HTTP Servlet server. * It aggregates Connectors (HTTP request receivers) and request Handlers. * The server is itself a handler and a ThreadPool. Connectors use the ThreadPool methods * to run jobs that will eventually call the handle method. * * @org.apache.xbean.XBean description="Creates an embedded Jetty web server" */ public class Server extends HandlerWrapper implements Attributes { private static final Logger LOG = Log.getLogger(Server.class); private static final String __version; static { if (Server.class.getPackage()!=null && "Eclipse.org - Jetty".equals(Server.class.getPackage().getImplementationVendor()) && Server.class.getPackage().getImplementationVersion()!=null) __version=Server.class.getPackage().getImplementationVersion(); else __version=System.getProperty("jetty.version","7.x.y-SNAPSHOT"); } private final Container _container=new Container(); private final AttributesMap _attributes = new AttributesMap(); private ThreadPool _threadPool; private Connector[] _connectors; private SessionIdManager _sessionIdManager; private boolean _sendServerVersion = true; //send Server: header private boolean _sendDateHeader = false; //send Date: header private int _graceful=0; private boolean _stopAtShutdown; private int _maxCookieVersion=1; private boolean _dumpAfterStart=false; private boolean _dumpBeforeStop=false; private boolean _uncheckedPrintWriter=false; /* ------------------------------------------------------------ */ public Server() { setServer(this); } /* ------------------------------------------------------------ */ /** Convenience constructor * Creates server and a {@link SelectChannelConnector} at the passed port. */ public Server(int port) { setServer(this); Connector connector=new SelectChannelConnector(); connector.setPort(port); setConnectors(new Connector[]{connector}); } /* ------------------------------------------------------------ */ /** Convenience constructor * Creates server and a {@link SelectChannelConnector} at the passed address. */ public Server(InetSocketAddress addr) { setServer(this); Connector connector=new SelectChannelConnector(); connector.setHost(addr.getHostName()); connector.setPort(addr.getPort()); setConnectors(new Connector[]{connector}); } /* ------------------------------------------------------------ */ public static String getVersion() { return __version; } /* ------------------------------------------------------------ */ /** * @return Returns the container. */ public Container getContainer() { return _container; } /* ------------------------------------------------------------ */ public boolean getStopAtShutdown() { return _stopAtShutdown; } /* ------------------------------------------------------------ */ public void setStopAtShutdown(boolean stop) { _stopAtShutdown=stop; if (stop) ShutdownThread.register(this); else ShutdownThread.deregister(this); } /* ------------------------------------------------------------ */ /** * @return Returns the connectors. */ public Connector[] getConnectors() { return _connectors; } /* ------------------------------------------------------------ */ public void addConnector(Connector connector) { setConnectors((Connector[])LazyList.addToArray(getConnectors(), connector, Connector.class)); } /* ------------------------------------------------------------ */ /** * Conveniance method which calls {@link #getConnectors()} and {@link #setConnectors(Connector[])} to * remove a connector. * @param connector The connector to remove. */ public void removeConnector(Connector connector) { setConnectors((Connector[])LazyList.removeFromArray (getConnectors(), connector)); } /* ------------------------------------------------------------ */ /** Set the connectors for this server. * Each connector has this server set as it's ThreadPool and its Handler. * @param connectors The connectors to set. */ public void setConnectors(Connector[] connectors) { if (connectors!=null) { for (int i=0;i<connectors.length;i++) connectors[i].setServer(this); } _container.update(this, _connectors, connectors, "connector"); _connectors = connectors; } /* ------------------------------------------------------------ */ /** * @return Returns the threadPool. */ public ThreadPool getThreadPool() { return _threadPool; } /* ------------------------------------------------------------ */ /** * @param threadPool The threadPool to set. */ public void setThreadPool(ThreadPool threadPool) { if (_threadPool!=null) removeBean(_threadPool); _container.update(this, _threadPool, threadPool, "threadpool",false); _threadPool = threadPool; if (_threadPool!=null) addBean(_threadPool); } /** * @return true if {@link #dumpStdErr()} is called after starting */ public boolean isDumpAfterStart() { return _dumpAfterStart; } /** * @param dumpAfterStart true if {@link #dumpStdErr()} is called after starting */ public void setDumpAfterStart(boolean dumpAfterStart) { _dumpAfterStart = dumpAfterStart; } /** * @return true if {@link #dumpStdErr()} is called before stopping */ public boolean isDumpBeforeStop() { return _dumpBeforeStop; } /** * @param dumpBeforeStop true if {@link #dumpStdErr()} is called before stopping */ public void setDumpBeforeStop(boolean dumpBeforeStop) { _dumpBeforeStop = dumpBeforeStop; } /* ------------------------------------------------------------ */ @Override protected void doStart() throws Exception { if (getStopAtShutdown()) ShutdownThread.register(this); LOG.info("jetty-"+__version); HttpGenerator.setServerVersion(__version); MultiException mex=new MultiException(); if (_threadPool==null) setThreadPool(new QueuedThreadPool()); try { super.doStart(); } catch(Throwable e) { mex.add(e); } if (_connectors!=null) { for (int i=0;i<_connectors.length;i++) { try{_connectors[i].start();} catch(Throwable e) { mex.add(e); } } } if (isDumpAfterStart()) dumpStdErr(); mex.ifExceptionThrow(); } /* ------------------------------------------------------------ */ @Override protected void doStop() throws Exception { if (isDumpBeforeStop()) dumpStdErr(); MultiException mex=new MultiException(); if (_graceful>0) { if (_connectors!=null) { for (int i=_connectors.length;i-->0;) { LOG.info("Graceful shutdown {}",_connectors[i]); try{_connectors[i].close();}catch(Throwable e){mex.add(e);} } } Handler[] contexts = getChildHandlersByClass(Graceful.class); for (int c=0;c<contexts.length;c++) { Graceful context=(Graceful)contexts[c]; LOG.info("Graceful shutdown {}",context); context.setShutdown(true); } Thread.sleep(_graceful); } if (_connectors!=null) { for (int i=_connectors.length;i-->0;) try{_connectors[i].stop();}catch(Throwable e){mex.add(e);} } try {super.doStop(); } catch(Throwable e) { mex.add(e);} mex.ifExceptionThrow(); if (getStopAtShutdown()) ShutdownThread.deregister(this); } /* ------------------------------------------------------------ */ /* Handle a request from a connection. * Called to handle a request on the connection when either the header has been received, * or after the entire request has been received (for short requests of known length), or * on the dispatch of an async request. */ public void handle(AbstractHttpConnection connection) throws IOException, ServletException { final String target=connection.getRequest().getPathInfo(); final Request request=connection.getRequest(); final Response response=connection.getResponse(); if (LOG.isDebugEnabled()) { LOG.debug("REQUEST "+target+" on "+connection); handle(target, request, request, response); LOG.debug("RESPONSE "+target+" "+connection.getResponse().getStatus()); } else handle(target, request, request, response); } /* ------------------------------------------------------------ */ /* Handle a request from a connection. * Called to handle a request on the connection when either the header has been received, * or after the entire request has been received (for short requests of known length), or * on the dispatch of an async request. */ public void handleAsync(AbstractHttpConnection connection) throws IOException, ServletException { final AsyncContinuation async = connection.getRequest().getAsyncContinuation(); final AsyncContinuation.AsyncEventState state = async.getAsyncEventState(); final Request baseRequest=connection.getRequest(); final String path=state.getPath(); if (path!=null) { // this is a dispatch with a path final String contextPath=state.getServletContext().getContextPath(); HttpURI uri = new HttpURI(URIUtil.addPaths(contextPath,path)); baseRequest.setUri(uri); baseRequest.setRequestURI(null); baseRequest.setPathInfo(baseRequest.getRequestURI()); if (uri.getQuery()!=null) baseRequest.mergeQueryString(uri.getQuery()); } final String target=baseRequest.getPathInfo(); final HttpServletRequest request=(HttpServletRequest)async.getRequest(); final HttpServletResponse response=(HttpServletResponse)async.getResponse(); if (LOG.isDebugEnabled()) { LOG.debug("REQUEST "+target+" on "+connection); handle(target, baseRequest, request, response); LOG.debug("RESPONSE "+target+" "+connection.getResponse().getStatus()); } else handle(target, baseRequest, request, response); } /* ------------------------------------------------------------ */ public void join() throws InterruptedException { getThreadPool().join(); } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ /** * @return Returns the sessionIdManager. */ public SessionIdManager getSessionIdManager() { return _sessionIdManager; } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ /** * @param sessionIdManager The sessionIdManager to set. */ public void setSessionIdManager(SessionIdManager sessionIdManager) { if (_sessionIdManager!=null) removeBean(_sessionIdManager); _container.update(this, _sessionIdManager, sessionIdManager, "sessionIdManager",false); _sessionIdManager = sessionIdManager; if (_sessionIdManager!=null) addBean(_sessionIdManager); } /* ------------------------------------------------------------ */ public void setSendServerVersion (boolean sendServerVersion) { _sendServerVersion = sendServerVersion; } /* ------------------------------------------------------------ */ public boolean getSendServerVersion() { return _sendServerVersion; } /* ------------------------------------------------------------ */ /** * @param sendDateHeader */ public void setSendDateHeader(boolean sendDateHeader) { _sendDateHeader = sendDateHeader; } /* ------------------------------------------------------------ */ public boolean getSendDateHeader() { return _sendDateHeader; } /* ------------------------------------------------------------ */ /** Get the maximum cookie version. * @return the maximum set-cookie version sent by this server */ public int getMaxCookieVersion() { return _maxCookieVersion; } /* ------------------------------------------------------------ */ /** Set the maximum cookie version. * @param maxCookieVersion the maximum set-cookie version sent by this server */ public void setMaxCookieVersion(int maxCookieVersion) { _maxCookieVersion = maxCookieVersion; } /* ------------------------------------------------------------ */ /** * Add a LifeCycle object to be started/stopped * along with the Server. * @deprecated Use {@link #addBean(Object)} * @param c */ @Deprecated public void addLifeCycle (LifeCycle c) { addBean(c); } /* ------------------------------------------------------------ */ /** * Add an associated bean. * The bean will be added to the servers {@link Container} * and if it is a {@link LifeCycle} instance, it will be * started/stopped along with the Server. Any beans that are also * {@link Destroyable}, will be destroyed with the server. * @param o the bean object to add */ @Override public boolean addBean(Object o) { if (super.addBean(o)) { _container.addBean(o); return true; } return false; } /** * Remove a LifeCycle object to be started/stopped * along with the Server * @deprecated Use {@link #removeBean(Object)} */ @Deprecated public void removeLifeCycle (LifeCycle c) { removeBean(c); } /* ------------------------------------------------------------ */ /** * Remove an associated bean. */ @Override public boolean removeBean (Object o) { if (super.removeBean(o)) { _container.removeBean(o); return true; } return false; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.util.AttributesMap#clearAttributes() */ public void clearAttributes() { _attributes.clearAttributes(); } /* ------------------------------------------------------------ */ /* * @see org.eclipse.util.AttributesMap#getAttribute(java.lang.String) */ public Object getAttribute(String name) { return _attributes.getAttribute(name); } /* ------------------------------------------------------------ */ /* * @see org.eclipse.util.AttributesMap#getAttributeNames() */ public Enumeration getAttributeNames() { return AttributesMap.getAttributeNamesCopy(_attributes); } /* ------------------------------------------------------------ */ /* * @see org.eclipse.util.AttributesMap#removeAttribute(java.lang.String) */ public void removeAttribute(String name) { _attributes.removeAttribute(name); } /* ------------------------------------------------------------ */ /* * @see org.eclipse.util.AttributesMap#setAttribute(java.lang.String, java.lang.Object) */ public void setAttribute(String name, Object attribute) { _attributes.setAttribute(name, attribute); } /* ------------------------------------------------------------ */ /** * @return the graceful */ public int getGracefulShutdown() { return _graceful; } /* ------------------------------------------------------------ */ /** * Set graceful shutdown timeout. If set, the internal <code>doStop()</code> method will not immediately stop the * server. Instead, all {@link Connector}s will be closed so that new connections will not be accepted * and all handlers that implement {@link Graceful} will be put into the shutdown mode so that no new requests * will be accepted, but existing requests can complete. The server will then wait the configured timeout * before stopping. * @param timeoutMS the milliseconds to wait for existing request to complete before stopping the server. * */ public void setGracefulShutdown(int timeoutMS) { _graceful=timeoutMS; } /* ------------------------------------------------------------ */ @Override public String toString() { return this.getClass().getName()+"@"+Integer.toHexString(hashCode()); } /* ------------------------------------------------------------ */ @Override public void dump(Appendable out,String indent) throws IOException { dumpThis(out); dump(out,indent,TypeUtil.asList(getHandlers()),getBeans(),TypeUtil.asList(_connectors)); } /* ------------------------------------------------------------ */ public boolean isUncheckedPrintWriter() { return _uncheckedPrintWriter; } /* ------------------------------------------------------------ */ public void setUncheckedPrintWriter(boolean unchecked) { _uncheckedPrintWriter=unchecked; } /* ------------------------------------------------------------ */ /* A handler that can be gracefully shutdown. * Called by doStop if a {@link #setGracefulShutdown} period is set. * TODO move this somewhere better */ public interface Graceful extends Handler { public void setShutdown(boolean shutdown); } /* ------------------------------------------------------------ */ public static void main(String...args) throws Exception { System.err.println(getVersion()); } }
jetty-project/jetty-plugin-support
jetty-server/src/main/java/org/eclipse/jetty/server/Server.java
Java
apache-2.0
20,772
/* * Copyright 2014 Google Inc. All Rights Reserved. * * 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.google.cloud.bigtable.hbase; import static com.google.cloud.bigtable.hbase.IntegrationTests.*; import org.apache.commons.lang.ArrayUtils; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CellUtil; import org.apache.hadoop.hbase.client.Append; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Table; import org.junit.Assert; import org.junit.Test; import java.util.List; public class TestAppend extends AbstractTest { /** * Requirement 5.1 - Append values to one or more columns within a single row. */ @Test public void testAppend() throws Exception { // Initialize Table table = getConnection().getTable(TABLE_NAME); byte[] rowKey = dataHelper.randomData("rowKey-"); byte[] qualifier = dataHelper.randomData("qualifier-"); byte[] value1 = dataHelper.randomData("value1-"); byte[] value2 = dataHelper.randomData("value1-"); byte[] value1And2 = ArrayUtils.addAll(value1, value2); // Put then append Put put = new Put(rowKey).addColumn(COLUMN_FAMILY, qualifier, value1); table.put(put); Append append = new Append(rowKey).add(COLUMN_FAMILY, qualifier, value2); Result result = table.append(append); Cell cell = result.getColumnLatestCell(COLUMN_FAMILY, qualifier); Assert.assertArrayEquals("Expect concatenated byte array", value1And2, CellUtil.cloneValue(cell)); // Test result Get get = new Get(rowKey).addColumn(COLUMN_FAMILY, qualifier); get.setMaxVersions(5); result = table.get(get); Assert.assertEquals("There should be two versions now", 2, result.size()); List<Cell> cells = result.getColumnCells(COLUMN_FAMILY, qualifier); Assert.assertArrayEquals("Expect concatenated byte array", value1And2, CellUtil.cloneValue(cells.get(0))); Assert.assertArrayEquals("Expect original value still there", value1, CellUtil.cloneValue(cells.get(1))); } @Test public void testAppendToEmptyCell() throws Exception { // Initialize Table table = getConnection().getTable(TABLE_NAME); byte[] rowKey = dataHelper.randomData("rowKey-"); byte[] qualifier = dataHelper.randomData("qualifier-"); byte[] value = dataHelper.randomData("value1-"); // Put then append Append append = new Append(rowKey).add(COLUMN_FAMILY, qualifier, value); table.append(append); // Test result Get get = new Get(rowKey).addColumn(COLUMN_FAMILY, qualifier); get.setMaxVersions(5); Result result = table.get(get); Assert.assertEquals("There should be one version now", 1, result.size()); Cell cell = result.getColumnLatestCell(COLUMN_FAMILY, qualifier); Assert.assertArrayEquals("Expect append value is entire value", value, CellUtil.cloneValue(cell)); } @Test public void testAppendNoResult() throws Exception { // Initialize Table table = getConnection().getTable(TABLE_NAME); byte[] rowKey = dataHelper.randomData("rowKey-"); byte[] qual = dataHelper.randomData("qualifier-"); byte[] value1 = dataHelper.randomData("value-"); byte[] value2 = dataHelper.randomData("value-"); // Put then append Put put = new Put(rowKey).addColumn(COLUMN_FAMILY, qual, value1); table.put(put); Append append = new Append(rowKey).add(COLUMN_FAMILY, qual, value2); append.setReturnResults(false); Result result = table.append(append); Assert.assertNull("Should not return result", result); } }
dmmcerlean/cloud-bigtable-client
bigtable-hbase-integration-tests/src/test/java/com/google/cloud/bigtable/hbase/TestAppend.java
Java
apache-2.0
4,163
/* * 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.activemq.artemis.api.core.client; import java.net.URI; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration; import org.apache.activemq.artemis.api.core.ActiveMQInterruptedException; import org.apache.activemq.artemis.api.core.DiscoveryGroupConfiguration; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.client.loadbalance.RoundRobinConnectionLoadBalancingPolicy; import org.apache.activemq.artemis.core.client.ActiveMQClientLogger; import org.apache.activemq.artemis.core.client.impl.ClientSessionFactoryImpl; import org.apache.activemq.artemis.core.client.impl.ServerLocatorImpl; import org.apache.activemq.artemis.uri.ServerLocatorParser; import org.apache.activemq.artemis.utils.ActiveMQThreadFactory; import org.apache.activemq.artemis.utils.ActiveMQThreadPoolExecutor; /** * Utility class for creating ActiveMQ Artemis {@link ClientSessionFactory} objects. * <p> * Once a {@link ClientSessionFactory} has been created, it can be further configured using its * setter methods before creating the sessions. Once a session is created, the factory can no longer * be modified (its setter methods will throw a {@link IllegalStateException}. */ public final class ActiveMQClient { private static int globalThreadPoolSize; private static int globalScheduledThreadPoolSize; public static final String DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME = RoundRobinConnectionLoadBalancingPolicy.class.getCanonicalName(); public static final long DEFAULT_CLIENT_FAILURE_CHECK_PERIOD = ActiveMQDefaultConfiguration.getDefaultClientFailureCheckPeriod(); public static final long DEFAULT_CLIENT_FAILURE_CHECK_PERIOD_INVM = -1; // 1 minute - this should be higher than ping period public static final long DEFAULT_CONNECTION_TTL = ActiveMQDefaultConfiguration.getDefaultConnectionTtl(); public static final long DEFAULT_CONNECTION_TTL_INVM = -1; // Any message beyond this size is considered a large message (to be sent in chunks) public static final int DEFAULT_MIN_LARGE_MESSAGE_SIZE = 100 * 1024; public static final boolean DEFAULT_COMPRESS_LARGE_MESSAGES = false; public static final int DEFAULT_CONSUMER_WINDOW_SIZE = 1024 * 1024; public static final int DEFAULT_CONSUMER_MAX_RATE = -1; public static final int DEFAULT_CONFIRMATION_WINDOW_SIZE = -1; public static final int DEFAULT_PRODUCER_WINDOW_SIZE = 64 * 1024; public static final int DEFAULT_PRODUCER_MAX_RATE = -1; public static final boolean DEFAULT_BLOCK_ON_ACKNOWLEDGE = false; public static final boolean DEFAULT_BLOCK_ON_DURABLE_SEND = true; public static final boolean DEFAULT_BLOCK_ON_NON_DURABLE_SEND = false; public static final boolean DEFAULT_AUTO_GROUP = false; public static final long DEFAULT_CALL_TIMEOUT = 30000; public static final long DEFAULT_CALL_FAILOVER_TIMEOUT = 30000; public static final int DEFAULT_ACK_BATCH_SIZE = 1024 * 1024; public static final boolean DEFAULT_PRE_ACKNOWLEDGE = false; public static final long DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT = 10000; public static final long DEFAULT_DISCOVERY_REFRESH_TIMEOUT = 10000; public static final int DEFAULT_DISCOVERY_PORT = 9876; public static final long DEFAULT_RETRY_INTERVAL = 2000; public static final double DEFAULT_RETRY_INTERVAL_MULTIPLIER = ActiveMQDefaultConfiguration.getDefaultRetryIntervalMultiplier(); public static final long DEFAULT_MAX_RETRY_INTERVAL = ActiveMQDefaultConfiguration.getDefaultMaxRetryInterval(); public static final int DEFAULT_RECONNECT_ATTEMPTS = 0; public static final int INITIAL_CONNECT_ATTEMPTS = 1; public static final boolean DEFAULT_FAILOVER_ON_INITIAL_CONNECTION = false; public static final boolean DEFAULT_IS_HA = false; public static final boolean DEFAULT_USE_GLOBAL_POOLS = true; public static final int DEFAULT_THREAD_POOL_MAX_SIZE = -1; public static final int DEFAULT_GLOBAL_THREAD_POOL_MAX_SIZE = 8 * Runtime.getRuntime().availableProcessors(); public static final int DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE = 5; public static final boolean DEFAULT_CACHE_LARGE_MESSAGE_CLIENT = false; public static final int DEFAULT_INITIAL_MESSAGE_PACKET_SIZE = 1500; public static final boolean DEFAULT_XA = false; public static final boolean DEFAULT_HA = false; public static final String DEFAULT_CORE_PROTOCOL = "CORE"; public static final String THREAD_POOL_MAX_SIZE_PROPERTY_KEY = "activemq.artemis.client.global.thread.pool.max.size"; public static final String SCHEDULED_THREAD_POOL_SIZE_PROPERTY_KEY = "activemq.artemis.client.global.scheduled.thread.pool.core.size"; private static ExecutorService globalThreadPool; private static boolean injectedPools = false; private static ScheduledExecutorService globalScheduledThreadPool; static { initializeGlobalThreadPoolProperties(); } public static synchronized void clearThreadPools() { clearThreadPools(10, TimeUnit.SECONDS); } public static synchronized void clearThreadPools(long time, TimeUnit unit) { if (injectedPools) { globalThreadPool = null; globalScheduledThreadPool = null; injectedPools = false; return; } if (globalThreadPool != null) { globalThreadPool.shutdown(); try { if (!globalThreadPool.awaitTermination(time, unit)) { globalThreadPool.shutdownNow(); ActiveMQClientLogger.LOGGER.warn("Couldn't finish the client globalThreadPool in less than 10 seconds, interrupting it now"); } } catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } finally { globalThreadPool = null; } } if (globalScheduledThreadPool != null) { globalScheduledThreadPool.shutdown(); try { if (!globalScheduledThreadPool.awaitTermination(time, unit)) { globalScheduledThreadPool.shutdownNow(); ActiveMQClientLogger.LOGGER.warn("Couldn't finish the client scheduled in less than 10 seconds, interrupting it now"); } } catch (InterruptedException e) { throw new ActiveMQInterruptedException(e); } finally { globalScheduledThreadPool = null; } } } /** * Warning: This method has to be called before any clients or servers is started on the JVM otherwise previous ServerLocator would be broken after this call. */ public static synchronized void injectPools(ExecutorService globalThreadPool, ScheduledExecutorService scheduledThreadPool) { if (globalThreadPool == null || scheduledThreadPool == null) throw new IllegalArgumentException("thread pools must not be null"); // We call clearThreadPools as that will shutdown any previously used executor clearThreadPools(); ActiveMQClient.globalThreadPool = globalThreadPool; ActiveMQClient.globalScheduledThreadPool = scheduledThreadPool; injectedPools = true; } public static synchronized ExecutorService getGlobalThreadPool() { if (globalThreadPool == null) { ThreadFactory factory = AccessController.doPrivileged(new PrivilegedAction<ThreadFactory>() { @Override public ThreadFactory run() { return new ActiveMQThreadFactory("ActiveMQ-client-global-threads", true, ClientSessionFactoryImpl.class.getClassLoader()); } }); if (globalThreadPoolSize == -1) { globalThreadPool = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), factory); } else { globalThreadPool = new ActiveMQThreadPoolExecutor(0, ActiveMQClient.globalThreadPoolSize, 60L, TimeUnit.SECONDS, factory); } } return globalThreadPool; } public static synchronized ScheduledExecutorService getGlobalScheduledThreadPool() { if (globalScheduledThreadPool == null) { ThreadFactory factory = AccessController.doPrivileged(new PrivilegedAction<ThreadFactory>() { @Override public ThreadFactory run() { return new ActiveMQThreadFactory("ActiveMQ-client-global-scheduled-threads", true, ClientSessionFactoryImpl.class.getClassLoader()); } }); globalScheduledThreadPool = new ScheduledThreadPoolExecutor(ActiveMQClient.globalScheduledThreadPoolSize, factory); } return globalScheduledThreadPool; } public static int getGlobalThreadPoolSize() { return globalThreadPoolSize; } public static int getGlobalScheduledThreadPoolSize() { return globalScheduledThreadPoolSize; } /** * Initializes the global thread pools properties from System properties. This method will update the global * thread pool configuration based on defined System properties (or defaults if they are not set). * The System properties key names are as follow: * * ActiveMQClient.THREAD_POOL_MAX_SIZE_PROPERTY_KEY="activemq.artemis.client.global.thread.pool.max.size" * ActiveMQClient.SCHEDULED_THREAD_POOL_SIZE_PROPERTY_KEY="activemq.artemis.client.global.scheduled.thread.pool.core.size * * The min value for max thread pool size is 2. If the value is not -1, but lower than 2, it will be ignored and will default to 2. * A value of -1 configures an unbounded thread pool. * * Note: If global thread pools have already been created, they will not be updated with these new values. */ public static void initializeGlobalThreadPoolProperties() { setGlobalThreadPoolProperties(Integer.valueOf(System.getProperty(ActiveMQClient.THREAD_POOL_MAX_SIZE_PROPERTY_KEY, "" + ActiveMQClient.DEFAULT_GLOBAL_THREAD_POOL_MAX_SIZE)), Integer.valueOf(System.getProperty(ActiveMQClient.SCHEDULED_THREAD_POOL_SIZE_PROPERTY_KEY, "" + ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE))); } /** * Allows programmatical configuration of global thread pools properties. This method will update the global * thread pool configuration based on the provided values notifying all globalThreadPoolListeners. * * Note: If global thread pools have already been created, they will not be updated with these new values. * * The min value for globalThreadMaxPoolSize is 2. If the value is not -1, but lower than 2, it will be ignored and will default to 2. * A value of -1 configures an unbounded thread pool. */ public static void setGlobalThreadPoolProperties(int globalThreadMaxPoolSize, int globalScheduledThreadPoolSize) { if (globalThreadMaxPoolSize < 2 && globalThreadMaxPoolSize != -1) globalThreadMaxPoolSize = 2; ActiveMQClient.globalScheduledThreadPoolSize = globalScheduledThreadPoolSize; ActiveMQClient.globalThreadPoolSize = globalThreadMaxPoolSize; } /** * Creates an ActiveMQConnectionFactory; * * @return the ActiveMQConnectionFactory */ public static ServerLocator createServerLocator(final String url) throws Exception { ServerLocatorParser parser = new ServerLocatorParser(); return parser.newObject(new URI(url), null); } /** * Create a ServerLocator which creates session factories using a static list of transportConfigurations, the ServerLocator is not updated automatically * as the cluster topology changes, and no HA backup information is propagated to the client * * @param transportConfigurations * @return the ServerLocator */ public static ServerLocator createServerLocatorWithoutHA(TransportConfiguration... transportConfigurations) { return new ServerLocatorImpl(false, transportConfigurations); } /** * Create a ServerLocator which creates session factories using a static list of transportConfigurations, the ServerLocator is not updated automatically * as the cluster topology changes, and no HA backup information is propagated to the client * * @param ha The Locator will support topology updates and ha (this required the server to be clustered, otherwise the first connection will timeout) * @param transportConfigurations * @return the ServerLocator */ public static ServerLocator createServerLocator(final boolean ha, TransportConfiguration... transportConfigurations) { return new ServerLocatorImpl(ha, transportConfigurations); } /** * Create a ServerLocator which creates session factories from a set of live servers, no HA * backup information is propagated to the client * <p> * The UDP address and port are used to listen for live servers in the cluster * * @param groupConfiguration * @return the ServerLocator */ public static ServerLocator createServerLocatorWithoutHA(final DiscoveryGroupConfiguration groupConfiguration) { return new ServerLocatorImpl(false, groupConfiguration); } /** * Create a ServerLocator which creates session factories from a set of live servers, no HA * backup information is propagated to the client The UDP address and port are used to listen for * live servers in the cluster * * @param ha The Locator will support topology updates and ha (this required the server to be * clustered, otherwise the first connection will timeout) * @param groupConfiguration * @return the ServerLocator */ public static ServerLocator createServerLocator(final boolean ha, final DiscoveryGroupConfiguration groupConfiguration) { return new ServerLocatorImpl(ha, groupConfiguration); } /** * Create a ServerLocator which will receive cluster topology updates from the cluster as servers * leave or join and new backups are appointed or removed. * <p> * The initial list of servers supplied in this method is simply to make an initial connection to * the cluster, once that connection is made, up to date cluster topology information is * downloaded and automatically updated whenever the cluster topology changes. * <p> * If the topology includes backup servers that information is also propagated to the client so * that it can know which server to failover onto in case of live server failure. * * @param initialServers The initial set of servers used to make a connection to the cluster. * Each one is tried in turn until a successful connection is made. Once a connection * is made, the cluster topology is downloaded and the rest of the list is ignored. * @return the ServerLocator */ public static ServerLocator createServerLocatorWithHA(TransportConfiguration... initialServers) { return new ServerLocatorImpl(true, initialServers); } /** * Create a ServerLocator which will receive cluster topology updates from the cluster as servers * leave or join and new backups are appointed or removed. * <p> * The discoveryAddress and discoveryPort parameters in this method are used to listen for UDP * broadcasts which contain connection information for members of the cluster. The broadcasted * connection information is simply used to make an initial connection to the cluster, once that * connection is made, up to date cluster topology information is downloaded and automatically * updated whenever the cluster topology changes. * <p> * If the topology includes backup servers that information is also propagated to the client so * that it can know which server to failover onto in case of live server failure. * * @param groupConfiguration * @return the ServerLocator */ public static ServerLocator createServerLocatorWithHA(final DiscoveryGroupConfiguration groupConfiguration) { return new ServerLocatorImpl(true, groupConfiguration); } private ActiveMQClient() { // Utility class } }
paulgallagher75/activemq-artemis
artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ActiveMQClient.java
Java
apache-2.0
17,476
/** * */ package org.minnal.core.server; import io.netty.channel.ChannelPipeline; import io.netty.handler.ssl.SslHandler; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.KeyStore; import java.security.Security; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import org.minnal.core.MinnalException; import org.minnal.core.Router; import org.minnal.core.config.ConnectorConfiguration; import org.minnal.core.config.SSLConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author ganeshs * */ public class HttpsConnector extends AbstractHttpConnector { private static final Logger logger = LoggerFactory.getLogger(HttpsConnector.class); /** * @param configuration * @param router */ public HttpsConnector(ConnectorConfiguration configuration, Router router) { super(configuration, router); if (configuration.getSslConfiguration() == null) { logger.error("SSL configuration is missing for https connector"); throw new MinnalException("SSL configuration is missing for https scheme"); } } @Override protected void addChannelHandlers(ChannelPipeline pipeline) { logger.debug("Adding ssl handler to the pipeline"); SSLEngine engine = createSslEngine(); engine.setUseClientMode(false); pipeline.addFirst("ssl", new SslHandler(engine)); } /** * @return */ protected SSLEngine createSslEngine() { logger.debug("Creating a SSL engine from the SSL context"); String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm"); if (algorithm == null) { algorithm = "SunX509"; logger.trace("ssl.KeyManagerFactory.algorithm algorithm is not set. Defaulting to {}", algorithm); } SSLContext serverContext = null; SSLConfiguration configuration = getConnectorConfiguration().getSslConfiguration(); InputStream stream = null; try { File file = new File(configuration.getKeyStoreFile()); stream = new FileInputStream(file); KeyStore ks = KeyStore.getInstance(configuration.getKeystoreType()); ks.load(stream, configuration.getKeyStorePassword().toCharArray()); // Set up key manager factory to use our key store KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm); kmf.init(ks, configuration.getKeyPassword().toCharArray()); // Initialize the SSLContext to work with our key managers. serverContext = SSLContext.getInstance(configuration.getProtocol()); serverContext.init(kmf.getKeyManagers(), null, null); } catch (Exception e) { logger.error("Failed while initializing the ssl context", e); throw new MinnalException("Failed to initialize the ssl context", e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { logger.trace("Failed while closing the stream", e); } } } return serverContext.createSSLEngine(); } }
minnal/minnal
minnal-core/src/main/java/org/minnal/core/server/HttpsConnector.java
Java
apache-2.0
2,969
package com.fishercoder.solutions; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; /** * 729. My Calendar I * * Implement a MyCalendar class to store your events. A new event can be added if adding the event will not cause a double booking. * Your class will have the method, book(int start, int end). * Formally, this represents a booking on the half open interval [start, end), * the range of real numbers x such that start <= x < end. * A double booking happens when two events have some non-empty intersection (ie., there is some time that is common to both events.) * For each call to the method MyCalendar.book, * return true if the event can be added to the calendar successfully without causing a double booking. * Otherwise, return false and do not add the event to the calendar. Your class will be called like this: MyCalendar cal = new MyCalendar(); MyCalendar.book(start, end) Example 1: MyCalendar(); MyCalendar.book(10, 20); // returns true MyCalendar.book(15, 25); // returns false MyCalendar.book(20, 30); // returns true Explanation: The first event can be booked. The second can't because time 15 is already booked by another event. The third event can be booked, as the first event takes every time less than 20, but not including 20. Note: The number of calls to MyCalendar.book per test case will be at most 1000. In calls to MyCalendar.book(start, end), start and end are integers in the range [0, 10^9]. */ public class _729 { public static class Solution1 { /** * credit: https://discuss.leetcode.com/topic/111205/java-8-liner-treemap */ public static class MyCalendar { TreeMap<Integer, Integer> calendar; public MyCalendar() { calendar = new TreeMap<>(); } public boolean book(int start, int end) { Integer floorKey = calendar.floorKey(start); if (floorKey != null && calendar.get(floorKey) > start) { return false; } Integer ceilingKey = calendar.ceilingKey(start); if (ceilingKey != null && ceilingKey < end) { return false; } calendar.put(start, end); return true; } } } public static class Solution2 { public class MyCalendar { List<int[]> calendar; MyCalendar() { calendar = new ArrayList(); } public boolean book(int start, int end) { for (int i = 0; i < calendar.size(); i++) { if (calendar.get(i)[0] < end && start < calendar.get(i)[1]) { return false; } } calendar.add(new int[]{start, end}); return true; } } } }
cy19890513/Leetcode-1
src/main/java/com/fishercoder/solutions/_729.java
Java
apache-2.0
2,937
/* ### * IP: GHIDRA * * 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 ghidra.framework.main.datatree; import java.awt.*; import java.awt.datatransfer.Transferable; import java.awt.dnd.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.swing.*; import javax.swing.event.ListSelectionListener; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import docking.ActionContext; import docking.action.*; import docking.dnd.*; import docking.widgets.OptionDialog; import docking.widgets.table.*; import ghidra.app.util.GenericHelpTopics; import ghidra.framework.client.ClientUtil; import ghidra.framework.main.GetVersionedObjectTask; import ghidra.framework.model.*; import ghidra.framework.plugintool.PluginTool; import ghidra.framework.store.ItemCheckoutStatus; import ghidra.framework.store.Version; import ghidra.util.*; import ghidra.util.task.*; /** * Panel that shows version history in a JTable */ public class VersionHistoryPanel extends JPanel implements Draggable { private static final HelpLocation HELP = new HelpLocation(GenericHelpTopics.VERSION_CONTROL, "Show History"); private PluginTool tool; private DomainFile domainFile; private String domainFilePath; private VersionHistoryTableModel tableModel; private GTable table; private DragSource dragSource; private DragGestureAdapter dragGestureAdapter; private DragSrcAdapter dragSourceAdapter; private int dragAction = DnDConstants.ACTION_COPY_OR_MOVE; /** * Constructor * @param tool tool * @param domainFile domain file; may be null * @throws IOException if there was a problem accessing the * version history */ public VersionHistoryPanel(PluginTool tool, DomainFile domainFile) throws IOException { this(tool, domainFile, false); } /** * Constructor * @param tool tool * @param domainFile domain file * @param enableUserInteraction if true Draggable support will be enabled */ VersionHistoryPanel(PluginTool tool, DomainFile domainFile, boolean enableUserInteraction) { super(new BorderLayout()); this.tool = tool; create(); if (enableUserInteraction) { setUpDragSite(); table.addMouseListener(new MyMouseListener()); } setDomainFile(domainFile); } /** * Set the domain file to show its history * @param domainFile the file */ public void setDomainFile(DomainFile domainFile) { this.domainFile = domainFile; if (domainFile != null) { this.domainFilePath = domainFile.getPathname(); } refresh(); } /** * Get current domain file * @return current domain file */ public DomainFile getDomainFile() { return domainFile; } /** * Get current domain file path or null * @return domain file path */ public String getDomainFilePath() { return domainFilePath; } /** * Add the list selection listener to the history table * @param selectionListener the listener */ public void addListSelectionListener(ListSelectionListener selectionListener) { table.getSelectionModel().addListSelectionListener(selectionListener); } /** * Remove the list selection listener from history table. * @param selectionListener the listener */ public void removeListSelectionListener(ListSelectionListener selectionListener) { table.getSelectionModel().removeListSelectionListener(selectionListener); } /** * Get the domain object for the selected version. * @param consumer the consumer * @param readOnly true if read only * @return null if there is no selection */ public DomainObject getSelectedVersion(Object consumer, boolean readOnly) { int row = table.getSelectedRow(); if (row >= 0) { Version version = tableModel.getVersionAt(row); return getVersionedObject(consumer, version.getVersion(), readOnly); } return null; } public boolean isVersionSelected() { return !table.getSelectionModel().isSelectionEmpty(); } public int getSelectedVersionNumber() { int row = table.getSelectedRow(); if (row >= 0) { Version version = tableModel.getVersionAt(row); return version.getVersion(); } return -1; } @Override public void dragCanceled(DragSourceDropEvent event) { // no-op } @Override public int getDragAction() { return dragAction; } @Override public DragSourceListener getDragSourceListener() { return dragSourceAdapter; } @Override public Transferable getTransferable(Point p) { int row = table.rowAtPoint(p); if (row >= 0) { Version version = tableModel.getVersionAt(row); return new VersionInfoTransferable(domainFile.getPathname(), version.getVersion()); } return null; } @Override public boolean isStartDragOk(DragGestureEvent e) { int row = table.rowAtPoint(e.getDragOrigin()); if (row >= 0) { return true; } return false; } @Override public void move() { // no-op } // For Junit tests VersionHistoryTableModel getVersionHistoryTableModel() { return tableModel; } private void create() { tableModel = new VersionHistoryTableModel(new Version[0]); table = new GTable(tableModel); JScrollPane sp = new JScrollPane(table); table.setPreferredScrollableViewportSize(new Dimension(600, 120)); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); add(sp, BorderLayout.CENTER); TableColumnModel columnModel = table.getColumnModel(); MyCellRenderer cellRenderer = new MyCellRenderer(); for (int i = 0; i < columnModel.getColumnCount(); i++) { TableColumn column = columnModel.getColumn(i); GTableHeaderRenderer headRenderer = new GTableHeaderRenderer(); column.setHeaderRenderer(headRenderer); column.setCellRenderer(cellRenderer); String name = (String) column.getIdentifier(); if (name.equals(VersionHistoryTableModel.VERSION)) { column.setPreferredWidth(80); } else if (name.equals(VersionHistoryTableModel.DATE)) { column.setPreferredWidth(210); } else if (name.equals(VersionHistoryTableModel.COMMENTS)) { column.setPreferredWidth(250); } else if (name.equals(VersionHistoryTableModel.USER)) { column.setPreferredWidth(125); } } } /** * Set up the drag and drop stuff. */ private void setUpDragSite() { // set up drag stuff dragSource = DragSource.getDefaultDragSource(); dragGestureAdapter = new DragGestureAdapter(this); dragSourceAdapter = new DragSrcAdapter(this); dragSource.createDefaultDragGestureRecognizer(table, dragAction, dragGestureAdapter); } private DomainObject getVersionedObject(Object consumer, int versionNumber, boolean readOnly) { GetVersionedObjectTask task = new GetVersionedObjectTask(consumer, domainFile, versionNumber, readOnly); tool.execute(task, 1000); return task.getVersionedObject(); } private void delete() { int row = table.getSelectedRow(); if (row != 0 && row != tableModel.getRowCount() - 1) { Msg.showError(this, this, "Cannot Delete Version", "Only first and last version may be deleted."); return; } Version version = tableModel.getVersionAt(row); try { for (ItemCheckoutStatus status : domainFile.getCheckouts()) { if (status.getCheckoutVersion() == version.getVersion()) { Msg.showError(this, this, "Cannot Delete Version", "File version has one or more checkouts."); return; } } if (confirmDelete()) { DeleteTask task = new DeleteTask(version.getVersion()); new TaskLauncher(task, this); } } catch (IOException e) { ClientUtil.handleException(tool.getProject().getRepository(), e, "Delete Version", this); } } private boolean confirmDelete() { String message; int messageType; if (tableModel.getRowCount() == 1) { message = "Deleting the only version will permanently delete the file.\n" + "Are you sure you want to continue?"; messageType = OptionDialog.WARNING_MESSAGE; } else { message = "Are you sure you want to delete the selected version?"; messageType = OptionDialog.QUESTION_MESSAGE; } return OptionDialog.showOptionDialog(table, "Delete Version", message, "Delete", messageType) == OptionDialog.OPTION_ONE; } void refresh() { try { Version[] history = null; if (domainFile != null) { history = domainFile.getVersionHistory(); } if (history == null) { history = new Version[0]; } tableModel.refresh(history); } catch (IOException e) { ClientUtil.handleException(tool.getProject().getRepository(), e, "Get Version History", this); } } private void openWith(String toolName) { int row = table.getSelectedRow(); Version version = tableModel.getVersionAt(row); DomainObject versionedObj = getVersionedObject(this, version.getVersion(), true); if (versionedObj != null) { if (toolName != null) { tool.getToolServices().launchTool(toolName, versionedObj.getDomainFile()); } else { tool.getToolServices().launchDefaultTool(versionedObj.getDomainFile()); } versionedObj.release(this); } } private void open() { openWith(null); } public List<DockingActionIf> createPopupActions() { List<DockingActionIf> list = new ArrayList<>(); list.add(new DeleteAction()); Project project = tool.getProject(); ToolChest toolChest = project.getLocalToolChest(); if (toolChest == null) { return list; } ToolTemplate[] templates = toolChest.getToolTemplates(); if (templates.length == 0) { return list; } list.add(new OpenDefaultAction()); for (ToolTemplate toolTemplate : templates) { list.add(new OpenWithAction(toolTemplate.getName())); } return list; } GTable getTable() { return table; } //================================================================================================== // Inner Classes //================================================================================================== private class MyCellRenderer extends GTableCellRenderer { @Override public Component getTableCellRendererComponent(GTableCellRenderingData data) { super.getTableCellRendererComponent(data); Object value = data.getValue(); int row = data.getRowViewIndex(); int col = data.getColumnModelIndex(); if (value instanceof Date) { setText(DateUtils.formatDateTimestamp((Date) value)); } setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); String toolTipText = null; Version version = tableModel.getVersionAt(row); if (col == VersionHistoryTableModel.COMMENTS_COL) { String comments = version.getComment(); if (comments != null) { toolTipText = HTMLUtilities.toHTML(comments); } } else if (col == VersionHistoryTableModel.DATE_COL) { toolTipText = "Date when version was created"; } setToolTipText(toolTipText); return this; } } private abstract class HistoryTableAction extends DockingAction { HistoryTableAction(String name) { super(name, "Version History Panel", false); setHelpLocation(HELP); } @Override public boolean isEnabledForContext(ActionContext context) { MouseEvent mouseEvent = context.getMouseEvent(); if (mouseEvent == null) { return false; } if (context.getSourceComponent() != table) { return false; } if (domainFile == null) { return false; } int rowAtPoint = table.rowAtPoint(mouseEvent.getPoint()); return rowAtPoint >= 0; } } private class DeleteAction extends HistoryTableAction { DeleteAction() { super("Delete Version"); setDescription( "Deletes the selected version (Only first and last version can be deleted)"); setPopupMenuData(new MenuData(new String[] { "Delete" }, "AAA")); } @Override public void actionPerformed(ActionContext context) { delete(); } } private class OpenDefaultAction extends HistoryTableAction { OpenDefaultAction() { super("Open In Default Tool"); setDescription("Opens the selected version in the default tool."); MenuData data = new MenuData(new String[] { "Open in Default Tool" }, "AAB"); data.setMenuSubGroup("1"); // before the specific tool 'open' actions setPopupMenuData(data); } @Override public void actionPerformed(ActionContext context) { open(); } } private class OpenWithAction extends HistoryTableAction { private String toolName; OpenWithAction(String toolName) { super("Open With " + toolName); this.toolName = toolName; setDescription("Opens the version using the " + toolName + " tool."); MenuData data = new MenuData(new String[] { "Open With", toolName }, "AAB"); setPopupMenuData(data); } @Override public void actionPerformed(ActionContext context) { openWith(toolName); } } private class MyMouseListener extends MouseAdapter { @Override public void mouseClicked(MouseEvent e) { handleMouseClick(e); } private void handleMouseClick(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { int row = table.rowAtPoint(e.getPoint()); if (row < 0) { return; } open(); } } } private class DeleteTask extends Task { private int versionNumber; DeleteTask(int versionNumber) { super("Delete Version", false, false, true); this.versionNumber = versionNumber; } @Override public void run(TaskMonitor monitor) { try { domainFile.delete(versionNumber); } catch (IOException e) { ClientUtil.handleException(tool.getProject().getRepository(), e, "Delete Version", VersionHistoryPanel.this); } } } }
NationalSecurityAgency/ghidra
Ghidra/Framework/Project/src/main/java/ghidra/framework/main/datatree/VersionHistoryPanel.java
Java
apache-2.0
14,019
/** * 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.aurora.benchmark.fakes; import java.util.concurrent.atomic.AtomicLong; import com.google.common.base.Supplier; import com.twitter.common.stats.Stat; import com.twitter.common.stats.StatsProvider; public class FakeStatsProvider implements StatsProvider { @Override public AtomicLong makeCounter(String name) { return new AtomicLong(); } @Override public <T extends Number> Stat<T> makeGauge(final String name, final Supplier<T> gauge) { return new Stat<T>() { @Override public String getName() { return name; } @Override public T read() { return gauge.get(); } }; } @Override public StatsProvider untracked() { return this; } @Override public RequestTimer makeRequestTimer(String name) { return new RequestTimer() { @Override public void requestComplete(long latencyMicros) { // no-op } @Override public void incErrors() { // no-op } @Override public void incReconnects() { // no-op } @Override public void incTimeouts() { // no-op } }; } }
kidaa/aurora
src/jmh/java/org/apache/aurora/benchmark/fakes/FakeStatsProvider.java
Java
apache-2.0
1,736
package org.hl7.fhir.r4.formats; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.hl7.fhir.r4.model.CodeType; import org.hl7.fhir.r4.model.CodeableConcept; import org.hl7.fhir.r4.model.Coding; import org.hl7.fhir.r4.model.Enumeration; import org.hl7.fhir.r4.model.Resource; import org.hl7.fhir.r4.model.Type; import org.hl7.fhir.r4.utils.formats.Turtle; import org.hl7.fhir.r4.utils.formats.Turtle.Complex; import org.hl7.fhir.r4.utils.formats.Turtle.Section; import org.hl7.fhir.r4.utils.formats.Turtle.Subject; import org.hl7.fhir.exceptions.FHIRFormatError; import org.hl7.fhir.utilities.xhtml.XhtmlNode; public abstract class RdfParserBase extends ParserBase implements IParser { protected abstract void composeResource(Complex complex, Resource resource) throws IOException; @Override public ParserType getType() { return ParserType.RDF_TURTLE; } @Override public Resource parse(InputStream input) throws IOException, FHIRFormatError { throw new Error("Parsing not implemented yet"); } @Override public Type parseType(InputStream input, String knownType) throws IOException, FHIRFormatError { throw new Error("Parsing not implemented yet"); } private String url; @Override public void compose(OutputStream stream, Resource resource) throws IOException { Turtle ttl = new Turtle(); // ttl.setFormat(FFormat); ttl.prefix("fhir", "http://hl7.org/fhir/"); ttl.prefix("rdfs", "http://www.w3.org/2000/01/rdf-schema#"); Section section = ttl.section("resource"); Subject subject; if (url != null) subject = section.triple("<"+url+">", "a", "fhir:"+resource.getResourceType().toString()); else subject = section.triple("[]", "a", "fhir:"+resource.getResourceType().toString()); composeResource(subject, resource); try { ttl.commit(stream, false); } catch (Exception e) { throw new IOException(e); } } @Override public void compose(OutputStream stream, Type type, String rootName) throws IOException { throw new Error("Not supported in RDF"); } protected String ttlLiteral(String value) { return "\"" +Turtle.escape(value, true) + "\""; } protected void composeXhtml(Complex t, String string, String string2, XhtmlNode div, int i) { } protected void decorateCode(Complex t, Enumeration<? extends Enum> value) { } protected void decorateCode(Complex t, CodeType value) { } protected void decorateCoding(Complex t, Coding element) { if (!element.hasSystem()) return; if ("http://snomed.info/sct".equals(element.getSystem())) { t.prefix("sct", "http://snomed.info/sct/"); t.predicate("a", "sct:"+element.getCode()); } else if ("http://snomed.info/sct".equals(element.getSystem())) { t.prefix("loinc", "http://loinc.org/rdf#"); t.predicate("a", "loinc:"+element.getCode()); } } protected void decorateCodeableConcept(Complex t, CodeableConcept element) { for (Coding c : element.getCoding()) decorateCoding(t, c); } }
eug48/hapi-fhir
hapi-fhir-structures-r4/src/main/java/org/hl7/fhir/r4/formats/RdfParserBase.java
Java
apache-2.0
3,090
package com.openclinic.khambenh; import java.util.ArrayList; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.Viewer; public class ContentProviderCtNhapthuoc implements IStructuredContentProvider { public Object[] getElements(Object inputElement) { if (inputElement instanceof ArrayList) { return ((ArrayList) inputElement).toArray(); } return new Object[0]; } public void dispose() { } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } }
vuzzan/openclinic
src/com/openclinic/khambenh/ContentProviderCtNhapthuoc.java
Java
apache-2.0
554
/* * Copyright (c) 2013 ITOCHU Techno-Solutions Corporation. * * 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 jp.co.ctc_g.jfw.core.util; import static org.junit.Assert.*; import org.junit.Test; public class FormatsTest { @Test public void format日付テスト() { String format = "%4$2s %3$2s %2$2s %1$2s"; String expected = " d c b a"; String actual = Formats.format(format, "a", "b", "c", "d"); assertEquals(expected, actual); } @Test public void format浮動小数値テスト() { String format = "%,9.3f"; String expected = "6,217.580"; String actual = Formats.format(format, 6217.58f); assertEquals(expected, actual); } }
ctc-g/sinavi-jfw
util/jfw-util-core/src/test/java/jp/co/ctc_g/jfw/core/util/FormatsTest.java
Java
apache-2.0
1,253
package eu.straider.web.gwt.gauges.client.components; import com.google.gwt.canvas.client.Canvas; import com.google.gwt.canvas.dom.client.Context2d; import com.google.gwt.canvas.dom.client.CssColor; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.i18n.client.NumberFormat; import com.google.gwt.user.client.ui.Composite; import eu.straider.web.gwt.gauges.client.ColorRange; import eu.straider.web.gwt.gauges.client.Gauge; import eu.straider.web.gwt.gauges.client.GaugeAnimation; import java.util.ArrayList; import java.util.Collections; import java.util.List; abstract class AbstractGauge<T extends Number> extends Composite implements Gauge<T> { private Context2d context; private Canvas canvas; private T value; private boolean animate; private boolean borderVisible; private T minValue; private T maxValue; private int animationDuration; private NumberFormat valueMask; private String valueFont; private String captionFont; private boolean captionVisible; private List<ColorRange<T>> colorRanges; private CssColor gaugeColor; private CssColor borderColor; private CssColor backgroundColor; private CssColor tickColor; private CssColor textColor; private CssColor captionColor; private boolean backgroundEnabled; private double borderWidth; private int majorTicks = 0; private int minorTicks = 0; private boolean drawTicks; private boolean drawText; private double majorTicksSize = 1; private double minorTicksSize = 1; private String caption; private GaugeAnimation<T> gaugeAnimation; public AbstractGauge() { backgroundEnabled = true; animate = true; drawText = true; captionVisible = true; caption = ""; gaugeColor = CssColor.make("black"); borderColor = CssColor.make("black"); tickColor = CssColor.make("black"); textColor = CssColor.make("black"); captionColor = CssColor.make("black"); backgroundColor = CssColor.make("white"); colorRanges = new ArrayList<ColorRange<T>>(); valueMask = NumberFormat.getFormat("0"); valueFont = "normal 10px monospace"; captionFont = "normal 10px monospace"; canvas = Canvas.createIfSupported(); context = canvas.getContext2d(); animationDuration = 200; borderWidth = 1; majorTicks = 0; minorTicks = 0; majorTicksSize = 3; minorTicksSize = 1; drawTicks = false; gaugeAnimation = new SimpleGaugeValueAnimation<T>(this); initWidget(canvas); } @Override public void setValueColor(CssColor color) { textColor = color; repaint(); } @Override public CssColor getValueColor() { return textColor; } @Override public void setCaptionColor(CssColor color) { captionColor = color; repaint(); } @Override public CssColor getCaptionColor() { return captionColor; } @Override public void setTickColor(CssColor color) { tickColor = color; repaint(); } @Override public CssColor getTickColor() { return tickColor; } @Override public void setGaugeAnimation(GaugeAnimation<T> animation) { gaugeAnimation = animation; } @Override public GaugeAnimation<T> getGaugeAnimation() { return gaugeAnimation; } protected Canvas getCanvas() { return canvas; } protected Context2d getContext() { return context; } @Override public void setCaption(String caption) { this.caption = caption; repaint(); } @Override public String getCaption() { return caption; } @Override public void setCaptionFont(String font) { captionFont = font; repaint(); } @Override public String getCaptionFont() { return captionFont; } @Override public void setCaptionEnabled(boolean enabled) { captionVisible = enabled; repaint(); } @Override public boolean isCaptionEnabled() { return captionVisible; } @Override public void setVisible(boolean visible) { super.setVisible(visible); if (visible) { repaint(); } } @Override public T getValue() { return value; } @Override public void setValue(T value) { setValue(value, true); } @Override public void setValue(T value, boolean fireEvents) { T oldValue = getValue(); if (value.doubleValue() > maxValue.doubleValue()) { value = maxValue; } else if (value.doubleValue() < minValue.doubleValue()) { value = minValue; } this.value = value; if (oldValue == null) { oldValue = getMinValue(); } if (isAnimationEnabled()) { gaugeAnimation.goToValue(value, oldValue, getAnimationDuration()); } else { repaint(); } if (fireEvents) { ValueChangeEvent.fire(this, value); } } @Override public HandlerRegistration addValueChangeHandler(ValueChangeHandler<T> handler) { return addHandler(handler, ValueChangeEvent.getType()); } @Override public void setBackgroundColor(CssColor color) { backgroundColor = color; repaint(); } @Override public CssColor getBackgroundColor() { return backgroundColor; } @Override public void setBackgroundColorEnabled(boolean enabled) { backgroundEnabled = enabled; repaint(); } @Override public boolean isBackgroundColorEnabled() { return backgroundEnabled; } @Override public boolean isAnimationEnabled() { return animate; } @Override public void setAnimationEnabled(boolean enable) { animate = enable; repaint(); } @Override public T getMinValue() { return minValue; } @Override public T getMaxValue() { return maxValue; } @Override public void setMinValue(T minValue) { this.minValue = minValue; repaint(); } @Override public void setMaxValue(T maxValue) { this.maxValue = maxValue; repaint(); } @Override public void setSize(int size) { canvas.setHeight(size + "px"); canvas.setWidth(size + "px"); canvas.setCoordinateSpaceHeight(size); canvas.setCoordinateSpaceWidth(size); repaint(); } @Override public void setAnimationDuration(int milliseconds) { animationDuration = milliseconds; repaint(); } @Override public int getAnimationDuration() { return animationDuration; } @Override public void setValueFormat(NumberFormat mask) { this.valueMask = mask; repaint(); } @Override public NumberFormat getValueFormat() { return valueMask; } @Override public void setValueFont(String font) { this.valueFont = font; repaint(); } @Override public String getValueFont() { return valueFont; } @Override public void addColorRange(ColorRange range) { colorRanges.add(range); repaint(); } @Override public List<ColorRange<T>> getColorRanges() { return Collections.unmodifiableList(colorRanges); } @Override public void removeColorRange(ColorRange range) { colorRanges.remove(range); repaint(); } @Override public void clearColorRanges() { colorRanges.clear(); repaint(); } @Override public void setGaugeColor(CssColor color) { gaugeColor = color; repaint(); } @Override public CssColor getGaugeColor() { return gaugeColor; } @Override public void setBorderWidth(double borderWidth) { this.borderWidth = borderWidth; repaint(); } @Override public double getBorderWidth() { return borderWidth; } @Override public void setBorderColor(CssColor color) { this.borderColor = color; repaint(); } @Override public CssColor getBorderColor() { return borderColor; } @Override public void setBorderEnabled(boolean enabled) { borderVisible = enabled; repaint(); } @Override public boolean isBorderEnabled() { return borderVisible; } @Override public boolean isTicksEnabled() { return drawTicks; } @Override public void setTicksEnabled(boolean enabled) { drawTicks = enabled; repaint(); } @Override public void setMinorTicks(int ticks) { minorTicks = ticks; repaint(); } @Override public int getMinorTicks() { return minorTicks; } @Override public void setMajorTicks(int ticks) { majorTicks = ticks; repaint(); } @Override public int getMajorTicks() { return majorTicks; } @Override public void setMajorTicksSizeInPercentOfSize(double size) { majorTicksSize = size; repaint(); } @Override public void setMinorTicksSizeInPercentOfSize(double size) { minorTicksSize = size; repaint(); } @Override public double getMajorTicksSizeInPercentOfSize() { return majorTicksSize; } @Override public double getMinorTicksSizeInPercentOfSize() { return minorTicksSize; } @Override public void setGaugeTextEnabled(boolean enabled) { drawText = enabled; repaint(); } @Override public boolean isGaugeTextEnabled() { return drawText; } private void repaint() { if (getValue() != null) { drawGauge(getValue().doubleValue()); } } protected void drawGauge(double currentValue) { if (isVisible()) { if (isBackgroundColorEnabled()) { drawGaugeBackground(currentValue); } if (isBorderEnabled()) { drawGaugeBorder(currentValue); } drawGaugeDial(currentValue); if (isGaugeTextEnabled()) { drawGaugeText(currentValue); } if (isCaptionEnabled()) { drawGaugeCaption(); } if (isTicksEnabled()) { drawGaugeTicks(currentValue); } } } abstract void drawGaugeDial(double currentValue); abstract void drawGaugeText(double currentValue); abstract void drawGaugeCaption(); abstract void drawGaugeBorder(double currentValue); abstract void drawGaugeTicks(double currentValue); abstract void drawGaugeBackground(double currentValue); }
GMMStraider/gauges
src/main/java/eu/straider/web/gwt/gauges/client/components/AbstractGauge.java
Java
apache-2.0
11,147
/******************************************************************************* * Copyright (c) 2010-2014 Alexander Kerner. All rights reserved. * * 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 net.sf.kerner.utils.collections; import java.io.Serializable; import java.util.Collection; import java.util.Comparator; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; public class PropertiesSorted implements SortedMap<String, Object>, Serializable { private static final long serialVersionUID = -7867760517665815796L; public static PropertiesSorted fromProperties(final Properties properties) { final PropertiesSorted result = new PropertiesSorted(); for (final java.util.Map.Entry<Object, Object> e : properties.entrySet()) { result.put(e.getKey().toString(), e.getValue()); } return result; } private final SortedMap<String, Object> delegate; public PropertiesSorted() { delegate = new TreeMap<String, Object>(); } public PropertiesSorted(final Comparator<? super String> c) { delegate = new TreeMap<String, Object>(c); } public PropertiesSorted(final Properties properties) { delegate = fromProperties(properties); } public PropertiesSorted(final SortedMap<String, Object> delegate) { this.delegate = delegate; } public void clear() { delegate.clear(); } public Comparator<? super String> comparator() { return delegate.comparator(); } public boolean containsKey(final Object key) { return delegate.containsKey(key); } public boolean containsValue(final Object value) { return delegate.containsValue(value); } public Set<java.util.Map.Entry<String, Object>> entrySet() { return delegate.entrySet(); } @Override public boolean equals(final Object o) { return delegate.equals(o); } public String firstKey() { return delegate.firstKey(); } public Object get(final Object key) { return delegate.get(key); } @Override public int hashCode() { return delegate.hashCode(); } public SortedMap<String, Object> headMap(final String toKey) { return delegate.headMap(toKey); } public boolean isEmpty() { return delegate.isEmpty(); } public Set<String> keySet() { return delegate.keySet(); } public String lastKey() { return delegate.lastKey(); } public Object put(final String key, final Object value) { return delegate.put(key, value); } public void putAll(final Map<? extends String, ? extends Object> m) { delegate.putAll(m); } public Object remove(final Object key) { return delegate.remove(key); } public int size() { return delegate.size(); } public SortedMap<String, Object> subMap(final String fromKey, final String toKey) { return delegate.subMap(fromKey, toKey); } public SortedMap<String, Object> tailMap(final String fromKey) { return delegate.tailMap(fromKey); } public Properties toProperties() { final Properties p = new Properties(); p.putAll(delegate); return p; } @Override public String toString() { return UtilCollection.toString(delegate.entrySet()); } public Collection<Object> values() { return delegate.values(); } }
SilicoSciences/net.sf.kerner.utils.collections
src/main/java/net/sf/kerner/utils/collections/PropertiesSorted.java
Java
apache-2.0
3,908
/** * 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.camel.processor; import org.apache.camel.CamelExecutionException; import org.apache.camel.ContextTestSupport; import org.apache.camel.RollbackExchangeException; import org.apache.camel.builder.RouteBuilder; /** * @version $Revision$ */ public class RollbackDefaultMessageTest extends ContextTestSupport { public void testRollback() throws Exception { try { template.sendBody("direct:start", "Hello World"); fail("Should have thrown an exception"); } catch (CamelExecutionException e) { assertIsInstanceOf(RollbackExchangeException.class, e.getCause()); assertNotNull(e.getCause().getMessage()); } } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { context.setTracing(true); from("direct:start").rollback(); } }; } }
kingargyle/turmeric-bot
camel-core/src/test/java/org/apache/camel/processor/RollbackDefaultMessageTest.java
Java
apache-2.0
1,827
package com.zj.model; /** * 包含同步方法的model * Created by LZJ on 2015/12/3. */ public class Money { /** * 当一个方法被声明为同步的时候,这个方法就会拥有一个锁,同一时刻只有拥有了该方法的锁的对象可以调用该方法,<br/> * 此为互斥锁 */ public synchronized void minus() { } }
hqq2023623/notes
thread/src/main/java/com/zj/model/Money.java
Java
apache-2.0
368
package org.lnu.is.service; import org.lnu.is.dao.dao.Dao; import org.lnu.is.extractor.ParametersExtractor; import org.lnu.is.pagination.MultiplePagedSearch; import org.lnu.is.pagination.PagedResult; import java.util.Map; /** * * Default implementation of Service class. * NOTE: If you have some custom logic for any of methods below in this class, * you can easily extend this class, write some custom logic, and inject * it in services-context.xml. * * @author ivanursul * * @param <ENTITY> Entity, Please see is-lnu-domain module. * @param <ENTITYLIST> Entity, Please see is-lnu-domain module. * @param <KEY> Key of corresponding * @param <DAO> Dao */ public class DefaultService<ENTITY, ENTITYLIST, KEY, DAO extends Dao<ENTITY, ENTITYLIST, KEY>> implements Service<ENTITY, ENTITYLIST, KEY> { protected DAO dao; private ParametersExtractor<ENTITYLIST> parametersExtractor; @Override public void createEntity(final ENTITY entity) { dao.save(entity); } @Override public ENTITY getEntity(final KEY id) { return dao.getEntityById(id); } @Override public void updateEntity(final ENTITY entity) { dao.update(entity); } @Override public void removeEntity(final ENTITY entity) { dao.delete(entity); } @Override public PagedResult<ENTITY> getEntities(final MultiplePagedSearch<ENTITYLIST> search) { Map<String, Object> parameters = parametersExtractor.getParameters(search.getEntity()); search.setParameters(parameters); return dao.getEntities(search); } public void setDao(final DAO defaultDao) { this.dao = defaultDao; } public void setParametersExtractor(final ParametersExtractor<ENTITYLIST> parametersExtractor) { this.parametersExtractor = parametersExtractor; } public DAO getDao() { return dao; } public ParametersExtractor<ENTITYLIST> getParametersExtractor() { return parametersExtractor; } }
ifnul/ums-backend
is-lnu-service/src/main/java/org/lnu/is/service/DefaultService.java
Java
apache-2.0
1,881
/** * ActionServiceImpl.java */ package com.skycloud.jkb.service.impl; import java.util.List; import java.util.Locale; import java.util.Set; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.skycloud.api.domain.action.ActionCreateRequest; import com.skycloud.api.domain.action.ActionCreateRequest.ActionCreateParams; import com.skycloud.api.domain.base.ActionCondition; import com.skycloud.api.domain.base.ActionOperation; import com.skycloud.api.domain.base.ActionOperationMessage; import com.skycloud.api.domain.base.ActionOperationSyn; import com.skycloud.jkb.base.impl.BaseServiceImpl; import com.skycloud.jkb.component.ApiInvoker; import com.skycloud.jkb.dao.IActionDao; import com.skycloud.jkb.pojo.constant.SysConstant; import com.skycloud.jkb.pojo.entity.Conditions; import com.skycloud.jkb.pojo.entity.Operations; import com.skycloud.jkb.pojo.entity.Opmessage; import com.skycloud.jkb.pojo.entity.OpmessageUsr; import com.skycloud.jkb.pojo.model.Action; import com.skycloud.jkb.pojo.vo.ApiResult; import com.skycloud.jkb.pojo.vo.PageResult; import com.skycloud.jkb.service.IActionService; import com.skycloud.jkb.util.CollectionUtil; import com.skycloud.jkb.util.NumberUtil; /** * 【告警动作】业务逻辑实现. * * @creation 2014年01月03日 12:19:14 * @modification 2014年01月03日 12:19:14 * @company Skycloud * @author xiweicheng * @version 1.0 * */ @Service @Transactional public class ActionServiceImpl extends BaseServiceImpl implements IActionService { private static Logger logger = Logger.getLogger(ActionServiceImpl.class); @Autowired IActionDao actionDao; @Autowired ApiInvoker apiInvoker; @Override public boolean save(Locale locale, Action action) { logger.debug("[业务逻辑层]添加【告警动作】"); ActionCreateRequest actionCreateRequest = new ActionCreateRequest(); ActionCreateParams params = actionCreateRequest.getParams(); // 告警动作基本信息 params.setName(action.getName()); params.setEventsource(action.getEventsource()); params.setEvaltype(action.getEvaltype()); params.setStatus(action.getStatus()); params.setEsc_period(action.getEscPeriod()); params.setDef_shortdata(action.getDefShortdata()); params.setDef_longdata(action.getDefLongdata()); // 告警动作条件(多个条件) Set<Conditions> conditionses = action.getConditionses(); if (CollectionUtil.isNotEmpty(conditionses)) { for (Conditions conditions : conditionses) { ActionCondition actionCondition = new ActionCondition(); actionCondition.setConditiontype(conditions.getConditiontype()); actionCondition.setOperator(conditions.getOperator()); actionCondition.setValue(conditions.getValue()); params.getConditions().add(actionCondition); } } // 告警动作操作(多个操作) Set<Operations> operationses = action.getOperationses(); if (CollectionUtil.isNotEmpty(operationses)) { for (Operations operations : operationses) { ActionOperation actionOperation = new ActionOperation(); actionOperation.setOperationtype(operations.getOperationtype()); actionOperation.setEsc_step_from(operations.getEscStepFrom()); actionOperation.setEsc_step_to(operations.getEscStepTo()); actionOperation.setEvaltype(operations.getEvaltype()); params.getOperations().add(actionOperation); // TODO // // List<ActionOperationSyn> opcommand_grp; // Set<OpcommandGrp> opcommandGrps = // operations.getOpcommandGrps(); // if (CollectionUtil.isNotEmpty(opcommandGrps)) { // } // // // List<ActionOperationSyn> opcommand_hst; // Set<OpcommandHst> opcommandHsts = // operations.getOpcommandHsts(); // if (CollectionUtil.isNotEmpty(opcommandHsts)) { // } // // List<ActionOperationSyn> opconditions; // Set<Opconditions> opconditionses = // operations.getOpconditionses(); // if (CollectionUtil.isNotEmpty(opconditionses)) { // } // // List<ActionOperationSyn> opgroup; // Set<Opgroup> opgroups = operations.getOpgroups(); // if (CollectionUtil.isNotEmpty(opgroups)) { // } // // List<ActionOperationSyn> opmessage_grp; // Set<OpmessageGrp> opmessageGrps = // operations.getOpmessageGrps(); // if (CollectionUtil.isNotEmpty(opmessageGrps)) { // } // // List<ActionOperationSyn> optemplate; // Set<Optemplate> optemplates = operations.getOptemplates(); // if (CollectionUtil.isNotEmpty(optemplates)) { // } // List<ActionOperationSyn> opmessage_usr; Set<OpmessageUsr> opmessageUsrs = operations.getOpmessageUsrs(); if (CollectionUtil.isNotEmpty(opmessageUsrs)) { for (OpmessageUsr opmessageUsr : opmessageUsrs) { ActionOperationSyn actionOperationSyn = new ActionOperationSyn(); actionOperationSyn.setUserid(String.valueOf(opmessageUsr.getUsers().getUserid())); actionOperation.getOpmessage_usr().add(actionOperationSyn); } } // ActionOperationMessage opmessage; Opmessage opmessage = operations.getOpmessage(); if (opmessage != null) { ActionOperationMessage actionOperationMessage = new ActionOperationMessage(); actionOperationMessage.setDefault_msg(opmessage.getDefaultMsg()); actionOperationMessage.setMediatypeid(String.valueOf(opmessage.getMediaType().getMediatypeid())); actionOperationMessage.setSubject(opmessage.getSubject()); actionOperationMessage.setMessage(opmessage.getMessage()); actionOperation.setOpmessage(actionOperationMessage); } } } ApiResult invoke = apiInvoker.invoke(actionCreateRequest); throwRuntimeExceptionWhenTrue(invoke.failed(), invoke.getMessage()); action.setActionid(NumberUtil.toLong(invoke.getIdResult(SysConstant.ID_ACTIONIDS))); return true; } @Override public boolean delete(Locale locale, Action action) { logger.debug("[业务逻辑层]删除【告警动作】"); // TODO return true; } @Override public Action get(Locale locale, Action action) { logger.debug("[业务逻辑层]获取【告警动作】"); // TODO return null; } @Override public boolean update(Locale locale, Action action) { logger.debug("[业务逻辑层]更新【告警动作】"); // TODO return true; } @Override public List<Action> list(Locale locale) { logger.debug("[业务逻辑层]列举【告警动作】"); // TODO return null; } @Override public List<Action> query(Locale locale, Action action) { logger.debug("[业务逻辑层]查询【告警动作】(不分页)"); // TODO return null; } @Override public PageResult paging(Locale locale, Action action, Long start, Long limit) { logger.debug("[业务逻辑层]查询【告警动作】(分页)"); PageResult pageResult = new PageResult(); // TODO return pageResult; } @Override public boolean exists(Locale locale, Action action) { logger.debug("[业务逻辑层]判断【告警动作】是否存在"); // TODO return true; } }
xiwc/jkb
src/main/java/com/skycloud/jkb/service/impl/ActionServiceImpl.java
Java
apache-2.0
7,114
/* * Copyright 2003-2009 the original author or authors. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain event 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.jdon.components.guavacache; public class GuavaCacheConf { private final int maximumSize; public GuavaCacheConf(String maximumSize) { this.maximumSize = Integer.parseInt(maximumSize); } public int getMaximumSize() { return maximumSize; } }
banq/jdonframework
src/main/java/com/jdon/components/guavacache/GuavaCacheConf.java
Java
apache-2.0
916
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.example.project15_2_1; public final class R { public static final class attr { } public static final class drawable { public static final int ic_launcher=0x7f020000; } public static final class id { public static final int text=0x7f060000; } public static final class layout { public static final int activity_project15_2_1=0x7f030000; } public static final class string { public static final int app_name=0x7f040000; public static final int hello_world=0x7f040001; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f050000; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f050001; } }
00wendi00/MyProject
W_eclipse1/Project15_2_1/gen/com/example/project15_2_1/R.java
Java
apache-2.0
1,837
package com.sakurafish.parrot.callconfirm.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.sakurafish.parrot.callconfirm.Pref.Pref; import com.sakurafish.parrot.callconfirm.R; import com.sakurafish.parrot.callconfirm.config.Config; import com.sakurafish.parrot.callconfirm.utils.AlarmUtils; import static com.sakurafish.parrot.callconfirm.config.Config.PREF_STATE_INVALID_TELNO; public class BootReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) { if ((intent == null) || !intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { return; } Pref.setPref(context, Config.PREF_AFTER_CONFIRM, false); Pref.setPref(context, PREF_STATE_INVALID_TELNO, false); if (Pref.getPrefBool(context, context.getString(R.string.PREF_NOTIFICATION), true)) { AlarmUtils.unregisterAlarm(context); AlarmUtils.registerAlarm(context); } } }
sakurabird/Android-ParrotCallConfirm
app/src/main/java/com/sakurafish/parrot/callconfirm/receiver/BootReceiver.java
Java
apache-2.0
1,062
/* * Copyright 2006-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.consol.citrus.http.config.xml; import javax.servlet.http.Cookie; import java.util.List; import com.consol.citrus.config.util.BeanDefinitionParserUtils; import com.consol.citrus.config.xml.DescriptionElementParser; import com.consol.citrus.config.xml.MessageSelectorParser; import com.consol.citrus.config.xml.ReceiveMessageActionParser; import com.consol.citrus.http.message.HttpMessage; import com.consol.citrus.http.message.HttpMessageBuilder; import com.consol.citrus.http.message.HttpMessageHeaders; import com.consol.citrus.validation.builder.DefaultMessageBuilder; import com.consol.citrus.validation.context.HeaderValidationContext; import com.consol.citrus.validation.context.ValidationContext; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.util.StringUtils; import org.springframework.util.xml.DomUtils; import org.w3c.dom.Element; /** * @author Christoph Deppisch * @since 2.4 */ public class HttpReceiveResponseActionParser extends ReceiveMessageActionParser { @Override public BeanDefinition parse(Element element, ParserContext parserContext) { BeanDefinitionBuilder builder = parseComponent(element, parserContext); builder.addPropertyValue("name", "http:" + element.getLocalName()); DescriptionElementParser.doParse(element, builder); BeanDefinitionParserUtils.setPropertyReference(builder, element.getAttribute("actor"), "actor"); String receiveTimeout = element.getAttribute("timeout"); if (StringUtils.hasText(receiveTimeout)) { builder.addPropertyValue("receiveTimeout", Long.valueOf(receiveTimeout)); } if (!element.hasAttribute("uri") && !element.hasAttribute("client")) { throw new BeanCreationException("Neither http request uri nor http client endpoint reference is given - invalid test action definition"); } if (element.hasAttribute("client")) { builder.addPropertyReference("endpoint", element.getAttribute("client")); } else if (element.hasAttribute("uri")) { builder.addPropertyValue("endpointUri", element.getAttribute("uri")); } HttpMessage httpMessage = new HttpMessage(); Element body = DomUtils.getChildElementByTagName(element, "body"); List<ValidationContext> validationContexts = parseValidationContexts(body, builder); Element headers = DomUtils.getChildElementByTagName(element, "headers"); if (headers != null) { List<?> headerElements = DomUtils.getChildElementsByTagName(headers, "header"); for (Object headerElement : headerElements) { Element header = (Element) headerElement; httpMessage.setHeader(header.getAttribute("name"), header.getAttribute("value")); } String statusCode = headers.getAttribute("status"); if (StringUtils.hasText(statusCode)) { httpMessage.setHeader(HttpMessageHeaders.HTTP_STATUS_CODE, statusCode); } String reasonPhrase = headers.getAttribute("reason-phrase"); if (StringUtils.hasText(reasonPhrase)) { httpMessage.reasonPhrase(reasonPhrase); } String version = headers.getAttribute("version"); if (StringUtils.hasText(version)) { httpMessage.version(version); } List<?> cookieElements = DomUtils.getChildElementsByTagName(headers, "cookie"); for (Object item : cookieElements) { Element cookieElement = (Element) item; Cookie cookie = new Cookie(cookieElement.getAttribute("name"), cookieElement.getAttribute("value")); if (cookieElement.hasAttribute("comment")) { cookie.setComment(cookieElement.getAttribute("comment")); } if (cookieElement.hasAttribute("path")) { cookie.setPath(cookieElement.getAttribute("path")); } if (cookieElement.hasAttribute("domain")) { cookie.setDomain(cookieElement.getAttribute("domain")); } if (cookieElement.hasAttribute("max-age")) { cookie.setMaxAge(Integer.valueOf(cookieElement.getAttribute("max-age"))); } if (cookieElement.hasAttribute("secure")) { cookie.setSecure(Boolean.valueOf(cookieElement.getAttribute("secure"))); } if (cookieElement.hasAttribute("version")) { cookie.setVersion(Integer.valueOf(cookieElement.getAttribute("version"))); } httpMessage.cookie(cookie); } boolean ignoreCase = headers.hasAttribute("ignore-case") ? Boolean.valueOf(headers.getAttribute("ignore-case")) : true; validationContexts.stream().filter(context -> context instanceof HeaderValidationContext) .map(context -> (HeaderValidationContext) context) .forEach(context -> context.setHeaderNameIgnoreCase(ignoreCase)); } MessageSelectorParser.doParse(element, builder); HttpMessageBuilder httpMessageBuilder = new HttpMessageBuilder(httpMessage); DefaultMessageBuilder messageContentBuilder = constructMessageBuilder(body, builder); httpMessageBuilder.setName(messageContentBuilder.getName()); httpMessageBuilder.setPayloadBuilder(messageContentBuilder.getPayloadBuilder()); messageContentBuilder.getHeaderBuilders().forEach(httpMessageBuilder::addHeaderBuilder); builder.addPropertyValue("messageBuilder", httpMessageBuilder); builder.addPropertyValue("validationContexts", validationContexts); builder.addPropertyValue("variableExtractors", getVariableExtractors(element)); return builder.getBeanDefinition(); } }
christophd/citrus
endpoints/citrus-http/src/main/java/com/consol/citrus/http/config/xml/HttpReceiveResponseActionParser.java
Java
apache-2.0
6,782
package de.ikolus.sz.jaavario; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; public class NoiseHandlerThread implements Runnable { private PressureBasedInformation pbinfo; private Lock lockForPbinfo; private Condition condForPbinfo; private long lastTime=0; private NoiseMaker noiseMaker; public NoiseHandlerThread(Lock lock, Condition condition, PressureBasedInformation pbinfo,float notificationSinkRate, float notificationClimbRate) { this.lockForPbinfo=lock; this.pbinfo=pbinfo; this.condForPbinfo=condition; noiseMaker=new NoiseMaker(notificationSinkRate,notificationClimbRate); } @Override public void run() { while(!Thread.interrupted()) { try { lockForPbinfo.lockInterruptibly(); //theoretically relevant new data could already be present here. //This is only the case if either the NoiseMaker takes very long for processing or the PressureSensor is read very quickly condForPbinfo.await(); } catch (InterruptedException e) { break; } if(pbinfo.getValidTime()==lastTime) { lockForPbinfo.unlock(); } else { double csRate=pbinfo.getClimbSinkRate(); lastTime=pbinfo.getValidTime(); lockForPbinfo.unlock(); //play the stuff noiseMaker.makeNoise(csRate, lastTime); } } noiseMaker.shutdownNoiseMaker(); } }
sebzie/jaavario
jaavario/src/de/ikolus/sz/jaavario/NoiseHandlerThread.java
Java
apache-2.0
1,353
/* * Copyright 2017-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.rules.modern; import java.nio.file.Path; import java.nio.file.Paths; /** * Represents an output path of a Buildable. Can be converted to a Path with an OutputPathResolver. */ public final class OutputPath { private Path path; public OutputPath(String name) { this(Paths.get(name)); } public OutputPath(Path path) { this.path = path; } public OutputPath resolve(String subPath) { return new OutputPath(path.resolve(subPath)); } public OutputPath resolve(Path subPath) { return new OutputPath(path.resolve(subPath)); } Path getPath() { return path; } public static class Internals { public static Path getPathFrom(OutputPath outputPath) { return outputPath.getPath(); } } }
shybovycha/buck
src/com/facebook/buck/rules/modern/OutputPath.java
Java
apache-2.0
1,375
/* * 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.jackrabbit.oak.security.privilege; import javax.annotation.Nonnull; import org.apache.jackrabbit.oak.api.Root; import org.apache.jackrabbit.oak.core.ImmutableRoot; import org.apache.jackrabbit.oak.spi.commit.CommitInfo; import org.apache.jackrabbit.oak.spi.commit.SubtreeValidator; import org.apache.jackrabbit.oak.spi.commit.Validator; import org.apache.jackrabbit.oak.spi.commit.ValidatorProvider; import org.apache.jackrabbit.oak.spi.state.NodeState; import static org.apache.jackrabbit.JcrConstants.JCR_SYSTEM; import static org.apache.jackrabbit.oak.spi.security.privilege.PrivilegeConstants.REP_PRIVILEGES; /** * {@code PrivilegeValidatorProvider} to construct a {@code Validator} instance * to make sure modifications to the /jcr:system/rep:privileges tree are compliant * with constraints applied for custom privileges. */ class PrivilegeValidatorProvider extends ValidatorProvider { @Nonnull @Override public Validator getRootValidator( NodeState before, NodeState after, CommitInfo info) { return new SubtreeValidator(new PrivilegeValidator(createRoot(before), createRoot(after)), JCR_SYSTEM, REP_PRIVILEGES); } private Root createRoot(NodeState nodeState) { return new ImmutableRoot(nodeState); } }
denismo/jackrabbit-dynamodb-store
oak-core/src/main/java/org/apache/jackrabbit/oak/security/privilege/PrivilegeValidatorProvider.java
Java
apache-2.0
2,109
package com.google.android.apps.forscience.ble; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothManager; import android.bluetooth.BluetoothProfile; import android.content.Context; import android.os.Handler; import android.os.Looper; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; /** * This is the entry point for subscribing a sensor and receiving data from an Arduino MKR SCI * external board. * * <p>subscribe() and unsubscribe() methods allow to start and stop receiving data from the external * board through a BLE connection. When subscribing, following information need to be passed: * * <ul> * <li>external device address; * <li>characteristic (sensor) to be subscribed (valid ones are available as constants in the * class); * <li>a listener for receiving values from subscribed characteristic. * </ul> */ public class MkrSciBleManager { public static final String SERVICE_UUID = "555a0001-0000-467a-9538-01f0652c74e8"; private static final String VERSION_UUID = "555a0001-0001-467a-9538-01f0652c74e8"; public static final String INPUT_1_UUID = "555a0001-2001-467a-9538-01f0652c74e8"; public static final String INPUT_2_UUID = "555a0001-2002-467a-9538-01f0652c74e8"; public static final String INPUT_3_UUID = "555a0001-2003-467a-9538-01f0652c74e8"; public static final String VOLTAGE_UUID = "555a0001-4001-467a-9538-01f0652c74e8"; public static final String CURRENT_UUID = "555a0001-4002-467a-9538-01f0652c74e8"; public static final String RESISTANCE_UUID = "555a0001-4003-467a-9538-01f0652c74e8"; public static final String ACCELEROMETER_UUID = "555a0001-5001-467a-9538-01f0652c74e8"; public static final String GYROSCOPE_UUID = "555a0001-5002-467a-9538-01f0652c74e8"; public static final String MAGNETOMETER_UUID = "555a0001-5003-467a-9538-01f0652c74e8"; private static final double MAX_VALUE = 2000000000D; private static final double MIN_VALUE = -2000000000D; private static final Handler handler = new Handler(Looper.getMainLooper()); // device bt address > gatt handler private static final Map<String, GattHandler> gattHandlers = new HashMap<>(); public static void subscribe( Context context, String address, String characteristic, Listener listener) { synchronized (gattHandlers) { GattHandler gattHandler = gattHandlers.get(address); if (gattHandler == null) { BluetoothManager manager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); if (manager == null) { return; } BluetoothAdapter adapter = manager.getAdapter(); BluetoothDevice device = adapter.getRemoteDevice(address); gattHandler = new GattHandler(); gattHandlers.put(address, gattHandler); device.connectGatt(context, true /* autoConnect */, gattHandler); } gattHandler.subscribe(characteristic, listener); } } public static void unsubscribe(String address, String characteristic, Listener listener) { synchronized (gattHandlers) { GattHandler gattHandler = gattHandlers.get(address); if (gattHandler != null) { gattHandler.unsubscribe(characteristic, listener); handler.postDelayed( () -> { synchronized (gattHandlers) { if (!gattHandler.hasSubscribers()) { gattHandlers.remove(address); gattHandler.disconnect(); } } }, 2000L); } } } private static class GattHandler extends BluetoothGattCallback { private static final UUID NOTIFICATION_DESCRIPTOR = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); private final Map<String, List<Listener>> listenersMap = new HashMap<>(); private BluetoothGatt gatt; private final List<BluetoothGattCharacteristic> characteristics = new ArrayList<>(); private final List<Runnable> gattActions = new ArrayList<>(); private boolean readyForAction = false; private boolean busy = false; private long firmwareVersion = -1; private void disconnect() { if (gatt != null) { gatt.disconnect(); } } private void subscribe(String characteristicUuid, Listener listener) { boolean subscribe = false; synchronized (listenersMap) { List<Listener> listeners = listenersMap.get(characteristicUuid); if (listeners == null) { listeners = new ArrayList<>(); listenersMap.put(characteristicUuid, listeners); subscribe = true; } listeners.add(listener); if (firmwareVersion > -1) { listener.onFirmwareVersion(firmwareVersion); } } if (subscribe) { enqueueGattAction( () -> { BluetoothGattCharacteristic c = getCharacteristic(characteristicUuid); if (c != null) { gatt.setCharacteristicNotification(c, true); BluetoothGattDescriptor d = c.getDescriptor(NOTIFICATION_DESCRIPTOR); d.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); gatt.writeDescriptor(d); } }); } } private void unsubscribe(String characteristicUuid, Listener listener) { boolean unsubscribe = false; synchronized (listenersMap) { List<Listener> listeners = listenersMap.get(characteristicUuid); if (listeners != null) { listeners.remove(listener); if (listeners.size() == 0) { listenersMap.remove(characteristicUuid); unsubscribe = true; } } } if (unsubscribe) { enqueueGattAction( () -> { BluetoothGattCharacteristic c = getCharacteristic(characteristicUuid); if (c != null) { gatt.setCharacteristicNotification(c, true); BluetoothGattDescriptor d = c.getDescriptor(NOTIFICATION_DESCRIPTOR); d.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE); gatt.writeDescriptor(d); } }); } } private boolean hasSubscribers() { synchronized (listenersMap) { return listenersMap.size() > 0; } } private BluetoothGattCharacteristic getCharacteristic(String uuid) { for (BluetoothGattCharacteristic aux : characteristics) { if (Objects.equals(uuid, aux.getUuid().toString())) { return aux; } } return null; } private void enqueueGattAction(Runnable action) { synchronized (gattActions) { if (readyForAction && !busy) { busy = true; action.run(); } else { gattActions.add(action); } } } private void onGattActionCompleted() { synchronized (gattActions) { if (readyForAction && gattActions.size() > 0) { busy = true; gattActions.remove(0).run(); } else { busy = false; } } } @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED) { this.gatt = gatt; characteristics.clear(); gatt.discoverServices(); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { readyForAction = false; gatt.disconnect(); } } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { BluetoothGattService service = this.gatt.getService(UUID.fromString(SERVICE_UUID)); if (service != null) { characteristics.addAll(service.getCharacteristics()); } BluetoothGattCharacteristic c = getCharacteristic(VERSION_UUID); if (c != null) { this.gatt.readCharacteristic(c); } } @Override public void onDescriptorRead( BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { onGattActionCompleted(); } @Override public void onDescriptorWrite( BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { onGattActionCompleted(); } @Override public void onCharacteristicRead( BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { final String uuid = characteristic.getUuid().toString(); if (VERSION_UUID.equals(uuid) && firmwareVersion == -1) { final byte[] value = characteristic.getValue(); if (value.length == 4) { final ByteBuffer buffer = ByteBuffer.allocate(8); buffer.put((byte) 0); buffer.put((byte) 0); buffer.put((byte) 0); buffer.put((byte) 0); buffer.put(value[3]); buffer.put(value[2]); buffer.put(value[1]); buffer.put(value[0]); buffer.position(0); firmwareVersion = buffer.getLong(); // delivering to listener(s) synchronized (listenersMap) { for (List<Listener> listeners : listenersMap.values()) { if (listeners != null) { for (Listener l : listeners) { l.onFirmwareVersion(firmwareVersion); } } } } } readyForAction = true; } onGattActionCompleted(); } @Override public void onCharacteristicWrite( BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { onGattActionCompleted(); } @Override public void onCharacteristicChanged( BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { final String uuid = characteristic.getUuid().toString(); final ValueType type; switch (uuid) { case INPUT_1_UUID: case INPUT_2_UUID: case INPUT_3_UUID: type = ValueType.UINT16; break; case VOLTAGE_UUID: case CURRENT_UUID: case RESISTANCE_UUID: type = ValueType.SFLOAT; break; case ACCELEROMETER_UUID: case GYROSCOPE_UUID: case MAGNETOMETER_UUID: type = ValueType.SFLOAT_ARR; break; default: type = null; } if (type != null) { final double[] values = parse(type, characteristic.getValue()); if (values != null) { // filter to avoid too large values blocking the UI for (int i = 0; i < values.length; i++) { if (values[i] > MAX_VALUE) { values[i] = MAX_VALUE; } else if (values[i] < MIN_VALUE) { values[i] = MIN_VALUE; } } // delivering to listener(s) synchronized (listenersMap) { List<Listener> listeners = listenersMap.get(uuid); if (listeners != null) { for (Listener l : listeners) { l.onValuesUpdated(values); } } } } } } } private static double[] parse(ValueType valueType, byte[] value) { if (ValueType.UINT8.equals(valueType)) { if (value.length < 1) { return null; } final ByteBuffer buffer = ByteBuffer.allocate(4); buffer.put((byte) 0); buffer.put((byte) 0); buffer.put((byte) 0); buffer.put(value[0]); buffer.position(0); return new double[] {buffer.getInt()}; } if (ValueType.UINT16.equals(valueType)) { if (value.length < 2) { return null; } final ByteBuffer buffer = ByteBuffer.allocate(4); buffer.put((byte) 0); buffer.put((byte) 0); buffer.put(value[1]); buffer.put(value[0]); buffer.position(0); return new double[] {buffer.getInt()}; } if (ValueType.UINT32.equals(valueType)) { if (value.length < 4) { return null; } final ByteBuffer buffer = ByteBuffer.allocate(8); buffer.put((byte) 0); buffer.put((byte) 0); buffer.put((byte) 0); buffer.put((byte) 0); buffer.put(value[3]); buffer.put(value[2]); buffer.put(value[1]); buffer.put(value[0]); buffer.position(0); return new double[] {buffer.getLong()}; } if (ValueType.SFLOAT.equals(valueType)) { if (value.length < 4) { return null; } final ByteBuffer buffer = ByteBuffer.allocate(4); buffer.put(value[3]); buffer.put(value[2]); buffer.put(value[1]); buffer.put(value[0]); buffer.position(0); return new double[] {buffer.getFloat()}; } if (ValueType.SFLOAT_ARR.equals(valueType)) { final int size = value.length / 4; final double[] array = new double[size]; final ByteBuffer buffer = ByteBuffer.allocate(4); for (int i = 0; i < size; i++) { final int offset = 4 * i; buffer.position(0); buffer.put(value[3 + offset]); buffer.put(value[2 + offset]); buffer.put(value[1 + offset]); buffer.put(value[offset]); buffer.position(0); array[i] = buffer.getFloat(); } return array; } return null; } private enum ValueType { UINT8, UINT16, UINT32, SFLOAT, SFLOAT_ARR } /** * Values read from a subscribed characteristic/sensor available in the external board are passed * through implementations of this interface. */ public interface Listener { void onFirmwareVersion(long firmwareVersion); void onValuesUpdated(double[] values); } }
googlearchive/science-journal
OpenScienceJournal/whistlepunk_library/src/main/java/com/google/android/apps/forscience/ble/MkrSciBleManager.java
Java
apache-2.0
14,080
/* * Copyright 2015 the original author or authors. * @https://github.com/scouter-project/scouter * * 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 scouterx.webapp.request; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.apache.commons.lang3.StringUtils; import scouterx.webapp.framework.client.server.ServerManager; import scouterx.webapp.framework.util.ZZ; import scouterx.webapp.model.scouter.SDictionaryText; import javax.validation.constraints.NotNull; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * @author Gun Lee (gunlee01@gmail.com) on 2017. 8. 30. */ @Getter @Setter @ToString public class DictionaryRequest { private static final char COLON = ':'; @NotNull private Map<String, Set<SDictionaryText>> dictSets; private int serverId; /** * some sorts of dictionary are created every day. so date is needed to find exact text. * format : yyyymmdd */ @NotNull @PathParam("yyyymmdd") String yyyymmdd; /** * dictionary key list to find text from dictionary * * @param dictKeys - format : [service:10001,service:10002,obj:20001,sql:55555] (bracket is optional) */ @QueryParam("dictKeys") public void setDictSets(String dictKeys) { Set<String> textList = ZZ.splitParamStringSet(dictKeys); dictSets = textList.stream() .map(s -> { String[] parts = StringUtils.split(s, COLON); return new SDictionaryText(parts[0], Integer.valueOf(parts[1]), null); }) .collect(Collectors.groupingBy(SDictionaryText::getTextType, Collectors.toSet())); } @QueryParam("serverId") public void setServerId(int serverId) { this.serverId = ServerManager.getInstance().getServerIfNullDefault(serverId).getId(); } }
scouter-project/scouter
scouter.webapp/src/main/java/scouterx/webapp/request/DictionaryRequest.java
Java
apache-2.0
2,323
package controllers; public class Report { // report code //update 2 }
catalin-burcea/betsoft
betsoft/src/controllers/Report.java
Java
apache-2.0
74
package org.f0w.k2i.core.exchange; /** * Factory for {@link MovieRatingChanger} */ public interface MovieRatingChangerFactory { /** * Create instance of {@link MovieRatingChanger}. * * @return {@link MovieRatingChanger} instance */ MovieRatingChanger create(); }
REDNBLACK/J-Kinopoisk2IMDB
core/src/main/java/org/f0w/k2i/core/exchange/MovieRatingChangerFactory.java
Java
apache-2.0
294
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.codepipeline.model; import java.io.Serializable; /** * <p> * Represents information about a gate declaration. * </p> */ public class BlockerDeclaration implements Serializable, Cloneable { /** * <p> * The name of the gate declaration. * </p> */ private String name; /** * <p> * The type of the gate declaration. * </p> */ private String type; /** * <p> * The name of the gate declaration. * </p> * * @param name * The name of the gate declaration. */ public void setName(String name) { this.name = name; } /** * <p> * The name of the gate declaration. * </p> * * @return The name of the gate declaration. */ public String getName() { return this.name; } /** * <p> * The name of the gate declaration. * </p> * * @param name * The name of the gate declaration. * @return Returns a reference to this object so that method calls can be * chained together. */ public BlockerDeclaration withName(String name) { setName(name); return this; } /** * <p> * The type of the gate declaration. * </p> * * @param type * The type of the gate declaration. * @see BlockerType */ public void setType(String type) { this.type = type; } /** * <p> * The type of the gate declaration. * </p> * * @return The type of the gate declaration. * @see BlockerType */ public String getType() { return this.type; } /** * <p> * The type of the gate declaration. * </p> * * @param type * The type of the gate declaration. * @return Returns a reference to this object so that method calls can be * chained together. * @see BlockerType */ public BlockerDeclaration withType(String type) { setType(type); return this; } /** * <p> * The type of the gate declaration. * </p> * * @param type * The type of the gate declaration. * @see BlockerType */ public void setType(BlockerType type) { this.type = type.toString(); } /** * <p> * The type of the gate declaration. * </p> * * @param type * The type of the gate declaration. * @return Returns a reference to this object so that method calls can be * chained together. * @see BlockerType */ public BlockerDeclaration withType(BlockerType type) { setType(type); return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getName() != null) sb.append("Name: " + getName() + ","); if (getType() != null) sb.append("Type: " + getType()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof BlockerDeclaration == false) return false; BlockerDeclaration other = (BlockerDeclaration) obj; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getType() == null ^ this.getType() == null) return false; if (other.getType() != null && other.getType().equals(this.getType()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getType() == null) ? 0 : getType().hashCode()); return hashCode; } @Override public BlockerDeclaration clone() { try { return (BlockerDeclaration) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
mhurne/aws-sdk-java
aws-java-sdk-codepipeline/src/main/java/com/amazonaws/services/codepipeline/model/BlockerDeclaration.java
Java
apache-2.0
5,406
package org.devocative.metis.web.odata2; import org.apache.olingo.odata2.api.ODataService; import org.apache.olingo.odata2.api.ODataServiceFactory; import org.apache.olingo.odata2.api.exception.ODataException; import org.apache.olingo.odata2.api.processor.ODataContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MetisServiceFactory extends ODataServiceFactory { private static final Logger logger = LoggerFactory.getLogger(MetisServiceFactory.class); @Override public ODataService createService(ODataContext ctx) throws ODataException { try { return createODataSingleProcessorService(MetisEdmProvider.get(), MetisODataSingleProcessor.get()); } catch (Exception e) { logger.error("Odata.MetisServiceFactory", e); throw new ODataException(e); } } }
mbizhani/Metis
web/src/main/java/org/devocative/metis/web/odata2/MetisServiceFactory.java
Java
apache-2.0
797
/* * Copyright 2017 Young Digital Planet S.A. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.ydp.empiria.player.client.components; import com.google.gwt.core.client.GWT; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.AbsolutePanel; import com.google.gwt.user.client.ui.HasWidgets; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Widget; import eu.ydp.gwtutil.client.NumberUtils; import java.util.Iterator; public class PanelWithScrollbars implements IsWidget, HasWidgets { private static PanelWithScrollbarsUiBinder uiBinder = GWT.create(PanelWithScrollbarsUiBinder.class); interface PanelWithScrollbarsUiBinder extends UiBinder<Widget, PanelWithScrollbars> { } @UiField AbsolutePanel mainPanel; @UiField AbsolutePanel horizontalScrollPanel; @UiField AbsolutePanel verticalScrollPanel; @UiField AbsolutePanel horizontalScrollSlider; @UiField AbsolutePanel verticalScrollSlider; private int mainPanelHeight; private int mainPanelWidth; private Timer fadeoutTimer; public PanelWithScrollbars() { uiBinder.createAndBindUi(this); fadeoutTimer = new Timer() { @Override public void run() { fadeOutElement(verticalScrollPanel.getElement(), 200); fadeOutElement(horizontalScrollPanel.getElement(), 200); } }; } public void setSize(String width, String height) { mainPanel.setSize(width, height); mainPanelHeight = NumberUtils.tryParseInt(height.replaceAll("\\D", ""), 0); mainPanelWidth = NumberUtils.tryParseInt(width.replaceAll("\\D", ""), 0); } public void setHorizontalPosition(double position, double sizeCurrent, double sizeAll, boolean showScrolls) { double left = horizontalScrollPanel.getOffsetWidth() * ((position / sizeAll)); horizontalScrollPanel.setWidgetPosition(horizontalScrollSlider, (int) left, 0); double width = horizontalScrollPanel.getOffsetWidth() * sizeCurrent / sizeAll; horizontalScrollSlider.setWidth(String.valueOf((int) width) + "px"); if (showScrolls) showScrollbars(); } public void setVerticalPosition(double position, double sizeCurrent, double sizeAll, boolean showScrolls) { double top = verticalScrollPanel.getOffsetHeight() * ((position / sizeAll)); verticalScrollPanel.setWidgetPosition(verticalScrollSlider, 0, (int) top); double height = verticalScrollPanel.getOffsetHeight() * sizeCurrent / sizeAll; verticalScrollSlider.setHeight(String.valueOf((int) height) + "px"); if (showScrolls) showScrollbars(); } @Override public Widget asWidget() { return mainPanel; } @Override public void add(Widget w) { mainPanel.add(w); } public void add(IsWidget w) { mainPanel.add(w); } @Override public void clear() { mainPanel.clear(); } @Override public Iterator<Widget> iterator() { return mainPanel.iterator(); } @Override public boolean remove(Widget w) { return mainPanel.remove(w); } private void showScrollbars() { fadeoutTimer.cancel(); int hScrollHeight = horizontalScrollPanel.getOffsetHeight(); mainPanel.setWidgetPosition(horizontalScrollPanel, 0, mainPanelHeight - hScrollHeight); int vScrollWidth = verticalScrollPanel.getOffsetWidth(); mainPanel.setWidgetPosition(verticalScrollPanel, mainPanelWidth - vScrollWidth, 0); setScrollbarsVisible(); fadeoutTimer.schedule(500); } private void setScrollbarsVisible() { verticalScrollPanel.setVisible(true); horizontalScrollPanel.setVisible(true); opacityto(verticalScrollPanel.getElement(), 100); opacityto(horizontalScrollPanel.getElement(), 100); } protected native void opacityto(com.google.gwt.dom.client.Element elm, int v)/*-{ elm.style.opacity = v / 100; elm.style.MozOpacity = v / 100; elm.style.KhtmlOpacity = v / 100; elm.style.filter = " alpha(opacity =" + v + ")"; }-*/; protected native void fadeOutElement(com.google.gwt.dom.client.Element element, int fadeEffectTime)/*-{ var instance = this; var _this = element; instance.@eu.ydp.empiria.player.client.components.PanelWithScrollbars::opacityto(Lcom/google/gwt/dom/client/Element;I)(_this, 100); var delay = fadeEffectTime; _this.style.zoom = 1; // for ie, set haslayout _this.style.display = "block"; for (i = 0; i <= 100; i += 5) { (function (j) { setTimeout(function () { j = 100 - j; instance.@eu.ydp.empiria.player.client.components.PanelWithScrollbars::opacityto(Lcom/google/gwt/dom/client/Element;I)(_this, j); }, j * delay / 100); })(i); } }-*/; }
YoungDigitalPlanet/empiria.player
src/main/java/eu/ydp/empiria/player/client/components/PanelWithScrollbars.java
Java
apache-2.0
5,835
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.treasuredata.client.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; /** * */ public class TDSaveQueryRequest { private final String name; private final String cron; private final TDJob.Type type; private final String query; private final String timezone; private final long delay; private final String database; private final int priority; private final int retryLimit; private final String result; private final TDJob.EngineVersion engineVersion; public TDSaveQueryRequest( @JsonProperty("name") String name, @JsonProperty("cron") String cron, @JsonProperty("type") TDJob.Type type, @JsonProperty("query") String query, @JsonProperty("timezone") String timezone, @JsonProperty("delay") long delay, @JsonProperty("database") String database, @JsonProperty("priority") int priority, @JsonProperty("retry_limit") int retryLimit, @JsonProperty("result") String result, @JsonProperty("engine_version") @JsonInclude(JsonInclude.Include.NON_NULL) TDJob.EngineVersion engineVersion) { this.name = name; this.cron = cron; this.type = type; this.query = query; this.timezone = timezone; this.delay = delay; this.database = database; this.priority = priority; this.retryLimit = retryLimit; this.result = result; this.engineVersion = engineVersion; } public String getName() { return name; } public String getCron() { return cron; } public TDJob.Type getType() { return type; } public String getQuery() { return query; } public String getTimezone() { return timezone; } public long getDelay() { return delay; } public String getDatabase() { return database; } public int getPriority() { return priority; } @JsonProperty("retry_limit") public int getRetryLimit() { return retryLimit; } public String getResult() { return result; } @JsonProperty("engine_version") @JsonInclude(JsonInclude.Include.NON_NULL) public TDJob.EngineVersion getEngineVersion() { return engineVersion; } }
treasure-data/td-client-java
src/main/java/com/treasuredata/client/model/TDSaveQueryRequest.java
Java
apache-2.0
3,278
/* * Copyright 2019-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bremersee.comparator; /** * The value extractor exception. * * @author Christian Bremer */ public class ValueExtractorException extends ComparatorException { /** * Instantiates a new value extractor exception. * * @param message the message */ public ValueExtractorException(String message) { super(message); } /** * Instantiates a new value extractor exception. * * @param message the message * @param cause the cause */ public ValueExtractorException(String message, Throwable cause) { super(message, cause); } }
bremersee/comparator
src/main/java/org/bremersee/comparator/ValueExtractorException.java
Java
apache-2.0
1,204
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.updateSettings.impl; import com.intellij.ide.IdeBundle; import com.intellij.ide.plugins.*; import com.intellij.ide.startup.StartupActionScriptManager; import com.intellij.openapi.application.*; import com.intellij.openapi.application.impl.ApplicationInfoImpl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.BuildNumber; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.PathUtil; import com.intellij.util.Urls; import com.intellij.util.io.HttpRequests; import com.intellij.util.io.ZipUtil; import com.intellij.util.text.VersionComparatorUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.nio.file.Path; import java.util.*; /** * @author anna */ public final class PluginDownloader { private static final Logger LOG = Logger.getInstance(PluginDownloader.class); private static final String FILENAME = "filename="; private final PluginId myPluginId; private final String myPluginName; private final @Nullable String myProductCode; private final Date myReleaseDate; private final int myReleaseVersion; private final String myDescription; private final List<PluginId> myDepends; private final String myPluginUrl; private final BuildNumber myBuildNumber; private String myPluginVersion; private IdeaPluginDescriptor myDescriptor; private File myFile; private File myOldFile; private boolean myShownErrors; private PluginDownloader(@NotNull IdeaPluginDescriptor descriptor, @NotNull String url, @Nullable BuildNumber buildNumber) { myPluginId = descriptor.getPluginId(); myPluginName = descriptor.getName(); myProductCode = descriptor.getProductCode(); myReleaseDate = descriptor.getReleaseDate(); myReleaseVersion = descriptor.getReleaseVersion(); myDescription = descriptor.getDescription(); myDepends = descriptor instanceof PluginNode ? ((PluginNode)descriptor).getDepends() : Arrays.asList(descriptor.getDependentPluginIds()); myPluginUrl = url; myBuildNumber = buildNumber; myPluginVersion = descriptor.getVersion(); myDescriptor = descriptor; } /** * @deprecated Use {@link #getId()} */ @NotNull @Deprecated public String getPluginId() { return myPluginId.getIdString(); } @NotNull public PluginId getId() { return myPluginId; } public String getPluginVersion() { return myPluginVersion; } @NotNull public String getPluginName() { return myPluginName != null ? myPluginName : myPluginId.getIdString(); } @Nullable public String getProductCode() { return myProductCode; } public Date getReleaseDate() { return myReleaseDate; } public int getReleaseVersion() { return myReleaseVersion; } @Nullable public BuildNumber getBuildNumber() { return myBuildNumber; } @NotNull public IdeaPluginDescriptor getDescriptor() { return myDescriptor; } public File getFile() { return myFile; } public boolean isShownErrors() { return myShownErrors; } public boolean prepareToInstall(@NotNull ProgressIndicator indicator) throws IOException { return prepareToInstallAndLoadDescriptor(indicator) != null; } @Nullable public IdeaPluginDescriptorImpl prepareToInstallAndLoadDescriptor(@NotNull ProgressIndicator indicator) throws IOException { myShownErrors = false; if (myFile != null) { IdeaPluginDescriptorImpl actualDescriptor = loadDescriptionFromJar(myFile.toPath()); myDescriptor = actualDescriptor; return actualDescriptor; } IdeaPluginDescriptor descriptor = null; if (!Boolean.getBoolean(StartupActionScriptManager.STARTUP_WIZARD_MODE) && PluginManagerCore.isPluginInstalled(myPluginId)) { //store old plugins file descriptor = PluginManagerCore.getPlugin(myPluginId); LOG.assertTrue(descriptor != null); if (myPluginVersion != null && compareVersionsSkipBrokenAndIncompatible(descriptor, myPluginVersion) <= 0) { LOG.info("Plugin " + myPluginId + ": current version (max) " + myPluginVersion); return null; } myOldFile = descriptor.isBundled() ? null : descriptor.getPath(); } // download plugin String errorMessage = null; try { myFile = downloadPlugin(indicator); } catch (IOException ex) { myFile = null; LOG.warn(ex); errorMessage = ex.getMessage(); } if (myFile == null) { Application app = ApplicationManager.getApplication(); if (app != null) { myShownErrors = true; if (errorMessage == null) { errorMessage = IdeBundle.message("unknown.error"); } String text = IdeBundle.message("error.plugin.was.not.installed", getPluginName(), errorMessage); String title = IdeBundle.message("title.failed.to.download"); app.invokeLater(() -> Messages.showErrorDialog(text, title), ModalityState.any()); } return null; } IdeaPluginDescriptorImpl actualDescriptor = loadDescriptionFromJar(myFile.toPath()); if (actualDescriptor != null) { InstalledPluginsState state = InstalledPluginsState.getInstanceIfLoaded(); if (state != null && state.wasUpdated(actualDescriptor.getPluginId())) { return null; //already updated } myPluginVersion = actualDescriptor.getVersion(); if (descriptor != null && compareVersionsSkipBrokenAndIncompatible(descriptor, myPluginVersion) <= 0) { LOG.info("Plugin " + myPluginId + ": current version (max) " + myPluginVersion); return null; //was not updated } myDescriptor = actualDescriptor; if (PluginManagerCore.isIncompatible(actualDescriptor, myBuildNumber)) { LOG.info("Plugin " + myPluginId + " is incompatible with current installation " + "(since:" + actualDescriptor.getSinceBuild() + " until:" + actualDescriptor.getUntilBuild() + ")"); return null; //host outdated plugins, no compatible plugin for new version } } return actualDescriptor; } public static int compareVersionsSkipBrokenAndIncompatible(@NotNull IdeaPluginDescriptor existingPlugin, String newPluginVersion) { int state = comparePluginVersions(newPluginVersion, existingPlugin.getVersion()); if (state < 0 && (PluginManagerCore.isBrokenPlugin(existingPlugin) || PluginManagerCore.isIncompatible(existingPlugin))) { state = 1; } return state; } public static int comparePluginVersions(String newPluginVersion, String oldPluginVersion) { return VersionComparatorUtil.compare(newPluginVersion, oldPluginVersion); } @Nullable public static IdeaPluginDescriptorImpl loadDescriptionFromJar(@NotNull Path file) throws IOException { IdeaPluginDescriptorImpl descriptor = PluginManager.loadDescriptor(file, PluginManagerCore.PLUGIN_XML); if (descriptor == null) { if (file.getFileName().toString().endsWith(".zip")) { final File outputDir = FileUtil.createTempDirectory("plugin", ""); try { ZipUtil.extract(file.toFile(), outputDir, null); final File[] files = outputDir.listFiles(); if (files != null && files.length == 1) { descriptor = PluginManager.loadDescriptor(files[0].toPath(), PluginManagerCore.PLUGIN_XML); } } finally { FileUtil.delete(outputDir); } } } return descriptor; } public void install() throws IOException { if (myFile == null) { throw new IOException("Plugin '" + getPluginName() + "' was not successfully downloaded"); } PluginInstaller.installAfterRestart(myFile, true, myOldFile, myDescriptor); InstalledPluginsState state = InstalledPluginsState.getInstanceIfLoaded(); if (state != null) { state.onPluginInstall(myDescriptor, PluginManagerCore.isPluginInstalled(myDescriptor.getPluginId()), true); } } public boolean tryInstallWithoutRestart(@Nullable JComponent ownerComponent) { final IdeaPluginDescriptorImpl descriptorImpl = (IdeaPluginDescriptorImpl)myDescriptor; if (!DynamicPlugins.allowLoadUnloadWithoutRestart(descriptorImpl)) return false; if (myOldFile != null) { IdeaPluginDescriptor installedPlugin = PluginManagerCore.getPlugin(myDescriptor.getPluginId()); if (installedPlugin == null) { return false; } IdeaPluginDescriptorImpl installedPluginDescriptor = PluginManager.loadDescriptor(((IdeaPluginDescriptorImpl)installedPlugin).getPluginPath(), PluginManagerCore.PLUGIN_XML, Collections.emptySet()); if (installedPluginDescriptor == null || !DynamicPlugins.unloadPlugin(installedPluginDescriptor)) { return false; } } PluginInstaller.installAndLoadDynamicPlugin(myFile, ownerComponent, descriptorImpl); return true; } @NotNull private File downloadPlugin(@NotNull ProgressIndicator indicator) throws IOException { File pluginsTemp = new File(PathManager.getPluginTempPath()); if (!pluginsTemp.exists() && !pluginsTemp.mkdirs()) { throw new IOException(IdeBundle.message("error.cannot.create.temp.dir", pluginsTemp)); } indicator.checkCanceled(); indicator.setText2(IdeBundle.message("progress.downloading.plugin", getPluginName())); File file = FileUtil.createTempFile(pluginsTemp, "plugin_", "_download", true, false); return HttpRequests.request(myPluginUrl).gzip(false).productNameAsUserAgent().connect(request -> { request.saveToFile(file, indicator); String fileName = guessFileName(request.getConnection(), file); File newFile = new File(file.getParentFile(), fileName); FileUtil.rename(file, newFile); return newFile; }); } @NotNull private String guessFileName(@NotNull URLConnection connection, @NotNull File file) throws IOException { String fileName = null; final String contentDisposition = connection.getHeaderField("Content-Disposition"); LOG.debug("header: " + contentDisposition); if (contentDisposition != null && contentDisposition.contains(FILENAME)) { final int startIdx = contentDisposition.indexOf(FILENAME); final int endIdx = contentDisposition.indexOf(';', startIdx); fileName = contentDisposition.substring(startIdx + FILENAME.length(), endIdx > 0 ? endIdx : contentDisposition.length()); if (StringUtil.startsWithChar(fileName, '\"') && StringUtil.endsWithChar(fileName, '\"')) { fileName = fileName.substring(1, fileName.length() - 1); } } if (fileName == null) { // try to find a filename in an URL final String usedURL = connection.getURL().toString(); LOG.debug("url: " + usedURL); fileName = usedURL.substring(usedURL.lastIndexOf('/') + 1); if (fileName.length() == 0 || fileName.contains("?")) { fileName = myPluginUrl.substring(myPluginUrl.lastIndexOf('/') + 1); } } if (!PathUtil.isValidFileName(fileName)) { LOG.debug("fileName: " + fileName); FileUtil.delete(file); throw new IOException("Invalid filename returned by a server"); } return fileName; } // creators-converters public static PluginDownloader createDownloader(@NotNull IdeaPluginDescriptor descriptor) throws IOException { return createDownloader(descriptor, null, null); } @NotNull public static PluginDownloader createDownloader( @NotNull IdeaPluginDescriptor descriptor, @Nullable String host, @Nullable BuildNumber buildNumber ) throws IOException { String url; try { if (host != null && descriptor instanceof PluginNode) { url = ((PluginNode)descriptor).getDownloadUrl(); if (!new URI(url).isAbsolute()) { url = new URL(new URL(host), url).toExternalForm(); } } else { final Map<String, String> parameters = new HashMap<>(); parameters.put("id", descriptor.getPluginId().getIdString()); parameters.put("build", getBuildNumberForDownload(buildNumber)); parameters.put("uuid", PermanentInstallationID.get()); url = Urls .newFromEncoded(ApplicationInfoImpl.getShadowInstance().getPluginsDownloadUrl()) .addParameters(parameters) .toExternalForm(); } } catch (URISyntaxException e) { throw new IOException(e); } return new PluginDownloader(descriptor, url, buildNumber); } @NotNull public static String getBuildNumberForDownload(@Nullable BuildNumber buildNumber) { return buildNumber != null ? buildNumber.asString() : PluginRepositoryRequests.getBuildForPluginRepositoryRequests(); } @NotNull public static PluginNode createPluginNode(@Nullable String host, @NotNull PluginDownloader downloader) { IdeaPluginDescriptor descriptor = downloader.getDescriptor(); if (descriptor instanceof PluginNode) { return (PluginNode)descriptor; } PluginNode node = new PluginNode(downloader.myPluginId); node.setName(downloader.getPluginName()); node.setProductCode(downloader.getProductCode()); node.setReleaseDate(downloader.getReleaseDate()); node.setReleaseVersion(downloader.getReleaseVersion()); node.setVersion(downloader.getPluginVersion()); node.setRepositoryName(host); node.setDownloadUrl(downloader.myPluginUrl); node.setDepends(downloader.myDepends, null); node.setDescription(downloader.myDescription); return node; } }
leafclick/intellij-community
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/PluginDownloader.java
Java
apache-2.0
14,000
package sssj.index.minibatch; import it.unimi.dsi.fastutil.BidirectionalIterator; import it.unimi.dsi.fastutil.ints.Int2DoubleMap.Entry; import it.unimi.dsi.fastutil.ints.Int2ReferenceMap; import it.unimi.dsi.fastutil.ints.Int2ReferenceOpenHashMap; import it.unimi.dsi.fastutil.longs.Long2DoubleMap; import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap; import java.util.Map; import sssj.index.AbstractIndex; import sssj.index.PostingEntry; import sssj.index.minibatch.component.PostingList; import sssj.index.minibatch.component.Residuals; import sssj.io.Vector; import sssj.util.Commons; public class APIndex extends AbstractIndex { private Int2ReferenceMap<PostingList> idx = new Int2ReferenceOpenHashMap<>(); private Residuals residuals = new Residuals(); private final double theta; private final double lambda; private final Vector maxVector; public APIndex(double theta, double lambda, Vector maxVector) { this.theta = theta; this.lambda = lambda; this.maxVector = maxVector; } @Override public Map<Long, Double> queryWith(final Vector v, final boolean addToIndex) { /* candidate generation */ Long2DoubleOpenHashMap accumulator = generateCandidates(v); /* candidate verification */ Long2DoubleOpenHashMap matches = verifyCandidates(v, accumulator); /* index building */ if (addToIndex) { Vector residual = addToIndex(v); residuals.add(residual); } return matches; } private Long2DoubleOpenHashMap generateCandidates(final Vector v) { Long2DoubleOpenHashMap accumulator = new Long2DoubleOpenHashMap(); double remscore = Vector.similarity(v, maxVector); /* candidate generation */ for (BidirectionalIterator<Entry> it = v.int2DoubleEntrySet().fastIterator(v.int2DoubleEntrySet().last()); it .hasPrevious();) { // iterate over v in reverse order Entry e = it.previous(); int dimension = e.getIntKey(); double queryWeight = e.getDoubleValue(); // x_j PostingList list; if ((list = idx.get(dimension)) != null) { for (PostingEntry pe : list) { numPostingEntries++; final long targetID = pe.getID(); // y if (accumulator.containsKey(targetID) || Double.compare(remscore, theta) >= 0) { final double targetWeight = pe.getWeight(); // y_j final double additionalSimilarity = queryWeight * targetWeight; // x_j * y_j accumulator.addTo(targetID, additionalSimilarity); // A[y] += x_j * y_j } } } remscore -= queryWeight * maxVector.get(dimension); } numCandidates += accumulator.size(); return accumulator; } private Long2DoubleOpenHashMap verifyCandidates(final Vector v, Long2DoubleOpenHashMap accumulator) { Long2DoubleOpenHashMap matches = new Long2DoubleOpenHashMap(); for (Long2DoubleMap.Entry e : accumulator.long2DoubleEntrySet()) { long candidateID = e.getLongKey(); Vector candidateResidual = residuals.get(candidateID); assert (candidateResidual != null); double score = e.getDoubleValue() + Vector.similarity(v, candidateResidual); // A[y] + dot(y',x) long deltaT = v.timestamp() - candidateID; score *= Commons.forgettingFactor(lambda, deltaT); // apply forgetting factor numSimilarities++; if (Double.compare(score, theta) >= 0) // final check matches.put(candidateID, score); } numMatches += matches.size(); return matches; } private Vector addToIndex(final Vector v) { double pscore = 0; Vector residual = new Vector(v.timestamp()); for (Entry e : v.int2DoubleEntrySet()) { int dimension = e.getIntKey(); double weight = e.getDoubleValue(); pscore += weight * maxVector.get(dimension); if (Double.compare(pscore, theta) >= 0) { PostingList list; if ((list = idx.get(dimension)) == null) { list = new PostingList(); idx.put(dimension, list); } list.add(v.timestamp(), weight); size++; // v.remove(dimension); } else { residual.put(dimension, weight); } } return residual; } @Override public String toString() { return "APIndex [idx=" + idx + ", residuals=" + residuals + "]"; } }
gdfm/sssj
src/main/java/sssj/index/minibatch/APIndex.java
Java
apache-2.0
4,286
package com.mvpdemo.luch.mvp.Model; import com.mvpdemo.luch.mvp.Contract.PhotoContract; import rx.Observer; /** * Creator lh on 2017/4/28 10:16. * Email:3021634343@qq.com * Description: */ public class PhotoModel implements PhotoContract.Model{ @Override public void getPhoto(int page, Observer observer) { } }
Luhangh/MvpSample
app/src/main/java/com/mvpdemo/luch/mvp/Model/PhotoModel.java
Java
apache-2.0
334
/* * Copyright 2015 Fabio Collini. * * 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 it.cosenonjaviste.demomv2m.ui; import android.support.design.widget.Snackbar; import it.cosenonjaviste.demomv2m.core.MessageManager; import it.cosenonjaviste.mv2m.ActivityHolder; public class SnackbarMessageManager implements MessageManager { @Override public void showMessage(ActivityHolder activityHolder, int message) { if (activityHolder != null) { Snackbar.make(activityHolder.getActivity().findViewById(android.R.id.content), message, Snackbar.LENGTH_LONG).show(); } } }
fabioCollini/mv2m
demo/src/main/java/it/cosenonjaviste/demomv2m/ui/SnackbarMessageManager.java
Java
apache-2.0
1,126
/* * Copyright 2012 Bangkok Project Team, GRIDSOLUT GmbH + Co.KG, and * University of Stuttgart (Institute of Architecture of Application Systems) * All Rights Reserved. * * 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.htm.peopleresolution; import com.htm.peopleresolutionprovider.LpgResolutionProvider_UserByGroup; import com.htm.taskmodel.ILogicalPeopleGroupDef; public class LPGResolutionProviderFactory { private static LpgResolutionProvider_UserByGroup userByGroup; public static IPeopleResolutionProvider createPeopleResolutionProvider( ILogicalPeopleGroupDef lpgDefinition) { /* Here all logical people group resolution provider must be registered. */ if (lpgDefinition .equals(LpgResolutionProvider_UserByGroup.SUPPORTED_LPG_DEF)) { /* Avoid multiple instantiation */ if (userByGroup == null) { return new LpgResolutionProvider_UserByGroup(); } return userByGroup; } else { throw new RuntimeException( "No logical people goup resolution provider can be found for logical " + "people group definition " + lpgDefinition.getName() + ".");// TODO Exception handling } } }
ungerts/task-manager
src/main/java/com/htm/peopleresolution/LPGResolutionProviderFactory.java
Java
apache-2.0
1,836
package org.iii.sample; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App implements CommandLineRunner{ public static void main(String[] args) { SpringApplication.run(App.class, args); } public void run(String... arg0) throws Exception { } }
yugzan/spring-study
sample-gmaildeliver/src/main/java/org/iii/sample/App.java
Java
apache-2.0
418
/* * Copyright (c) 2013, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software;Designed and Developed mainly by many Chinese * opensource volunteers. you can redistribute it and/or modify it under the * terms of the GNU General Public License version 2 only, as published by the * Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Any questions about this component can be directed to it's project Web address * https://code.google.com/p/opencloudb/. * */ package com.talent.mysql.utils; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * 加密解密工具类 * 摘自cobar * */ public class SecurityUtil { public static final byte[] scramble411(byte[] pass, byte[] seed) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] pass1 = md.digest(pass); md.reset(); byte[] pass2 = md.digest(pass1); md.reset(); md.update(seed); byte[] pass3 = md.digest(pass2); for (int i = 0; i < pass3.length; i++) { pass3[i] = (byte) (pass3[i] ^ pass1[i]); } return pass3; } public static final String scramble323(String pass, String seed) { if ((pass == null) || (pass.length() == 0)) { return pass; } byte b; double d; long[] pw = hash(seed); long[] msg = hash(pass); long max = 0x3fffffffL; long seed1 = (pw[0] ^ msg[0]) % max; long seed2 = (pw[1] ^ msg[1]) % max; char[] chars = new char[seed.length()]; for (int i = 0; i < seed.length(); i++) { seed1 = ((seed1 * 3) + seed2) % max; seed2 = (seed1 + seed2 + 33) % max; d = (double) seed1 / (double) max; b = (byte) java.lang.Math.floor((d * 31) + 64); chars[i] = (char) b; } seed1 = ((seed1 * 3) + seed2) % max; seed2 = (seed1 + seed2 + 33) % max; d = (double) seed1 / (double) max; b = (byte) java.lang.Math.floor(d * 31); for (int i = 0; i < seed.length(); i++) { chars[i] ^= (char) b; } return new String(chars); } private static long[] hash(String src) { long nr = 1345345333L; long add = 7; long nr2 = 0x12345671L; long tmp; for (int i = 0; i < src.length(); ++i) { switch (src.charAt(i)) { case ' ': case '\t': continue; default: tmp = (0xff & src.charAt(i)); nr ^= ((((nr & 63) + add) * tmp) + (nr << 8)); nr2 += ((nr2 << 8) ^ nr); add += tmp; } } long[] result = new long[2]; result[0] = nr & 0x7fffffffL; result[1] = nr2 & 0x7fffffffL; return result; } }
youngor/openclouddb
MyCat-Balance/src/main/java/com/talent/mysql/utils/SecurityUtil.java
Java
apache-2.0
3,610
/** * Copyright (C) 2006-2013 phloc systems * http://www.phloc.com * office[at]phloc[dot]com * * 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.phloc.commons.supplementary.test.java; import java.io.Serializable; import java.security.Provider; import java.security.Security; import java.util.Comparator; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.phloc.commons.collections.ContainerHelper; public final class FuncTestJavaListDigestProvider { private static final class ProviderComparator implements Comparator <Provider>, Serializable { public int compare (final Provider o1, final Provider o2) { return o1.getName ().compareTo (o2.getName ()); } } private static final class AlgorithmComparator implements Comparator <Object>, Serializable { public int compare (final Object o1, final Object o2) { return o1.toString ().compareTo (o2.toString ()); } } private static final Logger s_aLogger = LoggerFactory.getLogger (FuncTestJavaListDigestProvider.class); @Test public void testListAllDigestProvider () { for (final Provider element : ContainerHelper.getSorted (ContainerHelper.newList (Security.getProviders ()), new ProviderComparator ())) { s_aLogger.info ("Provider: '" + element + "'"); for (final Object sAlgo : ContainerHelper.getSortedByKey (element, new AlgorithmComparator ()).keySet ()) s_aLogger.info ("\t" + sAlgo); } } }
lsimons/phloc-schematron-standalone
phloc-commons/src/test/java/com/phloc/commons/supplementary/test/java/FuncTestJavaListDigestProvider.java
Java
apache-2.0
2,072
/* * (c) Copyright 2022 Palantir Technologies Inc. All rights reserved. * * 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.palantir.atlasdb.backup; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import org.immutables.value.Value; @JsonSerialize(as = ImmutableRestoreRequestWithId.class) @JsonDeserialize(as = ImmutableRestoreRequestWithId.class) @Value.Immutable public interface RestoreRequestWithId { RestoreRequest restoreRequest(); String backupId(); static RestoreRequestWithId of(RestoreRequest restoreRequest, String backupId) { return ImmutableRestoreRequestWithId.builder() .restoreRequest(restoreRequest) .backupId(backupId) .build(); } }
palantir/atlasdb
atlasdb-ete-tests/src/main/java/com/palantir/atlasdb/backup/RestoreRequestWithId.java
Java
apache-2.0
1,333
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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.facebook.buck.core.model.graph; import com.facebook.buck.core.model.actiongraph.ActionGraphAndBuilder; import com.facebook.buck.core.model.targetgraph.TargetGraph; import com.facebook.buck.core.model.targetgraph.TargetGraphCreationResult; import com.facebook.buck.core.util.immutables.BuckStyleImmutable; import java.util.Optional; import org.immutables.value.Value; /** * Container class for {@link ActionGraphAndBuilder} and {@link TargetGraphCreationResult}. Also * contains helper methods to choose which {@link TargetGraph} to use ({@link * com.facebook.buck.versions.VersionedTargetGraph} vs un-versioned). */ @Value.Immutable @BuckStyleImmutable abstract class AbstractActionAndTargetGraphs { abstract TargetGraphCreationResult getUnversionedTargetGraph(); abstract Optional<TargetGraphCreationResult> getVersionedTargetGraph(); public abstract ActionGraphAndBuilder getActionGraphAndBuilder(); /** Helper method to choose versioned vs un-versioned {@link TargetGraph}. */ public static TargetGraphCreationResult getTargetGraph( TargetGraphCreationResult unversionedTargetGraph, Optional<TargetGraphCreationResult> versionedTargetGraph) { // If a versioned target graph was produced then we always use it, // otherwise the unversioned graph is used. return versionedTargetGraph.orElse(unversionedTargetGraph); } /** Helper method to get the appropriate {@link TargetGraph}. */ public TargetGraphCreationResult getTargetGraph() { return getTargetGraph(getUnversionedTargetGraph(), getVersionedTargetGraph()); } }
zpao/buck
src/com/facebook/buck/core/model/graph/AbstractActionAndTargetGraphs.java
Java
apache-2.0
2,206
package com.xinyou.frame.searchstruct; public class CoSearch { public String getCo_guid() { return co_guid; } public void setCo_guid(String co_guid) { this.co_guid = co_guid; } public String getCo_id() { return co_id; } public void setCo_id(String co_id) { this.co_id = co_id; } public String getCo_name() { return co_name; } public void setCo_name(String co_name) { this.co_name = co_name; } public int getPage_no() { return page_no; } public void setPage_no(int page_no) { this.page_no = page_no; } public int getPage_size() { return page_size; } public void setPage_size(int page_size) { this.page_size = page_size; } private String co_guid; private String co_id; private String co_name; private int page_no; private int page_size; }
mikeleishen/bacosys
frame/frame-service/src/main/java/com/xinyou/frame/searchstruct/CoSearch.java
Java
apache-2.0
787
package com.yjl.javabase.thinkinjava.operators;//: operators/Exponents.java // "e" means "10 to the power." public class Exponents { public static void main(String[] args) { // Uppercase and lowercase 'e' are the same: float expFloat = 1.39e-43f; expFloat = 1.39E-43f; System.out.println(expFloat); double expDouble = 47e47d; // 'd' is optional double expDouble2 = 47e47; // Automatically double System.out.println(expDouble); } } /* Output: 1.39E-43 4.7E48 *///:~
yangjunlin-const/WhileTrueCoding
JavaBase/src/main/java/com/yjl/javabase/thinkinjava/operators/Exponents.java
Java
apache-2.0
498