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
|
---|---|---|---|---|---|
/*
* Source https://github.com/evanx by @evanxsummers
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 vellum.crypto;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.Arrays;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vellum.util.Base64;
/**
*
* @author evan.summers
*/
public class Passwords {
static final Logger logger = LoggerFactory.getLogger(Passwords.class);
public static final int HASH_MILLIS = 200;
public static final String ALGORITHM = "PBKDF2WithHmacSHA1";
public static final int ITERATION_COUNT = 100*1000;
public static final int KEY_SIZE = 160;
public static final int SALT_LENGTH = 16;
public static final int ENCODED_SALT_LENGTH = 24;
public static byte[] generateSalt() {
byte[] salt = new byte[SALT_LENGTH];
SecureRandom random = new SecureRandom();
random.nextBytes(salt);
return salt;
}
public static byte[] hashPassword(char[] password, byte[] salt)
throws GeneralSecurityException {
return hashPassword(password, salt, ITERATION_COUNT, KEY_SIZE);
}
public static byte[] hashPassword(char[] password, byte[] salt,
int iterationCount, int keySize) throws GeneralSecurityException {
long timestamp = System.currentTimeMillis();
try {
PBEKeySpec spec = new PBEKeySpec(password, salt, iterationCount, keySize);
SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
return factory.generateSecret(spec).getEncoded();
} catch (IllegalArgumentException e) {
throw new GeneralSecurityException("key size " + keySize, e);
} finally {
long duration = System.currentTimeMillis() - timestamp;
if (duration < HASH_MILLIS) {
logger.warn("hashPassword {}ms", duration);
}
}
}
public static boolean matches(char[] password, String passwordHash, String salt)
throws GeneralSecurityException {
return matches(password, passwordHash, salt, ITERATION_COUNT, KEY_SIZE);
}
public static boolean matches(char[] password, String passwordHash, String salt, int iterationCount, int keySize)
throws GeneralSecurityException {
return matches(password, Base64.decode(passwordHash), Base64.decode(salt), iterationCount, keySize);
}
public static boolean matches(char[] password, byte[] passwordHash, byte[] salt)
throws GeneralSecurityException {
return matches(password, passwordHash, salt, ITERATION_COUNT, KEY_SIZE);
}
public static boolean matches(char[] password, byte[] passwordHash, byte[] salt,
int iterationCount, int keySize) throws GeneralSecurityException {
return Arrays.equals(passwordHash, hashPassword(password, salt,
iterationCount, keySize));
}
}
| evanx/vellumcore | src/vellum/crypto/Passwords.java | Java | apache-2.0 | 3,861 |
package se.ugli.habanero.j.datasource;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import se.ugli.habanero.j.HabaneroException;
class DBCPDataSourceFactory {
public static DataSource create(final Properties properties) {
try {
return BasicDataSourceFactory.createDataSource(properties);
} catch (final Exception e) {
throw new HabaneroException(e);
}
}
}
| ugli/habanero-java | src/main/java/se/ugli/habanero/j/datasource/DBCPDataSourceFactory.java | Java | apache-2.0 | 445 |
package cz.muni.fi.pa165.methanolmanager.service.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author Petr Barton
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ProducerDto {
public Integer id;
private String name;
private long producedToxicBottles;
}
| matobet/methanol-manager | service-api/src/main/java/cz/muni/fi/pa165/methanolmanager/service/dto/ProducerDto.java | Java | apache-2.0 | 338 |
package sk.skrecyclerview.event;
/**
* Created by SK on 2017-05-09.
*/
public class UpdateEvent {
}
| magicbaby810/homepage | app/src/main/java/sk/skrecyclerview/event/UpdateEvent.java | Java | apache-2.0 | 112 |
package lodVader.mongodb.collections.RDFResources.rdfType;
import java.util.Iterator;
import java.util.Set;
import lodVader.exceptions.LODVaderMissingPropertiesException;
import lodVader.exceptions.mongodb.LODVaderNoPKFoundException;
import lodVader.exceptions.mongodb.LODVaderObjectAlreadyExistsException;
import lodVader.mongodb.collections.RDFResources.GeneralRDFResourceDB;
public class RDFTypeSubjectDB extends GeneralRDFResourceDB{
public static final String COLLECTION_NAME = "RDFTypeSubjects";
public RDFTypeSubjectDB(String id) {
super(COLLECTION_NAME, id);
}
public RDFTypeSubjectDB() {
super(COLLECTION_NAME);
}
@Override
public void insertSet(Set<String> set) {
Iterator<String> i = set.iterator();
RDFTypeSubjectDB t = null;
while(i.hasNext()){
t=new RDFTypeSubjectDB(i.next());
try {
t.update(true);
} catch (LODVaderMissingPropertiesException | LODVaderObjectAlreadyExistsException
| LODVaderNoPKFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
| AKSW/LODVader | src/main/java/lodVader/mongodb/collections/RDFResources/rdfType/RDFTypeSubjectDB.java | Java | apache-2.0 | 1,050 |
/*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.dialogflow.v3.model;
/**
* InputDataset used to create model or do evaluation. NextID:5
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Dialogflow API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GoogleCloudDialogflowV2InputDataset extends com.google.api.client.json.GenericJson {
/**
* Required. ConversationDataset resource name. Format:
* `projects//locations//conversationDatasets/`
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String dataset;
/**
* Required. ConversationDataset resource name. Format:
* `projects//locations//conversationDatasets/`
* @return value or {@code null} for none
*/
public java.lang.String getDataset() {
return dataset;
}
/**
* Required. ConversationDataset resource name. Format:
* `projects//locations//conversationDatasets/`
* @param dataset dataset or {@code null} for none
*/
public GoogleCloudDialogflowV2InputDataset setDataset(java.lang.String dataset) {
this.dataset = dataset;
return this;
}
@Override
public GoogleCloudDialogflowV2InputDataset set(String fieldName, Object value) {
return (GoogleCloudDialogflowV2InputDataset) super.set(fieldName, value);
}
@Override
public GoogleCloudDialogflowV2InputDataset clone() {
return (GoogleCloudDialogflowV2InputDataset) super.clone();
}
}
| googleapis/google-api-java-client-services | clients/google-api-services-dialogflow/v3/1.31.0/com/google/api/services/dialogflow/v3/model/GoogleCloudDialogflowV2InputDataset.java | Java | apache-2.0 | 2,438 |
/*
* Desenvolvido pela equipe Super-Bits.com CNPJ 20.019.971/0001-90
*/
package com.super_bits.modulosSB.webPaginas.util.geradorCodigo;
import com.super_bits.modulos.SBAcessosModel.model.acoes.AcaoDoSistema;
import com.super_bits.modulosSB.SBCore.UtilGeral.MapaAcoesSistema;
import com.super_bits.modulosSB.SBCore.UtilGeral.UtilSBCoreStrings;
import com.super_bits.modulosSB.SBCore.UtilGeral.UtilSBCoreStringsCammelCase;
import com.super_bits.modulosSB.SBCore.modulos.Controller.Interfaces.acoes.ItfAcaoController;
import com.super_bits.modulosSB.SBCore.modulos.Controller.Interfaces.acoes.ItfAcaoControllerEntidade;
import com.super_bits.modulosSB.SBCore.modulos.Controller.Interfaces.acoes.ItfAcaoDoSistema;
import com.super_bits.modulosSB.SBCore.modulos.Controller.Interfaces.acoes.ItfAcaoSelecionarAcao;
import com.super_bits.modulosSB.SBCore.modulos.Controller.Interfaces.permissoes.ItfAcaoFormulario;
import com.super_bits.modulosSB.SBCore.modulos.Controller.Interfaces.permissoes.ItfAcaoFormularioEntidade;
import com.super_bits.modulosSB.SBCore.modulos.Controller.Interfaces.permissoes.ItfAcaoGerenciarEntidade;
import org.jboss.forge.roaster.model.source.JavaClassSource;
/**
*
* @author SalvioF
*/
public class GeradorGetAcaoDaGestao extends GeradorClasseEscopoApp {
private final ItfAcaoGerenciarEntidade pAcao;
private boolean codigoGerado = false;
public GeradorGetAcaoDaGestao(ItfAcaoGerenciarEntidade pAcao) {
super("org.coletivoJava.superBitsFW.webPaginas.config", getNomeClasseGetAcoesGestao(pAcao));
this.pAcao = pAcao;
gerarCodigo();
}
private static String getNomeClasseGetAcoesGestao(ItfAcaoGerenciarEntidade pAcao) {
return "Acoes"
+ UtilSBCoreStringsCammelCase.getCamelByTextoPrimeiraLetraMaiusculaSemCaracterEspecial(pAcao.getModulo().getEnumVinculado().toString())
+ "_"
+ UtilSBCoreStringsCammelCase.getCamelByTextoPrimeiraLetraMaiusculaSemCaracterEspecial(pAcao.getEnumAcaoDoSistema().toString());
}
public static void adicionarAcao(JavaClassSource estruturaClasse, ItfAcaoDoSistema pAcao) {
String nomePropriedade = UtilSBCoreStringsCammelCase.getCamelByTextoPrimeiraLetraMaiusculaSemCaracterEspecial(pAcao.getEnumAcaoDoSistema().toString());
String nomeMetodo = "get" + nomePropriedade;
Class tipoRetorno = ItfAcaoDoSistema.class;
switch (pAcao.getTipoAcaoSistema()) {
case ACAO_DO_SISTEMA:
tipoRetorno = AcaoDoSistema.class;
break;
case ACAO_ENTIDADE_FORMULARIO:
tipoRetorno = ItfAcaoFormularioEntidade.class;
break;
case ACAO_FORMULARIO:
tipoRetorno = ItfAcaoFormulario.class;
break;
case ACAO_ENTIDADE_FORMULARIO_MODAL:
tipoRetorno = ItfAcaoFormulario.class;
break;
case ACAO_ENTIDADE_GERENCIAR:
tipoRetorno = ItfAcaoFormulario.class;
break;
case ACAO_ENTIDADE_CONTROLLER:
tipoRetorno = ItfAcaoControllerEntidade.class;
break;
case ACAO_CONTROLLER:
tipoRetorno = ItfAcaoController.class;
break;
case ACAO_SELECAO_DE_ACAO:
tipoRetorno = ItfAcaoSelecionarAcao.class;
break;
default:
throw new AssertionError(pAcao.getTipoAcaoSistema().name());
}
//+ "" + pAcao.getNomeUnico() + " }";
estruturaClasse.addMethod()
.setPublic()
.setName(nomeMetodo)
.setReturnType(tipoRetorno)
.setBody(" return (" + tipoRetorno.getSimpleName() + ") MapaAcoesSistema.getAcaoDoSistemaByNomeUnico(\"" + pAcao.getNomeUnico() + "\");");
}
public final JavaClassSource gerarCodigo() {
if (codigoGerado) {
return getCodigoJava();
}
System.out.println("AcoesVinculadas=" + pAcao.getAcoesVinculadas());
getCodigoJava().addImport(MapaAcoesSistema.class);
adicionarAcao(getCodigoJava(), pAcao);
for (ItfAcaoDoSistema acao : pAcao.getAcoesVinculadas()) {
adicionarAcao(getCodigoJava(), acao);
}
return getCodigoJava();
}
}
| salviof/SuperBits_FrameWork | SB_FRAMEWORK/SBWebPaginasSemTagLib/src/main/java/com/super_bits/modulosSB/webPaginas/util/geradorCodigo/GeradorGetAcaoDaGestao.java | Java | apache-2.0 | 4,358 |
/*
* Copyright 2020 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.ml4j.nn.components.builders;
import org.ml4j.nn.axons.BiasVector;
import org.ml4j.nn.axons.FeaturesVector;
import org.ml4j.nn.axons.WeightsMatrix;
import org.ml4j.nn.axons.WeightsVector;
/**
* Interface for helper to load YOLO v2 weights
*
* @author Michael Lavelle
*
*/
public interface YOLOv2WeightsLoader {
WeightsMatrix getConvolutionalLayerWeights(String name, int width, int height, int inputDepth, int outputDepth);
BiasVector getConvolutionalLayerBiases(String name, int outputDepth);
WeightsVector getBatchNormLayerWeights(String name, int inputDepth);
BiasVector getBatchNormLayerBias(String name, int inputDepth);
FeaturesVector getBatchNormLayerMovingVariance(String name, int inputDepth);
FeaturesVector getBatchNormLayerMovingMean(String name, int inputDepth);
}
| ml4j/ml4j-impl | ml4j-builders-impl/src/test/java/org/ml4j/nn/components/builders/YOLOv2WeightsLoader.java | Java | apache-2.0 | 1,423 |
/*
* #%L
* AbstractTransportConnectionTestCases.java - mongodb-async-driver - Allanbank Consulting, Inc.
* %%
* Copyright (C) 2011 - 2014 Allanbank Consulting, 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.
* #L%
*/
package com.allanbank.mongodb.client.connection.socket;
import java.io.IOException;
import java.net.SocketException;
import com.allanbank.mongodb.MongoClientConfiguration;
import com.allanbank.mongodb.bson.io.StringDecoderCache;
import com.allanbank.mongodb.bson.io.StringEncoderCache;
import com.allanbank.mongodb.client.state.Server;
import com.allanbank.mongodb.client.transport.Transport;
import com.allanbank.mongodb.client.transport.TransportFactory;
import com.allanbank.mongodb.client.transport.TransportOutputBuffer;
import com.allanbank.mongodb.client.transport.bio.one.OneThreadTransportFactory;
/**
* AbstractTransportConnectionTestCases provides tests for the
* {@link TransportConnection} class when using the
* {@link OneThreadTransportFactory}.
*
* @copyright 2011-2015, Allanbank Consulting, Inc., All Rights Reserved
*/
public class OneThreadTransportConnectionTest
extends AbstractTransportConnectionTestCases {
/**
* Creates the {@link TransportConnection} using a
* {@link OneThreadTransportFactory}.
*
* @param server
* The server to connect to.
* @param config
* The configuration for the connection.
* @throws SocketException
* On a failure connecting.
* @throws IOException
* On a failure talking to the server.
*/
@Override
@SuppressWarnings("unchecked")
protected void connect(final Server server,
final MongoClientConfiguration config) throws SocketException,
IOException {
myTestConnection = new TransportConnection(server, config, myCollector);
final TransportFactory factory = new OneThreadTransportFactory();
final Transport<TransportOutputBuffer> transport = (Transport<TransportOutputBuffer>) factory
.createTransport(server, config, new StringEncoderCache(),
new StringDecoderCache(), myTestConnection);
myTestConnection.setTransport(transport);
myTestConnection.start();
}
}
| allanbank/mongodb-async-driver | src/test/java/com/allanbank/mongodb/client/connection/socket/OneThreadTransportConnectionTest.java | Java | apache-2.0 | 2,803 |
package com.litmantech.readrecorder.audio;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.util.Log;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Created by Jeff_Dev_PC on 5/19/2016.
*/
public class Playback {
private static final String TAG = "Playback";
private final int sampleRate;
private final int minBufSize;
private final AudioTrack audioTrack;
private Thread playbackThread;
private boolean stopPlayBack;
private LinkedBlockingQueue<short[]> audioQueue;
/**
* Playback will create a new Audio Track and call play.
*/
public Playback(){
sampleRate = 16000;
minBufSize = AudioRecord.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, minBufSize, AudioTrack.MODE_STREAM);
}
/**
* asynchronously play audio data.
* @return a LinkedBlockingQueue that you will continuously put your audio into.
*/
public LinkedBlockingQueue<short[]> Play(){
Log.d(TAG,"Start called");
if(playbackThread !=null)
return audioQueue;
audioTrack.play();
audioQueue = new LinkedBlockingQueue<>();
playbackThread = new Thread(new Runnable() {
@Override
public void run() {
stopPlayBack = false;
AsyncPlay(audioQueue);
audioTrack.stop();
playbackThread = null;
}
});
playbackThread.start();
return audioQueue;
}
private void AsyncPlay(LinkedBlockingQueue<short[]> audioQueue) {
while (!stopPlayBack){
try {
short[] audioData = audioQueue.take();//this will block, will need to call interrupt on this thread
WriteAudio(audioData);
} catch (InterruptedException e) {
// Don't care is the thread is Interrupted. Its ok we'll do nothing...
}
}
}
private void WriteAudio(short[] audioData){
audioTrack.write(audioData,0,audioData.length);
}
/**
* Will block your thread until stop is done. if you get locked and want to get out just call interrupt(); on the thread
*/
public void Stop() {
Log.d(TAG,"Stop called");
stopPlayBack = true;
if(playbackThread != null){
try {
playbackThread.interrupt();
playbackThread.join();
} catch (InterruptedException e) {/*we will do nothing here. dont care if another thread interrupts this thread*/}
}
}
}
| JeffTheJava/Read_Recorder | Android_App/ReadRecorder/app/src/main/java/com/litmantech/readrecorder/audio/Playback.java | Java | apache-2.0 | 2,920 |
package com.angkorteam.pluggable.framework.validation.constraints;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* The annotated element must be a number whose value must be higher or equal to
* the specified minimum.
* <p/>
* Supported types are:
* <ul>
* <li>{@code BigDecimal}</li>
* <li>{@code BigInteger}</li>
* <li>{@code byte}, {@code short}, {@code int}, {@code long}, and their
* respective wrappers</li>
* </ul>
* Note that {@code double} and {@code float} are not supported due to rounding
* errors (some providers might provide some approximative support).
* <p/>
* {@code null} elements are considered valid.
*
* @author Socheat KHAUV
*/
@Target({ FIELD })
@Retention(RUNTIME)
@Documented
public @interface Min {
/**
* @return value the element must be higher or equal to
*/
int value();
}
| PkayJava/pluggable | framework/src/main/java/com/angkorteam/pluggable/framework/validation/constraints/Min.java | Java | apache-2.0 | 1,031 |
package org.rmatil.sync.network.core.model;
import java.io.Serializable;
/**
* Holds encrypted data for transmitting over the network
*/
public class EncryptedData implements Serializable {
private static final long serialVersionUID = - 4560981371427777538L;
/**
* The signature of the data
*/
protected byte[] signature;
/**
* Holds the encrypted symmetric key,
* i.e. an RSA-encrypted AES key
*/
protected byte[] encryptedKey;
/**
* Holds the symmetric encrypted data
*/
protected byte[] encryptedData;
/**
* @param signature The signature
* @param encryptedKey The RSA encrypted symmetric key
* @param encryptedData The symmetrically encrypted data
*/
public EncryptedData(byte[] signature, byte[] encryptedKey, byte[] encryptedData) {
this.signature = signature;
this.encryptedKey = encryptedKey;
this.encryptedData = encryptedData;
}
/**
* Returns the signature of the plain text
*
* @return The signature of the plain text message
*/
public byte[] getSignature() {
return signature;
}
/**
* Returns the RSA encrypted symmetric key
*
* @return The encrypted symmetric key
*/
public byte[] getEncryptedKey() {
return encryptedKey;
}
/**
* Returns the symmetrically encrypted data
*
* @return The encrypted data
*/
public byte[] getEncryptedData() {
return encryptedData;
}
}
| p2p-sync/network | src/main/java/org/rmatil/sync/network/core/model/EncryptedData.java | Java | apache-2.0 | 1,535 |
package com.deepoove.poi.tl.issue;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFNum;
import org.apache.poi.xwpf.usermodel.XWPFNumbering;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.DocxRenderData;
import com.deepoove.poi.tl.source.XWPFTestSupport;
import com.deepoove.poi.xwpf.XWPFNumberingWrapper;
@DisplayName("Issue257 列表序号合并重新开始编号")
public class Issue257 {
@Test
public void testDocxMerge() throws Exception {
// 编号继续前一个编号可以修改为重新开始编号
Map<String, Object> params = new HashMap<String, Object>();
params.put("docx",
new DocxRenderData(new File("src/test/resources/issue/257_MERGE.docx"), Arrays.asList(1, 2)));
XWPFTemplate doc = XWPFTemplate.compile("src/test/resources/issue/257.docx");
doc.render(params);
XWPFDocument document = XWPFTestSupport.readNewDocument(doc);
XWPFNumbering numbering = document.getNumbering();
XWPFNumberingWrapper numberingWrapper = new XWPFNumberingWrapper(numbering);
List<XWPFNum> nums = numberingWrapper.getNums();
Set<BigInteger> abstracNumSet = new HashSet<>();
for (XWPFNum num : nums) {
BigInteger abstractNumId = num.getCTNum().getAbstractNumId().getVal();
assertTrue(abstracNumSet.add(abstractNumId));
}
document.close();
}
}
| Sayi/poi-tl | poi-tl/src/test/java/com/deepoove/poi/tl/issue/Issue257.java | Java | apache-2.0 | 1,799 |
package io.norberg.automatter.example;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static java.lang.System.out;
public class SimpleExample {
public static void main(final String... args) throws IOException {
Foobar foobar = new FoobarBuilder()
.foo("hello world")
.bar(17)
.build();
out.println("bar: " + foobar.bar());
out.println("foo: " + foobar.foo());
out.println("foobar: " + foobar);
Foobar modified = foobar.builder()
.bar(18)
.build();
out.println("modified: " + modified);
List<String> foo = new ArrayList<String>();
List<String> bar = new ArrayList<String>(foo);
}
}
| udoprog/auto-matter | example/src/main/java/io/norberg/automatter/example/SimpleExample.java | Java | apache-2.0 | 704 |
/*
* Copyright 2013, TopicQuests
*
* 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.topicquests.model;
import org.topicquests.common.api.ITopicQuestsOntology;
import org.topicquests.model.api.IQueryIterator;
import org.topicquests.model.api.IQueryModel;
import org.topicquests.model.api.ITicket;
import org.topicquests.common.QueryUtil;
/**
* @author park
*
*/
public class QueryModel implements IQueryModel {
private Environment environment;
private final String labelQuery = ITopicQuestsOntology.LABEL_PROPERTY;
private final String detailsQuery = ITopicQuestsOntology.DETAILS_PROPERTY;
private final String instanceQuery = ITopicQuestsOntology.INSTANCE_OF_PROPERTY_TYPE+":";
private final String subClassQuery = ITopicQuestsOntology.SUBCLASS_OF_PROPERTY_TYPE+":";
/**
*
*/
public QueryModel(Environment env) {
environment = env;
}
/* (non-Javadoc)
* @see org.topicquests.model.api.IQueryModel#listNodesByLabel(java.lang.String, java.lang.String, int, java.util.Set)
*/
@Override
public IQueryIterator listNodesByLabel(String label, String language,
int count, ITicket credentials) {
IQueryIterator itr = new QueryIterator(environment);
itr.start(makeField(labelQuery,language)+":"+QueryUtil.escapeQueryCulprits(label), count, credentials);
return itr;
}
/* (non-Javadoc)
* @see org.topicquests.model.api.IQueryModel#listNodesByDetails(java.lang.String, java.lang.String, int, java.util.Set)
*/
@Override
public IQueryIterator listNodesByDetails(String details, String language,
int count, ITicket credentials) {
IQueryIterator itr = new QueryIterator(environment);
itr.start(makeField(detailsQuery,language)+":"+QueryUtil.escapeQueryCulprits(details), count, credentials);
return itr;
}
/* (non-Javadoc)
* @see org.topicquests.model.api.IQueryModel#listTuplesByRelation(java.lang.String, int, java.util.Set)
*/
@Override
public IQueryIterator listTuplesByRelation(String relationType, int count,
ITicket credentials) {
IQueryIterator itr = new QueryIterator(environment);
itr.start(instanceQuery+relationType, count, credentials);
return itr;
}
/* (non-Javadoc)
* @see org.topicquests.model.api.IQueryModel#listNodeInstances(java.lang.String, int, java.util.Set)
*/
@Override
public IQueryIterator listNodeInstances(String nodeTypeLocator, int count,
ITicket credentials) {
IQueryIterator itr = new QueryIterator(environment);
itr.start(instanceQuery+nodeTypeLocator, count, credentials);
return itr;
}
/* (non-Javadoc)
* @see org.topicquests.model.api.IQueryModel#listNodeSubclasses(java.lang.String, int, java.util.Set)
*/
@Override
public IQueryIterator listNodeSubclasses(String superClassLocator,
int count, ITicket credentials) {
IQueryIterator itr = new QueryIterator(environment);
itr.start(subClassQuery+superClassLocator, count, credentials);
return itr;
}
/**
* Calculate the appropriate Solr field
* @param fieldBase
* @param language
* @return
*/
String makeField(String fieldBase, String language) {
//TODO sort this out: do we still need it for non-SOLR topic maps?
String result = fieldBase;
if (!language.equals("en"))
result += language;
return result;
}
}
| SolrSherlock/TopicQuestsCoreAPI | src/java/org/topicquests/model/QueryModel.java | Java | apache-2.0 | 3,747 |
/*
* Copyright (c) 2014 Spotify AB.
*
* 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.spotify.helios.servicescommon;
import com.google.common.base.Strings;
import com.google.common.util.concurrent.AbstractIdleService;
import com.spotify.helios.common.LoggingConfig;
import com.spotify.logging.LoggingConfigurator;
import com.spotify.logging.LoggingConfigurator.Level;
import org.slf4j.bridge.SLF4JBridgeHandler;
import java.io.File;
import static com.google.common.collect.Iterables.get;
import static com.spotify.logging.LoggingConfigurator.Level.ALL;
import static com.spotify.logging.LoggingConfigurator.Level.DEBUG;
import static com.spotify.logging.LoggingConfigurator.Level.INFO;
import static java.util.Arrays.asList;
/**
* Handles setting up proper logging for our services.
*/
public abstract class ServiceMain extends AbstractIdleService {
protected ServiceMain(LoggingConfig loggingConfig, String sentryDsn) {
setupLogging(loggingConfig, sentryDsn);
}
protected static void setupLogging(LoggingConfig config, String sentryDsn) {
if (config.getNoLogSetup()) {
return;
}
// Hijack JUL
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
final int verbose = config.getVerbosity();
final Level level = get(asList(INFO, DEBUG, ALL), verbose, ALL);
final File logconfig = config.getConfigFile();
if (logconfig != null) {
LoggingConfigurator.configure(logconfig);
} else {
if (config.isSyslog()) {
LoggingConfigurator.configureSyslogDefaults("helios", level);
} else {
LoggingConfigurator.configureDefaults("helios", level);
}
if (!Strings.isNullOrEmpty(sentryDsn)) {
LoggingConfigurator.addSentryAppender(sentryDsn);
}
}
}
}
| mbruggmann/helios | helios-services/src/main/java/com/spotify/helios/servicescommon/ServiceMain.java | Java | apache-2.0 | 2,566 |
package com.infiniteviewpager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.View;
/**
* A FragmentPagerAdapter that can be used to achieve paging wrap-around when you have less than 4
* pages. Duplicate instances of pages will be created to fulfill the min case.
*/
public class MinFragmentPagerAdapter extends FragmentPagerAdapter {
private FragmentPagerAdapter mAdapter;
public MinFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
public void setAdapter(FragmentPagerAdapter adapter) {
this.mAdapter = adapter;
}
@Override
public int getCount() {
int realCount = mAdapter.getCount();
if (realCount == 1) {
return 4;
} else if (realCount == 2 || realCount == 3) {
return realCount * 2;
} else {
return realCount;
}
}
@Override
public boolean isViewFromObject(View view, Object object) {
return mAdapter.isViewFromObject(view, object);
}
/**
* Warning: If you only have 1-3 real pages, this method will create multiple, duplicate
* instances of your Fragments to ensure wrap-around is possible. This may be a problem if you
* have editable fields or transient state (they will not be in sync).
*
* @param position
* @return
*/
@Override
public Fragment getItem(int position) {
int realCount = mAdapter.getCount();
if (realCount == 1) {
return mAdapter.getItem(0);
} else if (realCount == 2 || realCount == 3) {
return mAdapter.getItem(position % realCount);
} else {
return mAdapter.getItem(position);
}
}
}
| Iamasoldier6/SoldierNews | SoldierNews/app/src/main/java/com/infiniteviewpager/MinFragmentPagerAdapter.java | Java | apache-2.0 | 1,810 |
/*
* Copyright 2011 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.openehealth.ipf.commons.ihe.xds.iti39;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.Action;
import org.apache.cxf.annotations.DataBinding;
import org.openehealth.ipf.commons.ihe.xds.core.XdsJaxbDataBinding;
import org.openehealth.ipf.commons.ihe.xds.core.ebxml.ebxml30.RetrieveDocumentSetRequestType;
import org.openehealth.ipf.commons.ihe.xds.core.ebxml.ebxml30.RetrieveDocumentSetResponseType;
/**
* ITI-39 SEI.
*/
@WebService(targetNamespace = "urn:ihe:iti:xds-b:2007", name = "RespondingGateway_PortType", portName = "RespondingGateway_Port_Soap12")
@XmlSeeAlso({
org.openehealth.ipf.commons.ihe.xds.core.stub.ebrs30.rim.ObjectFactory.class,
org.openehealth.ipf.commons.ihe.xds.core.stub.ebrs30.lcm.ObjectFactory.class,
org.openehealth.ipf.commons.ihe.xds.core.stub.ebrs30.rs.ObjectFactory.class,
org.openehealth.ipf.commons.ihe.xds.core.stub.ebrs30.query.ObjectFactory.class })
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
@DataBinding(XdsJaxbDataBinding.class)
public interface Iti39PortType {
/**
* Retrieves a set of documents according to the ITI-39 specification.
*/
@WebResult(name = "RetrieveDocumentSetResponse", targetNamespace = "urn:ihe:iti:xds-b:2007", partName = "body")
@Action(input = "urn:ihe:iti:2007:CrossGatewayRetrieve", output = "urn:ihe:iti:2007:CrossGatewayRetrieveResponse")
@WebMethod(operationName = "RespondingGateway_CrossGatewayRetrieve")
RetrieveDocumentSetResponseType documentRepositoryRetrieveDocumentSet(
@WebParam(partName = "body", name = "RetrieveDocumentSetRequest", targetNamespace = "urn:ihe:iti:xds-b:2007")
RetrieveDocumentSetRequestType body
);
}
| oehf/ipf | commons/ihe/xds/src/main/java/org/openehealth/ipf/commons/ihe/xds/iti39/Iti39PortType.java | Java | apache-2.0 | 2,495 |
/**
* Create on 2017-07-10
* Create by CHENZHEMING
* Build by
* CHENZHEMING
* HUANGXIAOYU
*
* 基础工具类,用于封装各种常用方法。
* 此类只用于编写或添加无法对工具方法进行分类的方法。
* 如果工具方法可以具体分类请添加至已经划分种类的类中(例:UDate。
*
*/
package utils;
public class Utils {
/**
* 判断这个对象是否为空
*
* @param o
* 需要判断对象
* @return 一个boolean类型的返回值
*/
public static boolean isNull(Object o) {
if (o.equals(null)) {
return true;
} else {
return false;
}
}
/**
* 盘对这个对象是否不为空
*
* @param o
* 需要判断的对象
* @return 一个boolean的返回值
*/
public static boolean isNotNull(Object o) {
if (o.equals(null)) {
return false;
} else {
return true;
}
}
/**
* 判断这个字符串是否为空
*
* @param s
* 需要判断的字符串
* @return 一个boolean的返回值
*/
public static boolean strIsNull(String s) {
if (s.equals(null)) {
return true;
} else {
if (s.length() > 0) {
return false;
} else {
return true;
}
}
}
/**
* 判断这个字符串是否不为空
*
* @param s
* 需要判断的字符串
* @return 一个boolean类型的返回值
*/
public static boolean strIsNotNull(String s) {
if (s.equals(null)) {
return false;
} else {
if (s.length() > 0) {
return true;
} else {
return false;
}
}
}
}
| Linkcore4423/Utils | UtilsPackage/src/utils/Utils.java | Java | apache-2.0 | 1,643 |
package fengfei.berain.server;
public class Focus {
public static Persistence persistence;
public static String namespace;
public static String getKey(String path) {
String[] ps = path.split("/");
return ps[ps.length - 1];
}
public static String getParent(String path) {
int index = path.lastIndexOf('/');
return path.substring(0, index);
}
public static String toGlobalPath(String path) {
return removeLastSlash(namespace + path);
}
public static String toPath(String globalpath) {
return removeLastSlash(globalpath.replace(namespace, ""));
}
public static String removeLastSlash(String path) {
if (!"/".equals(path) && path.endsWith("/")) {
return path.substring(0, path.length() - 1);
} else {
return path;
}
}
public static void main(String[] args) {
String path = "/r34234/";
System.out.println(removeLastSlash(path));
}
public static String id2path(String id) {
String path = id.replaceAll("[_]", "/");
if (path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
System.out.println("-----------------------------: " + path);
return path;
}
}
| tietang/berain-server | app/fengfei/berain/server/Focus.java | Java | apache-2.0 | 1,129 |
package jdk.util.concurrent.locks;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by why on 4/3/2017.
*/
public class ReentrantLockTest {
@Test
public void test() throws InterruptedException {
ReentrantLock lock = new ReentrantLock();
Condition condition = lock.newCondition();
Thread thread = new Thread(() -> {
lock.tryLock();
try {
System.out.println("wait signal");
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("got signal");
lock.unlock();
});
Thread thread2 = new Thread(() -> {
lock.tryLock();
System.out.println("i got the lock");
try {
TimeUnit.SECONDS.sleep(1);
condition.signal();
System.out.println("i send a signal");
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.unlock();
});
thread.start();
TimeUnit.MILLISECONDS.sleep(10);
thread2.start();
TimeUnit.SECONDS.sleep(2);
}
}
| whyDK37/pinenut | java-core/jdk/src/test/java/jdk/util/concurrent/locks/ReentrantLockTest.java | Java | apache-2.0 | 1,162 |
/**
* Copyright 2010 Tobias Sarnowski
*
* 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.eveonline.api.eve;
import com.eveonline.api.ApiService;
import com.eveonline.api.exceptions.ApiException;
/**
* @author Tobias Sarnowski
*/
public interface FacWarStatsApi extends ApiService {
public static final String XMLPATH = "/eve/FacWarStats.xml.aspx";
/**
* @return faction warfare statistics
* @throws ApiException if an error occurs
*/
FacWarStats getFacWarStats() throws ApiException;
}
| sarnowski/eve-interfaces | src/main/java/com/eveonline/api/eve/FacWarStatsApi.java | Java | apache-2.0 | 1,027 |
package net.dirtydeeds.discordsoundboard;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import static java.nio.file.LinkOption.NOFOLLOW_LINKS;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Observable;
/**
* Observable class used to watch changes to files in a given directory
*
* @author dfurrer.
*/
@Service
public class MainWatch extends Observable {
@Async
@SuppressWarnings("unchecked")
public void watchDirectoryPath(Path path) {
// Sanity check - Check if path is a folder
try {
Boolean isFolder = (Boolean) Files.getAttribute(path,
"basic:isDirectory", NOFOLLOW_LINKS);
if (!isFolder) {
throw new IllegalArgumentException("Path: " + path + " is not a folder");
}
} catch (IOException e) {
// Folder does not exists
e.printStackTrace();
}
System.out.println("Watching path: " + path);
// We obtain the file system of the Path
FileSystem fs = path.getFileSystem ();
// We create the new WatchService using the new try() block
try(WatchService service = fs.newWatchService()) {
// We register the path to the service
// We watch for creation events
path.register(service, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
// Start the infinite polling loop
WatchKey key;
while(true) {
key = service.take();
// Dequeueing events
Kind<?> kind;
for(WatchEvent<?> watchEvent : key.pollEvents()) {
// Get the type of the event
kind = watchEvent.kind();
if (kind == ENTRY_CREATE || kind == ENTRY_DELETE || kind == ENTRY_MODIFY) {
// A new Path was created
Path newPath = ((WatchEvent<Path>) watchEvent).context();
// Output
//Mark the observable object as changed.
this.setChanged();
System.out.println("New path created: " + newPath + " kind of operation: " + kind);
notifyObservers(this);
}
}
if(!key.reset()) {
break; //loop
}
}
} catch(IOException | InterruptedException ioe) {
ioe.printStackTrace();
}
}
}
| Darkside138/DiscordSoundboard | src/main/java/net/dirtydeeds/discordsoundboard/MainWatch.java | Java | apache-2.0 | 2,999 |
package org.pac4j.oauth.profile.creator;
import com.github.scribejava.core.model.*;
import org.pac4j.core.context.HttpConstants;
import org.pac4j.core.exception.HttpAction;
import org.pac4j.oauth.config.OAuth20Configuration;
import org.pac4j.oauth.config.OAuthConfiguration;
import org.pac4j.oauth.credentials.OAuth20Credentials;
import org.pac4j.oauth.profile.OAuth20Profile;
/**
* OAuth 2.0 profile creator.
*
* @author Jerome Leleu
* @since 2.0.0
*/
public class OAuth20ProfileCreator<U extends OAuth20Profile>
extends OAuthProfileCreator<OAuth20Credentials, U, OAuth20Configuration, OAuth2AccessToken> {
public OAuth20ProfileCreator(final OAuth20Configuration configuration) {
super(configuration);
}
@Override
protected OAuth2AccessToken getAccessToken(final OAuth20Credentials credentials) throws HttpAction {
return credentials.getAccessToken();
}
@Override
protected void addAccessTokenToProfile(final U profile, final OAuth2AccessToken accessToken) {
if (profile != null) {
final String token = accessToken.getAccessToken();
logger.debug("add access_token: {} to profile", token);
profile.setAccessToken(token);
}
}
@Override
protected void signRequest(final OAuth2AccessToken accessToken, final OAuthRequest request) {
this.configuration.getService().signRequest(accessToken, request);
if (this.configuration.isTokenAsHeader()) {
request.addHeader(HttpConstants.AUTHORIZATION_HEADER, HttpConstants.BEARER_HEADER_PREFIX + accessToken.getAccessToken());
}
if (Verb.POST.equals(request.getVerb())) {
request.addParameter(OAuthConfiguration.OAUTH_TOKEN, accessToken.getAccessToken());
}
}
}
| topicusonderwijs/pac4j | pac4j-oauth/src/main/java/org/pac4j/oauth/profile/creator/OAuth20ProfileCreator.java | Java | apache-2.0 | 1,788 |
package com.github.benyzhous.springboot.quick.commons.exception;
/**
* Created by chababa on 7/12/16.
*/
public class MissingParameterException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
public MissingParameterException() {
}
public MissingParameterException(String message) {
super("Missing paramter:" + message);
}
}
| benyzhous/springboot-quick-build | commons-quick/src/main/java/com/github/benyzhous/springboot/quick/commons/exception/MissingParameterException.java | Java | apache-2.0 | 379 |
package com.twu.biblioteca.options;
import com.twu.biblioteca.libstores.AllLibraryStores;
import com.twu.biblioteca.BookTitleComparator;
import com.twu.biblioteca.UserAccountManager;
/**
* Created by aloysiusang on 11/6/15.
*/
public class CheckOutBookOption extends MainMenuOption{
private static final String INPUT_TITLE = "Please enter the title of the book you wish to checkout: ";
private static final String MESSAGE_CHECKOUT_SUCCESSFUL = "Thank you! Enjoy the book";
private static final String MESSAGE_CHECKOUT_UNSUCCESSFUL = "That book is not available.";
public CheckOutBookOption() {
super("Checkout a book");
}
@Override
public String execute(UserAccountManager userAccountManager, AllLibraryStores libraryStores) {
System.out.print(INPUT_TITLE);
String title = getUserInput();
boolean success = libraryStores.getBookStore().checkoutResource(userAccountManager.getCurrentUser(), title, new BookTitleComparator());
return success ? MESSAGE_CHECKOUT_SUCCESSFUL : MESSAGE_CHECKOUT_UNSUCCESSFUL;
}
}
| aloysiusang/twu-biblioteca-aloysiusang | src/com/twu/biblioteca/options/CheckOutBookOption.java | Java | apache-2.0 | 1,086 |
package io.github.cloudiator.rest.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.github.cloudiator.rest.model.Distribution;
import io.github.cloudiator.rest.model.TimeUnit;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.*;
/**
* StartTime
*/
@Validated
public class StartTime {
@JsonProperty("distribution")
private Distribution distribution = null;
@JsonProperty("unit")
private TimeUnit unit = null;
public StartTime distribution(Distribution distribution) {
this.distribution = distribution;
return this;
}
/**
* Get distribution
* @return distribution
**/
@ApiModelProperty(value = "")
@Valid
public Distribution getDistribution() {
return distribution;
}
public void setDistribution(Distribution distribution) {
this.distribution = distribution;
}
public StartTime unit(TimeUnit unit) {
this.unit = unit;
return this;
}
/**
* Get unit
* @return unit
**/
@ApiModelProperty(value = "")
@Valid
public TimeUnit getUnit() {
return unit;
}
public void setUnit(TimeUnit unit) {
this.unit = unit;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
StartTime startTime = (StartTime) o;
return Objects.equals(this.distribution, startTime.distribution) &&
Objects.equals(this.unit, startTime.unit);
}
@Override
public int hashCode() {
return Objects.hash(distribution, unit);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class StartTime {\n");
sb.append(" distribution: ").append(toIndentedString(distribution)).append("\n");
sb.append(" unit: ").append(toIndentedString(unit)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| cloudiator/rest-server | model/src/main/java/io/github/cloudiator/rest/model/StartTime.java | Java | apache-2.0 | 2,436 |
/*
* 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
///////////////
package com.hp.hpl.jena.ontology.impl;
// Imports
///////////////
import junit.framework.TestSuite;
/**
* <p>
* Unit tests for all different declaration
* </p>
*
* @author Ian Dickinson, HP Labs
* (<a href="mailto:[email protected]" >email</a>)
* @version CVS $Id: TestAxioms.java,v 1.2 2009-10-06 13:04:42 ian_dickinson Exp $
*/
public class TestAxioms
extends OntTestBase
{
// Constants
//////////////////////////////////
// Static variables
//////////////////////////////////
// Instance variables
//////////////////////////////////
// Constructors
//////////////////////////////////
public TestAxioms( String s ) {
super( s );
}
// External signature methods
//////////////////////////////////
protected String getTestName() {
return "TestAxioms";
}
public static TestSuite suite() {
return new TestAxioms( "TestAxioms" );
}
@Override
public OntTestCase[] getTests() {
return new OntTestCase[] {
};
}
// Internal implementation methods
//////////////////////////////////
//==============================================================================
// Inner class definitions
//==============================================================================
}
| danc86/jena-core | src/test/java/com/hp/hpl/jena/ontology/impl/TestAxioms.java | Java | apache-2.0 | 2,223 |
package sedion.jeffli.wmuitp.service.impl;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.servlet.http.HttpSession;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sedion.jeffli.wmuitp.constant.TeacherInfoConstant;
import sedion.jeffli.wmuitp.constant.main.Constant;
import sedion.jeffli.wmuitp.constant.database.CommonConstant;
import sedion.jeffli.wmuitp.dao.ProfessionInfoDAO;
import sedion.jeffli.wmuitp.dao.TeacherInfoDAO;
import sedion.jeffli.wmuitp.dao.UserLoginDAO;
import sedion.jeffli.wmuitp.entity.*;
import sedion.jeffli.wmuitp.exception.EntityException;
import sedion.jeffli.wmuitp.service.TeacherInfoService;
import sedion.jeffli.wmuitp.util.FileOperateUtil;
import sedion.jeffli.wmuitp.util.Page;
import sedion.jeffli.wmuitp.util.session.AdminUtil;
//是一个泛化的概念,仅仅表示一个组件 (Bean) ,可以作用在任何层次。
//@Service 通常作用在业务层,但是目前该功能与 @Component 相同。
@Service
public class TeacherInfoServiceImpl implements TeacherInfoService
{
private static final String All_TEACHERINFOS = "FROM TeacherInfo AS ti ";
@Autowired
private UserLoginDAO userLoginDAO;
@Autowired
private TeacherInfoDAO teacherInfoDAO;
@Autowired
private ProfessionInfoDAO professionInfoDAO;
@Autowired
public HttpSession session;
@Override
public int addTeacherByXls(MultipartFile file)
{
// 保存错误列表
List<Cell[]> errors = new ArrayList<>();
if (new File(Constant.getCachePath()).exists())
new File(Constant.getCachePath()).mkdir();
File file1 = new File(Constant.getCachePath(), Calendar.getInstance().getTimeInMillis() + ".xls");
try {
file.transferTo(file1);
} catch (IllegalStateException e1) {
System.out.println("读取文件异常");
e1.printStackTrace();
} catch (IOException e1) {
System.out.println("读取文件异常");
e1.printStackTrace();
}
int count = 0;
Workbook wb = null;
try {
// 构造Workbook(工作薄)对象
wb = Workbook.getWorkbook(file1);
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (wb == null)
return -1;
// 获得了Workbook对象之后,就可以通过它得到Sheet(工作表)对象了
Sheet[] sheet = wb.getSheets();
try {
if (sheet != null && sheet.length > 0)
{
// 对第一个工作表进行操作
// 得到当前工作表的行数
int rowNum = sheet[0].getRows();
Cell[] cells = null;
for (int j = 1; j < rowNum; j++)
{
// 得到当前行的所有单元格
try
{
cells = sheet[0].getRow(j);
String name = cells[0].getContents().trim();
String number = cells[1].getContents().trim();
String job = cells[2].getContents().trim();
String age = cells[3].getContents().trim();
String skillDetail = cells[4].getContents().trim();
String profession = cells[5].getContents().trim();
String college = cells[6].getContents().trim();
//判断是否为空
if (name.equals("") || number.equals("")|| profession.equals("")|| college.equals(""))
throw new Exception();
// 判断用户名是否存在
UserLogin results = userLoginDAO.getUserLoginByName(number);
// System.out.println("results="+results.toString());
if (results != null)
throw new Exception();
UserLogin userLogin = new UserLogin();
userLogin.setUlSign("tea");
userLogin.setUlPassword(Constant.INIT_PASSWORD);
userLogin.setUlName(number);
userLoginDAO.updateEntity(userLogin);
//判断专业是否存在
ProfessionInfo professionInfo = professionInfoDAO.getprofessionInfoByProfessionInfoAndCollege(profession, college);
System.out.println("professionInfo=="+professionInfo);
if(professionInfo==null)
{
professionInfo = new ProfessionInfo();
professionInfo.setPiCollege(college);
professionInfo.setPiProfession(profession);
professionInfoDAO.updateEntity(professionInfo);
}
//创建teacher实例
TeacherInfo teacher = new TeacherInfo();
teacher.setUserLogin(userLogin);
teacher.setTiSkills(skillDetail);
teacher.setTiSign("T");
teacher.setTiName(name);
teacher.setTiJob(job);
teacher.setTiAge(age);
teacher.setTiAddress("");
teacher.setProfessionInfo(professionInfo);
teacherInfoDAO.updateEntity(teacher);
}
catch (Exception e)
{
//记录保存错误行
errors.add(cells);
count++;
System.out.println("Add Teacher By Xls Error!");
continue;
}
}
}
}finally{
// 最后关闭资源,释放内存
if(wb!=null)
wb.close();
if(file1!=null)
file1.delete();
}
OutputStream os = null;
WritableWorkbook book = null;
// 整理错误数据
if (errors.size() != 0)
{
System.out.println("错误");
try
{
UserLogin ul = AdminUtil.getUserLoginFromHttpSession(session);
File f = new File(Constant.getCachePath(), ul.getUlName()
+ ".xls");
if (f.exists())
f.delete();
// f.createTempFile(ul.getUlName(), ".xls");
os = new FileOutputStream(Constant.getCachePath()
+ ul.getUlName() + ".xls");
book = Workbook.createWorkbook(os);
WritableSheet ws = book.createSheet("Error Line", 0);
//首行信息
Label label1 = new Label(0, 0,"教师姓名");
Label label2 = new Label(1, 0,"教师编号");
Label label3 = new Label(2, 0,"教师职称(可空)");
Label label4 = new Label(3, 0,"教师年龄(可空)");
Label label5 = new Label(4, 0,"教师技能详情(可空)");
Label label6 = new Label(5, 0,"专业名称");
Label label7 = new Label(6, 0,"所属学院");
ws.addCell(label1);
ws.addCell(label2);
ws.addCell(label3);
ws.addCell(label4);
ws.addCell(label5);
ws.addCell(label6);
ws.addCell(label7);
for (int i = 1; i < errors.size(); i++)
{
for (int j = 0; j < errors.get(i).length; j++)
{
System.out.println("内容"+i+"行"+j+"列"+errors.get(i)[j].getContents());
Label label = new Label(j, i,errors.get(i)[j].getContents());
// 将定义好的单元格添加到工作表中
ws.addCell(label);
}
}
// 写入
book.write();
System.out.println("导入失败内容写出成功");
} catch (Exception e) {
System.out.println("导入失败内容写出失败");
throw new EntityException(" StudentInfoServiceImpl addTeacherByXls(...) Error!!",e);
}finally{
try {
if(book!=null)
book.close();
if(os!=null)
os.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
}
return count;
}
@Override
public int initTeacherInfoPassword(String teacherInfoId)
{
try
{
TeacherInfo teacherInfo = teacherInfoDAO.findById(teacherInfoId);
UserLogin userLogin = teacherInfo.getUserLogin();
userLogin.setUlPassword(Constant.INIT_PASSWORD);
userLoginDAO.updateEntity(userLogin);
}
catch (Exception e)
{
throw new EntityException(
"Error! TeacherInfoServiceImpl.initTeacherInfoPassword(String teacherInfoId) ",
e);
}
return Constant.RESULT_SUCCESS;
}
@Override
public TeacherInfo getTeacherInfoByTeacherInfoUserLogin(UserLogin userLogin)
{
return teacherInfoDAO.getTeacherInfoByUserLoginId(userLogin.getUlId().toString());
}
@Override
public TeacherInfo getTeacherInfoByTeacherInfoID(String teacherInfoId)
{
return teacherInfoDAO.findById(Integer.valueOf(teacherInfoId));
}
@Override
public int deleteTeacherInfo(String teacherInfoIDStr)
{
String[] teacherInfoIDStrs;
if (teacherInfoIDStr != null && !teacherInfoIDStr.equals(""))
{
teacherInfoIDStrs = teacherInfoIDStr.split(Constant.LINE);
for (String teacherInfoID : teacherInfoIDStrs)
{
try
{
TeacherInfo teacherInfo = teacherInfoDAO
.findById(teacherInfoID);
userLoginDAO.turnTransient(teacherInfo.getUserLogin());
teacherInfoDAO.turnTransient(teacherInfo);// 删除
}
catch (Exception e)
{
throw new EntityException(
"Error! TeacherInfoServiceImpl.deleteTeacherInfo(String teacherInfoIDStr) ",
e);
}
}
return Constant.RESULT_SUCCESS;
}
return Constant.RESULT_FAIL;
}
@Override
public int saveOrUpdateTeacherInfo(TeacherInfo teacherInfo,
UserLogin userLogin, String professionInfoID, MultipartFile file)
{
if (userLogin.getUlId() == null)// 验证用户名是否已经存在
{
UserLogin result = userLoginDAO.getUserLoginByName(userLogin.getUlName());
if (result != null)
return Constant.RESULT_EXIST;
}
userLogin.setUlPassword(Constant.INIT_PASSWORD);// 设置初始密码
userLogin.setUlSign("tea");
userLoginDAO.updateEntity(userLogin);
ProfessionInfo professionInfo = new ProfessionInfo();
/*
* if (file == null && teacherInfo.getTiId() != null) {
* System.out.println("进来"); String Address =
* teacherInfoDAO.findById(teacherInfo.getTiId()) .getTiAddress();
* teacherInfo.setTiAddress(Address); }
*/
if (professionInfoID != null && !professionInfoID.equals(""))
{
professionInfo = professionInfoDAO.findById(professionInfoID);
} else
return Constant.RESULT_FAIL;
teacherInfo.setTiSign("T");
teacherInfo.setUserLogin(userLogin);
teacherInfo.setProfessionInfo(professionInfo);
teacherInfoDAO.updateEntity(teacherInfo);
/****************** 保存照片 ************************/
if (file != null) {
System.out.println("进来了");
String path = TeacherInfoConstant.TEACHER_IMG_PATH;// 储存地址
File dirFlie = new File(path);
String fileName = String.valueOf(teacherInfo.getTiId())
+ FileOperateUtil.getExtension(file.getOriginalFilename());
File targetFile = new File(path, fileName);
System.out.println("dirFlie.exists()=" + dirFlie.exists());
if (!dirFlie.isDirectory()) // 如果文件夹不存在 则创建文件夹
dirFlie.mkdirs();
try
{
file.transferTo(targetFile);// 保存
}
catch (Exception e)
{
// file Exception
e.printStackTrace();
}
teacherInfo.setTiAddress(fileName);
teacherInfoDAO.updateEntity(teacherInfo);
}
/******************************************/
return Constant.RESULT_SUCCESS;
}
@Override
public List<TeacherInfo> getTeacherInfosPages(Page<TeacherInfo> page,
int[] pageParams)
{
List<TeacherInfo> results = new ArrayList<>();
StringBuilder resultsHQL = new StringBuilder(All_TEACHERINFOS);
try
{
results = teacherInfoDAO.findByPage(resultsHQL.toString(),
pageParams[0], pageParams[1]);
page.setTotalCount(teacherInfoDAO.getCount(resultsHQL.toString()));
page.setResult(results);
}
catch (Exception e)
{
e.printStackTrace();
}
return results;
}
@Override
public TeacherInfo getTeacherInfoIDByOBJ(String userLoginId)
{
String hql = All_TEACHERINFOS + CommonConstant.ONE_EQUALS_ONE;
if (userLoginId != null && !userLoginId.equals(""))
{
hql += " AND ti.userLogin.ulId=" + userLoginId;
}
return teacherInfoDAO.getUniqueResultByHQL(hql);
}
@Override
public List<TeacherInfo> getTeacherInfos()
{
return teacherInfoDAO.findAll();
}
@Override
public List<TeacherInfo> getLessTeacherInfoForSearch(String collegeName,
String professionName, String teacherName, String jobName)
{
collegeName = StringUtils.trimToEmpty(collegeName);
professionName = StringUtils.trimToEmpty(professionName);
teacherName = StringUtils.trimToEmpty(teacherName);
jobName = StringUtils.trimToEmpty(jobName);
StringBuilder resultsHQL = new StringBuilder(All_TEACHERINFOS)
.append(CommonConstant.ONE_EQUALS_ONE);
resultsHQL.append(" AND ti.professionInfo.piCollege LIKE '%")
.append(collegeName).append("%' ");
resultsHQL.append(" AND ti.tiJob LIKE '%").append(jobName)
.append("%' ");
resultsHQL.append(" AND ti.professionInfo.piProfession LIKE '%")
.append(professionName).append("%' ");
resultsHQL.append(" AND ti.tiName LIKE '%").append(teacherName)
.append("%' ");
return teacherInfoDAO.getListByHQL(resultsHQL.toString());
}
@Override
public List<TeacherInfo> getTeacherInfosPagesForSearch(
Page<TeacherInfo> page, int[] pageParams, String collegeName,
String professionName, String teacherName, String jobName)
{
collegeName = StringUtils.trimToEmpty(collegeName);
professionName = StringUtils.trimToEmpty(professionName);
teacherName = StringUtils.trimToEmpty(teacherName);
jobName = StringUtils.trimToEmpty(jobName);
List<TeacherInfo> results = new ArrayList<>();
StringBuilder resultsHQL = new StringBuilder(All_TEACHERINFOS)
.append(CommonConstant.ONE_EQUALS_ONE);
resultsHQL.append(" AND ti.professionInfo.piCollege LIKE '%")
.append(collegeName).append("%' ");
resultsHQL.append(" AND ti.tiJob LIKE '%").append(jobName)
.append("%' ");
resultsHQL.append(" AND ti.professionInfo.piProfession LIKE '%")
.append(professionName).append("%' ");
resultsHQL.append(" AND ti.tiName LIKE '%").append(teacherName)
.append("%' ");
try
{
results = teacherInfoDAO.findByPage(resultsHQL.toString(),
pageParams[0], pageParams[1]);
page.setTotalCount(teacherInfoDAO.getCount(resultsHQL.toString()));
page.setResult(results);
}
catch (Exception e)
{
throw new EntityException(
"Error! TeacherInfoServiceImpl.getTeacherInfosPagesForSearch(...) ",
e);
}
return results;
}
}
| JeffLi1993/itp | itp-web/wmuitp/src/sedion/jeffli/wmuitp/service/impl/TeacherInfoServiceImpl.java | Java | apache-2.0 | 14,133 |
/*
* Copyright 2017 Marcus Portmann
*
* 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 guru.mmp.application.web.template.components;
//~--- non-JDK imports --------------------------------------------------------
import guru.mmp.application.web.template.resources.TemplateJavaScriptResourceReference;
import guru.mmp.application.web.template.util.FeedbackUtil;
import org.apache.wicket.ajax.AjaxRequestHandler;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.model.IModel;
import org.apache.wicket.request.IRequestHandler;
/**
* The <code>TextAreaWithFeedback</code> class extends the Wicket <code>TextArea</code>
* component to provide support for displaying the feedback message for the component.
*
* @param <T>
*
* @author Marcus Portmann
*/
public class TextAreaWithFeedback<T> extends TextArea<T>
{
private static final long serialVersionUID = 1000000;
private String feedbackMessageClasses;
/**
* Constructs a new <code>TextAreaWithFeedback</code>.
*
* @param id the non-null id of this component
*/
public TextAreaWithFeedback(String id)
{
super(id);
setOutputMarkupId(true);
}
/**
* Constructs a new <code>TextAreaWithFeedback</code>.
*
* @param id the non-null id of this component
* @param model the model for this component
*/
@SuppressWarnings("unused")
public TextAreaWithFeedback(String id, IModel<T> model)
{
super(id, model);
setOutputMarkupId(true);
}
/**
* Returns the additional CSS classes to apply to the feedback message.
*
* @return the additional CSS classes to apply to the feedback message
*/
public String getFeedbackMessageClasses()
{
return feedbackMessageClasses;
}
/**
* @param response the Wicket header response
*
* @see org.apache.wicket.markup.html.form.TextField#renderHead(IHeaderResponse)
*/
@Override
public void renderHead(IHeaderResponse response)
{
super.renderHead(response);
response.render(TemplateJavaScriptResourceReference.getJavaScriptHeaderItem());
String feedbackJavaScript = FeedbackUtil.generateFeedbackJavaScript(getMarkupId(), this, false,
feedbackMessageClasses);
if (feedbackJavaScript != null)
{
response.render(JavaScriptHeaderItem.forScript(feedbackJavaScript, null));
}
}
/**
* Set the additional CSS classes to apply to the feedback message.
*
* @param feedbackMessageClasses the additional CSS classes to apply to the feedback message
*/
public void setFeedbackMessageClasses(String feedbackMessageClasses)
{
this.feedbackMessageClasses = feedbackMessageClasses;
}
/**
* @see org.apache.wicket.markup.html.form.TextArea#onConfigure()
*/
@Override
protected void onConfigure()
{
super.onConfigure();
FeedbackUtil.applyFeedbackCssClassModifier(this);
}
/**
* @see org.apache.wicket.markup.html.form.TextArea#onRender()
*/
@Override
protected void onRender()
{
super.onRender();
IRequestHandler requestHandler = getRequestCycle().getActiveRequestHandler();
if (requestHandler instanceof AjaxRequestHandler)
{
AjaxRequestHandler ajaxRequestHandler = (AjaxRequestHandler) requestHandler;
String feedbackJavaScript = FeedbackUtil.generateFeedbackJavaScript(getMarkupId(), this,
true, feedbackMessageClasses);
if (feedbackJavaScript != null)
{
ajaxRequestHandler.appendJavaScript(feedbackJavaScript);
}
}
}
}
| marcusportmann/mmp-java | src/mmp-application-wicket/src/main/java/guru/mmp/application/web/template/components/TextAreaWithFeedback.java | Java | apache-2.0 | 4,138 |
/*
* 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.lexruntime;
import org.w3c.dom.*;
import java.net.*;
import java.util.*;
import javax.annotation.Generated;
import org.apache.commons.logging.*;
import com.amazonaws.*;
import com.amazonaws.annotation.SdkInternalApi;
import com.amazonaws.auth.*;
import com.amazonaws.handlers.*;
import com.amazonaws.http.*;
import com.amazonaws.internal.*;
import com.amazonaws.internal.auth.*;
import com.amazonaws.metrics.*;
import com.amazonaws.regions.*;
import com.amazonaws.transform.*;
import com.amazonaws.util.*;
import com.amazonaws.protocol.json.*;
import com.amazonaws.util.AWSRequestMetrics.Field;
import com.amazonaws.annotation.ThreadSafe;
import com.amazonaws.client.AwsSyncClientParams;
import com.amazonaws.client.builder.AdvancedConfig;
import com.amazonaws.services.lexruntime.AmazonLexRuntimeClientBuilder;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.lexruntime.model.*;
import com.amazonaws.services.lexruntime.model.transform.*;
/**
* Client for accessing Amazon Lex Runtime Service. All service calls made using this client are blocking, and will not
* return until the service call completes.
* <p>
* <p>
* Amazon Lex provides both build and runtime endpoints. Each endpoint provides a set of operations (API). Your
* conversational bot uses the runtime API to understand user utterances (user input text or voice). For example,
* suppose a user says "I want pizza", your bot sends this input to Amazon Lex using the runtime API. Amazon Lex
* recognizes that the user request is for the OrderPizza intent (one of the intents defined in the bot). Then Amazon
* Lex engages in user conversation on behalf of the bot to elicit required information (slot values, such as pizza size
* and crust type), and then performs fulfillment activity (that you configured when you created the bot). You use the
* build-time API to create and manage your Amazon Lex bot. For a list of build-time operations, see the build-time API,
* .
* </p>
*/
@ThreadSafe
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AmazonLexRuntimeClient extends AmazonWebServiceClient implements AmazonLexRuntime {
/** Provider for AWS credentials. */
private final AWSCredentialsProvider awsCredentialsProvider;
private static final Log log = LogFactory.getLog(AmazonLexRuntime.class);
/** Default signing name for the service. */
private static final String DEFAULT_SIGNING_NAME = "lex";
/** Client configuration factory providing ClientConfigurations tailored to this client */
protected static final ClientConfigurationFactory configFactory = new ClientConfigurationFactory();
private final AdvancedConfig advancedConfig;
private static final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory = new com.amazonaws.protocol.json.SdkJsonProtocolFactory(
new JsonClientMetadata()
.withProtocolVersion("1.1")
.withSupportsCbor(false)
.withSupportsIon(false)
.withContentTypeOverride("application/json")
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("ConflictException").withExceptionUnmarshaller(
com.amazonaws.services.lexruntime.model.transform.ConflictExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("NotFoundException").withExceptionUnmarshaller(
com.amazonaws.services.lexruntime.model.transform.NotFoundExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("InternalFailureException").withExceptionUnmarshaller(
com.amazonaws.services.lexruntime.model.transform.InternalFailureExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("RequestTimeoutException").withExceptionUnmarshaller(
com.amazonaws.services.lexruntime.model.transform.RequestTimeoutExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("DependencyFailedException").withExceptionUnmarshaller(
com.amazonaws.services.lexruntime.model.transform.DependencyFailedExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("UnsupportedMediaTypeException").withExceptionUnmarshaller(
com.amazonaws.services.lexruntime.model.transform.UnsupportedMediaTypeExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("NotAcceptableException").withExceptionUnmarshaller(
com.amazonaws.services.lexruntime.model.transform.NotAcceptableExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("BadRequestException").withExceptionUnmarshaller(
com.amazonaws.services.lexruntime.model.transform.BadRequestExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("LimitExceededException").withExceptionUnmarshaller(
com.amazonaws.services.lexruntime.model.transform.LimitExceededExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("BadGatewayException").withExceptionUnmarshaller(
com.amazonaws.services.lexruntime.model.transform.BadGatewayExceptionUnmarshaller.getInstance()))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("LoopDetectedException").withExceptionUnmarshaller(
com.amazonaws.services.lexruntime.model.transform.LoopDetectedExceptionUnmarshaller.getInstance()))
.withBaseServiceExceptionClass(com.amazonaws.services.lexruntime.model.AmazonLexRuntimeException.class));
public static AmazonLexRuntimeClientBuilder builder() {
return AmazonLexRuntimeClientBuilder.standard();
}
/**
* Constructs a new client to invoke service methods on Amazon Lex Runtime Service using the specified parameters.
*
* <p>
* All service calls made using this new client object are blocking, and will not return until the service call
* completes.
*
* @param clientParams
* Object providing client parameters.
*/
AmazonLexRuntimeClient(AwsSyncClientParams clientParams) {
this(clientParams, false);
}
/**
* Constructs a new client to invoke service methods on Amazon Lex Runtime Service using the specified parameters.
*
* <p>
* All service calls made using this new client object are blocking, and will not return until the service call
* completes.
*
* @param clientParams
* Object providing client parameters.
*/
AmazonLexRuntimeClient(AwsSyncClientParams clientParams, boolean endpointDiscoveryEnabled) {
super(clientParams);
this.awsCredentialsProvider = clientParams.getCredentialsProvider();
this.advancedConfig = clientParams.getAdvancedConfig();
init();
}
private void init() {
setServiceNameIntern(DEFAULT_SIGNING_NAME);
setEndpointPrefix(ENDPOINT_PREFIX);
// calling this.setEndPoint(...) will also modify the signer accordingly
setEndpoint("runtime.lex.us-east-1.amazonaws.com");
HandlerChainFactory chainFactory = new HandlerChainFactory();
requestHandler2s.addAll(chainFactory.newRequestHandlerChain("/com/amazonaws/services/lexruntime/request.handlers"));
requestHandler2s.addAll(chainFactory.newRequestHandler2Chain("/com/amazonaws/services/lexruntime/request.handler2s"));
requestHandler2s.addAll(chainFactory.getGlobalHandlers());
}
/**
* <p>
* Removes session information for a specified bot, alias, and user ID.
* </p>
*
* @param deleteSessionRequest
* @return Result of the DeleteSession operation returned by the service.
* @throws NotFoundException
* The resource (such as the Amazon Lex bot or an alias) that is referred to is not found.
* @throws BadRequestException
* Request validation failed, there is no usable message in the context, or the bot build failed, is still
* in progress, or contains unbuilt changes.
* @throws LimitExceededException
* Exceeded a limit.
* @throws InternalFailureException
* Internal service error. Retry the call.
* @throws ConflictException
* Two clients are using the same AWS account, Amazon Lex bot, and user ID.
* @sample AmazonLexRuntime.DeleteSession
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/runtime.lex-2016-11-28/DeleteSession" target="_top">AWS API
* Documentation</a>
*/
@Override
public DeleteSessionResult deleteSession(DeleteSessionRequest request) {
request = beforeClientExecution(request);
return executeDeleteSession(request);
}
@SdkInternalApi
final DeleteSessionResult executeDeleteSession(DeleteSessionRequest deleteSessionRequest) {
ExecutionContext executionContext = createExecutionContext(deleteSessionRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<DeleteSessionRequest> request = null;
Response<DeleteSessionResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new DeleteSessionRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(deleteSessionRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);
request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Lex Runtime Service");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "DeleteSession");
request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
HttpResponseHandler<AmazonWebServiceResponse<DeleteSessionResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new DeleteSessionResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Returns session information for a specified bot, alias, and user ID.
* </p>
*
* @param getSessionRequest
* @return Result of the GetSession operation returned by the service.
* @throws NotFoundException
* The resource (such as the Amazon Lex bot or an alias) that is referred to is not found.
* @throws BadRequestException
* Request validation failed, there is no usable message in the context, or the bot build failed, is still
* in progress, or contains unbuilt changes.
* @throws LimitExceededException
* Exceeded a limit.
* @throws InternalFailureException
* Internal service error. Retry the call.
* @sample AmazonLexRuntime.GetSession
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/runtime.lex-2016-11-28/GetSession" target="_top">AWS API
* Documentation</a>
*/
@Override
public GetSessionResult getSession(GetSessionRequest request) {
request = beforeClientExecution(request);
return executeGetSession(request);
}
@SdkInternalApi
final GetSessionResult executeGetSession(GetSessionRequest getSessionRequest) {
ExecutionContext executionContext = createExecutionContext(getSessionRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<GetSessionRequest> request = null;
Response<GetSessionResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new GetSessionRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(getSessionRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);
request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Lex Runtime Service");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "GetSession");
request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
HttpResponseHandler<AmazonWebServiceResponse<GetSessionResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata()
.withPayloadJson(true).withHasStreamingSuccessResponse(false), new GetSessionResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Sends user input (text or speech) to Amazon Lex. Clients use this API to send text and audio requests to Amazon
* Lex at runtime. Amazon Lex interprets the user input using the machine learning model that it built for the bot.
* </p>
* <p>
* The <code>PostContent</code> operation supports audio input at 8kHz and 16kHz. You can use 8kHz audio to achieve
* higher speech recognition accuracy in telephone audio applications.
* </p>
* <p>
* In response, Amazon Lex returns the next message to convey to the user. Consider the following example messages:
* </p>
* <ul>
* <li>
* <p>
* For a user input "I would like a pizza," Amazon Lex might return a response with a message eliciting slot data
* (for example, <code>PizzaSize</code>): "What size pizza would you like?".
* </p>
* </li>
* <li>
* <p>
* After the user provides all of the pizza order information, Amazon Lex might return a response with a message to
* get user confirmation: "Order the pizza?".
* </p>
* </li>
* <li>
* <p>
* After the user replies "Yes" to the confirmation prompt, Amazon Lex might return a conclusion statement:
* "Thank you, your cheese pizza has been ordered.".
* </p>
* </li>
* </ul>
* <p>
* Not all Amazon Lex messages require a response from the user. For example, conclusion statements do not require a
* response. Some messages require only a yes or no response. In addition to the <code>message</code>, Amazon Lex
* provides additional context about the message in the response that you can use to enhance client behavior, such
* as displaying the appropriate client user interface. Consider the following examples:
* </p>
* <ul>
* <li>
* <p>
* If the message is to elicit slot data, Amazon Lex returns the following context information:
* </p>
* <ul>
* <li>
* <p>
* <code>x-amz-lex-dialog-state</code> header set to <code>ElicitSlot</code>
* </p>
* </li>
* <li>
* <p>
* <code>x-amz-lex-intent-name</code> header set to the intent name in the current context
* </p>
* </li>
* <li>
* <p>
* <code>x-amz-lex-slot-to-elicit</code> header set to the slot name for which the <code>message</code> is eliciting
* information
* </p>
* </li>
* <li>
* <p>
* <code>x-amz-lex-slots</code> header set to a map of slots configured for the intent with their current values
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* If the message is a confirmation prompt, the <code>x-amz-lex-dialog-state</code> header is set to
* <code>Confirmation</code> and the <code>x-amz-lex-slot-to-elicit</code> header is omitted.
* </p>
* </li>
* <li>
* <p>
* If the message is a clarification prompt configured for the intent, indicating that the user intent is not
* understood, the <code>x-amz-dialog-state</code> header is set to <code>ElicitIntent</code> and the
* <code>x-amz-slot-to-elicit</code> header is omitted.
* </p>
* </li>
* </ul>
* <p>
* In addition, Amazon Lex also returns your application-specific <code>sessionAttributes</code>. For more
* information, see <a href="https://docs.aws.amazon.com/lex/latest/dg/context-mgmt.html">Managing Conversation
* Context</a>.
* </p>
*
* @param postContentRequest
* @return Result of the PostContent operation returned by the service.
* @throws NotFoundException
* The resource (such as the Amazon Lex bot or an alias) that is referred to is not found.
* @throws BadRequestException
* Request validation failed, there is no usable message in the context, or the bot build failed, is still
* in progress, or contains unbuilt changes.
* @throws LimitExceededException
* Exceeded a limit.
* @throws InternalFailureException
* Internal service error. Retry the call.
* @throws ConflictException
* Two clients are using the same AWS account, Amazon Lex bot, and user ID.
* @throws UnsupportedMediaTypeException
* The Content-Type header (<code>PostContent</code> API) has an invalid value.
* @throws NotAcceptableException
* The accept header in the request does not have a valid value.
* @throws RequestTimeoutException
* The input speech is too long.
* @throws DependencyFailedException
* One of the dependencies, such as AWS Lambda or Amazon Polly, threw an exception. For example, </p>
* <ul>
* <li>
* <p>
* If Amazon Lex does not have sufficient permissions to call a Lambda function.
* </p>
* </li>
* <li>
* <p>
* If a Lambda function takes longer than 30 seconds to execute.
* </p>
* </li>
* <li>
* <p>
* If a fulfillment Lambda function returns a <code>Delegate</code> dialog action without removing any slot
* values.
* </p>
* </li>
* @throws BadGatewayException
* Either the Amazon Lex bot is still building, or one of the dependent services (Amazon Polly, AWS Lambda)
* failed with an internal service error.
* @throws LoopDetectedException
* This exception is not used.
* @sample AmazonLexRuntime.PostContent
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/runtime.lex-2016-11-28/PostContent" target="_top">AWS API
* Documentation</a>
*/
@Override
public PostContentResult postContent(PostContentRequest request) {
request = beforeClientExecution(request);
return executePostContent(request);
}
@SdkInternalApi
final PostContentResult executePostContent(PostContentRequest postContentRequest) {
ExecutionContext executionContext = createExecutionContext(postContentRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<PostContentRequest> request = null;
Response<PostContentResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new PostContentRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(postContentRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);
request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Lex Runtime Service");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "PostContent");
request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);
request.addHandlerContext(HandlerContextKey.HAS_STREAMING_INPUT, Boolean.TRUE);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
HttpResponseHandler<AmazonWebServiceResponse<PostContentResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(false).withHasStreamingSuccessResponse(true), new PostContentResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
request.addHandlerContext(HandlerContextKey.HAS_STREAMING_OUTPUT, Boolean.TRUE);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Sends user input to Amazon Lex. Client applications can use this API to send requests to Amazon Lex at runtime.
* Amazon Lex then interprets the user input using the machine learning model it built for the bot.
* </p>
* <p>
* In response, Amazon Lex returns the next <code>message</code> to convey to the user an optional
* <code>responseCard</code> to display. Consider the following example messages:
* </p>
* <ul>
* <li>
* <p>
* For a user input "I would like a pizza", Amazon Lex might return a response with a message eliciting slot data
* (for example, PizzaSize): "What size pizza would you like?"
* </p>
* </li>
* <li>
* <p>
* After the user provides all of the pizza order information, Amazon Lex might return a response with a message to
* obtain user confirmation "Proceed with the pizza order?".
* </p>
* </li>
* <li>
* <p>
* After the user replies to a confirmation prompt with a "yes", Amazon Lex might return a conclusion statement:
* "Thank you, your cheese pizza has been ordered.".
* </p>
* </li>
* </ul>
* <p>
* Not all Amazon Lex messages require a user response. For example, a conclusion statement does not require a
* response. Some messages require only a "yes" or "no" user response. In addition to the <code>message</code>,
* Amazon Lex provides additional context about the message in the response that you might use to enhance client
* behavior, for example, to display the appropriate client user interface. These are the <code>slotToElicit</code>,
* <code>dialogState</code>, <code>intentName</code>, and <code>slots</code> fields in the response. Consider the
* following examples:
* </p>
* <ul>
* <li>
* <p>
* If the message is to elicit slot data, Amazon Lex returns the following context information:
* </p>
* <ul>
* <li>
* <p>
* <code>dialogState</code> set to ElicitSlot
* </p>
* </li>
* <li>
* <p>
* <code>intentName</code> set to the intent name in the current context
* </p>
* </li>
* <li>
* <p>
* <code>slotToElicit</code> set to the slot name for which the <code>message</code> is eliciting information
* </p>
* </li>
* <li>
* <p>
* <code>slots</code> set to a map of slots, configured for the intent, with currently known values
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* If the message is a confirmation prompt, the <code>dialogState</code> is set to ConfirmIntent and
* <code>SlotToElicit</code> is set to null.
* </p>
* </li>
* <li>
* <p>
* If the message is a clarification prompt (configured for the intent) that indicates that user intent is not
* understood, the <code>dialogState</code> is set to ElicitIntent and <code>slotToElicit</code> is set to null.
* </p>
* </li>
* </ul>
* <p>
* In addition, Amazon Lex also returns your application-specific <code>sessionAttributes</code>. For more
* information, see <a href="https://docs.aws.amazon.com/lex/latest/dg/context-mgmt.html">Managing Conversation
* Context</a>.
* </p>
*
* @param postTextRequest
* @return Result of the PostText operation returned by the service.
* @throws NotFoundException
* The resource (such as the Amazon Lex bot or an alias) that is referred to is not found.
* @throws BadRequestException
* Request validation failed, there is no usable message in the context, or the bot build failed, is still
* in progress, or contains unbuilt changes.
* @throws LimitExceededException
* Exceeded a limit.
* @throws InternalFailureException
* Internal service error. Retry the call.
* @throws ConflictException
* Two clients are using the same AWS account, Amazon Lex bot, and user ID.
* @throws DependencyFailedException
* One of the dependencies, such as AWS Lambda or Amazon Polly, threw an exception. For example, </p>
* <ul>
* <li>
* <p>
* If Amazon Lex does not have sufficient permissions to call a Lambda function.
* </p>
* </li>
* <li>
* <p>
* If a Lambda function takes longer than 30 seconds to execute.
* </p>
* </li>
* <li>
* <p>
* If a fulfillment Lambda function returns a <code>Delegate</code> dialog action without removing any slot
* values.
* </p>
* </li>
* @throws BadGatewayException
* Either the Amazon Lex bot is still building, or one of the dependent services (Amazon Polly, AWS Lambda)
* failed with an internal service error.
* @throws LoopDetectedException
* This exception is not used.
* @sample AmazonLexRuntime.PostText
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/runtime.lex-2016-11-28/PostText" target="_top">AWS API
* Documentation</a>
*/
@Override
public PostTextResult postText(PostTextRequest request) {
request = beforeClientExecution(request);
return executePostText(request);
}
@SdkInternalApi
final PostTextResult executePostText(PostTextRequest postTextRequest) {
ExecutionContext executionContext = createExecutionContext(postTextRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<PostTextRequest> request = null;
Response<PostTextResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new PostTextRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(postTextRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);
request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Lex Runtime Service");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "PostText");
request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
HttpResponseHandler<AmazonWebServiceResponse<PostTextResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata()
.withPayloadJson(true).withHasStreamingSuccessResponse(false), new PostTextResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Creates a new session or modifies an existing session with an Amazon Lex bot. Use this operation to enable your
* application to set the state of the bot.
* </p>
* <p>
* For more information, see <a href="https://docs.aws.amazon.com/lex/latest/dg/how-session-api.html">Managing
* Sessions</a>.
* </p>
*
* @param putSessionRequest
* @return Result of the PutSession operation returned by the service.
* @throws NotFoundException
* The resource (such as the Amazon Lex bot or an alias) that is referred to is not found.
* @throws BadRequestException
* Request validation failed, there is no usable message in the context, or the bot build failed, is still
* in progress, or contains unbuilt changes.
* @throws LimitExceededException
* Exceeded a limit.
* @throws InternalFailureException
* Internal service error. Retry the call.
* @throws ConflictException
* Two clients are using the same AWS account, Amazon Lex bot, and user ID.
* @throws NotAcceptableException
* The accept header in the request does not have a valid value.
* @throws DependencyFailedException
* One of the dependencies, such as AWS Lambda or Amazon Polly, threw an exception. For example, </p>
* <ul>
* <li>
* <p>
* If Amazon Lex does not have sufficient permissions to call a Lambda function.
* </p>
* </li>
* <li>
* <p>
* If a Lambda function takes longer than 30 seconds to execute.
* </p>
* </li>
* <li>
* <p>
* If a fulfillment Lambda function returns a <code>Delegate</code> dialog action without removing any slot
* values.
* </p>
* </li>
* @throws BadGatewayException
* Either the Amazon Lex bot is still building, or one of the dependent services (Amazon Polly, AWS Lambda)
* failed with an internal service error.
* @sample AmazonLexRuntime.PutSession
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/runtime.lex-2016-11-28/PutSession" target="_top">AWS API
* Documentation</a>
*/
@Override
public PutSessionResult putSession(PutSessionRequest request) {
request = beforeClientExecution(request);
return executePutSession(request);
}
@SdkInternalApi
final PutSessionResult executePutSession(PutSessionRequest putSessionRequest) {
ExecutionContext executionContext = createExecutionContext(putSessionRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<PutSessionRequest> request = null;
Response<PutSessionResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new PutSessionRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(putSessionRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);
request.addHandlerContext(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Lex Runtime Service");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "PutSession");
request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
HttpResponseHandler<AmazonWebServiceResponse<PutSessionResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata()
.withPayloadJson(false).withHasStreamingSuccessResponse(true), new PutSessionResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
request.addHandlerContext(HandlerContextKey.HAS_STREAMING_OUTPUT, Boolean.TRUE);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* Returns additional metadata for a previously executed successful, request, typically used for debugging issues
* where a service isn't acting as expected. This data isn't considered part of the result data returned by an
* operation, so it's available through this separate, diagnostic interface.
* <p>
* Response metadata is only cached for a limited period of time, so if you need to access this extra diagnostic
* information for an executed request, you should use this method to retrieve it as soon as possible after
* executing the request.
*
* @param request
* The originally executed request
*
* @return The response metadata for the specified request, or null if none is available.
*/
public ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest request) {
return client.getResponseMetadataForRequest(request);
}
/**
* Normal invoke with authentication. Credentials are required and may be overriden at the request level.
**/
private <X, Y extends AmazonWebServiceRequest> Response<X> invoke(Request<Y> request, HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler,
ExecutionContext executionContext) {
return invoke(request, responseHandler, executionContext, null, null);
}
/**
* Normal invoke with authentication. Credentials are required and may be overriden at the request level.
**/
private <X, Y extends AmazonWebServiceRequest> Response<X> invoke(Request<Y> request, HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler,
ExecutionContext executionContext, URI cachedEndpoint, URI uriFromEndpointTrait) {
executionContext.setCredentialsProvider(CredentialUtils.getCredentialsProvider(request.getOriginalRequest(), awsCredentialsProvider));
return doInvoke(request, responseHandler, executionContext, cachedEndpoint, uriFromEndpointTrait);
}
/**
* Invoke with no authentication. Credentials are not required and any credentials set on the client or request will
* be ignored for this operation.
**/
private <X, Y extends AmazonWebServiceRequest> Response<X> anonymousInvoke(Request<Y> request,
HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler, ExecutionContext executionContext) {
return doInvoke(request, responseHandler, executionContext, null, null);
}
/**
* Invoke the request using the http client. Assumes credentials (or lack thereof) have been configured in the
* ExecutionContext beforehand.
**/
private <X, Y extends AmazonWebServiceRequest> Response<X> doInvoke(Request<Y> request, HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler,
ExecutionContext executionContext, URI discoveredEndpoint, URI uriFromEndpointTrait) {
if (discoveredEndpoint != null) {
request.setEndpoint(discoveredEndpoint);
request.getOriginalRequest().getRequestClientOptions().appendUserAgent("endpoint-discovery");
} else if (uriFromEndpointTrait != null) {
request.setEndpoint(uriFromEndpointTrait);
} else {
request.setEndpoint(endpoint);
}
request.setTimeOffset(timeOffset);
HttpResponseHandler<AmazonServiceException> errorResponseHandler = protocolFactory.createErrorResponseHandler(new JsonErrorResponseMetadata());
return client.execute(request, responseHandler, errorResponseHandler, executionContext);
}
@com.amazonaws.annotation.SdkInternalApi
static com.amazonaws.protocol.json.SdkJsonProtocolFactory getProtocolFactory() {
return protocolFactory;
}
@Override
public void shutdown() {
super.shutdown();
}
}
| aws/aws-sdk-java | aws-java-sdk-lex/src/main/java/com/amazonaws/services/lexruntime/AmazonLexRuntimeClient.java | Java | apache-2.0 | 39,578 |
/*
* Copyright 2014-2019 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.opsworks.model.transform;
import java.util.List;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.opsworks.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DescribeInstancesRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DescribeInstancesRequestMarshaller {
private static final MarshallingInfo<String> STACKID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("StackId").build();
private static final MarshallingInfo<String> LAYERID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("LayerId").build();
private static final MarshallingInfo<List> INSTANCEIDS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("InstanceIds").build();
private static final DescribeInstancesRequestMarshaller instance = new DescribeInstancesRequestMarshaller();
public static DescribeInstancesRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(DescribeInstancesRequest describeInstancesRequest, ProtocolMarshaller protocolMarshaller) {
if (describeInstancesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describeInstancesRequest.getStackId(), STACKID_BINDING);
protocolMarshaller.marshall(describeInstancesRequest.getLayerId(), LAYERID_BINDING);
protocolMarshaller.marshall(describeInstancesRequest.getInstanceIds(), INSTANCEIDS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-opsworks/src/main/java/com/amazonaws/services/opsworks/model/transform/DescribeInstancesRequestMarshaller.java | Java | apache-2.0 | 2,684 |
/**
* $URL: https://source.sakaiproject.org/svn/sitestats/tags/sakai-10.6/sitestats-impl/src/test/org/sakaiproject/sitestats/test/mocks/FakePlacement.java $
* $Id: FakePlacement.java 105078 2012-02-24 23:00:38Z [email protected] $
*
* Copyright (c) 2006-2009 The Sakai Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.sitestats.test.mocks;
import java.util.Properties;
import org.sakaiproject.tool.api.Placement;
import org.sakaiproject.tool.api.Tool;
public class FakePlacement implements Placement {
Properties config;
Properties placementConfig;
String context;
String id;
String title;
Tool tool;
public FakePlacement(Tool tool, String context) {
this.tool = tool;
this.context = context;
}
public String getToolId() {
return tool.getId();
}
public void save() {
}
public Properties getConfig() {
return config;
}
public void setConfig(Properties config) {
this.config = config;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Properties getPlacementConfig() {
return placementConfig;
}
public void setPlacementConfig(Properties placementConfig) {
this.placementConfig = placementConfig;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Tool getTool() {
return tool;
}
public void setTool(Tool tool) {
this.tool = tool;
}
public void setTool(String toolId, Tool tool) {
this.tool = tool;
}
}
| eemirtekin/Sakai-10.6-TR | sitestats/sitestats-impl/src/test/org/sakaiproject/sitestats/test/mocks/FakePlacement.java | Java | apache-2.0 | 2,194 |
package com.github.shell88.bddvideoannotator.stubjava;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java-Klasse für stringArray complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="stringArray">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="item" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "stringArray", propOrder = {
"item"
})
public class StringArray {
@XmlElement(nillable = true)
protected List<String> item;
/**
* Gets the value of the item 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 item property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getItem().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getItem() {
if (item == null) {
item = new ArrayList<String>();
}
return this.item;
}
}
| shell88/bdd_videoannotator | java/src/main/java/com/github/shell88/bddvideoannotator/stubjava/StringArray.java | Java | apache-2.0 | 1,828 |
package com.sixthsolution.apex.nlp.test;
import com.sixthsolution.apex.nlp.ner.ChunkedPart;
import com.sixthsolution.apex.nlp.ner.Entity;
import com.sixthsolution.apex.nlp.ner.Label;
import com.sixthsolution.apex.nlp.ner.regex.ChunkDetector;
import com.sixthsolution.apex.nlp.tagger.TaggedWord;
import com.sixthsolution.apex.nlp.tagger.Tagger;
import com.sixthsolution.apex.nlp.tokenization.Tokenizer;
import java.util.Iterator;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertNull;
import static junit.framework.TestCase.assertTrue;
/**
* @author Saeed Masoumi ([email protected])
*/
public class ChunkDetectorAssertion {
private static ChunkDetectorAssertion instance = null;
private final ChunkDetector detector;
private Tokenizer tokenizer;
private Tagger tagger;
private ChunkDetectorAssertion(Tokenizer tokenizer, Tagger tagger, ChunkDetector detector) {
this.tokenizer = tokenizer;
this.tagger = tagger;
this.detector = detector;
}
private static ChunkDetectorAssertion getInstance() {
return instance;
}
public static void init(Tokenizer tokenizer, Tagger tagger, ChunkDetector detector) {
instance = new ChunkDetectorAssertion(tokenizer, tagger, detector);
}
public static ChunkedPartAssertion assertChunkedPart(String sentence) {
System.out.println("chunk detector for: " + sentence);
long startTime = System.currentTimeMillis();
ChunkedPartAssertion result = new ChunkedPartAssertion(instance.detector.detect(
instance.tagger.tag(instance.tokenizer.tokenize(sentence))));
System.out.println(
"Detecting takes: " + (System.currentTimeMillis() - startTime) + " millis");
return result;
}
public static class ChunkedPartAssertion {
private final ChunkedPart chunkedPart;
public ChunkedPartAssertion(ChunkedPart chunkedPart) {
System.out.println("chunkedpart:"+chunkedPart);
this.chunkedPart = chunkedPart;
}
public ChunkedPartAssertion entity(Entity entity) {
assertTrue(chunkedPart.getEntity().equals(entity));
return this;
}
public ChunkedPartAssertion label(Label label) {
assertEquals(label, chunkedPart.getLabel());
return this;
}
public ChunkedPartAssertion text(String text) {
StringBuilder sb = new StringBuilder();
// System.out.println("tagwords:"+chunkedPart.getTaggedWords());
Iterator<TaggedWord> itr = chunkedPart.getTaggedWords().iterator();
// System.out.println("String:"+text);
Iterator<TaggedWord> itr2 = chunkedPart.getTaggedWords().iterator();
System.out.println(itr2.next().toString()+"**");
while (itr.hasNext()) {
// System.out.println(itr2.next().toString()+"**");
sb.append(itr.next().getWord());
if (itr.hasNext()) {
sb.append(" ");
}
}
assertEquals(text, sb.toString());
return this;
}
public ChunkedPartAssertion noDetection() {
assertNull(chunkedPart);
return this;
}
}
}
| 6thsolution/ApexNLP | apex/src/test/java/com/sixthsolution/apex/nlp/test/ChunkDetectorAssertion.java | Java | apache-2.0 | 3,352 |
package fr.fasar.raspy.tuto;
import javax.sound.sampled.*;
import java.io.*;
/**
* A sample program is to demonstrate how to record sound in Java
* author: www.codejava.net
*/
public class JavaSoundRecorder {
// record duration, in milliseconds
static final long RECORD_TIME = 10000; // 1 minute
// path of the wav file
File wavFile = new File("C:\\work\\sandbox\\JAVA\\raspy\\outfile\\RecordAudio.wav");
// format of audio file
AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;
// the line from which audio data is captured
TargetDataLine line;
/**
* Defines an audio format
*/
AudioFormat getAudioFormat() {
float sampleRate = 16000;
int sampleSizeInBits = 8;
int channels = 1;
boolean signed = true;
boolean bigEndian = false;
AudioFormat format = new AudioFormat(sampleRate, sampleSizeInBits,
channels, signed, bigEndian);
return format;
}
/**
* Captures the sound and record into a WAV file
*/
void start() {
try {
AudioFormat format = getAudioFormat();
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
// checks if system supports the data line
if (!AudioSystem.isLineSupported(info)) {
System.out.println("Line not supported");
System.exit(0);
}
line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format);
line.start(); // start capturing
System.out.println("Start capturing...");
AudioInputStream ais = new AudioInputStream(line);
System.out.println("Start recording...");
// start recording
AudioSystem.write(ais, fileType, wavFile);
} catch (LineUnavailableException ex) {
ex.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* Closes the target data line to finish capturing and recording
*/
void finish() {
line.stop();
line.close();
System.out.println("Finished");
}
/**
* Entry to run the program
*/
public static void main(String[] args) {
final JavaSoundRecorder recorder = new JavaSoundRecorder();
// creates a new thread that waits for a specified
// of time before stopping
Thread stopper = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(RECORD_TIME);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
recorder.finish();
}
});
stopper.start();
// start recording
recorder.start();
}
} | fasar/RaSpy | raspy-tuto/src/main/java/fr/fasar/raspy/tuto/JavaSoundRecorder.java | Java | apache-2.0 | 2,877 |
package com.wincom.mstar.domain;
import java.util.ArrayList;
import java.util.List;
public class CDoorEventTypeExample {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table nfjd502.dbo.CDoorEventType
*
* @mbggenerated Thu Mar 02 11:23:21 CST 2017
*/
protected String orderByClause;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table nfjd502.dbo.CDoorEventType
*
* @mbggenerated Thu Mar 02 11:23:21 CST 2017
*/
protected boolean distinct;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table nfjd502.dbo.CDoorEventType
*
* @mbggenerated Thu Mar 02 11:23:21 CST 2017
*/
protected List<Criteria> oredCriteria;
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table nfjd502.dbo.CDoorEventType
*
* @mbggenerated Thu Mar 02 11:23:21 CST 2017
*/
public CDoorEventTypeExample() {
oredCriteria = new ArrayList<Criteria>();
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table nfjd502.dbo.CDoorEventType
*
* @mbggenerated Thu Mar 02 11:23:21 CST 2017
*/
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table nfjd502.dbo.CDoorEventType
*
* @mbggenerated Thu Mar 02 11:23:21 CST 2017
*/
public String getOrderByClause() {
return orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table nfjd502.dbo.CDoorEventType
*
* @mbggenerated Thu Mar 02 11:23:21 CST 2017
*/
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table nfjd502.dbo.CDoorEventType
*
* @mbggenerated Thu Mar 02 11:23:21 CST 2017
*/
public boolean isDistinct() {
return distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table nfjd502.dbo.CDoorEventType
*
* @mbggenerated Thu Mar 02 11:23:21 CST 2017
*/
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table nfjd502.dbo.CDoorEventType
*
* @mbggenerated Thu Mar 02 11:23:21 CST 2017
*/
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table nfjd502.dbo.CDoorEventType
*
* @mbggenerated Thu Mar 02 11:23:21 CST 2017
*/
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table nfjd502.dbo.CDoorEventType
*
* @mbggenerated Thu Mar 02 11:23:21 CST 2017
*/
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table nfjd502.dbo.CDoorEventType
*
* @mbggenerated Thu Mar 02 11:23:21 CST 2017
*/
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table nfjd502.dbo.CDoorEventType
*
* @mbggenerated Thu Mar 02 11:23:21 CST 2017
*/
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table nfjd502.dbo.CDoorEventType
*
* @mbggenerated Thu Mar 02 11:23:21 CST 2017
*/
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andEventtypeIsNull() {
addCriterion("EventType is null");
return (Criteria) this;
}
public Criteria andEventtypeIsNotNull() {
addCriterion("EventType is not null");
return (Criteria) this;
}
public Criteria andEventtypeEqualTo(Integer value) {
addCriterion("EventType =", value, "eventtype");
return (Criteria) this;
}
public Criteria andEventtypeNotEqualTo(Integer value) {
addCriterion("EventType <>", value, "eventtype");
return (Criteria) this;
}
public Criteria andEventtypeGreaterThan(Integer value) {
addCriterion("EventType >", value, "eventtype");
return (Criteria) this;
}
public Criteria andEventtypeGreaterThanOrEqualTo(Integer value) {
addCriterion("EventType >=", value, "eventtype");
return (Criteria) this;
}
public Criteria andEventtypeLessThan(Integer value) {
addCriterion("EventType <", value, "eventtype");
return (Criteria) this;
}
public Criteria andEventtypeLessThanOrEqualTo(Integer value) {
addCriterion("EventType <=", value, "eventtype");
return (Criteria) this;
}
public Criteria andEventtypeIn(List<Integer> values) {
addCriterion("EventType in", values, "eventtype");
return (Criteria) this;
}
public Criteria andEventtypeNotIn(List<Integer> values) {
addCriterion("EventType not in", values, "eventtype");
return (Criteria) this;
}
public Criteria andEventtypeBetween(Integer value1, Integer value2) {
addCriterion("EventType between", value1, value2, "eventtype");
return (Criteria) this;
}
public Criteria andEventtypeNotBetween(Integer value1, Integer value2) {
addCriterion("EventType not between", value1, value2, "eventtype");
return (Criteria) this;
}
public Criteria andEventdescIsNull() {
addCriterion("EventDesc is null");
return (Criteria) this;
}
public Criteria andEventdescIsNotNull() {
addCriterion("EventDesc is not null");
return (Criteria) this;
}
public Criteria andEventdescEqualTo(String value) {
addCriterion("EventDesc =", value, "eventdesc");
return (Criteria) this;
}
public Criteria andEventdescNotEqualTo(String value) {
addCriterion("EventDesc <>", value, "eventdesc");
return (Criteria) this;
}
public Criteria andEventdescGreaterThan(String value) {
addCriterion("EventDesc >", value, "eventdesc");
return (Criteria) this;
}
public Criteria andEventdescGreaterThanOrEqualTo(String value) {
addCriterion("EventDesc >=", value, "eventdesc");
return (Criteria) this;
}
public Criteria andEventdescLessThan(String value) {
addCriterion("EventDesc <", value, "eventdesc");
return (Criteria) this;
}
public Criteria andEventdescLessThanOrEqualTo(String value) {
addCriterion("EventDesc <=", value, "eventdesc");
return (Criteria) this;
}
public Criteria andEventdescLike(String value) {
addCriterion("EventDesc like", value, "eventdesc");
return (Criteria) this;
}
public Criteria andEventdescNotLike(String value) {
addCriterion("EventDesc not like", value, "eventdesc");
return (Criteria) this;
}
public Criteria andEventdescIn(List<String> values) {
addCriterion("EventDesc in", values, "eventdesc");
return (Criteria) this;
}
public Criteria andEventdescNotIn(List<String> values) {
addCriterion("EventDesc not in", values, "eventdesc");
return (Criteria) this;
}
public Criteria andEventdescBetween(String value1, String value2) {
addCriterion("EventDesc between", value1, value2, "eventdesc");
return (Criteria) this;
}
public Criteria andEventdescNotBetween(String value1, String value2) {
addCriterion("EventDesc not between", value1, value2, "eventdesc");
return (Criteria) this;
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table nfjd502.dbo.CDoorEventType
*
* @mbggenerated do_not_delete_during_merge Thu Mar 02 11:23:21 CST 2017
*/
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table nfjd502.dbo.CDoorEventType
*
* @mbggenerated Thu Mar 02 11:23:21 CST 2017
*/
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | xtwxy/cassandra-tests | mstar-server-dao/src/main/java/com/wincom/mstar/domain/CDoorEventTypeExample.java | Java | apache-2.0 | 13,188 |
/*
* Copyright 2015 Adaptris Ltd.
*
* 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.adaptris.core.services.aggregator;
import java.io.IOException;
import javax.mail.MessagingException;
import com.adaptris.annotation.ComponentProfile;
import com.adaptris.annotation.DisplayOrder;
import com.adaptris.core.AdaptrisMessage;
import com.adaptris.core.CoreConstants;
import com.adaptris.core.MetadataCollection;
import com.adaptris.util.text.mime.MultiPartOutput;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
* {@link MessageAggregator} implementation that creates a new mime part for each message that needs
* to be joined up.
* <p>
* The original pre-split document is ignored, the unique ID of the message is used as the
* Content-ID of the new multipart; the payloads from the split messages are used to form the
* resulting multipart message. If an explicit Content-Id (expression or otherwise) has been
* specified then this will be resolved and used as that parts {@code Content-ID} otherwise the
* split message's unique-id will be used. If the same {@code Content-ID} is re-used for multiple
* split messages then results are undefined. The most likely situation is that parts will be lost
* and only one preserved.
* </p>
* <p>
* As a result of this join operation, the message will be marked as MIME encoded using
* {@link com.adaptris.core.CoreConstants#MSG_MIME_ENCODED} metadata.
* </p>
* </p>
*
* @config ignore-original-mime-aggregator
* @see CoreConstants#MSG_MIME_ENCODED
* @author lchan
*
*/
@XStreamAlias("ignore-original-mime-aggregator")
@DisplayOrder(order = {"encoding", "mimeContentSubType", "mimeHeaderFilter", "overwriteMetadata",
"partContentId", "partContentType", "partHeaderFilter"})
@ComponentProfile(
summary = "Aggregator implementation that creates a new mime part for each message that needs to be joined up")
public class IgnoreOriginalMimeAggregator extends MimeAggregator {
@Override
protected MultiPartOutput createInitialPart(AdaptrisMessage original) throws MessagingException, IOException {
MultiPartOutput output =
new MultiPartOutput(original.getUniqueId(), mimeContentSubType(original));
MetadataCollection metadata = mimeHeaderFilter().filter(original);
metadata.forEach((e) -> {
output.setHeader(e.getKey(), e.getValue());
});
return output;
}
}
| adaptris/interlok | interlok-core/src/main/java/com/adaptris/core/services/aggregator/IgnoreOriginalMimeAggregator.java | Java | apache-2.0 | 2,903 |
package com.sibilantsolutions.grison.driver.foscam.entity;
import com.google.auto.value.AutoValue;
import com.sibilantsolutions.grison.driver.foscam.domain.ResultCodeE;
@AutoValue
public abstract class VerifyRespTextEntity implements FoscamTextEntity {
public abstract ResultCodeE resultCode();
public static VerifyRespTextEntity.Builder builder() {
return new AutoValue_VerifyRespTextEntity.Builder();
}
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder resultCode(ResultCodeE resultCode);
public abstract VerifyRespTextEntity build();
}
}
| jtgeiger/grison | lib/src/main/java/com/sibilantsolutions/grison/driver/foscam/entity/VerifyRespTextEntity.java | Java | apache-2.0 | 627 |
package chapter03.inst.sizeof;
public class DeepSizeOfMain {
public static void main(String []args) {
DeepObjectSizeOf.deepSizeOf(new Integer(1));
DeepObjectSizeOf.deepSizeOf(new String());
DeepObjectSizeOf.deepSizeOf(new char[1]);
}
}
| muzi666boy/jdk-test | src/chapter03/inst/sizeof/DeepSizeOfMain.java | Java | apache-2.0 | 258 |
/*****************************************************************************
* 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 bsh;
public class ProjectCoinFeature extends KnownIssue {
// public static boolean IS_BELOW_JAVA_v7 = "1.7".compareTo(System.getProperty("java.version").substring(0,3)) < 0;
}
| beanshell/beanshell | src/test/java/bsh/ProjectCoinFeature.java | Java | apache-2.0 | 1,693 |
/**
* Copyright (C) 2006-2020 Talend Inc. - www.talend.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.
*/
@Components(family = "demo")
@Icon(Icon.IconType.DEFAULT)
package org.talend.test.valid.datastore;
import org.talend.sdk.component.api.component.Components;
import org.talend.sdk.component.api.component.Icon;
| chmyga/component-runtime | component-tools/src/test/java/org/talend/test/valid/datastore/package-info.java | Java | apache-2.0 | 828 |
package com.lpnpcs.yuanhelper.widget.swipeback;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.View;
public class SwipeBackPreferenceActivity extends PreferenceActivity implements SwipeBackActivityBase {
private SwipeBackActivityHelper mHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHelper = new SwipeBackActivityHelper(this);
mHelper.onActivityCreate();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mHelper.onPostCreate();
}
@Override
public View findViewById(int id) {
View v = super.findViewById(id);
if (v == null && mHelper != null)
return mHelper.findViewById(id);
return v;
}
@Override
public SwipeBackLayout getSwipeBackLayout() {
return mHelper.getSwipeBackLayout();
}
@Override
public void setSwipeBackEnable(boolean enable) {
getSwipeBackLayout().setEnableGesture(enable);
}
@Override
public void scrollToFinishActivity() {
getSwipeBackLayout().scrollToFinishActivity();
}
}
| lpnpcs/yuanhelper | app/src/main/java/com/lpnpcs/yuanhelper/widget/swipeback/SwipeBackPreferenceActivity.java | Java | apache-2.0 | 1,245 |
/*
* 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.bigquery.storage.v1beta1;
import com.google.api.pathtemplate.PathTemplate;
import com.google.api.resourcenames.ResourceName;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
@Generated("by gapic-generator-java")
public class ProjectName implements ResourceName {
private static final PathTemplate PROJECT =
PathTemplate.createWithoutUrlEncoding("projects/{project}");
private volatile Map<String, String> fieldValuesMap;
private final String project;
@Deprecated
protected ProjectName() {
project = null;
}
private ProjectName(Builder builder) {
project = Preconditions.checkNotNull(builder.getProject());
}
public String getProject() {
return project;
}
public static Builder newBuilder() {
return new Builder();
}
public Builder toBuilder() {
return new Builder(this);
}
public static ProjectName of(String project) {
return newBuilder().setProject(project).build();
}
public static String format(String project) {
return newBuilder().setProject(project).build().toString();
}
public static ProjectName parse(String formattedString) {
if (formattedString.isEmpty()) {
return null;
}
Map<String, String> matchMap =
PROJECT.validatedMatch(
formattedString, "ProjectName.parse: formattedString not in valid format");
return of(matchMap.get("project"));
}
public static List<ProjectName> parseList(List<String> formattedStrings) {
List<ProjectName> list = new ArrayList<>(formattedStrings.size());
for (String formattedString : formattedStrings) {
list.add(parse(formattedString));
}
return list;
}
public static List<String> toStringList(List<ProjectName> values) {
List<String> list = new ArrayList<>(values.size());
for (ProjectName value : values) {
if (value == null) {
list.add("");
} else {
list.add(value.toString());
}
}
return list;
}
public static boolean isParsableFrom(String formattedString) {
return PROJECT.matches(formattedString);
}
@Override
public Map<String, String> getFieldValuesMap() {
if (fieldValuesMap == null) {
synchronized (this) {
if (fieldValuesMap == null) {
ImmutableMap.Builder<String, String> fieldMapBuilder = ImmutableMap.builder();
if (project != null) {
fieldMapBuilder.put("project", project);
}
fieldValuesMap = fieldMapBuilder.build();
}
}
}
return fieldValuesMap;
}
public String getFieldValue(String fieldName) {
return getFieldValuesMap().get(fieldName);
}
@Override
public String toString() {
return PROJECT.instantiate("project", project);
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o != null || getClass() == o.getClass()) {
ProjectName that = ((ProjectName) o);
return Objects.equals(this.project, that.project);
}
return false;
}
@Override
public int hashCode() {
int h = 1;
h *= 1000003;
h ^= Objects.hashCode(project);
return h;
}
/** Builder for projects/{project}. */
public static class Builder {
private String project;
protected Builder() {}
public String getProject() {
return project;
}
public Builder setProject(String project) {
this.project = project;
return this;
}
private Builder(ProjectName projectName) {
this.project = projectName.project;
}
public ProjectName build() {
return new ProjectName(this);
}
}
}
| googleapis/java-bigquerystorage | proto-google-cloud-bigquerystorage-v1beta1/src/main/java/com/google/cloud/bigquery/storage/v1beta1/ProjectName.java | Java | apache-2.0 | 4,441 |
/* Copyright 2013 Rabidgremlin Limited
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.rabidgremlin.serverimager;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.bridge.SLF4JBridgeHandler;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.ParameterException;
import com.google.common.base.Joiner;
import com.rabidgremlin.serverimager.api.ApiHelper;
import com.rabidgremlin.serverimager.api.ImageDetails;
import com.rabidgremlin.serverimager.api.ServerDetails;
import com.rabidgremlin.serverimager.opts.MainOptions;
public class ServerImager
{
private static Logger log = LoggerFactory.getLogger(ServerImager.class);
public static void main(String[] args)
{
// Bridge JUL to SLF4J
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
log.info("Starting ServerImager...");
MainOptions options = new MainOptions();
JCommander jc = new JCommander(options);
jc.setProgramName("java -jar serverimager.jar");
ApiHelper apiHelper = null;
try
{
// validate the args
jc.parse(args);
// turn on debugging logging if requested
if (options.debug)
{
ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory
.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
root.setLevel(ch.qos.logback.classic.Level.DEBUG);
}
// create the api helper
apiHelper = new ApiHelper(options.username, options.apiKey, options.rackspaceZone);
// get the list of servers
List<ServerDetails> servers = apiHelper.getServers();
// create map to validate servers against
HashMap<String, ServerDetails> serversByNameMap = new HashMap<String, ServerDetails>();
for (ServerDetails server : servers)
{
serversByNameMap.put(server.getName(), server);
}
// validate that requested servers exist
for (String server : options.servers)
{
log.debug("Checking if server {} exists...", server);
if (!serversByNameMap.containsKey(server))
{
throw new Exception("Cannot find server: " + server + ". Current servers are: "
+ Joiner.on(", ").join(serversByNameMap.keySet()));
}
}
// dump list of servers that will be processed
log.info("Processing images for servers:");
for (String server : options.servers)
{
ServerDetails serverDetails = serversByNameMap.get(server);
log.info(" {} ({})", serverDetails.getName(), serverDetails.getId());
}
// create images
if (options.noImageCreation)
{
log.warn("-nocreate specified. NO IMAGES WILL BE CREATED!");
}
else
{
log.info("Creating server images...");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
String timestamp = formatter.format(new Date());
log.debug("Using timestamp {}", timestamp);
// create images for server
for (String server : options.servers)
{
ServerDetails serverDetails = serversByNameMap.get(server);
String imageName = options.imageNamePrefix + "_" + serverDetails.getName() + "_" + timestamp;
log.info("Requested creation of image {} for server {}", imageName, serverDetails.getName());
apiHelper.createImage(imageName, serverDetails.getId());
}
}
// delete old images
if (options.nukeOldImages)
{
// build up set of server ids for the servers specified on cmd line
HashSet<String> serverIdSet = new HashSet<String>();
for (String server : options.servers)
{
ServerDetails serverDetails = serversByNameMap.get(server);
if (serverDetails != null)
{
serverIdSet.add(serverDetails.getId());
}
}
log.info("Deleting images older then {} days", options.maxImageAgeInDays);
List<ImageDetails> images = apiHelper.getImages(options.imageNamePrefix, serverIdSet);
int deletedCount = 0;
for (ImageDetails image : images)
{
log.debug("Image {} is {} days old", image.getName(), image.getAgeInDays());
if (image.getAgeInDays() >= options.maxImageAgeInDays)
{
log.info("Deleting image {} ({})...", image.getName(), image.getId());
apiHelper.deleteImage(image.getId());
deletedCount++;
}
else
{
log.info("Skipping image {}. It is only {} days old", image.getName(), image.getAgeInDays());
}
}
log.info("{} images deleted.", deletedCount);
}
else
{
log.warn("-nuke not specified. NO IMAGES WILL BE DELETED!");
}
log.info("Done.");
}
catch (ParameterException e)
{
log.error("Parameter error: {}", e.getMessage());
jc.usage();
System.exit(1);
}
catch (Throwable t)
{
log.error("Unexpected error: {}", t.getMessage());
log.debug("Stacktrace: ", t);
System.exit(1);
}
finally
{
if (apiHelper != null)
{
apiHelper.close();
}
}
}
}
| rabidgremlin/ServerImager | src/com/rabidgremlin/serverimager/ServerImager.java | Java | apache-2.0 | 5,921 |
package com.pilaf.cs.rest;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.mobile.device.Device;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.pilaf.cs.security.jwt.JwtAuthenticationRequest;
import com.pilaf.cs.security.jwt.JwtAuthenticationResponse;
import com.pilaf.cs.security.jwt.JwtTokenUtil;
import com.pilaf.cs.security.jwt.UserAuth;
@RestController
public class AuthenticationRestController extends AbstractRestController {
@Value("${jwt.header}")
private String tokenHeader;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private UserDetailsService userDetailsService;
@RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest, Device device) throws AuthenticationException {
// Perform the security
final Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
authenticationRequest.getUsername(),
authenticationRequest.getPassword()
)
);
SecurityContextHolder.getContext().setAuthentication(authentication);
// Reload password post-security so we can generate token
final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
final String token = jwtTokenUtil.generateToken(userDetails, device);
// Return the token
return ResponseEntity.ok(new JwtAuthenticationResponse(token));
}
@RequestMapping(value = "${jwt.route.authentication.refresh}", method = RequestMethod.GET)
public ResponseEntity<?> refreshAndGetAuthenticationToken(HttpServletRequest request) {
String token = request.getHeader(tokenHeader);
String username = jwtTokenUtil.getUsernameFromToken(token);
UserAuth user = (UserAuth) userDetailsService.loadUserByUsername(username);
if (jwtTokenUtil.canTokenBeRefreshed(token, user.getLastPasswordResetDate())) {
String refreshedToken = jwtTokenUtil.refreshToken(token);
return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken));
} else {
return ResponseEntity.badRequest().body(null);
}
}
}
| rakocz88/castlesiege2.0 | CastleSiegePom/CastleSiegeApp/src/main/java/com/pilaf/cs/rest/AuthenticationRestController.java | Java | apache-2.0 | 3,332 |
/*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/
package io.shardingsphere.shardingproxy.backend.jdbc.execute.response;
import io.shardingsphere.shardingproxy.backend.jdbc.execute.response.unit.ExecuteResponseUnit;
import io.shardingsphere.shardingproxy.backend.jdbc.execute.response.unit.ExecuteUpdateResponseUnit;
import io.shardingsphere.shardingproxy.transport.mysql.packet.command.CommandResponsePackets;
import io.shardingsphere.shardingproxy.transport.mysql.packet.generic.OKPacket;
import lombok.Getter;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
/**
* Execute update response.
*
* @author zhangliang
*/
public final class ExecuteUpdateResponse implements ExecuteResponse {
@Getter
private final List<OKPacket> packets = new LinkedList<>();
public ExecuteUpdateResponse(final Collection<ExecuteResponseUnit> responseUnits) {
for (ExecuteResponseUnit each : responseUnits) {
packets.add(((ExecuteUpdateResponseUnit) each).getOkPacket());
}
}
/**
* Merge packets.
*
* @return merged packet.
*/
public CommandResponsePackets merge() {
int affectedRows = 0;
long lastInsertId = 0;
for (OKPacket each : packets) {
affectedRows += each.getAffectedRows();
if (each.getLastInsertId() > lastInsertId) {
lastInsertId = each.getLastInsertId();
}
}
return new CommandResponsePackets(new OKPacket(1, affectedRows, lastInsertId));
}
}
| dangdangdotcom/sharding-jdbc | sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/execute/response/ExecuteUpdateResponse.java | Java | apache-2.0 | 2,130 |
/**
* Copyright (C) 2016 - 2030 youtongluan.
*
* 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.yx.redis.v3;
import java.util.function.Function;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;
/**
* jedis2.x 额外增加的方法
*/
public interface Redis3x {
/**
* 执行redis的批量操作或jedis的原生操作。<BR>
* 注意:<B>如果是集群情况下,要保证所有的操作确实在key所对应的节点上才行,所以这个方法在集群环境里要慎重使用</B>
*
* @param <T>
* 返回值类型
* @param sampleKey
* 只有在集群情况下才有意义,用于寻找真正的jedis节点
* @param callback
* 批处理的代码
* @return 返回的是callback的返回值
*/
<T> T execute(String sampleKey, Function<Jedis, T> callback);
Long publish(String channel, String message);
void subscribe(JedisPubSub jedisPubSub, String... channels);
void psubscribe(final JedisPubSub jedisPubSub, final String... patterns);
}
| youtongluan/sumk | src/main/java/org/yx/redis/v3/Redis3x.java | Java | apache-2.0 | 1,557 |
package cellmate.cell;
import com.google.common.annotations.Beta;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Required for use with the extractor and writer APIs.
* See {@link cellmate.extractor.SingleMultiValueCellExtractor} and
* {@link cellmate.writer.DBRecordWriter}
*
*/
@Beta
@Target(value={ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Cell {
}
| bfemiano/cellmate | cellmate-core/src/main/java/cellmate/cell/Cell.java | Java | apache-2.0 | 512 |
/*
* Copyright 2014-2016 Media for Mobile
*
* 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.m4m.domain.mediaComposer;
import org.m4m.AudioFormat;
import org.m4m.MediaComposer;
import org.m4m.VideoFormat;
import org.junit.Test;
import org.m4m.domain.AudioDecoder;
import org.m4m.domain.AudioEncoder;
import org.m4m.domain.MediaSource;
import org.m4m.domain.VideoDecoder;
import org.m4m.domain.VideoEncoder;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class WhenSingleTrack extends MediaComposerTest {
@Test
public void canSetAudioFormatWithoutTarget() {
mediaComposer = new MediaComposer(new AndroidMediaObjectFactoryFake(create), progressListener);
AudioFormat audioFormat = create.audioFormat().construct();
mediaComposer.setTargetAudioFormat(audioFormat);
assertEquals(audioFormat, mediaComposer.getTargetAudioFormat());
}
@Test
public void canSetVideoFormatWithoutTarget() {
mediaComposer = new MediaComposer(new AndroidMediaObjectFactoryFake(create), progressListener);
VideoFormat videoFormat = create.videoFormat().construct();
mediaComposer.setTargetVideoFormat(videoFormat);
assertEquals(videoFormat, mediaComposer.getTargetVideoFormat());
}
@Test
public void canTranscodeWithVideoFormatSetButNoVideoInStream() throws IOException, InterruptedException {
AndroidMediaObjectFactoryFake androidMediaObjectFactoryFake = new AndroidMediaObjectFactoryFake(create);
MediaSource mediaSource = create.mediaSource()
.withAudioTrack(0, 100).with(4).audioFrames()
.construct();
AudioDecoder audioDecoder = create.audioDecoder().construct();
AudioEncoder audioEncoder = create.audioEncoder()
.withOutputFormatChanged()
.whichEncodesTo(a.frame().withTimeStamp(0).construct())
.whichEncodesTo(a.frame().withTimeStamp(25).construct())
.whichEncodesTo(a.frame().withTimeStamp(50).construct())
.whichEncodesTo(a.frame().withTimeStamp(75).withFlag(4).construct())
.construct();
androidMediaObjectFactoryFake
.withMediaSource(mediaSource)
.withAudioDecoder(audioDecoder)
.withAudioEncoder(audioEncoder);
mediaComposer = new MediaComposer(androidMediaObjectFactoryFake, progressListener);
VideoFormat videoFormat = create.videoFormat().construct();
mediaComposer.setTargetVideoFormat(videoFormat);
AudioFormat audioFormat = create.audioFormat().construct();
mediaComposer.setTargetAudioFormat(audioFormat);
mediaComposer.addSourceFile("");
mediaComposer.setTargetFile("");
mediaComposer.start();
waitUntilDone(progressListener);
assertThat(progressListener).containsProgress(0f, 0.25f, 0.5f, 0.75f, 1f);
}
@Test
public void canTranscodeWithAudioFormatSetButNoAudioInStream() throws IOException, InterruptedException {
AndroidMediaObjectFactoryFake androidMediaObjectFactoryFake = new AndroidMediaObjectFactoryFake(create);
MediaSource mediaSource = create.mediaSource()
.withVideoTrack(0, 100).with(4).videoFrames()
.construct();
VideoDecoder decoder = create.videoDecoder()
.whichDecodesTo(create.frame(100).withTimeStamp(12).construct())
.whichDecodesTo(create.frame(100).withTimeStamp(12).construct())
.whichDecodesTo(create.frame(100).withTimeStamp(12).construct())
.whichDecodesTo(create.frame(100).withTimeStamp(12).construct())
.construct();
VideoEncoder videoEncoder = create.videoEncoder()
.withOutputFormatChanged()
.whichEncodesTo(create.frame(100).withTimeStamp(0).construct())
.whichEncodesTo(create.frame(100).withTimeStamp(25).construct())
.whichEncodesTo(create.frame(100).withTimeStamp(50).construct())
.whichEncodesTo(create.frame(100).withTimeStamp(75).construct())
.construct();
androidMediaObjectFactoryFake
.withVideoDecoder(decoder)
.withVideoEncoder(videoEncoder)
.withMediaSource(mediaSource);
mediaComposer = new MediaComposer(androidMediaObjectFactoryFake, progressListener);
VideoFormat videoFormat = create.videoFormat().construct();
mediaComposer.setTargetVideoFormat(videoFormat);
AudioFormat audioFormat = create.audioFormat().construct();
mediaComposer.setTargetAudioFormat(audioFormat);
mediaComposer.addSourceFile("");
mediaComposer.setTargetFile("");
mediaComposer.start();
waitUntilDone(progressListener);
assertThat(progressListener).containsProgress(0f, 0.25f, 0.5f, 0.75f, 1f);
}
}
| INDExOS/media-for-mobile | domain/src/test/java/org/m4m/domain/mediaComposer/WhenSingleTrack.java | Java | apache-2.0 | 5,481 |
/*
* 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.servicecomb.loadbalance.filter;
import java.util.ArrayList;
import java.util.List;
import org.apache.servicecomb.foundation.common.event.AlarmEvent.Type;
import org.apache.servicecomb.foundation.common.event.EventManager;
import org.apache.servicecomb.loadbalance.Configuration;
import org.apache.servicecomb.loadbalance.CseServer;
import org.apache.servicecomb.loadbalance.ServerListFilterExt;
import org.apache.servicecomb.loadbalance.event.IsolationServerEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.EventBus;
import com.netflix.loadbalancer.LoadBalancerStats;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ServerStats;
public final class IsolationServerListFilter implements ServerListFilterExt {
private static final Logger LOGGER = LoggerFactory.getLogger(IsolationServerListFilter.class);
private static final double PERCENT = 100;
private String microserviceName;
private int errorThresholdPercentage;
private long singleTestTime;
private long enableRequestThreshold;
private int continuousFailureThreshold;
private LoadBalancerStats stats;
public EventBus eventBus = EventManager.getEventBus();
public void setLoadBalancerStats(LoadBalancerStats stats) {
this.stats = stats;
}
public LoadBalancerStats getLoadBalancerStats() {
return stats;
}
public String getMicroserviceName() {
return microserviceName;
}
public void setMicroserviceName(String microserviceName) {
this.microserviceName = microserviceName;
}
@Override
public List<Server> getFilteredListOfServers(List<Server> servers) {
if (!Configuration.INSTANCE.isIsolationFilterOpen(microserviceName)) {
return servers;
}
List<Server> filteredServers = new ArrayList<>();
for (Server server : servers) {
if (allowVisit(server)) {
filteredServers.add(server);
}
}
return filteredServers;
}
private void updateSettings() {
errorThresholdPercentage = Configuration.INSTANCE.getErrorThresholdPercentage(microserviceName);
singleTestTime = Configuration.INSTANCE.getSingleTestTime(microserviceName);
enableRequestThreshold = Configuration.INSTANCE.getEnableRequestThreshold(microserviceName);
continuousFailureThreshold = Configuration.INSTANCE.getContinuousFailureThreshold(microserviceName);
}
private boolean allowVisit(Server server) {
updateSettings();
ServerStats serverStats = stats.getSingleServerStat(server);
long totalRequest = serverStats.getTotalRequestsCount();
long failureRequest = serverStats.getSuccessiveConnectionFailureCount();
int currentCountinuousFailureCount = 0;
double currentErrorThresholdPercentage = 0;
if (totalRequest < enableRequestThreshold) {
return true;
}
if (continuousFailureThreshold > 0) {
// continuousFailureThreshold has higher priority to decide the result
currentCountinuousFailureCount = ((CseServer) server).getCountinuousFailureCount();
if (currentCountinuousFailureCount < continuousFailureThreshold) {
return true;
}
} else {
// if continuousFailureThreshold, then check error percentage
currentErrorThresholdPercentage = (failureRequest / (double) totalRequest) * PERCENT;
if (currentErrorThresholdPercentage < errorThresholdPercentage) {
return true;
}
}
if ((System.currentTimeMillis() - ((CseServer) server).getLastVisitTime()) > singleTestTime) {
LOGGER.info("The Service {}'s instance {} has been break, will give a single test opportunity.",
microserviceName,
server);
eventBus.post(new IsolationServerEvent(microserviceName, totalRequest, currentCountinuousFailureCount,
currentErrorThresholdPercentage,
continuousFailureThreshold, errorThresholdPercentage, enableRequestThreshold,
singleTestTime, Type.CLOSE));
return true;
}
LOGGER.warn("The Service {}'s instance {} has been break!", microserviceName, server);
eventBus.post(new IsolationServerEvent(microserviceName, totalRequest, currentCountinuousFailureCount,
currentErrorThresholdPercentage,
continuousFailureThreshold, errorThresholdPercentage, enableRequestThreshold,
singleTestTime, Type.OPEN));
return false;
}
}
| acsukesh/java-chassis | handlers/handler-loadbalance/src/main/java/org/apache/servicecomb/loadbalance/filter/IsolationServerListFilter.java | Java | apache-2.0 | 5,176 |
package com.cjw.zhiyue.ui.view;
import java.util.List;
import com.cjw.zhiyue.R;
import com.cjw.zhiyue.db.Dao.PlayListDao;
import com.cjw.zhiyue.db.domain.SongInfo;
import com.cjw.zhiyue.domain.PlaySongInfo;
import com.cjw.zhiyue.global.GlobalConstant;
import com.cjw.zhiyue.http.protocol.PlaySongProtocol;
import com.cjw.zhiyue.ui.adapter.MyBaseAdapter.OnItemClickListener;
import com.cjw.zhiyue.ui.adapter.popupw.PlayListPopupwAdapter;
import com.cjw.zhiyue.utils.UIUtils;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.widget.PopupWindow;
import android.widget.Toast;
public class PalyListPopupw extends PopupWindow {
protected static final int GET_SUCCESS = 0;
private View mRootView;
private RecyclerView mRecyclerview;
private PlayListPopupwAdapter mListAdapter = null;
public PalyListPopupw() {
}
public PalyListPopupw(Context context) {
super(context);
}
public PalyListPopupw(View contentView) {
super(contentView);
}
public PalyListPopupw(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PalyListPopupw(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public PalyListPopupw(View contentView, int width, int height) {
super(contentView, width, height);
}
public PalyListPopupw(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public PalyListPopupw(View contentView, int width, int height, boolean focusable) {
super(contentView, width, height, focusable);
}
/**
* 通过此构造方法生成列表的popupwindow
*/
public PalyListPopupw(int width, int height) {
super(width, height);
mRootView = initRootView();
setContentView(mRootView);
setPopupWindow();// 设置各自参数
}
/**
* 生成根布局
*/
private View initRootView() {
View view = UIUtils.inflate(R.layout.layout_popupw_play_list);
mRecyclerview = (RecyclerView) view.findViewById(R.id.recyclerview);
return view;
}
/**
* 设置各自参数
*/
private void setPopupWindow() {
setBackgroundDrawable(new ColorDrawable());// 设置透明背景,背景如果不设置的话,回退按钮不起作用
setOutsideTouchable(true);// 外部可点击
setFocusable(true);
setAnimationStyle(R.style.animat_dialog);// 设置进程动画
initRecyclerView();
}
/**
* 初始化RecyclerView
*/
private void initRecyclerView() {
final LinearLayoutManager layoutManager = new LinearLayoutManager(UIUtils.getContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerview.setLayoutManager(layoutManager);
mRecyclerview.setItemAnimator(new DefaultItemAnimator()); // 设置增加或删除条目的动画
// recyclerview.addItemDecoration(new
// SpaceItemDecoration(UIUtils.dip2px(10)));//设置间距
List<SongInfo> songPlayList = PlayListDao.getPlayListDao().query();
mListAdapter = new PlayListPopupwAdapter(songPlayList);
mRecyclerview.setAdapter(mListAdapter);
mListAdapter.setOnItemClickListener(new OnItemClickListener<SongInfo>() {
@Override
public void onItemClick(View view, int position, SongInfo info) {
// 请求网络播放音乐
requestSongProtocol(info);
PalyListPopupw.this.dismiss();
}
});
}
/**
* 重新获取列表数据
*/
public void setAdaperData() {
List<SongInfo> songPlayList = PlayListDao.getPlayListDao().query();
mListAdapter.data = songPlayList;
mListAdapter.notifyDataSetChanged();//更新播放列表内容
}
/**
* 请求网络,拿到播放地址
*/
protected void requestSongProtocol(SongInfo songInfo) {
final Intent intent = new Intent(GlobalConstant.REQUEST_PLAY_SONG_ACTION);
PlaySongProtocol playSongProtocol = new PlaySongProtocol() {
@Override
public PlaySongInfo parseData(String result) {
// 重写解析方法,网络请求成功后,去开始服务播放音乐
PlaySongInfo playSongInfo = super.parseData(result);
// 发送广播
intent.putExtra("result", GET_SUCCESS);
intent.putExtra("playSongInfo", playSongInfo);
UIUtils.getContext().sendBroadcast(intent);
return playSongInfo;
}
@Override
public void requestHttpFail() {
// 请求播放地址失败
Toast.makeText(UIUtils.getContext(), "请检查网络连接", Toast.LENGTH_SHORT).show();
}
};
playSongProtocol.getDataFromCache("&songid=" + songInfo.song_id);
}
}
| cjw363/zhiyue | ZhiYue/src/com/cjw/zhiyue/ui/view/PalyListPopupw.java | Java | apache-2.0 | 4,726 |
package com.suscipio_solutions.consecro_mud.Abilities.Druid;
import java.util.Arrays;
import java.util.Vector;
import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CharStats;
import com.suscipio_solutions.consecro_mud.Items.interfaces.RawMaterial;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.Races.interfaces.Race;
import com.suscipio_solutions.consecro_mud.core.CMClass;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.interfaces.Physical;
@SuppressWarnings("rawtypes")
public class Chant_BreatheWater extends Chant
{
@Override public String ID() { return "Chant_BreatheWater"; }
private final static String localizedName = CMLib.lang().L("Fish Gills");
@Override public String name() { return localizedName; }
private final static String localizedStaticDisplay = CMLib.lang().L("(Fish Gills)");
@Override public String displayText() { return localizedStaticDisplay; }
@Override public int classificationCode(){return Ability.ACODE_CHANT|Ability.DOMAIN_SHAPE_SHIFTING;}
@Override public int abstractQuality(){return Ability.QUALITY_OK_SELF;}
protected int[] lastSet=null;
protected int[] newSet=null;
@Override
public void unInvoke()
{
if(!(affected instanceof MOB))
return;
final MOB mob=(MOB)affected;
super.unInvoke();
if(canBeUninvoked())
mob.tell(L("Your fish gills disappear."));
}
@Override
public void affectCharStats(MOB affected, CharStats affectableStats)
{
if(affectableStats.getBodyPart(Race.BODY_GILL)==0)
affectableStats.alterBodypart(Race.BODY_GILL,2);
super.affectCharStats(affected,affectableStats);
final int[] breatheables=affectableStats.getBreathables();
if(breatheables.length==0)
return;
if((lastSet!=breatheables)||(newSet==null))
{
newSet=Arrays.copyOf(affectableStats.getBreathables(),affectableStats.getBreathables().length+2);
newSet[newSet.length-1]=RawMaterial.RESOURCE_SALTWATER;
newSet[newSet.length-2]=RawMaterial.RESOURCE_FRESHWATER;
Arrays.sort(newSet);
lastSet=breatheables;
}
affectableStats.setBreathables(newSet);
}
@Override
public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
{
MOB target=mob;
if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB))
target=(MOB)givenTarget;
if(target.fetchEffect(this.ID())!=null)
{
mob.tell(target,null,null,L("<S-NAME> <S-IS-ARE> already a water breather."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> chant(s) to <T-NAMESELF>.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> grow(s) a pair of gills!"));
beneficialAffect(mob,target,asLevel,0);
}
}
else
beneficialWordsFizzle(mob,target,L("<S-NAME> chant(s) to <T-NAMESELF>, but nothing happens."));
return success;
}
}
| ConsecroMUD/ConsecroMUD | com/suscipio_solutions/consecro_mud/Abilities/Druid/Chant_BreatheWater.java | Java | apache-2.0 | 3,318 |
/*
* Copyright 2016 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.firebase.ui.database;
import android.util.Log;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
class FirebaseIndexArray extends FirebaseArray {
private static final String TAG = FirebaseIndexArray.class.getSimpleName();
private Query mQuery;
private Map<Query, ValueEventListener> mRefs = new HashMap<>();
private List<DataSnapshot> mDataSnapshots = new ArrayList<>();
private OnChangedListener mListener;
FirebaseIndexArray(Query keyRef, Query dataRef) {
super(keyRef);
mQuery = dataRef;
}
@Override
public void cleanup() {
super.cleanup();
Set<Query> refs = new HashSet<>(mRefs.keySet());
for (Query ref : refs) {
ref.removeEventListener(mRefs.remove(ref));
}
}
@Override
public int getCount() {
return mDataSnapshots.size();
}
@Override
public DataSnapshot getItem(int index) {
return mDataSnapshots.get(index);
}
private int getIndexForKey(String key) {
int dataCount = getCount();
int index = 0;
for (int keyIndex = 0; index < dataCount; keyIndex++) {
String superKey = super.getItem(keyIndex).getKey();
if (key.equals(superKey)) {
break;
} else if (mDataSnapshots.get(index).getKey().equals(superKey)) {
index++;
}
}
return index;
}
private boolean isMatch(int index, String key) {
return index >= 0 && index < getCount() && mDataSnapshots.get(index).getKey().equals(key);
}
@Override
public void onChildAdded(DataSnapshot keySnapshot, String previousChildKey) {
super.setOnChangedListener(null);
super.onChildAdded(keySnapshot, previousChildKey);
super.setOnChangedListener(mListener);
Query ref = mQuery.getRef().child(keySnapshot.getKey());
mRefs.put(ref, ref.addValueEventListener(new DataRefListener()));
}
@Override
public void onChildChanged(DataSnapshot snapshot, String previousChildKey) {
super.setOnChangedListener(null);
super.onChildChanged(snapshot, previousChildKey);
super.setOnChangedListener(mListener);
}
@Override
public void onChildRemoved(DataSnapshot keySnapshot) {
String key = keySnapshot.getKey();
int index = getIndexForKey(key);
mQuery.getRef().child(key).removeEventListener(mRefs.remove(mQuery.getRef().child(key)));
super.setOnChangedListener(null);
super.onChildRemoved(keySnapshot);
super.setOnChangedListener(mListener);
if (isMatch(index, key)) {
mDataSnapshots.remove(index);
notifyChangedListeners(OnChangedListener.EventType.REMOVED, index);
}
}
@Override
public void onChildMoved(DataSnapshot keySnapshot, String previousChildKey) {
String key = keySnapshot.getKey();
int oldIndex = getIndexForKey(key);
super.setOnChangedListener(null);
super.onChildMoved(keySnapshot, previousChildKey);
super.setOnChangedListener(mListener);
if (isMatch(oldIndex, key)) {
DataSnapshot snapshot = mDataSnapshots.remove(oldIndex);
int newIndex = getIndexForKey(key);
mDataSnapshots.add(newIndex, snapshot);
notifyChangedListeners(OnChangedListener.EventType.MOVED, newIndex, oldIndex);
}
}
@Override
public void onCancelled(DatabaseError error) {
Log.e(TAG, "A fatal error occurred retrieving the necessary keys to populate your adapter.");
super.onCancelled(error);
}
@Override
public void setOnChangedListener(OnChangedListener listener) {
super.setOnChangedListener(listener);
mListener = listener;
}
private class DataRefListener implements ValueEventListener {
@Override
public void onDataChange(DataSnapshot snapshot) {
String key = snapshot.getKey();
int index = getIndexForKey(key);
if (snapshot.getValue() != null) {
if (!isMatch(index, key)) {
mDataSnapshots.add(index, snapshot);
notifyChangedListeners(OnChangedListener.EventType.ADDED, index);
} else {
mDataSnapshots.set(index, snapshot);
notifyChangedListeners(OnChangedListener.EventType.CHANGED, index);
}
} else {
if (isMatch(index, key)) {
mDataSnapshots.remove(index);
notifyChangedListeners(OnChangedListener.EventType.REMOVED, index);
} else {
Log.w(TAG, "Key not found at ref: " + snapshot.getRef());
}
}
}
@Override
public void onCancelled(DatabaseError error) {
notifyCancelledListeners(error);
}
}
}
| mgumiero9/Tazo | database/src/main/java/com/firebase/ui/database/FirebaseIndexArray.java | Java | apache-2.0 | 5,856 |
/*
* 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.ecr.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.ecr.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* LimitExceededException JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class LimitExceededExceptionUnmarshaller extends EnhancedJsonErrorUnmarshaller {
private LimitExceededExceptionUnmarshaller() {
super(com.amazonaws.services.ecr.model.LimitExceededException.class, "LimitExceededException");
}
@Override
public com.amazonaws.services.ecr.model.LimitExceededException unmarshallFromContext(JsonUnmarshallerContext context) throws Exception {
com.amazonaws.services.ecr.model.LimitExceededException limitExceededException = new com.amazonaws.services.ecr.model.LimitExceededException(null);
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return limitExceededException;
}
private static LimitExceededExceptionUnmarshaller instance;
public static LimitExceededExceptionUnmarshaller getInstance() {
if (instance == null)
instance = new LimitExceededExceptionUnmarshaller();
return instance;
}
}
| aws/aws-sdk-java | aws-java-sdk-ecr/src/main/java/com/amazonaws/services/ecr/model/transform/LimitExceededExceptionUnmarshaller.java | Java | apache-2.0 | 2,804 |
/*
* 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.iot.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.iot.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* ListTargetsForPolicyRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ListTargetsForPolicyRequestProtocolMarshaller implements Marshaller<Request<ListTargetsForPolicyRequest>, ListTargetsForPolicyRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON).requestUri("/policy-targets/{policyName}")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(false).serviceName("AWSIot").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public ListTargetsForPolicyRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<ListTargetsForPolicyRequest> marshall(ListTargetsForPolicyRequest listTargetsForPolicyRequest) {
if (listTargetsForPolicyRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<ListTargetsForPolicyRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
listTargetsForPolicyRequest);
protocolMarshaller.startMarshalling();
ListTargetsForPolicyRequestMarshaller.getInstance().marshall(listTargetsForPolicyRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| aws/aws-sdk-java | aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/transform/ListTargetsForPolicyRequestProtocolMarshaller.java | Java | apache-2.0 | 2,706 |
/* 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 android.support.v7.recyclerview;
public final class R {
public static final class attr {
public static final int layoutManager = 0x7f01007e;
public static final int reverseLayout = 0x7f010080;
public static final int spanCount = 0x7f01007f;
public static final int stackFromEnd = 0x7f010081;
}
public static final class dimen {
public static final int item_touch_helper_max_drag_scroll_per_frame = 0x7f0a006a;
}
public static final class id {
public static final int item_touch_helper_previous_elevation = 0x7f0e0006;
}
public static final class styleable {
public static final int[] RecyclerView = { 0x010100c4, 0x7f01007e, 0x7f01007f, 0x7f010080, 0x7f010081 };
public static final int RecyclerView_android_orientation = 0;
public static final int RecyclerView_layoutManager = 1;
public static final int RecyclerView_reverseLayout = 3;
public static final int RecyclerView_spanCount = 2;
public static final int RecyclerView_stackFromEnd = 4;
}
}
| smarani/InfraShareMobile | InfraShare Mobile/app/build/generated/source/r/debug/android/support/v7/recyclerview/R.java | Java | apache-2.0 | 1,170 |
/*
* 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.geode.management.internal;
import java.net.UnknownHostException;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.Logger;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.apache.geode.cache.AttributesFactory;
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.cache.DataPolicy;
import org.apache.geode.cache.RegionAttributes;
import org.apache.geode.cache.Scope;
import org.apache.geode.distributed.internal.DistributionConfig;
import org.apache.geode.internal.GemFireVersion;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.net.SSLConfigurationFactory;
import org.apache.geode.internal.net.SocketCreator;
import org.apache.geode.internal.cache.InternalRegionArguments;
import org.apache.geode.internal.logging.LogService;
import org.apache.geode.internal.security.SecurableCommunicationChannel;
import org.apache.geode.management.ManagementService;
/**
* Agent implementation that controls the HTTP server end points used for REST clients to connect
* gemfire data node.
* <p>
* The RestAgent is used to start http service in embedded mode on any non manager data node with
* developer REST APIs service enabled.
*
* @since GemFire 8.0
*/
public class RestAgent {
private static final Logger logger = LogService.getLogger();
private boolean running = false;
private final DistributionConfig config;
public RestAgent(DistributionConfig config) {
this.config = config;
}
public synchronized boolean isRunning() {
return this.running;
}
private boolean isManagementRestServiceRunning(InternalCache cache) {
final SystemManagementService managementService =
(SystemManagementService) ManagementService.getManagementService(cache);
return (managementService.getManagementAgent() != null
&& managementService.getManagementAgent().isHttpServiceRunning());
}
public synchronized void start(InternalCache cache) {
if (!this.running && this.config.getHttpServicePort() != 0
&& !isManagementRestServiceRunning(cache)) {
try {
startHttpService();
this.running = true;
cache.setRESTServiceRunning(true);
// create region to hold query information (queryId, queryString). Added
// for the developer REST APIs
RestAgent.createParameterizedQueryRegion();
} catch (RuntimeException e) {
logger.debug(e.getMessage(), e);
}
}
}
public synchronized void stop() {
if (this.running) {
stopHttpService();
if (logger.isDebugEnabled()) {
logger.debug("Gemfire Rest Http service stopped");
}
this.running = false;
} else {
if (logger.isDebugEnabled()) {
logger.debug("Attempt to stop Gemfire Rest Http service which is not running");
}
}
}
private Server httpServer;
private final String GEMFIRE_VERSION = GemFireVersion.getGemFireVersion();
private AgentUtil agentUtil = new AgentUtil(GEMFIRE_VERSION);
private boolean isRunningInTomcat() {
return (System.getProperty("catalina.base") != null
|| System.getProperty("catalina.home") != null);
}
// Start HTTP service in embedded mode
public void startHttpService() {
// TODO: add a check that will make sure that we start HTTP service on
// non-manager data node
String httpServiceBindAddress = getBindAddressForHttpService(this.config);
logger.info("Attempting to start HTTP service on port ({}) at bind-address ({})...",
this.config.getHttpServicePort(), httpServiceBindAddress);
// Find the developer REST WAR file
final String gemfireAPIWar = agentUtil.findWarLocation("geode-web-api");
if (gemfireAPIWar == null) {
logger.info(
"Unable to find GemFire Developer REST API WAR file; the Developer REST Interface for GemFire will not be accessible.");
}
try {
// Check if we're already running inside Tomcat
if (isRunningInTomcat()) {
logger.warn(
"Detected presence of catalina system properties. HTTP service will not be started. To enable the GemFire Developer REST API, please deploy the /geode-web-api WAR file in your application server.");
} else if (agentUtil.isWebApplicationAvailable(gemfireAPIWar)) {
final int port = this.config.getHttpServicePort();
this.httpServer = JettyHelper.initJetty(httpServiceBindAddress, port,
SSLConfigurationFactory.getSSLConfigForComponent(SecurableCommunicationChannel.WEB));
this.httpServer = JettyHelper.addWebApplication(httpServer, "/gemfire-api", gemfireAPIWar);
this.httpServer = JettyHelper.addWebApplication(httpServer, "/geode", gemfireAPIWar);
if (logger.isDebugEnabled()) {
logger.debug("Starting HTTP embedded server on port ({}) at bind-address ({})...",
((ServerConnector) this.httpServer.getConnectors()[0]).getPort(),
httpServiceBindAddress);
}
this.httpServer = JettyHelper.startJetty(this.httpServer);
logger.info("HTTP service started successfully...!!");
}
} catch (Exception e) {
stopHttpService();// Jetty needs to be stopped even if it has failed to
// start. Some of the threads are left behind even if
// server.start() fails due to an exception
throw new RuntimeException("HTTP service failed to start due to " + e.getMessage());
}
}
public static String getBindAddressForHttpService(DistributionConfig config) {
String bindAddress = config.getHttpServiceBindAddress();
if (!StringUtils.isBlank(bindAddress))
return bindAddress;
bindAddress = config.getServerBindAddress();
if (!StringUtils.isBlank(bindAddress))
return bindAddress;
bindAddress = config.getBindAddress();
if (!StringUtils.isBlank(bindAddress))
return bindAddress;
try {
bindAddress = SocketCreator.getLocalHost().getHostAddress();
logger.info("RestAgent.getBindAddressForHttpService.localhost: "
+ SocketCreator.getLocalHost().getHostAddress());
} catch (UnknownHostException e) {
logger.error("LocalHost could not be found.", e);
}
return bindAddress;
}
private void stopHttpService() {
if (this.httpServer != null) {
logger.info("Stopping the HTTP service...");
try {
this.httpServer.stop();
} catch (Exception e) {
logger.warn("Failed to stop the HTTP service because: {}", e.getMessage(), e);
} finally {
try {
this.httpServer.destroy();
} catch (Exception ignore) {
logger.error("Failed to properly release resources held by the HTTP service: {}",
ignore.getMessage(), ignore);
} finally {
this.httpServer = null;
System.clearProperty("catalina.base");
System.clearProperty("catalina.home");
}
}
}
}
/**
* This method will create a REPLICATED region named _ParameterizedQueries__. In developer REST
* APIs, this region will be used to store the queryId and queryString as a key and value
* respectively.
*/
public static void createParameterizedQueryRegion() {
try {
if (logger.isDebugEnabled()) {
logger.debug("Starting creation of __ParameterizedQueries__ region");
}
InternalCache cache = (InternalCache) CacheFactory.getAnyInstance();
if (cache != null) {
final InternalRegionArguments regionArguments = new InternalRegionArguments();
regionArguments.setIsUsedForMetaRegion(true);
final AttributesFactory<String, String> attributesFactory =
new AttributesFactory<String, String>();
attributesFactory.setConcurrencyChecksEnabled(false);
attributesFactory.setDataPolicy(DataPolicy.REPLICATE);
attributesFactory.setKeyConstraint(String.class);
attributesFactory.setScope(Scope.DISTRIBUTED_ACK);
attributesFactory.setStatisticsEnabled(false);
attributesFactory.setValueConstraint(String.class);
final RegionAttributes<String, String> regionAttributes = attributesFactory.create();
cache.createVMRegion("__ParameterizedQueries__", regionAttributes, regionArguments);
if (logger.isDebugEnabled()) {
logger.debug("Successfully created __ParameterizedQueries__ region");
}
} else {
logger.error("Cannot create ParameterizedQueries Region as no cache found!");
}
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("Error creating __ParameterizedQueries__ Region with cause {}", e.getMessage(),
e);
}
}
}
}
| prasi-in/geode | geode-core/src/main/java/org/apache/geode/management/internal/RestAgent.java | Java | apache-2.0 | 9,579 |
package ru.pavlenov.bio.chapter.rosalind.alignment;
import com.google.common.base.Joiner;
import net.sf.jfasta.impl.FASTAElementIterator;
import net.sf.jfasta.impl.FASTAFileReaderImpl;
import ru.pavlenov.bio.genome.DNA;
import ru.pavlenov.bio.utils.Dump;
import ru.pavlenov.bio.utils.File;
import java.io.IOException;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* ⓭
* Какой сам? by Pavlenov Semen 29.06.14.
*
* Finding a Spliced Motif
* http://rosalind.info/problems/sseq/
*
* Given: Two DNA strings s and t (each of length at most 1 kbp) in FASTA format.
* Return: One collection of indices of s in which the symbols of t appear as a subsequence of s.
* If multiple solutions exist, you may return any one.
*/
public class Sseq {
public static void start() throws IOException {
String data = File.readFile("/home/laser13/IdeaProjects/bio/src/ru/pavlenov/bio/chapter/rosalind/alignment/Sseq.data", Charset.defaultCharset());
FASTAFileReaderImpl fasta = new FASTAFileReaderImpl(new StringReader(data));
FASTAElementIterator it = fasta.getIterator();
String text = it.next().getSequence();
String kmer = it.next().getSequence();
List<Integer> indices = new ArrayList<>();
int i = 0, j = 0;
while (i < text.length() && j < kmer.length()) {
if (text.charAt(i) == kmer.charAt(j)) {
indices.add(i + 1);
j += 1;
}
i += 1;
}
Dump.println(Joiner.on(" ").join(indices));
}
} | laser13/rosalind | src/java/ru/pavlenov/bio/chapter/rosalind/alignment/Sseq.java | Java | apache-2.0 | 1,624 |
/**
* 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.
*
* Copyright 2012-2016 the original author or authors.
*/
package org.assertj.core.internal.floats;
import static org.assertj.core.test.TestData.someInfo;
import org.assertj.core.api.AssertionInfo;
import org.assertj.core.internal.Floats;
import org.assertj.core.internal.FloatsBaseTest;
import org.junit.Test;
/**
* Tests for <code>{@link Floats#assertIsNegative(AssertionInfo, Float)}</code>.
*
* @author Alex Ruiz
* @author Joel Costigliola
*/
public class Floats_assertIsNegative_Test extends FloatsBaseTest {
@Test
public void should_succeed_since_actual_is_negative() {
floats.assertIsNegative(someInfo(), (float) -6);
}
@Test
public void should_fail_since_actual_is_not_negative() {
thrown.expectAssertionError("%nExpecting:%n <6.0f>%nto be less than:%n <0.0f>");
floats.assertIsNegative(someInfo(), 6.0f);
}
@Test
public void should_fail_since_actual_is_not_negative_according_to_absolute_value_comparison_strategy() {
thrown.expectAssertionError("%nExpecting:%n <-6.0f>%nto be less than:%n <0.0f> when comparing values using 'AbsValueComparator'");
floatsWithAbsValueComparisonStrategy.assertIsNegative(someInfo(), (float) -6);
}
@Test
public void should_fail_since_actual_is_not_negative_according_to_absolute_value_comparison_strategy2() {
thrown.expectAssertionError("%nExpecting:%n <6.0f>%nto be less than:%n <0.0f>");
floatsWithAbsValueComparisonStrategy.assertIsNegative(someInfo(), 6.0f);
}
}
| dorzey/assertj-core | src/test/java/org/assertj/core/internal/floats/Floats_assertIsNegative_Test.java | Java | apache-2.0 | 2,026 |
package org.wso2.carbon.pc.core.assets;
import org.apache.axis2.AxisFault;
import org.apache.axis2.jaxws.util.SoapUtils;
import org.apache.taglibs.standard.tag.el.sql.SetDataSourceTag;
import org.wso2.carbon.authenticator.stub.LoginAuthenticationExceptionException;
import org.wso2.carbon.bpmn.core.mgt.model.xsd.BPMNInstance;
import org.wso2.carbon.bpmn.core.mgt.model.xsd.BPMNVariable;
import org.wso2.carbon.bpmn.stub.BPMNDeploymentServiceBPSFaultException;
import org.wso2.carbon.bpmn.stub.BPMNInstanceServiceBPSFaultException;
import org.wso2.carbon.pc.core.ProcessCenter;
import org.wso2.carbon.pc.core.ProcessCenterConstants;
import org.wso2.carbon.pc.core.ProcessCenterException;
import org.wso2.carbon.pc.core.clients.LoginAdminServiceClient;
import org.wso2.carbon.pc.core.clients.WorkflowServiceClient;
import org.wso2.carbon.pc.core.config.ProcessCenterConfiguration;
import org.wso2.carbon.pc.core.runtime.ProcessServer;
import org.wso2.carbon.pc.core.runtime.ProcessServerImpl;
import java.io.File;
import java.net.MalformedURLException;
import java.rmi.RemoteException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.utils.CarbonUtils;
/**
* Created by dimuth on 8/23/16.
*/
public class Instance {
BPMNInstance[] instances;
BPMNInstance inst =new BPMNInstance();
LoginAdminServiceClient loginServiceClient;
String username;
String password;
String url;
public Instance(String usr, String psw, String url) throws ProcessCenterException {
this.url = url;
this.username = usr;
this.password = psw;
try {
loginServiceClient = new LoginAdminServiceClient(this.url);
} catch (AxisFault axisFault) {
throw new ProcessCenterException("Error while creating Login admin service client ", axisFault);
}
}
public BPMNInstance[] getInstanceList() throws ProcessCenterException {
try {
WorkflowServiceClient workflowServiceClient = new WorkflowServiceClient(loginServiceClient.authenticate
(this.username, this.password.toCharArray()), this.url, null);
instances = workflowServiceClient.getInstanceList();
return instances;
} catch (LoginAuthenticationExceptionException e) {
throw new ProcessCenterException("Authentication error while undeploying bpmn package to BPS server ", e);
} catch (MalformedURLException e) {
throw new ProcessCenterException("Error occurred while passing server Url ", e);
} catch (RemoteException e) {
throw new ProcessCenterException("Error occurred undeploying bpmn package to BPS server ", e);
} catch (BPMNInstanceServiceBPSFaultException e) {
e.printStackTrace();
}
return null;
}
}
| dimuthnc/product-pc | modules/components/core/org.wso2.carbon.pc.core/src/main/java/org/wso2/carbon/pc/core/assets/Instance.java | Java | apache-2.0 | 2,879 |
/**
* Licensed to the Rhiot under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The 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 io.rhiot.component.deviceio.i2c;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.impl.ScheduledPollConsumer;
import jdk.dio.ClosedDeviceException;
import jdk.dio.DeviceDescriptor;
import jdk.dio.UnavailableDeviceException;
import jdk.dio.i2cbus.I2CDevice;
/**
* The I2C consumer.
*/
public abstract class I2CConsumer extends ScheduledPollConsumer implements I2CDevice {
private final I2CDevice device;
public I2CConsumer(I2CEndpoint endpoint, Processor processor, I2CDevice device) {
super(endpoint, processor);
this.device = device;
}
public abstract void createBody(Exchange exchange) throws IOException;
public I2CDevice getDevice() {
return device;
}
@Override
protected int poll() throws Exception {
Exchange exchange = getEndpoint().createExchange();
try {
createBody(exchange);
getProcessor().process(exchange);
return 1; // number of messages polled
} finally {
// log exception if an exception occurred and was not handled
if (exchange.getException() != null) {
getExceptionHandler().handleException("Error processing exchange", exchange, exchange.getException());
}
}
}
@Override
public int read() throws IOException {
return this.device.read();
}
public void sleep(long howMuch) {
try {
Thread.sleep(howMuch);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
@Override
public I2CEndpoint getEndpoint() {
return (I2CEndpoint) super.getEndpoint();
}
@Override
public void close() throws IOException {
this.device.close();
}
@Override
public <U extends I2CDevice> DeviceDescriptor<U> getDescriptor() {
return this.device.getDescriptor();
}
@Override
public boolean isOpen() {
return this.device.isOpen();
}
@Override
public void tryLock(int arg0) throws UnavailableDeviceException, ClosedDeviceException, IOException {
this.device.tryLock(arg0);
}
@Override
public void unlock() throws IOException {
this.device.unlock();
}
@Override
public ByteBuffer getInputBuffer() throws ClosedDeviceException, IOException {
return this.device.getInputBuffer();
}
@Override
public ByteBuffer getOutputBuffer() throws ClosedDeviceException, IOException {
return this.device.getOutputBuffer();
}
@Override
public void begin() throws IOException, UnavailableDeviceException, ClosedDeviceException {
this.device.begin();
}
@Override
public void end() throws IOException, UnavailableDeviceException, ClosedDeviceException {
this.device.end();
}
@Override
public Bus getBus() throws IOException {
return this.device.getBus();
}
@Override
public int read(ByteBuffer arg0) throws IOException, UnavailableDeviceException, ClosedDeviceException {
return this.device.read(arg0);
}
@Override
public int read(int arg0, ByteBuffer arg1) throws IOException, UnavailableDeviceException, ClosedDeviceException {
return this.device.read(arg0, arg1);
}
@Override
public int read(int arg0, int arg1, ByteBuffer arg2)
throws IOException, UnavailableDeviceException, ClosedDeviceException {
return this.device.read(arg0, arg1, arg2);
}
@Override
public int read(int arg0, int arg1, int arg2, ByteBuffer arg3)
throws IOException, UnavailableDeviceException, ClosedDeviceException {
return this.device.read(arg0, arg1, arg2, arg3);
}
@Override
public int write(ByteBuffer arg0) throws IOException, UnavailableDeviceException, ClosedDeviceException {
return this.device.write(arg0);
}
@Override
public void write(int arg0) throws IOException, UnavailableDeviceException, ClosedDeviceException {
this.device.write(arg0);
}
@Override
public int write(int arg0, int arg1, ByteBuffer arg2)
throws IOException, UnavailableDeviceException, ClosedDeviceException {
return this.device.write(arg0, arg1, arg2);
}
}
| finiteloopme/rhiot | datastream/components/camel-device-io/src/main/java/io/rhiot/component/deviceio/i2c/I2CConsumer.java | Java | apache-2.0 | 5,154 |
/**
* 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.hadoop.yarn.logaggregation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.service.AbstractService;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
/**
* A service that periodically deletes aggregated logs.
*/
@Private
public class AggregatedLogDeletionService extends AbstractService {
private static final Log LOG =
LogFactory.getLog(AggregatedLogDeletionService.class);
private Timer timer = null;
private long checkIntervalMsecs;
static class LogDeletionTask extends TimerTask {
private Configuration conf;
private long retentionMillis;
private String suffix = null;
private Path remoteRootLogDir = null;
public LogDeletionTask(Configuration conf, long retentionSecs) {
this.conf = conf;
this.retentionMillis = retentionSecs * 1000;
this.suffix = LogAggregationUtils.getRemoteNodeLogDirSuffix(conf);
this.remoteRootLogDir = new Path(
conf.get(YarnConfiguration.NM_REMOTE_APP_LOG_DIR,
YarnConfiguration.DEFAULT_NM_REMOTE_APP_LOG_DIR));
}
@Override
public void run() {
long cutoffMillis = System.currentTimeMillis() - retentionMillis;
LOG.info("aggregated log deletion started.");
try {
FileSystem fs = remoteRootLogDir.getFileSystem(conf);
for (FileStatus userDir : fs.listStatus(remoteRootLogDir)) {
if (userDir.isDirectory()) {
Path userDirPath = new Path(userDir.getPath(), suffix);
deleteOldLogDirsFrom(userDirPath, cutoffMillis, fs);
}
}
} catch (IOException e) {
logIOException("Error reading root log dir this deletion " +
"attempt is being aborted", e);
}
LOG.info("aggregated log deletion finished.");
}
private static void deleteOldLogDirsFrom(Path dir, long cutoffMillis,
FileSystem fs) {
try {
for (FileStatus appDir : fs.listStatus(dir)) {
if (appDir.isDirectory() &&
appDir.getModificationTime() < cutoffMillis) {
if (shouldDeleteLogDir(appDir, cutoffMillis, fs)) {
try {
LOG.info("Deleting aggregated logs in " + appDir.getPath());
fs.delete(appDir.getPath(), true);
} catch (IOException e) {
logIOException("Could not delete " + appDir.getPath(), e);
}
}
}
}
} catch (IOException e) {
logIOException("Could not read the contents of " + dir, e);
}
}
private static boolean shouldDeleteLogDir(FileStatus dir, long cutoffMillis,
FileSystem fs) {
boolean shouldDelete = true;
try {
for (FileStatus node : fs.listStatus(dir.getPath())) {
if (node.getModificationTime() >= cutoffMillis) {
shouldDelete = false;
break;
}
}
} catch (IOException e) {
logIOException("Error reading the contents of " + dir.getPath(), e);
shouldDelete = false;
}
return shouldDelete;
}
}
private static void logIOException(String comment, IOException e) {
if (e instanceof AccessControlException) {
String message = e.getMessage();
//TODO fix this after HADOOP-8661
message = message.split("\n")[0];
LOG.warn(comment + " " + message);
} else {
LOG.error(comment, e);
}
}
public AggregatedLogDeletionService() {
super(AggregatedLogDeletionService.class.getName());
}
@Override
protected void serviceStart() throws Exception {
scheduleLogDeletionTask();
super.serviceStart();
}
@Override
protected void serviceStop() throws Exception {
stopTimer();
super.serviceStop();
}
private void setLogAggCheckIntervalMsecs(long retentionSecs) {
Configuration conf = getConfig();
checkIntervalMsecs = 1000 * conf.getLong(
YarnConfiguration.LOG_AGGREGATION_RETAIN_CHECK_INTERVAL_SECONDS,
YarnConfiguration.DEFAULT_LOG_AGGREGATION_RETAIN_CHECK_INTERVAL_SECONDS);
if (checkIntervalMsecs <= 0) {
// when unspecified compute check interval as 1/10th of retention
checkIntervalMsecs = (retentionSecs * 1000) / 10;
}
}
public void refreshLogRetentionSettings() {
if (getServiceState() == STATE.STARTED) {
Configuration conf = createConf();
setConfig(conf);
stopTimer();
scheduleLogDeletionTask();
} else {
LOG.warn(
"Failed to execute refreshLogRetentionSettings : Aggregated Log Deletion Service is not started");
}
}
private void scheduleLogDeletionTask() {
Configuration conf = getConfig();
if (!conf.getBoolean(YarnConfiguration.LOG_AGGREGATION_ENABLED,
YarnConfiguration.DEFAULT_LOG_AGGREGATION_ENABLED)) {
// Log aggregation is not enabled so don't bother
return;
}
long retentionSecs =
conf.getLong(YarnConfiguration.LOG_AGGREGATION_RETAIN_SECONDS,
YarnConfiguration.DEFAULT_LOG_AGGREGATION_RETAIN_SECONDS);
if (retentionSecs < 0) {
LOG.info("Log Aggregation deletion is disabled because retention is" +
" too small (" + retentionSecs + ")");
return;
}
setLogAggCheckIntervalMsecs(retentionSecs);
TimerTask task = new LogDeletionTask(conf, retentionSecs);
timer = new Timer();
timer.scheduleAtFixedRate(task, 0, checkIntervalMsecs);
}
private void stopTimer() {
if (timer != null) {
timer.cancel();
}
}
public long getCheckIntervalMsecs() {
return checkIntervalMsecs;
}
protected Configuration createConf() {
return new Configuration();
}
}
| srijeyanthan/hops | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogDeletionService.java | Java | apache-2.0 | 6,907 |
package com.massive.deliveries.test.di;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Qualifier;
/**
* Creaated by Balwinder on 26/08/17.
*/
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface ActivityContext {
}
| balwinderSingh1989/MassiveTest | app/src/main/java/com/massive/deliveries/test/di/ActivityContext.java | Java | apache-2.0 | 295 |
// Copyright 2016 The Bazel Authors. 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.devtools.build.lib.rules.objc;
import static com.google.devtools.build.lib.rules.objc.ObjcProvider.MULTI_ARCH_DYNAMIC_LIBRARIES;
import static com.google.devtools.build.lib.rules.objc.ObjcRuleClasses.DylibDependingRule.DYLIBS_ATTR_NAME;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode;
import com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.rules.RuleConfiguredTargetFactory;
import com.google.devtools.build.lib.rules.apple.AppleConfiguration;
import com.google.devtools.build.lib.rules.apple.Platform;
import com.google.devtools.build.lib.rules.apple.Platform.PlatformType;
import com.google.devtools.build.lib.rules.cpp.CcToolchainProvider;
import com.google.devtools.build.lib.rules.objc.CompilationSupport.ExtraLinkArgs;
import java.util.Map;
import java.util.Set;
/**
* Implementation for the "apple_dynamic_library" rule.
*/
public class AppleDynamicLibrary implements RuleConfiguredTargetFactory {
@Override
public final ConfiguredTarget create(RuleContext ruleContext)
throws InterruptedException, RuleErrorException {
PlatformType platformType = MultiArchSplitTransitionProvider.getPlatformType(ruleContext);
AppleConfiguration appleConfiguration = ruleContext.getFragment(AppleConfiguration.class);
Platform platform = appleConfiguration.getMultiArchPlatform(platformType);
ImmutableListMultimap<BuildConfiguration, ObjcProvider> configurationToNonPropagatedObjcMap =
ruleContext.getPrerequisitesByConfiguration("non_propagated_deps", Mode.SPLIT,
ObjcProvider.class);
ImmutableListMultimap<BuildConfiguration, TransitiveInfoCollection> configToDepsCollectionMap =
ruleContext.getPrerequisitesByConfiguration("deps", Mode.SPLIT);
Iterable<ObjcProvider> dylibProviders =
ruleContext.getPrerequisites(DYLIBS_ATTR_NAME, Mode.TARGET, ObjcProvider.class);
Set<BuildConfiguration> childConfigurations = getChildConfigurations(ruleContext);
Artifact outputArtifact =
ObjcRuleClasses.intermediateArtifacts(ruleContext).combinedArchitectureDylib();
MultiArchBinarySupport multiArchBinarySupport = new MultiArchBinarySupport(ruleContext);
Map<BuildConfiguration, ObjcCommon> objcCommonByDepConfiguration =
multiArchBinarySupport.objcCommonByDepConfiguration(childConfigurations,
configToDepsCollectionMap, configurationToNonPropagatedObjcMap, dylibProviders);
multiArchBinarySupport.registerActions(
platform,
new ExtraLinkArgs("-dynamiclib"),
ImmutableSet.<Artifact>of(),
objcCommonByDepConfiguration,
configToDepsCollectionMap,
outputArtifact);
NestedSetBuilder<Artifact> filesToBuild =
NestedSetBuilder.<Artifact>stableOrder()
.add(outputArtifact);
RuleConfiguredTargetBuilder targetBuilder =
ObjcRuleClasses.ruleConfiguredTarget(ruleContext, filesToBuild.build());
ObjcProvider.Builder objcProviderBuilder = new ObjcProvider.Builder();
for (ObjcCommon objcCommon : objcCommonByDepConfiguration.values()) {
objcProviderBuilder.addTransitiveAndPropagate(objcCommon.getObjcProvider());
}
objcProviderBuilder.add(MULTI_ARCH_DYNAMIC_LIBRARIES, outputArtifact);
targetBuilder.addProvider(ObjcProvider.class, objcProviderBuilder.build());
return targetBuilder.build();
}
private Set<BuildConfiguration> getChildConfigurations(RuleContext ruleContext) {
// This is currently a hack to obtain all child configurations regardless of the attribute
// values of this rule -- this rule does not currently use the actual info provided by
// this attribute. b/28403953 tracks cc toolchain usage.
ImmutableListMultimap<BuildConfiguration, CcToolchainProvider> configToProvider =
ruleContext.getPrerequisitesByConfiguration(":cc_toolchain", Mode.SPLIT,
CcToolchainProvider.class);
return configToProvider.keySet();
}
}
| zhexuany/bazel | src/main/java/com/google/devtools/build/lib/rules/objc/AppleDynamicLibrary.java | Java | apache-2.0 | 5,112 |
/* 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.flowable.rest.api.runtime;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.flowable.engine.task.Task;
import org.flowable.rest.service.BaseSpringRestTestCase;
import org.flowable.rest.service.api.RestUrls;
import com.fasterxml.jackson.databind.JsonNode;
/**
* Test for all REST-operations related to sub tasks.
*
* @author Tijs Rademakers
*/
public class TaskSubTaskCollectionResourceTest extends BaseSpringRestTestCase {
/**
* Test getting all sub tasks. GET runtime/tasks/{taskId}/subtasks
*/
public void testGetSubTasks() throws Exception {
Task parentTask = taskService.newTask();
parentTask.setName("parent task");
taskService.saveTask(parentTask);
Task subTask = taskService.newTask();
subTask.setName("sub task 1");
subTask.setParentTaskId(parentTask.getId());
taskService.saveTask(subTask);
Task subTask2 = taskService.newTask();
subTask2.setName("sub task 2");
subTask2.setParentTaskId(parentTask.getId());
taskService.saveTask(subTask2);
// Request all sub tasks
CloseableHttpResponse response = executeRequest(new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_SUBTASKS_COLLECTION, parentTask.getId())), HttpStatus.SC_OK);
JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
closeResponse(response);
assertNotNull(responseNode);
assertTrue(responseNode.isArray());
assertEquals(2, responseNode.size());
boolean foundSubtask1 = false;
boolean foundSubtask2 = false;
for (int i = 0; i < responseNode.size(); i++) {
JsonNode var = responseNode.get(i);
if ("sub task 1".equals(var.get("name").asText())) {
foundSubtask1 = true;
assertEquals(subTask.getId(), var.get("id").asText());
} else if ("sub task 2".equals(var.get("name").asText())) {
foundSubtask2 = true;
assertEquals(subTask2.getId(), var.get("id").asText());
}
}
assertTrue(foundSubtask1);
assertTrue(foundSubtask2);
taskService.deleteTask(parentTask.getId());
taskService.deleteTask(subTask.getId());
taskService.deleteTask(subTask2.getId());
historyService.deleteHistoricTaskInstance(parentTask.getId());
historyService.deleteHistoricTaskInstance(subTask.getId());
historyService.deleteHistoricTaskInstance(subTask2.getId());
}
}
| motorina0/flowable-engine | modules/flowable-rest/src/test/java/org/flowable/rest/api/runtime/TaskSubTaskCollectionResourceTest.java | Java | apache-2.0 | 3,050 |
/*
* Copyright 2015 Tyler Davis
*
* 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.github.davityle.ngprocessor.util;
import com.github.davityle.ngprocessor.model.Model;
import com.github.davityle.ngprocessor.model.Scope;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
import javax.annotation.processing.RoundEnvironment;
import javax.inject.Inject;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
public class ScopeUtils {
public static final String NG_SCOPE_ANNOTATION = "com.ngandroid.lib.annotations.NgScope";
public static final String NG_MODEL_ANNOTATION = "com.ngandroid.lib.annotations.NgModel";
public static final String SCOPE_APPENDAGE = "$$NgScope";
private final ElementUtils elementUtils;
private final RoundEnvironment roundEnv;
private final MessageUtils messageUtils;
private final CollectionUtils collectionUtils;
@Inject
public ScopeUtils(ElementUtils elementUtils, RoundEnvironment roundEnv, MessageUtils messageUtils, CollectionUtils collectionUtils){
this.elementUtils = elementUtils;
this.roundEnv = roundEnv;
this.messageUtils = messageUtils;
this.collectionUtils = collectionUtils;
}
public Set<Scope> getScopes(Set<? extends TypeElement> annotations){
Collection<TypeElement> annotatedScopes = collectionUtils.filter(new ArrayList<>(annotations), new CollectionUtils.Function<TypeElement, Boolean>() {
@Override
public Boolean apply(TypeElement annotation) {
return NG_SCOPE_ANNOTATION.equals(annotation.getQualifiedName().toString());
}
});
final Collection<Element> ngModels = getModels(annotations);
ngModels.forEach(new Consumer<Element>() {
@Override
public void accept(Element element) {
if (!elementUtils.isAccessible(element)) {
messageUtils.error(Option.of(element), "Unable to access field '%s' from scope '%s'. Must have default or public access", element.toString(), element.getEnclosingElement().toString());
}
}
});
Collection<Scope> scopes = collectionUtils.flatMap(annotatedScopes, new CollectionUtils.Function<TypeElement, Collection<Scope>>() {
@Override
public Collection<Scope> apply(TypeElement annotation) {
Collection<Element> javaScopes = new ArrayList<>(roundEnv.getElementsAnnotatedWith(annotation));
return collectionUtils.map(javaScopes, new CollectionUtils.Function<Element, Scope>() {
@Override
public Scope apply(final Element scope) {
Set<Modifier> modifiers = scope.getModifiers();
if (modifiers.contains(Modifier.PRIVATE) || modifiers.contains(Modifier.PROTECTED)) {
messageUtils.error(Option.of(scope), "Unable to access Scope '%s'. Must have default or public access", scope.toString());
}
return new Scope(scope, getModelsForScope(ngModels, scope), getScopeName(scope), elementUtils.getTypeName(scope), elementUtils.getSimpleName(scope));
}
});
}
});
return new HashSet<>(scopes);
}
public Collection<Element> getModels(Set<? extends TypeElement> annotations) {
return collectionUtils.flatMap(collectionUtils.filter(new ArrayList<>(annotations), new CollectionUtils.Function<TypeElement, Boolean>() {
@Override
public Boolean apply(TypeElement annotation) {
return NG_MODEL_ANNOTATION.equals(annotation.getQualifiedName().toString());
}
}), new CollectionUtils.Function<TypeElement, Collection<Element>>() {
@Override
public Collection<Element> apply(TypeElement annotation) {
return new ArrayList<>(roundEnv.getElementsAnnotatedWith(annotation));
}
});
}
private Collection<Model> getModelsForScope(final Collection<Element> ngModels, final Element scope) {
return collectionUtils.map(collectionUtils.filter(ngModels, new CollectionUtils.Function<Element, Boolean>() {
@Override
public Boolean apply(Element element) {
return element.getEnclosingElement().equals(scope);
}
}), new CollectionUtils.Function<Element, Model>() {
@Override
public Model apply(Element element) {
return new Model(element.getSimpleName().toString(), elementUtils.getTypeName(element));
}
});
}
private String getScopeName(final Element scope) {
return elementUtils.getAnnotationValue(scope, ScopeUtils.NG_SCOPE_ANNOTATION, "name", String.class).fold(new Option.OptionCB<String, String>() {
@Override
public String absent() {
messageUtils.error(Option.of(scope), "Scope must have a name.");
return "";
}
@Override
public String present(String s) {
return s;
}
});
}
}
| davityle/ngAndroid | ng-processor/src/main/java/com/github/davityle/ngprocessor/util/ScopeUtils.java | Java | apache-2.0 | 5,919 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.nested;
import com.carrotsearch.randomizedtesting.annotations.Seed;
import org.apache.lucene.search.Explanation;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus;
import org.elasticsearch.action.admin.cluster.stats.ClusterStatsResponse;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchPhaseExecutionException;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.test.ElasticsearchIntegrationTest;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.FilterBuilders.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*;
import static org.hamcrest.Matchers.*;
public class SimpleNestedTests extends ElasticsearchIntegrationTest {
@Test
public void simpleNested() throws Exception {
assertAcked(prepareCreate("test").addMapping("type1", "nested1", "type=nested").addMapping("type2", "nested1", "type=nested"));
ensureGreen();
// check on no data, see it works
SearchResponse searchResponse = client().prepareSearch("test").setQuery(termQuery("_all", "n_value1_1")).execute().actionGet();
assertThat(searchResponse.getHits().totalHits(), equalTo(0l));
searchResponse = client().prepareSearch("test").setQuery(termQuery("n_field1", "n_value1_1")).execute().actionGet();
assertThat(searchResponse.getHits().totalHits(), equalTo(0l));
client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject()
.field("field1", "value1")
.startArray("nested1")
.startObject()
.field("n_field1", "n_value1_1")
.field("n_field2", "n_value2_1")
.endObject()
.startObject()
.field("n_field1", "n_value1_2")
.field("n_field2", "n_value2_2")
.endObject()
.endArray()
.endObject()).execute().actionGet();
waitForRelocation(ClusterHealthStatus.GREEN);
// flush, so we fetch it from the index (as see that we filter nested docs)
flush();
GetResponse getResponse = client().prepareGet("test", "type1", "1").get();
assertThat(getResponse.isExists(), equalTo(true));
assertThat(getResponse.getSourceAsBytes(), notNullValue());
// check the numDocs
assertDocumentCount("test", 3);
// check that _all is working on nested docs
searchResponse = client().prepareSearch("test").setQuery(termQuery("_all", "n_value1_1")).execute().actionGet();
assertThat(searchResponse.getHits().totalHits(), equalTo(1l));
searchResponse = client().prepareSearch("test").setQuery(termQuery("n_field1", "n_value1_1")).execute().actionGet();
assertThat(searchResponse.getHits().totalHits(), equalTo(0l));
// search for something that matches the nested doc, and see that we don't find the nested doc
searchResponse = client().prepareSearch("test").setQuery(matchAllQuery()).get();
assertThat(searchResponse.getHits().totalHits(), equalTo(1l));
searchResponse = client().prepareSearch("test").setQuery(termQuery("n_field1", "n_value1_1")).get();
assertThat(searchResponse.getHits().totalHits(), equalTo(0l));
// now, do a nested query
searchResponse = client().prepareSearch("test").setQuery(nestedQuery("nested1", termQuery("nested1.n_field1", "n_value1_1"))).get();
assertNoFailures(searchResponse);
assertThat(searchResponse.getHits().totalHits(), equalTo(1l));
searchResponse = client().prepareSearch("test").setQuery(nestedQuery("nested1", termQuery("nested1.n_field1", "n_value1_1"))).setSearchType(SearchType.DFS_QUERY_THEN_FETCH).get();
assertNoFailures(searchResponse);
assertThat(searchResponse.getHits().totalHits(), equalTo(1l));
// add another doc, one that would match if it was not nested...
client().prepareIndex("test", "type1", "2").setSource(jsonBuilder().startObject()
.field("field1", "value1")
.startArray("nested1")
.startObject()
.field("n_field1", "n_value1_1")
.field("n_field2", "n_value2_2")
.endObject()
.startObject()
.field("n_field1", "n_value1_2")
.field("n_field2", "n_value2_1")
.endObject()
.endArray()
.endObject()).execute().actionGet();
waitForRelocation(ClusterHealthStatus.GREEN);
// flush, so we fetch it from the index (as see that we filter nested docs)
flush();
assertDocumentCount("test", 6);
searchResponse = client().prepareSearch("test").setQuery(nestedQuery("nested1",
boolQuery().must(termQuery("nested1.n_field1", "n_value1_1")).must(termQuery("nested1.n_field2", "n_value2_1")))).execute().actionGet();
assertNoFailures(searchResponse);
assertThat(searchResponse.getHits().totalHits(), equalTo(1l));
// filter
searchResponse = client().prepareSearch("test").setQuery(filteredQuery(matchAllQuery(), nestedFilter("nested1",
boolQuery().must(termQuery("nested1.n_field1", "n_value1_1")).must(termQuery("nested1.n_field2", "n_value2_1"))))).execute().actionGet();
assertNoFailures(searchResponse);
assertThat(searchResponse.getHits().totalHits(), equalTo(1l));
// check with type prefix
searchResponse = client().prepareSearch("test").setQuery(nestedQuery("nested1",
boolQuery().must(termQuery("nested1.n_field1", "n_value1_1")).must(termQuery("nested1.n_field2", "n_value2_1")))).execute().actionGet();
assertNoFailures(searchResponse);
assertThat(searchResponse.getHits().totalHits(), equalTo(1l));
// check delete, so all is gone...
DeleteResponse deleteResponse = client().prepareDelete("test", "type1", "2").execute().actionGet();
assertThat(deleteResponse.isFound(), equalTo(true));
// flush, so we fetch it from the index (as see that we filter nested docs)
flush();
assertDocumentCount("test", 3);
searchResponse = client().prepareSearch("test").setQuery(nestedQuery("nested1", termQuery("nested1.n_field1", "n_value1_1"))).execute().actionGet();
assertNoFailures(searchResponse);
assertThat(searchResponse.getHits().totalHits(), equalTo(1l));
searchResponse = client().prepareSearch("test").setTypes("type1", "type2").setQuery(nestedQuery("nested1", termQuery("nested1.n_field1", "n_value1_1"))).execute().actionGet();
assertNoFailures(searchResponse);
assertThat(searchResponse.getHits().totalHits(), equalTo(1l));
}
@Test @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/10661")
public void simpleNestedMatchQueries() throws Exception {
XContentBuilder builder = jsonBuilder().startObject()
.startObject("type1")
.startObject("properties")
.startObject("nested1")
.field("type", "nested")
.endObject()
.startObject("field1")
.field("type", "long")
.endObject()
.endObject()
.endObject()
.endObject();
assertAcked(prepareCreate("test").addMapping("type1", builder));
ensureGreen();
List<IndexRequestBuilder> requests = new ArrayList<>();
int numDocs = randomIntBetween(2, 35);
requests.add(client().prepareIndex("test", "type1", "0").setSource(jsonBuilder().startObject()
.field("field1", 0)
.startArray("nested1")
.startObject()
.field("n_field1", "n_value1_1")
.field("n_field2", "n_value2_1")
.endObject()
.startObject()
.field("n_field1", "n_value1_2")
.field("n_field2", "n_value2_2")
.endObject()
.endArray()
.endObject()));
requests.add(client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject()
.field("field1", 1)
.startArray("nested1")
.startObject()
.field("n_field1", "n_value1_8")
.field("n_field2", "n_value2_5")
.endObject()
.startObject()
.field("n_field1", "n_value1_3")
.field("n_field2", "n_value2_1")
.endObject()
.endArray()
.endObject()));
for (int i = 2; i < numDocs; i++) {
requests.add(client().prepareIndex("test", "type1", String.valueOf(i)).setSource(jsonBuilder().startObject()
.field("field1", i)
.startArray("nested1")
.startObject()
.field("n_field1", "n_value1_8")
.field("n_field2", "n_value2_5")
.endObject()
.startObject()
.field("n_field1", "n_value1_2")
.field("n_field2", "n_value2_2")
.endObject()
.endArray()
.endObject()));
}
indexRandom(true, requests);
waitForRelocation(ClusterHealthStatus.GREEN);
SearchResponse searchResponse = client().prepareSearch("test")
.setQuery(nestedQuery("nested1", boolQuery()
.should(termQuery("nested1.n_field1", "n_value1_1").queryName("test1"))
.should(termQuery("nested1.n_field1", "n_value1_3").queryName("test2"))
.should(termQuery("nested1.n_field2", "n_value2_2").queryName("test3"))
))
.setSize(numDocs)
.addSort("field1", SortOrder.ASC)
.get();
assertNoFailures(searchResponse);
assertAllSuccessful(searchResponse);
assertThat(searchResponse.getHits().totalHits(), equalTo((long) numDocs));
assertThat(searchResponse.getHits().getAt(0).id(), equalTo("0"));
assertThat(searchResponse.getHits().getAt(0).matchedQueries(), arrayWithSize(2));
assertThat(searchResponse.getHits().getAt(0).matchedQueries(), arrayContainingInAnyOrder("test1", "test3"));
assertThat(searchResponse.getHits().getAt(1).id(), equalTo("1"));
assertThat(searchResponse.getHits().getAt(1).matchedQueries(), arrayWithSize(1));
assertThat(searchResponse.getHits().getAt(1).matchedQueries(), arrayContaining("test2"));
for (int i = 2; i < numDocs; i++) {
assertThat(searchResponse.getHits().getAt(i).id(), equalTo(String.valueOf(i)));
assertThat(searchResponse.getHits().getAt(i).matchedQueries(), arrayWithSize(1));
assertThat(searchResponse.getHits().getAt(i).matchedQueries(), arrayContaining("test3"));
}
}
@Test
public void simpleNestedDeletedByQuery1() throws Exception {
simpleNestedDeleteByQuery(3, 0);
}
@Test
public void simpleNestedDeletedByQuery2() throws Exception {
simpleNestedDeleteByQuery(3, 1);
}
@Test
public void simpleNestedDeletedByQuery3() throws Exception {
simpleNestedDeleteByQuery(3, 2);
}
private void simpleNestedDeleteByQuery(int total, int docToDelete) throws Exception {
assertAcked(prepareCreate("test")
.setSettings(settingsBuilder().put(indexSettings()).put("index.referesh_interval", -1).build())
.addMapping("type1", jsonBuilder().startObject().startObject("type1").startObject("properties")
.startObject("nested1")
.field("type", "nested")
.endObject()
.endObject().endObject().endObject()));
ensureGreen();
for (int i = 0; i < total; i++) {
client().prepareIndex("test", "type1", Integer.toString(i)).setSource(jsonBuilder().startObject()
.field("field1", "value1")
.startArray("nested1")
.startObject()
.field("n_field1", "n_value1_1")
.field("n_field2", "n_value2_1")
.endObject()
.startObject()
.field("n_field1", "n_value1_2")
.field("n_field2", "n_value2_2")
.endObject()
.endArray()
.endObject()).execute().actionGet();
}
flush();
assertDocumentCount("test", total * 3);
client().prepareDeleteByQuery("test").setQuery(QueryBuilders.idsQuery("type1").ids(Integer.toString(docToDelete))).execute().actionGet();
flush();
refresh();
assertDocumentCount("test", (total * 3l) - 3);
for (int i = 0; i < total; i++) {
assertThat(client().prepareGet("test", "type1", Integer.toString(i)).execute().actionGet().isExists(), equalTo(i != docToDelete));
}
}
@Test
public void noChildrenNestedDeletedByQuery1() throws Exception {
noChildrenNestedDeleteByQuery(3, 0);
}
@Test
public void noChildrenNestedDeletedByQuery2() throws Exception {
noChildrenNestedDeleteByQuery(3, 1);
}
@Test
public void noChildrenNestedDeletedByQuery3() throws Exception {
noChildrenNestedDeleteByQuery(3, 2);
}
private void noChildrenNestedDeleteByQuery(long total, int docToDelete) throws Exception {
assertAcked(prepareCreate("test")
.setSettings(settingsBuilder().put(indexSettings()).put("index.referesh_interval", -1).build())
.addMapping("type1", jsonBuilder().startObject().startObject("type1").startObject("properties")
.startObject("nested1")
.field("type", "nested")
.endObject()
.endObject().endObject().endObject()));
ensureGreen();
for (int i = 0; i < total; i++) {
client().prepareIndex("test", "type1", Integer.toString(i)).setSource(jsonBuilder().startObject()
.field("field1", "value1")
.endObject()).execute().actionGet();
}
flush();
refresh();
assertDocumentCount("test", total);
client().prepareDeleteByQuery("test").setQuery(QueryBuilders.idsQuery("type1").ids(Integer.toString(docToDelete))).execute().actionGet();
flush();
refresh();
assertDocumentCount("test", total - 1);
for (int i = 0; i < total; i++) {
assertThat(client().prepareGet("test", "type1", Integer.toString(i)).execute().actionGet().isExists(), equalTo(i != docToDelete));
}
}
@Test
public void multiNested() throws Exception {
assertAcked(prepareCreate("test")
.addMapping("type1", jsonBuilder().startObject().startObject("type1").startObject("properties")
.startObject("nested1")
.field("type", "nested").startObject("properties")
.startObject("nested2").field("type", "nested").endObject()
.endObject().endObject()
.endObject().endObject().endObject()));
ensureGreen();
client().prepareIndex("test", "type1", "1").setSource(jsonBuilder()
.startObject()
.field("field", "value")
.startArray("nested1")
.startObject().field("field1", "1").startArray("nested2").startObject().field("field2", "2").endObject().startObject().field("field2", "3").endObject().endArray().endObject()
.startObject().field("field1", "4").startArray("nested2").startObject().field("field2", "5").endObject().startObject().field("field2", "6").endObject().endArray().endObject()
.endArray()
.endObject()).execute().actionGet();
// flush, so we fetch it from the index (as see that we filter nested docs)
flush();
GetResponse getResponse = client().prepareGet("test", "type1", "1").execute().actionGet();
assertThat(getResponse.isExists(), equalTo(true));
waitForRelocation(ClusterHealthStatus.GREEN);
// check the numDocs
assertDocumentCount("test", 7);
// do some multi nested queries
SearchResponse searchResponse = client().prepareSearch("test").setQuery(nestedQuery("nested1",
termQuery("nested1.field1", "1"))).execute().actionGet();
assertNoFailures(searchResponse);
assertThat(searchResponse.getHits().totalHits(), equalTo(1l));
searchResponse = client().prepareSearch("test").setQuery(nestedQuery("nested1.nested2",
termQuery("nested1.nested2.field2", "2"))).execute().actionGet();
assertNoFailures(searchResponse);
assertThat(searchResponse.getHits().totalHits(), equalTo(1l));
searchResponse = client().prepareSearch("test").setQuery(nestedQuery("nested1",
boolQuery().must(termQuery("nested1.field1", "1")).must(nestedQuery("nested1.nested2", termQuery("nested1.nested2.field2", "2"))))).execute().actionGet();
assertNoFailures(searchResponse);
assertThat(searchResponse.getHits().totalHits(), equalTo(1l));
searchResponse = client().prepareSearch("test").setQuery(nestedQuery("nested1",
boolQuery().must(termQuery("nested1.field1", "1")).must(nestedQuery("nested1.nested2", termQuery("nested1.nested2.field2", "3"))))).execute().actionGet();
assertNoFailures(searchResponse);
assertThat(searchResponse.getHits().totalHits(), equalTo(1l));
searchResponse = client().prepareSearch("test").setQuery(nestedQuery("nested1",
boolQuery().must(termQuery("nested1.field1", "1")).must(nestedQuery("nested1.nested2", termQuery("nested1.nested2.field2", "4"))))).execute().actionGet();
assertNoFailures(searchResponse);
assertThat(searchResponse.getHits().totalHits(), equalTo(0l));
searchResponse = client().prepareSearch("test").setQuery(nestedQuery("nested1",
boolQuery().must(termQuery("nested1.field1", "1")).must(nestedQuery("nested1.nested2", termQuery("nested1.nested2.field2", "5"))))).execute().actionGet();
assertNoFailures(searchResponse);
assertThat(searchResponse.getHits().totalHits(), equalTo(0l));
searchResponse = client().prepareSearch("test").setQuery(nestedQuery("nested1",
boolQuery().must(termQuery("nested1.field1", "4")).must(nestedQuery("nested1.nested2", termQuery("nested1.nested2.field2", "5"))))).execute().actionGet();
assertNoFailures(searchResponse);
assertThat(searchResponse.getHits().totalHits(), equalTo(1l));
searchResponse = client().prepareSearch("test").setQuery(nestedQuery("nested1",
boolQuery().must(termQuery("nested1.field1", "4")).must(nestedQuery("nested1.nested2", termQuery("nested1.nested2.field2", "2"))))).execute().actionGet();
assertNoFailures(searchResponse);
assertThat(searchResponse.getHits().totalHits(), equalTo(0l));
}
@Test
// When IncludeNestedDocsQuery is wrapped in a FilteredQuery then a in-finite loop occurs b/c of a bug in IncludeNestedDocsQuery#advance()
// This IncludeNestedDocsQuery also needs to be aware of the filter from alias
public void testDeleteNestedDocsWithAlias() throws Exception {
assertAcked(prepareCreate("test")
.setSettings(settingsBuilder().put(indexSettings()).put("index.referesh_interval", -1).build())
.addMapping("type1", jsonBuilder().startObject().startObject("type1").startObject("properties")
.startObject("field1")
.field("type", "string")
.endObject()
.startObject("nested1")
.field("type", "nested")
.endObject()
.endObject().endObject().endObject()));
client().admin().indices().prepareAliases()
.addAlias("test", "alias1", FilterBuilders.termFilter("field1", "value1")).execute().actionGet();
ensureGreen();
client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject()
.field("field1", "value1")
.startArray("nested1")
.startObject()
.field("n_field1", "n_value1_1")
.field("n_field2", "n_value2_1")
.endObject()
.startObject()
.field("n_field1", "n_value1_2")
.field("n_field2", "n_value2_2")
.endObject()
.endArray()
.endObject()).execute().actionGet();
client().prepareIndex("test", "type1", "2").setSource(jsonBuilder().startObject()
.field("field1", "value2")
.startArray("nested1")
.startObject()
.field("n_field1", "n_value1_1")
.field("n_field2", "n_value2_1")
.endObject()
.startObject()
.field("n_field1", "n_value1_2")
.field("n_field2", "n_value2_2")
.endObject()
.endArray()
.endObject()).execute().actionGet();
flush();
refresh();
assertDocumentCount("test", 6);
client().prepareDeleteByQuery("alias1").setQuery(QueryBuilders.matchAllQuery()).execute().actionGet();
flush();
refresh();
// This must be 3, otherwise child docs aren't deleted.
// If this is 5 then only the parent has been removed
assertDocumentCount("test", 3);
assertThat(client().prepareGet("test", "type1", "1").execute().actionGet().isExists(), equalTo(false));
}
@Test
public void testExplain() throws Exception {
assertAcked(prepareCreate("test")
.addMapping("type1", jsonBuilder().startObject().startObject("type1").startObject("properties")
.startObject("nested1")
.field("type", "nested")
.endObject()
.endObject().endObject().endObject()));
ensureGreen();
client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject()
.field("field1", "value1")
.startArray("nested1")
.startObject()
.field("n_field1", "n_value1")
.endObject()
.startObject()
.field("n_field1", "n_value1")
.endObject()
.endArray()
.endObject())
.setRefresh(true)
.execute().actionGet();
SearchResponse searchResponse = client().prepareSearch("test")
.setQuery(nestedQuery("nested1", termQuery("nested1.n_field1", "n_value1")).scoreMode("total"))
.setExplain(true)
.execute().actionGet();
assertNoFailures(searchResponse);
assertThat(searchResponse.getHits().totalHits(), equalTo(1l));
Explanation explanation = searchResponse.getHits().hits()[0].explanation();
assertThat(explanation.getValue(), equalTo(2f));
assertThat(explanation.toString(), startsWith("2.0 = sum of:\n 2.0 = Score based on child doc range from 0 to 1\n"));
// TODO: Enable when changes from BlockJoinQuery#explain are added to Lucene (Most likely version 4.2)
// assertThat(explanation.getDetails().length, equalTo(2));
// assertThat(explanation.getDetails()[0].getValue(), equalTo(1f));
// assertThat(explanation.getDetails()[0].getDescription(), equalTo("Child[0]"));
// assertThat(explanation.getDetails()[1].getValue(), equalTo(1f));
// assertThat(explanation.getDetails()[1].getDescription(), equalTo("Child[1]"));
}
@Test
public void testSimpleNestedSorting() throws Exception {
assertAcked(prepareCreate("test")
.setSettings(settingsBuilder()
.put(indexSettings())
.put("index.refresh_interval", -1))
.addMapping("type1", jsonBuilder().startObject().startObject("type1").startObject("properties")
.startObject("nested1")
.field("type", "nested")
.startObject("properties")
.startObject("field1")
.field("type", "long")
.field("store", "yes")
.endObject()
.endObject()
.endObject()
.endObject().endObject().endObject()));
ensureGreen();
client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject()
.field("field1", 1)
.startArray("nested1")
.startObject()
.field("field1", 5)
.endObject()
.startObject()
.field("field1", 4)
.endObject()
.endArray()
.endObject()).execute().actionGet();
client().prepareIndex("test", "type1", "2").setSource(jsonBuilder().startObject()
.field("field1", 2)
.startArray("nested1")
.startObject()
.field("field1", 1)
.endObject()
.startObject()
.field("field1", 2)
.endObject()
.endArray()
.endObject()).execute().actionGet();
client().prepareIndex("test", "type1", "3").setSource(jsonBuilder().startObject()
.field("field1", 3)
.startArray("nested1")
.startObject()
.field("field1", 3)
.endObject()
.startObject()
.field("field1", 4)
.endObject()
.endArray()
.endObject()).execute().actionGet();
refresh();
SearchResponse searchResponse = client().prepareSearch("test")
.setTypes("type1")
.setQuery(QueryBuilders.matchAllQuery())
.addSort(SortBuilders.fieldSort("nested1.field1").order(SortOrder.ASC))
.execute().actionGet();
assertHitCount(searchResponse, 3);
assertThat(searchResponse.getHits().hits()[0].id(), equalTo("2"));
assertThat(searchResponse.getHits().hits()[0].sortValues()[0].toString(), equalTo("1"));
assertThat(searchResponse.getHits().hits()[1].id(), equalTo("3"));
assertThat(searchResponse.getHits().hits()[1].sortValues()[0].toString(), equalTo("3"));
assertThat(searchResponse.getHits().hits()[2].id(), equalTo("1"));
assertThat(searchResponse.getHits().hits()[2].sortValues()[0].toString(), equalTo("4"));
searchResponse = client().prepareSearch("test")
.setTypes("type1")
.setQuery(QueryBuilders.matchAllQuery())
.addSort(SortBuilders.fieldSort("nested1.field1").order(SortOrder.DESC))
.execute().actionGet();
assertHitCount(searchResponse, 3);
assertThat(searchResponse.getHits().hits()[0].id(), equalTo("1"));
assertThat(searchResponse.getHits().hits()[0].sortValues()[0].toString(), equalTo("5"));
assertThat(searchResponse.getHits().hits()[1].id(), equalTo("3"));
assertThat(searchResponse.getHits().hits()[1].sortValues()[0].toString(), equalTo("4"));
assertThat(searchResponse.getHits().hits()[2].id(), equalTo("2"));
assertThat(searchResponse.getHits().hits()[2].sortValues()[0].toString(), equalTo("2"));
searchResponse = client().prepareSearch("test")
.setTypes("type1")
.setQuery(QueryBuilders.matchAllQuery())
.addSort(SortBuilders.scriptSort("_fields['nested1.field1'].value + 1", "number").setNestedPath("nested1").order(SortOrder.DESC))
.execute().actionGet();
assertHitCount(searchResponse, 3);
assertThat(searchResponse.getHits().hits()[0].id(), equalTo("1"));
assertThat(searchResponse.getHits().hits()[0].sortValues()[0].toString(), equalTo("6.0"));
assertThat(searchResponse.getHits().hits()[1].id(), equalTo("3"));
assertThat(searchResponse.getHits().hits()[1].sortValues()[0].toString(), equalTo("5.0"));
assertThat(searchResponse.getHits().hits()[2].id(), equalTo("2"));
assertThat(searchResponse.getHits().hits()[2].sortValues()[0].toString(), equalTo("3.0"));
searchResponse = client().prepareSearch("test")
.setTypes("type1")
.setQuery(QueryBuilders.matchAllQuery())
.addSort(SortBuilders.scriptSort("_fields['nested1.field1'].value + 1", "number").setNestedPath("nested1").sortMode("sum").order(SortOrder.DESC))
.execute().actionGet();
// B/c of sum it is actually +2
assertHitCount(searchResponse, 3);
assertThat(searchResponse.getHits().hits()[0].id(), equalTo("1"));
assertThat(searchResponse.getHits().hits()[0].sortValues()[0].toString(), equalTo("11.0"));
assertThat(searchResponse.getHits().hits()[1].id(), equalTo("3"));
assertThat(searchResponse.getHits().hits()[1].sortValues()[0].toString(), equalTo("9.0"));
assertThat(searchResponse.getHits().hits()[2].id(), equalTo("2"));
assertThat(searchResponse.getHits().hits()[2].sortValues()[0].toString(), equalTo("5.0"));
searchResponse = client().prepareSearch("test")
.setTypes("type1")
.setQuery(QueryBuilders.matchAllQuery())
.addSort(SortBuilders.scriptSort("_fields['nested1.field1'].value", "number")
.setNestedFilter(rangeFilter("nested1.field1").from(1).to(3))
.setNestedPath("nested1").sortMode("avg").order(SortOrder.DESC))
.execute().actionGet();
assertHitCount(searchResponse, 3);
assertThat(searchResponse.getHits().hits()[0].id(), equalTo("1"));
assertThat(searchResponse.getHits().hits()[0].sortValues()[0].toString(), equalTo(Double.toString(Double.MAX_VALUE)));
assertThat(searchResponse.getHits().hits()[1].id(), equalTo("3"));
assertThat(searchResponse.getHits().hits()[1].sortValues()[0].toString(), equalTo("3.0"));
assertThat(searchResponse.getHits().hits()[2].id(), equalTo("2"));
assertThat(searchResponse.getHits().hits()[2].sortValues()[0].toString(), equalTo("1.5"));
searchResponse = client().prepareSearch("test")
.setTypes("type1")
.setQuery(QueryBuilders.matchAllQuery())
.addSort(SortBuilders.scriptSort("_fields['nested1.field1'].value", "string")
.setNestedPath("nested1").order(SortOrder.DESC))
.execute().actionGet();
assertHitCount(searchResponse, 3);
assertThat(searchResponse.getHits().hits()[0].id(), equalTo("1"));
assertThat(searchResponse.getHits().hits()[0].sortValues()[0].toString(), equalTo("5"));
assertThat(searchResponse.getHits().hits()[1].id(), equalTo("3"));
assertThat(searchResponse.getHits().hits()[1].sortValues()[0].toString(), equalTo("4"));
assertThat(searchResponse.getHits().hits()[2].id(), equalTo("2"));
assertThat(searchResponse.getHits().hits()[2].sortValues()[0].toString(), equalTo("2"));
searchResponse = client().prepareSearch("test")
.setTypes("type1")
.setQuery(QueryBuilders.matchAllQuery())
.addSort(SortBuilders.scriptSort("_fields['nested1.field1'].value", "string")
.setNestedPath("nested1").order(SortOrder.ASC))
.execute().actionGet();
assertHitCount(searchResponse, 3);
assertThat(searchResponse.getHits().hits()[0].id(), equalTo("2"));
assertThat(searchResponse.getHits().hits()[0].sortValues()[0].toString(), equalTo("1"));
assertThat(searchResponse.getHits().hits()[1].id(), equalTo("3"));
assertThat(searchResponse.getHits().hits()[1].sortValues()[0].toString(), equalTo("3"));
assertThat(searchResponse.getHits().hits()[2].id(), equalTo("1"));
assertThat(searchResponse.getHits().hits()[2].sortValues()[0].toString(), equalTo("4"));
try {
client().prepareSearch("test")
.setTypes("type1")
.setQuery(QueryBuilders.matchAllQuery())
.addSort(SortBuilders.scriptSort("_fields['nested1.field1'].value", "string")
.setNestedPath("nested1").sortMode("sum").order(SortOrder.ASC))
.execute().actionGet();
Assert.fail("SearchPhaseExecutionException should have been thrown");
} catch (SearchPhaseExecutionException e) {
assertThat(e.toString(), containsString("type [string] doesn't support mode [SUM]"));
}
}
@Test
public void testSimpleNestedSorting_withNestedFilterMissing() throws Exception {
assertAcked(prepareCreate("test")
.setSettings(settingsBuilder()
.put(indexSettings())
.put("index.referesh_interval", -1))
.addMapping("type1", jsonBuilder().startObject().startObject("type1").startObject("properties")
.startObject("nested1")
.field("type", "nested")
.startObject("properties")
.startObject("field1")
.field("type", "long")
.endObject()
.startObject("field2")
.field("type", "boolean")
.endObject()
.endObject()
.endObject()
.endObject().endObject().endObject()));
ensureGreen();
client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject()
.field("field1", 1)
.startArray("nested1")
.startObject()
.field("field1", 5)
.field("field2", true)
.endObject()
.startObject()
.field("field1", 4)
.field("field2", true)
.endObject()
.endArray()
.endObject()).execute().actionGet();
client().prepareIndex("test", "type1", "2").setSource(jsonBuilder().startObject()
.field("field1", 2)
.startArray("nested1")
.startObject()
.field("field1", 1)
.field("field2", true)
.endObject()
.startObject()
.field("field1", 2)
.field("field2", true)
.endObject()
.endArray()
.endObject()).execute().actionGet();
// Doc with missing nested docs if nested filter is used
refresh();
client().prepareIndex("test", "type1", "3").setSource(jsonBuilder().startObject()
.field("field1", 3)
.startArray("nested1")
.startObject()
.field("field1", 3)
.field("field2", false)
.endObject()
.startObject()
.field("field1", 4)
.field("field2", false)
.endObject()
.endArray()
.endObject()).execute().actionGet();
refresh();
SearchRequestBuilder searchRequestBuilder = client().prepareSearch("test").setTypes("type1")
.setQuery(QueryBuilders.matchAllQuery())
.addSort(SortBuilders.fieldSort("nested1.field1").setNestedFilter(termFilter("nested1.field2", true)).missing(10).order(SortOrder.ASC));
if (randomBoolean()) {
searchRequestBuilder.setScroll("10m");
}
SearchResponse searchResponse = searchRequestBuilder.get();
assertHitCount(searchResponse, 3);
assertThat(searchResponse.getHits().hits()[0].id(), equalTo("2"));
assertThat(searchResponse.getHits().hits()[0].sortValues()[0].toString(), equalTo("1"));
assertThat(searchResponse.getHits().hits()[1].id(), equalTo("1"));
assertThat(searchResponse.getHits().hits()[1].sortValues()[0].toString(), equalTo("4"));
assertThat(searchResponse.getHits().hits()[2].id(), equalTo("3"));
assertThat(searchResponse.getHits().hits()[2].sortValues()[0].toString(), equalTo("10"));
searchRequestBuilder = client().prepareSearch("test").setTypes("type1").setQuery(QueryBuilders.matchAllQuery())
.addSort(SortBuilders.fieldSort("nested1.field1").setNestedFilter(termFilter("nested1.field2", true)).missing(10).order(SortOrder.DESC));
if (randomBoolean()) {
searchRequestBuilder.setScroll("10m");
}
searchResponse = searchRequestBuilder.get();
assertHitCount(searchResponse, 3);
assertThat(searchResponse.getHits().hits()[0].id(), equalTo("3"));
assertThat(searchResponse.getHits().hits()[0].sortValues()[0].toString(), equalTo("10"));
assertThat(searchResponse.getHits().hits()[1].id(), equalTo("1"));
assertThat(searchResponse.getHits().hits()[1].sortValues()[0].toString(), equalTo("5"));
assertThat(searchResponse.getHits().hits()[2].id(), equalTo("2"));
assertThat(searchResponse.getHits().hits()[2].sortValues()[0].toString(), equalTo("2"));
client().prepareClearScroll().addScrollId("_all").get();
}
@Test
public void testSortNestedWithNestedFilter() throws Exception {
assertAcked(prepareCreate("test")
.addMapping("type1", XContentFactory.jsonBuilder().startObject()
.startObject("type1")
.startObject("properties")
.startObject("grand_parent_values").field("type", "long").endObject()
.startObject("parent").field("type", "nested")
.startObject("properties")
.startObject("parent_values").field("type", "long").endObject()
.startObject("child").field("type", "nested")
.startObject("properties")
.startObject("child_values").field("type", "long").endObject()
.endObject()
.endObject()
.endObject()
.endObject()
.endObject()
.endObject()
.endObject()));
ensureGreen();
// sum: 11
client().prepareIndex("test", "type1", Integer.toString(1)).setSource(jsonBuilder().startObject()
.field("grand_parent_values", 1l)
.startObject("parent")
.field("filter", false)
.field("parent_values", 1l)
.startObject("child")
.field("filter", true)
.field("child_values", 1l)
.startObject("child_obj")
.field("value", 1l)
.endObject()
.endObject()
.startObject("child")
.field("filter", false)
.field("child_values", 6l)
.endObject()
.endObject()
.startObject("parent")
.field("filter", true)
.field("parent_values", 2l)
.startObject("child")
.field("filter", false)
.field("child_values", -1l)
.endObject()
.startObject("child")
.field("filter", false)
.field("child_values", 5l)
.endObject()
.endObject()
.endObject()).execute().actionGet();
// sum: 7
client().prepareIndex("test", "type1", Integer.toString(2)).setSource(jsonBuilder().startObject()
.field("grand_parent_values", 2l)
.startObject("parent")
.field("filter", false)
.field("parent_values", 2l)
.startObject("child")
.field("filter", true)
.field("child_values", 2l)
.startObject("child_obj")
.field("value", 2l)
.endObject()
.endObject()
.startObject("child")
.field("filter", false)
.field("child_values", 4l)
.endObject()
.endObject()
.startObject("parent")
.field("parent_values", 3l)
.field("filter", true)
.startObject("child")
.field("child_values", -2l)
.field("filter", false)
.endObject()
.startObject("child")
.field("filter", false)
.field("child_values", 3l)
.endObject()
.endObject()
.endObject()).execute().actionGet();
// sum: 2
client().prepareIndex("test", "type1", Integer.toString(3)).setSource(jsonBuilder().startObject()
.field("grand_parent_values", 3l)
.startObject("parent")
.field("parent_values", 3l)
.field("filter", false)
.startObject("child")
.field("filter", true)
.field("child_values", 3l)
.startObject("child_obj")
.field("value", 3l)
.endObject()
.endObject()
.startObject("child")
.field("filter", false)
.field("child_values", 1l)
.endObject()
.endObject()
.startObject("parent")
.field("parent_values", 4l)
.field("filter", true)
.startObject("child")
.field("filter", false)
.field("child_values", -3l)
.endObject()
.startObject("child")
.field("filter", false)
.field("child_values", 1l)
.endObject()
.endObject()
.endObject()).execute().actionGet();
refresh();
// Without nested filter
SearchResponse searchResponse = client().prepareSearch()
.setQuery(matchAllQuery())
.addSort(
SortBuilders.fieldSort("parent.child.child_values")
.setNestedPath("parent.child")
.order(SortOrder.ASC)
)
.execute().actionGet();
assertHitCount(searchResponse, 3);
assertThat(searchResponse.getHits().getHits().length, equalTo(3));
assertThat(searchResponse.getHits().getHits()[0].getId(), equalTo("3"));
assertThat(searchResponse.getHits().getHits()[0].sortValues()[0].toString(), equalTo("-3"));
assertThat(searchResponse.getHits().getHits()[1].getId(), equalTo("2"));
assertThat(searchResponse.getHits().getHits()[1].sortValues()[0].toString(), equalTo("-2"));
assertThat(searchResponse.getHits().getHits()[2].getId(), equalTo("1"));
assertThat(searchResponse.getHits().getHits()[2].sortValues()[0].toString(), equalTo("-1"));
// With nested filter
searchResponse = client().prepareSearch()
.setQuery(matchAllQuery())
.addSort(
SortBuilders.fieldSort("parent.child.child_values")
.setNestedPath("parent.child")
.setNestedFilter(FilterBuilders.termFilter("parent.child.filter", true))
.order(SortOrder.ASC)
)
.execute().actionGet();
assertHitCount(searchResponse, 3);
assertThat(searchResponse.getHits().getHits().length, equalTo(3));
assertThat(searchResponse.getHits().getHits()[0].getId(), equalTo("1"));
assertThat(searchResponse.getHits().getHits()[0].sortValues()[0].toString(), equalTo("1"));
assertThat(searchResponse.getHits().getHits()[1].getId(), equalTo("2"));
assertThat(searchResponse.getHits().getHits()[1].sortValues()[0].toString(), equalTo("2"));
assertThat(searchResponse.getHits().getHits()[2].getId(), equalTo("3"));
assertThat(searchResponse.getHits().getHits()[2].sortValues()[0].toString(), equalTo("3"));
// Nested path should be automatically detected, expect same results as above search request
searchResponse = client().prepareSearch()
.setQuery(matchAllQuery())
.addSort(
SortBuilders.fieldSort("parent.child.child_values")
.setNestedFilter(FilterBuilders.termFilter("parent.child.filter", true))
.order(SortOrder.ASC)
)
.execute().actionGet();
assertHitCount(searchResponse, 3);
assertThat(searchResponse.getHits().getHits().length, equalTo(3));
assertThat(searchResponse.getHits().getHits()[0].getId(), equalTo("1"));
assertThat(searchResponse.getHits().getHits()[0].sortValues()[0].toString(), equalTo("1"));
assertThat(searchResponse.getHits().getHits()[1].getId(), equalTo("2"));
assertThat(searchResponse.getHits().getHits()[1].sortValues()[0].toString(), equalTo("2"));
assertThat(searchResponse.getHits().getHits()[2].getId(), equalTo("3"));
assertThat(searchResponse.getHits().getHits()[2].sortValues()[0].toString(), equalTo("3"));
searchResponse = client().prepareSearch()
.setQuery(matchAllQuery())
.addSort(
SortBuilders.fieldSort("parent.parent_values")
.setNestedPath("parent.child")
.setNestedFilter(FilterBuilders.termFilter("parent.filter", false))
.order(SortOrder.ASC)
)
.execute().actionGet();
assertHitCount(searchResponse, 3);
assertThat(searchResponse.getHits().getHits().length, equalTo(3));
assertThat(searchResponse.getHits().getHits()[0].getId(), equalTo("1"));
assertThat(searchResponse.getHits().getHits()[0].sortValues()[0].toString(), equalTo("1"));
assertThat(searchResponse.getHits().getHits()[1].getId(), equalTo("2"));
assertThat(searchResponse.getHits().getHits()[1].sortValues()[0].toString(), equalTo("2"));
assertThat(searchResponse.getHits().getHits()[2].getId(), equalTo("3"));
assertThat(searchResponse.getHits().getHits()[2].sortValues()[0].toString(), equalTo("3"));
searchResponse = client().prepareSearch()
.setQuery(matchAllQuery())
.addSort(
SortBuilders.fieldSort("parent.child.child_values")
.setNestedPath("parent.child")
.setNestedFilter(FilterBuilders.termFilter("parent.filter", false))
.order(SortOrder.ASC)
)
.execute().actionGet();
assertHitCount(searchResponse, 3);
assertThat(searchResponse.getHits().getHits().length, equalTo(3));
// TODO: If we expose ToChildBlockJoinQuery we can filter sort values based on a higher level nested objects
// assertThat(searchResponse.getHits().getHits()[0].getId(), equalTo("3"));
// assertThat(searchResponse.getHits().getHits()[0].sortValues()[0].toString(), equalTo("-3"));
// assertThat(searchResponse.getHits().getHits()[1].getId(), equalTo("2"));
// assertThat(searchResponse.getHits().getHits()[1].sortValues()[0].toString(), equalTo("-2"));
// assertThat(searchResponse.getHits().getHits()[2].getId(), equalTo("1"));
// assertThat(searchResponse.getHits().getHits()[2].sortValues()[0].toString(), equalTo("-1"));
// Check if closest nested type is resolved
searchResponse = client().prepareSearch()
.setQuery(matchAllQuery())
.addSort(
SortBuilders.fieldSort("parent.child.child_obj.value")
.setNestedFilter(FilterBuilders.termFilter("parent.child.filter", true))
.order(SortOrder.ASC)
)
.execute().actionGet();
assertHitCount(searchResponse, 3);
assertThat(searchResponse.getHits().getHits().length, equalTo(3));
assertThat(searchResponse.getHits().getHits()[0].getId(), equalTo("1"));
assertThat(searchResponse.getHits().getHits()[0].sortValues()[0].toString(), equalTo("1"));
assertThat(searchResponse.getHits().getHits()[1].getId(), equalTo("2"));
assertThat(searchResponse.getHits().getHits()[1].sortValues()[0].toString(), equalTo("2"));
assertThat(searchResponse.getHits().getHits()[2].getId(), equalTo("3"));
assertThat(searchResponse.getHits().getHits()[2].sortValues()[0].toString(), equalTo("3"));
// Sort mode: sum
searchResponse = client().prepareSearch()
.setQuery(matchAllQuery())
.addSort(
SortBuilders.fieldSort("parent.child.child_values")
.setNestedPath("parent.child")
.sortMode("sum")
.order(SortOrder.ASC)
)
.execute().actionGet();
assertHitCount(searchResponse, 3);
assertThat(searchResponse.getHits().getHits().length, equalTo(3));
assertThat(searchResponse.getHits().getHits()[0].getId(), equalTo("3"));
assertThat(searchResponse.getHits().getHits()[0].sortValues()[0].toString(), equalTo("2"));
assertThat(searchResponse.getHits().getHits()[1].getId(), equalTo("2"));
assertThat(searchResponse.getHits().getHits()[1].sortValues()[0].toString(), equalTo("7"));
assertThat(searchResponse.getHits().getHits()[2].getId(), equalTo("1"));
assertThat(searchResponse.getHits().getHits()[2].sortValues()[0].toString(), equalTo("11"));
searchResponse = client().prepareSearch()
.setQuery(matchAllQuery())
.addSort(
SortBuilders.fieldSort("parent.child.child_values")
.setNestedPath("parent.child")
.sortMode("sum")
.order(SortOrder.DESC)
)
.execute().actionGet();
assertHitCount(searchResponse, 3);
assertThat(searchResponse.getHits().getHits().length, equalTo(3));
assertThat(searchResponse.getHits().getHits()[0].getId(), equalTo("1"));
assertThat(searchResponse.getHits().getHits()[0].sortValues()[0].toString(), equalTo("11"));
assertThat(searchResponse.getHits().getHits()[1].getId(), equalTo("2"));
assertThat(searchResponse.getHits().getHits()[1].sortValues()[0].toString(), equalTo("7"));
assertThat(searchResponse.getHits().getHits()[2].getId(), equalTo("3"));
assertThat(searchResponse.getHits().getHits()[2].sortValues()[0].toString(), equalTo("2"));
// Sort mode: sum with filter
searchResponse = client().prepareSearch()
.setQuery(matchAllQuery())
.addSort(
SortBuilders.fieldSort("parent.child.child_values")
.setNestedPath("parent.child")
.setNestedFilter(FilterBuilders.termFilter("parent.child.filter", true))
.sortMode("sum")
.order(SortOrder.ASC)
)
.execute().actionGet();
assertHitCount(searchResponse, 3);
assertThat(searchResponse.getHits().getHits().length, equalTo(3));
assertThat(searchResponse.getHits().getHits()[0].getId(), equalTo("1"));
assertThat(searchResponse.getHits().getHits()[0].sortValues()[0].toString(), equalTo("1"));
assertThat(searchResponse.getHits().getHits()[1].getId(), equalTo("2"));
assertThat(searchResponse.getHits().getHits()[1].sortValues()[0].toString(), equalTo("2"));
assertThat(searchResponse.getHits().getHits()[2].getId(), equalTo("3"));
assertThat(searchResponse.getHits().getHits()[2].sortValues()[0].toString(), equalTo("3"));
// Sort mode: avg
searchResponse = client().prepareSearch()
.setQuery(matchAllQuery())
.addSort(
SortBuilders.fieldSort("parent.child.child_values")
.setNestedPath("parent.child")
.sortMode("avg")
.order(SortOrder.ASC)
)
.execute().actionGet();
assertHitCount(searchResponse, 3);
assertThat(searchResponse.getHits().getHits().length, equalTo(3));
assertThat(searchResponse.getHits().getHits()[0].getId(), equalTo("3"));
assertThat(searchResponse.getHits().getHits()[0].sortValues()[0].toString(), equalTo("1"));
assertThat(searchResponse.getHits().getHits()[1].getId(), equalTo("2"));
assertThat(searchResponse.getHits().getHits()[1].sortValues()[0].toString(), equalTo("2"));
assertThat(searchResponse.getHits().getHits()[2].getId(), equalTo("1"));
assertThat(searchResponse.getHits().getHits()[2].sortValues()[0].toString(), equalTo("3"));
searchResponse = client().prepareSearch()
.setQuery(matchAllQuery())
.addSort(
SortBuilders.fieldSort("parent.child.child_values")
.setNestedPath("parent.child")
.sortMode("avg")
.order(SortOrder.DESC)
)
.execute().actionGet();
assertHitCount(searchResponse, 3);
assertThat(searchResponse.getHits().getHits().length, equalTo(3));
assertThat(searchResponse.getHits().getHits()[0].getId(), equalTo("1"));
assertThat(searchResponse.getHits().getHits()[0].sortValues()[0].toString(), equalTo("3"));
assertThat(searchResponse.getHits().getHits()[1].getId(), equalTo("2"));
assertThat(searchResponse.getHits().getHits()[1].sortValues()[0].toString(), equalTo("2"));
assertThat(searchResponse.getHits().getHits()[2].getId(), equalTo("3"));
assertThat(searchResponse.getHits().getHits()[2].sortValues()[0].toString(), equalTo("1"));
// Sort mode: avg with filter
searchResponse = client().prepareSearch()
.setQuery(matchAllQuery())
.addSort(
SortBuilders.fieldSort("parent.child.child_values")
.setNestedPath("parent.child")
.setNestedFilter(FilterBuilders.termFilter("parent.child.filter", true))
.sortMode("avg")
.order(SortOrder.ASC)
)
.execute().actionGet();
assertHitCount(searchResponse, 3);
assertThat(searchResponse.getHits().getHits().length, equalTo(3));
assertThat(searchResponse.getHits().getHits()[0].getId(), equalTo("1"));
assertThat(searchResponse.getHits().getHits()[0].sortValues()[0].toString(), equalTo("1"));
assertThat(searchResponse.getHits().getHits()[1].getId(), equalTo("2"));
assertThat(searchResponse.getHits().getHits()[1].sortValues()[0].toString(), equalTo("2"));
assertThat(searchResponse.getHits().getHits()[2].getId(), equalTo("3"));
assertThat(searchResponse.getHits().getHits()[2].sortValues()[0].toString(), equalTo("3"));
}
@Test
// https://github.com/elasticsearch/elasticsearch/issues/9305
public void testNestedSortingWithNestedFilterAsFilter() throws Exception {
assertAcked(prepareCreate("test").addMapping("type", jsonBuilder().startObject().startObject("properties")
.startObject("officelocation").field("type", "string").endObject()
.startObject("users")
.field("type", "nested")
.startObject("properties")
.startObject("first").field("type", "string").endObject()
.startObject("last").field("type", "string").endObject()
.startObject("workstations")
.field("type", "nested")
.startObject("properties")
.startObject("stationid").field("type", "string").endObject()
.startObject("phoneid").field("type", "string").endObject()
.endObject()
.endObject()
.endObject()
.endObject()
.endObject().endObject()));
client().prepareIndex("test", "type", "1").setSource(jsonBuilder().startObject()
.field("officelocation", "gendale")
.startArray("users")
.startObject()
.field("first", "fname1")
.field("last", "lname1")
.startArray("workstations")
.startObject()
.field("stationid", "s1")
.field("phoneid", "p1")
.endObject()
.startObject()
.field("stationid", "s2")
.field("phoneid", "p2")
.endObject()
.endArray()
.endObject()
.startObject()
.field("first", "fname2")
.field("last", "lname2")
.startArray("workstations")
.startObject()
.field("stationid", "s3")
.field("phoneid", "p3")
.endObject()
.startObject()
.field("stationid", "s4")
.field("phoneid", "p4")
.endObject()
.endArray()
.endObject()
.startObject()
.field("first", "fname3")
.field("last", "lname3")
.startArray("workstations")
.startObject()
.field("stationid", "s5")
.field("phoneid", "p5")
.endObject()
.startObject()
.field("stationid", "s6")
.field("phoneid", "p6")
.endObject()
.endArray()
.endObject()
.endArray()
.endObject()).get();
client().prepareIndex("test", "type", "2").setSource(jsonBuilder().startObject()
.field("officelocation", "gendale")
.startArray("users")
.startObject()
.field("first", "fname4")
.field("last", "lname4")
.startArray("workstations")
.startObject()
.field("stationid", "s1")
.field("phoneid", "p1")
.endObject()
.startObject()
.field("stationid", "s2")
.field("phoneid", "p2")
.endObject()
.endArray()
.endObject()
.startObject()
.field("first", "fname5")
.field("last", "lname5")
.startArray("workstations")
.startObject()
.field("stationid", "s3")
.field("phoneid", "p3")
.endObject()
.startObject()
.field("stationid", "s4")
.field("phoneid", "p4")
.endObject()
.endArray()
.endObject()
.startObject()
.field("first", "fname1")
.field("last", "lname1")
.startArray("workstations")
.startObject()
.field("stationid", "s5")
.field("phoneid", "p5")
.endObject()
.startObject()
.field("stationid", "s6")
.field("phoneid", "p6")
.endObject()
.endArray()
.endObject()
.endArray()
.endObject()).get();
refresh();
SearchResponse searchResponse = client().prepareSearch("test")
.addSort(SortBuilders.fieldSort("users.first")
.order(SortOrder.ASC))
.addSort(SortBuilders.fieldSort("users.first")
.order(SortOrder.ASC)
.setNestedPath("users")
.setNestedFilter(nestedFilter("users.workstations", termFilter("users.workstations.stationid", "s5"))))
.get();
assertNoFailures(searchResponse);
assertHitCount(searchResponse, 2);
assertThat(searchResponse.getHits().getAt(0).id(), equalTo("2"));
assertThat(searchResponse.getHits().getAt(0).sortValues()[0].toString(), equalTo("fname1"));
assertThat(searchResponse.getHits().getAt(0).sortValues()[1].toString(), equalTo("fname1"));
assertThat(searchResponse.getHits().getAt(1).id(), equalTo("1"));
assertThat(searchResponse.getHits().getAt(1).sortValues()[0].toString(), equalTo("fname1"));
assertThat(searchResponse.getHits().getAt(1).sortValues()[1].toString(), equalTo("fname3"));
}
@Test
public void testCheckFixedBitSetCache() throws Exception {
boolean loadFixedBitSeLazily = randomBoolean();
ImmutableSettings.Builder settingsBuilder = ImmutableSettings.builder().put(indexSettings())
.put("index.refresh_interval", -1);
if (loadFixedBitSeLazily) {
settingsBuilder.put("index.load_fixed_bitset_filters_eagerly", false);
}
assertAcked(prepareCreate("test")
.setSettings(settingsBuilder)
.addMapping("type")
);
client().prepareIndex("test", "type", "0").setSource("field", "value").get();
client().prepareIndex("test", "type", "1").setSource("field", "value").get();
refresh();
ensureSearchable("test");
// No nested mapping yet, there shouldn't be anything in the fixed bit set cache
ClusterStatsResponse clusterStatsResponse = client().admin().cluster().prepareClusterStats().get();
assertThat(clusterStatsResponse.getIndicesStats().getSegments().getBitsetMemoryInBytes(), equalTo(0l));
// Now add nested mapping
assertAcked(
client().admin().indices().preparePutMapping("test").setType("type").setSource("array1", "type=nested")
);
XContentBuilder builder = jsonBuilder().startObject()
.startArray("array1").startObject().field("field1", "value1").endObject().endArray()
.endObject();
// index simple data
client().prepareIndex("test", "type", "2").setSource(builder).get();
client().prepareIndex("test", "type", "3").setSource(builder).get();
client().prepareIndex("test", "type", "4").setSource(builder).get();
client().prepareIndex("test", "type", "5").setSource(builder).get();
client().prepareIndex("test", "type", "6").setSource(builder).get();
refresh();
ensureSearchable("test");
if (loadFixedBitSeLazily) {
clusterStatsResponse = client().admin().cluster().prepareClusterStats().get();
assertThat(clusterStatsResponse.getIndicesStats().getSegments().getBitsetMemoryInBytes(), equalTo(0l));
// only when querying with nested the fixed bitsets are loaded
SearchResponse searchResponse = client().prepareSearch("test")
.setQuery(nestedQuery("array1", termQuery("array1.field1", "value1")))
.get();
assertNoFailures(searchResponse);
assertThat(searchResponse.getHits().totalHits(), equalTo(5l));
}
clusterStatsResponse = client().admin().cluster().prepareClusterStats().get();
assertThat(clusterStatsResponse.getIndicesStats().getSegments().getBitsetMemoryInBytes(), greaterThan(0l));
assertAcked(client().admin().indices().prepareDelete("test"));
clusterStatsResponse = client().admin().cluster().prepareClusterStats().get();
assertThat(clusterStatsResponse.getIndicesStats().getSegments().getBitsetMemoryInBytes(), equalTo(0l));
}
/**
*/
private void assertDocumentCount(String index, long numdocs) {
IndicesStatsResponse stats = admin().indices().prepareStats(index).clear().setDocs(true).get();
assertNoFailures(stats);
assertThat(stats.getIndex(index).getPrimaries().docs.getCount(), is(numdocs));
}
} | zuoyebushiwo/ElasticSearch-Final | src/test/java/org/elasticsearch/nested/SimpleNestedTests.java | Java | apache-2.0 | 68,853 |
package jdo.core.repository.specification;
public class Or<E> extends Composite<E> {
public Or(Specification<E> left, Specification<E> right) {
super(left, right);
}
@Override
public boolean isSatisfiedBy(E entity) {
return left.isSatisfiedBy(entity) || right.isSatisfiedBy(entity);
}
}
| JimBarrows/JavaDomainObjects | common/src/main/java/jdo/core/repository/specification/Or.java | Java | apache-2.0 | 299 |
package sprout.oram;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.List;
import org.junit.Test;
import sprout.util.Util;
public class TreeTest
{
public Forest forest;
public TreeTest()
{
// create the tree so we can actually run some tests on it...
try
{
forest = new Forest();
forest.buildFromFile("config/smallConfig.yaml", "config/smallData.txt", "db.bin");
}
catch (NumberFormatException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ForestException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void testLevels()
{
for (int i = 0; i < forest.getNumberOfTrees(); i++)
{
try
{
Util.disp("Working on ORAM-" + i);
Tree t = forest.getTree(i);
long numLeaves = t.getNumLeaves();
for (long l = 0; l < numLeaves; l++)
{
Util.disp("\tFetch leaf path: " + l);
List<Tuple> tuples = t.getPathToLeaf(l);
}
}
catch (ForestException e)
{
e.printStackTrace();
assertEquals(false, true); // this won't happen
}
catch (TreeException e)
{
e.printStackTrace();
assertEquals(false, true); // this won't happen
}
}
}
}
| chris-wood/ORAM3P | test/sprout/oram/TreeTest.java | Java | apache-2.0 | 1,323 |
package servlets;
import accounts.AccountService;
import accounts.UserProfile;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SignUpServlet extends HttpServlet{
private final AccountService accountService;
public SignUpServlet(AccountService accountService) {
this.accountService = accountService;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String login = req.getParameter("login");
String pass = req.getParameter("password");
if(login!=null&&pass!=null) {
UserProfile user = new UserProfile(login,pass,login);
accountService.addNewUser(user);
}
}
}
| nesterione/problem-solving-and-algorithms | problems/Stepic/Java/L2/src/main/java/servlets/SignUpServlet.java | Java | apache-2.0 | 892 |
/*
* 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.phonemetra.deskclock.widget;
import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.phonemetra.deskclock.R;
/**
* A custom {@link View} that exposes an action to the user.
* <p>
* This is a copy of packages/apps/UnifiedEmail/src/com/android/mail/ui/ActionableToastBar.java
* with minor modifications.
*/
public class ActionableToastBar extends LinearLayout {
private boolean mHidden = false;
private Animator mShowAnimation;
private Animator mHideAnimation;
private final int mBottomMarginSizeInConversation;
/** Icon for the description. */
private ImageView mActionDescriptionIcon;
/** The clickable view */
private View mActionButton;
/** Icon for the action button. */
private ImageView mActionIcon;
/** The view that contains the description. */
private TextView mActionDescriptionView;
/** The view that contains the text for the action button. */
private TextView mActionText;
//private ToastBarOperation mOperation;
public ActionableToastBar(Context context) {
this(context, null);
}
public ActionableToastBar(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ActionableToastBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mBottomMarginSizeInConversation = context.getResources().getDimensionPixelSize(
R.dimen.toast_bar_bottom_margin_in_conversation);
LayoutInflater.from(context).inflate(R.layout.actionable_toast_row, this, true);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mActionDescriptionIcon = (ImageView) findViewById(R.id.description_icon);
mActionDescriptionView = (TextView) findViewById(R.id.description_text);
mActionButton = findViewById(R.id.action_button);
mActionIcon = (ImageView)findViewById(R.id.action_icon);
mActionText = (TextView) findViewById(R.id.action_text);
}
/**
* Tells the view that it will be appearing in the conversation pane
* and should adjust its layout parameters accordingly.
* @param isInConversationMode true if the view will be shown in the conversation view
*/
public void setConversationMode(boolean isInConversationMode) {
final FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) getLayoutParams();
params.bottomMargin = isInConversationMode ? mBottomMarginSizeInConversation : 0;
setLayoutParams(params);
}
/**
* Displays the toast bar and makes it visible. Allows the setting of
* parameters to customize the display.
* @param listener performs some action when the action button is clicked
* @param descriptionIconResourceId resource ID for the description icon or
* 0 if no icon should be shown
* @param descriptionText a description text to show in the toast bar
* @param showActionIcon if true, the action button icon should be shown
* @param actionTextResource resource ID for the text to show in the action button
* @param replaceVisibleToast if true, this toast should replace any currently visible toast.
* Otherwise, skip showing this toast.
*/
public void show(final ActionClickedListener listener, int descriptionIconResourceId,
CharSequence descriptionText, boolean showActionIcon, int actionIconResourceId,
int actionTextResource, boolean replaceVisibleToast) {
if (!mHidden && !replaceVisibleToast) {
return;
}
mActionButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View widget) {
if (listener != null) {
listener.onActionClicked();
}
hide(true);
}
});
// Set description icon.
if (descriptionIconResourceId == 0) {
mActionDescriptionIcon.setVisibility(GONE);
} else {
mActionDescriptionIcon.setVisibility(VISIBLE);
mActionDescriptionIcon.setImageResource(descriptionIconResourceId);
}
// Set action icon
if (showActionIcon) {
mActionIcon.setVisibility(VISIBLE);
mActionIcon.setImageResource(actionIconResourceId == 0 ?
R.drawable.ic_menu_revert_holo_dark : actionIconResourceId);
} else {
mActionIcon.setVisibility(GONE);
}
mActionDescriptionView.setText(descriptionText);
if (actionTextResource == 0) {
mActionText.setVisibility(GONE);
} else {
mActionText.setVisibility(VISIBLE);
mActionText.setText(actionTextResource);
}
mHidden = false;
getShowAnimation().start();
}
/**
* Hides the view and resets the state.
*/
public void hide(boolean animate) {
// Prevent multiple call to hide.
// Also prevent hiding if show animation is going on.
if (!mHidden && !getShowAnimation().isRunning()) {
mHidden = true;
if (getVisibility() == View.VISIBLE) {
mActionDescriptionView.setText("");
mActionButton.setOnClickListener(null);
// Hide view once it's clicked.
if (animate) {
getHideAnimation().start();
} else {
setAlpha(0);
setVisibility(View.GONE);
}
}
}
}
private Animator getShowAnimation() {
if (mShowAnimation == null) {
mShowAnimation = AnimatorInflater.loadAnimator(getContext(), R.animator.fade_in);
mShowAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animator animation) {
// There is a tiny change that and hide animation could have finished right
// before the show animation finished. In that case, the hide will mark the
// view as GONE. We need to make sure the last one wins.
setVisibility(View.VISIBLE);
}
});
mShowAnimation.setTarget(this);
}
return mShowAnimation;
}
private Animator getHideAnimation() {
if (mHideAnimation == null) {
mHideAnimation = AnimatorInflater.loadAnimator(getContext(), R.animator.fade_out);
mHideAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
setVisibility(View.GONE);
}
});
mHideAnimation.setTarget(this);
}
return mHideAnimation;
}
public boolean isEventInToastBar(MotionEvent event) {
if (!isShown()) {
return false;
}
int[] xy = new int[2];
float x = event.getX();
float y = event.getY();
getLocationOnScreen(xy);
return (x > xy[0] && x < (xy[0] + getWidth()) && y > xy[1] && y < xy[1] + getHeight());
}
/**
* Classes that wish to perform some action when the action button is clicked
* should implement this interface.
*/
public interface ActionClickedListener {
public void onActionClicked();
}
}
| TurboOS/android_packages_apps_DeskClock | src/com/phonemetra/deskclock/widget/ActionableToastBar.java | Java | apache-2.0 | 8,614 |
package org.openqa.grid.metrics.prometheus;
import com.google.gson.JsonObject;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.openqa.grid.common.exception.RemoteException;
import org.openqa.selenium.ImmutableCapabilities;
import org.openqa.selenium.Platform;
import org.openqa.selenium.remote.http.HttpClient;
import org.openqa.grid.common.RegistrationRequest;
import org.openqa.grid.internal.GridRegistry;
import org.openqa.grid.internal.RemoteProxy;
import org.openqa.grid.internal.TestSession;
import org.openqa.grid.internal.TestSlot;
import org.openqa.grid.internal.listeners.CommandListener;
import org.openqa.grid.internal.listeners.SelfHealingProxy;
import org.openqa.grid.internal.listeners.TestSessionListener;
import org.openqa.grid.internal.listeners.TimeoutListener;
import org.openqa.grid.internal.utils.CapabilityMatcher;
import org.openqa.grid.internal.utils.HtmlRenderer;
import org.openqa.grid.internal.utils.configuration.GridNodeConfiguration;
class InstrumentedRemoteProxy extends Instrumented
implements RemoteProxy, TimeoutListener, SelfHealingProxy, CommandListener, TestSessionListener {
private static final Logger log = Logger.getLogger(InstrumentedRemoteProxy.class.getName());
private RemoteProxy delegate;
public InstrumentedRemoteProxy(RemoteProxy proxy) {
delegate = proxy;
}
public List<TestSlot> getTestSlots() {
return delegate.getTestSlots();
}
public <T extends GridRegistry> T getRegistry() {
return delegate.getRegistry();
}
public CapabilityMatcher getCapabilityHelper() {
return delegate.getCapabilityHelper();
}
public void setupTimeoutListener() {
delegate.setupTimeoutListener();
}
public String getId() {
return delegate.getId();
}
public void teardown() {
delegate.teardown();
}
public GridNodeConfiguration getConfig() {
return delegate.getConfig();
}
public RegistrationRequest getOriginalRegistrationRequest() {
return delegate.getOriginalRegistrationRequest();
}
public int getMaxNumberOfConcurrentTestSessions() {
return delegate.getMaxNumberOfConcurrentTestSessions();
}
public URL getRemoteHost() {
return delegate.getRemoteHost();
}
public TestSession getNewSession(Map<String, Object> requestedCapability) {
TestSession t = delegate.getNewSession(requestedCapability);
if (t != null) {
try {
ImmutableCapabilities c = new ImmutableCapabilities(requestedCapability);
//"browser", "browserVersion", "platform", "platformVersion", "node"
String[] labels = new String[] { c.getBrowserName(), c.getVersion(),
getPlatform(c).toString(),
nodeLabel(t.getSlot()) };
Metrics.testSessionsCount.labels(labels).inc();
Metrics.testSessionsActive.labels(labels).inc();
Metrics.pendingNewSessions.dec();
} catch (Exception e) {
log.warning(e.getLocalizedMessage());
}
}
return t;
}
public int getTotalUsed() {
return delegate.getTotalUsed();
}
/**
* Returns the object responsible for rendering any information about the proxy in a Web application.
*
* @return the renderer.
*/
public HtmlRenderer getHtmlRender() {
return delegate.getHtmlRender();
}
public int getTimeOut() {
return delegate.getTimeOut();
}
public HttpClient getHttpClient(URL url) {
return delegate.getHttpClient(url);
}
public JsonObject getStatus() {
return delegate.getStatus();
}
public Map<String, Object> getProxyStatus() {
return delegate.getProxyStatus();
}
public boolean hasCapability(Map<String, Object> requestedCapability) {
return delegate.hasCapability(requestedCapability);
}
public boolean isBusy() {
return delegate.isBusy();
}
public float getResourceUsageInPercent() {
return delegate.getResourceUsageInPercent();
}
public long getLastSessionStart() {
return delegate.getLastSessionStart();
}
// less busy to more busy.
public int compareTo(RemoteProxy o) {
return delegate.compareTo(o);
}
/**
* Will be run after the proxy slot is reserved for the test, but before the first command is
* forwarded to the remote.
* <p>
* Gives a chance to do a setup on the remote before the test start.
* <p>
* WARNING : beforeSession should NOT throw exception. If an exception is thrown, the session is
* considered invalid and the resources will be freed.
*
* @param session session
* @see RegistrationListener if the setup applies to all the tests.
*/
public void beforeSession(TestSession session) {
if (delegate instanceof TestSessionListener) {
((TestSessionListener) delegate).beforeSession(session);
}
}
/**
* Will be run after the last command is forwarded, but before the proxy slot is released.
* <p>
* If the test crashes before a session is provided by the remote, session.externalKey will be
* null.
* <p>
* WARNING : after session should NOT throw exception. If an exception is thrown, the resources
* will NOT be released, as it could mean the remote is now corrupted.
*
* @param session session
*/
public void afterSession(TestSession session) {
if (delegate instanceof TestSessionListener) {
((TestSessionListener) delegate).afterSession(session);
}
}
/**
* start/restart the polling for the remote proxy. A typical poll will try to contact the remote
* proxy to see if it's still accessible, but it can have more logic in it, like checking the
* resource usage ( RAM etc) on the remote.
*/
public void startPolling() {
if (delegate instanceof SelfHealingProxy) {
((SelfHealingProxy) delegate).startPolling();
}
}
/**
* put the polling on hold.
*/
public void stopPolling() {
if (delegate instanceof SelfHealingProxy) {
((SelfHealingProxy) delegate).stopPolling();
}
}
/**
* Allow to record when something important about the remote state is detected.
*
* @param event RemoteException event to be called when something happens
*/
public void addNewEvent(RemoteException event) {
if (delegate instanceof SelfHealingProxy) {
((SelfHealingProxy) delegate).addNewEvent(event);
}
}
// TODO freynaud pass the list as a param ?
/**
* Allow to process the list of all the events that were detected on this Remote so far. A typical
* implementation of this method will be to put the proxy on hold if the network connection is
* bad, or to restart the remote if the resources used are too important
*
* @param events list of RemoteExceptions occurred
* @param lastInserted last event that occurred
*/
public void onEvent(List<RemoteException> events, RemoteException lastInserted) {
if (delegate instanceof SelfHealingProxy) {
((SelfHealingProxy) delegate).onEvent(events, lastInserted);
}
}
/**
* Executed before the hub forwards the request. reading the content of the request stream will
* prevent the content from being forwarded.
* <p>
* Throwing an exception will prevent the forward to the remote.
*
* @param session session
* @param request request
* @param response response
*/
public void beforeCommand(TestSession session, HttpServletRequest request, HttpServletResponse response) {
if (delegate instanceof CommandListener) {
((CommandListener) delegate).beforeCommand(session, request, response);
}
}
/**
* Executed just before the forwards returns.
* <p>
* Throwing an exception will result in an error for the client.
*
* @param session session
* @param request request
* @param response response
*/
public void afterCommand(TestSession session, HttpServletRequest request, HttpServletResponse response) {
if (delegate instanceof CommandListener) {
((CommandListener) delegate).afterCommand(session, request, response);
}
}
/**
* Gives a chance to clean the resources on the remote when the session has timed out.
* <p>
* Is executed before the session is released to the hub. If an exception is thrown, the slot that
* was associated with the session is considered corrupted and won't be released for future use.
* <p>
* You can check session.getInternalKey before timing out. internalkey==null usually means the
* initial POST /session hasn't been completed yet.For instance if you use web driver, that means
* the browser is in the process of being started. During that state, you can't really clean the
* resources properly.
*
* @param session session
*/
public void beforeRelease(TestSession session) {
if (delegate instanceof TimeoutListener) {
((TimeoutListener) delegate).beforeRelease(session);
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime + (delegate == null ? 0 : delegate.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof InstrumentedRemoteProxy))
return false;
InstrumentedRemoteProxy other = (InstrumentedRemoteProxy) obj;
return delegate == null ? other.delegate == null : delegate.equals(other.delegate);
}
@Override
public String toString() {
return String.format("Instrumented(%s)", delegate == null ? "null" : delegate.toString());
}
}
| jabbrwcky/selenium | java/server/src/org/openqa/grid/metrics/prometheus/InstrumentedRemoteProxy.java | Java | apache-2.0 | 9,605 |
/*
* Copyright (c) 2016-present, RxJava Contributors.
*
* 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 io.reactivex.rxjava3.tck;
import org.reactivestreams.Publisher;
import org.testng.annotations.Test;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.internal.functions.Functions;
@Test
public class DoFinallyTckTest extends BaseTck<Integer> {
@Override
public Publisher<Integer> createPublisher(long elements) {
return
Flowable.range(0, (int)elements).doFinally(Functions.EMPTY_ACTION)
;
}
}
| ReactiveX/RxJava | src/test/java/io/reactivex/rxjava3/tck/DoFinallyTckTest.java | Java | apache-2.0 | 1,074 |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package net.opengis.gml;
import org.eclipse.emf.ecore.EObject;
import org.w3._1999.xlink.ActuateType;
import org.w3._1999.xlink.ShowType;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Vertical Datum Ref Type</b></em>'.
* <!-- end-user-doc -->
*
* <!-- begin-model-doc -->
* Association to a vertical datum, either referencing or containing the definition of that datum.
* <!-- end-model-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link net.opengis.gml.VerticalDatumRefType#getVerticalDatum <em>Vertical Datum</em>}</li>
* <li>{@link net.opengis.gml.VerticalDatumRefType#getActuate <em>Actuate</em>}</li>
* <li>{@link net.opengis.gml.VerticalDatumRefType#getArcrole <em>Arcrole</em>}</li>
* <li>{@link net.opengis.gml.VerticalDatumRefType#getHref <em>Href</em>}</li>
* <li>{@link net.opengis.gml.VerticalDatumRefType#getRemoteSchema <em>Remote Schema</em>}</li>
* <li>{@link net.opengis.gml.VerticalDatumRefType#getRole <em>Role</em>}</li>
* <li>{@link net.opengis.gml.VerticalDatumRefType#getShow <em>Show</em>}</li>
* <li>{@link net.opengis.gml.VerticalDatumRefType#getTitle <em>Title</em>}</li>
* <li>{@link net.opengis.gml.VerticalDatumRefType#getType <em>Type</em>}</li>
* </ul>
* </p>
*
* @see net.opengis.gml.GmlPackage#getVerticalDatumRefType()
* @model extendedMetaData="name='VerticalDatumRefType' kind='elementOnly'"
* @generated
*/
public interface VerticalDatumRefType extends EObject {
/**
* Returns the value of the '<em><b>Vertical Datum</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Vertical Datum</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Vertical Datum</em>' containment reference.
* @see #setVerticalDatum(VerticalDatumType)
* @see net.opengis.gml.GmlPackage#getVerticalDatumRefType_VerticalDatum()
* @model containment="true"
* extendedMetaData="kind='element' name='VerticalDatum' namespace='##targetNamespace'"
* @generated
*/
VerticalDatumType getVerticalDatum();
/**
* Sets the value of the '{@link net.opengis.gml.VerticalDatumRefType#getVerticalDatum <em>Vertical Datum</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Vertical Datum</em>' containment reference.
* @see #getVerticalDatum()
* @generated
*/
void setVerticalDatum(VerticalDatumType value);
/**
* Returns the value of the '<em><b>Actuate</b></em>' attribute.
* The literals are from the enumeration {@link org.w3._1999.xlink.ActuateType}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
*
* The 'actuate' attribute is used to communicate the desired timing
* of traversal from the starting resource to the ending resource;
* it's value should be treated as follows:
* onLoad - traverse to the ending resource immediately on loading
* the starting resource
* onRequest - traverse from the starting resource to the ending
* resource only on a post-loading event triggered for
* this purpose
* other - behavior is unconstrained; examine other markup in link
* for hints
* none - behavior is unconstrained
*
* <!-- end-model-doc -->
* @return the value of the '<em>Actuate</em>' attribute.
* @see org.w3._1999.xlink.ActuateType
* @see #isSetActuate()
* @see #unsetActuate()
* @see #setActuate(ActuateType)
* @see net.opengis.gml.GmlPackage#getVerticalDatumRefType_Actuate()
* @model unsettable="true"
* extendedMetaData="kind='attribute' name='actuate' namespace='http://www.w3.org/1999/xlink'"
* @generated
*/
ActuateType getActuate();
/**
* Sets the value of the '{@link net.opengis.gml.VerticalDatumRefType#getActuate <em>Actuate</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Actuate</em>' attribute.
* @see org.w3._1999.xlink.ActuateType
* @see #isSetActuate()
* @see #unsetActuate()
* @see #getActuate()
* @generated
*/
void setActuate(ActuateType value);
/**
* Unsets the value of the '{@link net.opengis.gml.VerticalDatumRefType#getActuate <em>Actuate</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetActuate()
* @see #getActuate()
* @see #setActuate(ActuateType)
* @generated
*/
void unsetActuate();
/**
* Returns whether the value of the '{@link net.opengis.gml.VerticalDatumRefType#getActuate <em>Actuate</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Actuate</em>' attribute is set.
* @see #unsetActuate()
* @see #getActuate()
* @see #setActuate(ActuateType)
* @generated
*/
boolean isSetActuate();
/**
* Returns the value of the '<em><b>Arcrole</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Arcrole</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Arcrole</em>' attribute.
* @see #setArcrole(String)
* @see net.opengis.gml.GmlPackage#getVerticalDatumRefType_Arcrole()
* @model dataType="org.eclipse.emf.ecore.xml.type.AnyURI"
* extendedMetaData="kind='attribute' name='arcrole' namespace='http://www.w3.org/1999/xlink'"
* @generated
*/
String getArcrole();
/**
* Sets the value of the '{@link net.opengis.gml.VerticalDatumRefType#getArcrole <em>Arcrole</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Arcrole</em>' attribute.
* @see #getArcrole()
* @generated
*/
void setArcrole(String value);
/**
* Returns the value of the '<em><b>Href</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Href</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Href</em>' attribute.
* @see #setHref(String)
* @see net.opengis.gml.GmlPackage#getVerticalDatumRefType_Href()
* @model dataType="org.eclipse.emf.ecore.xml.type.AnyURI"
* extendedMetaData="kind='attribute' name='href' namespace='http://www.w3.org/1999/xlink'"
* @generated
*/
String getHref();
/**
* Sets the value of the '{@link net.opengis.gml.VerticalDatumRefType#getHref <em>Href</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Href</em>' attribute.
* @see #getHref()
* @generated
*/
void setHref(String value);
/**
* Returns the value of the '<em><b>Remote Schema</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Reference to an XML Schema fragment that specifies the content model of the propertys value. This is in conformance with the XML Schema Section 4.14 Referencing Schemas from Elsewhere.
* <!-- end-model-doc -->
* @return the value of the '<em>Remote Schema</em>' attribute.
* @see #setRemoteSchema(String)
* @see net.opengis.gml.GmlPackage#getVerticalDatumRefType_RemoteSchema()
* @model dataType="org.eclipse.emf.ecore.xml.type.AnyURI"
* extendedMetaData="kind='attribute' name='remoteSchema' namespace='##targetNamespace'"
* @generated
*/
String getRemoteSchema();
/**
* Sets the value of the '{@link net.opengis.gml.VerticalDatumRefType#getRemoteSchema <em>Remote Schema</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Remote Schema</em>' attribute.
* @see #getRemoteSchema()
* @generated
*/
void setRemoteSchema(String value);
/**
* Returns the value of the '<em><b>Role</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Role</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Role</em>' attribute.
* @see #setRole(String)
* @see net.opengis.gml.GmlPackage#getVerticalDatumRefType_Role()
* @model dataType="org.eclipse.emf.ecore.xml.type.AnyURI"
* extendedMetaData="kind='attribute' name='role' namespace='http://www.w3.org/1999/xlink'"
* @generated
*/
String getRole();
/**
* Sets the value of the '{@link net.opengis.gml.VerticalDatumRefType#getRole <em>Role</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Role</em>' attribute.
* @see #getRole()
* @generated
*/
void setRole(String value);
/**
* Returns the value of the '<em><b>Show</b></em>' attribute.
* The literals are from the enumeration {@link org.w3._1999.xlink.ShowType}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
*
* The 'show' attribute is used to communicate the desired presentation
* of the ending resource on traversal from the starting resource; it's
* value should be treated as follows:
* new - load ending resource in a new window, frame, pane, or other
* presentation context
* replace - load the resource in the same window, frame, pane, or
* other presentation context
* embed - load ending resource in place of the presentation of the
* starting resource
* other - behavior is unconstrained; examine other markup in the
* link for hints
* none - behavior is unconstrained
*
* <!-- end-model-doc -->
* @return the value of the '<em>Show</em>' attribute.
* @see org.w3._1999.xlink.ShowType
* @see #isSetShow()
* @see #unsetShow()
* @see #setShow(ShowType)
* @see net.opengis.gml.GmlPackage#getVerticalDatumRefType_Show()
* @model unsettable="true"
* extendedMetaData="kind='attribute' name='show' namespace='http://www.w3.org/1999/xlink'"
* @generated
*/
ShowType getShow();
/**
* Sets the value of the '{@link net.opengis.gml.VerticalDatumRefType#getShow <em>Show</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Show</em>' attribute.
* @see org.w3._1999.xlink.ShowType
* @see #isSetShow()
* @see #unsetShow()
* @see #getShow()
* @generated
*/
void setShow(ShowType value);
/**
* Unsets the value of the '{@link net.opengis.gml.VerticalDatumRefType#getShow <em>Show</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetShow()
* @see #getShow()
* @see #setShow(ShowType)
* @generated
*/
void unsetShow();
/**
* Returns whether the value of the '{@link net.opengis.gml.VerticalDatumRefType#getShow <em>Show</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Show</em>' attribute is set.
* @see #unsetShow()
* @see #getShow()
* @see #setShow(ShowType)
* @generated
*/
boolean isSetShow();
/**
* Returns the value of the '<em><b>Title</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Title</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Title</em>' attribute.
* @see #setTitle(String)
* @see net.opengis.gml.GmlPackage#getVerticalDatumRefType_Title()
* @model dataType="org.eclipse.emf.ecore.xml.type.String"
* extendedMetaData="kind='attribute' name='title' namespace='http://www.w3.org/1999/xlink'"
* @generated
*/
String getTitle();
/**
* Sets the value of the '{@link net.opengis.gml.VerticalDatumRefType#getTitle <em>Title</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Title</em>' attribute.
* @see #getTitle()
* @generated
*/
void setTitle(String value);
/**
* Returns the value of the '<em><b>Type</b></em>' attribute.
* The default value is <code>"simple"</code>.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Type</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Type</em>' attribute.
* @see #isSetType()
* @see #unsetType()
* @see #setType(String)
* @see net.opengis.gml.GmlPackage#getVerticalDatumRefType_Type()
* @model default="simple" unsettable="true" dataType="org.eclipse.emf.ecore.xml.type.String"
* extendedMetaData="kind='attribute' name='type' namespace='http://www.w3.org/1999/xlink'"
* @generated
*/
String getType();
/**
* Sets the value of the '{@link net.opengis.gml.VerticalDatumRefType#getType <em>Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Type</em>' attribute.
* @see #isSetType()
* @see #unsetType()
* @see #getType()
* @generated
*/
void setType(String value);
/**
* Unsets the value of the '{@link net.opengis.gml.VerticalDatumRefType#getType <em>Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetType()
* @see #getType()
* @see #setType(String)
* @generated
*/
void unsetType();
/**
* Returns whether the value of the '{@link net.opengis.gml.VerticalDatumRefType#getType <em>Type</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Type</em>' attribute is set.
* @see #unsetType()
* @see #getType()
* @see #setType(String)
* @generated
*/
boolean isSetType();
} // VerticalDatumRefType
| markus1978/citygml4emf | de.hub.citygml.emf.ecore/src/net/opengis/gml/VerticalDatumRefType.java | Java | apache-2.0 | 14,078 |
package quark.test;
public class Harness implements io.datawire.quark.runtime.QObject {
public static quark.reflect.Class quark_List_quark_test_Test__ref = quark_md.Root.quark_List_quark_test_Test__md;
public static quark.reflect.Class quark_test_Harness_ref = quark_md.Root.quark_test_Harness_md;
public String pkg;
public java.util.ArrayList<Test> tests = new java.util.ArrayList(java.util.Arrays.asList(new Object[]{}));
public Integer filtered = 0;
public Harness(String pkg) {
(this).pkg = pkg;
}
public void collect(java.util.ArrayList<String> filters) {
java.util.ArrayList<String> names = new java.util.ArrayList((quark.reflect.Class.classes).keySet());
java.util.Collections.sort(names, null);
Integer idx = 0;
String pfx = (this.pkg) + (".");
while ((idx) < ((names).size())) {
String name = (names).get(idx);
if ((Boolean.valueOf((name).startsWith(pfx))) && (Boolean.valueOf((name).endsWith("Test")))) {
quark.reflect.Class klass = quark.reflect.Class.get(name);
java.util.ArrayList<quark.reflect.Method> methods = (klass).getMethods();
Integer jdx = 0;
while ((jdx) < ((methods).size())) {
quark.reflect.Method meth = (methods).get(jdx);
String mname = (meth).getName();
if ((Boolean.valueOf((mname).startsWith("test"))) && ((((meth).getParameters()).size())==(0) || ((Object)(((meth).getParameters()).size()) != null && ((Object) (((meth).getParameters()).size())).equals(0)))) {
Test test = new MethodTest(klass, meth);
if ((test).match(filters)) {
(this.tests).add(test);
} else {
this.filtered = (this.filtered) + (1);
}
}
jdx = (jdx) + (1);
}
}
idx = (idx) + (1);
}
}
public void list() {
Integer idx = 0;
while ((idx) < ((this.tests).size())) {
Test test = (this.tests).get(idx);
do{System.out.println((test).name);System.out.flush();}while(false);
idx = (idx) + (1);
}
}
public void run() {
do{System.out.println(Functions.bold("=============================== starting tests ==============================="));System.out.flush();}while(false);
Integer idx = 0;
Integer failures = 0;
while ((idx) < ((this.tests).size())) {
Test test = (this.tests).get(idx);
(test).start();
(test).run();
(test).stop();
if ((((test).failures).size()) > (0)) {
failures = (failures) + (1);
}
idx = (idx) + (1);
}
Integer passed = ((this.tests).size()) - (failures);
do{System.out.println(Functions.bold("=============================== stopping tests ==============================="));System.out.flush();}while(false);
String result = ((((((("Total: ") + (Integer.toString(((this.tests).size()) + (this.filtered)))) + (", Filtered: ")) + (Integer.toString(this.filtered))) + (", Passed: ")) + (Integer.toString(passed))) + (", Failed: ")) + (Integer.toString(failures));
if ((failures) > (0)) {
do{System.out.println(Functions.red(result));System.out.flush();}while(false);
} else {
do{System.out.println(Functions.green(result));System.out.flush();}while(false);
}
}
public String _getClass() {
return "quark.test.Harness";
}
public Object _getField(String name) {
if ((name)==("pkg") || ((Object)(name) != null && ((Object) (name)).equals("pkg"))) {
return (this).pkg;
}
if ((name)==("tests") || ((Object)(name) != null && ((Object) (name)).equals("tests"))) {
return (this).tests;
}
if ((name)==("filtered") || ((Object)(name) != null && ((Object) (name)).equals("filtered"))) {
return (this).filtered;
}
return null;
}
public void _setField(String name, Object value) {
if ((name)==("pkg") || ((Object)(name) != null && ((Object) (name)).equals("pkg"))) {
(this).pkg = (String) (value);
}
if ((name)==("tests") || ((Object)(name) != null && ((Object) (name)).equals("tests"))) {
(this).tests = (java.util.ArrayList<Test>) (value);
}
if ((name)==("filtered") || ((Object)(name) != null && ((Object) (name)).equals("filtered"))) {
(this).filtered = (Integer) (value);
}
}
}
| bozzzzo/quark | quarkc/test/emit/expected/java/quark/src/main/java/quark/test/Harness.java | Java | apache-2.0 | 4,748 |
/*
* (C) Copyright IBM Corp. 2019, 2020.
*
* 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.ibm.watson.natural_language_understanding.v1.model;
import com.google.gson.annotations.SerializedName;
import com.ibm.cloud.sdk.core.service.model.GenericModel;
/** Tokenization options. */
public class SyntaxOptionsTokens extends GenericModel {
protected Boolean lemma;
@SerializedName("part_of_speech")
protected Boolean partOfSpeech;
/** Builder. */
public static class Builder {
private Boolean lemma;
private Boolean partOfSpeech;
private Builder(SyntaxOptionsTokens syntaxOptionsTokens) {
this.lemma = syntaxOptionsTokens.lemma;
this.partOfSpeech = syntaxOptionsTokens.partOfSpeech;
}
/** Instantiates a new builder. */
public Builder() {}
/**
* Builds a SyntaxOptionsTokens.
*
* @return the new SyntaxOptionsTokens instance
*/
public SyntaxOptionsTokens build() {
return new SyntaxOptionsTokens(this);
}
/**
* Set the lemma.
*
* @param lemma the lemma
* @return the SyntaxOptionsTokens builder
*/
public Builder lemma(Boolean lemma) {
this.lemma = lemma;
return this;
}
/**
* Set the partOfSpeech.
*
* @param partOfSpeech the partOfSpeech
* @return the SyntaxOptionsTokens builder
*/
public Builder partOfSpeech(Boolean partOfSpeech) {
this.partOfSpeech = partOfSpeech;
return this;
}
}
protected SyntaxOptionsTokens(Builder builder) {
lemma = builder.lemma;
partOfSpeech = builder.partOfSpeech;
}
/**
* New builder.
*
* @return a SyntaxOptionsTokens builder
*/
public Builder newBuilder() {
return new Builder(this);
}
/**
* Gets the lemma.
*
* <p>Set this to `true` to return the lemma for each token.
*
* @return the lemma
*/
public Boolean lemma() {
return lemma;
}
/**
* Gets the partOfSpeech.
*
* <p>Set this to `true` to return the part of speech for each token.
*
* @return the partOfSpeech
*/
public Boolean partOfSpeech() {
return partOfSpeech;
}
}
| watson-developer-cloud/java-sdk | natural-language-understanding/src/main/java/com/ibm/watson/natural_language_understanding/v1/model/SyntaxOptionsTokens.java | Java | apache-2.0 | 2,657 |
package com.code.chat;
import java.security.Principal;
import javax.inject.Inject;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.stereotype.Controller;
import com.code.service.impl.ActiveUserService;
@Controller
public class ActiveUserController {
private ActiveUserService activeUserService;
@Inject
public ActiveUserController(ActiveUserService activeUserService) {
this.activeUserService = activeUserService;
}
@MessageMapping("/activeUsers")
public void activeUsers(Message<Object> message) {
Principal user = message.getHeaders().get(SimpMessageHeaderAccessor.USER_HEADER, Principal.class);
activeUserService.mark(user.getName());
}
} | yanchhuong/ngday | src/main/java/com/code/chat/ActiveUserController.java | Java | apache-2.0 | 846 |
/*
* Copyright 2014 NAVER Corp.
*
* 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.baidu.oped.apm.profiler.plugin.xml.transformer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import com.baidu.oped.apm.bootstrap.instrument.MethodFilter;
import com.baidu.oped.apm.bootstrap.interceptor.group.ExecutionPolicy;
import com.baidu.oped.apm.profiler.plugin.DefaultProfilerPluginContext;
import com.baidu.oped.apm.profiler.plugin.xml.FieldInjector;
import com.baidu.oped.apm.profiler.plugin.xml.GetterInjector;
import com.baidu.oped.apm.profiler.plugin.xml.OverrideMethodInjector;
import com.baidu.oped.apm.profiler.plugin.xml.FieldInitializationStrategy.ByConstructor;
import com.baidu.oped.apm.profiler.plugin.xml.interceptor.AnnotatedInterceptorInjector;
import com.baidu.oped.apm.profiler.plugin.xml.interceptor.TargetAnnotatedInterceptorInjector;
public class DefaultClassFileTransformerBuilder implements ClassFileTransformerBuilder, ConditionalClassFileTransformerBuilder, RecipeBuilder<ClassRecipe> {
private final DefaultProfilerPluginContext pluginContext;
private final List<ClassRecipe> recipes = new ArrayList<ClassRecipe>();
private final List<RecipeBuilder<ClassRecipe>> recipeBuilders = new ArrayList<RecipeBuilder<ClassRecipe>>();
private final ClassCondition condition;
private final String targetClassName;
public DefaultClassFileTransformerBuilder(DefaultProfilerPluginContext pluginContext, String targetClassName) {
this(pluginContext, targetClassName, null);
}
private DefaultClassFileTransformerBuilder(DefaultProfilerPluginContext pluginContext, String targetClassName, ClassCondition condition) {
this.pluginContext = pluginContext;
this.targetClassName = targetClassName;
this.condition = condition;
}
@Override
public void conditional(ClassCondition condition, ConditionalClassFileTransformerSetup describer) {
DefaultClassFileTransformerBuilder conditional = new DefaultClassFileTransformerBuilder(pluginContext, targetClassName, condition);
describer.setup(conditional);
recipeBuilders.add(conditional);
}
@Override
public void injectGetter(String getterTyepName, String fieldName) {
recipes.add(new GetterInjector(getterTyepName, fieldName));
}
@Override
public void injectField(String accessorTypeName) {
recipes.add(new FieldInjector(accessorTypeName));
}
@Override
public void injectField(String accessorTypeName, String initialValueType) {
recipes.add(new FieldInjector(accessorTypeName, new ByConstructor(initialValueType)));
}
@Override
public void overrideMethodToDelegate(String name, String... paramTypes) {
recipes.add(new OverrideMethodInjector(name, paramTypes));
}
@Override
public InterceptorBuilder injectInterceptor(String className, Object... constructorArgs) {
TargetAnnotatedInterceptorInjectorBuilder builder = new TargetAnnotatedInterceptorInjectorBuilder(className, constructorArgs);
recipeBuilders.add(builder);
return builder;
}
@Override
public MethodTransformerBuilder editMethods(MethodFilter... filters) {
DefaultMethodEditorBuilder builder = new DefaultMethodEditorBuilder(filters);
recipeBuilders.add(builder);
return builder;
}
@Override
public MethodTransformerBuilder editMethod(String name, String... parameterTypeNames) {
DefaultMethodEditorBuilder builder = new DefaultMethodEditorBuilder(name, parameterTypeNames);
recipeBuilders.add(builder);
return builder;
}
@Override
public ConstructorTransformerBuilder editConstructor(String... parameterTypeNames) {
DefaultMethodEditorBuilder builder = new DefaultMethodEditorBuilder(parameterTypeNames);
recipeBuilders.add(builder);
return builder;
}
@Override
public void weave(String aspectClassName) {
recipes.add(new ClassWeaver(aspectClassName));
}
@Override
public MatchableClassFileTransformer build() {
ClassRecipe recipe = buildClassRecipe();
return new DedicatedClassFileTransformer(pluginContext, targetClassName, recipe);
}
private ClassRecipe buildClassRecipe() {
List<ClassRecipe> recipes = new ArrayList<ClassRecipe>(this.recipes);
for (RecipeBuilder<ClassRecipe> builder : recipeBuilders) {
recipes.add(builder.buildRecipe());
}
if (recipes.isEmpty()) {
throw new IllegalStateException("No class transformation registered");
}
ClassRecipe recipe = recipes.size() == 1 ? recipes.get(0) : new ClassCookBook(recipes);
return recipe;
}
@Override
public ClassRecipe buildRecipe() {
if (condition == null) {
throw new IllegalStateException();
}
ClassRecipe recipe = buildClassRecipe();
return new ConditionalClassRecipe(pluginContext, condition, recipe);
}
private class TargetAnnotatedInterceptorInjectorBuilder implements InterceptorBuilder, RecipeBuilder<ClassRecipe> {
private final String interceptorClassName;
private final Object[] constructorArguments;
private String groupName;
private ExecutionPolicy executionPoint;
public TargetAnnotatedInterceptorInjectorBuilder(String interceptorClassName, Object[] constructorArguments) {
this.interceptorClassName = interceptorClassName;
this.constructorArguments = constructorArguments;
}
@Override
public void group(String groupName) {
group(groupName, ExecutionPolicy.BOUNDARY);
}
@Override
public void group(String groupName, ExecutionPolicy point) {
this.groupName = groupName;
this.executionPoint = point;
}
@Override
public ClassRecipe buildRecipe() {
return new TargetAnnotatedInterceptorInjector(pluginContext, interceptorClassName, constructorArguments, groupName, executionPoint);
}
}
private class AnnotatedInterceptorInjectorBuilder implements InterceptorBuilder, RecipeBuilder<MethodRecipe> {
private final String interceptorClassName;
private final Object[] constructorArguments;
private String groupName;
private ExecutionPolicy executionPoint;
public AnnotatedInterceptorInjectorBuilder(String interceptorClassName, Object[] constructorArguments) {
this.interceptorClassName = interceptorClassName;
this.constructorArguments = constructorArguments;
}
@Override
public void group(String groupName) {
group(groupName, ExecutionPolicy.BOUNDARY);
}
@Override
public void group(String groupName, ExecutionPolicy point) {
this.groupName = groupName;
this.executionPoint = point;
}
@Override
public MethodRecipe buildRecipe() {
return new AnnotatedInterceptorInjector(pluginContext, interceptorClassName, constructorArguments, groupName, executionPoint);
}
}
public class DefaultMethodEditorBuilder implements MethodTransformerBuilder, ConstructorTransformerBuilder, RecipeBuilder<ClassRecipe> {
private final String methodName;
private final String[] parameterTypeNames;
private final MethodFilter[] filters;
private final List<RecipeBuilder<MethodRecipe>> recipeBuilders = new ArrayList<RecipeBuilder<MethodRecipe>>();
private final EnumSet<MethodTransformerProperty> properties = EnumSet.noneOf(MethodTransformerProperty.class);
private MethodTransformerExceptionHandler exceptionHandler;
private DefaultMethodEditorBuilder(String... parameterTypeNames) {
this.methodName = null;
this.parameterTypeNames = parameterTypeNames;
this.filters = null;
}
private DefaultMethodEditorBuilder(String methodName, String... parameterTypeNames) {
this.methodName = methodName;
this.parameterTypeNames = parameterTypeNames;
this.filters = null;
}
private DefaultMethodEditorBuilder(MethodFilter[] filters) {
this.methodName = null;
this.parameterTypeNames = null;
this.filters = filters;
}
@Override
public void property(MethodTransformerProperty... properties) {
this.properties.addAll(Arrays.asList(properties));
}
@Override
public InterceptorBuilder injectInterceptor(String interceptorClassName, Object... constructorArguments) {
AnnotatedInterceptorInjectorBuilder builder = new AnnotatedInterceptorInjectorBuilder(interceptorClassName, constructorArguments);
recipeBuilders.add(builder);
return builder;
}
@Override
public void exceptionHandler(MethodTransformerExceptionHandler handler) {
this.exceptionHandler = handler;
}
@Override
public MethodTransformer buildRecipe() {
List<MethodRecipe> recipes = buildMethodRecipe();
MethodTransformer transformer = buildMethodEditor(recipes);
return transformer;
}
private MethodTransformer buildMethodEditor(List<MethodRecipe> recipes) {
MethodTransformer transformer;
if (filters != null && filters.length > 0) {
transformer = new FilteringMethodTransformer(filters, recipes, exceptionHandler);
} else if (methodName != null) {
transformer = new DedicatedMethodTransformer(methodName, parameterTypeNames, recipes, exceptionHandler, properties.contains(MethodTransformerProperty.IGNORE_IF_NOT_EXIST));
} else {
transformer = new ConstructorTransformer(parameterTypeNames, recipes, exceptionHandler, properties.contains(MethodTransformerProperty.IGNORE_IF_NOT_EXIST));
}
return transformer;
}
private List<MethodRecipe> buildMethodRecipe() {
if (recipeBuilders.isEmpty()) {
// For now, a method transformer without any interceptor is meaningless.
throw new IllegalStateException("No interceptors are defined");
}
List<MethodRecipe> recipes = new ArrayList<MethodRecipe>(recipeBuilders.size());
for (RecipeBuilder<MethodRecipe> builder : recipeBuilders) {
recipes.add(builder.buildRecipe());
}
return recipes;
}
}
}
| masonmei/java-agent | profiler/src/main/java/com/baidu/oped/apm/profiler/plugin/xml/transformer/DefaultClassFileTransformerBuilder.java | Java | apache-2.0 | 11,486 |
/**
* vertigo - simple java starter
*
* Copyright (C) 2013-2018, KleeGroup, [email protected] (http://www.kleegroup.com)
* KleeGroup, Centre d'affaire la Boursidiere - BP 159 - 92357 Le Plessis Robinson Cedex - France
*
* 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 io.vertigo.orchestra.dao.execution;
import javax.inject.Inject;
import java.util.Optional;
import io.vertigo.app.Home;
import io.vertigo.dynamo.task.metamodel.TaskDefinition;
import io.vertigo.dynamo.task.model.Task;
import io.vertigo.dynamo.task.model.TaskBuilder;
import io.vertigo.dynamo.impl.store.util.DAO;
import io.vertigo.dynamo.store.StoreManager;
import io.vertigo.dynamo.store.StoreServices;
import io.vertigo.dynamo.task.TaskManager;
import io.vertigo.orchestra.domain.execution.OActivityWorkspace;
import io.vertigo.lang.Generated;
/**
* This class is automatically generated.
* DO NOT EDIT THIS FILE DIRECTLY.
*/
@Generated
public final class OActivityWorkspaceDAO extends DAO<OActivityWorkspace, java.lang.Long> implements StoreServices {
/**
* Contructeur.
* @param storeManager Manager de persistance
* @param taskManager Manager de Task
*/
@Inject
public OActivityWorkspaceDAO(final StoreManager storeManager, final TaskManager taskManager) {
super(OActivityWorkspace.class, storeManager, taskManager);
}
/**
* Creates a taskBuilder.
* @param name the name of the task
* @return the builder
*/
private static TaskBuilder createTaskBuilder(final String name) {
final TaskDefinition taskDefinition = Home.getApp().getDefinitionSpace().resolve(name, TaskDefinition.class);
return Task.builder(taskDefinition);
}
/**
* Execute la tache TK_GET_ACTIVITY_WORKSPACE.
* @param aceId Long
* @param in Boolean
* @return Option de io.vertigo.orchestra.domain.execution.OActivityWorkspace dtOActivityWorkspace
*/
public Optional<io.vertigo.orchestra.domain.execution.OActivityWorkspace> getActivityWorkspace(final Long aceId, final Boolean in) {
final Task task = createTaskBuilder("TK_GET_ACTIVITY_WORKSPACE")
.addValue("ACE_ID", aceId)
.addValue("IN", in)
.build();
return Optional.ofNullable((io.vertigo.orchestra.domain.execution.OActivityWorkspace) getTaskManager()
.execute(task)
.getResult());
}
}
| KleeGroup/vertigo-addons | vertigo-orchestra/src/main/javagen/io/vertigo/orchestra/dao/execution/OActivityWorkspaceDAO.java | Java | apache-2.0 | 2,794 |
/**
* Copyright (C) 2012 cogroo <[email protected]>
*
* 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.cogroo.tools.chunker2;
import opennlp.tools.util.BeamSearchContextGenerator;
import org.cogroo.tools.featurizer.WordTag;
/**
* Interface for the context generator used in syntactic chunking.
*/
public interface ChunkerContextGenerator extends
BeamSearchContextGenerator<WordTag> {
/**
* Returns the contexts for chunking of the specified index.
*
* @param i
* The index of the token in the specified toks array for which the
* context should be constructed.
* @param toks
* The tokens of the sentence. The <code>toString</code> methods of
* these objects should return the token text.
* @param tags
* The POS tags for the the specified tokens.
* @param preds
* The previous decisions made in the taging of this sequence. Only
* indices less than i will be examined.
* @return An array of predictive contexts on which a model basis its
* decisions.
*/
public String[] getContext(int i, WordTag[] wordTag, String[] preds);
}
| Fichberg/cogroo4 | cogroo-nlp/src/main/java/org/cogroo/tools/chunker2/ChunkerContextGenerator.java | Java | apache-2.0 | 1,688 |
package org.openntf.domino.graph2.builtin;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Comparator;
import java.util.Date;
import java.util.logging.Logger;
import org.openntf.domino.DateTime;
import org.openntf.domino.graph.ElementComparator;
/**
* @author withersp
*
*/
public class DEdgeFrameComparator implements Comparator<DEdgeFrame>, Serializable {
@SuppressWarnings("unused")
private static final Logger log_ = Logger.getLogger(ElementComparator.class.getName());
private static final long serialVersionUID = 1L;
private String[] props_;
private final boolean caseSensitive_;
public DEdgeFrameComparator(final String... props) {
if (props == null || props.length == 0) {
props_ = new String[0];
} else {
props_ = props;
}
caseSensitive_ = false;
}
public DEdgeFrameComparator(final boolean caseSensitive, final String... props) {
if (props == null || props.length == 0) {
props_ = new String[0];
} else {
props_ = props;
}
caseSensitive_ = caseSensitive;
}
@Override
public int compare(final DEdgeFrame o1, final DEdgeFrame o2) {
int result = 0;
result = compareStrs(o1, o2);
return result;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private int compareStrs(final DEdgeFrame arg0, final DEdgeFrame arg1) {
int result = 0;
if (!arg0.getClass().equals(arg1.getClass())) {
return -1;
}
for (String key : props_) {
// First try to get a property
if (arg0.asEdge().getPropertyKeys().contains(key)) {
java.lang.Object v0 = arg0.asEdge().getProperty(key);
java.lang.Object v1 = arg1.asEdge().getProperty(key);
result = compareObjects(v0, v1);
} else {
// Try get + key
Method[] meths = arg0.getClass().getDeclaredMethods();
for (Method crystal : meths) {
if (crystal.getName().equalsIgnoreCase("get" + key)) {
try {
java.lang.Object v0 = crystal.invoke(arg0, (Object) null);
java.lang.Object v1 = crystal.invoke(arg1, (Object) null);
result = compareObjects(v0, v1);
} catch (IllegalAccessException e) {
// TODO: handle exception
} catch (InvocationTargetException e) {
// TODO: handle exception
}
break;
}
}
// Final fallback is getProperty()
java.lang.Object v0 = arg0.asEdge().getProperty(key);
java.lang.Object v1 = arg1.asEdge().getProperty(key);
result = compareObjects(v0, v1);
}
if (result != 0) {
break;
}
}
if (result == 0) {
result = ((Comparable) arg0.asEdge().getId()).compareTo(arg1.asEdge().getId());
// if (result == 0) {
// System.out.println("Element comparator still ended up with match!??!");
// result = -1;
// }
}
return result;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private int compareObjects(final Object arg0, final Object arg1) {
int result = 0;
if (arg0 == null && arg1 == null) {
result = 0;
} else if (arg0 == null) {
return -1;
} else if (arg1 == null) {
return 1;
}
if (arg0 instanceof Number && arg1 instanceof Number) {
double d0 = ((Number) arg0).doubleValue();
double d1 = ((Number) arg1).doubleValue();
if (d0 > d1) {
result = 1;
} else if (d1 > d0) {
result = -1;
}
} else if (arg0 instanceof String && arg1 instanceof String) {
String s0 = (String) arg0;
String s1 = (String) arg1;
if (caseSensitive_) {
result = s0.compareTo(s1);
} else {
result = s0.compareToIgnoreCase(s1);
}
} else if (arg0 instanceof Date && arg1 instanceof Date) {
Date d0 = (Date) arg0;
Date d1 = (Date) arg1;
result = d0.compareTo(d1);
} else if (arg0 instanceof DateTime && arg1 instanceof DateTime) {
DateTime d0 = (DateTime) arg0;
DateTime d1 = (DateTime) arg1;
result = d0.compareTo(d1);
} else if (arg0 != null && arg1 != null) {
if (arg0 instanceof Comparable && arg1 instanceof Comparable) {
result = ((Comparable) arg0).compareTo(arg1);
}
}
return result;
}
}
| rPraml/org.openntf.domino | domino/graph/src/main/java/org/openntf/domino/graph2/builtin/DEdgeFrameComparator.java | Java | apache-2.0 | 4,042 |
package org.ovirt.engine.ui.webadmin.section.main.view.tab.cluster;
import javax.inject.Inject;
import org.ovirt.engine.core.common.businessentities.NetworkStatus;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.network;
import org.ovirt.engine.ui.common.idhandler.ElementIdHandler;
import org.ovirt.engine.ui.common.uicommon.model.SearchableDetailModelProvider;
import org.ovirt.engine.ui.common.widget.table.column.EnumColumn;
import org.ovirt.engine.ui.common.widget.table.column.TextColumnWithTooltip;
import org.ovirt.engine.ui.uicommonweb.UICommand;
import org.ovirt.engine.ui.uicommonweb.models.clusters.ClusterListModel;
import org.ovirt.engine.ui.uicommonweb.models.clusters.ClusterNetworkListModel;
import org.ovirt.engine.ui.webadmin.section.main.presenter.tab.cluster.SubTabClusterNetworkPresenter;
import org.ovirt.engine.ui.webadmin.section.main.view.AbstractSubTabTableView;
import org.ovirt.engine.ui.webadmin.widget.action.WebAdminButtonDefinition;
import org.ovirt.engine.ui.webadmin.widget.table.column.NetworkStatusColumn;
import com.google.gwt.core.client.GWT;
public class SubTabClusterNetworkView extends AbstractSubTabTableView<VDSGroup, network, ClusterListModel, ClusterNetworkListModel>
implements SubTabClusterNetworkPresenter.ViewDef {
interface ViewIdHandler extends ElementIdHandler<SubTabClusterNetworkView> {
ViewIdHandler idHandler = GWT.create(ViewIdHandler.class);
}
@Inject
public SubTabClusterNetworkView(SearchableDetailModelProvider<network, ClusterListModel, ClusterNetworkListModel> modelProvider) {
super(modelProvider);
ViewIdHandler.idHandler.generateAndSetIds(this);
initTable();
initWidget(getTable());
}
void initTable() {
getTable().addColumn(new NetworkStatusColumn(), "", "20px");
TextColumnWithTooltip<network> nameColumn = new TextColumnWithTooltip<network>() {
@Override
public String getValue(network object) {
return object.getname();
}
};
getTable().addColumn(nameColumn, "Name");
TextColumnWithTooltip<network> statusColumn = new EnumColumn<network, NetworkStatus>() {
@Override
public NetworkStatus getRawValue(network object) {
return object.getStatus();
}
};
getTable().addColumn(statusColumn, "Status");
TextColumnWithTooltip<network> roleColumn = new TextColumnWithTooltip<network>() {
@Override
public String getValue(network object) {
// according to ClusterNetworkListView.xaml:45
return object.getis_display() ? "Display" : "";
}
};
getTable().addColumn(roleColumn, "Role");
TextColumnWithTooltip<network> descColumn = new TextColumnWithTooltip<network>() {
@Override
public String getValue(network object) {
return object.getdescription();
}
};
getTable().addColumn(descColumn, "Description");
getTable().addActionButton(new WebAdminButtonDefinition<network>("Add Network") {
@Override
protected UICommand resolveCommand() {
return getDetailModel().getNewNetworkCommand();
}
});
getTable().addActionButton(new WebAdminButtonDefinition<network>("Assign/Detach Networks") {
@Override
protected UICommand resolveCommand() {
return getDetailModel().getManageCommand();
}
});
getTable().addActionButton(new WebAdminButtonDefinition<network>("Set as Display") {
@Override
protected UICommand resolveCommand() {
return getDetailModel().getSetAsDisplayCommand();
}
});
}
}
| Dhandapani/gluster-ovirt | frontend/webadmin/modules/webadmin/src/main/java/org/ovirt/engine/ui/webadmin/section/main/view/tab/cluster/SubTabClusterNetworkView.java | Java | apache-2.0 | 3,924 |
package com.lambdazen.pixy.pipemakers;
import java.util.List;
import java.util.Map;
import com.lambdazen.pixy.PipeMaker;
import com.lambdazen.pixy.PixyDatum;
import com.lambdazen.pixy.PixyPipe;
import com.lambdazen.pixy.VariableGenerator;
import com.lambdazen.pixy.pipes.AdjacentStep;
public class BothLoop3 implements PipeMaker {
@Override
public String getSignature() {
return "bothLoop/3";
}
@Override
public PixyPipe makePipe(List<PixyDatum> bindings, Map<String, PixyDatum> replacements, VariableGenerator varGen) {
return PipeMakerUtils.adjacentLoopPipe(AdjacentStep.both, AdjacentStep.both, bindings, replacements, varGen);
}
}
| lambdazen/pixy | src/main/java/com/lambdazen/pixy/pipemakers/BothLoop3.java | Java | apache-2.0 | 650 |
package tgm.sew.hit.roboterfabrik;
import java.util.LinkedList;
import java.util.Random;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
/**
*
* @author Ari Ayvazyan
* @version 30.09.2013
*
*/
public class Lieferant implements Stoppable {
/**
* der Seed fuer die Zufallszahlen der lieferungen
*/
private long seed;
/**
* Die ID des Mitarbeiters
*/
private LinkedList<Long> id;
/**
* Mit stop() zu setzen, dient um die weitere ausfuehrung zu stoppen.
*/
private boolean stop=false;
/**
* Der Lagermitarbeiter
*/
private LagerMitarbeiter lagerM;
/**
* das Lagerverzeichnis
*/
//private String lagerVerz;
/**
* das sekretariat fuer die ID vergabe
*/
private Sekretariat sekretariat;
/**
* Erstellt einen neuen Lieferanten der neue Teile in den angegebenen pfad liefert.
*
* @param id - die ID des Lieferanten
* @param lagerverzeichnis - Das zu benutzende Verzeichnis
* @param lagerM - Der zu benutzende LagerMitarbeiter
* @param sekretariat - fuer die Bauteil ID vergabe
*/
public Lieferant(LinkedList<Long> id, String lagerVerzeichnis, LagerMitarbeiter lagerM,Sekretariat sekretariat) {
this.id=id;
this.seed=new Random().nextLong();//kann angepasst werden
this.lagerM=lagerM;
//this.lagerVerz=lagerVerzeichnis;
this.sekretariat=sekretariat;
}
/**
*
* @param bestandteilname - Kann Arm, Rumpf, Auge oder Kettenantrieb sein.
*/
protected void liefern(String bestandteilname) {
Logger logger=Logger.getLogger("Arbeitsverlauf");
if(bestandteilname.equalsIgnoreCase("Arm")){
Arm bestandteil=new Arm(this.sekretariat.getBauTeilID()); //erstelle einen neuen Arm mit der vom Sektretariat vergebenen ID
logger.log(Level.INFO, "Neues Teil an einen Lagermitarbeiter geliefert: "+bestandteil.toString());
lagerM.einlagern(bestandteil);
}
if(bestandteilname.equalsIgnoreCase("Rumpf")){
Rumpf bestandteil=new Rumpf(this.sekretariat.getBauTeilID()); //erstelle einen neuen Rumpf mit der vom Sektretariat vergebenen ID
logger.log(Level.INFO, "Neues Teil an einen Lagermitarbeiter geliefert: "+bestandteil.toString());
lagerM.einlagern(bestandteil);
}
if(bestandteilname.equalsIgnoreCase("Auge")){
Auge bestandteil=new Auge(this.sekretariat.getBauTeilID()); //erstelle ein neues Auge mit der vom Sektretariat vergebenen ID
logger.log(Level.INFO, "Neues Teil an einen Lagermitarbeiter geliefert: "+bestandteil.toString());
lagerM.einlagern(bestandteil);
}
if(bestandteilname.equalsIgnoreCase("Kettenantrieb")){
Kettenantrieb bestandteil=new Kettenantrieb(this.sekretariat.getBauTeilID()); //erstelle einen neuen Kettenantrieb mit der vom Sektretariat vergebenen ID
logger.log(Level.INFO, "Neues Teil an einen Lagermitarbeiter geliefert: "+bestandteil.toString());
lagerM.einlagern(bestandteil);
}
if(bestandteilname.equalsIgnoreCase("Antenne")){
Antenne bestandteil=new Antenne(this.sekretariat.getBauTeilID()); //erstelle einen neuen Kettenantrieb mit der vom Sektretariat vergebenen ID
logger.log(Level.INFO, "Neues Teil an einen Lagermitarbeiter geliefert: "+bestandteil.toString());
lagerM.einlagern(bestandteil);
}
if(bestandteilname.equalsIgnoreCase("Greifer")){
Greifer bestandteil=new Greifer(this.sekretariat.getBauTeilID()); //erstelle einen neuen Kettenantrieb mit der vom Sektretariat vergebenen ID
logger.log(Level.INFO, "Neues Teil an einen Lagermitarbeiter geliefert: "+bestandteil.toString());
lagerM.einlagern(bestandteil);
}
}
/**
* @see Stoppable#stop()
*/
public void stop(){
this.stop=true;
}
/**
* @see Runnable#run()
*/
@Override
public void run() {
Random r=new Random(seed);
long arbeitsgeschwindigkeit=100l; //in Millisekunden
while(!stop){//Liefere solange bis stop() aufgerufen wird
try {
Thread.sleep(arbeitsgeschwindigkeit);
} catch (InterruptedException e) {
e.printStackTrace();
}
int bestandTeilZfZahl=r.nextInt(6); //Liefert einen pseudo zufaelligen wert um ein zufaelliges Bestandteil zu erstellen.
switch(bestandTeilZfZahl){
case 0:
liefern("Auge");
liefern("Auge");
break;
case 1:
liefern("Rumpf");
break;
case 2:
liefern("Kettenantrieb");
break;
case 3:
liefern("Arm");
liefern("Arm");
break;
case 4:
liefern("Antenne");
break;
case 5:
liefern("Greifer");
liefern("Greifer");
break;
default: //sollte nie auftreten
System.err.println("Die Zufallszahl liegt ausserhalb der erwarteten Werte. Klassenname: "+getClass().getName());
}
}
}
}
| aayvazyan-tgm/tgm.sew.4ahit.roboterfabrik.Simulation | src/tgm/sew/hit/roboterfabrik/Lieferant.java | Java | apache-2.0 | 4,800 |
package com.github.saksham.hulaki.utils;
import com.github.saksham.hulaki.exceptions.SmtpException;
import com.google.common.collect.Lists;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Properties;
public class EmailSender {
private static final String DEFAULT_CHARSET = "UTF-8";
private String charset = DEFAULT_CHARSET;
private String encoding;
private List<String> additionalHeaderLines = Lists.newArrayList();
private final String smtpHostname;
private final int smtpPort;
private String username;
private String password;
public EmailSender(String smtpHostname, int smtpPort) {
this.smtpHostname = smtpHostname;
this.smtpPort = smtpPort;
}
public void sendEmail(String from, String to, String subject, String body) {
sendEmail(from, new String[]{to}, subject, body);
}
public void sendEmail(String from, MimeMessage... mimeMessages) throws MessagingException {
Session session = newSmtpSession(from);
Transport transport = session.getTransport("smtp");
transport.connect(smtpHostname, smtpPort, username, password);
for(MimeMessage message : mimeMessages) {
if(encoding != null) {
message.setHeader("Content-Transfer-Encoding", encoding);
}
message.setFrom(new InternetAddress(from));
for(String headerLine : additionalHeaderLines) {
message.addHeaderLine(headerLine);
}
transport.sendMessage(message, message.getAllRecipients());
}
transport.close();
}
public void sendEmail(String from, String[] to, String subject, String body) {
Session session = newSmtpSession(from);
try {
MimeMessage message = new MimeMessage(session);
message.setHeader("Content-Type", "text/plain; charset=" + charset + "; format=flowed");
message.setHeader("X-Accept-Language", "pt-br, pt");
List<InternetAddress> recipients = Lists.newArrayList();
for (String email : to) {
recipients.add(new InternetAddress(email, email));
}
message.setFrom(new InternetAddress(from));
message.addRecipients(Message.RecipientType.TO, recipients.toArray(new InternetAddress[recipients.size()]));
message.setSubject(subject);
message.setText(body);
sendEmail(from, message);
} catch (Exception ex) {
throw new SmtpException(ex);
}
}
public Session newSmtpSession(String from) {
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", smtpHostname);
properties.setProperty("mail.smtp.port", Integer.toString(smtpPort));
properties.put("mail.mime.charset", charset);
properties.put("mail.from", from);
return Session.getDefaultInstance(properties);
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public void setCharset(String charset) {
this.charset = charset;
}
public void addHeaderLine(String headerLine) {
additionalHeaderLines.add(headerLine);
}
public void addHeader(String headerKey, String headerValue) {
addHeaderLine(headerKey + ": " + headerValue);
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
}
| saksham/hulaki | src/main/java/com/github/saksham/hulaki/utils/EmailSender.java | Java | apache-2.0 | 3,764 |
package com.ss.editor.ui.dialog.asset.file;
import com.ss.editor.annotation.FxThread;
import com.ss.editor.ui.component.asset.tree.resource.ResourceElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.nio.file.Path;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* The implementation of the {@link AssetEditorDialog} to choose the {@link Path} from asset.
*
* @author JavaSaBr
*/
public class FolderAssetEditorDialog extends AssetEditorDialog<Path> {
public FolderAssetEditorDialog(@NotNull final Consumer<Path> consumer) {
super(consumer);
setOnlyFolders(true);
}
public FolderAssetEditorDialog(@NotNull final Consumer<Path> consumer,
@Nullable final Function<Path, String> validator) {
super(consumer, validator);
setOnlyFolders(true);
}
@Override
@FxThread
protected void processOpen(@NotNull final ResourceElement element) {
super.processOpen(element);
final Consumer<Path> consumer = getConsumer();
consumer.accept(element.getFile());
}
@Override
@FxThread
protected @Nullable Path getObject(@NotNull final ResourceElement element) {
return element.getFile();
}
}
| JavaSaBr/jME3-SpaceShift-Editor | src/main/java/com/ss/editor/ui/dialog/asset/file/FolderAssetEditorDialog.java | Java | apache-2.0 | 1,309 |
/*
* Copyright (c) 2003-2012 Fred Hutchinson Cancer Research Center
*
* 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.fhcrc.cpl.viewer.quant.commandline;
import org.fhcrc.cpl.viewer.commandline.modules.BaseViewerCommandLineModuleImpl;
import org.fhcrc.cpl.viewer.quant.gui.ProteinQuantSummaryFrame;
import org.fhcrc.cpl.viewer.quant.gui.ProteinSummarySelectorFrame;
import org.fhcrc.cpl.viewer.quant.gui.QuantitationReviewer;
import org.fhcrc.cpl.viewer.qa.QAUtilities;
import org.fhcrc.cpl.toolbox.commandline.CommandLineModule;
import org.fhcrc.cpl.toolbox.commandline.CommandLineModuleExecutionException;
import org.fhcrc.cpl.toolbox.commandline.arguments.*;
import org.fhcrc.cpl.toolbox.ApplicationContext;
import org.fhcrc.cpl.toolbox.proteomics.ProteinUtilities;
import org.fhcrc.cpl.toolbox.proteomics.filehandler.ProtXmlReader;
import org.apache.log4j.Logger;
import javax.xml.stream.XMLStreamException;
import java.io.*;
import java.util.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* test
*/
public class ProteinQuantChartsCLM extends BaseViewerCommandLineModuleImpl
implements CommandLineModule
{
protected static Logger _log = Logger.getLogger(ProteinQuantChartsCLM.class);
public File protXmlFile;
public File pepXmlFile;
public File outDir;
public File mzXmlDir;
public Boolean appendOutput = true;
public float minProteinProphet = 0.9f;
public float minHighRatio = 0f;
public float maxLowRatio = 999f;
public Map<String, List<String>> proteinGeneListMap;
public List<ProtXmlReader.Protein> proteins;
public File outFile;
protected ProteinQuantSummaryFrame quantSummaryFrame;
protected boolean hasRun = false;
public ProteinQuantChartsCLM()
{
init(true);
}
public ProteinQuantChartsCLM(boolean shouldCaptureOutputArgs)
{
init(shouldCaptureOutputArgs);
}
protected void init(boolean shouldCaptureOutputArgs)
{
mCommandName = "proteinquantcharts";
CommandLineArgumentDefinition[] argDefs =
{
new FileToReadArgumentDefinition("protxml", true, "ProtXML file with protein " +
"identifications"),
new FileToReadArgumentDefinition("pepxml", false,
"PepXML file containing peptide identifications. If absent, will look in " +
"ProtXML file for location"),
new DirectoryToReadArgumentDefinition("mzxmldir", true, "Directory with mzXML " +
"files from the runs that generated the database search results"),
new DecimalArgumentDefinition("minproteinprophet", false,
"Minimum ProteinProphet group probability for proteins",
minProteinProphet),
new FileToReadArgumentDefinition("protgenefile", false,
"Tab-delimited file associating gene symbols with protein accession numbers"),
new StringListArgumentDefinition("proteins", false,
"Protein(s) whose events you wish to survey. If specifying multiple proteins, " +
"separate names with ','. Leave blank for a table of all proteins.)"),
new FileToReadArgumentDefinition("proteinfile", false,
"File containing protein accessions, one per line"),
new DecimalArgumentDefinition("minhighratio", false,
"Ratios must be higher than this, or lower than maxratio, or both",
minHighRatio),
new DecimalArgumentDefinition("maxlowratio", false,
"Ratios must be lower than this, or higher than minratio, or both",
maxLowRatio),
new StringListArgumentDefinition("genes", false,
"Gene(s) whose events you wish to survey (requires 'protgenefile', " +
"can't be used with 'proteins'). If specifying multiple proteins, " +
"separate names with ','. Leave blank for a table of all proteins.)"),
};
addArgumentDefinitions(argDefs);
if (shouldCaptureOutputArgs)
{
addArgumentDefinition(new DirectoryToWriteArgumentDefinition("outdir", false,
"Base output directory for charts (protein-specific charts will be created in " +
"protein-specific subdirectories)"));
addArgumentDefinition(new FileToWriteArgumentDefinition("out", false,
"Output .tsv file location (if blank, output will be written to a temporary file)"));
addArgumentDefinition(new BooleanArgumentDefinition("appendoutput", false,
"Append output to a file, if that file already exists? (otherwise, remove " +
"existing file)", appendOutput), true);
}
}
public void assignArgumentValues()
throws ArgumentValidationException
{
mzXmlDir = getFileArgumentValue("mzxmldir");
protXmlFile = getFileArgumentValue("protxml");
pepXmlFile = getFileArgumentValue("pepxml");
if (pepXmlFile == null)
{
try
{
ApplicationContext.infoMessage("Finding source PepXML file in ProtXML file " +
protXmlFile.getAbsolutePath() + "...");
List<File> pepXmlFiles = ProteinUtilities.findSourcePepXMLFiles(protXmlFile);
if (pepXmlFiles.size() > 1)
throw new ArgumentValidationException("Multiple PepXML files specified in ProtXML file " +
protXmlFile.getAbsolutePath() +
". Multiple PepXML files per ProtXML file are not currently supported by Qurate.");
pepXmlFile = pepXmlFiles.get(0);
ApplicationContext.infoMessage("Located PepXML file " + pepXmlFile.getAbsolutePath());
}
catch (FileNotFoundException e)
{
throw new ArgumentValidationException("Can't open PepXML file specified in ProtXML file " +
protXmlFile.getAbsolutePath());
}
catch (XMLStreamException e)
{
throw new ArgumentValidationException("Can't open PepXML file specified in ProtXML file " +
protXmlFile.getAbsolutePath());
}
}
if (hasArgumentValue("outdir"))
outDir = getFileArgumentValue("outdir");
if (hasArgumentValue("appendoutput"))
appendOutput = getBooleanArgumentValue("appendoutput");
if (hasArgumentValue("genes"))
{
assertArgumentPresent("protgenefile", "genes");
assertArgumentAbsent("proteins", "genes");
assertArgumentAbsent("proteinfile", "genes");
}
List<String> proteinNames = (List<String>) getArgumentValue("proteins");
if ((proteinNames == null || proteinNames.isEmpty()) && hasArgumentValue("proteinfile"))
{
proteinNames = new ArrayList<String>();
File proteinFile = getFileArgumentValue("proteinfile");
try {
BufferedReader br = new BufferedReader(new FileReader(proteinFile));
while (true) {
String line = br.readLine();
if (line == null)
break;
proteinNames.add(line);
}
} catch(Exception e) {
throw new ArgumentValidationException("Failed to read proteinfile.",e);
}
}
if (proteinNames == null || proteinNames.isEmpty())
{
ApplicationContext.infoMessage("No protein names provided, searching all proteins");
}
else
{
}
minProteinProphet = getFloatArgumentValue("minproteinprophet");
if (hasArgumentValue("out"))
outFile = getFileArgumentValue("out");
File protGeneFile = getFileArgumentValue("protgenefile");
if (protGeneFile != null)
{
try
{
proteinGeneListMap = QAUtilities.loadIpiGeneListMap(protGeneFile);
}
catch (Exception e)
{
throw new ArgumentValidationException("Failed to load protein-gene map file",e);
}
}
List<String> geneNames = (List<String>) getArgumentValue("genes");
if (geneNames != null && !geneNames.isEmpty())
{
//todo: this is inefficient -- reopens the file, rather than using the earlier map to construct this one
try
{
ApplicationContext.infoMessage("Loading gene-protein map....");
Map<String,List<String>> geneIpiListMap = QAUtilities.loadGeneIpiListMap(protGeneFile);
Set<String> proteinNamesTheseGenes = new HashSet<String>();
for (String geneName : geneNames)
{
List<String> proteinsThisGene = null;
if (geneIpiListMap.containsKey(geneName))
{
proteinsThisGene = geneIpiListMap.get(geneName);
}
else
{
//check different case
for (String geneInMap : geneIpiListMap.keySet())
{
if (geneInMap.equalsIgnoreCase(geneName))
{
ApplicationContext.infoMessage("NOTE: for gene " + geneName + ", found similar gene " +
geneInMap + " with different case. Using " + geneInMap);
proteinsThisGene = geneIpiListMap.get(geneInMap);
}
}
}
if (proteinsThisGene == null)
{
ApplicationContext.infoMessage("WARNING: No proteins found for gene " + geneName);
}
else
{
proteinNamesTheseGenes.addAll(proteinsThisGene);
for (String protein : proteinsThisGene)
{
ApplicationContext.infoMessage("Using protein " + protein + " for gene " + geneName);
}
}
}
proteinNames = new ArrayList<String>(proteinNamesTheseGenes);
}
catch (IOException e)
{
throw new ArgumentValidationException("Failed to load protein-gene map file",e);
}
}
if (proteinNames != null && !proteinNames.isEmpty())
loadProteins(proteinNames);
minHighRatio = getFloatArgumentValue("minhighratio");
maxLowRatio = getFloatArgumentValue("maxlowratio");
}
protected void loadProteins(List<String> proteinNames) throws ArgumentValidationException
{
proteins = new ArrayList<ProtXmlReader.Protein>();
try
{
//todo: this will only check the first protein occurrence for quantitation. We could be
//throwing away quantitated proteins that are quantitated in another occurrence
Map<String, ProtXmlReader.Protein> proteinNameProteinMap =
ProteinUtilities.loadFirstProteinOccurrence(protXmlFile, proteinNames, minProteinProphet);
List<String> notFoundProteinNames = new ArrayList<String>();
List<String> unquantitatedProteinNames = new ArrayList<String>();
List<String> okProteinNames = new ArrayList<String>();
for (String proteinName : proteinNames)
{
if (!proteinNameProteinMap.containsKey(proteinName))
notFoundProteinNames.add(proteinName);
else
{
if (proteinNameProteinMap.get(proteinName).getQuantitationRatio() == null)
unquantitatedProteinNames.add(proteinName);
else okProteinNames.add(proteinName);
}
}
if (okProteinNames.isEmpty())
throw new ArgumentValidationException("None of the specified proteins were found, and quantitated, in the protXml file " +
protXmlFile.getAbsolutePath() + " with probability >= " + minProteinProphet);
if (!notFoundProteinNames.isEmpty())
{
StringBuffer message = new StringBuffer("WARNING! Some specified proteins were not found" +
" in file " +
protXmlFile.getAbsolutePath() + " with probability >= " + minProteinProphet + ". Missing protein(s): ");
for (String proteinName : notFoundProteinNames)
message.append(" " + proteinName);
QuantitationReviewer.infoMessage(message.toString());
}
if (!unquantitatedProteinNames.isEmpty())
{
StringBuffer message = new StringBuffer("WARNING!!! Some specified proteins were not quantitated in file " +
protXmlFile.getAbsolutePath() + " with probability >= " + minProteinProphet + ". Unquantitated protein(s): ");
for (String proteinName : unquantitatedProteinNames)
message.append(" " + proteinName);
QuantitationReviewer.infoMessage(message.toString());
}
for (String proteinName : okProteinNames)
{
ProtXmlReader.Protein thisProtein = proteinNameProteinMap.get(proteinName);
if (proteins.contains(thisProtein))
{
ApplicationContext.infoMessage("NOTE: Indistinguishable protein " +
thisProtein.getProteinName() + " used for protein " + proteinName);
}
else
{
String origProteinName = thisProtein.getProteinName();
if (!origProteinName.equals(proteinName))
{
thisProtein.setProteinName(proteinName);
ApplicationContext.infoMessage("NOTE: Using specified protein name " + proteinName +
" instead of original name " + origProteinName + " for indistinguishable protein");
}
proteins.add(thisProtein);
}
}
System.err.println("Done figuring out proteins.");
}
catch (Exception e)
{
throw new ArgumentValidationException("Error loading proteins from file " +
protXmlFile.getAbsolutePath(), e);
}
System.err.println("Done parsing args.");
if (proteins != null)
System.err.println("Proteins to manage: " + proteins.size());
}
/**
* do the actual work
*/
public void execute() throws CommandLineModuleExecutionException
{
System.err.println("execute 1");
final QuantitationReviewer quantReviewer = new QuantitationReviewer(true, false);
System.err.println("execute 2");
quantReviewer.settingsCLM = this;
if (proteins != null)
{
System.err.println("Showing quant summary frame for " + proteins.size() + " proteins...");
quantReviewer.showProteinQuantSummaryFrame(proteins, proteinGeneListMap);
}
else
{
try
{
final ProteinSummarySelectorFrame proteinSummarySelector = new ProteinSummarySelectorFrame();
proteinSummarySelector.setMinProteinProphet(minProteinProphet);
proteinSummarySelector.setMinHighRatio(minHighRatio);
proteinSummarySelector.setMaxLowRatio(maxLowRatio);
proteinSummarySelector.setProteinGeneMap(proteinGeneListMap);
proteinSummarySelector.addSelectionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (proteinSummarySelector.getSelectedProteins() != null &&
!proteinSummarySelector.getSelectedProteins().isEmpty())
{
quantReviewer.showProteinQuantSummaryFrame(proteinSummarySelector.getSelectedProteins());
}
}
}
);
proteinSummarySelector.displayProteins(protXmlFile);
proteinSummarySelector.setVisible(true);
}
catch (Exception e)
{
throw new CommandLineModuleExecutionException("Error opening ProtXML file " +
protXmlFile.getAbsolutePath(),e);
}
}
}
public Map<String, List<String>> getProteinGeneListMap()
{
return proteinGeneListMap;
}
public void setProteinGeneListMap(Map<String, List<String>> proteinGeneListMap)
{
this.proteinGeneListMap = proteinGeneListMap;
}
}
| dhmay/msInspect | src/org/fhcrc/cpl/viewer/quant/commandline/ProteinQuantChartsCLM.java | Java | apache-2.0 | 18,464 |
/*
* Copyright 2008 Marc Boorshtein
*
* 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.sourceforge.myvd.inserts.ldap;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.logging.log4j.Logger;
import net.sourceforge.myvd.types.Password;
import com.novell.ldap.LDAPException;
import com.novell.ldap.LDAPSearchResults;
import com.novell.ldap.util.DN;
public class LDAPConnectionPool {
static Logger logger = org.apache.logging.log4j.LogManager.getLogger(LDAPConnectionPool.class.getName());
ArrayList<ConnectionWrapper> pool;
int maxRetries;
int maxCons;
int minCons;
LDAPConnectionType type;
private LDAPInterceptor interceptor;
public LDAPConnectionPool(LDAPInterceptor interceptor,int minCons,int maxCons,int maxRetries, LDAPConnectionType type,String spmlImpl,boolean isSOAP) throws LDAPException {
this.interceptor = interceptor;
this.minCons = minCons;
this.maxCons = maxCons;
this.maxRetries = maxRetries;
this.type = type;
this.pool = new ArrayList<ConnectionWrapper>();
try {
for (int i=0;i<minCons;i++) {
ConnectionWrapper wrapper = new ConnectionWrapper(this.interceptor);
wrapper.unlock();
wrapper.reConnect();
this.pool.add(wrapper);
}
} catch (Throwable t) {
logger.warn("Could not initialize pool",t);
}
}
public ConnectionWrapper getConnection(DN bindDN,Password pass,boolean force) throws LDAPException {
return this.getConnection(bindDN,pass,force,0);
}
public ConnectionWrapper getConnection(DN bindDN,Password pass,boolean force,int trys) throws LDAPException {
if (trys >= this.maxRetries) {
return null;
}
Iterator<ConnectionWrapper> it = this.pool.iterator();
boolean wasfound = false;
while (it.hasNext()) {
ConnectionWrapper wrapper = it.next();
//See if the connection is locked
if (wrapper.wasLocked()) {
continue;
}
//if there is an available connection, make sure to make a note
wasfound = true;
//if we are binding, we want to return the connection
if (force) {
return wrapper;
}
//check to see if the currnt connection has the right binddn
if ((wrapper.getBindDN() == null && bindDN.toString() == null) || (wrapper.getBindDN() != null && bindDN.equals(wrapper.getBindDN()))) {
return wrapper;
}
//we have not yet found a connection
//so we can re-lock the connection
wrapper.unlock();
}
if (wasfound) {
it = this.pool.iterator();
while (it.hasNext()) {
ConnectionWrapper wrapper = it.next();
//See if the connection is locked
if (wrapper.wasLocked()) {
continue;
}
/*
if (wrapper == null) {
//System.out.println("wrapper is null");
}
if (bindDN == null) {
//System.out.println("bindDN is null");
}
if (wrapper.getBindDN() == null) {
//System.out.println("wrapper.getBindDN is null");
}
if (bindDN.toString() == null) {
//System.out.println("bindDN.toString() is null");
}*/
////System.out.println("?" + wrapper.getBindDN().toString());
if (wrapper.getBindDN() != null && bindDN.toString().equals(wrapper.getBindDN().toString())) {
return wrapper;
} else {
try {
wrapper.bind(bindDN,pass);
return wrapper;
} catch (LDAPException e) {
wrapper.unlock();
wrapper.reBind();
throw e;
}
}
}
}
////System.out.println("max cons:" + this.maxCons + "; cur cons : " + this.pool.size());
if (this.maxCons > this.pool.size()) {
ConnectionWrapper wrapper = new ConnectionWrapper(this.interceptor);
wrapper.wasLocked();
wrapper.reConnect();
//If this is a bind, we only want to do it once
if (! force) {
wrapper.bind(bindDN,pass);
}
this.pool.add(wrapper);
return wrapper;
} else {
this.waitForConnection();
return this.getConnection(bindDN,pass,force,trys + 1);
}
}
private synchronized void waitForConnection() {
try {
this.wait(10000);
} catch (InterruptedException e) {
//dont care
}
}
public synchronized void returnConnection(ConnectionWrapper con) {
con.unlock();
synchronized (this) {
this.notifyAll();
}
}
public void shutDownPool() {
Iterator<ConnectionWrapper> it = this.pool.iterator();
while (it.hasNext()) {
try {
it.next().getConnection().disconnect();
} catch (Throwable t) {
LDAPInterceptor.logger.error("Error disconnecting", t);
}
}
}
public void executeHeartBeat() {
if (logger.isDebugEnabled()) {
logger.debug("Running heartbeats for '" + this.interceptor.getHost() + "'");
}
for (ConnectionWrapper wrapper : this.pool) {
if (logger.isDebugEnabled()) {
logger.debug("Checking for '" + this.interceptor.getHost() + "' / " + wrapper);
}
//skip locked connection
if (! wrapper.wasLocked()) {
if (logger.isDebugEnabled()) {
logger.debug("Sending heartbeat to '" + this.interceptor.getHost() + "' / " + wrapper);
}
//run a heartbeat
try {
//reset the bind
wrapper.bind(new DN(interceptor.proxyDN),new Password(interceptor.proxyPass));
//search
LDAPSearchResults res = wrapper.getConnection().search(interceptor.getRemoteBase().toString(), 0, "(objectClass=*)", new String[]{"1.1"}, false);
while (res.hasMore()) {
res.next();
}
if (logger.isDebugEnabled()) {
logger.debug("Heartbeat successful for '" + this.interceptor.getHost() + "' / " + wrapper);
}
} catch (LDAPException e) {
logger.warn("Could not execute ldap heartbeat for " + this.interceptor.getHost() + "/" + this.interceptor.getPort() + ", recreating connection",e);
try {
wrapper.reConnect();
} catch (LDAPException e1) {
logger.warn("Could not reconnect",e1);
}
}
wrapper.unlock();
} else {
if (logger.isDebugEnabled()) {
logger.debug("Connection locked for '" + this.interceptor.getHost() + "' / " + wrapper);
}
}
}
}
}
| TremoloSecurity/MyVirtualDirectory | src/main/java/net/sourceforge/myvd/inserts/ldap/LDAPConnectionPool.java | Java | apache-2.0 | 6,600 |
/*
* Copyright (c) 2004 World Wide Web Consortium,
*
* (Massachusetts Institute of Technology, European Research Consortium for
* Informatics and Mathematics, Keio University). All Rights Reserved. This
* work is distributed under the W3C(r) Software License [1] 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.
*
* [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231
*/
package mf.org.w3c.dom;
import mf.org.w3c.dom.Node;
/**
* <code>DOMLocator</code> is an interface that describes a location (e.g.
* where an error occurred).
* <p>See also the <a href='http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407'>Document Object Model (DOM) Level 3 Core Specification</a>.
* @since DOM Level 3
*/
public interface DOMLocator {
/**
* The line number this locator is pointing to, or <code>-1</code> if
* there is no column number available.
*/
public int getLineNumber();
/**
* The column number this locator is pointing to, or <code>-1</code> if
* there is no column number available.
*/
public int getColumnNumber();
/**
* The byte offset into the input source this locator is pointing to or
* <code>-1</code> if there is no byte offset available.
*/
public int getByteOffset();
/**
* The UTF-16, as defined in [Unicode] and Amendment 1 of [ISO/IEC 10646], offset into the input source this locator is pointing to or
* <code>-1</code> if there is no UTF-16 offset available.
*/
public int getUtf16Offset();
/**
* The node this locator is pointing to, or <code>null</code> if no node
* is available.
*/
public Node getRelatedNode();
/**
* The URI this locator is pointing to, or <code>null</code> if no URI is
* available.
*/
public String getUri();
}
| BartoszJarocki/boilerpipe-android | src/main/java/mf/org/w3c/dom/DOMLocator.java | Java | apache-2.0 | 1,947 |
package com.pungwe.cms.core.security.controller;
import com.pungwe.cms.config.TestConfig;
import com.pungwe.cms.core.annotations.stereotypes.Block;
import com.pungwe.cms.core.block.impl.BlockConfigImpl;
import com.pungwe.cms.core.block.services.BlockConfigServiceImpl;
import com.pungwe.cms.core.block.services.BlockManagementService;
import com.pungwe.cms.core.block.system.PageTitleBlock;
import com.pungwe.cms.core.config.BaseApplicationConfig;
import com.pungwe.cms.core.module.services.ModuleManagementService;
import com.pungwe.cms.test.AbstractControllerTest;
import com.pungwe.cms.test.AbstractWebTest;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Created by 917903 on 18/04/2016.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration({TestConfig.class, BaseApplicationConfig.class})
@WebAppConfiguration("src/main/resources")
public class LoginControllerTest extends AbstractControllerTest {
@Test
public void testLoginControllerRender() throws Exception {
MvcResult result = mockMvc.perform(get("/login")).andExpect(request().asyncStarted()).andReturn();
result.getAsyncResult();
MvcResult finalResult = mockMvc
.perform(
asyncDispatch(
result
)
)
.andExpect(
status().isOk()
).andExpect(
content().contentType("text/html;charset=UTF-8"))
.andExpect(
view().name("system/html")
).andReturn();
String content = finalResult.getResponse().getContentAsString();
Document doc = Jsoup.parse(content);
assertEquals("Login", doc.select("html head title").text());
assertEquals("Login", doc.select("html body h1").html());
assertEquals(1, doc.select("input[name=username[0].value]").size());
assertEquals(1, doc.select("input[name=password[0].value]").size());
assertEquals(1, doc.select("input[name=submit]").size());
assertEquals("text", doc.select("input[name=username[0].value]").attr("type"));
assertEquals("password", doc.select("input[name=password[0].value]").attr("type"));
assertEquals("submit", doc.select("input[name=submit]").attr("type"));
}
}
| thunderbird/pungwecms | core/src/test/java/com/pungwe/cms/core/security/controller/LoginControllerTest.java | Java | apache-2.0 | 3,368 |
/*
* #%L
* Simple JSF Exporter Primefaces Excel
* %%
* Copyright (C) 2015 A9SKI
* %%
* 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.
* #L%
*/
package com.a9ski.jsf.exporter;
import java.io.File;
import java.io.Serializable;
/**
* Exporter options for {@link DataTableExcelExporter}
*
* @author Kiril Arabadzhiyski
*
*/
public class DataTableExporterOptions implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1075141154058776746L;
private SelectionType selectionType = SelectionType.ALL;
private File templateFile = null;
private int firstHeaderRow = 0;
private int chunkSize = 100;
public SelectionType getSelectionType() {
return selectionType;
}
public void setSelectionType(final SelectionType selectionType) {
this.selectionType = selectionType;
}
/**
* Gets the template file used to construct the export excel.
* @return the template file used to construct the export excel.
*/
public File getTemplateFile() {
return this.templateFile;
}
/**
* Sets the template file used to construct the export excel.
* @param templateFile the template file used to construct the export excel.
*/
public void setTemplateFile(final File templateFile) {
this.templateFile = templateFile;
}
/**
* Gets the first header row (zero based). Default value is 0
* @return the first header row (zero based)
*/
public int getFirstHeaderRow() {
return firstHeaderRow;
}
/**
* Sets the first header row (zero based)
* @param firstHeaderRow the first header row
*/
public void setFirstHeaderRow(int firstHeaderRow) {
this.firstHeaderRow = firstHeaderRow;
}
/**
* Gets the max number of items loaded in the memory. Used only when exporint the entire table
* @return the max number of items loaded in the memory
*/
public int getChunkSize() {
return chunkSize;
}
/**
* Sets the max number of items loaded in the memory. Used only when exporint the entire table
* @param chunkSize
*/
public void setChunkSize(int chunkSize) {
this.chunkSize = chunkSize;
}
}
| thexman/simple-jsf-exporter | simple-jsf-exporter-primefaces-excel/src/main/java/com/a9ski/jsf/exporter/DataTableExporterOptions.java | Java | apache-2.0 | 2,587 |
/*
* Copyright 2014 NAVER Corp.
*
* 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.navercorp.pinpoint.web.alarm;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import org.junit.Test;
import com.navercorp.pinpoint.web.alarm.checker.SlowCountChecker;
import com.navercorp.pinpoint.web.alarm.vo.Rule;
public class CheckerCategoryTest {
@Test
public void createCheckerTest() {
CheckerCategory slowCount = CheckerCategory.getValue("slow count");
Rule rule = new Rule(null, "", CheckerCategory.SLOW_COUNT.getName(), 75, "testGroup", false, false, false, "");
SlowCountChecker checker = (SlowCountChecker) slowCount.createChecker(null, rule);
rule = new Rule(null, "", CheckerCategory.SLOW_COUNT.getName(), 63, "testGroup", false, false, false, "");
SlowCountChecker checker2 = (SlowCountChecker) slowCount.createChecker(null, rule);
assertNotSame(checker, checker2);
assertNotNull(checker);
assertEquals(75, (int)checker.getRule().getThreshold());
assertNotNull(checker2);
assertEquals(63, (int)checker2.getRule().getThreshold());
}
}
| jaehong-kim/pinpoint | web/src/test/java/com/navercorp/pinpoint/web/alarm/CheckerCategoryTest.java | Java | apache-2.0 | 1,830 |
package org.eclipse.jetty.server.handler;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpMethods;
import org.eclipse.jetty.http.HttpParser;
import org.eclipse.jetty.io.AsyncEndPoint;
import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.io.ConnectedEndPoint;
import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.nio.AsyncConnection;
import org.eclipse.jetty.io.nio.IndirectNIOBuffer;
import org.eclipse.jetty.io.nio.SelectChannelEndPoint;
import org.eclipse.jetty.io.nio.SelectorManager;
import org.eclipse.jetty.server.AbstractHttpConnection;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.HostMap;
import org.eclipse.jetty.util.TypeUtil;
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.ThreadPool;
/**
* <p>Implementation of a tunneling proxy that supports HTTP CONNECT.</p>
* <p>To work as CONNECT proxy, objects of this class must be instantiated using the no-arguments
* constructor, since the remote server information will be present in the CONNECT URI.</p>
*/
public class ConnectHandler extends HandlerWrapper
{
private static final Logger LOG = Log.getLogger(ConnectHandler.class);
private final SelectorManager _selectorManager = new Manager();
private volatile int _connectTimeout = 5000;
private volatile int _writeTimeout = 30000;
private volatile ThreadPool _threadPool;
private volatile boolean _privateThreadPool;
private HostMap<String> _white = new HostMap<String>();
private HostMap<String> _black = new HostMap<String>();
public ConnectHandler()
{
this(null);
}
public ConnectHandler(String[] white, String[] black)
{
this(null, white, black);
}
public ConnectHandler(Handler handler)
{
setHandler(handler);
}
public ConnectHandler(Handler handler, String[] white, String[] black)
{
setHandler(handler);
set(white, _white);
set(black, _black);
}
/**
* @return the timeout, in milliseconds, to connect to the remote server
*/
public int getConnectTimeout()
{
return _connectTimeout;
}
/**
* @param connectTimeout the timeout, in milliseconds, to connect to the remote server
*/
public void setConnectTimeout(int connectTimeout)
{
_connectTimeout = connectTimeout;
}
/**
* @return the timeout, in milliseconds, to write data to a peer
*/
public int getWriteTimeout()
{
return _writeTimeout;
}
/**
* @param writeTimeout the timeout, in milliseconds, to write data to a peer
*/
public void setWriteTimeout(int writeTimeout)
{
_writeTimeout = writeTimeout;
}
@Override
public void setServer(Server server)
{
super.setServer(server);
server.getContainer().update(this, null, _selectorManager, "selectManager");
if (_privateThreadPool)
server.getContainer().update(this, null, _privateThreadPool, "threadpool", true);
else
_threadPool = server.getThreadPool();
}
/**
* @return the thread pool
*/
public ThreadPool getThreadPool()
{
return _threadPool;
}
/**
* @param threadPool the thread pool
*/
public void setThreadPool(ThreadPool threadPool)
{
if (getServer() != null)
getServer().getContainer().update(this, _privateThreadPool ? _threadPool : null, threadPool, "threadpool", true);
_privateThreadPool = threadPool != null;
_threadPool = threadPool;
}
@Override
protected void doStart() throws Exception
{
super.doStart();
if (_threadPool == null)
{
_threadPool = getServer().getThreadPool();
_privateThreadPool = false;
}
if (_threadPool instanceof LifeCycle && !((LifeCycle)_threadPool).isRunning())
((LifeCycle)_threadPool).start();
_selectorManager.start();
}
@Override
protected void doStop() throws Exception
{
_selectorManager.stop();
ThreadPool threadPool = _threadPool;
if (_privateThreadPool && _threadPool != null && threadPool instanceof LifeCycle)
((LifeCycle)threadPool).stop();
super.doStop();
}
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
if (HttpMethods.CONNECT.equalsIgnoreCase(request.getMethod()))
{
LOG.debug("CONNECT request for {}", request.getRequestURI());
try
{
handleConnect(baseRequest, request, response, request.getRequestURI());
}
catch(Exception e)
{
LOG.warn("ConnectHandler "+baseRequest.getUri()+" "+ e);
LOG.debug(e);
}
}
else
{
super.handle(target, baseRequest, request, response);
}
}
/**
* <p>Handles a CONNECT request.</p>
* <p>CONNECT requests may have authentication headers such as <code>Proxy-Authorization</code>
* that authenticate the client with the proxy.</p>
*
* @param baseRequest Jetty-specific http request
* @param request the http request
* @param response the http response
* @param serverAddress the remote server address in the form {@code host:port}
* @throws ServletException if an application error occurs
* @throws IOException if an I/O error occurs
*/
protected void handleConnect(Request baseRequest, HttpServletRequest request, HttpServletResponse response, String serverAddress) throws ServletException, IOException
{
boolean proceed = handleAuthentication(request, response, serverAddress);
if (!proceed)
return;
String host = serverAddress;
int port = 80;
int colon = serverAddress.indexOf(':');
if (colon > 0)
{
host = serverAddress.substring(0, colon);
port = Integer.parseInt(serverAddress.substring(colon + 1));
}
if (!validateDestination(host))
{
LOG.info("ProxyHandler: Forbidden destination " + host);
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
baseRequest.setHandled(true);
return;
}
SocketChannel channel = connectToServer(request, host, port);
// Transfer unread data from old connection to new connection
// We need to copy the data to avoid races:
// 1. when this unread data is written and the server replies before the clientToProxy
// connection is installed (it is only installed after returning from this method)
// 2. when the client sends data before this unread data has been written.
AbstractHttpConnection httpConnection = AbstractHttpConnection.getCurrentConnection();
Buffer headerBuffer = ((HttpParser)httpConnection.getParser()).getHeaderBuffer();
Buffer bodyBuffer = ((HttpParser)httpConnection.getParser()).getBodyBuffer();
int length = headerBuffer == null ? 0 : headerBuffer.length();
length += bodyBuffer == null ? 0 : bodyBuffer.length();
IndirectNIOBuffer buffer = null;
if (length > 0)
{
buffer = new IndirectNIOBuffer(length);
if (headerBuffer != null)
{
buffer.put(headerBuffer);
headerBuffer.clear();
}
if (bodyBuffer != null)
{
buffer.put(bodyBuffer);
bodyBuffer.clear();
}
}
ConcurrentMap<String, Object> context = new ConcurrentHashMap<String, Object>();
prepareContext(request, context);
ClientToProxyConnection clientToProxy = prepareConnections(context, channel, buffer);
// CONNECT expects a 200 response
response.setStatus(HttpServletResponse.SC_OK);
// Prevent close
baseRequest.getConnection().getGenerator().setPersistent(true);
// Close to force last flush it so that the client receives it
response.getOutputStream().close();
upgradeConnection(request, response, clientToProxy);
}
private ClientToProxyConnection prepareConnections(ConcurrentMap<String, Object> context, SocketChannel channel, Buffer buffer)
{
AbstractHttpConnection httpConnection = AbstractHttpConnection.getCurrentConnection();
ProxyToServerConnection proxyToServer = newProxyToServerConnection(context, buffer);
ClientToProxyConnection clientToProxy = newClientToProxyConnection(context, channel, httpConnection.getEndPoint(), httpConnection.getTimeStamp());
clientToProxy.setConnection(proxyToServer);
proxyToServer.setConnection(clientToProxy);
return clientToProxy;
}
/**
* <p>Handles the authentication before setting up the tunnel to the remote server.</p>
* <p>The default implementation returns true.</p>
*
* @param request the HTTP request
* @param response the HTTP response
* @param address the address of the remote server in the form {@code host:port}.
* @return true to allow to connect to the remote host, false otherwise
* @throws ServletException to report a server error to the caller
* @throws IOException to report a server error to the caller
*/
protected boolean handleAuthentication(HttpServletRequest request, HttpServletResponse response, String address) throws ServletException, IOException
{
return true;
}
protected ClientToProxyConnection newClientToProxyConnection(ConcurrentMap<String, Object> context, SocketChannel channel, EndPoint endPoint, long timeStamp)
{
return new ClientToProxyConnection(context, channel, endPoint, timeStamp);
}
protected ProxyToServerConnection newProxyToServerConnection(ConcurrentMap<String, Object> context, Buffer buffer)
{
return new ProxyToServerConnection(context, buffer);
}
private SocketChannel connectToServer(HttpServletRequest request, String host, int port) throws IOException
{
SocketChannel channel = connect(request, host, port);
channel.configureBlocking(false);
return channel;
}
/**
* <p>Establishes a connection to the remote server.</p>
*
* @param request the HTTP request that initiated the tunnel
* @param host the host to connect to
* @param port the port to connect to
* @return a {@link SocketChannel} connected to the remote server
* @throws IOException if the connection cannot be established
*/
protected SocketChannel connect(HttpServletRequest request, String host, int port) throws IOException
{
SocketChannel channel = SocketChannel.open();
try
{
// Connect to remote server
LOG.debug("Establishing connection to {}:{}", host, port);
channel.socket().setTcpNoDelay(true);
channel.socket().connect(new InetSocketAddress(host, port), getConnectTimeout());
LOG.debug("Established connection to {}:{}", host, port);
return channel;
}
catch (IOException x)
{
LOG.debug("Failed to establish connection to " + host + ":" + port, x);
try
{
channel.close();
}
catch (IOException xx)
{
LOG.ignore(xx);
}
throw x;
}
}
protected void prepareContext(HttpServletRequest request, ConcurrentMap<String, Object> context)
{
}
private void upgradeConnection(HttpServletRequest request, HttpServletResponse response, Connection connection) throws IOException
{
// Set the new connection as request attribute and change the status to 101
// so that Jetty understands that it has to upgrade the connection
request.setAttribute("org.eclipse.jetty.io.Connection", connection);
response.setStatus(HttpServletResponse.SC_SWITCHING_PROTOCOLS);
LOG.debug("Upgraded connection to {}", connection);
}
private void register(SocketChannel channel, ProxyToServerConnection proxyToServer) throws IOException
{
_selectorManager.register(channel, proxyToServer);
proxyToServer.waitReady(_connectTimeout);
}
/**
* <p>Reads (with non-blocking semantic) into the given {@code buffer} from the given {@code endPoint}.</p>
*
* @param endPoint the endPoint to read from
* @param buffer the buffer to read data into
* @param context the context information related to the connection
* @return the number of bytes read (possibly 0 since the read is non-blocking)
* or -1 if the channel has been closed remotely
* @throws IOException if the endPoint cannot be read
*/
protected int read(EndPoint endPoint, Buffer buffer, ConcurrentMap<String, Object> context) throws IOException
{
return endPoint.fill(buffer);
}
/**
* <p>Writes (with blocking semantic) the given buffer of data onto the given endPoint.</p>
*
* @param endPoint the endPoint to write to
* @param buffer the buffer to write
* @param context the context information related to the connection
* @throws IOException if the buffer cannot be written
* @return the number of bytes written
*/
protected int write(EndPoint endPoint, Buffer buffer, ConcurrentMap<String, Object> context) throws IOException
{
if (buffer == null)
return 0;
int length = buffer.length();
final StringBuilder debug = LOG.isDebugEnabled()?new StringBuilder():null;
int flushed = endPoint.flush(buffer);
if (debug!=null)
debug.append(flushed);
// Loop until all written
while (buffer.length()>0 && !endPoint.isOutputShutdown())
{
if (!endPoint.isBlocking())
{
boolean ready = endPoint.blockWritable(getWriteTimeout());
if (!ready)
throw new IOException("Write timeout");
}
flushed = endPoint.flush(buffer);
if (debug!=null)
debug.append("+").append(flushed);
}
LOG.debug("Written {}/{} bytes {}", debug, length, endPoint);
buffer.compact();
return length;
}
private class Manager extends SelectorManager
{
@Override
protected SelectChannelEndPoint newEndPoint(SocketChannel channel, SelectSet selectSet, SelectionKey key) throws IOException
{
SelectChannelEndPoint endp = new SelectChannelEndPoint(channel, selectSet, key, channel.socket().getSoTimeout());
endp.setConnection(selectSet.getManager().newConnection(channel,endp, key.attachment()));
endp.setMaxIdleTime(_writeTimeout);
return endp;
}
@Override
public AsyncConnection newConnection(SocketChannel channel, AsyncEndPoint endpoint, Object attachment)
{
ProxyToServerConnection proxyToServer = (ProxyToServerConnection)attachment;
proxyToServer.setTimeStamp(System.currentTimeMillis());
proxyToServer.setEndPoint(endpoint);
return proxyToServer;
}
@Override
protected void endPointOpened(SelectChannelEndPoint endpoint)
{
ProxyToServerConnection proxyToServer = (ProxyToServerConnection)endpoint.getSelectionKey().attachment();
proxyToServer.ready();
}
@Override
public boolean dispatch(Runnable task)
{
return _threadPool.dispatch(task);
}
@Override
protected void endPointClosed(SelectChannelEndPoint endpoint)
{
}
@Override
protected void endPointUpgraded(ConnectedEndPoint endpoint, Connection oldConnection)
{
}
}
public class ProxyToServerConnection implements AsyncConnection
{
private final CountDownLatch _ready = new CountDownLatch(1);
private final Buffer _buffer = new IndirectNIOBuffer(4096);
private final ConcurrentMap<String, Object> _context;
private volatile Buffer _data;
private volatile ClientToProxyConnection _toClient;
private volatile long _timestamp;
private volatile AsyncEndPoint _endPoint;
public ProxyToServerConnection(ConcurrentMap<String, Object> context, Buffer data)
{
_context = context;
_data = data;
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder("ProxyToServer");
builder.append("(:").append(_endPoint.getLocalPort());
builder.append("<=>:").append(_endPoint.getRemotePort());
return builder.append(")").toString();
}
public Connection handle() throws IOException
{
LOG.debug("{}: begin reading from server", this);
try
{
writeData();
while (true)
{
int read = read(_endPoint, _buffer, _context);
if (read == -1)
{
LOG.debug("{}: server closed connection {}", this, _endPoint);
if (_endPoint.isOutputShutdown() || !_endPoint.isOpen())
closeClient();
else
_toClient.shutdownOutput();
break;
}
if (read == 0)
break;
LOG.debug("{}: read from server {} bytes {}", this, read, _endPoint);
int written = write(_toClient._endPoint, _buffer, _context);
LOG.debug("{}: written to {} {} bytes", this, _toClient, written);
}
return this;
}
catch (ClosedChannelException x)
{
LOG.debug(x);
throw x;
}
catch (IOException x)
{
LOG.warn(this + ": unexpected exception", x);
close();
throw x;
}
catch (RuntimeException x)
{
LOG.warn(this + ": unexpected exception", x);
close();
throw x;
}
finally
{
LOG.debug("{}: end reading from server", this);
}
}
public void onInputShutdown() throws IOException
{
// TODO
}
private void writeData() throws IOException
{
// This method is called from handle() and closeServer()
// which may happen concurrently (e.g. a client closing
// while reading from the server), so needs synchronization
synchronized (this)
{
if (_data != null)
{
try
{
int written = write(_endPoint, _data, _context);
LOG.debug("{}: written to server {} bytes", this, written);
}
finally
{
// Attempt once to write the data; if the write fails (for example
// because the connection is already closed), clear the data and
// give up to avoid to continue to write data to a closed connection
_data = null;
}
}
}
}
public void setConnection(ClientToProxyConnection connection)
{
_toClient = connection;
}
public long getTimeStamp()
{
return _timestamp;
}
public void setTimeStamp(long timestamp)
{
_timestamp = timestamp;
}
public void setEndPoint(AsyncEndPoint endpoint)
{
_endPoint = endpoint;
}
public boolean isIdle()
{
return false;
}
public boolean isSuspended()
{
return false;
}
public void onClose()
{
}
public void ready()
{
_ready.countDown();
}
public void waitReady(long timeout) throws IOException
{
try
{
_ready.await(timeout, TimeUnit.MILLISECONDS);
}
catch (final InterruptedException x)
{
throw new IOException()
{{
initCause(x);
}};
}
}
public void closeClient() throws IOException
{
_toClient.closeClient();
}
public void closeServer() throws IOException
{
_endPoint.close();
}
public void close()
{
try
{
closeClient();
}
catch (IOException x)
{
LOG.debug(this + ": unexpected exception closing the client", x);
}
try
{
closeServer();
}
catch (IOException x)
{
LOG.debug(this + ": unexpected exception closing the server", x);
}
}
public void shutdownOutput() throws IOException
{
writeData();
_endPoint.shutdownOutput();
}
public void onIdleExpired(long idleForMs)
{
try
{
shutdownOutput();
}
catch(Exception e)
{
LOG.debug(e);
close();
}
}
}
public class ClientToProxyConnection implements AsyncConnection
{
private final Buffer _buffer = new IndirectNIOBuffer(4096);
private final ConcurrentMap<String, Object> _context;
private final SocketChannel _channel;
private final EndPoint _endPoint;
private final long _timestamp;
private volatile ProxyToServerConnection _toServer;
private boolean _firstTime = true;
public ClientToProxyConnection(ConcurrentMap<String, Object> context, SocketChannel channel, EndPoint endPoint, long timestamp)
{
_context = context;
_channel = channel;
_endPoint = endPoint;
_timestamp = timestamp;
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder("ClientToProxy");
builder.append("(:").append(_endPoint.getLocalPort());
builder.append("<=>:").append(_endPoint.getRemotePort());
return builder.append(")").toString();
}
public Connection handle() throws IOException
{
LOG.debug("{}: begin reading from client", this);
try
{
if (_firstTime)
{
_firstTime = false;
register(_channel, _toServer);
LOG.debug("{}: registered channel {} with connection {}", this, _channel, _toServer);
}
while (true)
{
int read = read(_endPoint, _buffer, _context);
if (read == -1)
{
LOG.debug("{}: client closed connection {}", this, _endPoint);
if (_endPoint.isOutputShutdown() || !_endPoint.isOpen())
closeServer();
else
_toServer.shutdownOutput();
break;
}
if (read == 0)
break;
LOG.debug("{}: read from client {} bytes {}", this, read, _endPoint);
int written = write(_toServer._endPoint, _buffer, _context);
LOG.debug("{}: written to {} {} bytes", this, _toServer, written);
}
return this;
}
catch (ClosedChannelException x)
{
LOG.debug(x);
closeServer();
throw x;
}
catch (IOException x)
{
LOG.warn(this + ": unexpected exception", x);
close();
throw x;
}
catch (RuntimeException x)
{
LOG.warn(this + ": unexpected exception", x);
close();
throw x;
}
finally
{
LOG.debug("{}: end reading from client", this);
}
}
public void onInputShutdown() throws IOException
{
// TODO
}
public long getTimeStamp()
{
return _timestamp;
}
public boolean isIdle()
{
return false;
}
public boolean isSuspended()
{
return false;
}
public void onClose()
{
}
public void setConnection(ProxyToServerConnection connection)
{
_toServer = connection;
}
public void closeClient() throws IOException
{
_endPoint.close();
}
public void closeServer() throws IOException
{
_toServer.closeServer();
}
public void close()
{
try
{
closeClient();
}
catch (IOException x)
{
LOG.debug(this + ": unexpected exception closing the client", x);
}
try
{
closeServer();
}
catch (IOException x)
{
LOG.debug(this + ": unexpected exception closing the server", x);
}
}
public void shutdownOutput() throws IOException
{
_endPoint.shutdownOutput();
}
public void onIdleExpired(long idleForMs)
{
try
{
shutdownOutput();
}
catch(Exception e)
{
LOG.debug(e);
close();
}
}
}
/**
* Add a whitelist entry to an existing handler configuration
*
* @param entry new whitelist entry
*/
public void addWhite(String entry)
{
add(entry, _white);
}
/**
* Add a blacklist entry to an existing handler configuration
*
* @param entry new blacklist entry
*/
public void addBlack(String entry)
{
add(entry, _black);
}
/**
* Re-initialize the whitelist of existing handler object
*
* @param entries array of whitelist entries
*/
public void setWhite(String[] entries)
{
set(entries, _white);
}
/**
* Re-initialize the blacklist of existing handler object
*
* @param entries array of blacklist entries
*/
public void setBlack(String[] entries)
{
set(entries, _black);
}
/**
* Helper method to process a list of new entries and replace
* the content of the specified host map
*
* @param entries new entries
* @param hostMap target host map
*/
protected void set(String[] entries, HostMap<String> hostMap)
{
hostMap.clear();
if (entries != null && entries.length > 0)
{
for (String addrPath : entries)
{
add(addrPath, hostMap);
}
}
}
/**
* Helper method to process the new entry and add it to
* the specified host map.
*
* @param entry new entry
* @param hostMap target host map
*/
private void add(String entry, HostMap<String> hostMap)
{
if (entry != null && entry.length() > 0)
{
entry = entry.trim();
if (hostMap.get(entry) == null)
{
hostMap.put(entry, entry);
}
}
}
/**
* Check the request hostname against white- and blacklist.
*
* @param host hostname to check
* @return true if hostname is allowed to be proxied
*/
public boolean validateDestination(String host)
{
if (_white.size() > 0)
{
Object whiteObj = _white.getLazyMatches(host);
if (whiteObj == null)
{
return false;
}
}
if (_black.size() > 0)
{
Object blackObj = _black.getLazyMatches(host);
if (blackObj != null)
{
return false;
}
}
return true;
}
@Override
public void dump(Appendable out, String indent) throws IOException
{
dumpThis(out);
if (_privateThreadPool)
dump(out, indent, Arrays.asList(_threadPool, _selectorManager), TypeUtil.asList(getHandlers()), getBeans());
else
dump(out, indent, Arrays.asList(_selectorManager), TypeUtil.asList(getHandlers()), getBeans());
}
}
| thomasbecker/jetty-spdy | jetty-server/src/main/java/org/eclipse/jetty/server/handler/ConnectHandler.java | Java | apache-2.0 | 30,481 |
package com.github.athi.athifx.test.views;
import com.github.athi.athifx.gui.menu.item.DisableEnableAMenuItemEvent;
import com.github.athi.athifx.gui.navigation.view.AView;
import com.github.athi.athifx.gui.navigation.view.View;
import com.github.athi.athifx.test.configuration.TestItems;
import com.google.common.eventbus.EventBus;
import com.google.inject.Inject;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javax.annotation.PostConstruct;
/**
* Created by Athi
*/
@View(itemId = 4)
public class ItemFourView extends AView {
private static final String VIEW_NAME = ItemFourView.class.getSimpleName();
@Inject
private EventBus eventBus;
@PostConstruct
public void initItemFourView() {
getChildren().add(new Label(VIEW_NAME));
Button disableButton = new Button("Disable/Enable item3");
disableButton.setOnAction(event -> eventBus.post(new DisableEnableAMenuItemEvent(TestItems.ITEM_THREE)));
this.getChildren().addAll(disableButton);
}
@Override
public void enter() {
System.out.println("ENTER: " + VIEW_NAME);
}
}
| Athi/athifx | athi-fx-test/src/main/java/com/github/athi/athifx/test/views/ItemFourView.java | Java | apache-2.0 | 1,137 |
package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_0148 {
}
| lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_0148.java | Java | apache-2.0 | 151 |
package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_3576 {
}
| lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_3576.java | Java | apache-2.0 | 151 |
package ru.stqa.pft.mantis.tests;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.lanwen.verbalregex.VerbalExpression;
import ru.stqa.pft.mantis.model.MailMessage;
import ru.stqa.pft.mantis.model.Users;
import javax.xml.rpc.ServiceException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.List;
import static org.testng.AssertJUnit.assertTrue;
public class ChangePasswordTest extends BaseTest {
@BeforeMethod
public void startMailServer() throws RemoteException, ServiceException, MalformedURLException {
//Проверяю есть ли открытый баг по данному тесту, если есть - пропускаю тест
skipIfNotFixed(0000001);
app.mail().start();
}
@Test
public void testChangePassword() throws IOException, SQLException, ServiceException {
//Авторизуемся под администратором
app.web().loginWeb("administrator", "root");
//Выбираем пользователя, которому меняем пароль
Users user = app.db().listUsers().iterator().next();
//Отправляем ссылку на смену пароля пользователю
app.web().resetPassword(user.getUsername());
//Получаем ссылку и пользователь меняет пароль
List<MailMessage> mailMessages = app.mail().waitForMail(1, 10000);
String confirmationLink = findConfirmationLink(mailMessages, user.getEmail());
String newPassword = "newPassword";
app.registration().finish(confirmationLink, newPassword);
//Проверяем, что пользователь может авторизоваться с новым паролем
assertTrue(app.newSession().login(user.getUsername(), newPassword));
}
//Среди потокока писем, находит письмо отправленное на конкретный email и возвращает ссылку из письма
private String findConfirmationLink(List<MailMessage> mailMessages, String email) {
MailMessage mailMessage = mailMessages.stream().filter((m) -> m.to.equals(email)).findFirst().get();
VerbalExpression regex = VerbalExpression.regex().find("http://").nonSpace().oneOrMore().build();
return regex.getText(mailMessage.text);
}
@AfterMethod(alwaysRun = true)
public void stopMailServer() {
app.mail().stop();
}
}
| semyonova/java_test | mantis-tests/src/test/java/ru/stqa/pft/mantis/tests/ChangePasswordTest.java | Java | apache-2.0 | 2,581 |
package android.database;
/*
* #%L
* Matos
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2010 - 2014 Orange SA
* %%
* 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.
* #L%
*/
@com.francetelecom.rd.stubs.annotation.ClassDone(0)
public class CursorWrapper
implements Cursor
{
// Constructors
public CursorWrapper(Cursor arg1){
}
// Methods
public short getShort(int arg1){
return (short) 0;
}
public int getInt(int arg1){
return 0;
}
public long getLong(int arg1){
return 0l;
}
public float getFloat(int arg1){
return 0.0f;
}
public double getDouble(int arg1){
return 0.0d;
}
public void close(){
}
public int getType(int arg1){
return 0;
}
public java.lang.String getString(int arg1){
return (java.lang.String) null;
}
public boolean isFirst(){
return false;
}
public boolean isClosed(){
return false;
}
public int getCount(){
return 0;
}
public void registerDataSetObserver(@com.francetelecom.rd.stubs.annotation.CallBackRegister("android.database.DataSetObserver.onChanged") DataSetObserver arg1){
}
public void unregisterDataSetObserver(DataSetObserver arg1){
}
public int getPosition(){
return 0;
}
public boolean requery(){
return false;
}
public android.os.Bundle getExtras(){
return (android.os.Bundle) null;
}
public void deactivate(){
}
public java.lang.String [] getColumnNames(){
return (java.lang.String []) null;
}
public int getColumnIndex(java.lang.String arg1){
return 0;
}
public boolean isNull(int arg1){
return false;
}
public byte [] getBlob(int arg1){
return (byte []) null;
}
public void copyStringToBuffer(int arg1, CharArrayBuffer arg2){
}
public int getColumnIndexOrThrow(java.lang.String arg1) throws java.lang.IllegalArgumentException{
return 0;
}
public boolean moveToNext(){
return false;
}
public boolean moveToFirst(){
return false;
}
public boolean isAfterLast(){
return false;
}
public boolean moveToPosition(int arg1){
return false;
}
public void registerContentObserver(@com.francetelecom.rd.stubs.annotation.CallBackRegister("android.database.ContentObserver.onChange") ContentObserver arg1){
}
public void unregisterContentObserver(ContentObserver arg1){
}
public boolean move(int arg1){
return false;
}
public int getColumnCount(){
return 0;
}
public boolean moveToLast(){
return false;
}
public boolean moveToPrevious(){
return false;
}
public boolean isLast(){
return false;
}
public boolean isBeforeFirst(){
return false;
}
public java.lang.String getColumnName(int arg1){
return (java.lang.String) null;
}
public void setNotificationUri(android.content.ContentResolver arg1, android.net.Uri arg2){
}
public boolean getWantsAllOnMoveCalls(){
return false;
}
public android.os.Bundle respond(android.os.Bundle arg1){
return (android.os.Bundle) null;
}
public Cursor getWrappedCursor(){
return (Cursor) null;
}
}
| Orange-OpenSource/matos-profiles | matos-android/src/main/java/android/database/CursorWrapper.java | Java | apache-2.0 | 3,567 |
/*
* Copyright (c) 2019 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.05.20 at 05:41:15 PM CEST
//
package com.evolveum.prism.xml.ns._public.types_3;
import com.evolveum.midpoint.prism.delta.PlusMinusZero;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
import java.io.Serializable;
@XmlType(name = "PlusMinusZeroType")
@XmlEnum
public enum PlusMinusZeroType implements Serializable {
@XmlEnumValue("plus")
PLUS("plus", PlusMinusZero.PLUS),
@XmlEnumValue("minus")
MINUS("minus", PlusMinusZero.MINUS),
@XmlEnumValue("zero")
ZERO("zero", PlusMinusZero.ZERO);
private final String value;
private final PlusMinusZero enumValue;
PlusMinusZeroType(String v, PlusMinusZero eV) {
value = v;
enumValue = eV;
}
public String value() {
return value;
}
public static PlusMinusZeroType fromValue(String v) {
for (PlusMinusZeroType c: PlusMinusZeroType.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
public static PlusMinusZeroType fromValue(PlusMinusZero v) {
if (v == null) {
return null;
}
for (PlusMinusZeroType c: PlusMinusZeroType.values()) {
if (v == c.enumValue) {
return c;
}
}
throw new IllegalArgumentException(String.valueOf(v));
}
}
| bshp/midPoint | infra/prism-api/src/main/java/com/evolveum/prism/xml/ns/_public/types_3/PlusMinusZeroType.java | Java | apache-2.0 | 1,931 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.