hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e09f1b79cb8b966b82181258c270aeb57ecde28
1,976
java
Java
src/main/java_redis/com/uber/profiling/RedisOutputReporter.java
zhenyaderyaka/jvm-profiler
f0adcc19ddce4ae539e0a0d4bed1079abec51b03
[ "Apache-2.0" ]
1,577
2018-01-11T00:11:18.000Z
2022-03-30T05:49:21.000Z
src/main/java_redis/com/uber/profiling/RedisOutputReporter.java
zhenyaderyaka/jvm-profiler
f0adcc19ddce4ae539e0a0d4bed1079abec51b03
[ "Apache-2.0" ]
75
2018-01-17T18:43:51.000Z
2022-02-04T07:34:31.000Z
src/main/java_redis/com/uber/profiling/RedisOutputReporter.java
zhenyaderyaka/jvm-profiler
f0adcc19ddce4ae539e0a0d4bed1079abec51b03
[ "Apache-2.0" ]
324
2018-01-11T07:56:18.000Z
2022-03-22T04:22:11.000Z
30.875
121
0.649798
4,218
package com.uber.profiling.reporters; import com.uber.profiling.Reporter; import com.uber.profiling.util.AgentLogger; import com.uber.profiling.util.JsonUtils; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Date; import java.util.List; import java.util.Map; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; public class RedisOutputReporter implements Reporter { private static final AgentLogger logger = AgentLogger.getLogger(RedisOutputReporter.class.getName()); private JedisPool redisConn = null; @Override public void updateArguments(Map<String, List<String>> parsedArgs) { } //JedisPool should always be used as it is thread safe. @Override public void report(String profilerName, Map<String, Object> metrics) { ensureJedisConn(); try { Jedis jedisClient = redisConn.getResource(); jedisClient.set(createOriginStamp(profilerName), JsonUtils.serialize(metrics)); redisConn.returnResource(jedisClient); } catch (Exception err) { logger.warn(err.toString()); } } public String createOriginStamp(String profilerName) { try { return (profilerName + "-" + InetAddress.getLocalHost().getHostAddress() + "-" + System.currentTimeMillis()); } catch (UnknownHostException err) { logger.warn("Address could not be determined and will be omitted!"); return (profilerName + "-" + System.currentTimeMillis()); } } @Override public void close() { synchronized (this) { redisConn.close(); redisConn = null; } } private void ensureJedisConn() { synchronized (this) { if (redisConn == null || redisConn.isClosed()) { redisConn = new JedisPool(System.getenv("JEDIS_PROFILER_CONNECTION")); return; } } } }
3e09f281334148d0ace05b064379188a11b5ed90
2,196
java
Java
unity-websocket-server/src/main/java/com/logiclodge/unitywebsocketserver/config/SecurityConfig.java
Binary-L0G1C/java-unity-websocket-connector
77785b804e92ba35e9d0ba43763846b77692f360
[ "Apache-2.0" ]
3
2018-03-10T23:25:53.000Z
2021-02-24T22:00:36.000Z
unity-websocket-server/src/main/java/com/logiclodge/unitywebsocketserver/config/SecurityConfig.java
Binary-L0G1C/java-unity-websocket-connector
77785b804e92ba35e9d0ba43763846b77692f360
[ "Apache-2.0" ]
null
null
null
unity-websocket-server/src/main/java/com/logiclodge/unitywebsocketserver/config/SecurityConfig.java
Binary-L0G1C/java-unity-websocket-connector
77785b804e92ba35e9d0ba43763846b77692f360
[ "Apache-2.0" ]
2
2018-01-08T07:20:05.000Z
2019-07-01T12:40:25.000Z
38.526316
107
0.780055
4,219
/* * Copyright 2017 L0G1C (David B) - logiclodge.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.logiclodge.unitywebsocketserver.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import com.logiclodge.unitywebsocketserver.user.User; import com.logiclodge.unitywebsocketserver.user.UserDao; /** * @author L0G1C (David B) <a * href=https://github.com/Binary-L0G1C/java-unity-websocket-connector> * https://github.com/Binary-L0G1C/java-unity-websocket-connector </a> */ @Configuration @ComponentScan("com.logiclodge.unitywebsocketserver") @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired UserDao userDao; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { for (User user : userDao.getUsers()) { auth.inMemoryAuthentication().withUser(user.getUsername()).password(user.getPassword()).roles("USER"); } } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() // .authorizeRequests().antMatchers("/**").access("hasRole('ROLE_USER')") // .and().httpBasic(); } }
3e09f2aa5e2d9ee04313567fae50646d5da3c06e
6,845
java
Java
trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/skin/pregen/variant/AgentVariantExtractor.java
pervasync/myfaces-trinidad
0eaa7c977cefbd54b42024b233664891265aade7
[ "Apache-2.0" ]
4
2017-08-18T08:21:39.000Z
2019-05-21T21:06:55.000Z
trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/skin/pregen/variant/AgentVariantExtractor.java
pervasync/myfaces-trinidad
0eaa7c977cefbd54b42024b233664891265aade7
[ "Apache-2.0" ]
2
2019-04-14T08:51:28.000Z
2019-04-14T10:11:18.000Z
trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/skin/pregen/variant/AgentVariantExtractor.java
pervasync/myfaces-trinidad
0eaa7c977cefbd54b42024b233664891265aade7
[ "Apache-2.0" ]
9
2017-10-06T15:15:58.000Z
2021-11-08T13:55:28.000Z
30.695067
106
0.704018
4,220
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.myfaces.trinidadinternal.skin.pregen.variant; import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.apache.myfaces.trinidad.context.Version; import org.apache.myfaces.trinidad.util.Range; import org.apache.myfaces.trinidadinternal.agent.TrinidadAgent.Application; import org.apache.myfaces.trinidadinternal.skin.AgentAtRuleMatcher; import org.apache.myfaces.trinidadinternal.style.xml.parse.StyleSheetNode; /** * An @-rule processor for extracting @agent rule metadata. */ final class AgentVariantExtractor implements SkinVariantExtractor<ApplicationAndVersion> { /** * Creates an AgentVariantExtractor for a specified set of supported * agent applications. AgentVariantExtractor.getVariants() will only * ApplicationAndVersion instances corresponding to these agent * applications. If no supported agent applications are specified, * all agent applications found in the style sheet nodes will be * treated as supported. */ public AgentVariantExtractor( Collection<Application> supportedApplications ) { _appVersionsMap = new HashMap<Application, Set<Version>>(); _supportedApplications = _initSupportedApplications(supportedApplications); // Seed the map with unknown agent. This won't appear // in the skin definition, but we need to cover this case // during pregeneration. _addApplicationIfSupported(Application.UNKNOWN); } private Collection<Application> _initSupportedApplications( Collection<Application> supportedApplications ) { if ((supportedApplications == null) || supportedApplications.isEmpty()) { return new AbstractCollection<Application>() { @Override public boolean contains(Object o) { return true; } @Override public Iterator<Application> iterator() { throw new UnsupportedOperationException(); } @Override public int size() { throw new UnsupportedOperationException(); } }; } return new HashSet<Application>(supportedApplications); } @Override public void visit(StyleSheetNode node) { AgentAtRuleMatcher agentMatcher = node.getAgentMatcher(); if (agentMatcher != null) { _addApplicationVersions(agentMatcher); } } /** * Returns alist containing ApplicationAndVersions * corresponding to all processed @agent rules. */ public List<ApplicationAndVersion> getVariants() { List<ApplicationAndVersion> appAndVersionsList = _toAppAndVersionsList(_appVersionsMap); return appAndVersionsList; } private void _addApplicationVersions(AgentAtRuleMatcher agentMatcher) { assert(agentMatcher != null); Collection<Application> nodeApplications = agentMatcher.getAllApplications(); for (Application application : nodeApplications) { boolean supported = _addApplicationIfSupported(application); if (supported) { Collection<Range<Version>> versionRanges = agentMatcher.getAllVersionsForApplication(application); _addVersions(application, versionRanges); } } } private boolean _addApplicationIfSupported(Application application) { if (!_supportedApplications.contains(application)) { return false; } if (!_appVersionsMap.containsKey(application)) { Set<Version> versions = new TreeSet<Version>(); // Minimally, every application needs to be able // to pregenerate for the unknown version case. versions.add(_UNKNOWN_VERSION); _appVersionsMap.put(application, versions); } return true; } private void _addVersions( Application application, Collection<Range<Version>> versionRanges ) { Collection<Version> versions = _appVersionsMap.get(application); assert(versions != null); for (Range<Version> versionRange : versionRanges) { // We add the start/end points of the range to our // set of versions to pregenerate. // Also note that from here on out we only want to // deal with "concrete" versions. If we leave version // wildcards in place, we can lose information due to // Version's wildcard-sensitive natural ordering (ie. // a Set.add() might fail because a matching/wildcarded // version is already present.) versions.add(versionRange.getStart().toMinimumVersion()); versions.add(versionRange.getEnd().toMaximumVersion()); } } private static List<ApplicationAndVersion> _toAppAndVersionsList( Map<Application, Set<Version>> appVersionsMap ) { List<ApplicationAndVersion> appAndVersions = new ArrayList<ApplicationAndVersion>(); for (Map.Entry<Application, Set<Version>> entry : appVersionsMap.entrySet()) { for (Version version : entry.getValue()) { appAndVersions.add(new ApplicationAndVersion(entry.getKey(), version)); } } // Sort to make logger output/progress easier to monitor Collections.sort(appAndVersions); return appAndVersions; } // Map of application to versions that have been encountered // during processing private final Map<Application, Set<Version>> _appVersionsMap; // Only extract version information for these applications. private final Collection<Application> _supportedApplications; // A Version that we use to ensure that we pregenerate style sheets // for the case where the agent version does not match any version // specified in the skin. private static final Version _UNKNOWN_VERSION = new Version("unknown"); }
3e09f346cfb8d208864f7d81a65e6c0e0c503821
5,573
java
Java
src/edu/uta/futureye/io/MeshReader.java
yuemingl/Futureye_JIT
09dc7103c96c7f072c30b9ada5b0c4c13189a12e
[ "BSD-3-Clause" ]
24
2017-02-15T05:41:38.000Z
2021-11-11T08:21:42.000Z
src/edu/uta/futureye/io/MeshReader.java
yuemingl/Futureye_v2
09dc7103c96c7f072c30b9ada5b0c4c13189a12e
[ "BSD-3-Clause" ]
2
2019-05-25T15:39:49.000Z
2021-04-27T03:59:33.000Z
src/edu/uta/futureye/io/MeshReader.java
yuemingl/Futureye_JIT
09dc7103c96c7f072c30b9ada5b0c4c13189a12e
[ "BSD-3-Clause" ]
7
2017-02-18T04:06:22.000Z
2021-11-11T08:21:43.000Z
29.204188
67
0.626927
4,221
/** * Copyright (c) 2010, kenaa@example.com. All rights reserved. * * */ package edu.uta.futureye.io; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import edu.uta.futureye.core.Element; import edu.uta.futureye.core.Mesh; import edu.uta.futureye.core.Node; import edu.uta.futureye.util.container.ElementList; import edu.uta.futureye.util.container.NodeList; /** * Read .grd file generated from Gridgen * * @author yuemingl * */ public class MeshReader { Mesh mesh = new Mesh(); String file = null; public boolean debug = false; public MeshReader(String fileName) { this.file = fileName; } public Mesh read2DMesh() { FileInputStream in; try { in = new FileInputStream(file); InputStreamReader reader = new InputStreamReader(in,"UTF-8"); BufferedReader br = new BufferedReader(reader); String str = null; int nNode = 0; int nElement = 0; mesh.clearAll(); while((str = br.readLine()) != null){ if(debug) System.out.println(str); if(str.startsWith("#")) continue; String[] line = str.split("(\\s)+"); if(nNode == 0) { nNode = Integer.valueOf(line[0]); nElement = Integer.valueOf(line[1]); } else { if(mesh.getNodeList().size() < nNode) { int index = Integer.valueOf(line[0]); double x = Double.valueOf(line[1]); double y = Double.valueOf(line[2]); Node node = new Node(index, x, y); mesh.addNode(node); } else if(mesh.getElementList().size() < nElement) { String type = line[2]; if(type.equalsIgnoreCase("tri")) { NodeList list = new NodeList(); list.add(mesh.getNodeList().at(Integer.valueOf(line[3]))); list.add(mesh.getNodeList().at(Integer.valueOf(line[4]))); list.add(mesh.getNodeList().at(Integer.valueOf(line[5]))); Element ele = new Element(list); mesh.addElement(ele); } else if(type.equalsIgnoreCase("quad")) { NodeList list = new NodeList(); list.add(mesh.getNodeList().at(Integer.valueOf(line[3]))); list.add(mesh.getNodeList().at(Integer.valueOf(line[4]))); list.add(mesh.getNodeList().at(Integer.valueOf(line[5]))); list.add(mesh.getNodeList().at(Integer.valueOf(line[6]))); Element ele = new Element(list); mesh.addElement(ele); } } } } br.close(); in.close(); ElementList nEList = mesh.getElementList(); int nE = nEList.size(); for(int i=1;i<=nE;i++) { Element e = nEList.at(i); e.adjustVerticeToCounterClockwise(); } return mesh; } catch (Exception e) { e.printStackTrace(); } return null; } public Mesh read3DMesh() { FileInputStream in; try { in = new FileInputStream(file); InputStreamReader reader = new InputStreamReader(in,"UTF-8"); BufferedReader br = new BufferedReader(reader); String str = null; int nNode = 0; int nElement = 0; mesh.clearAll(); while((str = br.readLine()) != null){ if(debug) System.out.println(str); if(str.startsWith("#")) continue; String[] line = str.split("(\\s)+"); if(nNode == 0) { //Read in node number and element number nNode = Integer.valueOf(line[0]); nElement = Integer.valueOf(line[1]); } else { if(mesh.getNodeList().size() < nNode) { int index = Integer.valueOf(line[0]); double x = Double.valueOf(line[1]); double y = Double.valueOf(line[2]); double z = Double.valueOf(line[3]); Node node = new Node(index, x, y, z); mesh.addNode(node); } else if(mesh.getElementList().size() < nElement) { String type = line[2]; if(type.equalsIgnoreCase("tet")) { NodeList list = new NodeList(); list.add(mesh.getNodeList().at(Integer.valueOf(line[3]))); list.add(mesh.getNodeList().at(Integer.valueOf(line[4]))); list.add(mesh.getNodeList().at(Integer.valueOf(line[5]))); list.add(mesh.getNodeList().at(Integer.valueOf(line[6]))); Element ele = new Element(list); mesh.addElement(ele); } else if(type.equalsIgnoreCase("hex")) { NodeList list = new NodeList(); list.add(mesh.getNodeList().at(Integer.valueOf(line[3]))); list.add(mesh.getNodeList().at(Integer.valueOf(line[4]))); list.add(mesh.getNodeList().at(Integer.valueOf(line[5]))); list.add(mesh.getNodeList().at(Integer.valueOf(line[6]))); list.add(mesh.getNodeList().at(Integer.valueOf(line[7]))); list.add(mesh.getNodeList().at(Integer.valueOf(line[8]))); list.add(mesh.getNodeList().at(Integer.valueOf(line[9]))); list.add(mesh.getNodeList().at(Integer.valueOf(line[10]))); Element ele = new Element(list); mesh.addElement(ele); } } } } br.close(); in.close(); //add bufix ElementList nEList = mesh.getElementList(); int nE = nEList.size(); for(int i=1;i<=nE;i++) { Element e = nEList.at(i); e.adjustVerticeToCounterClockwise(); } return mesh; } catch (Exception e) { e.printStackTrace(); } return null; } public NodeList getNodeList() { return mesh.getNodeList(); } public ElementList getElementList() { return mesh.getElementList(); } public static void main(String[] args) { //MeshReader r1 = new MeshReader("mixed.grd"); MeshReader r1 = new MeshReader("block1.grd"); //Mesh m = r1.read2DMesh(); Mesh m = r1.read3DMesh(); System.out.println("nodes read: "+m.getNodeList().size()); System.out.println("elements read: "+m.getElementList().size()); } }
3e09f34c4bed2c15432d058981241b1e4ce7e3a6
277
java
Java
src/main/java/com/labbati/cando/provider/CollectionActionsProvider.java
labbati/can-do
cd45a1600e0f93c23ef4e2d5e2abc310977abe8f
[ "MIT" ]
null
null
null
src/main/java/com/labbati/cando/provider/CollectionActionsProvider.java
labbati/can-do
cd45a1600e0f93c23ef4e2d5e2abc310977abe8f
[ "MIT" ]
null
null
null
src/main/java/com/labbati/cando/provider/CollectionActionsProvider.java
labbati/can-do
cd45a1600e0f93c23ef4e2d5e2abc310977abe8f
[ "MIT" ]
null
null
null
23.083333
103
0.808664
4,222
package com.labbati.cando.provider; import com.labbati.cando.model.Action; import java.util.List; @FunctionalInterface public interface CollectionActionsProvider<T> { List<Action> provide(Class<T> t, Boolean includeDeniedActions, Boolean includeInactiveConstraints); }
3e09f439009571a16daec474e78697b5d7223534
13,047
java
Java
src/ui/paineis/formularios/FormularioPessoaFisica.java
SENAI-ads-group/java-swing-csv-GLV
898558df9c29e56f34195b4401e1aaf14494be9c
[ "MIT" ]
1
2021-06-02T21:11:41.000Z
2021-06-02T21:11:41.000Z
src/ui/paineis/formularios/FormularioPessoaFisica.java
SENAI-ads-group/java-swing-csv-GLV
898558df9c29e56f34195b4401e1aaf14494be9c
[ "MIT" ]
1
2020-11-27T01:53:43.000Z
2020-11-27T01:53:43.000Z
src/ui/paineis/formularios/FormularioPessoaFisica.java
SENAI-ads-group/java-swing-csv-GLV
898558df9c29e56f34195b4401e1aaf14494be9c
[ "MIT" ]
1
2021-06-02T21:11:45.000Z
2021-06-02T21:11:45.000Z
49.233962
145
0.693339
4,223
package ui.paineis.formularios; import java.util.Map; import java.util.Set; import model.entidades.PessoaFisica; import model.exceptions.ValidacaoException; import util.FieldUtilities; import util.Validador; /** * * @author Patrick-Ribeiro */ public class FormularioPessoaFisica extends javax.swing.JPanel { private PessoaFisica pessoa; public FormularioPessoaFisica(PessoaFisica pessoa) { initComponents(); this.pessoa = pessoa; } public void setPessoa(PessoaFisica pessoa) { this.pessoa = pessoa; } public void atualizarFormulario() { if (pessoa != null) { textFieldNome.setText(pessoa.getNome()); textFieldEmail.setText(pessoa.getEmail()); formattedTextFieldCPF.setText(pessoa.getCpf()); formattedTextFieldRG.setText(pessoa.getRegistroGeral()); formattedTextFieldTelefone.setText(pessoa.getTelefone()); dateChooserNascimento.setDate(pessoa.getDataNascimento()); } } public PessoaFisica getDadosFormulario() throws ValidacaoException { if (pessoa == null) { pessoa = new PessoaFisica(); } limparErros(); validarCampos(); pessoa.setNome(textFieldNome.getText()); pessoa.setCpf(formattedTextFieldCPF.getText()); pessoa.setTelefone(formattedTextFieldTelefone.getText()); pessoa.setRegistroGeral(formattedTextFieldRG.getText()); pessoa.setEmail(textFieldEmail.getText()); pessoa.setDataNascimento(dateChooserNascimento.getDate()); return pessoa; } private void validarCampos() throws ValidacaoException { ValidacaoException exception = new ValidacaoException(PessoaFisica.class.getSimpleName()); if (FieldUtilities.textFieldIsEmpty(textFieldNome)) { exception.addError("nome", "Nome não informado"); } if (FieldUtilities.formattedTextFieldIsEmpty(formattedTextFieldCPF)) { exception.addError("CPF", "CPF não informado"); } else if (!FieldUtilities.formattedTextFieldIsValid(formattedTextFieldCPF) || !Validador.cpfIsValido(formattedTextFieldCPF.getText())) { exception.addError("CPF", "CPF inválido"); } if (FieldUtilities.formattedTextFieldIsEmpty(formattedTextFieldRG)) { exception.addError("RG", "RG não informado"); } else if (!FieldUtilities.formattedTextFieldIsValid(formattedTextFieldRG)) { exception.addError("RG", "RG inválido"); } if (FieldUtilities.formattedTextFieldIsEmpty(formattedTextFieldTelefone)) { exception.addError("telefone", "Telefone não informado"); } else if (!FieldUtilities.formattedTextFieldIsValid(formattedTextFieldTelefone)) { exception.addError("telefone", "Telefone inválido"); } if (dateChooserNascimento.getDate() == null) { exception.addError("dataNascimento", "Data não informada"); } if (exception.getErrors().size() > 0) { throw exception; } } public void exibirMensagensErro(Map<String, String> erros) { Set<String> fields = erros.keySet(); if (fields.contains("nome")) { labelErroNome.setText(erros.get("nome")); } if (fields.contains("CPF")) { labelErroCPF.setText(erros.get("CPF")); } if (fields.contains("RG")) { labelErroRG.setText(erros.get("RG")); } if (fields.contains("telefone")) { labelErroTelefone.setText(erros.get("telefone")); } if (fields.contains("dataNascimento")) { labelErroDataNascimento.setText(erros.get("dataNascimento")); } } private void limparErros() { labelErroNome.setText(""); labelErroCPF.setText(""); labelErroRG.setText(""); labelErroTelefone.setText(""); labelErroDataNascimento.setText(""); labelErroEmail.setText(""); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { labelNome = new javax.swing.JLabel(); labelTelefone = new javax.swing.JLabel(); textFieldEmail = new javax.swing.JTextField(); labelEmail = new javax.swing.JLabel(); labelCPF = new javax.swing.JLabel(); labelDataNascimento = new javax.swing.JLabel(); labelRG = new javax.swing.JLabel(); dateChooserNascimento = new com.toedter.calendar.JDateChooser(); labelErroDataNascimento = new javax.swing.JLabel(); labelErroNome = new javax.swing.JLabel(); labelErroCPF = new javax.swing.JLabel(); labelErroTelefone = new javax.swing.JLabel(); labelErroRG = new javax.swing.JLabel(); labelErroEmail = new javax.swing.JLabel(); textFieldNome = new javax.swing.JTextField(); formattedTextFieldTelefone = new javax.swing.JFormattedTextField(); formattedTextFieldRG = new javax.swing.JFormattedTextField(); formattedTextFieldCPF = new javax.swing.JFormattedTextField(); setBackground(new java.awt.Color(255, 255, 255)); setMaximumSize(new java.awt.Dimension(390, 280)); setMinimumSize(new java.awt.Dimension(390, 280)); setPreferredSize(new java.awt.Dimension(390, 280)); setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); labelNome.setFont(new java.awt.Font("Segoe UI", 0, 13)); // NOI18N labelNome.setText("Nome"); add(labelNome, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); labelTelefone.setFont(new java.awt.Font("Segoe UI", 0, 13)); // NOI18N labelTelefone.setText("Telefone"); add(labelTelefone, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 0, -1, -1)); textFieldEmail.setMaximumSize(new java.awt.Dimension(170, 25)); textFieldEmail.setMinimumSize(new java.awt.Dimension(170, 25)); textFieldEmail.setPreferredSize(new java.awt.Dimension(190, 25)); add(textFieldEmail, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 140, -1, -1)); labelEmail.setFont(new java.awt.Font("Segoe UI", 0, 13)); // NOI18N labelEmail.setText("Email"); add(labelEmail, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 120, -1, -1)); labelCPF.setFont(new java.awt.Font("Segoe UI", 0, 13)); // NOI18N labelCPF.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); labelCPF.setText("CPF"); labelCPF.setToolTipText(""); labelCPF.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT); add(labelCPF, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 60, -1, -1)); labelDataNascimento.setFont(new java.awt.Font("Segoe UI", 0, 13)); // NOI18N labelDataNascimento.setText("Data de nascimento"); add(labelDataNascimento, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 120, -1, -1)); labelRG.setFont(new java.awt.Font("Segoe UI", 0, 13)); // NOI18N labelRG.setText("RG"); labelRG.setToolTipText(""); labelRG.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT); add(labelRG, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 60, -1, -1)); dateChooserNascimento.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N dateChooserNascimento.setPreferredSize(new java.awt.Dimension(190, 25)); add(dateChooserNascimento, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 140, -1, -1)); labelErroDataNascimento.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N labelErroDataNascimento.setForeground(java.awt.Color.red); labelErroDataNascimento.setMaximumSize(new java.awt.Dimension(150, 15)); labelErroDataNascimento.setMinimumSize(new java.awt.Dimension(150, 15)); labelErroDataNascimento.setPreferredSize(new java.awt.Dimension(190, 15)); add(labelErroDataNascimento, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 165, -1, -1)); labelErroNome.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N labelErroNome.setForeground(java.awt.Color.red); labelErroNome.setMaximumSize(new java.awt.Dimension(150, 15)); labelErroNome.setMinimumSize(new java.awt.Dimension(150, 15)); labelErroNome.setPreferredSize(new java.awt.Dimension(190, 15)); add(labelErroNome, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 45, -1, -1)); labelErroCPF.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N labelErroCPF.setForeground(java.awt.Color.red); labelErroCPF.setMaximumSize(new java.awt.Dimension(150, 15)); labelErroCPF.setMinimumSize(new java.awt.Dimension(150, 15)); labelErroCPF.setPreferredSize(new java.awt.Dimension(190, 15)); add(labelErroCPF, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 105, -1, -1)); labelErroTelefone.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N labelErroTelefone.setForeground(java.awt.Color.red); labelErroTelefone.setMaximumSize(new java.awt.Dimension(150, 15)); labelErroTelefone.setMinimumSize(new java.awt.Dimension(150, 15)); labelErroTelefone.setPreferredSize(new java.awt.Dimension(190, 15)); add(labelErroTelefone, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 45, -1, -1)); labelErroRG.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N labelErroRG.setForeground(java.awt.Color.red); labelErroRG.setMaximumSize(new java.awt.Dimension(150, 15)); labelErroRG.setMinimumSize(new java.awt.Dimension(150, 15)); labelErroRG.setPreferredSize(new java.awt.Dimension(190, 15)); add(labelErroRG, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 105, -1, -1)); labelErroEmail.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N labelErroEmail.setForeground(java.awt.Color.red); labelErroEmail.setMaximumSize(new java.awt.Dimension(150, 15)); labelErroEmail.setMinimumSize(new java.awt.Dimension(150, 15)); labelErroEmail.setPreferredSize(new java.awt.Dimension(190, 15)); add(labelErroEmail, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 165, -1, -1)); textFieldNome.setMaximumSize(new java.awt.Dimension(170, 25)); textFieldNome.setMinimumSize(new java.awt.Dimension(170, 25)); textFieldNome.setPreferredSize(new java.awt.Dimension(190, 25)); add(textFieldNome, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 20, -1, -1)); util.FieldUtilities.setFieldOnlyText(textFieldNome, 25); formattedTextFieldTelefone.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter())); formattedTextFieldTelefone.setPreferredSize(new java.awt.Dimension(190, 25)); add(formattedTextFieldTelefone, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 20, -1, -1)); util.FieldUtilities.setFieldTelefone(formattedTextFieldTelefone); formattedTextFieldRG.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter())); formattedTextFieldRG.setPreferredSize(new java.awt.Dimension(190, 25)); add(formattedTextFieldRG, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 80, -1, -1)); util.FieldUtilities.setFieldRG(formattedTextFieldRG); formattedTextFieldCPF.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter())); formattedTextFieldCPF.setPreferredSize(new java.awt.Dimension(190, 25)); add(formattedTextFieldCPF, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 80, -1, -1)); util.FieldUtilities.setFieldCPF(formattedTextFieldCPF); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private com.toedter.calendar.JDateChooser dateChooserNascimento; private javax.swing.JFormattedTextField formattedTextFieldCPF; private javax.swing.JFormattedTextField formattedTextFieldRG; private javax.swing.JFormattedTextField formattedTextFieldTelefone; private javax.swing.JLabel labelCPF; private javax.swing.JLabel labelDataNascimento; private javax.swing.JLabel labelEmail; private javax.swing.JLabel labelErroCPF; private javax.swing.JLabel labelErroDataNascimento; private javax.swing.JLabel labelErroEmail; private javax.swing.JLabel labelErroNome; private javax.swing.JLabel labelErroRG; private javax.swing.JLabel labelErroTelefone; private javax.swing.JLabel labelNome; private javax.swing.JLabel labelRG; private javax.swing.JLabel labelTelefone; private javax.swing.JTextField textFieldEmail; private javax.swing.JTextField textFieldNome; // End of variables declaration//GEN-END:variables }
3e09f473aa1b39a41bb63ac606238d068a6ec7de
487
java
Java
omp-user-center/src/main/java/com/ahdms/user/center/bean/bo/AuditInfoReqBo.java
wosqinxiang/omp_user
0aaaad7671b016892b01b2769f851d67e683d97b
[ "Apache-2.0" ]
null
null
null
omp-user-center/src/main/java/com/ahdms/user/center/bean/bo/AuditInfoReqBo.java
wosqinxiang/omp_user
0aaaad7671b016892b01b2769f851d67e683d97b
[ "Apache-2.0" ]
null
null
null
omp-user-center/src/main/java/com/ahdms/user/center/bean/bo/AuditInfoReqBo.java
wosqinxiang/omp_user
0aaaad7671b016892b01b2769f851d67e683d97b
[ "Apache-2.0" ]
null
null
null
17.392857
48
0.708419
4,224
package com.ahdms.user.center.bean.bo; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * @author qinxiang * @date 2020-07-13 19:48 */ @Data public class AuditInfoReqBo { @ApiModelProperty("审核结果(0.通过 1.退回)") private Integer auditResult; @ApiModelProperty("审核备注") private String auditDesc; @ApiModelProperty("审核类型(1.企业认证 2.企业商务信息变更)") private Integer auditType; @ApiModelProperty("审核内容的业务主键") private String auditInfo; }
3e09f4a4875e534650a5dbe380675868fc10b38f
54,684
java
Java
gemfirexd/tools/src/dunit/java/com/pivotal/gemfirexd/wan/GfxdWanCommonTestBase.java
xyxiaoyou/snappy-store
013ff282f888878cc99600e260ec1cde60112304
[ "Apache-2.0" ]
38
2016-01-04T01:31:40.000Z
2020-04-07T06:35:36.000Z
gemfirexd/tools/src/dunit/java/com/pivotal/gemfirexd/wan/GfxdWanCommonTestBase.java
xyxiaoyou/snappy-store
013ff282f888878cc99600e260ec1cde60112304
[ "Apache-2.0" ]
261
2016-01-07T09:14:26.000Z
2019-12-05T10:15:56.000Z
gemfirexd/tools/src/dunit/java/com/pivotal/gemfirexd/wan/GfxdWanCommonTestBase.java
xyxiaoyou/snappy-store
013ff282f888878cc99600e260ec1cde60112304
[ "Apache-2.0" ]
22
2016-03-09T05:47:09.000Z
2020-04-02T17:55:30.000Z
42.227027
159
0.669081
4,225
/* * Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying * LICENSE file. */ package com.pivotal.gemfirexd.wan; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.util.Set; import com.gemstone.gemfire.cache.CacheClosedException; import com.gemstone.gemfire.cache.CacheException; import com.gemstone.gemfire.cache.Region; import com.gemstone.gemfire.cache.wan.GatewaySender; import com.gemstone.gemfire.internal.cache.ForceReattemptException; import com.gemstone.gemfire.internal.cache.partitioned.PRLocallyDestroyedException; import com.gemstone.gemfire.internal.cache.wan.AbstractGatewaySenderEventProcessor; import com.gemstone.gemfire.internal.cache.wan.parallel.ParallelGatewaySenderImpl; import com.pivotal.gemfirexd.TestUtil; import com.pivotal.gemfirexd.internal.engine.Misc; import com.pivotal.gemfirexd.internal.engine.jdbc.GemFireXDRuntimeException; import com.pivotal.gemfirexd.procedure.ProcedureExecutionContext; import io.snappydata.test.dunit.SerializableRunnable; public abstract class GfxdWanCommonTestBase extends GfxdWanTestBase { public GfxdWanCommonTestBase(String name) { super(name); } @Override public void setUp() throws Exception { super.setUp(); } @Override protected void vmTearDown() throws Exception { super.vmTearDown(); } /** * Basic Insert doesn't user BULK DML route. * It gets notification just as in case of gemfire region. * @throws Exception */ public void testBasicInsert() throws Exception { String goldenFile = TestUtil.getResourcesDir() + "/lib/GemFireXDGatewayDUnit.xml"; // start two sites // each having 2 data-store nodes, 1 accessor and 1 locator // 1 locator // 1 datastore + sender // 1 datastore + sender + receiver // 1 accessor + sender + receiver startSites(2); // create gatewayreceiver final String createGWR = "create gatewayreceiver myrcvr(bindaddress 'localhost') server groups(sgSender)"; executeSql(SITE_B, createGWR); // create gatewaysender final String createGWS = getCreateGatewayDML(); executeSql(SITE_A, createGWS); // create PTable final String createPTable = "create table EMP.PARTITIONED_TABLE (ID int , " + "DESCRIPTION varchar(1024) not null, ADDRESS varchar(1024) not null, " + "primary key (ID)) partition by column(ADDRESS) redundancy 1 server groups (sg1)"; executeSql(SITE_A, createPTable + " GatewaySender (MySender)" + getSQLSuffixClause()); executeSql(SITE_B, createPTable + getSQLSuffixClause()); // doInsertOperations executeSql(SITE_A, "insert into EMP.PARTITIONED_TABLE values (1, 'First', 'A714')"); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id7", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id7", true, false); } protected abstract String getCreateGatewayDML(); public void testBasicPrepStmt() throws Exception { String goldenFile = TestUtil.getResourcesDir() + "/lib/GemFireXDGatewayDUnit.xml"; // start two sites // each having 2 data-store nodes, 1 accessor and 1 locator // 1 locator // 1 datastore + sender // 1 datastore + sender + receiver // 1 accessor + sender + receiver startSites(2); // create gatewayreceiver final String createGWR = "create gatewayreceiver myrcvr(bindaddress 'localhost') server groups(sgSender)"; executeSql(SITE_B, createGWR); // create gatewaysender final String createGWS = getCreateGatewayDML(); executeSql(SITE_A, createGWS); // create PTable final String createPTable = "create table EMP.PARTITIONED_TABLE (ID int , " + "DESCRIPTION varchar(1024) not null, ADDRESS varchar(1024) not null, COMPANY varchar(1024) DEFAULT 'Pivotal', " + "primary key (ID)) partition by column(ADDRESS) redundancy 1 server groups (sg1)"; executeSql(SITE_A, createPTable + " GatewaySender (MySender)" + getSQLSuffixClause()); executeSql(SITE_B, createPTable + getSQLSuffixClause()); // doPrepStmtInsertOperations // server 4 belongs to site A serverExecute(4, prepInsert()); // doInsertOperations sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id7", true, false); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "id2", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id7", true, false); sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "id2", true, false); } /** * Basic Insert/Update/Delete doesn't user BULK DML route. * It gets notification just as in case of gemfire region. * @throws Exception */ public void testBasicUpdateDelete() throws Exception { String goldenFile = TestUtil.getResourcesDir() + "/lib/GemFireXDGatewayDUnit.xml"; // start two sites // each having 2 data-store nodes, 1 accessor and 1 locator // 1 locator // 1 datastore + sender // 1 datastore + sender + receiver // 1 accessor + sender + receiver startSites(2); // create gatewayreceiver final String createGWR = "create gatewayreceiver myrcvr(bindaddress 'localhost') server groups(sgSender)"; executeSql(SITE_B, createGWR); // create gatewaysender final String createGWS = getCreateGatewayDML(); executeSql(SITE_A, createGWS); // create PTable final String createPTable = "create table EMP.PARTITIONED_TABLE (ID int , " + "DESCRIPTION varchar(1024) not null, ADDRESS varchar(1024) not null, " + "primary key (ID)) partition by column(ADDRESS) redundancy 1 server groups (sg1)"; executeSql(SITE_A, createPTable + " GatewaySender (MySender)" + getSQLSuffixClause()); executeSql(SITE_B, createPTable + getSQLSuffixClause()); // doInsertOperations executeSql(SITE_A, "insert into EMP.PARTITIONED_TABLE values (1, 'First', 'A714')"); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id7", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id7", true, false); //doUpdateOperations executeSql(SITE_A, "Update EMP.PARTITIONED_TABLE set DESCRIPTION = 'Second' where ID = 1"); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id2", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id2", true, false); //doDeleteOperations executeSql(SITE_A, "Delete from EMP.PARTITIONED_TABLE where ID = 1"); sqlExecuteVerify(SITE_A, "select ADDRESS from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "empty", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select ADDRESS from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "empty", true, false); } public void testNonPKBasedUpdateDelete() throws Exception { String goldenFile = TestUtil.getResourcesDir() + "/lib/GemFireXDGatewayDUnit.xml"; // start two sites // each having 2 data-store nodes, 1 accessor and 1 locator // 1 locator // 1 datastore + sender // 1 datastore + sender + receiver // 1 accessor + sender + receiver startSites(2); // create gatewayreceiver final String createGWR = "create gatewayreceiver myrcvr(bindaddress 'localhost') server groups(sgSender)"; executeSql(SITE_B, createGWR); // create gatewaysender final String createGWS = getCreateGatewayDML(); executeSql(SITE_A, createGWS); // create PTable final String createPTable = "create table EMP.PARTITIONED_TABLE (ID int , " + "DESCRIPTION varchar(1024) not null, ADDRESS varchar(1024) not null, " + "primary key (ID)) partition by column(ADDRESS) redundancy 1 server groups (sg1)"; executeSql(SITE_A, createPTable + " GatewaySender (MySender)" + getSQLSuffixClause()); executeSql(SITE_B, createPTable + getSQLSuffixClause()); // doInsertOperations executeSql(SITE_A, "insert into EMP.PARTITIONED_TABLE values (1, 'First', 'A714')"); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id7", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id7", true, false); //doUpdateOperations executeSql(SITE_A, "Update EMP.PARTITIONED_TABLE set DESCRIPTION = 'Second' where ADDRESS = 'A714'"); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id2", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id2", true, false); //doDeleteOperations executeSql(SITE_A, "Delete from EMP.PARTITIONED_TABLE where DESCRIPTION = 'Second'"); sqlExecuteVerify(SITE_A, "select ADDRESS from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "empty", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select ADDRESS from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "empty", true, false); } public void testBatchInsert() throws Exception { String goldenFile = TestUtil.getResourcesDir() + "/lib/GemFireXDGatewayDUnit.xml"; // start two sites // each having 2 data-store nodes, 1 accessor and 1 locator // 1 locator // 1 datastore + sender // 1 datastore + sender + receiver // 1 accessor + sender + receiver startSites(2); addExpectedException(new String[] { SITE_A, SITE_B }, new Object[] { CacheClosedException.class }); // create gatewayreceiver final String createGWR = "create gatewayreceiver myrcvr(bindaddress 'localhost') server groups(sgSender)"; executeSql(SITE_B, createGWR); // create gatewaysender final String createGWS = getCreateGatewayDML(); executeSql(SITE_A, createGWS); // create PTable final String createPTable = "create table EMP.PARTITIONED_TABLE (ID int , " + "DESCRIPTION varchar(1024) not null, ADDRESS varchar(1024) not null, COMPANY varchar(1024) DEFAULT 'Pivotal'," + "primary key (ID)) partition by column(ADDRESS) redundancy 1 server groups (sg1)"; executeSql(SITE_A, createPTable + " GatewaySender (MySender)" + getSQLSuffixClause()); executeSql(SITE_B, createPTable + getSQLSuffixClause()); // doBatchInsertOperations // server 4 belongs to site A serverExecute(4, batchInsert()); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id7", true, false); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "id2", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id7", true, false); sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "id2", true, false); } public void testBatchUpdate() throws Exception { String goldenFile = TestUtil.getResourcesDir() + "/lib/GemFireXDGatewayDUnit.xml"; // start two sites // each having 2 data-store nodes, 1 accessor and 1 locator // 1 locator // 1 datastore + sender // 1 datastore + sender + receiver // 1 accessor + sender + receiver startSites(2); // create gatewayreceiver final String createGWR = "create gatewayreceiver myrcvr(bindaddress 'localhost') server groups(sgSender)"; executeSql(SITE_B, createGWR); // create gatewaysender final String createGWS = getCreateGatewayDML(); executeSql(SITE_A, createGWS); // create PTable final String createPTable = "create table EMP.PARTITIONED_TABLE (ID int , " + "DESCRIPTION varchar(1024) not null, ADDRESS varchar(1024) not null, COMPANY varchar(1024) DEFAULT 'Pivotal', " + "primary key (ID)) partition by column(ADDRESS) redundancy 1 server groups (sg1)"; executeSql(SITE_A, createPTable + " GatewaySender (MySender)" + getSQLSuffixClause()); executeSql(SITE_B, createPTable + getSQLSuffixClause()); // doBatchInsertOperations // server 4 belongs to site A serverExecute(4, batchInsert()); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id7", true, false); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "id2", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id7", true, false); sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "id2", true, false); // doBatchUpdateOperations // server 4 belongs to site A serverExecute(4, batchUpdate()); sqlExecuteVerify(SITE_A, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id10", true, false); sqlExecuteVerify(SITE_A, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "id10", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id10", true, false); sqlExecuteVerify(SITE_B, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "id10", true, false); } public void testBatchDelete() throws Exception { String goldenFile = TestUtil.getResourcesDir() + "/lib/GemFireXDGatewayDUnit.xml"; // start two sites // each having 2 data-store nodes, 1 accessor and 1 locator // 1 locator // 1 datastore + sender // 1 datastore + sender + receiver // 1 accessor + sender + receiver startSites(2); addExpectedException(new String[] { SITE_A, SITE_B }, new Object[] { ForceReattemptException.class }); // create gatewayreceiver final String createGWR = "create gatewayreceiver myrcvr(bindaddress 'localhost') server groups(sgSender)"; executeSql(SITE_B, createGWR); // create gatewaysender final String createGWS = getCreateGatewayDML(); executeSql(SITE_A, createGWS); // create PTable final String createPTable = "create table EMP.PARTITIONED_TABLE (ID int , " + "DESCRIPTION varchar(1024) not null, ADDRESS varchar(1024) not null, COMPANY varchar(1024) DEFAULT 'Pivotal', " + "primary key (ID)) partition by column(ADDRESS) redundancy 1 server groups (sg1)"; executeSql(SITE_A, createPTable + " GatewaySender (MySender)" + getSQLSuffixClause()); executeSql(SITE_B, createPTable + getSQLSuffixClause()); // doBatchInsertOperations // server 4 belongs to site A serverExecute(4, batchInsert()); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id7", true, false); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "id2", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id7", true, false); sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "id2", true, false); // doBatchUpdateOperations // server 4 belongs to site A serverExecute(4, batchUpdate()); sqlExecuteVerify(SITE_A, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id10", true, false); sqlExecuteVerify(SITE_A, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "id10", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id10", true, false); sqlExecuteVerify(SITE_B, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "id10", true, false); // doBatchDeleteOperations serverExecute(4, batchDelete()); sqlExecuteVerify(SITE_A, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "empty", true, false); sqlExecuteVerify(SITE_A, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "empty", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "empty", true, false); sqlExecuteVerify(SITE_B, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "empty", true, false); } public void testBULKUpdate() throws Exception { String goldenFile = TestUtil.getResourcesDir() + "/lib/GemFireXDGatewayDUnit.xml"; // start two sites // each having 2 data-store nodes, 1 accessor and 1 locator // 1 locator // 1 datastore + sender // 1 datastore + sender + receiver // 1 accessor + sender + receiver startSites(2); addExpectedException(new String[] { SITE_A, SITE_B }, new Object[] { ForceReattemptException.class }); // create gatewayreceiver final String createGWR = "create gatewayreceiver myrcvr(bindaddress 'localhost') server groups(sgSender)"; executeSql(SITE_B, createGWR); // create gatewaysender final String createGWS = getCreateGatewayDML(); executeSql(SITE_A, createGWS); // create PTable final String createPTable = "create table EMP.PARTITIONED_TABLE (ID int , " + "DESCRIPTION varchar(1024) not null, ADDRESS varchar(1024) not null, COMPANY varchar(1024), " + "primary key (ID)) partition by column(ADDRESS) redundancy 1 server groups (sg1)"; executeSql(SITE_A, createPTable + " GatewaySender (MySender)" + getSQLSuffixClause()); executeSql(SITE_B, createPTable + getSQLSuffixClause()); // doBatchInsertOperations // server 4 belongs to site A serverExecute(4, batchInsertForBULK()); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id7", true, false); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "id2", true, false); executeSql(SITE_A, "Update EMP.PARTITIONED_TABLE set DESCRIPTION = 'Second' where ADDRESS = 'A714'"); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id2", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id2", true, false); sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "id2", true, false); // two rows are with same desc: SECOND // do bulk update executeSql(SITE_A, "Update EMP.PARTITIONED_TABLE set COMPANY = 'Pivotal' where DESCRIPTION = 'Second'"); // verify within site : ADDRESS=A715 sqlExecuteVerify(SITE_A, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id10", true, false); sqlExecuteVerify(SITE_A, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "id10", true, false); //wait for queue to be empty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify in remote site : ADDRESS=A715 sqlExecuteVerify(SITE_B, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id10", true, false); sqlExecuteVerify(SITE_B, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "id10", true, false); } public void testBULKDelete() throws Exception { String goldenFile = TestUtil.getResourcesDir() + "/lib/GemFireXDGatewayDUnit.xml"; // start two sites // each having 2 data-store nodes, 1 accessor and 1 locator // 1 locator // 1 datastore + sender // 1 datastore + sender + receiver // 1 accessor + sender + receiver startSites(2); // create gatewayreceiver final String createGWR = "create gatewayreceiver myrcvr(bindaddress 'localhost') server groups(sgSender)"; executeSql(SITE_B, createGWR); // create gatewaysender final String createGWS = getCreateGatewayDML(); executeSql(SITE_A, createGWS); // create PTable final String createPTable = "create table EMP.PARTITIONED_TABLE (ID int , " + "DESCRIPTION varchar(1024) not null, ADDRESS varchar(1024) not null, COMPANY varchar(1024), " + "primary key (ID)) partition by column(ADDRESS) redundancy 1 server groups (sg1)"; executeSql(SITE_A, createPTable + " GatewaySender (MySender)" + getSQLSuffixClause()); executeSql(SITE_B, createPTable + getSQLSuffixClause()); // doBatchInsertOperations // server 4 belongs to site A serverExecute(4, batchInsertForBULK()); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id7", true, false); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "id2", true, false); // update record to make desc same executeSql(SITE_A, "Update EMP.PARTITIONED_TABLE set DESCRIPTION = 'Second' where ADDRESS = 'A714'"); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id2", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id2", true, false); sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "id2", true, false); // two rows are with same desc: SECOND // do bulk update executeSql(SITE_A, "Delete from EMP.PARTITIONED_TABLE where DESCRIPTION = 'Second'"); // verify within site : ADDRESS=A715 sqlExecuteVerify(SITE_A, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "empty", true, false); sqlExecuteVerify(SITE_A, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "empty", true, false); //wait for queue to be empty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify in remote site : ADDRESS=A715 sqlExecuteVerify(SITE_B, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "empty", true, false); sqlExecuteVerify(SITE_B, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "empty", true, false); } public void testTxOperations() throws Exception { String goldenFile = TestUtil.getResourcesDir() + "/lib/GemFireXDGatewayDUnit.xml"; // start two sites // each having 2 data-store nodes, 1 accessor and 1 locator // 1 locator // 1 datastore + sender // 1 datastore + sender + receiver // 1 accessor + sender + receiver startSites(2); // create gatewayreceiver final String createGWR = "create gatewayreceiver myrcvr(bindaddress 'localhost') server groups(sgSender)"; executeSql(SITE_B, createGWR); // create gatewaysender final String createGWS = getCreateGatewayDML(); executeSql(SITE_A, createGWS); // create PTable final String createPTable = "create table EMP.PARTITIONED_TABLE (ID int , " + "DESCRIPTION varchar(1024) not null, ADDRESS varchar(1024) not null, COMPANY varchar(1024), " + "primary key (ID)) partition by column(ADDRESS) redundancy 1 server groups (sg1)"; executeSql(SITE_A, createPTable + " GatewaySender (MySender)" + getSQLSuffixClause()); executeSql(SITE_B, createPTable + getSQLSuffixClause()); // doTxInsertOperations // server 4 belongs to site A serverExecute(4, txInsert()); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id7", true, false); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "id2", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id7", true, false); sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "id2", true, false); } public void testTxInsertUpdateDeleteOperations() throws Exception { String goldenFile = TestUtil.getResourcesDir() + "/lib/GemFireXDGatewayDUnit.xml"; // start two sites // each having 2 data-store nodes, 1 accessor and 1 locator // 1 locator // 1 datastore + sender // 1 datastore + sender + receiver // 1 accessor + sender + receiver startSites(2); // create gatewayreceiver final String createGWR = "create gatewayreceiver myrcvr(bindaddress 'localhost') server groups(sgSender)"; executeSql(SITE_B, createGWR); // create gatewaysender final String createGWS = getCreateGatewayDML(); executeSql(SITE_A, createGWS); // create PTable final String createPTable = "create table EMP.PARTITIONED_TABLE (ID int , " + "DESCRIPTION varchar(1024) not null, ADDRESS varchar(1024) not null, COMPANY varchar(1024), " + "primary key (ID)) partition by column(ADDRESS) redundancy 1 server groups (sg1)"; executeSql(SITE_A, createPTable + " GatewaySender (MySender)" + getSQLSuffixClause()); executeSql(SITE_B, createPTable + getSQLSuffixClause()); // doTxInsertOperations // server 4 belongs to site A serverExecute(4, txInsert()); serverExecute(4, txUpdate()); sqlExecuteVerify(SITE_A, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id10", true, false); sqlExecuteVerify(SITE_A, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "id10", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id10", true, false); sqlExecuteVerify(SITE_B, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "id10", true, false); serverExecute(4, txDelete()); sqlExecuteVerify(SITE_A, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "empty", true, false); sqlExecuteVerify(SITE_A, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "empty", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "empty", true, false); sqlExecuteVerify(SITE_B, "select COMPANY from EMP.PARTITIONED_TABLE WHERE ID = 2", goldenFile, "empty", true, false); } private Runnable txUpdate() { SerializableRunnable senderConf = new SerializableRunnable( "Sender Configurator") { @Override public void run() throws CacheException { try { Connection conn = TestUtil.jdbcConn; conn.setAutoCommit(false); //conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); Statement st = conn.createStatement(); //st.execute("insert into EMP.PARTITIONED_TABLE values (1, 'First', 'A714', 'Pivotal')"); //st.execute("insert into EMP.PARTITIONED_TABLE values (2, 'Second', 'J 605', 'Zimbra')"); st.execute("Update EMP.PARTITIONED_TABLE set COMPANY = 'Pivotal' where DESCRIPTION = 'First'"); st.execute("Update EMP.PARTITIONED_TABLE set COMPANY = 'Pivotal' where DESCRIPTION = 'Second'"); conn.commit(); } catch (SQLException sqle) { throw GemFireXDRuntimeException.newRuntimeException(null, sqle); } } }; return senderConf; } private Runnable txDelete() { SerializableRunnable senderConf = new SerializableRunnable( "Sender Configurator") { @Override public void run() throws CacheException { try { Connection conn = TestUtil.jdbcConn; conn.setAutoCommit(false); //conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); Statement st = conn.createStatement(); //st.execute("insert into EMP.PARTITIONED_TABLE values (1, 'First', 'A714', 'Pivotal')"); //st.execute("insert into EMP.PARTITIONED_TABLE values (2, 'Second', 'J 605', 'Zimbra')"); st.execute("Delete from EMP.PARTITIONED_TABLE where ID = 1"); st.execute("Delete from EMP.PARTITIONED_TABLE where ID = 2"); conn.commit(); } catch (SQLException sqle) { throw GemFireXDRuntimeException.newRuntimeException(null, sqle); } } }; return senderConf; } public void testBasicInsertOnNonPKBasedTable() throws Exception { String goldenFile = TestUtil.getResourcesDir() + "/lib/GemFireXDGatewayDUnit.xml"; // start two sites // each having 2 data-store nodes, 1 accessor and 1 locator // 1 locator // 1 datastore + sender // 1 datastore + sender + receiver // 1 accessor + sender + receiver startSites(2); // create gatewayreceiver final String createGWR = "create gatewayreceiver myrcvr(bindaddress 'localhost') server groups(sgSender)"; executeSql(SITE_B, createGWR); // create gatewaysender final String createGWS = getCreateGatewayDML(); executeSql(SITE_A, createGWS); // create PTable (NON PK) final String createPTable = "create table EMP.PARTITIONED_TABLE (ID int , " + "DESCRIPTION varchar(1024) not null, ADDRESS varchar(1024) not null ) " + " partition by column(ADDRESS) redundancy 1 server groups (sg1)"; executeSql(SITE_A, createPTable + " GatewaySender (MySender)" + getSQLSuffixClause()); executeSql(SITE_B, createPTable + getSQLSuffixClause()); // doInsertOperations executeSql(SITE_A, "insert into EMP.PARTITIONED_TABLE values (1, 'First', 'A714')"); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id7", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id7", true, false); } public void testUpdateOnNonPKBasedTable() throws Exception { String goldenFile = TestUtil.getResourcesDir() + "/lib/GemFireXDGatewayDUnit.xml"; // start two sites // each having 2 data-store nodes, 1 accessor and 1 locator // 1 locator // 1 datastore + sender // 1 datastore + sender + receiver // 1 accessor + sender + receiver startSites(2); // create gatewayreceiver final String createGWR = "create gatewayreceiver myrcvr(bindaddress 'localhost') server groups(sgSender)"; executeSql(SITE_B, createGWR); // create gatewaysender final String createGWS = getCreateGatewayDML(); executeSql(SITE_A, createGWS); // create PTable (NON PK) final String createPTable = "create table EMP.PARTITIONED_TABLE (ID int , " + "DESCRIPTION varchar(1024) not null, ADDRESS varchar(1024) not null ) " + " partition by column(ADDRESS) redundancy 1 server groups (sg1)"; executeSql(SITE_A, createPTable + " GatewaySender (MySender)" + getSQLSuffixClause()); executeSql(SITE_B, createPTable + getSQLSuffixClause()); // doInsertOperations executeSql(SITE_A, "insert into EMP.PARTITIONED_TABLE values (1, 'First', 'A714')"); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id7", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id7", true, false); //doUpdateOperations executeSql(SITE_A, "Update EMP.PARTITIONED_TABLE set DESCRIPTION = 'Second' where ID = 1"); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id2", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "id2", true, false); //doDeleteOperations executeSql(SITE_A, "Delete from EMP.PARTITIONED_TABLE where ID = 1"); sqlExecuteVerify(SITE_A, "select ADDRESS from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "empty", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select ADDRESS from EMP.PARTITIONED_TABLE WHERE ID = 1", goldenFile, "empty", true, false); } public void testIdentityColumnGeneratedAlways() throws Exception { String goldenFile = TestUtil.getResourcesDir() + "/lib/GemFireXDGatewayDUnit.xml"; // start two sites // each having 2 data-store nodes, 1 accessor and 1 locator // 1 locator // 1 datastore + sender // 1 datastore + sender + receiver // 1 accessor + sender + receiver startSites(2); addExpectedException(new String[] { SITE_A, SITE_B }, new Object[] { PRLocallyDestroyedException.class, ForceReattemptException.class }); // create gatewayreceiver final String createGWR = "create gatewayreceiver myrcvr(bindaddress 'localhost') server groups(sgSender)"; executeSql(SITE_B, createGWR); // create gatewaysender final String createGWS = getCreateGatewayDML(); executeSql(SITE_A, createGWS); // create PTable final String createPTable = "create table EMP.PARTITIONED_TABLE (ID bigint GENERATED ALWAYS AS IDENTITY, " + "DESCRIPTION varchar(1024) not null, ADDRESS varchar(1024) not null, " + "primary key (ID)) partition by column(ADDRESS) redundancy 1 server groups (sg1)"; executeSql(SITE_A, createPTable + " GatewaySender (MySender)" + getSQLSuffixClause()); executeSql(SITE_B, createPTable + getSQLSuffixClause()); // doInsertOperations executeSql(SITE_A, "insert into EMP.PARTITIONED_TABLE (DESCRIPTION, ADDRESS)values ('First', 'A714')"); sqlExecuteVerify(SITE_A, "select ADDRESS from EMP.PARTITIONED_TABLE WHERE DESCRIPTION = 'First'", goldenFile, "id8", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify that ID is same on both site. sqlExecuteVerify(SITE_A, "select ADDRESS from EMP.PARTITIONED_TABLE WHERE DESCRIPTION = 'First'", goldenFile, "id8", true, false); //doUpdateOperations executeSql(SITE_A, "Update EMP.PARTITIONED_TABLE set DESCRIPTION = 'Second' where ADDRESS = 'A714'"); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ADDRESS = 'A714'", goldenFile, "id2", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ADDRESS = 'A714'", goldenFile, "id2", true, false); //doDeleteOperations executeSql(SITE_A, "Delete from EMP.PARTITIONED_TABLE where ADDRESS = 'A714'"); sqlExecuteVerify(SITE_A, "select ADDRESS from EMP.PARTITIONED_TABLE WHERE ADDRESS = 'A714'", goldenFile, "empty", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select ADDRESS from EMP.PARTITIONED_TABLE WHERE ADDRESS = 'A714'", goldenFile, "empty", true, false); } public void testIdentityColumnGeneratedDefault() throws Exception { String goldenFile = TestUtil.getResourcesDir() + "/lib/GemFireXDGatewayDUnit.xml"; // start two sites // each having 2 data-store nodes, 1 accessor and 1 locator // 1 locator // 1 datastore + sender // 1 datastore + sender + receiver // 1 accessor + sender + receiver startSites(2); addExpectedException(new String[] { SITE_A, SITE_B }, new Object[] { PRLocallyDestroyedException.class }); // create gatewayreceiver final String createGWR = "create gatewayreceiver myrcvr(bindaddress 'localhost') server groups(sgSender)"; executeSql(SITE_B, createGWR); // create gatewaysender final String createGWS = getCreateGatewayDML(); executeSql(SITE_A, createGWS); // create PTable final String createPTable = "create table EMP.PARTITIONED_TABLE (ID bigint GENERATED BY DEFAULT AS IDENTITY (START WITH 5,INCREMENT BY 5), " + "DESCRIPTION varchar(1024) not null, ADDRESS varchar(1024) not null, " + "primary key (ID)) partition by column(ADDRESS) redundancy 1 server groups (sg1)"; executeSql(SITE_A, createPTable + " GatewaySender (MySender)" + getSQLSuffixClause()); executeSql(SITE_B, createPTable + getSQLSuffixClause()); // doInsertOperations executeSql(SITE_A, "insert into EMP.PARTITIONED_TABLE (DESCRIPTION, ADDRESS)values ('First', 'A714')"); sqlExecuteVerify(SITE_A, "select ADDRESS from EMP.PARTITIONED_TABLE WHERE DESCRIPTION = 'First'", goldenFile, "id8", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify that ID is same on both site. sqlExecuteVerify(SITE_A, "select ADDRESS from EMP.PARTITIONED_TABLE WHERE DESCRIPTION = 'First'", goldenFile, "id8", true, false); //doUpdateOperations executeSql(SITE_A, "Update EMP.PARTITIONED_TABLE set DESCRIPTION = 'Second' where ADDRESS = 'A714'"); sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ADDRESS = 'A714'", goldenFile, "id2", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_A, "select DESCRIPTION from EMP.PARTITIONED_TABLE WHERE ADDRESS = 'A714'", goldenFile, "id2", true, false); //doDeleteOperations executeSql(SITE_A, "Delete from EMP.PARTITIONED_TABLE where ADDRESS = 'A714'"); sqlExecuteVerify(SITE_A, "select ADDRESS from EMP.PARTITIONED_TABLE WHERE ADDRESS = 'A714'", goldenFile, "empty", true, false); // waitForTheQueueToGetEmpty executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); // verify sqlExecuteVerify(SITE_B, "select ADDRESS from EMP.PARTITIONED_TABLE WHERE ADDRESS = 'A714'", goldenFile, "empty", true, false); } public void testDAP_PartitionedRegion() throws Exception { String goldenFile = TestUtil.getResourcesDir() + "/lib/GemFireXDGatewayDUnit.xml"; startSites(2); addExpectedException(new String[] { SITE_A, SITE_B }, new Object[] { PRLocallyDestroyedException.class }); // create gatewayreceiver final String createGWR = "create gatewayreceiver myrcvr(bindaddress 'localhost') server groups(sgSender)"; executeSql(SITE_B, createGWR); // create gatewaysender final String createGWS = getCreateGatewayDML(); executeSql(SITE_A, createGWS); // create PTable final String createPTable = "create table EMP.PARTITIONED_TABLE (ID int , " + "DESCRIPTION varchar(1024) not null, ADDRESS varchar(1024) not null, COMPANY varchar(1024) DEFAULT 'Pivotal'," + "primary key (ID)) partition by column(ADDRESS) redundancy 1 server groups (sg1)"; executeSql(SITE_A, createPTable + " GatewaySender (MySender)"); executeSql(SITE_B, createPTable); serverExecute(4, wanInsertDAP("EMP.PARTITIONED_TABLE")); executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); sqlExecuteVerify(SITE_B, "select DESCRIPTION from EMP.PARTITIONED_TABLE", goldenFile, "batch_id2", true, false); final String wanUpdateDAP = "CREATE PROCEDURE wan_update_dap(IN inParam1 VARCHAR(50)) LANGUAGE JAVA PARAMETER STYLE JAVA MODIFIES SQL DATA EXTERNAL NAME '" + GfxdWanCommonTestBase.class.getName() + ".wanUpdateDAP'"; serverExecute(4, callDAP(wanUpdateDAP, "EMP.PARTITIONED_TABLE")); sqlExecuteVerify(SITE_A, "select COMPANY from EMP.PARTITIONED_TABLE ORDER BY ID", goldenFile, "batch_id8", true, false); executeSql(SITE_A, "call SYS.WAIT_FOR_SENDER_QUEUE_FLUSH('MYSENDER', 0, 0)"); sqlExecuteVerify(SITE_B, "select COMPANY from EMP.PARTITIONED_TABLE ORDER BY ID", goldenFile, "batch_id8", true, false); } public static Runnable wanInsertDAP(final String table) throws SQLException { SerializableRunnable wanInsert = new SerializableRunnable( "DAP Caller") { @Override public void run() throws CacheException { try { Connection conn = TestUtil.jdbcConn; Statement st = conn.createStatement(); boolean orig = conn.getAutoCommit(); conn.setAutoCommit(false); st.addBatch("insert into " + table + " values (1, 'First', 'A', 'VMWARE')"); st.addBatch("insert into " + table + " values (2, 'Second', 'B', 'VMWARE')"); st.addBatch("insert into " + table + " values (3, 'Third', 'C', 'VMWARE')"); st.addBatch("insert into " + table + " values (4, 'Fourth', 'D', 'VMWARE')"); st.addBatch("insert into " + table + " values (5, 'Fifth', 'E', 'VMWARE')"); st.addBatch("insert into " + table + " values (6, 'Sixth', 'F', 'VMWARE')"); st.executeBatch(); conn.commit(); conn.setAutoCommit(orig); } catch (SQLException sqle) { throw GemFireXDRuntimeException.newRuntimeException(null, sqle); } } }; return wanInsert; } public static void wanUpdateDAP(String inParam1, ProcedureExecutionContext context) throws SQLException { Connection conn = context.getConnection(); Statement st = conn.createStatement(); st.execute("<local> Update "+inParam1+ " set COMPANY = 'PIVOTAL' where ID = 2 OR ID = 4 OR ID = 6"); } public static Runnable callDAP(final String procedure, final String table){ SerializableRunnable senderConf = new SerializableRunnable( "DAP Caller") { @Override public void run() throws CacheException { try { Connection conn = TestUtil.jdbcConn; Statement st = conn.createStatement(); st.execute(procedure); CallableStatement cs = null; cs = conn.prepareCall("CALL wan_update_dap(?) ON SERVER GROUPS (sg2)"); cs.setString(1, table); cs.execute(); } catch (SQLException sqle) { throw GemFireXDRuntimeException.newRuntimeException(null, sqle); } } }; return senderConf; } public static Runnable batchInsert() { SerializableRunnable senderConf = new SerializableRunnable( "Sender Configurator") { @Override public void run() throws CacheException { try { Connection conn = TestUtil.jdbcConn; Statement st = conn.createStatement(); st.addBatch("insert into EMP.PARTITIONED_TABLE values (1, 'First', 'A714', 'Pivotal')"); st.addBatch("insert into EMP.PARTITIONED_TABLE values (2, 'Second', 'J 605', 'Pivotal')"); st.executeBatch(); } catch (SQLException sqle) { throw GemFireXDRuntimeException.newRuntimeException(null, sqle); } } }; return senderConf; } public static Runnable batchUpdate() { SerializableRunnable senderConf = new SerializableRunnable( "Sender Configurator") { @Override public void run() throws CacheException { try { Connection conn = TestUtil.jdbcConn; Statement st = conn.createStatement(); st.addBatch("Update EMP.PARTITIONED_TABLE set COMPANY = 'Pivotal' where DESCRIPTION = 'First'"); st.addBatch("Update EMP.PARTITIONED_TABLE set COMPANY = 'Pivotal' where DESCRIPTION = 'Second'"); st.executeBatch(); } catch (SQLException sqle) { throw GemFireXDRuntimeException.newRuntimeException(null, sqle); } } }; return senderConf; } public static Runnable batchDelete() { SerializableRunnable senderConf = new SerializableRunnable( "Sender Configurator") { @Override public void run() throws CacheException { try { Connection conn = TestUtil.jdbcConn; Statement st = conn.createStatement(); st.addBatch("Delete from EMP.PARTITIONED_TABLE where ID = 1"); st.addBatch("Delete from EMP.PARTITIONED_TABLE where ID = 2"); st.executeBatch(); } catch (SQLException sqle) { throw GemFireXDRuntimeException.newRuntimeException(null, sqle); } } }; return senderConf; } public static Runnable batchInsertForBULK() { SerializableRunnable senderConf = new SerializableRunnable( "Sender Configurator") { @Override public void run() throws CacheException { try { Connection conn = TestUtil.jdbcConn; Statement st = conn.createStatement(); st.addBatch("insert into EMP.PARTITIONED_TABLE values (1, 'First', 'A714', 'Pivotal')"); st.addBatch("insert into EMP.PARTITIONED_TABLE values (2, 'Second', 'J 605', 'Zimbra')"); st.executeBatch(); } catch (SQLException sqle) { throw GemFireXDRuntimeException.newRuntimeException(null, sqle); } } }; return senderConf; } public static Runnable txInsert() { SerializableRunnable senderConf = new SerializableRunnable( "Sender Configurator") { @Override public void run() throws CacheException { boolean origAutocommit = false; Connection conn = null; try { conn = TestUtil.jdbcConn; origAutocommit = conn.getAutoCommit(); conn.setAutoCommit(false); //conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); Statement st = conn.createStatement(); st.execute("insert into EMP.PARTITIONED_TABLE values (1, 'First', 'A714', 'Pivotal')"); st.execute("insert into EMP.PARTITIONED_TABLE values (2, 'Second', 'J 605', 'Zimbra')"); conn.commit(); } catch (SQLException sqle) { throw GemFireXDRuntimeException.newRuntimeException(null, sqle); } finally { if (conn != null) { try { conn.setAutoCommit(origAutocommit); } catch (SQLException e) { // Ignore } } } } }; return senderConf; } public static Runnable prepInsert() { SerializableRunnable senderConf = new SerializableRunnable( "Sender Configurator") { @Override public void run() throws CacheException { try { Connection conn = TestUtil.jdbcConn; conn.setAutoCommit(false); conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); PreparedStatement prep = conn.prepareStatement("insert into " + "EMP.PARTITIONED_TABLE (ID, DESCRIPTION, ADDRESS, COMPANY) values (?, ?, ?, ?)"); prep.setInt(1,1); prep.setString(2, "First"); prep.setString(3, "A714"); prep.setString(4, "Pivotal"); prep.addBatch(); prep.setInt(1,2); prep.setString(2, "Second"); prep.setString(3, "J 605"); prep.setString(4, "Zimbra"); prep.addBatch(); prep.executeBatch(); conn.commit(); } catch (SQLException sqle) { throw GemFireXDRuntimeException.newRuntimeException(null, sqle); } } }; return senderConf; } private static SerializableRunnable getExecutorToWaitForQueuesToDrain( final String senderId, final int regionSize) { SerializableRunnable waitForQueueToDrain = new SerializableRunnable( "waitForQueueToDrain") { @Override public void run() throws CacheException { Set<GatewaySender> senders = Misc.getGemFireCache() .getAllGatewaySenders(); Misc.getGemFireCache() .getLogger() .fine( "Inside waitForQueueToDrain for sender " + senderId + " all senders in cache are " + senders); ParallelGatewaySenderImpl sender = null; for (GatewaySender s : senders) { if (s.getId().equals(senderId)) { sender = (ParallelGatewaySenderImpl)s; break; } } AbstractGatewaySenderEventProcessor processor = sender .getEventProcessor(); if (processor == null) return; final Region<?, ?> region = processor.getQueue().getRegion(); WaitCriterion wc = new WaitCriterion() { public boolean done() { if (region.keySet().size() == regionSize) { Misc.getGemFireCache() .getLogger() .fine( "Inside waitForQueueToDrain for sender " + senderId + " queue is drained and empty "); return true; } Misc.getGemFireCache() .getLogger() .fine( "Inside waitForQueueToDrain for sender " + senderId + " queue is not yet drained " + region.keySet().size()); return false; } public String description() { return "Expected queue entries: " + regionSize + " but actual entries: " + region.keySet().size(); } }; waitForCriterion(wc, 60000, 500, true); } }; return waitForQueueToDrain; } }
3e09f4b389da63f155ed2357888881618c6c3a9a
903
java
Java
src/main/java/org/librenote/mc/cardinal/utils/events/PlayerJoin.java
oprogram/cardinal-utils
80cd8f3a84d2308992ed1e94f43df9de2365b369
[ "BSD-2-Clause" ]
null
null
null
src/main/java/org/librenote/mc/cardinal/utils/events/PlayerJoin.java
oprogram/cardinal-utils
80cd8f3a84d2308992ed1e94f43df9de2365b369
[ "BSD-2-Clause" ]
null
null
null
src/main/java/org/librenote/mc/cardinal/utils/events/PlayerJoin.java
oprogram/cardinal-utils
80cd8f3a84d2308992ed1e94f43df9de2365b369
[ "BSD-2-Clause" ]
null
null
null
39.26087
129
0.739756
4,226
package org.librenote.mc.cardinal.utils.events; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.librenote.mc.cardinal.utils.mechanics.CountryData; public class PlayerJoin implements Listener { @EventHandler public void onPlayerJoinEvent(PlayerJoinEvent playerJoinEvent) { Player player = playerJoinEvent.getPlayer(); if (!player.hasPlayedBefore()) { CountryData countryData = new CountryData(); String countryCode = countryData.getCountryCode(player); player.teleport(countryData.getCoords(countryData.getCountryCode(player), player.getWorld())); player.sendMessage(ChatColor.RED + "Welcome to LibreCraft. You have spawned in " + countryData.getName(countryCode)); } } }
3e09f4c31eabd360a14ca8345561e874cd39faf3
3,270
java
Java
app/src/main/java/org/ssyp/theforceawakens/game/Player.java
ssyp-ru/ssyp16-ws01
43ba941a26037ad8a49a545e5716db4518bebe9e
[ "CC0-1.0" ]
null
null
null
app/src/main/java/org/ssyp/theforceawakens/game/Player.java
ssyp-ru/ssyp16-ws01
43ba941a26037ad8a49a545e5716db4518bebe9e
[ "CC0-1.0" ]
null
null
null
app/src/main/java/org/ssyp/theforceawakens/game/Player.java
ssyp-ru/ssyp16-ws01
43ba941a26037ad8a49a545e5716db4518bebe9e
[ "CC0-1.0" ]
null
null
null
26.16
103
0.656269
4,227
package org.ssyp.theforceawakens.game; import org.ssyp.theforceawakens.commands.clientcommands.MsgCommand; import org.ssyp.theforceawakens.connection.Connection; import org.ssyp.theforceawakens.game.fight.Fight; import org.ssyp.theforceawakens.game.fight.FightRespond; import static org.ssyp.theforceawakens.game.PlayerState.Dead; import static org.ssyp.theforceawakens.game.PlayerState.Fighting; import static org.ssyp.theforceawakens.game.Team.Jedi; import static org.ssyp.theforceawakens.game.Team.Sith; import static org.ssyp.theforceawakens.game.World.*; public class Player implements Positionable { private Position position; private String name; private Team team; private PlayerState playerState; private Connection connection; private boolean listenWorldUpdate = false; private boolean listenRosterUpdate = false; private long timeToRespawn = 0; private Fight fight; public Player(String name, Connection connection) { this.name = name; this.connection = connection; this.team = Team.Neutral; this.position = new Position(0, 0); } public long getTimeToRespawn() { return timeToRespawn; } public Connection getConnection() { return connection; } public void setConnection(Connection connection) { this.connection = connection; } public String getName() { return name; } public Team getTeam() { return team; } /* game mechanics */ public void setTeam(Team team) { this.team = team; } public PlayerState getPlayerState() { return playerState; } public void setPlayerState(PlayerState playerState) { this.playerState = playerState; if(playerState == Dead) { this.timeToRespawn = System.currentTimeMillis() + RESPAWN_TIME; World.getInstance().notifyPlayers(new MsgCommand("Player " + this.name + " is now dead.")); } } public void endFight(PlayerState state) { this.fight = null; this.setPlayerState(state); } public void startFight(Fight fight) { this.fight = fight; this.setPlayerState(Fighting); } public void onFightRespond(FightRespond respond) { if(this.fight == null) return; this.fight.playerAttack(this, respond); } @Override public Position getPosition() { return position; } public void setPosition(Position position) { this.position = position; } @Override public String toString() { return this.name + " " + this.position + " " + this.team; } public void changeTeam() { this.team = (this.team == Jedi) ? Sith : Jedi; } public boolean getListenWorldUpdate() { return listenWorldUpdate; } public void setListenWorldUpdate(boolean isReady) { listenWorldUpdate = isReady; if (isReady) { listenRosterUpdate = false; } } public boolean getListenRosterUpdate() { return listenRosterUpdate; } public void setListenRosterUpdate(boolean isReady) { listenRosterUpdate = isReady; if (isReady) { listenWorldUpdate = false; } } }
3e09f548b96c56ba0aaf674b034cda926cee9ff8
1,606
java
Java
commons-math-legacy/src/main/java/org/apache/commons/math4/legacy/linear/NonSquareMatrixException.java
isabella232/commons-math
e052d9dc532be69c75b24973cf585865c02b63b2
[ "Apache-2.0" ]
494
2015-01-02T11:59:45.000Z
2022-03-24T20:03:06.000Z
commons-math-legacy/src/main/java/org/apache/commons/math4/legacy/linear/NonSquareMatrixException.java
isabella232/commons-math
e052d9dc532be69c75b24973cf585865c02b63b2
[ "Apache-2.0" ]
112
2015-07-05T18:55:27.000Z
2022-02-06T06:00:33.000Z
commons-math-legacy/src/main/java/org/apache/commons/math4/legacy/linear/NonSquareMatrixException.java
isabella232/commons-math
e052d9dc532be69c75b24973cf585865c02b63b2
[ "Apache-2.0" ]
462
2015-01-06T11:45:14.000Z
2022-03-24T18:42:10.000Z
38.238095
76
0.730386
4,228
/* * 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.commons.math4.legacy.linear; import org.apache.commons.math4.legacy.exception.DimensionMismatchException; import org.apache.commons.math4.legacy.exception.util.LocalizedFormats; /** * Exception to be thrown when a square matrix is expected. * * @since 3.0 */ public class NonSquareMatrixException extends DimensionMismatchException { /** Serializable version Id. */ private static final long serialVersionUID = -660069396594485772L; /** * Construct an exception from the mismatched dimensions. * * @param wrong Row dimension. * @param expected Column dimension. */ public NonSquareMatrixException(int wrong, int expected) { super(LocalizedFormats.NON_SQUARE_MATRIX, wrong, expected); } }
3e09f60219664d3ff9ea9fdf549acd978df4af2d
1,636
java
Java
shared/src/main/java/rs/iota/jni/IOTA.java
teampothole/XDKAbdroidBluetoothConnectiondSendIOTA
6ae3e07220d6b35acf986df2a28b61a9b4340458
[ "Apache-2.0" ]
null
null
null
shared/src/main/java/rs/iota/jni/IOTA.java
teampothole/XDKAbdroidBluetoothConnectiondSendIOTA
6ae3e07220d6b35acf986df2a28b61a9b4340458
[ "Apache-2.0" ]
null
null
null
shared/src/main/java/rs/iota/jni/IOTA.java
teampothole/XDKAbdroidBluetoothConnectiondSendIOTA
6ae3e07220d6b35acf986df2a28b61a9b4340458
[ "Apache-2.0" ]
null
null
null
29.214286
83
0.588631
4,229
package rs.iota.jni; import java.io.IOException; import java.util.concurrent.atomic.AtomicReference; public class IOTA { private enum LibraryState { NOT_LOADED, LOADING, LOADED } private static AtomicReference<LibraryState> libraryLoaded = new AtomicReference<>(LibraryState.NOT_LOADED); static { IOTA.loadLibrary(); } /** * Loads the necessary library files. * Calling this method twice will have no effect. * By default the method extracts the shared library for loading at * java.io.tmpdir, however, you can override this temporary location by * setting the environment variable IOTA_SHAREDLIB_DIR. */ public static void loadLibrary() { if (libraryLoaded.get() == LibraryState.LOADED) { return; } if (libraryLoaded.compareAndSet(LibraryState.NOT_LOADED, LibraryState.LOADING)) { final String tmpDir = System.getenv("IOTA_SHAREDLIB_DIR"); try { NativeLibraryLoader.getInstance().loadLibrary(tmpDir); } catch (IOException e) { libraryLoaded.set(LibraryState.NOT_LOADED); throw new RuntimeException("Unable to load the IOTA shared library" + e); } libraryLoaded.set(LibraryState.LOADED); return; } while (libraryLoaded.get() == LibraryState.LOADING) { try { Thread.sleep(10); } catch (final InterruptedException e) { //ignore } } } }
3e09f6ea6461db6bb2009d7c3976f7b9279b0c7c
4,745
java
Java
master_worker/deployment/digigob/digigob/deo-parent/deo-base-core/src/main/java/com/egoveris/deo/base/task/RechazarDocumento.java
GrupoWeb/k8s_srv_mineco
8be27c3d88d52a155a7a577a9a98af8baa68e89d
[ "MIT" ]
null
null
null
master_worker/deployment/digigob/digigob/deo-parent/deo-base-core/src/main/java/com/egoveris/deo/base/task/RechazarDocumento.java
GrupoWeb/k8s_srv_mineco
8be27c3d88d52a155a7a577a9a98af8baa68e89d
[ "MIT" ]
null
null
null
master_worker/deployment/digigob/digigob/deo-parent/deo-base-core/src/main/java/com/egoveris/deo/base/task/RechazarDocumento.java
GrupoWeb/k8s_srv_mineco
8be27c3d88d52a155a7a577a9a98af8baa68e89d
[ "MIT" ]
null
null
null
44.345794
98
0.773235
4,230
package com.egoveris.deo.base.task; import com.egoveris.deo.base.service.AvisoService; import com.egoveris.deo.base.service.FirmaConjuntaService; import com.egoveris.deo.base.service.TipoDocumentoService; import com.egoveris.deo.model.model.TipoDocumentoDTO; import com.egoveris.deo.util.Constantes; import com.egoveris.sharedsecurity.base.model.Usuario; import com.egoveris.sharedsecurity.base.service.IUsuarioService; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jbpm.api.ProcessEngine; import org.jbpm.api.activity.ActivityExecution; import org.jbpm.api.activity.ExternalActivityBehaviour; import org.springframework.beans.factory.annotation.Autowired; public class RechazarDocumento implements ExternalActivityBehaviour { private static final long serialVersionUID = 1L; @Autowired private transient ProcessEngine processEngine; @Autowired private TipoDocumentoService tipoDocumentoService; @Autowired private FirmaConjuntaService firmaConjuntaService; @Autowired private AvisoService avisoService; @Autowired private IUsuarioService usuarioService; public void signal(ActivityExecution execution, String signalName, Map<String, ?> parameters) throws Exception { execution.take(signalName); } @SuppressWarnings("unchecked") public void execute(ActivityExecution execution) throws Exception { String executionId = execution.getId(); int idTipoDocumento = Integer.parseInt((String) this.processEngine.getExecutionService() .getVariable(executionId, Constantes.VAR_TIPO_DOCUMENTO)); TipoDocumentoDTO tipoDocumentoGedo = tipoDocumentoService .buscarTipoDocumentoPorId(idTipoDocumento); String usuarioDerivador = (String) this.processEngine.getExecutionService() .getVariable(executionId, Constantes.VAR_USUARIO_DERIVADOR); String usuarioRechazo = (String) this.processEngine.getExecutionService() .getVariable(executionId, Constantes.VAR_USUARIO_FIRMANTE); this.processEngine.getExecutionService().setVariable(executionId, Constantes.VAR_USUARIO_REVISOR, usuarioDerivador); this.processEngine.getExecutionService().setVariable(executionId, Constantes.VAR_USUARIO_DERIVADOR, usuarioRechazo); this.processEngine.getExecutionService().setVariable(executionId, Constantes.VAR_TAREA_RECHAZO_DOCUMENTO, Constantes.TRANSICION_RECHAZADO); List<String> receptoresAviso = (List<String>) this.processEngine.getExecutionService() .getVariable(executionId, Constantes.VAR_RECEPTORES_AVISO_FIRMA); if (!receptoresAviso.contains(usuarioDerivador)) receptoresAviso.add(usuarioDerivador); String usuarioApoderador; // Adicionar al listado de avisos el usuario apoderador, si éste existiera. if (this.usuarioService.licenciaActiva(usuarioDerivador, new Date())) { usuarioApoderador = this.usuarioService.obtenerUsuario(usuarioDerivador).getApoderado(); } else { usuarioApoderador = usuarioDerivador; } if (usuarioApoderador != null && !receptoresAviso.contains(usuarioApoderador)) receptoresAviso.add(usuarioApoderador); // Si el tipo de documento exige firma conjunta se adicionan todos los // firmantes para que reciban el aviso // de RECHAZO. if (tipoDocumentoGedo.getEsFirmaConjunta()) { List<Usuario> usuarios = this.firmaConjuntaService.buscarFirmantesPorEstado(executionId, true); for (Usuario usuario : usuarios) { if (!receptoresAviso.contains(usuario.getUsername())) receptoresAviso.add(usuario.getUsername()); } List<Usuario> usuariosRevisores = this.firmaConjuntaService .buscarRevisoresPorEstado(executionId, true); for (Usuario usuarioRevisor : usuariosRevisores) { if (!receptoresAviso.contains(usuarioRevisor.getUsername())) receptoresAviso.add(usuarioRevisor.getUsername()); } // Actualizar estado de la lista de firmantes, solo si es template. this.firmaConjuntaService.actualizarEstadoFirmantes(executionId, false); this.firmaConjuntaService.actualizarEstadoRevisores(executionId, false); } Map<String, String> datos = new HashMap<String, String>(); datos.put("motivo", (String) this.processEngine.getExecutionService().getVariable(executionId, Constantes.VAR_MOTIVO_RECHAZO)); datos.put("referencia", (String) this.processEngine.getExecutionService() .getVariable(executionId, Constantes.VAR_MOTIVO)); this.avisoService.guardarAvisosRechazo(receptoresAviso, datos, usuarioRechazo); this.processEngine.getExecutionService().signalExecutionById(executionId, Constantes.TRANSICION_RECHAZO_TEMPLATE); } }
3e09f7ac09b3dd9bb802054a486affc497db986a
560
java
Java
app/src/main/java/com/example/path_02/Creators.java
Shehara-r-001/PATH-Android-App
04ddfc2f895ed47f834776979f1753ec452e3f0b
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/path_02/Creators.java
Shehara-r-001/PATH-Android-App
04ddfc2f895ed47f834776979f1753ec452e3f0b
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/path_02/Creators.java
Shehara-r-001/PATH-Android-App
04ddfc2f895ed47f834776979f1753ec452e3f0b
[ "Apache-2.0" ]
null
null
null
29.473684
117
0.778571
4,231
package com.example.path_02; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; import androidx.appcompat.app.AppCompatActivity; public class Creators extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.creators); } }
3e09f813971ce2522ee8a0c40683b4d82bb22e0c
7,604
java
Java
geode-gfsh/src/main/java/org/apache/geode/management/internal/cli/functions/GatewaySenderCreateFunction.java
nikochiko/geode
19f55add07d6a652911dc5a5e2116fcf7bf7b2f7
[ "Apache-2.0" ]
1,475
2016-12-06T06:10:53.000Z
2022-03-30T09:55:23.000Z
geode-gfsh/src/main/java/org/apache/geode/management/internal/cli/functions/GatewaySenderCreateFunction.java
nikochiko/geode
19f55add07d6a652911dc5a5e2116fcf7bf7b2f7
[ "Apache-2.0" ]
2,809
2016-12-06T19:24:26.000Z
2022-03-31T22:02:20.000Z
geode-gfsh/src/main/java/org/apache/geode/management/internal/cli/functions/GatewaySenderCreateFunction.java
Krishnan-Raghavan/geode
708588659751c1213c467f5b200b2c36952af563
[ "Apache-2.0", "BSD-3-Clause" ]
531
2016-12-06T05:48:47.000Z
2022-03-31T23:06:37.000Z
39.604167
100
0.76223
4,232
/* * 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.cli.functions; import java.util.List; import org.apache.logging.log4j.Logger; import org.apache.geode.annotations.Immutable; import org.apache.geode.cache.Cache; import org.apache.geode.cache.execute.FunctionContext; import org.apache.geode.cache.execute.ResultSender; import org.apache.geode.cache.wan.GatewayEventFilter; import org.apache.geode.cache.wan.GatewaySender; import org.apache.geode.cache.wan.GatewaySender.OrderPolicy; import org.apache.geode.cache.wan.GatewaySenderFactory; import org.apache.geode.cache.wan.GatewayTransportFilter; import org.apache.geode.internal.cache.execute.InternalFunction; import org.apache.geode.logging.internal.log4j.api.LogService; import org.apache.geode.management.internal.cli.CliUtils; import org.apache.geode.management.internal.functions.CliFunctionResult; import org.apache.geode.management.internal.i18n.CliStrings; import org.apache.geode.management.internal.util.ManagementUtils; public class GatewaySenderCreateFunction implements InternalFunction<GatewaySenderFunctionArgs> { private static final Logger logger = LogService.getLogger(); private static final long serialVersionUID = 8746830191680509335L; @Immutable public static final GatewaySenderCreateFunction INSTANCE = new GatewaySenderCreateFunction(); private static final String ID = "org.apache.geode.management.internal.cli.functions.GatewaySenderCreateFunction"; @Override public String getId() { return ID; } @Override public void execute(FunctionContext<GatewaySenderFunctionArgs> context) { ResultSender<Object> resultSender = context.getResultSender(); Cache cache = context.getCache(); String memberNameOrId = context.getMemberName(); GatewaySenderFunctionArgs gatewaySenderCreateArgs = context.getArguments(); try { GatewaySender createdGatewaySender = createGatewaySender(cache, gatewaySenderCreateArgs); resultSender.lastResult(new CliFunctionResult(memberNameOrId, CliFunctionResult.StatusState.OK, CliStrings.format( CliStrings.CREATE_GATEWAYSENDER__MSG__GATEWAYSENDER_0_CREATED_ON_1, createdGatewaySender.getId(), memberNameOrId))); } catch (Exception e) { logger.error(e.getMessage(), e); resultSender.lastResult(new CliFunctionResult(memberNameOrId, e, null)); } } /** * Creates the GatewaySender with given configuration. * */ @SuppressWarnings("deprecation") private GatewaySender createGatewaySender(Cache cache, GatewaySenderFunctionArgs gatewaySenderCreateArgs) { GatewaySenderFactory gateway = cache.createGatewaySenderFactory(); Boolean isParallel = gatewaySenderCreateArgs.isParallel(); if (isParallel != null) { gateway.setParallel(isParallel); } Boolean groupTransactionEvents = gatewaySenderCreateArgs.mustGroupTransactionEvents(); if (groupTransactionEvents != null) { gateway.setGroupTransactionEvents(groupTransactionEvents); } Boolean manualStart = gatewaySenderCreateArgs.isManualStart(); if (manualStart != null) { gateway.setManualStart(manualStart); } Integer maxQueueMemory = gatewaySenderCreateArgs.getMaxQueueMemory(); if (maxQueueMemory != null) { gateway.setMaximumQueueMemory(maxQueueMemory); } Integer batchSize = gatewaySenderCreateArgs.getBatchSize(); if (batchSize != null) { gateway.setBatchSize(batchSize); } Integer batchTimeInterval = gatewaySenderCreateArgs.getBatchTimeInterval(); if (batchTimeInterval != null) { gateway.setBatchTimeInterval(batchTimeInterval); } Boolean enableBatchConflation = gatewaySenderCreateArgs.isBatchConflationEnabled(); if (enableBatchConflation != null) { gateway.setBatchConflationEnabled(enableBatchConflation); } Integer socketBufferSize = gatewaySenderCreateArgs.getSocketBufferSize(); if (socketBufferSize != null) { gateway.setSocketBufferSize(socketBufferSize); } Integer socketReadTimeout = gatewaySenderCreateArgs.getSocketReadTimeout(); if (socketReadTimeout != null) { gateway.setSocketReadTimeout(socketReadTimeout); } Integer alertThreshold = gatewaySenderCreateArgs.getAlertThreshold(); if (alertThreshold != null) { gateway.setAlertThreshold(alertThreshold); } Integer dispatcherThreads = gatewaySenderCreateArgs.getDispatcherThreads(); if (dispatcherThreads != null) { gateway.setDispatcherThreads(dispatcherThreads); } if (dispatcherThreads != null && dispatcherThreads > 1) { String orderPolicy = gatewaySenderCreateArgs.getOrderPolicy(); gateway.setOrderPolicy(OrderPolicy.valueOf(orderPolicy)); } Boolean isPersistenceEnabled = gatewaySenderCreateArgs.isPersistenceEnabled(); if (isPersistenceEnabled != null) { gateway.setPersistenceEnabled(isPersistenceEnabled); } String diskStoreName = gatewaySenderCreateArgs.getDiskStoreName(); if (diskStoreName != null) { gateway.setDiskStoreName(diskStoreName); } Boolean isDiskSynchronous = gatewaySenderCreateArgs.isDiskSynchronous(); if (isDiskSynchronous != null) { gateway.setDiskSynchronous(isDiskSynchronous); } List<String> gatewayEventFilters = gatewaySenderCreateArgs.getGatewayEventFilter(); if (gatewayEventFilters != null) { for (String gatewayEventFilter : gatewayEventFilters) { Class<?> gatewayEventFilterKlass = ManagementUtils.forName(gatewayEventFilter, CliStrings.CREATE_GATEWAYSENDER__GATEWAYEVENTFILTER); gateway.addGatewayEventFilter( (GatewayEventFilter) CliUtils.newInstance(gatewayEventFilterKlass, CliStrings.CREATE_GATEWAYSENDER__GATEWAYEVENTFILTER)); } } List<String> gatewayTransportFilters = gatewaySenderCreateArgs.getGatewayTransportFilter(); if (gatewayTransportFilters != null) { for (String gatewayTransportFilter : gatewayTransportFilters) { Class<?> gatewayTransportFilterKlass = ManagementUtils.forName(gatewayTransportFilter, CliStrings.CREATE_GATEWAYSENDER__GATEWAYTRANSPORTFILTER); gateway.addGatewayTransportFilter((GatewayTransportFilter) CliUtils.newInstance( gatewayTransportFilterKlass, CliStrings.CREATE_GATEWAYSENDER__GATEWAYTRANSPORTFILTER)); } } Boolean enforceThreadsConnectSameReceiver = gatewaySenderCreateArgs.getEnforceThreadsConnectSameReceiver(); if (enforceThreadsConnectSameReceiver != null) { gateway.setEnforceThreadsConnectSameReceiver(enforceThreadsConnectSameReceiver); } return gateway.create(gatewaySenderCreateArgs.getId(), gatewaySenderCreateArgs.getRemoteDistributedSystemId()); } }
3e09f8b435ad65f53b8cdb54d8b8d2f8292f7ae3
3,369
java
Java
workflows/src/main/java/tipl/blocks/XDFBlock.java
JLLeitschuh/TIPL
89c5d82932f89a2b4064d5d86ac83045ce9bc7d5
[ "Apache-2.0" ]
1
2019-11-22T11:02:52.000Z
2019-11-22T11:02:52.000Z
workflows/src/main/java/tipl/blocks/XDFBlock.java
JLLeitschuh/TIPL
89c5d82932f89a2b4064d5d86ac83045ce9bc7d5
[ "Apache-2.0" ]
4
2019-11-21T14:13:32.000Z
2020-02-11T15:15:23.000Z
workflows/src/main/java/tipl/blocks/XDFBlock.java
JLLeitschuh/TIPL
89c5d82932f89a2b4064d5d86ac83045ce9bc7d5
[ "Apache-2.0" ]
1
2020-02-11T06:19:45.000Z
2020-02-11T06:19:45.000Z
28.075
99
0.639062
4,233
package tipl.blocks; import tipl.formats.TImgRO; import tipl.tools.XDF; import tipl.util.ArgumentParser; import tipl.util.ITIPLPluginIO; import tipl.util.TIPLGlobal; import tipl.util.TImgTools; /** * Run XDF analysis on a (or more than one) input image * * @author mader */ public class XDFBlock extends LocalTIPLBlock { /** * XDF Block is the block designed for using the XDF plugin and calculating a number of * different analyses from the input. The primary is a simple two point correlation function of * a fixed structure, but others include A to be phase correlations and ... * * @author mader */ @BaseTIPLBlock.BlockIdentity(blockName = "XDFBlock", inputNames = {"object(s) image", "mask image", "gray value image"}, outputNames = {"correlation function"}) final public static class xdfBlockFactory implements BaseTIPLBlock.TIPLBlockFactory { @Override public ITIPLBlock get() { return new XDFBlock(); } } ; public String prefix; public int minVoxCount; public String phaseName; // public double sphKernelRadius; public boolean writeShapeTensor; public final IBlockImage[] inImages = new IBlockImage[]{ new BlockImage("input", "input.tif", "Input image", true), new BlockImage("mask", "", "Mask Image", false), new BlockImage("value", "", "Value Image", false)}; public final IBlockImage[] outImages = new IBlockImage[]{new BlockImage( "rdf", "rdf.tif", "Correlation function", true)}; public final ITIPLPluginIO cXDF = new XDF(); final static String blockName = "XDFBlock"; public XDFBlock(final BlockIOHelper helperTools,final String inPrefix) { super(helperTools,blockName); prefix = inPrefix; } public XDFBlock(final String inPrefix) { this(new LocalTIPLBlock.LocalIOHelper(), inPrefix); } @Deprecated public XDFBlock() { this(""); } @Override protected IBlockImage[] bGetInputNames() { return inImages; } @Override protected IBlockImage[] bGetOutputNames() { return outImages; } @Override public boolean executeBlock() { final TImgRO inputAim = getInputFile("input"); final TImgRO maskAim = getInputFile("mask"); final TImgRO valueAim = getInputFile("value"); TImgRO[] inImgs = new TImgRO[]{inputAim, maskAim, valueAim}; cXDF.LoadImages(inImgs); cXDF.execute(); SaveImage(cXDF.ExportImages(inputAim)[0], "rdf"); XDF.WriteHistograms((XDF) cXDF, TImgTools.makeTImgExportable(inputAim), getFileParameter("rdf")); return true; } @Override protected String getDescription() { return "Run two point correlation analysis"; } @Override public String getPrefix() { return prefix; } @Override public void setPrefix(String newPrefix) { prefix = newPrefix; } @Override public ArgumentParser setParameterBlock(final ArgumentParser p) { TIPLGlobal.availableCores = p.getOptionInt("maxcores", TIPLGlobal.availableCores, "Number of cores/threads to use for processing"); return cXDF.setParameter(p, prefix); } }
3e09f8f89c6944cc4c5a6ec286498b268789b73b
3,320
java
Java
spring-project/src/main/java/com/dermacon/workshop/controller/RegistrationController.java
derMacon/workshop-organizer-docker
c4b6f2c2e47d724d4cf2a3c7f5c8a2b4b28085de
[ "MIT" ]
null
null
null
spring-project/src/main/java/com/dermacon/workshop/controller/RegistrationController.java
derMacon/workshop-organizer-docker
c4b6f2c2e47d724d4cf2a3c7f5c8a2b4b28085de
[ "MIT" ]
null
null
null
spring-project/src/main/java/com/dermacon/workshop/controller/RegistrationController.java
derMacon/workshop-organizer-docker
c4b6f2c2e47d724d4cf2a3c7f5c8a2b4b28085de
[ "MIT" ]
null
null
null
29.990991
90
0.674377
4,234
package com.dermacon.workshop.controller; import com.dermacon.workshop.data.Person; import com.dermacon.workshop.data.PersonRepository; import com.dermacon.workshop.data.form_input.FormSignupInfo; import com.dermacon.workshop.exception.ErrorCodeException; import com.dermacon.workshop.service.MailService; import com.dermacon.workshop.service.PersonService; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.MailException; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import javax.mail.MessagingException; /** * This class contains a Mail API developed using Spring Boot * * @author MukulJaiswal * */ @Controller @RequestMapping("registration") public class RegistrationController { private static Logger log = Logger.getLogger(ManagerController.class); @Autowired private MailService notificationService; @Autowired private PersonRepository personRepository; @Autowired private PersonService personService; @RequestMapping(value={"/", "/signup"}) public String signup_get(Model model) { model.addAttribute("signupInfo", new FormSignupInfo()); return "registration/registration"; } @PostMapping(value={"/", "/signup"}) public String signup_post(@ModelAttribute("signupInfo") FormSignupInfo formSignupInfo, Model model) { try { personService.register(formSignupInfo); } catch (ErrorCodeException e) { model.addAttribute("errorCode", e.getErrorCode()); return "error/error"; } return "redirect:/"; } /** * * @return */ @RequestMapping("send-mail") public String send() { Person receiver = personRepository.findAll().iterator().next(); /* * Here we will call sendEmail() for Sending mail to the sender. */ try { notificationService.sendEmail(receiver); } catch (MailException mailException) { log.error(mailException); } return "Congratulations! Your mail has been send to the user."; } /** * * @return * @throws MessagingException */ @RequestMapping("send-mail-attachment") public String sendWithAttachment() throws MessagingException { /* * Creating a User with the help of User class that we have declared. Setting * the First,Last and Email address of the sender. */ // user.setFirstName("Mukul"); // user.setLastName("Jaiswal"); // user.setEmailAddress("lyhxr@example.com"); //Receiver's email address /* * Here we will call sendEmailWithAttachment() for Sending mail to the sender * that contains a attachment. */ try { // notificationService.sendEmailWithAttachment(user); } catch (MailException mailException) { System.out.println(mailException); } return "Congratulations! Your mail has been send to the user."; } }
3e09f8f9b233dea53755bf444b4d620ea2ccabe7
458
java
Java
embeddingapi/embedding-asyncapi-android-tests/embeddingapi/src/org/xwalk/embedding/base/OnFullscreenToggledHelper.java
BruceDai/crosswalk-test-suite
ef012acfe1ab1dc311bd1677262ffffe361f8163
[ "BSD-3-Clause" ]
null
null
null
embeddingapi/embedding-asyncapi-android-tests/embeddingapi/src/org/xwalk/embedding/base/OnFullscreenToggledHelper.java
BruceDai/crosswalk-test-suite
ef012acfe1ab1dc311bd1677262ffffe361f8163
[ "BSD-3-Clause" ]
null
null
null
embeddingapi/embedding-asyncapi-android-tests/embeddingapi/src/org/xwalk/embedding/base/OnFullscreenToggledHelper.java
BruceDai/crosswalk-test-suite
ef012acfe1ab1dc311bd1677262ffffe361f8163
[ "BSD-3-Clause" ]
null
null
null
25.444444
63
0.724891
4,235
package org.xwalk.embedding.base; import org.chromium.content.browser.test.util.CallbackHelper; public class OnFullscreenToggledHelper extends CallbackHelper { private boolean mEnterFullscreen = false; public boolean getEnterFullscreen() { assert getCallCount() > 0; return mEnterFullscreen; } public void notifyCalled(boolean enterFullscreen) { mEnterFullscreen = enterFullscreen; notifyCalled(); } }
3e09f90294d18976891ac4bfb49c0bd1f0e067d4
1,943
java
Java
com.ibm.jbatch.container/src/test/java/test/artifacts/MyPropertyMapper.java
scottkurz/standards.jsr352.jbatch
9ddd3d85328cb129d8c5f8bf0e13d31febc5ce18
[ "Apache-2.0" ]
18
2015-01-14T15:05:55.000Z
2021-12-11T19:16:37.000Z
com.ibm.jbatch.container/src/test/java/test/artifacts/MyPropertyMapper.java
scottkurz/standards.jsr352.jbatch
9ddd3d85328cb129d8c5f8bf0e13d31febc5ce18
[ "Apache-2.0" ]
44
2015-01-05T17:58:41.000Z
2022-02-22T14:22:17.000Z
com.ibm.jbatch.container/src/test/java/test/artifacts/MyPropertyMapper.java
scottkurz/standards.jsr352.jbatch
9ddd3d85328cb129d8c5f8bf0e13d31febc5ce18
[ "Apache-2.0" ]
21
2015-01-19T16:14:25.000Z
2021-12-13T19:22:53.000Z
30.84127
94
0.746269
4,236
/* * Copyright 2014 International Business Machines Corp. * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. 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 test.artifacts; import java.util.Properties; import jakarta.batch.api.BatchProperty; import jakarta.batch.api.partition.PartitionMapper; import jakarta.batch.api.partition.PartitionPlan; import jakarta.batch.api.partition.PartitionPlanImpl; import jakarta.batch.runtime.context.StepContext; import jakarta.inject.Inject; public class MyPropertyMapper implements PartitionMapper{ @Inject StepContext stepCtx; @Inject @BatchProperty(name="stepProp2") String stepProp2; @Override public PartitionPlan mapPartitions() throws Exception { PartitionPlanImpl pp = new PartitionPlanImpl(); pp.setPartitions(4); Properties p0 = new Properties(); p0.setProperty("part", ""); Properties p1 = new Properties(); p1.setProperty("part", ""); Properties p2 = new Properties(); p2.setProperty("part", ""); Properties p3 = new Properties(); p3.setProperty("part", ""); Properties[] partitionProps = new Properties[4]; partitionProps[0] = p0; partitionProps[1] = p1; partitionProps[2] = p2; partitionProps[3] = p3; pp.setPartitionProperties(partitionProps); stepCtx.setExitStatus(stepCtx.getExitStatus() + ":" + stepProp2 + ":" + pp.getPartitions()); return pp; } }
3e09fa163b55e4e368a073b8fa953811f2761efb
2,760
java
Java
ExtractedJars/Health_com.huawei.health/javafiles/com/amap/api/mapcore/util/q$a.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
3
2019-05-01T09:22:08.000Z
2019-07-06T22:21:59.000Z
ExtractedJars/Health_com.huawei.health/javafiles/com/amap/api/mapcore/util/q$a.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
null
null
null
ExtractedJars/Health_com.huawei.health/javafiles/com/amap/api/mapcore/util/q$a.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
1
2020-11-26T12:22:02.000Z
2020-11-26T12:22:02.000Z
30.32967
80
0.503986
4,237
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.amap.api.mapcore.util; import java.io.Serializable; import java.util.Comparator; // Referenced classes of package com.amap.api.mapcore.util: // q, dd, hm static class q$a implements Serializable, Comparator { public int compare(Object obj, Object obj1) { obj = ((Object) ((dd)obj)); // 0 0:aload_1 // 1 1:checkcast #23 <Class dd> // 2 4:astore_1 obj1 = ((Object) ((dd)obj1)); // 3 5:aload_2 // 4 6:checkcast #23 <Class dd> // 5 9:astore_2 if(obj == null || obj1 == null) break MISSING_BLOCK_LABEL_82; // 6 10:aload_1 // 7 11:ifnull 66 // 8 14:aload_2 // 9 15:ifnull 66 float f; float f1; f = ((dd) (obj)).getZIndex(); // 10 18:aload_1 // 11 19:invokeinterface #27 <Method float dd.getZIndex()> // 12 24:fstore_3 f1 = ((dd) (obj1)).getZIndex(); // 13 25:aload_2 // 14 26:invokeinterface #27 <Method float dd.getZIndex()> // 15 31:fstore 4 if(f > f1) //* 16 33:fload_3 //* 17 34:fload 4 //* 18 36:fcmpl //* 19 37:ifle 42 return 1; // 20 40:iconst_1 // 21 41:ireturn f = ((dd) (obj)).getZIndex(); // 22 42:aload_1 // 23 43:invokeinterface #27 <Method float dd.getZIndex()> // 24 48:fstore_3 f1 = ((dd) (obj1)).getZIndex(); // 25 49:aload_2 // 26 50:invokeinterface #27 <Method float dd.getZIndex()> // 27 55:fstore 4 if(f < f1) //* 28 57:fload_3 //* 29 58:fload 4 //* 30 60:fcmpg //* 31 61:ifge 66 return -1; // 32 64:iconst_m1 // 33 65:ireturn break MISSING_BLOCK_LABEL_82; // 34 66:goto 82 obj; // 35 69:astore_1 hm.c(((Throwable) (obj)), "GlOverlayLayer", "compare"); // 36 70:aload_1 // 37 71:ldc1 #29 <String "GlOverlayLayer"> // 38 73:ldc1 #30 <String "compare"> // 39 75:invokestatic #36 <Method void hm.c(Throwable, String, String)> ((Throwable) (obj)).printStackTrace(); // 40 78:aload_1 // 41 79:invokevirtual #39 <Method void Throwable.printStackTrace()> return 0; // 42 82:iconst_0 // 43 83:ireturn } q$a() { // 0 0:aload_0 // 1 1:invokespecial #16 <Method void Object()> // 2 4:return } }
3e09fa34a9a4049278933e2376c7dfeb282db727
1,666
java
Java
src/main/java/com/readonlydev/lib/world/noise/SimplexNoise.java
ReadOnlyDevelopment/Interstellar
b6fca24157da89417951cffc2ca46ab2fe60a116
[ "MIT" ]
null
null
null
src/main/java/com/readonlydev/lib/world/noise/SimplexNoise.java
ReadOnlyDevelopment/Interstellar
b6fca24157da89417951cffc2ca46ab2fe60a116
[ "MIT" ]
null
null
null
src/main/java/com/readonlydev/lib/world/noise/SimplexNoise.java
ReadOnlyDevelopment/Interstellar
b6fca24157da89417951cffc2ca46ab2fe60a116
[ "MIT" ]
null
null
null
26.03125
106
0.596639
4,238
package com.readonlydev.lib.world.noise; /** * @author <a href="https://github.com/srs-bsns">srs-bsns</a> * @version 1.0.0 * @since 1.0.0 */ public interface SimplexNoise { /** * Returns a 2D noise float value for the given coordinates. * This is an alias for {@link #noise2d} * * @param x the x coordinate * @param y the y coordinate * @return the noise value * @since 1.0.0 */ float noise2f(float x, float y); /** * Returns a 3D noise float value for the given coordinates. * This is an alias for {@link #noise3d} * * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate * @return the noise value * @since 1.0.0 */ float noise3f(float x, float y, float z); /** * Returns a 2D noise double value for the given coordinates. * * @param x the x coordinate * @param y the y coordinate * @return the noise value * @since 1.0.0 */ double noise2d(double x, double y); /** * Returns a 3D noise double value for the given coordinates. * * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate * @return the noise value * @since 1.0.0 */ double noise3d(double x, double y, double z); /** * Performs a 2D noise multi-evaluation on a {@link ISimplexData2D} object with the given coordinates. * * @param x the x coordinate * @param y the y coordinate * @param data the ISimplexData2D object * @since 1.0.0 */ void multiEval2D(double x, double y, ISimplexData2D data); }
3e09fc040a08b620e9bc828c5cbf136a56b89439
2,148
java
Java
gdx-fireapp-html/tests/pl/mk5/gdx/fireapp/html/firebase/ScriptRunnerTest.java
einaru/gdx-fireapp
7927dc6d1cf5056be68870605712d3bae23af2fb
[ "Apache-2.0" ]
64
2017-09-22T08:10:45.000Z
2022-03-26T23:09:19.000Z
gdx-fireapp-html/tests/pl/mk5/gdx/fireapp/html/firebase/ScriptRunnerTest.java
einaru/gdx-fireapp
7927dc6d1cf5056be68870605712d3bae23af2fb
[ "Apache-2.0" ]
38
2017-10-04T10:55:08.000Z
2022-03-20T14:33:46.000Z
gdx-fireapp-html/tests/pl/mk5/gdx/fireapp/html/firebase/ScriptRunnerTest.java
einaru/gdx-fireapp
7927dc6d1cf5056be68870605712d3bae23af2fb
[ "Apache-2.0" ]
21
2017-09-22T08:10:47.000Z
2022-03-08T13:17:55.000Z
35.8
99
0.740223
4,239
/* * Copyright 2018 mk * * 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 pl.mk5.gdx.fireapp.html.firebase; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.internal.verification.VerificationModeFactory; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) @PrepareForTest({FirebaseScriptInformant.class}) public class ScriptRunnerTest { @Test public void firebaseScript_withFirebaseLoaded() { // Given PowerMockito.mockStatic(FirebaseScriptInformant.class); Mockito.when(FirebaseScriptInformant.isFirebaseScriptLoaded()).thenReturn(true); Runnable runnable = Mockito.mock(Runnable.class); // When ScriptRunner.firebaseScript(runnable); // Then Mockito.verify(runnable, VerificationModeFactory.times(1)).run(); } @Test public void firebaseScript_withoutFirebaseLoaded() { // Given PowerMockito.mockStatic(FirebaseScriptInformant.class); Mockito.when(FirebaseScriptInformant.isFirebaseScriptLoaded()).thenReturn(false); Runnable runnable = Mockito.mock(Runnable.class); // When ScriptRunner.firebaseScript(runnable); // Then Mockito.verify(runnable, VerificationModeFactory.times(0)).run(); PowerMockito.verifyStatic(FirebaseScriptInformant.class, VerificationModeFactory.times(1)); FirebaseScriptInformant.addWaitingAction(Mockito.refEq(runnable)); } }
3e09fda467813d140144380ecf67965f13ca8992
2,521
java
Java
artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/QuorumVoteMessage.java
sergey-vaysman/activemq-artemis
f7bb4c754a6ab9aa8bdf1b51685f71739a747eda
[ "Apache-2.0" ]
868
2015-05-07T07:38:19.000Z
2022-03-22T08:36:33.000Z
artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/QuorumVoteMessage.java
sergey-vaysman/activemq-artemis
f7bb4c754a6ab9aa8bdf1b51685f71739a747eda
[ "Apache-2.0" ]
2,100
2015-04-29T15:29:35.000Z
2022-03-31T20:21:54.000Z
artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/QuorumVoteMessage.java
sergey-vaysman/activemq-artemis
f7bb4c754a6ab9aa8bdf1b51685f71739a747eda
[ "Apache-2.0" ]
967
2015-05-03T14:28:27.000Z
2022-03-31T11:53:21.000Z
31.911392
80
0.731456
4,240
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.core.protocol.core.impl.wireformat; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; import org.apache.activemq.artemis.api.core.ActiveMQBuffers; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl; import org.apache.activemq.artemis.core.server.cluster.qourum.QuorumVoteHandler; import org.apache.activemq.artemis.core.server.cluster.qourum.Vote; public class QuorumVoteMessage extends PacketImpl { private SimpleString handler; private Vote vote; private ActiveMQBuffer voteBuffer; public QuorumVoteMessage() { super(QUORUM_VOTE); } public QuorumVoteMessage(SimpleString handler, Vote vote) { super(QUORUM_VOTE); this.handler = handler; this.vote = vote; } @Override public void encodeRest(ActiveMQBuffer buffer) { super.encodeRest(buffer); buffer.writeSimpleString(handler); vote.encode(buffer); } @Override public void decodeRest(ActiveMQBuffer buffer) { super.decodeRest(buffer); handler = buffer.readSimpleString(); voteBuffer = ActiveMQBuffers.fixedBuffer(buffer.readableBytes()); buffer.readBytes(voteBuffer); } public SimpleString getHandler() { return handler; } public Vote getVote() { return vote; } public void decode(QuorumVoteHandler voteHandler) { vote = voteHandler.decode(voteBuffer); } @Override protected String getPacketString() { StringBuffer buff = new StringBuffer(super.getPacketString()); buff.append(", vote=" + vote); buff.append(", handler=" + handler); return buff.toString(); } }
3e09fdc87d2706cf200f09e2c483469f6ce35066
1,078
java
Java
Aulas/Aula05/src/AtividadeAula04/MainCliente.java
Arthur-San/Desenvolvimento-de-Aplicativos-I
c831b552f3a23a874c770f2893cabc93d51ad338
[ "MIT" ]
1
2021-03-24T02:15:57.000Z
2021-03-24T02:15:57.000Z
Aula05/src/AtividadeAula04/MainCliente.java
nunes1909/DevAppI
8ba18877116f66313205ad1ac88df7085e1ddb69
[ "MIT" ]
null
null
null
Aula05/src/AtividadeAula04/MainCliente.java
nunes1909/DevAppI
8ba18877116f66313205ad1ac88df7085e1ddb69
[ "MIT" ]
2
2021-03-23T15:37:44.000Z
2021-03-23T15:40:48.000Z
29.944444
84
0.537106
4,241
package AtividadeAula04; import java.util.Scanner; public class MainCliente { public static void main(String[] args) { Scanner ler = new Scanner(System.in); Cliente c1 = new Cliente(); //invocação do métodos acessores - SET System.out.println("Nome do cliente: "); c1.setNome(ler.nextLine()); System.out.println("Digite a idade: "); c1.setIdade(ler.nextInt()); System.out.println("Digite a renda: "); c1.setRenda(ler.nextDouble()); //visualização dos dados digitados //invocação dos métodos acessores - GET System.out.println("**********"); System.out.println("SAÍDA DE DADOS"); System.out.println("**********"); //invocando os getters System.out.println("Nome: " + c1.getNome()); System.out.println("Idade: " + c1.getIdade() + " / " + c1.calcularIdade() ); System.out.println("Renda: " + c1.getRenda() + " / " + c1.calcularRenda() ); } }
3e09fde962d9e18b515d61ed6262efd33b4b318d
180
java
Java
app/src/main/java/com/android/skinthean/activity/Constant.java
sure13/SkinTheme
07457ca3626bfb5cea47a5725ee971098a1b0e41
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/android/skinthean/activity/Constant.java
sure13/SkinTheme
07457ca3626bfb5cea47a5725ee971098a1b0e41
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/android/skinthean/activity/Constant.java
sure13/SkinTheme
07457ca3626bfb5cea47a5725ee971098a1b0e41
[ "Apache-2.0" ]
null
null
null
15
59
0.705556
4,242
package com.android.skinthean.activity; /** * des: * author:onexzgj * time:2019/1/15 */ public class Constant { public static final String CURRENT_SKIN="CURRENT_SKIN"; }
3e09fe31e4c6389da92291d709d8f7b756983695
1,339
java
Java
ws_jdk_client/src/liang/ren/hello/SayBye.java
bede1/Myworkspace
521128d2c19bf22601282eeea095881f1cc0c838
[ "Apache-2.0" ]
null
null
null
ws_jdk_client/src/liang/ren/hello/SayBye.java
bede1/Myworkspace
521128d2c19bf22601282eeea095881f1cc0c838
[ "Apache-2.0" ]
null
null
null
ws_jdk_client/src/liang/ren/hello/SayBye.java
bede1/Myworkspace
521128d2c19bf22601282eeea095881f1cc0c838
[ "Apache-2.0" ]
null
null
null
21.95082
104
0.60717
4,243
package liang.ren.hello; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for sayBye complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="sayBye"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="personName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "sayBye", propOrder = { "personName" }) public class SayBye { protected String personName; /** * Gets the value of the personName property. * * @return * possible object is * {@link String } * */ public String getPersonName() { return personName; } /** * Sets the value of the personName property. * * @param value * allowed object is * {@link String } * */ public void setPersonName(String value) { this.personName = value; } }
3e09ff2316397055aa317b2c5e9f5a05833aacf1
2,171
java
Java
src/main/java/utils/CSVUtils.java
assaf-08/TopToy
b09aa143412ff54977cb8aa861beebf4a0c775cc
[ "Apache-2.0" ]
2
2020-03-04T19:57:40.000Z
2021-02-03T01:56:01.000Z
src/main/java/utils/CSVUtils.java
assaf-08/TopToy
b09aa143412ff54977cb8aa861beebf4a0c775cc
[ "Apache-2.0" ]
5
2020-04-23T18:33:24.000Z
2022-01-21T23:24:56.000Z
src/main/java/utils/CSVUtils.java
assaf-08/TopToy
b09aa143412ff54977cb8aa861beebf4a0c775cc
[ "Apache-2.0" ]
1
2020-08-14T17:47:13.000Z
2020-08-14T17:47:13.000Z
27.1375
120
0.572547
4,244
package utils; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import java.util.List; public class CSVUtils { private static final char DEFAULT_SEPARATOR = ','; public static void writeLine(Writer w, List<String> values) throws IOException { writeLine(w, values, DEFAULT_SEPARATOR, ' '); } public static void writeLine(Writer w, List<String> values, char separators) throws IOException { writeLine(w, values, separators, ' '); } private static String followCVSformat(String value) { String result = value; if (result.contains("\"")) { result = result.replace("\"", "\"\""); } return result; } private static void writeLine(Writer w, List<String> values, char separators, char customQuote) throws IOException { boolean first = true; //default customQuote is empty if (separators == ' ') { separators = DEFAULT_SEPARATOR; } StringBuilder sb = new StringBuilder(); for (String value : values) { if (!first) { sb.append(separators); } if (customQuote == ' ') { sb.append(followCVSformat(value)); } else { sb.append(customQuote).append(followCVSformat(value)).append(customQuote); } first = false; } sb.append("\n"); w.append(sb.toString()); } static public void writeLines(Writer w, List<List<String>> data) throws IOException { for (List<String> line : data) { writeLine(w, line); } } public static ArrayList<String[]> readLines(Reader r) throws IOException { ArrayList<String[]> ret = new ArrayList<>(); String line; String sep = String.valueOf(DEFAULT_SEPARATOR); try (BufferedReader br = new BufferedReader(r)) { while ((line = br.readLine()) != null) { String[] row = line.split(sep); ret.add(row); } } return ret; } }
3e09ff8168e2b64042db163017ae0cfbb9511a76
4,322
java
Java
Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/interpreters/DebuggerInterpreterPlugin.java
bdcht/ghidra
9e732318148cd11edeb4862afd23d56418551812
[ "Apache-2.0" ]
17
2022-01-15T03:52:37.000Z
2022-03-30T18:12:17.000Z
Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/interpreters/DebuggerInterpreterPlugin.java
bdcht/ghidra
9e732318148cd11edeb4862afd23d56418551812
[ "Apache-2.0" ]
9
2022-01-15T03:58:02.000Z
2022-02-21T10:22:49.000Z
Ghidra/Debug/Debugger/src/main/java/ghidra/app/plugin/core/debug/gui/interpreters/DebuggerInterpreterPlugin.java
bdcht/ghidra
9e732318148cd11edeb4862afd23d56418551812
[ "Apache-2.0" ]
1
2022-03-07T13:22:05.000Z
2022-03-07T13:22:05.000Z
33.503876
96
0.790838
4,245
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.app.plugin.core.debug.gui.interpreters; import java.util.HashMap; import java.util.Map; import javax.swing.SwingUtilities; import ghidra.app.plugin.PluginCategoryNames; import ghidra.app.plugin.core.debug.AbstractDebuggerPlugin; import ghidra.app.plugin.core.debug.DebuggerPluginPackage; import ghidra.app.plugin.core.interpreter.*; import ghidra.app.services.DebuggerInterpreterService; import ghidra.dbg.target.*; import ghidra.framework.plugintool.PluginInfo; import ghidra.framework.plugintool.PluginTool; import ghidra.framework.plugintool.annotation.AutoServiceConsumed; import ghidra.framework.plugintool.util.PluginStatus; @PluginInfo( shortDescription = "Debugger interpreter panel service", description = "Manage interpreter panels within debug sessions", category = PluginCategoryNames.DEBUGGER, packageName = DebuggerPluginPackage.NAME, status = PluginStatus.RELEASED, servicesRequired = { InterpreterPanelService.class, }, servicesProvided = { DebuggerInterpreterService.class, }) public class DebuggerInterpreterPlugin extends AbstractDebuggerPlugin implements DebuggerInterpreterService { @AutoServiceConsumed protected InterpreterPanelService consoleService; protected final Map<TargetObject, DebuggerInterpreterConnection> connections = new HashMap<>(); public DebuggerInterpreterPlugin(PluginTool tool) { super(tool); } @Override public DebuggerInterpreterConnection showConsole(TargetConsole targetConsole) { DebuggerInterpreterConnection conn; synchronized (connections) { conn = connections.computeIfAbsent(targetConsole, c -> createConnection(targetConsole)); } conn.getInterpreterConsole().show(); return conn; } @Override public DebuggerInterpreterConnection showConsole(TargetInterpreter targetInterpreter) { DebuggerInterpreterConnection conn; synchronized (connections) { conn = connections.computeIfAbsent(targetInterpreter, c -> createConnection(targetInterpreter)); } conn.getInterpreterConsole().show(); return conn; } protected void disableConsole(TargetObject targetConsole, InterpreterConsole guiConsole) { DebuggerInterpreterConnection old; synchronized (connections) { old = connections.remove(targetConsole); } assert old.getInterpreterConsole() == guiConsole; SwingUtilities.invokeLater(() -> { if (guiConsole.isInputPermitted()) { guiConsole.setInputPermitted(false); guiConsole.setTransient(); guiConsole.setPrompt(">>INVALID<<"); } }); } protected void createConsole(AbstractDebuggerWrappedConsoleConnection<?> connection) { //InterpreterConsole console = consoleService.createInterpreterPanel(connection, true); // TODO: Just fix the console plugin InterpreterConsole console = new DebuggerInterpreterProvider( (InterpreterPanelPlugin) consoleService, connection, true); connection.setConsole(console); connection.runInBackground(); } protected DebuggerInterpreterConnection createConnection(TargetConsole targetConsole) { DebuggerWrappedConsoleConnection conn = new DebuggerWrappedConsoleConnection(this, targetConsole); createConsole(conn); return conn; } protected DebuggerInterpreterConnection createConnection( TargetInterpreter targetInterpreter) { DebuggerWrappedInterpreterConnection conn = new DebuggerWrappedInterpreterConnection(this, targetInterpreter); createConsole(conn); return conn; } public void destroyConsole(TargetObject targetConsole, InterpreterConsole guiConsole) { DebuggerInterpreterConnection old; synchronized (connections) { old = connections.remove(targetConsole); } assert old.getInterpreterConsole() == guiConsole; SwingUtilities.invokeLater(() -> { guiConsole.dispose(); }); } }
3e09ff8ab744eb2371ad1ad9c6737b1eb2c86ea6
394
java
Java
src/main/java/ar/com/cashonline/api/common/Paging.java
abarazal/cash-online-challenge
b135a37527312c3eb52541813a2d1f683ee3fc92
[ "MIT" ]
null
null
null
src/main/java/ar/com/cashonline/api/common/Paging.java
abarazal/cash-online-challenge
b135a37527312c3eb52541813a2d1f683ee3fc92
[ "MIT" ]
null
null
null
src/main/java/ar/com/cashonline/api/common/Paging.java
abarazal/cash-online-challenge
b135a37527312c3eb52541813a2d1f683ee3fc92
[ "MIT" ]
null
null
null
14.592593
56
0.685279
4,246
package ar.com.cashonline.api.common; public class Paging { private Integer page; private Integer size; private Long total; public Paging(Integer page, Integer size, Long total) { this.page = page; this.size = size; this.total = total; } public Integer getPage() { return page; } public Integer getSize() { return size; } public Long getTotal() { return total; } }
3e0a004ec99455011953c06efc75dcab76722ebf
4,468
java
Java
source/tools/tools-initializer/src/test/java/test/com/jd/blockchain/tools/initializer/LedgerInitPropertiesTest.java
Spark3122/jdchain
03284140d3c93dd0599109f8cf9d410b5ded78cb
[ "Apache-2.0" ]
1
2019-09-18T03:19:02.000Z
2019-09-18T03:19:02.000Z
source/tools/tools-initializer/src/test/java/test/com/jd/blockchain/tools/initializer/LedgerInitPropertiesTest.java
Spark3122/jdchain
03284140d3c93dd0599109f8cf9d410b5ded78cb
[ "Apache-2.0" ]
null
null
null
source/tools/tools-initializer/src/test/java/test/com/jd/blockchain/tools/initializer/LedgerInitPropertiesTest.java
Spark3122/jdchain
03284140d3c93dd0599109f8cf9d410b5ded78cb
[ "Apache-2.0" ]
null
null
null
42.317757
105
0.770318
4,247
package test.com.jd.blockchain.tools.initializer; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import org.junit.Test; import org.springframework.core.io.ClassPathResource; import com.jd.blockchain.crypto.AddressEncoding; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.tools.initializer.LedgerInitProperties; import com.jd.blockchain.tools.initializer.LedgerInitProperties.ConsensusParticipantConfig; import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.codec.HexUtils; public class LedgerInitPropertiesTest { private static String expectedCreatedTimeStr = "2019-08-01 14:26:58.069+0800"; private static String expectedCreatedTimeStr1 = "2019-08-01 13:26:58.069+0700"; @Test public void testTimeFormat() throws ParseException { SimpleDateFormat timeFormat = new SimpleDateFormat(LedgerInitProperties.CREATED_TIME_FORMAT); // timeFormat.setTimeZone(TimeZone.getTimeZone("GMT+08:00")); TimeZone.setDefault(TimeZone.getTimeZone("GMT+08:00")); Date time = timeFormat.parse(expectedCreatedTimeStr); String actualTimeStr = timeFormat.format(time); assertEquals(expectedCreatedTimeStr, actualTimeStr); Date time1 = timeFormat.parse(expectedCreatedTimeStr1); String actualTimeStr1 = timeFormat.format(time1); assertEquals(expectedCreatedTimeStr, actualTimeStr1); } @Test public void testProperties() throws IOException, ParseException { ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger.init"); InputStream in = ledgerInitSettingResource.getInputStream(); try { LedgerInitProperties initProps = LedgerInitProperties.resolve(in); assertEquals(4, initProps.getConsensusParticipantCount()); String expectedLedgerSeed = "932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe" .replace("-", ""); String actualLedgerSeed = HexUtils.encode(initProps.getLedgerSeed()); assertEquals(expectedLedgerSeed, actualLedgerSeed); SimpleDateFormat timeFormat = new SimpleDateFormat(LedgerInitProperties.CREATED_TIME_FORMAT); timeFormat.setTimeZone(TimeZone.getTimeZone("GMT+08:00")); long expectedTs = timeFormat.parse(expectedCreatedTimeStr).getTime(); assertEquals(expectedTs, initProps.getCreatedTime()); String createdTimeStr = timeFormat.format(new Date(initProps.getCreatedTime())); assertEquals(expectedCreatedTimeStr, createdTimeStr); assertEquals("com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider", initProps.getConsensusProvider()); String[] cryptoProviders = initProps.getCryptoProviders(); assertEquals(2, cryptoProviders.length); assertEquals("com.jd.blockchain.crypto.service.classic.ClassicCryptoService", cryptoProviders[0]); assertEquals("com.jd.blockchain.crypto.service.sm.SMCryptoService", cryptoProviders[1]); ConsensusParticipantConfig part0 = initProps.getConsensusParticipant(0); assertEquals("jd.com", part0.getName()); PubKey pubKey0 = KeyGenCommand.decodePubKey("se2xy1bknelxn4y8xzxu3trosptip3q5"); assertEquals(pubKey0, part0.getPubKey()); assertEquals("127.0.0.1", part0.getInitializerAddress().getHost()); assertEquals(8800, part0.getInitializerAddress().getPort()); assertEquals(true, part0.getInitializerAddress().isSecure()); ConsensusParticipantConfig part1 = initProps.getConsensusParticipant(1); assertEquals(false, part1.getInitializerAddress().isSecure()); PubKey pubKey1 = KeyGenCommand.decodePubKey("949d1u22cbffbrarjh182eig55721odj"); assertEquals(pubKey1, part1.getPubKey()); ConsensusParticipantConfig part2 = initProps.getConsensusParticipant(2); assertEquals("74t3tndxag9o7h0890bnpfzh4olk2h9x", part2.getPubKey().toBase58()); } finally { in.close(); } } @Test public void testPubKeyAddress() { String[] pubKeys = TestConsts.PUB_KEYS; int index = 0; for (String pubKeyStr : pubKeys) { System.out.println("[" + index + "][配置] = " + pubKeyStr); PubKey pubKey = KeyGenCommand.decodePubKey(pubKeyStr); System.out.println("[" + index + "][公钥Base58] = " + pubKey.toBase58()); System.out.println("[" + index + "][地址] = " + AddressEncoding.generateAddress(pubKey).toBase58()); System.out.println("--------------------------------------------------------------------"); index++; } } }
3e0a006598d75415e8173e6d61639631af6c0687
156,949
java
Java
client/rest-high-level/src/test/java/org/elasticsearch/client/MachineLearningIT.java
Yanx0202/elasticsearch
f8002a7204ffd3098cd3cfdb806e728e8fcb3b47
[ "Apache-2.0" ]
3
2020-07-09T19:00:34.000Z
2020-07-09T19:01:20.000Z
client/rest-high-level/src/test/java/org/elasticsearch/client/MachineLearningIT.java
Yanx0202/elasticsearch
f8002a7204ffd3098cd3cfdb806e728e8fcb3b47
[ "Apache-2.0" ]
null
null
null
client/rest-high-level/src/test/java/org/elasticsearch/client/MachineLearningIT.java
Yanx0202/elasticsearch
f8002a7204ffd3098cd3cfdb806e728e8fcb3b47
[ "Apache-2.0" ]
1
2020-07-09T19:00:37.000Z
2020-07-09T19:00:37.000Z
54.534051
140
0.701788
4,248
/* * 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.client; import com.carrotsearch.randomizedtesting.generators.CodepointSetGenerator; import org.elasticsearch.ElasticsearchStatusException; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.ingest.PutPipelineRequest; import org.elasticsearch.action.support.WriteRequest; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.client.core.PageParams; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.client.indices.GetIndexRequest; import org.elasticsearch.client.ml.CloseJobRequest; import org.elasticsearch.client.ml.CloseJobResponse; import org.elasticsearch.client.ml.DeleteCalendarEventRequest; import org.elasticsearch.client.ml.DeleteCalendarJobRequest; import org.elasticsearch.client.ml.DeleteCalendarRequest; import org.elasticsearch.client.ml.DeleteDataFrameAnalyticsRequest; import org.elasticsearch.client.ml.DeleteDatafeedRequest; import org.elasticsearch.client.ml.DeleteExpiredDataRequest; import org.elasticsearch.client.ml.DeleteExpiredDataResponse; import org.elasticsearch.client.ml.DeleteFilterRequest; import org.elasticsearch.client.ml.DeleteForecastRequest; import org.elasticsearch.client.ml.DeleteJobRequest; import org.elasticsearch.client.ml.DeleteJobResponse; import org.elasticsearch.client.ml.DeleteModelSnapshotRequest; import org.elasticsearch.client.ml.DeleteTrainedModelRequest; import org.elasticsearch.client.ml.EstimateModelMemoryRequest; import org.elasticsearch.client.ml.EstimateModelMemoryResponse; import org.elasticsearch.client.ml.EvaluateDataFrameRequest; import org.elasticsearch.client.ml.EvaluateDataFrameResponse; import org.elasticsearch.client.ml.ExplainDataFrameAnalyticsRequest; import org.elasticsearch.client.ml.ExplainDataFrameAnalyticsResponse; import org.elasticsearch.client.ml.FindFileStructureRequest; import org.elasticsearch.client.ml.FindFileStructureResponse; import org.elasticsearch.client.ml.FlushJobRequest; import org.elasticsearch.client.ml.FlushJobResponse; import org.elasticsearch.client.ml.ForecastJobRequest; import org.elasticsearch.client.ml.ForecastJobResponse; import org.elasticsearch.client.ml.GetCalendarEventsRequest; import org.elasticsearch.client.ml.GetCalendarEventsResponse; import org.elasticsearch.client.ml.GetCalendarsRequest; import org.elasticsearch.client.ml.GetCalendarsResponse; import org.elasticsearch.client.ml.GetDataFrameAnalyticsRequest; import org.elasticsearch.client.ml.GetDataFrameAnalyticsResponse; import org.elasticsearch.client.ml.GetDataFrameAnalyticsStatsRequest; import org.elasticsearch.client.ml.GetDataFrameAnalyticsStatsResponse; import org.elasticsearch.client.ml.GetDatafeedRequest; import org.elasticsearch.client.ml.GetDatafeedResponse; import org.elasticsearch.client.ml.GetDatafeedStatsRequest; import org.elasticsearch.client.ml.GetDatafeedStatsResponse; import org.elasticsearch.client.ml.GetFiltersRequest; import org.elasticsearch.client.ml.GetFiltersResponse; import org.elasticsearch.client.ml.GetJobRequest; import org.elasticsearch.client.ml.GetJobResponse; import org.elasticsearch.client.ml.GetJobStatsRequest; import org.elasticsearch.client.ml.GetJobStatsResponse; import org.elasticsearch.client.ml.GetModelSnapshotsRequest; import org.elasticsearch.client.ml.GetModelSnapshotsResponse; import org.elasticsearch.client.ml.GetTrainedModelsRequest; import org.elasticsearch.client.ml.GetTrainedModelsResponse; import org.elasticsearch.client.ml.GetTrainedModelsStatsRequest; import org.elasticsearch.client.ml.GetTrainedModelsStatsResponse; import org.elasticsearch.client.ml.MlInfoRequest; import org.elasticsearch.client.ml.MlInfoResponse; import org.elasticsearch.client.ml.OpenJobRequest; import org.elasticsearch.client.ml.OpenJobResponse; import org.elasticsearch.client.ml.PostCalendarEventRequest; import org.elasticsearch.client.ml.PostCalendarEventResponse; import org.elasticsearch.client.ml.PostDataRequest; import org.elasticsearch.client.ml.PostDataResponse; import org.elasticsearch.client.ml.PreviewDatafeedRequest; import org.elasticsearch.client.ml.PreviewDatafeedResponse; import org.elasticsearch.client.ml.PutCalendarJobRequest; import org.elasticsearch.client.ml.PutCalendarRequest; import org.elasticsearch.client.ml.PutCalendarResponse; import org.elasticsearch.client.ml.PutDataFrameAnalyticsRequest; import org.elasticsearch.client.ml.PutDataFrameAnalyticsResponse; import org.elasticsearch.client.ml.PutDatafeedRequest; import org.elasticsearch.client.ml.PutDatafeedResponse; import org.elasticsearch.client.ml.PutFilterRequest; import org.elasticsearch.client.ml.PutFilterResponse; import org.elasticsearch.client.ml.PutJobRequest; import org.elasticsearch.client.ml.PutJobResponse; import org.elasticsearch.client.ml.PutTrainedModelRequest; import org.elasticsearch.client.ml.PutTrainedModelResponse; import org.elasticsearch.client.ml.RevertModelSnapshotRequest; import org.elasticsearch.client.ml.RevertModelSnapshotResponse; import org.elasticsearch.client.ml.SetUpgradeModeRequest; import org.elasticsearch.client.ml.StartDataFrameAnalyticsRequest; import org.elasticsearch.client.ml.StartDatafeedRequest; import org.elasticsearch.client.ml.StartDatafeedResponse; import org.elasticsearch.client.ml.StopDataFrameAnalyticsRequest; import org.elasticsearch.client.ml.StopDataFrameAnalyticsResponse; import org.elasticsearch.client.ml.StopDatafeedRequest; import org.elasticsearch.client.ml.StopDatafeedResponse; import org.elasticsearch.client.ml.UpdateDataFrameAnalyticsRequest; import org.elasticsearch.client.ml.UpdateDatafeedRequest; import org.elasticsearch.client.ml.UpdateFilterRequest; import org.elasticsearch.client.ml.UpdateJobRequest; import org.elasticsearch.client.ml.UpdateModelSnapshotRequest; import org.elasticsearch.client.ml.UpdateModelSnapshotResponse; import org.elasticsearch.client.ml.calendars.Calendar; import org.elasticsearch.client.ml.calendars.CalendarTests; import org.elasticsearch.client.ml.calendars.ScheduledEvent; import org.elasticsearch.client.ml.calendars.ScheduledEventTests; import org.elasticsearch.client.ml.datafeed.DatafeedConfig; import org.elasticsearch.client.ml.datafeed.DatafeedState; import org.elasticsearch.client.ml.datafeed.DatafeedStats; import org.elasticsearch.client.ml.datafeed.DatafeedUpdate; import org.elasticsearch.client.ml.dataframe.DataFrameAnalyticsConfig; import org.elasticsearch.client.ml.dataframe.DataFrameAnalyticsConfigUpdate; import org.elasticsearch.client.ml.dataframe.DataFrameAnalyticsDest; import org.elasticsearch.client.ml.dataframe.DataFrameAnalyticsSource; import org.elasticsearch.client.ml.dataframe.DataFrameAnalyticsState; import org.elasticsearch.client.ml.dataframe.DataFrameAnalyticsStats; import org.elasticsearch.client.ml.dataframe.OutlierDetection; import org.elasticsearch.client.ml.dataframe.PhaseProgress; import org.elasticsearch.client.ml.dataframe.QueryConfig; import org.elasticsearch.client.ml.dataframe.evaluation.classification.AccuracyMetric; import org.elasticsearch.client.ml.dataframe.evaluation.classification.Classification; import org.elasticsearch.client.ml.dataframe.evaluation.classification.MulticlassConfusionMatrixMetric; import org.elasticsearch.client.ml.dataframe.evaluation.regression.MeanSquaredErrorMetric; import org.elasticsearch.client.ml.dataframe.evaluation.regression.MeanSquaredLogarithmicErrorMetric; import org.elasticsearch.client.ml.dataframe.evaluation.regression.HuberMetric; import org.elasticsearch.client.ml.dataframe.evaluation.regression.RSquaredMetric; import org.elasticsearch.client.ml.dataframe.evaluation.regression.Regression; import org.elasticsearch.client.ml.dataframe.evaluation.softclassification.AucRocMetric; import org.elasticsearch.client.ml.dataframe.evaluation.softclassification.BinarySoftClassification; import org.elasticsearch.client.ml.dataframe.evaluation.softclassification.ConfusionMatrixMetric; import org.elasticsearch.client.ml.dataframe.evaluation.softclassification.PrecisionMetric; import org.elasticsearch.client.ml.dataframe.evaluation.softclassification.RecallMetric; import org.elasticsearch.client.ml.dataframe.explain.FieldSelection; import org.elasticsearch.client.ml.dataframe.explain.MemoryEstimation; import org.elasticsearch.client.ml.dataframe.stats.common.DataCounts; import org.elasticsearch.client.ml.dataframe.stats.common.MemoryUsage; import org.elasticsearch.client.ml.filestructurefinder.FileStructure; import org.elasticsearch.client.ml.inference.InferenceToXContentCompressor; import org.elasticsearch.client.ml.inference.MlInferenceNamedXContentProvider; import org.elasticsearch.client.ml.inference.TrainedModelConfig; import org.elasticsearch.client.ml.inference.TrainedModelDefinition; import org.elasticsearch.client.ml.inference.TrainedModelDefinitionTests; import org.elasticsearch.client.ml.inference.TrainedModelInput; import org.elasticsearch.client.ml.inference.TrainedModelStats; import org.elasticsearch.client.ml.inference.trainedmodel.RegressionConfig; import org.elasticsearch.client.ml.inference.trainedmodel.TargetType; import org.elasticsearch.client.ml.inference.trainedmodel.langident.LangIdentNeuralNetwork; import org.elasticsearch.client.ml.job.config.AnalysisConfig; import org.elasticsearch.client.ml.job.config.AnalysisLimits; import org.elasticsearch.client.ml.job.config.DataDescription; import org.elasticsearch.client.ml.job.config.Detector; import org.elasticsearch.client.ml.job.config.Job; import org.elasticsearch.client.ml.job.config.JobState; import org.elasticsearch.client.ml.job.config.JobUpdate; import org.elasticsearch.client.ml.job.config.MlFilter; import org.elasticsearch.client.ml.job.process.ModelSnapshot; import org.elasticsearch.client.ml.job.stats.JobStats; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.MatchAllQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.search.SearchHit; import org.junit.After; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.closeTo; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; public class MachineLearningIT extends ESRestHighLevelClientTestCase { @After public void cleanUp() throws IOException { new MlTestStateCleaner(logger, highLevelClient().machineLearning()).clearMlMetadata(); } public void testPutJob() throws Exception { String jobId = randomValidJobId(); Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); PutJobResponse putJobResponse = execute(new PutJobRequest(job), machineLearningClient::putJob, machineLearningClient::putJobAsync); Job createdJob = putJobResponse.getResponse(); assertThat(createdJob.getId(), is(jobId)); assertThat(createdJob.getJobType(), is(Job.ANOMALY_DETECTOR_JOB_TYPE)); } public void testGetJob() throws Exception { String jobId1 = randomValidJobId(); String jobId2 = randomValidJobId(); Job job1 = buildJob(jobId1); Job job2 = buildJob(jobId2); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job1), RequestOptions.DEFAULT); machineLearningClient.putJob(new PutJobRequest(job2), RequestOptions.DEFAULT); GetJobRequest request = new GetJobRequest(jobId1, jobId2); // Test getting specific jobs GetJobResponse response = execute(request, machineLearningClient::getJob, machineLearningClient::getJobAsync); assertEquals(2, response.count()); assertThat(response.jobs(), hasSize(2)); assertThat(response.jobs().stream().map(Job::getId).collect(Collectors.toList()), containsInAnyOrder(jobId1, jobId2)); // Test getting all jobs explicitly request = GetJobRequest.getAllJobsRequest(); response = execute(request, machineLearningClient::getJob, machineLearningClient::getJobAsync); assertTrue(response.count() >= 2L); assertTrue(response.jobs().size() >= 2L); assertThat(response.jobs().stream().map(Job::getId).collect(Collectors.toList()), hasItems(jobId1, jobId2)); // Test getting all jobs implicitly response = execute(new GetJobRequest(), machineLearningClient::getJob, machineLearningClient::getJobAsync); assertTrue(response.count() >= 2L); assertTrue(response.jobs().size() >= 2L); assertThat(response.jobs().stream().map(Job::getId).collect(Collectors.toList()), hasItems(jobId1, jobId2)); } public void testDeleteJob_GivenWaitForCompletionIsTrue() throws Exception { String jobId = randomValidJobId(); Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job), RequestOptions.DEFAULT); DeleteJobResponse response = execute(new DeleteJobRequest(jobId), machineLearningClient::deleteJob, machineLearningClient::deleteJobAsync); assertTrue(response.getAcknowledged()); assertNull(response.getTask()); } public void testDeleteJob_GivenWaitForCompletionIsFalse() throws Exception { String jobId = randomValidJobId(); Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job), RequestOptions.DEFAULT); DeleteJobRequest deleteJobRequest = new DeleteJobRequest(jobId); deleteJobRequest.setWaitForCompletion(false); DeleteJobResponse response = execute(deleteJobRequest, machineLearningClient::deleteJob, machineLearningClient::deleteJobAsync); assertNull(response.getAcknowledged()); assertNotNull(response.getTask()); } public void testOpenJob() throws Exception { String jobId = randomValidJobId(); Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job), RequestOptions.DEFAULT); OpenJobResponse response = execute(new OpenJobRequest(jobId), machineLearningClient::openJob, machineLearningClient::openJobAsync); assertTrue(response.isOpened()); } public void testCloseJob() throws Exception { String jobId = randomValidJobId(); Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job), RequestOptions.DEFAULT); machineLearningClient.openJob(new OpenJobRequest(jobId), RequestOptions.DEFAULT); CloseJobResponse response = execute(new CloseJobRequest(jobId), machineLearningClient::closeJob, machineLearningClient::closeJobAsync); assertTrue(response.isClosed()); } public void testFlushJob() throws Exception { String jobId = randomValidJobId(); Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job), RequestOptions.DEFAULT); machineLearningClient.openJob(new OpenJobRequest(jobId), RequestOptions.DEFAULT); FlushJobResponse response = execute(new FlushJobRequest(jobId), machineLearningClient::flushJob, machineLearningClient::flushJobAsync); assertTrue(response.isFlushed()); } public void testGetJobStats() throws Exception { String jobId1 = "ml-get-job-stats-test-id-1"; String jobId2 = "ml-get-job-stats-test-id-2"; Job job1 = buildJob(jobId1); Job job2 = buildJob(jobId2); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job1), RequestOptions.DEFAULT); machineLearningClient.putJob(new PutJobRequest(job2), RequestOptions.DEFAULT); machineLearningClient.openJob(new OpenJobRequest(jobId1), RequestOptions.DEFAULT); GetJobStatsRequest request = new GetJobStatsRequest(jobId1, jobId2); // Test getting specific GetJobStatsResponse response = execute(request, machineLearningClient::getJobStats, machineLearningClient::getJobStatsAsync); assertEquals(2, response.count()); assertThat(response.jobStats(), hasSize(2)); assertThat(response.jobStats().stream().map(JobStats::getJobId).collect(Collectors.toList()), containsInAnyOrder(jobId1, jobId2)); for (JobStats stats : response.jobStats()) { if (stats.getJobId().equals(jobId1)) { assertEquals(JobState.OPENED, stats.getState()); } else { assertEquals(JobState.CLOSED, stats.getState()); } } // Test getting all explicitly request = GetJobStatsRequest.getAllJobStatsRequest(); response = execute(request, machineLearningClient::getJobStats, machineLearningClient::getJobStatsAsync); assertTrue(response.count() >= 2L); assertTrue(response.jobStats().size() >= 2L); assertThat(response.jobStats().stream().map(JobStats::getJobId).collect(Collectors.toList()), hasItems(jobId1, jobId2)); // Test getting all implicitly response = execute(new GetJobStatsRequest(), machineLearningClient::getJobStats, machineLearningClient::getJobStatsAsync); assertTrue(response.count() >= 2L); assertTrue(response.jobStats().size() >= 2L); assertThat(response.jobStats().stream().map(JobStats::getJobId).collect(Collectors.toList()), hasItems(jobId1, jobId2)); // Test getting all with wildcard request = new GetJobStatsRequest("ml-get-job-stats-test-id-*"); response = execute(request, machineLearningClient::getJobStats, machineLearningClient::getJobStatsAsync); assertTrue(response.count() >= 2L); assertTrue(response.jobStats().size() >= 2L); assertThat(response.jobStats().stream().map(JobStats::getJobId).collect(Collectors.toList()), hasItems(jobId1, jobId2)); // Test when allow_no_jobs is false final GetJobStatsRequest erroredRequest = new GetJobStatsRequest("jobs-that-do-not-exist*"); erroredRequest.setAllowNoJobs(false); ElasticsearchStatusException exception = expectThrows(ElasticsearchStatusException.class, () -> execute(erroredRequest, machineLearningClient::getJobStats, machineLearningClient::getJobStatsAsync)); assertThat(exception.status().getStatus(), equalTo(404)); } public void testForecastJob() throws Exception { String jobId = "ml-forecast-job-test"; Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job), RequestOptions.DEFAULT); machineLearningClient.openJob(new OpenJobRequest(jobId), RequestOptions.DEFAULT); PostDataRequest.JsonBuilder builder = new PostDataRequest.JsonBuilder(); for(int i = 0; i < 30; i++) { Map<String, Object> hashMap = new HashMap<>(); hashMap.put("total", randomInt(1000)); hashMap.put("timestamp", (i+1)*1000); builder.addDoc(hashMap); } PostDataRequest postDataRequest = new PostDataRequest(jobId, builder); machineLearningClient.postData(postDataRequest, RequestOptions.DEFAULT); machineLearningClient.flushJob(new FlushJobRequest(jobId), RequestOptions.DEFAULT); ForecastJobRequest request = new ForecastJobRequest(jobId); ForecastJobResponse response = execute(request, machineLearningClient::forecastJob, machineLearningClient::forecastJobAsync); assertTrue(response.isAcknowledged()); assertNotNull(response.getForecastId()); } public void testPostData() throws Exception { String jobId = randomValidJobId(); Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job), RequestOptions.DEFAULT); machineLearningClient.openJob(new OpenJobRequest(jobId), RequestOptions.DEFAULT); PostDataRequest.JsonBuilder builder = new PostDataRequest.JsonBuilder(); for(int i = 0; i < 10; i++) { Map<String, Object> hashMap = new HashMap<>(); hashMap.put("total", randomInt(1000)); hashMap.put("timestamp", (i+1)*1000); builder.addDoc(hashMap); } PostDataRequest postDataRequest = new PostDataRequest(jobId, builder); PostDataResponse response = execute(postDataRequest, machineLearningClient::postData, machineLearningClient::postDataAsync); assertEquals(10, response.getDataCounts().getInputRecordCount()); assertEquals(0, response.getDataCounts().getOutOfOrderTimeStampCount()); } public void testUpdateJob() throws Exception { String jobId = randomValidJobId(); Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job), RequestOptions.DEFAULT); UpdateJobRequest request = new UpdateJobRequest(new JobUpdate.Builder(jobId).setDescription("Updated description").build()); PutJobResponse response = execute(request, machineLearningClient::updateJob, machineLearningClient::updateJobAsync); assertEquals("Updated description", response.getResponse().getDescription()); GetJobRequest getRequest = new GetJobRequest(jobId); GetJobResponse getResponse = machineLearningClient.getJob(getRequest, RequestOptions.DEFAULT); assertEquals("Updated description", getResponse.jobs().get(0).getDescription()); } public void testPutDatafeed() throws Exception { String jobId = randomValidJobId(); Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); execute(new PutJobRequest(job), machineLearningClient::putJob, machineLearningClient::putJobAsync); String datafeedId = "datafeed-" + jobId; DatafeedConfig datafeedConfig = DatafeedConfig.builder(datafeedId, jobId).setIndices("some_data_index").build(); PutDatafeedResponse response = execute(new PutDatafeedRequest(datafeedConfig), machineLearningClient::putDatafeed, machineLearningClient::putDatafeedAsync); DatafeedConfig createdDatafeed = response.getResponse(); assertThat(createdDatafeed.getId(), equalTo(datafeedId)); assertThat(createdDatafeed.getIndices(), equalTo(datafeedConfig.getIndices())); } public void testUpdateDatafeed() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String jobId = randomValidJobId(); Job job = buildJob(jobId); execute(new PutJobRequest(job), machineLearningClient::putJob, machineLearningClient::putJobAsync); String datafeedId = "datafeed-" + jobId; DatafeedConfig datafeedConfig = DatafeedConfig.builder(datafeedId, jobId).setIndices("some_data_index").build(); PutDatafeedResponse response = machineLearningClient.putDatafeed(new PutDatafeedRequest(datafeedConfig), RequestOptions.DEFAULT); DatafeedConfig createdDatafeed = response.getResponse(); assertThat(createdDatafeed.getId(), equalTo(datafeedId)); assertThat(createdDatafeed.getIndices(), equalTo(datafeedConfig.getIndices())); DatafeedUpdate datafeedUpdate = DatafeedUpdate.builder(datafeedId).setIndices("some_other_data_index").setScrollSize(10).build(); response = execute(new UpdateDatafeedRequest(datafeedUpdate), machineLearningClient::updateDatafeed, machineLearningClient::updateDatafeedAsync); DatafeedConfig updatedDatafeed = response.getResponse(); assertThat(datafeedUpdate.getId(), equalTo(updatedDatafeed.getId())); assertThat(datafeedUpdate.getIndices(), equalTo(updatedDatafeed.getIndices())); assertThat(datafeedUpdate.getScrollSize(), equalTo(updatedDatafeed.getScrollSize())); } public void testGetDatafeed() throws Exception { String jobId1 = "test-get-datafeed-job-1"; String jobId2 = "test-get-datafeed-job-2"; Job job1 = buildJob(jobId1); Job job2 = buildJob(jobId2); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job1), RequestOptions.DEFAULT); machineLearningClient.putJob(new PutJobRequest(job2), RequestOptions.DEFAULT); String datafeedId1 = jobId1 + "-feed"; String datafeedId2 = jobId2 + "-feed"; DatafeedConfig datafeed1 = DatafeedConfig.builder(datafeedId1, jobId1).setIndices("data_1").build(); DatafeedConfig datafeed2 = DatafeedConfig.builder(datafeedId2, jobId2).setIndices("data_2").build(); machineLearningClient.putDatafeed(new PutDatafeedRequest(datafeed1), RequestOptions.DEFAULT); machineLearningClient.putDatafeed(new PutDatafeedRequest(datafeed2), RequestOptions.DEFAULT); // Test getting specific datafeeds { GetDatafeedRequest request = new GetDatafeedRequest(datafeedId1, datafeedId2); GetDatafeedResponse response = execute(request, machineLearningClient::getDatafeed, machineLearningClient::getDatafeedAsync); assertEquals(2, response.count()); assertThat(response.datafeeds(), hasSize(2)); assertThat(response.datafeeds().stream().map(DatafeedConfig::getId).collect(Collectors.toList()), containsInAnyOrder(datafeedId1, datafeedId2)); } // Test getting a single one { GetDatafeedRequest request = new GetDatafeedRequest(datafeedId1); GetDatafeedResponse response = execute(request, machineLearningClient::getDatafeed, machineLearningClient::getDatafeedAsync); assertTrue(response.count() == 1L); assertThat(response.datafeeds().get(0).getId(), equalTo(datafeedId1)); } // Test getting all datafeeds explicitly { GetDatafeedRequest request = GetDatafeedRequest.getAllDatafeedsRequest(); GetDatafeedResponse response = execute(request, machineLearningClient::getDatafeed, machineLearningClient::getDatafeedAsync); assertTrue(response.count() == 2L); assertTrue(response.datafeeds().size() == 2L); assertThat(response.datafeeds().stream().map(DatafeedConfig::getId).collect(Collectors.toList()), hasItems(datafeedId1, datafeedId2)); } // Test getting all datafeeds implicitly { GetDatafeedResponse response = execute(new GetDatafeedRequest(), machineLearningClient::getDatafeed, machineLearningClient::getDatafeedAsync); assertTrue(response.count() >= 2L); assertTrue(response.datafeeds().size() >= 2L); assertThat(response.datafeeds().stream().map(DatafeedConfig::getId).collect(Collectors.toList()), hasItems(datafeedId1, datafeedId2)); } // Test get missing pattern with allow_no_datafeeds set to true { GetDatafeedRequest request = new GetDatafeedRequest("missing-*"); GetDatafeedResponse response = execute(request, machineLearningClient::getDatafeed, machineLearningClient::getDatafeedAsync); assertThat(response.count(), equalTo(0L)); } // Test get missing pattern with allow_no_datafeeds set to false { GetDatafeedRequest request = new GetDatafeedRequest("missing-*"); request.setAllowNoDatafeeds(false); ElasticsearchStatusException e = expectThrows(ElasticsearchStatusException.class, () -> execute(request, machineLearningClient::getDatafeed, machineLearningClient::getDatafeedAsync)); assertThat(e.status(), equalTo(RestStatus.NOT_FOUND)); } } public void testDeleteDatafeed() throws Exception { String jobId = randomValidJobId(); Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job), RequestOptions.DEFAULT); String datafeedId = "datafeed-" + jobId; DatafeedConfig datafeedConfig = DatafeedConfig.builder(datafeedId, jobId).setIndices("some_data_index").build(); execute(new PutDatafeedRequest(datafeedConfig), machineLearningClient::putDatafeed, machineLearningClient::putDatafeedAsync); AcknowledgedResponse response = execute(new DeleteDatafeedRequest(datafeedId), machineLearningClient::deleteDatafeed, machineLearningClient::deleteDatafeedAsync); assertTrue(response.isAcknowledged()); } public void testStartDatafeed() throws Exception { String jobId = "test-start-datafeed"; String indexName = "start_data_1"; // Set up the index and docs createIndex(indexName, defaultMappingForTest()); BulkRequest bulk = new BulkRequest(); bulk.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); long now = (System.currentTimeMillis()/1000)*1000; long thePast = now - 60000; int i = 0; long pastCopy = thePast; while(pastCopy < now) { IndexRequest doc = new IndexRequest(); doc.index(indexName); doc.id("id" + i); doc.source("{\"total\":" +randomInt(1000) + ",\"timestamp\":"+ pastCopy +"}", XContentType.JSON); bulk.add(doc); pastCopy += 1000; i++; } highLevelClient().bulk(bulk, RequestOptions.DEFAULT); final long totalDocCount = i; // create the job and the datafeed Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job), RequestOptions.DEFAULT); machineLearningClient.openJob(new OpenJobRequest(jobId), RequestOptions.DEFAULT); String datafeedId = jobId + "-feed"; DatafeedConfig datafeed = DatafeedConfig.builder(datafeedId, jobId) .setIndices(indexName) .setQueryDelay(TimeValue.timeValueSeconds(1)) .setFrequency(TimeValue.timeValueSeconds(1)).build(); machineLearningClient.putDatafeed(new PutDatafeedRequest(datafeed), RequestOptions.DEFAULT); StartDatafeedRequest startDatafeedRequest = new StartDatafeedRequest(datafeedId); startDatafeedRequest.setStart(String.valueOf(thePast)); // Should only process two documents startDatafeedRequest.setEnd(String.valueOf(thePast + 2000)); StartDatafeedResponse response = execute(startDatafeedRequest, machineLearningClient::startDatafeed, machineLearningClient::startDatafeedAsync); assertTrue(response.isStarted()); assertBusy(() -> { JobStats stats = machineLearningClient.getJobStats(new GetJobStatsRequest(jobId), RequestOptions.DEFAULT).jobStats().get(0); assertEquals(2L, stats.getDataCounts().getInputRecordCount()); assertEquals(JobState.CLOSED, stats.getState()); }, 30, TimeUnit.SECONDS); machineLearningClient.openJob(new OpenJobRequest(jobId), RequestOptions.DEFAULT); StartDatafeedRequest wholeDataFeed = new StartDatafeedRequest(datafeedId); // Process all documents and end the stream wholeDataFeed.setEnd(String.valueOf(now)); StartDatafeedResponse wholeResponse = execute(wholeDataFeed, machineLearningClient::startDatafeed, machineLearningClient::startDatafeedAsync); assertTrue(wholeResponse.isStarted()); assertBusy(() -> { JobStats stats = machineLearningClient.getJobStats(new GetJobStatsRequest(jobId), RequestOptions.DEFAULT).jobStats().get(0); assertEquals(totalDocCount, stats.getDataCounts().getInputRecordCount()); assertEquals(JobState.CLOSED, stats.getState()); }, 30, TimeUnit.SECONDS); } public void testStopDatafeed() throws Exception { String jobId1 = "test-stop-datafeed1"; String jobId2 = "test-stop-datafeed2"; String jobId3 = "test-stop-datafeed3"; String indexName = "stop_data_1"; // Set up the index createIndex(indexName, defaultMappingForTest()); // create the job and the datafeed Job job1 = buildJob(jobId1); putJob(job1); openJob(job1); Job job2 = buildJob(jobId2); putJob(job2); openJob(job2); Job job3 = buildJob(jobId3); putJob(job3); openJob(job3); String datafeedId1 = createAndPutDatafeed(jobId1, indexName); String datafeedId2 = createAndPutDatafeed(jobId2, indexName); String datafeedId3 = createAndPutDatafeed(jobId3, indexName); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.startDatafeed(new StartDatafeedRequest(datafeedId1), RequestOptions.DEFAULT); machineLearningClient.startDatafeed(new StartDatafeedRequest(datafeedId2), RequestOptions.DEFAULT); machineLearningClient.startDatafeed(new StartDatafeedRequest(datafeedId3), RequestOptions.DEFAULT); { StopDatafeedRequest request = new StopDatafeedRequest(datafeedId1); request.setAllowNoDatafeeds(false); StopDatafeedResponse stopDatafeedResponse = execute(request, machineLearningClient::stopDatafeed, machineLearningClient::stopDatafeedAsync); assertTrue(stopDatafeedResponse.isStopped()); } { StopDatafeedRequest request = new StopDatafeedRequest(datafeedId2, datafeedId3); request.setAllowNoDatafeeds(false); StopDatafeedResponse stopDatafeedResponse = execute(request, machineLearningClient::stopDatafeed, machineLearningClient::stopDatafeedAsync); assertTrue(stopDatafeedResponse.isStopped()); } { StopDatafeedResponse stopDatafeedResponse = execute(new StopDatafeedRequest("datafeed_that_doesnot_exist*"), machineLearningClient::stopDatafeed, machineLearningClient::stopDatafeedAsync); assertTrue(stopDatafeedResponse.isStopped()); } { StopDatafeedRequest request = new StopDatafeedRequest("datafeed_that_doesnot_exist*"); request.setAllowNoDatafeeds(false); ElasticsearchStatusException exception = expectThrows(ElasticsearchStatusException.class, () -> execute(request, machineLearningClient::stopDatafeed, machineLearningClient::stopDatafeedAsync)); assertThat(exception.status().getStatus(), equalTo(404)); } } public void testGetDatafeedStats() throws Exception { String jobId1 = "ml-get-datafeed-stats-test-id-1"; String jobId2 = "ml-get-datafeed-stats-test-id-2"; String indexName = "datafeed_stats_data_1"; // Set up the index createIndex(indexName, defaultMappingForTest()); // create the job and the datafeed Job job1 = buildJob(jobId1); putJob(job1); openJob(job1); Job job2 = buildJob(jobId2); putJob(job2); String datafeedId1 = createAndPutDatafeed(jobId1, indexName); String datafeedId2 = createAndPutDatafeed(jobId2, indexName); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.startDatafeed(new StartDatafeedRequest(datafeedId1), RequestOptions.DEFAULT); GetDatafeedStatsRequest request = new GetDatafeedStatsRequest(datafeedId1); // Test getting specific GetDatafeedStatsResponse response = execute(request, machineLearningClient::getDatafeedStats, machineLearningClient::getDatafeedStatsAsync); assertEquals(1, response.count()); assertThat(response.datafeedStats(), hasSize(1)); assertThat(response.datafeedStats().get(0).getDatafeedId(), equalTo(datafeedId1)); assertThat(response.datafeedStats().get(0).getDatafeedState().toString(), equalTo(DatafeedState.STARTED.toString())); // Test getting all explicitly request = GetDatafeedStatsRequest.getAllDatafeedStatsRequest(); response = execute(request, machineLearningClient::getDatafeedStats, machineLearningClient::getDatafeedStatsAsync); assertTrue(response.count() >= 2L); assertTrue(response.datafeedStats().size() >= 2L); assertThat(response.datafeedStats().stream().map(DatafeedStats::getDatafeedId).collect(Collectors.toList()), hasItems(datafeedId1, datafeedId2)); // Test getting all implicitly response = execute(new GetDatafeedStatsRequest(), machineLearningClient::getDatafeedStats, machineLearningClient::getDatafeedStatsAsync); assertTrue(response.count() >= 2L); assertTrue(response.datafeedStats().size() >= 2L); assertThat(response.datafeedStats().stream().map(DatafeedStats::getDatafeedId).collect(Collectors.toList()), hasItems(datafeedId1, datafeedId2)); // Test getting all with wildcard request = new GetDatafeedStatsRequest("ml-get-datafeed-stats-test-id-*"); response = execute(request, machineLearningClient::getDatafeedStats, machineLearningClient::getDatafeedStatsAsync); assertEquals(2L, response.count()); assertThat(response.datafeedStats(), hasSize(2)); assertThat(response.datafeedStats().stream().map(DatafeedStats::getDatafeedId).collect(Collectors.toList()), hasItems(datafeedId1, datafeedId2)); // Test when allow_no_jobs is false final GetDatafeedStatsRequest erroredRequest = new GetDatafeedStatsRequest("datafeeds-that-do-not-exist*"); erroredRequest.setAllowNoDatafeeds(false); ElasticsearchStatusException exception = expectThrows(ElasticsearchStatusException.class, () -> execute(erroredRequest, machineLearningClient::getDatafeedStats, machineLearningClient::getDatafeedStatsAsync)); assertThat(exception.status().getStatus(), equalTo(404)); } public void testPreviewDatafeed() throws Exception { String jobId = "test-preview-datafeed"; String indexName = "preview_data_1"; // Set up the index and docs createIndex(indexName, defaultMappingForTest()); BulkRequest bulk = new BulkRequest(); bulk.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); long now = (System.currentTimeMillis()/1000)*1000; long thePast = now - 60000; int i = 0; List<Integer> totalTotals = new ArrayList<>(60); while(thePast < now) { Integer total = randomInt(1000); IndexRequest doc = new IndexRequest(); doc.index(indexName); doc.id("id" + i); doc.source("{\"total\":" + total + ",\"timestamp\":"+ thePast +"}", XContentType.JSON); bulk.add(doc); thePast += 1000; i++; totalTotals.add(total); } highLevelClient().bulk(bulk, RequestOptions.DEFAULT); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); // create the job and the datafeed Job job = buildJob(jobId); putJob(job); openJob(job); String datafeedId = jobId + "-feed"; DatafeedConfig datafeed = DatafeedConfig.builder(datafeedId, jobId) .setIndices(indexName) .setQueryDelay(TimeValue.timeValueSeconds(1)) .setFrequency(TimeValue.timeValueSeconds(1)).build(); machineLearningClient.putDatafeed(new PutDatafeedRequest(datafeed), RequestOptions.DEFAULT); PreviewDatafeedResponse response = execute(new PreviewDatafeedRequest(datafeedId), machineLearningClient::previewDatafeed, machineLearningClient::previewDatafeedAsync); Integer[] totals = response.getDataList().stream().map(map -> (Integer)map.get("total")).toArray(Integer[]::new); assertThat(totalTotals, containsInAnyOrder(totals)); } public void testDeleteExpiredDataGivenNothingToDelete() throws Exception { // Tests that nothing goes wrong when there's nothing to delete MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); DeleteExpiredDataResponse response = execute(new DeleteExpiredDataRequest(), machineLearningClient::deleteExpiredData, machineLearningClient::deleteExpiredDataAsync); assertTrue(response.getDeleted()); } private String createExpiredData(String jobId) throws Exception { String indexName = jobId + "-data"; // Set up the index and docs createIndex(indexName, defaultMappingForTest()); BulkRequest bulk = new BulkRequest(); bulk.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); long nowMillis = System.currentTimeMillis(); int totalBuckets = 2 * 24; int normalRate = 10; int anomalousRate = 100; int anomalousBucket = 30; for (int bucket = 0; bucket < totalBuckets; bucket++) { long timestamp = nowMillis - TimeValue.timeValueHours(totalBuckets - bucket).getMillis(); int bucketRate = bucket == anomalousBucket ? anomalousRate : normalRate; for (int point = 0; point < bucketRate; point++) { IndexRequest indexRequest = new IndexRequest(indexName); indexRequest.source(XContentType.JSON, "timestamp", timestamp, "total", randomInt(1000)); bulk.add(indexRequest); } } highLevelClient().bulk(bulk, RequestOptions.DEFAULT); { // Index a randomly named unused state document String docId = "non_existing_job_" + randomFrom("model_state_1234567#1", "quantiles", "categorizer_state#1"); IndexRequest indexRequest = new IndexRequest(".ml-state-000001").id(docId); indexRequest.source(Collections.emptyMap(), XContentType.JSON); indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); highLevelClient().index(indexRequest, RequestOptions.DEFAULT); } Job job = buildJobForExpiredDataTests(jobId); putJob(job); openJob(job); String datafeedId = createAndPutDatafeed(jobId, indexName); startDatafeed(datafeedId, String.valueOf(0), String.valueOf(nowMillis - TimeValue.timeValueHours(24).getMillis())); waitForJobToClose(jobId); long prevJobTimeStamp = System.currentTimeMillis() / 1000; // Check that the current timestamp component, in seconds, differs from previously. // Note that we used to use an 'awaitBusy(() -> false, 1, TimeUnit.SECONDS);' // for the same purpose but the new approach... // a) explicitly checks that the timestamps, in seconds, are actually different and // b) is slightly more efficient since we may not need to wait an entire second for the timestamp to increment assertBusy(() -> { long timeNow = System.currentTimeMillis() / 1000; assertThat(prevJobTimeStamp, lessThan(timeNow)); }); // Update snapshot timestamp to force it out of snapshot retention window long oneDayAgo = nowMillis - TimeValue.timeValueHours(24).getMillis() - 1; updateModelSnapshotTimestamp(jobId, String.valueOf(oneDayAgo)); openJob(job); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); ForecastJobRequest forecastJobRequest = new ForecastJobRequest(jobId); forecastJobRequest.setDuration(TimeValue.timeValueHours(3)); forecastJobRequest.setExpiresIn(TimeValue.timeValueSeconds(1)); ForecastJobResponse forecastJobResponse = machineLearningClient.forecastJob(forecastJobRequest, RequestOptions.DEFAULT); waitForForecastToComplete(jobId, forecastJobResponse.getForecastId()); // Wait for the forecast to expire // FIXME: We should wait for something specific to change, rather than waiting for time to pass. waitUntil(() -> false, 1, TimeUnit.SECONDS); // Run up to now startDatafeed(datafeedId, String.valueOf(0), String.valueOf(nowMillis)); waitForJobToClose(jobId); return forecastJobResponse.getForecastId(); } public void testDeleteExpiredData() throws Exception { String jobId = "test-delete-expired-data"; String forecastId = createExpiredData(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); GetModelSnapshotsRequest getModelSnapshotsRequest = new GetModelSnapshotsRequest(jobId); GetModelSnapshotsResponse getModelSnapshotsResponse = execute(getModelSnapshotsRequest, machineLearningClient::getModelSnapshots, machineLearningClient::getModelSnapshotsAsync); assertEquals(2L, getModelSnapshotsResponse.count()); assertTrue(forecastExists(jobId, forecastId)); { // Verify .ml-state* contains the expected unused state document Iterable<SearchHit> hits = searchAll(".ml-state*"); List<SearchHit> target = new ArrayList<>(); hits.forEach(target::add); long numMatches = target.stream() .filter(c -> c.getId().startsWith("non_existing_job")) .count(); assertThat(numMatches, equalTo(1L)); } DeleteExpiredDataRequest request = new DeleteExpiredDataRequest(); DeleteExpiredDataResponse response = execute(request, machineLearningClient::deleteExpiredData, machineLearningClient::deleteExpiredDataAsync); assertTrue(response.getDeleted()); // Wait for the forecast to expire // FIXME: We should wait for something specific to change, rather than waiting for time to pass. waitUntil(() -> false, 1, TimeUnit.SECONDS); GetModelSnapshotsRequest getModelSnapshotsRequest1 = new GetModelSnapshotsRequest(jobId); GetModelSnapshotsResponse getModelSnapshotsResponse1 = execute(getModelSnapshotsRequest1, machineLearningClient::getModelSnapshots, machineLearningClient::getModelSnapshotsAsync); assertEquals(1L, getModelSnapshotsResponse1.count()); assertFalse(forecastExists(jobId, forecastId)); { // Verify .ml-state* doesn't contain unused state documents Iterable<SearchHit> hits = searchAll(".ml-state*"); List<SearchHit> hitList = new ArrayList<>(); hits.forEach(hitList::add); long numMatches = hitList.stream() .filter(c -> c.getId().startsWith("non_existing_job")) .count(); assertThat(numMatches, equalTo(0L)); } } public void testDeleteForecast() throws Exception { String jobId = "test-delete-forecast"; Job job = buildJob(jobId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putJob(new PutJobRequest(job), RequestOptions.DEFAULT); machineLearningClient.openJob(new OpenJobRequest(jobId), RequestOptions.DEFAULT); Job noForecastsJob = buildJob("test-delete-forecast-none"); machineLearningClient.putJob(new PutJobRequest(noForecastsJob), RequestOptions.DEFAULT); PostDataRequest.JsonBuilder builder = new PostDataRequest.JsonBuilder(); for(int i = 0; i < 30; i++) { Map<String, Object> hashMap = new HashMap<>(); hashMap.put("total", randomInt(1000)); hashMap.put("timestamp", (i+1)*1000); builder.addDoc(hashMap); } PostDataRequest postDataRequest = new PostDataRequest(jobId, builder); machineLearningClient.postData(postDataRequest, RequestOptions.DEFAULT); machineLearningClient.flushJob(new FlushJobRequest(jobId), RequestOptions.DEFAULT); ForecastJobResponse forecastJobResponse1 = machineLearningClient.forecastJob(new ForecastJobRequest(jobId), RequestOptions.DEFAULT); ForecastJobResponse forecastJobResponse2 = machineLearningClient.forecastJob(new ForecastJobRequest(jobId), RequestOptions.DEFAULT); waitForForecastToComplete(jobId, forecastJobResponse1.getForecastId()); waitForForecastToComplete(jobId, forecastJobResponse2.getForecastId()); { DeleteForecastRequest request = new DeleteForecastRequest(jobId); request.setForecastIds(forecastJobResponse1.getForecastId(), forecastJobResponse2.getForecastId()); AcknowledgedResponse response = execute(request, machineLearningClient::deleteForecast, machineLearningClient::deleteForecastAsync); assertTrue(response.isAcknowledged()); assertFalse(forecastExists(jobId, forecastJobResponse1.getForecastId())); assertFalse(forecastExists(jobId, forecastJobResponse2.getForecastId())); } { DeleteForecastRequest request = DeleteForecastRequest.deleteAllForecasts(noForecastsJob.getId()); request.setAllowNoForecasts(true); AcknowledgedResponse response = execute(request, machineLearningClient::deleteForecast, machineLearningClient::deleteForecastAsync); assertTrue(response.isAcknowledged()); } { DeleteForecastRequest request = DeleteForecastRequest.deleteAllForecasts(noForecastsJob.getId()); request.setAllowNoForecasts(false); ElasticsearchStatusException exception = expectThrows(ElasticsearchStatusException.class, () -> execute(request, machineLearningClient::deleteForecast, machineLearningClient::deleteForecastAsync)); assertThat(exception.status().getStatus(), equalTo(404)); } } private void waitForForecastToComplete(String jobId, String forecastId) throws Exception { GetRequest request = new GetRequest(".ml-anomalies-" + jobId); request.id(jobId + "_model_forecast_request_stats_" + forecastId); assertBusy(() -> { GetResponse getResponse = highLevelClient().get(request, RequestOptions.DEFAULT); assertTrue(getResponse.isExists()); assertTrue(getResponse.getSourceAsString().contains("finished")); }, 30, TimeUnit.SECONDS); } private boolean forecastExists(String jobId, String forecastId) throws Exception { GetRequest getRequest = new GetRequest(".ml-anomalies-" + jobId); getRequest.id(jobId + "_model_forecast_request_stats_" + forecastId); GetResponse getResponse = highLevelClient().get(getRequest, RequestOptions.DEFAULT); return getResponse.isExists(); } public void testPutCalendar() throws IOException { Calendar calendar = CalendarTests.testInstance(); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); PutCalendarResponse putCalendarResponse = execute(new PutCalendarRequest(calendar), machineLearningClient::putCalendar, machineLearningClient::putCalendarAsync); assertThat(putCalendarResponse.getCalendar(), equalTo(calendar)); } public void testPutCalendarJob() throws IOException { Calendar calendar = new Calendar("put-calendar-job-id", Collections.singletonList("put-calendar-job-0"), null); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); PutCalendarResponse putCalendarResponse = machineLearningClient.putCalendar(new PutCalendarRequest(calendar), RequestOptions.DEFAULT); assertThat(putCalendarResponse.getCalendar().getJobIds(), containsInAnyOrder( "put-calendar-job-0")); String jobId1 = "put-calendar-job-1"; String jobId2 = "put-calendar-job-2"; PutCalendarJobRequest putCalendarJobRequest = new PutCalendarJobRequest(calendar.getId(), jobId1, jobId2); putCalendarResponse = execute(putCalendarJobRequest, machineLearningClient::putCalendarJob, machineLearningClient::putCalendarJobAsync); assertThat(putCalendarResponse.getCalendar().getJobIds(), containsInAnyOrder(jobId1, jobId2, "put-calendar-job-0")); } public void testDeleteCalendarJob() throws IOException { Calendar calendar = new Calendar("del-calendar-job-id", Arrays.asList("del-calendar-job-0", "del-calendar-job-1", "del-calendar-job-2"), null); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); PutCalendarResponse putCalendarResponse = machineLearningClient.putCalendar(new PutCalendarRequest(calendar), RequestOptions.DEFAULT); assertThat(putCalendarResponse.getCalendar().getJobIds(), containsInAnyOrder("del-calendar-job-0", "del-calendar-job-1", "del-calendar-job-2")); String jobId1 = "del-calendar-job-0"; String jobId2 = "del-calendar-job-2"; DeleteCalendarJobRequest deleteCalendarJobRequest = new DeleteCalendarJobRequest(calendar.getId(), jobId1, jobId2); putCalendarResponse = execute(deleteCalendarJobRequest, machineLearningClient::deleteCalendarJob, machineLearningClient::deleteCalendarJobAsync); assertThat(putCalendarResponse.getCalendar().getJobIds(), containsInAnyOrder("del-calendar-job-1")); } public void testGetCalendars() throws Exception { Calendar calendar1 = CalendarTests.testInstance(); Calendar calendar2 = CalendarTests.testInstance(); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putCalendar(new PutCalendarRequest(calendar1), RequestOptions.DEFAULT); machineLearningClient.putCalendar(new PutCalendarRequest(calendar2), RequestOptions.DEFAULT); GetCalendarsRequest getCalendarsRequest = new GetCalendarsRequest(); getCalendarsRequest.setCalendarId("_all"); GetCalendarsResponse getCalendarsResponse = execute(getCalendarsRequest, machineLearningClient::getCalendars, machineLearningClient::getCalendarsAsync); assertEquals(2, getCalendarsResponse.count()); assertEquals(2, getCalendarsResponse.calendars().size()); assertThat(getCalendarsResponse.calendars().stream().map(Calendar::getId).collect(Collectors.toList()), hasItems(calendar1.getId(), calendar1.getId())); getCalendarsRequest.setCalendarId(calendar1.getId()); getCalendarsResponse = execute(getCalendarsRequest, machineLearningClient::getCalendars, machineLearningClient::getCalendarsAsync); assertEquals(1, getCalendarsResponse.count()); assertEquals(calendar1, getCalendarsResponse.calendars().get(0)); } public void testDeleteCalendar() throws IOException { Calendar calendar = CalendarTests.testInstance(); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); execute(new PutCalendarRequest(calendar), machineLearningClient::putCalendar, machineLearningClient::putCalendarAsync); AcknowledgedResponse response = execute(new DeleteCalendarRequest(calendar.getId()), machineLearningClient::deleteCalendar, machineLearningClient::deleteCalendarAsync); assertTrue(response.isAcknowledged()); // calendar is missing ElasticsearchStatusException exception = expectThrows(ElasticsearchStatusException.class, () -> execute(new DeleteCalendarRequest(calendar.getId()), machineLearningClient::deleteCalendar, machineLearningClient::deleteCalendarAsync)); assertThat(exception.status().getStatus(), equalTo(404)); } public void testGetCalendarEvent() throws Exception { Calendar calendar = new Calendar("get-calendar-event-id", Collections.singletonList("get-calendar-event-job"), null); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putCalendar(new PutCalendarRequest(calendar), RequestOptions.DEFAULT); List<ScheduledEvent> events = new ArrayList<>(3); for (int i = 0; i < 3; i++) { events.add(ScheduledEventTests.testInstance(calendar.getId(), null)); } machineLearningClient.postCalendarEvent(new PostCalendarEventRequest(calendar.getId(), events), RequestOptions.DEFAULT); { GetCalendarEventsRequest getCalendarEventsRequest = new GetCalendarEventsRequest(calendar.getId()); GetCalendarEventsResponse getCalendarEventsResponse = execute(getCalendarEventsRequest, machineLearningClient::getCalendarEvents, machineLearningClient::getCalendarEventsAsync); assertThat(getCalendarEventsResponse.events().size(), equalTo(3)); assertThat(getCalendarEventsResponse.count(), equalTo(3L)); } { GetCalendarEventsRequest getCalendarEventsRequest = new GetCalendarEventsRequest(calendar.getId()); getCalendarEventsRequest.setPageParams(new PageParams(1, 2)); GetCalendarEventsResponse getCalendarEventsResponse = execute(getCalendarEventsRequest, machineLearningClient::getCalendarEvents, machineLearningClient::getCalendarEventsAsync); assertThat(getCalendarEventsResponse.events().size(), equalTo(2)); assertThat(getCalendarEventsResponse.count(), equalTo(3L)); } { machineLearningClient.putJob(new PutJobRequest(buildJob("get-calendar-event-job")), RequestOptions.DEFAULT); GetCalendarEventsRequest getCalendarEventsRequest = new GetCalendarEventsRequest("_all"); getCalendarEventsRequest.setJobId("get-calendar-event-job"); GetCalendarEventsResponse getCalendarEventsResponse = execute(getCalendarEventsRequest, machineLearningClient::getCalendarEvents, machineLearningClient::getCalendarEventsAsync); assertThat(getCalendarEventsResponse.events().size(), equalTo(3)); assertThat(getCalendarEventsResponse.count(), equalTo(3L)); } } public void testPostCalendarEvent() throws Exception { Calendar calendar = CalendarTests.testInstance(); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putCalendar(new PutCalendarRequest(calendar), RequestOptions.DEFAULT); List<ScheduledEvent> events = new ArrayList<>(3); for (int i = 0; i < 3; i++) { events.add(ScheduledEventTests.testInstance(calendar.getId(), null)); } PostCalendarEventRequest postCalendarEventRequest = new PostCalendarEventRequest(calendar.getId(), events); PostCalendarEventResponse postCalendarEventResponse = execute(postCalendarEventRequest, machineLearningClient::postCalendarEvent, machineLearningClient::postCalendarEventAsync); assertThat(postCalendarEventResponse.getScheduledEvents(), containsInAnyOrder(events.toArray())); } public void testDeleteCalendarEvent() throws IOException { Calendar calendar = CalendarTests.testInstance(); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putCalendar(new PutCalendarRequest(calendar), RequestOptions.DEFAULT); List<ScheduledEvent> events = new ArrayList<>(3); for (int i = 0; i < 3; i++) { events.add(ScheduledEventTests.testInstance(calendar.getId(), null)); } machineLearningClient.postCalendarEvent(new PostCalendarEventRequest(calendar.getId(), events), RequestOptions.DEFAULT); GetCalendarEventsResponse getCalendarEventsResponse = machineLearningClient.getCalendarEvents(new GetCalendarEventsRequest(calendar.getId()), RequestOptions.DEFAULT); assertThat(getCalendarEventsResponse.events().size(), equalTo(3)); String deletedEvent = getCalendarEventsResponse.events().get(0).getEventId(); DeleteCalendarEventRequest deleteCalendarEventRequest = new DeleteCalendarEventRequest(calendar.getId(), deletedEvent); AcknowledgedResponse response = execute(deleteCalendarEventRequest, machineLearningClient::deleteCalendarEvent, machineLearningClient::deleteCalendarEventAsync); assertThat(response.isAcknowledged(), is(true)); getCalendarEventsResponse = machineLearningClient.getCalendarEvents(new GetCalendarEventsRequest(calendar.getId()), RequestOptions.DEFAULT); List<String> remainingIds = getCalendarEventsResponse.events() .stream() .map(ScheduledEvent::getEventId) .collect(Collectors.toList()); assertThat(remainingIds.size(), equalTo(2)); assertThat(remainingIds, not(hasItem(deletedEvent))); } public void testEstimateModelMemory() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String byFieldName = randomAlphaOfLength(10); String influencerFieldName = randomAlphaOfLength(10); AnalysisConfig analysisConfig = AnalysisConfig.builder( Collections.singletonList( Detector.builder().setFunction("count").setByFieldName(byFieldName).build() )).setInfluencers(Collections.singletonList(influencerFieldName)).build(); EstimateModelMemoryRequest estimateModelMemoryRequest = new EstimateModelMemoryRequest(analysisConfig); estimateModelMemoryRequest.setOverallCardinality(Collections.singletonMap(byFieldName, randomNonNegativeLong())); estimateModelMemoryRequest.setMaxBucketCardinality(Collections.singletonMap(influencerFieldName, randomNonNegativeLong())); EstimateModelMemoryResponse estimateModelMemoryResponse = execute( estimateModelMemoryRequest, machineLearningClient::estimateModelMemory, machineLearningClient::estimateModelMemoryAsync); ByteSizeValue modelMemoryEstimate = estimateModelMemoryResponse.getModelMemoryEstimate(); assertThat(modelMemoryEstimate.getBytes(), greaterThanOrEqualTo(10000000L)); } public void testPutDataFrameAnalyticsConfig_GivenOutlierDetectionAnalysis() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String configId = "test-put-df-analytics-outlier-detection"; DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setId(configId) .setSource(DataFrameAnalyticsSource.builder() .setIndex("put-test-source-index") .build()) .setDest(DataFrameAnalyticsDest.builder() .setIndex("put-test-dest-index") .build()) .setAnalysis(OutlierDetection.createDefault()) .setDescription("some description") .build(); createIndex("put-test-source-index", defaultMappingForTest()); PutDataFrameAnalyticsResponse putDataFrameAnalyticsResponse = execute( new PutDataFrameAnalyticsRequest(config), machineLearningClient::putDataFrameAnalytics, machineLearningClient::putDataFrameAnalyticsAsync); DataFrameAnalyticsConfig createdConfig = putDataFrameAnalyticsResponse.getConfig(); assertThat(createdConfig.getId(), equalTo(config.getId())); assertThat(createdConfig.getSource().getIndex(), equalTo(config.getSource().getIndex())); assertThat(createdConfig.getSource().getQueryConfig(), equalTo(new QueryConfig(new MatchAllQueryBuilder()))); // default value assertThat(createdConfig.getDest().getIndex(), equalTo(config.getDest().getIndex())); assertThat(createdConfig.getDest().getResultsField(), equalTo("ml")); // default value assertThat(createdConfig.getAnalysis(), equalTo(OutlierDetection.builder() .setComputeFeatureInfluence(true) .setOutlierFraction(0.05) .setStandardizationEnabled(true).build())); assertThat(createdConfig.getAnalyzedFields(), equalTo(config.getAnalyzedFields())); assertThat(createdConfig.getModelMemoryLimit(), equalTo(ByteSizeValue.parseBytesSizeValue("1gb", ""))); // default value assertThat(createdConfig.getDescription(), equalTo("some description")); assertThat(createdConfig.getMaxNumThreads(), equalTo(1)); } public void testPutDataFrameAnalyticsConfig_GivenRegression() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String configId = "test-put-df-analytics-regression"; DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setId(configId) .setSource(DataFrameAnalyticsSource.builder() .setIndex("put-test-source-index") .build()) .setDest(DataFrameAnalyticsDest.builder() .setIndex("put-test-dest-index") .build()) .setAnalysis(org.elasticsearch.client.ml.dataframe.Regression.builder("my_dependent_variable") .setPredictionFieldName("my_dependent_variable_prediction") .setTrainingPercent(80.0) .setRandomizeSeed(42L) .setLambda(1.0) .setGamma(1.0) .setEta(1.0) .setMaxTrees(10) .setFeatureBagFraction(0.5) .setNumTopFeatureImportanceValues(3) .setLossFunction(org.elasticsearch.client.ml.dataframe.Regression.LossFunction.MSLE) .setLossFunctionParameter(1.0) .build()) .setDescription("this is a regression") .build(); createIndex("put-test-source-index", defaultMappingForTest()); PutDataFrameAnalyticsResponse putDataFrameAnalyticsResponse = execute( new PutDataFrameAnalyticsRequest(config), machineLearningClient::putDataFrameAnalytics, machineLearningClient::putDataFrameAnalyticsAsync); DataFrameAnalyticsConfig createdConfig = putDataFrameAnalyticsResponse.getConfig(); assertThat(createdConfig.getId(), equalTo(config.getId())); assertThat(createdConfig.getSource().getIndex(), equalTo(config.getSource().getIndex())); assertThat(createdConfig.getSource().getQueryConfig(), equalTo(new QueryConfig(new MatchAllQueryBuilder()))); // default value assertThat(createdConfig.getDest().getIndex(), equalTo(config.getDest().getIndex())); assertThat(createdConfig.getDest().getResultsField(), equalTo("ml")); // default value assertThat(createdConfig.getAnalysis(), equalTo(config.getAnalysis())); assertThat(createdConfig.getAnalyzedFields(), equalTo(config.getAnalyzedFields())); assertThat(createdConfig.getModelMemoryLimit(), equalTo(ByteSizeValue.parseBytesSizeValue("1gb", ""))); // default value assertThat(createdConfig.getDescription(), equalTo("this is a regression")); } public void testPutDataFrameAnalyticsConfig_GivenClassification() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String configId = "test-put-df-analytics-classification"; DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setId(configId) .setSource(DataFrameAnalyticsSource.builder() .setIndex("put-test-source-index") .build()) .setDest(DataFrameAnalyticsDest.builder() .setIndex("put-test-dest-index") .build()) .setAnalysis(org.elasticsearch.client.ml.dataframe.Classification.builder("my_dependent_variable") .setPredictionFieldName("my_dependent_variable_prediction") .setTrainingPercent(80.0) .setRandomizeSeed(42L) .setClassAssignmentObjective( org.elasticsearch.client.ml.dataframe.Classification.ClassAssignmentObjective.MAXIMIZE_ACCURACY) .setNumTopClasses(1) .setLambda(1.0) .setGamma(1.0) .setEta(1.0) .setMaxTrees(10) .setFeatureBagFraction(0.5) .setNumTopFeatureImportanceValues(3) .build()) .setDescription("this is a classification") .build(); createIndex("put-test-source-index", defaultMappingForTest()); PutDataFrameAnalyticsResponse putDataFrameAnalyticsResponse = execute( new PutDataFrameAnalyticsRequest(config), machineLearningClient::putDataFrameAnalytics, machineLearningClient::putDataFrameAnalyticsAsync); DataFrameAnalyticsConfig createdConfig = putDataFrameAnalyticsResponse.getConfig(); assertThat(createdConfig.getId(), equalTo(config.getId())); assertThat(createdConfig.getSource().getIndex(), equalTo(config.getSource().getIndex())); assertThat(createdConfig.getSource().getQueryConfig(), equalTo(new QueryConfig(new MatchAllQueryBuilder()))); // default value assertThat(createdConfig.getDest().getIndex(), equalTo(config.getDest().getIndex())); assertThat(createdConfig.getDest().getResultsField(), equalTo("ml")); // default value assertThat(createdConfig.getAnalysis(), equalTo(config.getAnalysis())); assertThat(createdConfig.getAnalyzedFields(), equalTo(config.getAnalyzedFields())); assertThat(createdConfig.getModelMemoryLimit(), equalTo(ByteSizeValue.parseBytesSizeValue("1gb", ""))); // default value assertThat(createdConfig.getDescription(), equalTo("this is a classification")); } public void testUpdateDataFrameAnalytics() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String configId = "test-update-df-analytics-classification"; DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setId(configId) .setSource(DataFrameAnalyticsSource.builder().setIndex("update-test-source-index").build()) .setDest(DataFrameAnalyticsDest.builder().setIndex("update-test-dest-index").build()) .setAnalysis(org.elasticsearch.client.ml.dataframe.Classification.builder("my_dependent_variable").build()) .setDescription("this is a classification") .build(); createIndex("update-test-source-index", defaultMappingForTest()); machineLearningClient.putDataFrameAnalytics(new PutDataFrameAnalyticsRequest(config), RequestOptions.DEFAULT); UpdateDataFrameAnalyticsRequest request = new UpdateDataFrameAnalyticsRequest( DataFrameAnalyticsConfigUpdate.builder().setId(config.getId()).setDescription("Updated description").build()); PutDataFrameAnalyticsResponse response = execute(request, machineLearningClient::updateDataFrameAnalytics, machineLearningClient::updateDataFrameAnalyticsAsync); assertThat(response.getConfig().getDescription(), equalTo("Updated description")); GetDataFrameAnalyticsRequest getRequest = new GetDataFrameAnalyticsRequest(config.getId()); GetDataFrameAnalyticsResponse getResponse = machineLearningClient.getDataFrameAnalytics(getRequest, RequestOptions.DEFAULT); assertThat(getResponse.getAnalytics().get(0).getDescription(), equalTo("Updated description")); } public void testGetDataFrameAnalyticsConfig_SingleConfig() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String configId = "get-test-config"; DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setId(configId) .setSource(DataFrameAnalyticsSource.builder() .setIndex("get-test-source-index") .build()) .setDest(DataFrameAnalyticsDest.builder() .setIndex("get-test-dest-index") .build()) .setAnalysis(OutlierDetection.createDefault()) .build(); createIndex("get-test-source-index", defaultMappingForTest()); PutDataFrameAnalyticsResponse putDataFrameAnalyticsResponse = execute( new PutDataFrameAnalyticsRequest(config), machineLearningClient::putDataFrameAnalytics, machineLearningClient::putDataFrameAnalyticsAsync); DataFrameAnalyticsConfig createdConfig = putDataFrameAnalyticsResponse.getConfig(); GetDataFrameAnalyticsResponse getDataFrameAnalyticsResponse = execute( new GetDataFrameAnalyticsRequest(configId), machineLearningClient::getDataFrameAnalytics, machineLearningClient::getDataFrameAnalyticsAsync); assertThat(getDataFrameAnalyticsResponse.getAnalytics(), hasSize(1)); assertThat(getDataFrameAnalyticsResponse.getAnalytics(), contains(createdConfig)); } public void testGetDataFrameAnalyticsConfig_MultipleConfigs() throws Exception { createIndex("get-test-source-index", defaultMappingForTest()); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String configIdPrefix = "get-test-config-"; int numberOfConfigs = 10; List<DataFrameAnalyticsConfig> createdConfigs = new ArrayList<>(); for (int i = 0; i < numberOfConfigs; ++i) { String configId = configIdPrefix + i; DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setId(configId) .setSource(DataFrameAnalyticsSource.builder() .setIndex("get-test-source-index") .build()) .setDest(DataFrameAnalyticsDest.builder() .setIndex("get-test-dest-index") .build()) .setAnalysis(OutlierDetection.createDefault()) .build(); PutDataFrameAnalyticsResponse putDataFrameAnalyticsResponse = execute( new PutDataFrameAnalyticsRequest(config), machineLearningClient::putDataFrameAnalytics, machineLearningClient::putDataFrameAnalyticsAsync); DataFrameAnalyticsConfig createdConfig = putDataFrameAnalyticsResponse.getConfig(); createdConfigs.add(createdConfig); } { GetDataFrameAnalyticsResponse getDataFrameAnalyticsResponse = execute( GetDataFrameAnalyticsRequest.getAllDataFrameAnalyticsRequest(), machineLearningClient::getDataFrameAnalytics, machineLearningClient::getDataFrameAnalyticsAsync); assertThat(getDataFrameAnalyticsResponse.getAnalytics(), hasSize(numberOfConfigs)); assertThat(getDataFrameAnalyticsResponse.getAnalytics(), containsInAnyOrder(createdConfigs.toArray())); } { GetDataFrameAnalyticsResponse getDataFrameAnalyticsResponse = execute( new GetDataFrameAnalyticsRequest(configIdPrefix + "*"), machineLearningClient::getDataFrameAnalytics, machineLearningClient::getDataFrameAnalyticsAsync); assertThat(getDataFrameAnalyticsResponse.getAnalytics(), hasSize(numberOfConfigs)); assertThat(getDataFrameAnalyticsResponse.getAnalytics(), containsInAnyOrder(createdConfigs.toArray())); } { GetDataFrameAnalyticsResponse getDataFrameAnalyticsResponse = execute( new GetDataFrameAnalyticsRequest(configIdPrefix + "9", configIdPrefix + "1", configIdPrefix + "4"), machineLearningClient::getDataFrameAnalytics, machineLearningClient::getDataFrameAnalyticsAsync); assertThat(getDataFrameAnalyticsResponse.getAnalytics(), hasSize(3)); assertThat( getDataFrameAnalyticsResponse.getAnalytics(), containsInAnyOrder(createdConfigs.get(1), createdConfigs.get(4), createdConfigs.get(9))); } { GetDataFrameAnalyticsRequest getDataFrameAnalyticsRequest = new GetDataFrameAnalyticsRequest(configIdPrefix + "*"); getDataFrameAnalyticsRequest.setPageParams(new PageParams(3, 4)); GetDataFrameAnalyticsResponse getDataFrameAnalyticsResponse = execute( getDataFrameAnalyticsRequest, machineLearningClient::getDataFrameAnalytics, machineLearningClient::getDataFrameAnalyticsAsync); assertThat(getDataFrameAnalyticsResponse.getAnalytics(), hasSize(4)); assertThat( getDataFrameAnalyticsResponse.getAnalytics(), containsInAnyOrder(createdConfigs.get(3), createdConfigs.get(4), createdConfigs.get(5), createdConfigs.get(6))); } } public void testGetDataFrameAnalyticsConfig_ConfigNotFound() { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); GetDataFrameAnalyticsRequest request = new GetDataFrameAnalyticsRequest("config_that_does_not_exist"); ElasticsearchStatusException exception = expectThrows(ElasticsearchStatusException.class, () -> execute(request, machineLearningClient::getDataFrameAnalytics, machineLearningClient::getDataFrameAnalyticsAsync)); assertThat(exception.status().getStatus(), equalTo(404)); } public void testGetDataFrameAnalyticsStats() throws Exception { String sourceIndex = "get-stats-test-source-index"; String destIndex = "get-stats-test-dest-index"; createIndex(sourceIndex, defaultMappingForTest()); highLevelClient().index(new IndexRequest(sourceIndex).source(XContentType.JSON, "total", 10000), RequestOptions.DEFAULT); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String configId = "get-stats-test-config"; DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setId(configId) .setSource(DataFrameAnalyticsSource.builder() .setIndex(sourceIndex) .build()) .setDest(DataFrameAnalyticsDest.builder() .setIndex(destIndex) .build()) .setAnalysis(OutlierDetection.createDefault()) .build(); execute( new PutDataFrameAnalyticsRequest(config), machineLearningClient::putDataFrameAnalytics, machineLearningClient::putDataFrameAnalyticsAsync); GetDataFrameAnalyticsStatsResponse statsResponse = execute( new GetDataFrameAnalyticsStatsRequest(configId), machineLearningClient::getDataFrameAnalyticsStats, machineLearningClient::getDataFrameAnalyticsStatsAsync); assertThat(statsResponse.getAnalyticsStats(), hasSize(1)); DataFrameAnalyticsStats stats = statsResponse.getAnalyticsStats().get(0); assertThat(stats.getId(), equalTo(configId)); assertThat(stats.getState(), equalTo(DataFrameAnalyticsState.STOPPED)); assertNull(stats.getFailureReason()); assertNull(stats.getNode()); assertNull(stats.getAssignmentExplanation()); assertThat(statsResponse.getNodeFailures(), hasSize(0)); assertThat(statsResponse.getTaskFailures(), hasSize(0)); List<PhaseProgress> progress = stats.getProgress(); assertThat(progress, is(notNullValue())); assertThat(progress.size(), equalTo(4)); assertThat(progress.get(0), equalTo(new PhaseProgress("reindexing", 0))); assertThat(progress.get(1), equalTo(new PhaseProgress("loading_data", 0))); assertThat(progress.get(2), equalTo(new PhaseProgress("computing_outliers", 0))); assertThat(progress.get(3), equalTo(new PhaseProgress("writing_results", 0))); assertThat(stats.getMemoryUsage().getPeakUsageBytes(), equalTo(0L)); assertThat(stats.getMemoryUsage().getStatus(), equalTo(MemoryUsage.Status.OK)); assertThat(stats.getMemoryUsage().getMemoryReestimateBytes(), is(nullValue())); assertThat(stats.getDataCounts(), equalTo(new DataCounts(0, 0, 0))); } public void testStartDataFrameAnalyticsConfig() throws Exception { String sourceIndex = "start-test-source-index"; String destIndex = "start-test-dest-index"; createIndex(sourceIndex, defaultMappingForTest()); highLevelClient().index(new IndexRequest(sourceIndex).source(XContentType.JSON, "total", 10000) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT); // Verify that the destination index does not exist. Otherwise, analytics' reindexing step would fail. assertFalse(highLevelClient().indices().exists(new GetIndexRequest(destIndex), RequestOptions.DEFAULT)); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String configId = "start-test-config"; DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setId(configId) .setSource(DataFrameAnalyticsSource.builder() .setIndex(sourceIndex) .build()) .setDest(DataFrameAnalyticsDest.builder() .setIndex(destIndex) .build()) .setAnalysis(OutlierDetection.createDefault()) .build(); execute( new PutDataFrameAnalyticsRequest(config), machineLearningClient::putDataFrameAnalytics, machineLearningClient::putDataFrameAnalyticsAsync); assertThat(getAnalyticsState(configId), equalTo(DataFrameAnalyticsState.STOPPED)); AcknowledgedResponse startDataFrameAnalyticsResponse = execute( new StartDataFrameAnalyticsRequest(configId), machineLearningClient::startDataFrameAnalytics, machineLearningClient::startDataFrameAnalyticsAsync); assertTrue(startDataFrameAnalyticsResponse.isAcknowledged()); // Wait for the analytics to stop. assertBusy(() -> assertThat(getAnalyticsState(configId), equalTo(DataFrameAnalyticsState.STOPPED)), 30, TimeUnit.SECONDS); // Verify that the destination index got created. assertTrue(highLevelClient().indices().exists(new GetIndexRequest(destIndex), RequestOptions.DEFAULT)); } @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/43924") public void testStopDataFrameAnalyticsConfig() throws Exception { String sourceIndex = "stop-test-source-index"; String destIndex = "stop-test-dest-index"; createIndex(sourceIndex, defaultMappingForTest()); highLevelClient().index(new IndexRequest(sourceIndex).source(XContentType.JSON, "total", 10000) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT); // Verify that the destination index does not exist. Otherwise, analytics' reindexing step would fail. assertFalse(highLevelClient().indices().exists(new GetIndexRequest(destIndex), RequestOptions.DEFAULT)); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String configId = "stop-test-config"; DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setId(configId) .setSource(DataFrameAnalyticsSource.builder() .setIndex(sourceIndex) .build()) .setDest(DataFrameAnalyticsDest.builder() .setIndex(destIndex) .build()) .setAnalysis(OutlierDetection.createDefault()) .build(); execute( new PutDataFrameAnalyticsRequest(config), machineLearningClient::putDataFrameAnalytics, machineLearningClient::putDataFrameAnalyticsAsync); assertThat(getAnalyticsState(configId), equalTo(DataFrameAnalyticsState.STOPPED)); AcknowledgedResponse startDataFrameAnalyticsResponse = execute( new StartDataFrameAnalyticsRequest(configId), machineLearningClient::startDataFrameAnalytics, machineLearningClient::startDataFrameAnalyticsAsync); assertTrue(startDataFrameAnalyticsResponse.isAcknowledged()); assertThat(getAnalyticsState(configId), anyOf(equalTo(DataFrameAnalyticsState.STARTED), equalTo(DataFrameAnalyticsState.REINDEXING), equalTo(DataFrameAnalyticsState.ANALYZING))); StopDataFrameAnalyticsResponse stopDataFrameAnalyticsResponse = execute( new StopDataFrameAnalyticsRequest(configId), machineLearningClient::stopDataFrameAnalytics, machineLearningClient::stopDataFrameAnalyticsAsync); assertTrue(stopDataFrameAnalyticsResponse.isStopped()); assertThat(getAnalyticsState(configId), equalTo(DataFrameAnalyticsState.STOPPED)); } private DataFrameAnalyticsState getAnalyticsState(String configId) throws IOException { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); GetDataFrameAnalyticsStatsResponse statsResponse = machineLearningClient.getDataFrameAnalyticsStats(new GetDataFrameAnalyticsStatsRequest(configId), RequestOptions.DEFAULT); assertThat(statsResponse.getAnalyticsStats(), hasSize(1)); DataFrameAnalyticsStats stats = statsResponse.getAnalyticsStats().get(0); return stats.getState(); } public void testDeleteDataFrameAnalyticsConfig() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String configId = "delete-test-config"; DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setId(configId) .setSource(DataFrameAnalyticsSource.builder() .setIndex("delete-test-source-index") .build()) .setDest(DataFrameAnalyticsDest.builder() .setIndex("delete-test-dest-index") .build()) .setAnalysis(OutlierDetection.createDefault()) .build(); createIndex("delete-test-source-index", defaultMappingForTest()); GetDataFrameAnalyticsResponse getDataFrameAnalyticsResponse = execute( new GetDataFrameAnalyticsRequest(configId + "*"), machineLearningClient::getDataFrameAnalytics, machineLearningClient::getDataFrameAnalyticsAsync); assertThat(getDataFrameAnalyticsResponse.getAnalytics(), hasSize(0)); execute( new PutDataFrameAnalyticsRequest(config), machineLearningClient::putDataFrameAnalytics, machineLearningClient::putDataFrameAnalyticsAsync); getDataFrameAnalyticsResponse = execute( new GetDataFrameAnalyticsRequest(configId + "*"), machineLearningClient::getDataFrameAnalytics, machineLearningClient::getDataFrameAnalyticsAsync); assertThat(getDataFrameAnalyticsResponse.getAnalytics(), hasSize(1)); DeleteDataFrameAnalyticsRequest deleteRequest = new DeleteDataFrameAnalyticsRequest(configId); if (randomBoolean()) { deleteRequest.setForce(randomBoolean()); } AcknowledgedResponse deleteDataFrameAnalyticsResponse = execute(deleteRequest, machineLearningClient::deleteDataFrameAnalytics, machineLearningClient::deleteDataFrameAnalyticsAsync); assertTrue(deleteDataFrameAnalyticsResponse.isAcknowledged()); getDataFrameAnalyticsResponse = execute( new GetDataFrameAnalyticsRequest(configId + "*"), machineLearningClient::getDataFrameAnalytics, machineLearningClient::getDataFrameAnalyticsAsync); assertThat(getDataFrameAnalyticsResponse.getAnalytics(), hasSize(0)); } public void testDeleteDataFrameAnalyticsConfig_ConfigNotFound() { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); DeleteDataFrameAnalyticsRequest request = new DeleteDataFrameAnalyticsRequest("config_that_does_not_exist"); ElasticsearchStatusException exception = expectThrows(ElasticsearchStatusException.class, () -> execute( request, machineLearningClient::deleteDataFrameAnalytics, machineLearningClient::deleteDataFrameAnalyticsAsync)); assertThat(exception.status().getStatus(), equalTo(404)); } public void testEvaluateDataFrame_BinarySoftClassification() throws IOException { String indexName = "evaluate-test-index"; createIndex(indexName, mappingForSoftClassification()); BulkRequest bulk = new BulkRequest() .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) .add(docForSoftClassification(indexName, "blue", false, 0.1)) // #0 .add(docForSoftClassification(indexName, "blue", false, 0.2)) // #1 .add(docForSoftClassification(indexName, "blue", false, 0.3)) // #2 .add(docForSoftClassification(indexName, "blue", false, 0.4)) // #3 .add(docForSoftClassification(indexName, "blue", false, 0.7)) // #4 .add(docForSoftClassification(indexName, "blue", true, 0.2)) // #5 .add(docForSoftClassification(indexName, "green", true, 0.3)) // #6 .add(docForSoftClassification(indexName, "green", true, 0.4)) // #7 .add(docForSoftClassification(indexName, "green", true, 0.8)) // #8 .add(docForSoftClassification(indexName, "green", true, 0.9)); // #9 highLevelClient().bulk(bulk, RequestOptions.DEFAULT); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); EvaluateDataFrameRequest evaluateDataFrameRequest = new EvaluateDataFrameRequest( indexName, null, new BinarySoftClassification( actualField, probabilityField, PrecisionMetric.at(0.4, 0.5, 0.6), RecallMetric.at(0.5, 0.7), ConfusionMatrixMetric.at(0.5), AucRocMetric.withCurve())); EvaluateDataFrameResponse evaluateDataFrameResponse = execute(evaluateDataFrameRequest, machineLearningClient::evaluateDataFrame, machineLearningClient::evaluateDataFrameAsync); assertThat(evaluateDataFrameResponse.getEvaluationName(), equalTo(BinarySoftClassification.NAME)); assertThat(evaluateDataFrameResponse.getMetrics().size(), equalTo(4)); PrecisionMetric.Result precisionResult = evaluateDataFrameResponse.getMetricByName(PrecisionMetric.NAME); assertThat(precisionResult.getMetricName(), equalTo(PrecisionMetric.NAME)); // Precision is 3/5=0.6 as there were 3 true examples (#7, #8, #9) among the 5 positive examples (#3, #4, #7, #8, #9) assertThat(precisionResult.getScoreByThreshold("0.4"), closeTo(0.6, 1e-9)); // Precision is 2/3=0.(6) as there were 2 true examples (#8, #9) among the 3 positive examples (#4, #8, #9) assertThat(precisionResult.getScoreByThreshold("0.5"), closeTo(0.666666666, 1e-9)); // Precision is 2/3=0.(6) as there were 2 true examples (#8, #9) among the 3 positive examples (#4, #8, #9) assertThat(precisionResult.getScoreByThreshold("0.6"), closeTo(0.666666666, 1e-9)); assertNull(precisionResult.getScoreByThreshold("0.1")); RecallMetric.Result recallResult = evaluateDataFrameResponse.getMetricByName(RecallMetric.NAME); assertThat(recallResult.getMetricName(), equalTo(RecallMetric.NAME)); // Recall is 2/5=0.4 as there were 2 true positive examples (#8, #9) among the 5 true examples (#5, #6, #7, #8, #9) assertThat(recallResult.getScoreByThreshold("0.5"), closeTo(0.4, 1e-9)); // Recall is 2/5=0.4 as there were 2 true positive examples (#8, #9) among the 5 true examples (#5, #6, #7, #8, #9) assertThat(recallResult.getScoreByThreshold("0.7"), closeTo(0.4, 1e-9)); assertNull(recallResult.getScoreByThreshold("0.1")); ConfusionMatrixMetric.Result confusionMatrixResult = evaluateDataFrameResponse.getMetricByName(ConfusionMatrixMetric.NAME); assertThat(confusionMatrixResult.getMetricName(), equalTo(ConfusionMatrixMetric.NAME)); ConfusionMatrixMetric.ConfusionMatrix confusionMatrix = confusionMatrixResult.getScoreByThreshold("0.5"); assertThat(confusionMatrix.getTruePositives(), equalTo(2L)); // docs #8 and #9 assertThat(confusionMatrix.getFalsePositives(), equalTo(1L)); // doc #4 assertThat(confusionMatrix.getTrueNegatives(), equalTo(4L)); // docs #0, #1, #2 and #3 assertThat(confusionMatrix.getFalseNegatives(), equalTo(3L)); // docs #5, #6 and #7 assertNull(confusionMatrixResult.getScoreByThreshold("0.1")); AucRocMetric.Result aucRocResult = evaluateDataFrameResponse.getMetricByName(AucRocMetric.NAME); assertThat(aucRocResult.getMetricName(), equalTo(AucRocMetric.NAME)); assertThat(aucRocResult.getScore(), closeTo(0.70025, 1e-9)); assertNotNull(aucRocResult.getCurve()); List<AucRocMetric.AucRocPoint> curve = aucRocResult.getCurve(); AucRocMetric.AucRocPoint curvePointAtThreshold0 = curve.stream().filter(p -> p.getThreshold() == 0.0).findFirst().get(); assertThat(curvePointAtThreshold0.getTruePositiveRate(), equalTo(1.0)); assertThat(curvePointAtThreshold0.getFalsePositiveRate(), equalTo(1.0)); assertThat(curvePointAtThreshold0.getThreshold(), equalTo(0.0)); AucRocMetric.AucRocPoint curvePointAtThreshold1 = curve.stream().filter(p -> p.getThreshold() == 1.0).findFirst().get(); assertThat(curvePointAtThreshold1.getTruePositiveRate(), equalTo(0.0)); assertThat(curvePointAtThreshold1.getFalsePositiveRate(), equalTo(0.0)); assertThat(curvePointAtThreshold1.getThreshold(), equalTo(1.0)); } public void testEvaluateDataFrame_BinarySoftClassification_WithQuery() throws IOException { String indexName = "evaluate-with-query-test-index"; createIndex(indexName, mappingForSoftClassification()); BulkRequest bulk = new BulkRequest() .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) .add(docForSoftClassification(indexName, "blue", true, 1.0)) // #0 .add(docForSoftClassification(indexName, "blue", true, 1.0)) // #1 .add(docForSoftClassification(indexName, "blue", true, 1.0)) // #2 .add(docForSoftClassification(indexName, "blue", true, 1.0)) // #3 .add(docForSoftClassification(indexName, "blue", true, 0.0)) // #4 .add(docForSoftClassification(indexName, "blue", true, 0.0)) // #5 .add(docForSoftClassification(indexName, "green", true, 0.0)) // #6 .add(docForSoftClassification(indexName, "green", true, 0.0)) // #7 .add(docForSoftClassification(indexName, "green", true, 0.0)) // #8 .add(docForSoftClassification(indexName, "green", true, 1.0)); // #9 highLevelClient().bulk(bulk, RequestOptions.DEFAULT); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); EvaluateDataFrameRequest evaluateDataFrameRequest = new EvaluateDataFrameRequest( indexName, // Request only "blue" subset to be evaluated new QueryConfig(QueryBuilders.termQuery(datasetField, "blue")), new BinarySoftClassification(actualField, probabilityField, ConfusionMatrixMetric.at(0.5))); EvaluateDataFrameResponse evaluateDataFrameResponse = execute(evaluateDataFrameRequest, machineLearningClient::evaluateDataFrame, machineLearningClient::evaluateDataFrameAsync); assertThat(evaluateDataFrameResponse.getEvaluationName(), equalTo(BinarySoftClassification.NAME)); assertThat(evaluateDataFrameResponse.getMetrics().size(), equalTo(1)); ConfusionMatrixMetric.Result confusionMatrixResult = evaluateDataFrameResponse.getMetricByName(ConfusionMatrixMetric.NAME); assertThat(confusionMatrixResult.getMetricName(), equalTo(ConfusionMatrixMetric.NAME)); ConfusionMatrixMetric.ConfusionMatrix confusionMatrix = confusionMatrixResult.getScoreByThreshold("0.5"); assertThat(confusionMatrix.getTruePositives(), equalTo(4L)); // docs #0, #1, #2 and #3 assertThat(confusionMatrix.getFalsePositives(), equalTo(0L)); assertThat(confusionMatrix.getTrueNegatives(), equalTo(0L)); assertThat(confusionMatrix.getFalseNegatives(), equalTo(2L)); // docs #4 and #5 } public void testEvaluateDataFrame_Regression() throws IOException { String regressionIndex = "evaluate-regression-test-index"; createIndex(regressionIndex, mappingForRegression()); BulkRequest regressionBulk = new BulkRequest() .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) .add(docForRegression(regressionIndex, 0.3, 0.1)) // #0 .add(docForRegression(regressionIndex, 0.3, 0.2)) // #1 .add(docForRegression(regressionIndex, 0.3, 0.3)) // #2 .add(docForRegression(regressionIndex, 0.3, 0.4)) // #3 .add(docForRegression(regressionIndex, 0.3, 0.7)) // #4 .add(docForRegression(regressionIndex, 0.5, 0.2)) // #5 .add(docForRegression(regressionIndex, 0.5, 0.3)) // #6 .add(docForRegression(regressionIndex, 0.5, 0.4)) // #7 .add(docForRegression(regressionIndex, 0.5, 0.8)) // #8 .add(docForRegression(regressionIndex, 0.5, 0.9)); // #9 highLevelClient().bulk(regressionBulk, RequestOptions.DEFAULT); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); EvaluateDataFrameRequest evaluateDataFrameRequest = new EvaluateDataFrameRequest( regressionIndex, null, new Regression( actualRegression, predictedRegression, new MeanSquaredErrorMetric(), new MeanSquaredLogarithmicErrorMetric(1.0), new HuberMetric(1.0), new RSquaredMetric())); EvaluateDataFrameResponse evaluateDataFrameResponse = execute(evaluateDataFrameRequest, machineLearningClient::evaluateDataFrame, machineLearningClient::evaluateDataFrameAsync); assertThat(evaluateDataFrameResponse.getEvaluationName(), equalTo(Regression.NAME)); assertThat(evaluateDataFrameResponse.getMetrics().size(), equalTo(4)); MeanSquaredErrorMetric.Result mseResult = evaluateDataFrameResponse.getMetricByName(MeanSquaredErrorMetric.NAME); assertThat(mseResult.getMetricName(), equalTo(MeanSquaredErrorMetric.NAME)); assertThat(mseResult.getValue(), closeTo(0.061000000, 1e-9)); MeanSquaredLogarithmicErrorMetric.Result msleResult = evaluateDataFrameResponse.getMetricByName(MeanSquaredLogarithmicErrorMetric.NAME); assertThat(msleResult.getMetricName(), equalTo(MeanSquaredLogarithmicErrorMetric.NAME)); assertThat(msleResult.getValue(), closeTo(0.02759231770210426, 1e-9)); HuberMetric.Result huberResult = evaluateDataFrameResponse.getMetricByName(HuberMetric.NAME); assertThat(huberResult.getMetricName(), equalTo(HuberMetric.NAME)); assertThat(huberResult.getValue(), closeTo(0.029669771640929276, 1e-9)); RSquaredMetric.Result rSquaredResult = evaluateDataFrameResponse.getMetricByName(RSquaredMetric.NAME); assertThat(rSquaredResult.getMetricName(), equalTo(RSquaredMetric.NAME)); assertThat(rSquaredResult.getValue(), closeTo(-5.1000000000000005, 1e-9)); } public void testEvaluateDataFrame_Classification() throws IOException { String indexName = "evaluate-classification-test-index"; createIndex(indexName, mappingForClassification()); BulkRequest regressionBulk = new BulkRequest() .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) .add(docForClassification(indexName, "cat", "cat")) .add(docForClassification(indexName, "cat", "cat")) .add(docForClassification(indexName, "cat", "cat")) .add(docForClassification(indexName, "cat", "dog")) .add(docForClassification(indexName, "cat", "fish")) .add(docForClassification(indexName, "dog", "cat")) .add(docForClassification(indexName, "dog", "dog")) .add(docForClassification(indexName, "dog", "dog")) .add(docForClassification(indexName, "dog", "dog")) .add(docForClassification(indexName, "ant", "cat")); highLevelClient().bulk(regressionBulk, RequestOptions.DEFAULT); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); { // Accuracy EvaluateDataFrameRequest evaluateDataFrameRequest = new EvaluateDataFrameRequest( indexName, null, new Classification(actualClassField, predictedClassField, new AccuracyMetric())); EvaluateDataFrameResponse evaluateDataFrameResponse = execute(evaluateDataFrameRequest, machineLearningClient::evaluateDataFrame, machineLearningClient::evaluateDataFrameAsync); assertThat(evaluateDataFrameResponse.getEvaluationName(), equalTo(Classification.NAME)); assertThat(evaluateDataFrameResponse.getMetrics().size(), equalTo(1)); AccuracyMetric.Result accuracyResult = evaluateDataFrameResponse.getMetricByName(AccuracyMetric.NAME); assertThat(accuracyResult.getMetricName(), equalTo(AccuracyMetric.NAME)); assertThat( accuracyResult.getClasses(), equalTo( List.of( // 9 out of 10 examples were classified correctly new AccuracyMetric.PerClassResult("ant", 0.9), // 6 out of 10 examples were classified correctly new AccuracyMetric.PerClassResult("cat", 0.6), // 8 out of 10 examples were classified correctly new AccuracyMetric.PerClassResult("dog", 0.8)))); assertThat(accuracyResult.getOverallAccuracy(), equalTo(0.6)); // 6 out of 10 examples were classified correctly } { // Precision EvaluateDataFrameRequest evaluateDataFrameRequest = new EvaluateDataFrameRequest( indexName, null, new Classification( actualClassField, predictedClassField, new org.elasticsearch.client.ml.dataframe.evaluation.classification.PrecisionMetric())); EvaluateDataFrameResponse evaluateDataFrameResponse = execute(evaluateDataFrameRequest, machineLearningClient::evaluateDataFrame, machineLearningClient::evaluateDataFrameAsync); assertThat(evaluateDataFrameResponse.getEvaluationName(), equalTo(Classification.NAME)); assertThat(evaluateDataFrameResponse.getMetrics().size(), equalTo(1)); org.elasticsearch.client.ml.dataframe.evaluation.classification.PrecisionMetric.Result precisionResult = evaluateDataFrameResponse.getMetricByName( org.elasticsearch.client.ml.dataframe.evaluation.classification.PrecisionMetric.NAME); assertThat( precisionResult.getMetricName(), equalTo(org.elasticsearch.client.ml.dataframe.evaluation.classification.PrecisionMetric.NAME)); assertThat( precisionResult.getClasses(), equalTo( List.of( // 3 out of 5 examples labeled as "cat" were classified correctly new org.elasticsearch.client.ml.dataframe.evaluation.classification.PrecisionMetric.PerClassResult("cat", 0.6), // 3 out of 4 examples labeled as "dog" were classified correctly new org.elasticsearch.client.ml.dataframe.evaluation.classification.PrecisionMetric.PerClassResult("dog", 0.75)))); assertThat(precisionResult.getAvgPrecision(), equalTo(0.675)); } { // Recall EvaluateDataFrameRequest evaluateDataFrameRequest = new EvaluateDataFrameRequest( indexName, null, new Classification( actualClassField, predictedClassField, new org.elasticsearch.client.ml.dataframe.evaluation.classification.RecallMetric())); EvaluateDataFrameResponse evaluateDataFrameResponse = execute(evaluateDataFrameRequest, machineLearningClient::evaluateDataFrame, machineLearningClient::evaluateDataFrameAsync); assertThat(evaluateDataFrameResponse.getEvaluationName(), equalTo(Classification.NAME)); assertThat(evaluateDataFrameResponse.getMetrics().size(), equalTo(1)); org.elasticsearch.client.ml.dataframe.evaluation.classification.RecallMetric.Result recallResult = evaluateDataFrameResponse.getMetricByName( org.elasticsearch.client.ml.dataframe.evaluation.classification.RecallMetric.NAME); assertThat( recallResult.getMetricName(), equalTo(org.elasticsearch.client.ml.dataframe.evaluation.classification.RecallMetric.NAME)); assertThat( recallResult.getClasses(), equalTo( List.of( // 3 out of 5 examples labeled as "cat" were classified correctly new org.elasticsearch.client.ml.dataframe.evaluation.classification.RecallMetric.PerClassResult("cat", 0.6), // 3 out of 4 examples labeled as "dog" were classified correctly new org.elasticsearch.client.ml.dataframe.evaluation.classification.RecallMetric.PerClassResult("dog", 0.75), // no examples labeled as "ant" were classified correctly new org.elasticsearch.client.ml.dataframe.evaluation.classification.RecallMetric.PerClassResult("ant", 0.0)))); assertThat(recallResult.getAvgRecall(), equalTo(0.45)); } { // No size provided for MulticlassConfusionMatrixMetric, default used instead EvaluateDataFrameRequest evaluateDataFrameRequest = new EvaluateDataFrameRequest( indexName, null, new Classification(actualClassField, predictedClassField, new MulticlassConfusionMatrixMetric())); EvaluateDataFrameResponse evaluateDataFrameResponse = execute(evaluateDataFrameRequest, machineLearningClient::evaluateDataFrame, machineLearningClient::evaluateDataFrameAsync); assertThat(evaluateDataFrameResponse.getEvaluationName(), equalTo(Classification.NAME)); assertThat(evaluateDataFrameResponse.getMetrics().size(), equalTo(1)); MulticlassConfusionMatrixMetric.Result mcmResult = evaluateDataFrameResponse.getMetricByName(MulticlassConfusionMatrixMetric.NAME); assertThat(mcmResult.getMetricName(), equalTo(MulticlassConfusionMatrixMetric.NAME)); assertThat( mcmResult.getConfusionMatrix(), equalTo( List.of( new MulticlassConfusionMatrixMetric.ActualClass( "ant", 1L, List.of( new MulticlassConfusionMatrixMetric.PredictedClass("ant", 0L), new MulticlassConfusionMatrixMetric.PredictedClass("cat", 1L), new MulticlassConfusionMatrixMetric.PredictedClass("dog", 0L)), 0L), new MulticlassConfusionMatrixMetric.ActualClass( "cat", 5L, List.of( new MulticlassConfusionMatrixMetric.PredictedClass("ant", 0L), new MulticlassConfusionMatrixMetric.PredictedClass("cat", 3L), new MulticlassConfusionMatrixMetric.PredictedClass("dog", 1L)), 1L), new MulticlassConfusionMatrixMetric.ActualClass( "dog", 4L, List.of( new MulticlassConfusionMatrixMetric.PredictedClass("ant", 0L), new MulticlassConfusionMatrixMetric.PredictedClass("cat", 1L), new MulticlassConfusionMatrixMetric.PredictedClass("dog", 3L)), 0L)))); assertThat(mcmResult.getOtherActualClassCount(), equalTo(0L)); } { // Explicit size provided for MulticlassConfusionMatrixMetric metric EvaluateDataFrameRequest evaluateDataFrameRequest = new EvaluateDataFrameRequest( indexName, null, new Classification(actualClassField, predictedClassField, new MulticlassConfusionMatrixMetric(2))); EvaluateDataFrameResponse evaluateDataFrameResponse = execute(evaluateDataFrameRequest, machineLearningClient::evaluateDataFrame, machineLearningClient::evaluateDataFrameAsync); assertThat(evaluateDataFrameResponse.getEvaluationName(), equalTo(Classification.NAME)); assertThat(evaluateDataFrameResponse.getMetrics().size(), equalTo(1)); MulticlassConfusionMatrixMetric.Result mcmResult = evaluateDataFrameResponse.getMetricByName(MulticlassConfusionMatrixMetric.NAME); assertThat(mcmResult.getMetricName(), equalTo(MulticlassConfusionMatrixMetric.NAME)); assertThat( mcmResult.getConfusionMatrix(), equalTo( List.of( new MulticlassConfusionMatrixMetric.ActualClass( "cat", 5L, List.of( new MulticlassConfusionMatrixMetric.PredictedClass("cat", 3L), new MulticlassConfusionMatrixMetric.PredictedClass("dog", 1L)), 1L), new MulticlassConfusionMatrixMetric.ActualClass( "dog", 4L, List.of( new MulticlassConfusionMatrixMetric.PredictedClass("cat", 1L), new MulticlassConfusionMatrixMetric.PredictedClass("dog", 3L)), 0L) ))); assertThat(mcmResult.getOtherActualClassCount(), equalTo(1L)); } } private static XContentBuilder defaultMappingForTest() throws IOException { return XContentFactory.jsonBuilder().startObject() .startObject("properties") .startObject("timestamp") .field("type", "date") .endObject() .startObject("total") .field("type", "long") .endObject() .endObject() .endObject(); } private static final String datasetField = "dataset"; private static final String actualField = "label"; private static final String probabilityField = "p"; private static XContentBuilder mappingForSoftClassification() throws IOException { return XContentFactory.jsonBuilder().startObject() .startObject("properties") .startObject(datasetField) .field("type", "keyword") .endObject() .startObject(actualField) .field("type", "keyword") .endObject() .startObject(probabilityField) .field("type", "double") .endObject() .endObject() .endObject(); } private static IndexRequest docForSoftClassification(String indexName, String dataset, boolean isTrue, double p) { return new IndexRequest() .index(indexName) .source(XContentType.JSON, datasetField, dataset, actualField, Boolean.toString(isTrue), probabilityField, p); } private static final String actualClassField = "actual_class"; private static final String predictedClassField = "predicted_class"; private static XContentBuilder mappingForClassification() throws IOException { return XContentFactory.jsonBuilder().startObject() .startObject("properties") .startObject(actualClassField) .field("type", "keyword") .endObject() .startObject(predictedClassField) .field("type", "keyword") .endObject() .endObject() .endObject(); } private static IndexRequest docForClassification(String indexName, String actualClass, String predictedClass) { return new IndexRequest() .index(indexName) .source(XContentType.JSON, actualClassField, actualClass, predictedClassField, predictedClass); } private static final String actualRegression = "regression_actual"; private static final String predictedRegression = "regression_predicted"; private static XContentBuilder mappingForRegression() throws IOException { return XContentFactory.jsonBuilder().startObject() .startObject("properties") .startObject(actualRegression) .field("type", "double") .endObject() .startObject(predictedRegression) .field("type", "double") .endObject() .endObject() .endObject(); } private static IndexRequest docForRegression(String indexName, double actualValue, double predictedValue) { return new IndexRequest() .index(indexName) .source(XContentType.JSON, actualRegression, actualValue, predictedRegression, predictedValue); } private void createIndex(String indexName, XContentBuilder mapping) throws IOException { highLevelClient().indices().create(new CreateIndexRequest(indexName).mapping(mapping), RequestOptions.DEFAULT); } public void testExplainDataFrameAnalytics() throws IOException { String indexName = "explain-df-test-index"; createIndex(indexName, mappingForSoftClassification()); BulkRequest bulk1 = new BulkRequest() .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); for (int i = 0; i < 10; ++i) { bulk1.add(docForSoftClassification(indexName, randomAlphaOfLength(10), randomBoolean(), randomDoubleBetween(0.0, 1.0, true))); } highLevelClient().bulk(bulk1, RequestOptions.DEFAULT); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); ExplainDataFrameAnalyticsRequest explainRequest = new ExplainDataFrameAnalyticsRequest( DataFrameAnalyticsConfig.builder() .setSource(DataFrameAnalyticsSource.builder().setIndex(indexName).build()) .setAnalysis(OutlierDetection.createDefault()) .build()); // We are pretty liberal here as this test does not aim at verifying concrete numbers but rather end-to-end user workflow. ByteSizeValue lowerBound = new ByteSizeValue(1, ByteSizeUnit.KB); ByteSizeValue upperBound = new ByteSizeValue(1, ByteSizeUnit.GB); // Data Frame has 10 rows, expect that the returned estimates fall within (1kB, 1GB) range. ExplainDataFrameAnalyticsResponse response1 = execute(explainRequest, machineLearningClient::explainDataFrameAnalytics, machineLearningClient::explainDataFrameAnalyticsAsync); MemoryEstimation memoryEstimation1 = response1.getMemoryEstimation(); assertThat(memoryEstimation1.getExpectedMemoryWithoutDisk(), allOf(greaterThanOrEqualTo(lowerBound), lessThan(upperBound))); assertThat(memoryEstimation1.getExpectedMemoryWithDisk(), allOf(greaterThanOrEqualTo(lowerBound), lessThan(upperBound))); List<FieldSelection> fieldSelection = response1.getFieldSelection(); assertThat(fieldSelection.size(), equalTo(3)); assertThat(fieldSelection.stream().map(FieldSelection::getName).collect(Collectors.toList()), contains("dataset", "label", "p")); BulkRequest bulk2 = new BulkRequest() .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); for (int i = 10; i < 100; ++i) { bulk2.add(docForSoftClassification(indexName, randomAlphaOfLength(10), randomBoolean(), randomDoubleBetween(0.0, 1.0, true))); } highLevelClient().bulk(bulk2, RequestOptions.DEFAULT); // Data Frame now has 100 rows, expect that the returned estimates will be greater than or equal to the previous ones. ExplainDataFrameAnalyticsResponse response2 = execute( explainRequest, machineLearningClient::explainDataFrameAnalytics, machineLearningClient::explainDataFrameAnalyticsAsync); MemoryEstimation memoryEstimation2 = response2.getMemoryEstimation(); assertThat( memoryEstimation2.getExpectedMemoryWithoutDisk(), allOf(greaterThanOrEqualTo(memoryEstimation1.getExpectedMemoryWithoutDisk()), lessThan(upperBound))); assertThat( memoryEstimation2.getExpectedMemoryWithDisk(), allOf(greaterThanOrEqualTo(memoryEstimation1.getExpectedMemoryWithDisk()), lessThan(upperBound))); } public void testGetTrainedModels() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String modelIdPrefix = "get-trained-model-"; int numberOfModels = 5; for (int i = 0; i < numberOfModels; ++i) { String modelId = modelIdPrefix + i; putTrainedModel(modelId); } { GetTrainedModelsResponse getTrainedModelsResponse = execute( new GetTrainedModelsRequest(modelIdPrefix + 0).setDecompressDefinition(true).setIncludeDefinition(true), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync); assertThat(getTrainedModelsResponse.getCount(), equalTo(1L)); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(1)); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getCompressedDefinition(), is(nullValue())); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getDefinition(), is(not(nullValue()))); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getModelId(), equalTo(modelIdPrefix + 0)); getTrainedModelsResponse = execute( new GetTrainedModelsRequest(modelIdPrefix + 0).setDecompressDefinition(false).setIncludeDefinition(true), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync); assertThat(getTrainedModelsResponse.getCount(), equalTo(1L)); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(1)); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getCompressedDefinition(), is(not(nullValue()))); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getDefinition(), is(nullValue())); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getModelId(), equalTo(modelIdPrefix + 0)); getTrainedModelsResponse = execute( new GetTrainedModelsRequest(modelIdPrefix + 0).setDecompressDefinition(false).setIncludeDefinition(false), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync); assertThat(getTrainedModelsResponse.getCount(), equalTo(1L)); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(1)); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getCompressedDefinition(), is(nullValue())); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getDefinition(), is(nullValue())); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getModelId(), equalTo(modelIdPrefix + 0)); } { GetTrainedModelsResponse getTrainedModelsResponse = execute( GetTrainedModelsRequest.getAllTrainedModelConfigsRequest(), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(numberOfModels + 1)); assertThat(getTrainedModelsResponse.getCount(), equalTo(5L + 1)); } { GetTrainedModelsResponse getTrainedModelsResponse = execute( new GetTrainedModelsRequest(modelIdPrefix + 4, modelIdPrefix + 2, modelIdPrefix + 3), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(3)); assertThat(getTrainedModelsResponse.getCount(), equalTo(3L)); } { GetTrainedModelsResponse getTrainedModelsResponse = execute( new GetTrainedModelsRequest(modelIdPrefix + "*").setPageParams(new PageParams(1, 2)), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(2)); assertThat(getTrainedModelsResponse.getCount(), equalTo(5L)); assertThat( getTrainedModelsResponse.getTrainedModels().stream().map(TrainedModelConfig::getModelId).collect(Collectors.toList()), containsInAnyOrder(modelIdPrefix + 1, modelIdPrefix + 2)); } } public void testPutTrainedModel() throws Exception { String modelId = "test-put-trained-model"; String modelIdCompressed = "test-put-trained-model-compressed-definition"; MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); TrainedModelDefinition definition = TrainedModelDefinitionTests.createRandomBuilder(TargetType.REGRESSION).build(); TrainedModelConfig trainedModelConfig = TrainedModelConfig.builder() .setDefinition(definition) .setModelId(modelId) .setInferenceConfig(new RegressionConfig()) .setInput(new TrainedModelInput(Arrays.asList("col1", "col2", "col3", "col4"))) .setDescription("test model") .build(); PutTrainedModelResponse putTrainedModelResponse = execute(new PutTrainedModelRequest(trainedModelConfig), machineLearningClient::putTrainedModel, machineLearningClient::putTrainedModelAsync); TrainedModelConfig createdModel = putTrainedModelResponse.getResponse(); assertThat(createdModel.getModelId(), equalTo(modelId)); definition = TrainedModelDefinitionTests.createRandomBuilder(TargetType.REGRESSION).build(); trainedModelConfig = TrainedModelConfig.builder() .setCompressedDefinition(InferenceToXContentCompressor.deflate(definition)) .setModelId(modelIdCompressed) .setInferenceConfig(new RegressionConfig()) .setInput(new TrainedModelInput(Arrays.asList("col1", "col2", "col3", "col4"))) .setDescription("test model") .build(); putTrainedModelResponse = execute(new PutTrainedModelRequest(trainedModelConfig), machineLearningClient::putTrainedModel, machineLearningClient::putTrainedModelAsync); createdModel = putTrainedModelResponse.getResponse(); assertThat(createdModel.getModelId(), equalTo(modelIdCompressed)); GetTrainedModelsResponse getTrainedModelsResponse = execute( new GetTrainedModelsRequest(modelIdCompressed).setDecompressDefinition(true).setIncludeDefinition(true), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync); assertThat(getTrainedModelsResponse.getCount(), equalTo(1L)); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(1)); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getCompressedDefinition(), is(nullValue())); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getDefinition(), is(not(nullValue()))); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getModelId(), equalTo(modelIdCompressed)); } public void testGetTrainedModelsStats() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String modelIdPrefix = "a-get-trained-model-stats-"; int numberOfModels = 5; for (int i = 0; i < numberOfModels; ++i) { String modelId = modelIdPrefix + i; putTrainedModel(modelId); } String regressionPipeline = "{" + " \"processors\": [\n" + " {\n" + " \"inference\": {\n" + " \"target_field\": \"regression_value\",\n" + " \"model_id\": \"" + modelIdPrefix + 0 + "\",\n" + " \"inference_config\": {\"regression\": {}},\n" + " \"field_map\": {\n" + " \"col1\": \"col1\",\n" + " \"col2\": \"col2\",\n" + " \"col3\": \"col3\",\n" + " \"col4\": \"col4\"\n" + " }\n" + " }\n" + " }]}\n"; highLevelClient().ingest().putPipeline( new PutPipelineRequest("regression-stats-pipeline", new BytesArray(regressionPipeline.getBytes(StandardCharsets.UTF_8)), XContentType.JSON), RequestOptions.DEFAULT); { GetTrainedModelsStatsResponse getTrainedModelsStatsResponse = execute( GetTrainedModelsStatsRequest.getAllTrainedModelStatsRequest(), machineLearningClient::getTrainedModelsStats, machineLearningClient::getTrainedModelsStatsAsync); assertThat(getTrainedModelsStatsResponse.getTrainedModelStats(), hasSize(numberOfModels + 1)); assertThat(getTrainedModelsStatsResponse.getCount(), equalTo(5L + 1)); assertThat(getTrainedModelsStatsResponse.getTrainedModelStats().get(0).getPipelineCount(), equalTo(1)); assertThat(getTrainedModelsStatsResponse.getTrainedModelStats().get(1).getPipelineCount(), equalTo(0)); } { GetTrainedModelsStatsResponse getTrainedModelsStatsResponse = execute( new GetTrainedModelsStatsRequest(modelIdPrefix + 4, modelIdPrefix + 2, modelIdPrefix + 3), machineLearningClient::getTrainedModelsStats, machineLearningClient::getTrainedModelsStatsAsync); assertThat(getTrainedModelsStatsResponse.getTrainedModelStats(), hasSize(3)); assertThat(getTrainedModelsStatsResponse.getCount(), equalTo(3L)); } { GetTrainedModelsStatsResponse getTrainedModelsStatsResponse = execute( new GetTrainedModelsStatsRequest(modelIdPrefix + "*").setPageParams(new PageParams(1, 2)), machineLearningClient::getTrainedModelsStats, machineLearningClient::getTrainedModelsStatsAsync); assertThat(getTrainedModelsStatsResponse.getTrainedModelStats(), hasSize(2)); assertThat(getTrainedModelsStatsResponse.getCount(), equalTo(5L)); assertThat( getTrainedModelsStatsResponse.getTrainedModelStats() .stream() .map(TrainedModelStats::getModelId) .collect(Collectors.toList()), containsInAnyOrder(modelIdPrefix + 1, modelIdPrefix + 2)); } } public void testDeleteTrainedModel() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); String modelId = "delete-trained-model-test"; putTrainedModel(modelId); GetTrainedModelsResponse getTrainedModelsResponse = execute( new GetTrainedModelsRequest(modelId + "*").setIncludeDefinition(false).setAllowNoMatch(true), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync); assertThat(getTrainedModelsResponse.getCount(), equalTo(1L)); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(1)); AcknowledgedResponse deleteTrainedModelResponse = execute( new DeleteTrainedModelRequest(modelId), machineLearningClient::deleteTrainedModel, machineLearningClient::deleteTrainedModelAsync); assertTrue(deleteTrainedModelResponse.isAcknowledged()); getTrainedModelsResponse = execute( new GetTrainedModelsRequest(modelId + "*").setIncludeDefinition(false).setAllowNoMatch(true), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync); assertThat(getTrainedModelsResponse.getCount(), equalTo(0L)); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(0)); } public void testGetPrepackagedModels() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); GetTrainedModelsResponse getTrainedModelsResponse = execute( new GetTrainedModelsRequest("lang_ident_model_1").setIncludeDefinition(true), machineLearningClient::getTrainedModels, machineLearningClient::getTrainedModelsAsync); assertThat(getTrainedModelsResponse.getCount(), equalTo(1L)); assertThat(getTrainedModelsResponse.getTrainedModels(), hasSize(1)); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getModelId(), equalTo("lang_ident_model_1")); assertThat(getTrainedModelsResponse.getTrainedModels().get(0).getDefinition().getTrainedModel(), instanceOf(LangIdentNeuralNetwork.class)); } public void testPutFilter() throws Exception { String filterId = "filter-job-test"; MlFilter mlFilter = MlFilter.builder(filterId) .setDescription(randomAlphaOfLength(10)) .setItems(generateRandomStringArray(10, 10, false, false)) .build(); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); PutFilterResponse putFilterResponse = execute(new PutFilterRequest(mlFilter), machineLearningClient::putFilter, machineLearningClient::putFilterAsync); MlFilter createdFilter = putFilterResponse.getResponse(); assertThat(createdFilter, equalTo(mlFilter)); } public void testGetFilters() throws Exception { String filterId1 = "get-filter-test-1"; String filterId2 = "get-filter-test-2"; String filterId3 = "get-filter-test-3"; MlFilter mlFilter1 = MlFilter.builder(filterId1) .setDescription(randomAlphaOfLength(10)) .setItems(generateRandomStringArray(10, 10, false, false)) .build(); MlFilter mlFilter2 = MlFilter.builder(filterId2) .setDescription(randomAlphaOfLength(10)) .setItems(generateRandomStringArray(10, 10, false, false)) .build(); MlFilter mlFilter3 = MlFilter.builder(filterId3) .setDescription(randomAlphaOfLength(10)) .setItems(generateRandomStringArray(10, 10, false, false)) .build(); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putFilter(new PutFilterRequest(mlFilter1), RequestOptions.DEFAULT); machineLearningClient.putFilter(new PutFilterRequest(mlFilter2), RequestOptions.DEFAULT); machineLearningClient.putFilter(new PutFilterRequest(mlFilter3), RequestOptions.DEFAULT); { GetFiltersRequest getFiltersRequest = new GetFiltersRequest(); getFiltersRequest.setFilterId(filterId1); GetFiltersResponse getFiltersResponse = execute(getFiltersRequest, machineLearningClient::getFilter, machineLearningClient::getFilterAsync); assertThat(getFiltersResponse.count(), equalTo(1L)); assertThat(getFiltersResponse.filters().get(0), equalTo(mlFilter1)); } { GetFiltersRequest getFiltersRequest = new GetFiltersRequest(); getFiltersRequest.setFrom(1); getFiltersRequest.setSize(2); GetFiltersResponse getFiltersResponse = execute(getFiltersRequest, machineLearningClient::getFilter, machineLearningClient::getFilterAsync); assertThat(getFiltersResponse.count(), equalTo(3L)); assertThat(getFiltersResponse.filters().size(), equalTo(2)); assertThat(getFiltersResponse.filters().stream().map(MlFilter::getId).collect(Collectors.toList()), containsInAnyOrder("get-filter-test-2", "get-filter-test-3")); } } public void testUpdateFilter() throws Exception { String filterId = "update-filter-test"; MlFilter mlFilter = MlFilter.builder(filterId) .setDescription("old description") .setItems(Arrays.asList("olditem1", "olditem2")) .build(); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); machineLearningClient.putFilter(new PutFilterRequest(mlFilter), RequestOptions.DEFAULT); UpdateFilterRequest updateFilterRequest = new UpdateFilterRequest(filterId); updateFilterRequest.setAddItems(Arrays.asList("newItem1", "newItem2")); updateFilterRequest.setRemoveItems(Collections.singletonList("olditem1")); updateFilterRequest.setDescription("new description"); MlFilter filter = execute(updateFilterRequest, machineLearningClient::updateFilter, machineLearningClient::updateFilterAsync).getResponse(); assertThat(filter.getDescription(), equalTo(updateFilterRequest.getDescription())); assertThat(filter.getItems(), contains("newItem1", "newItem2", "olditem2")); } public void testDeleteFilter() throws Exception { String filterId = "delete-filter-job-test"; MlFilter mlFilter = MlFilter.builder(filterId) .setDescription(randomAlphaOfLength(10)) .setItems(generateRandomStringArray(10, 10, false, false)) .build(); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); PutFilterResponse putFilterResponse = execute(new PutFilterRequest(mlFilter), machineLearningClient::putFilter, machineLearningClient::putFilterAsync); MlFilter createdFilter = putFilterResponse.getResponse(); assertThat(createdFilter, equalTo(mlFilter)); DeleteFilterRequest deleteFilterRequest = new DeleteFilterRequest(filterId); AcknowledgedResponse response = execute(deleteFilterRequest, machineLearningClient::deleteFilter, machineLearningClient::deleteFilterAsync); assertTrue(response.isAcknowledged()); ElasticsearchStatusException exception = expectThrows(ElasticsearchStatusException.class, () -> execute(deleteFilterRequest, machineLearningClient::deleteFilter, machineLearningClient::deleteFilterAsync)); assertThat(exception.status().getStatus(), equalTo(404)); } public void testGetMlInfo() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); MlInfoResponse infoResponse = execute(new MlInfoRequest(), machineLearningClient::getMlInfo, machineLearningClient::getMlInfoAsync); Map<String, Object> info = infoResponse.getInfo(); assertThat(info, notNullValue()); assertTrue(info.containsKey("defaults")); assertTrue(info.containsKey("limits")); } public static String randomValidJobId() { CodepointSetGenerator generator = new CodepointSetGenerator("abcdefghijklmnopqrstuvwxyz0123456789".toCharArray()); return generator.ofCodePointsLength(random(), 10, 10); } private static Job buildJobForExpiredDataTests(String jobId) { Job.Builder builder = new Job.Builder(jobId); builder.setDescription(randomAlphaOfLength(10)); Detector detector = new Detector.Builder() .setFunction("count") .setDetectorDescription(randomAlphaOfLength(10)) .build(); AnalysisConfig.Builder configBuilder = new AnalysisConfig.Builder(Collections.singletonList(detector)); //should not be random, see:https://github.com/elastic/ml-cpp/issues/208 configBuilder.setBucketSpan(new TimeValue(1, TimeUnit.HOURS)); builder.setAnalysisConfig(configBuilder); builder.setModelSnapshotRetentionDays(1L); builder.setDailyModelSnapshotRetentionAfterDays(1L); DataDescription.Builder dataDescription = new DataDescription.Builder(); dataDescription.setTimeFormat(DataDescription.EPOCH_MS); dataDescription.setTimeField("timestamp"); builder.setDataDescription(dataDescription); return builder.build(); } public static Job buildJob(String jobId) { Job.Builder builder = new Job.Builder(jobId); builder.setDescription(randomAlphaOfLength(10)); Detector detector = new Detector.Builder() .setFieldName("total") .setFunction("sum") .setDetectorDescription(randomAlphaOfLength(10)) .build(); AnalysisConfig.Builder configBuilder = new AnalysisConfig.Builder(Arrays.asList(detector)); //should not be random, see:https://github.com/elastic/ml-cpp/issues/208 configBuilder.setBucketSpan(new TimeValue(5, TimeUnit.SECONDS)); builder.setAnalysisConfig(configBuilder); builder.setAnalysisLimits(new AnalysisLimits(512L, 4L)); DataDescription.Builder dataDescription = new DataDescription.Builder(); dataDescription.setTimeFormat(DataDescription.EPOCH_MS); dataDescription.setTimeField("timestamp"); builder.setDataDescription(dataDescription); return builder.build(); } private void putJob(Job job) throws IOException { highLevelClient().machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); } private void openJob(Job job) throws IOException { highLevelClient().machineLearning().openJob(new OpenJobRequest(job.getId()), RequestOptions.DEFAULT); } private void putTrainedModel(String modelId) throws IOException { TrainedModelDefinition definition = TrainedModelDefinitionTests.createRandomBuilder(TargetType.REGRESSION).build(); TrainedModelConfig trainedModelConfig = TrainedModelConfig.builder() .setDefinition(definition) .setModelId(modelId) .setInferenceConfig(new RegressionConfig()) .setInput(new TrainedModelInput(Arrays.asList("col1", "col2", "col3", "col4"))) .setDescription("test model") .build(); highLevelClient().machineLearning().putTrainedModel(new PutTrainedModelRequest(trainedModelConfig), RequestOptions.DEFAULT); } private void waitForJobToClose(String jobId) throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); assertBusy(() -> { JobStats stats = machineLearningClient.getJobStats(new GetJobStatsRequest(jobId), RequestOptions.DEFAULT).jobStats().get(0); assertEquals(JobState.CLOSED, stats.getState()); }, 30, TimeUnit.SECONDS); } private void startDatafeed(String datafeedId, String start, String end) throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); StartDatafeedRequest startDatafeedRequest = new StartDatafeedRequest(datafeedId); startDatafeedRequest.setStart(start); startDatafeedRequest.setEnd(end); StartDatafeedResponse response = execute(startDatafeedRequest, machineLearningClient::startDatafeed, machineLearningClient::startDatafeedAsync); assertTrue(response.isStarted()); } private void updateModelSnapshotTimestamp(String jobId, String timestamp) throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); GetModelSnapshotsRequest getModelSnapshotsRequest = new GetModelSnapshotsRequest(jobId); GetModelSnapshotsResponse getModelSnapshotsResponse = execute(getModelSnapshotsRequest, machineLearningClient::getModelSnapshots, machineLearningClient::getModelSnapshotsAsync); assertThat(getModelSnapshotsResponse.count(), greaterThanOrEqualTo(1L)); ModelSnapshot modelSnapshot = getModelSnapshotsResponse.snapshots().get(0); String snapshotId = modelSnapshot.getSnapshotId(); String documentId = jobId + "_model_snapshot_" + snapshotId; String snapshotUpdate = "{ \"timestamp\": " + timestamp + "}"; UpdateRequest updateSnapshotRequest = new UpdateRequest(".ml-anomalies-" + jobId, documentId); updateSnapshotRequest.doc(snapshotUpdate.getBytes(StandardCharsets.UTF_8), XContentType.JSON); highLevelClient().update(updateSnapshotRequest, RequestOptions.DEFAULT); } private String createAndPutDatafeed(String jobId, String indexName) throws IOException { String datafeedId = jobId + "-feed"; DatafeedConfig datafeed = DatafeedConfig.builder(datafeedId, jobId) .setIndices(indexName) .setQueryDelay(TimeValue.timeValueSeconds(1)) .setFrequency(TimeValue.timeValueSeconds(1)).build(); highLevelClient().machineLearning().putDatafeed(new PutDatafeedRequest(datafeed), RequestOptions.DEFAULT); return datafeedId; } public void createModelSnapshot(String jobId, String snapshotId) throws IOException { String documentId = jobId + "_model_snapshot_" + snapshotId; Job job = MachineLearningIT.buildJob(jobId); highLevelClient().machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared").id(documentId); indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); indexRequest.source("{\"job_id\":\"" + jobId + "\", \"timestamp\":1541587919000, " + "\"description\":\"State persisted due to job close at 2018-11-07T10:51:59+0000\", " + "\"snapshot_id\":\"" + snapshotId + "\", \"snapshot_doc_count\":1, \"model_size_stats\":{" + "\"job_id\":\"" + jobId + "\", \"result_type\":\"model_size_stats\",\"model_bytes\":51722, " + "\"total_by_field_count\":3, \"total_over_field_count\":0, \"total_partition_field_count\":2," + "\"bucket_allocation_failures_count\":0, \"memory_status\":\"ok\", \"log_time\":1541587919000, " + "\"timestamp\":1519930800000}, \"latest_record_time_stamp\":1519931700000," + "\"latest_result_time_stamp\":1519930800000, \"retain\":false}", XContentType.JSON); highLevelClient().index(indexRequest, RequestOptions.DEFAULT); } public void createModelSnapshots(String jobId, List<String> snapshotIds) throws IOException { Job job = MachineLearningIT.buildJob(jobId); highLevelClient().machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); for(String snapshotId : snapshotIds) { String documentId = jobId + "_model_snapshot_" + snapshotId; IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared").id(documentId); indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); indexRequest.source("{\"job_id\":\"" + jobId + "\", \"timestamp\":1541587919000, " + "\"description\":\"State persisted due to job close at 2018-11-07T10:51:59+0000\", " + "\"snapshot_id\":\"" + snapshotId + "\", \"snapshot_doc_count\":1, \"model_size_stats\":{" + "\"job_id\":\"" + jobId + "\", \"result_type\":\"model_size_stats\",\"model_bytes\":51722, " + "\"total_by_field_count\":3, \"total_over_field_count\":0, \"total_partition_field_count\":2," + "\"bucket_allocation_failures_count\":0, \"memory_status\":\"ok\", \"log_time\":1541587919000, " + "\"timestamp\":1519930800000}, \"latest_record_time_stamp\":1519931700000," + "\"latest_result_time_stamp\":1519930800000, \"retain\":false, " + "\"quantiles\":{\"job_id\":\""+jobId+"\", \"timestamp\":1541587919000, " + "\"quantile_state\":\"state\"}}", XContentType.JSON); highLevelClient().index(indexRequest, RequestOptions.DEFAULT); } } public void testDeleteModelSnapshot() throws IOException { String jobId = "test-delete-model-snapshot"; String snapshotId = "1541587919"; createModelSnapshot(jobId, snapshotId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); DeleteModelSnapshotRequest request = new DeleteModelSnapshotRequest(jobId, snapshotId); AcknowledgedResponse response = execute(request, machineLearningClient::deleteModelSnapshot, machineLearningClient::deleteModelSnapshotAsync); assertTrue(response.isAcknowledged()); } public void testUpdateModelSnapshot() throws Exception { String jobId = "test-update-model-snapshot"; String snapshotId = "1541587919"; createModelSnapshot(jobId, snapshotId); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); GetModelSnapshotsRequest getModelSnapshotsRequest = new GetModelSnapshotsRequest(jobId); GetModelSnapshotsResponse getModelSnapshotsResponse1 = execute(getModelSnapshotsRequest, machineLearningClient::getModelSnapshots, machineLearningClient::getModelSnapshotsAsync); assertEquals(getModelSnapshotsResponse1.count(), 1L); assertEquals("State persisted due to job close at 2018-11-07T10:51:59+0000", getModelSnapshotsResponse1.snapshots().get(0).getDescription()); UpdateModelSnapshotRequest request = new UpdateModelSnapshotRequest(jobId, snapshotId); request.setDescription("Updated description"); request.setRetain(true); UpdateModelSnapshotResponse response = execute(request, machineLearningClient::updateModelSnapshot, machineLearningClient::updateModelSnapshotAsync); assertTrue(response.getAcknowledged()); assertEquals("Updated description", response.getModel().getDescription()); assertTrue(response.getModel().getRetain()); GetModelSnapshotsResponse getModelSnapshotsResponse2 = execute(getModelSnapshotsRequest, machineLearningClient::getModelSnapshots, machineLearningClient::getModelSnapshotsAsync); assertEquals(getModelSnapshotsResponse2.count(), 1L); assertEquals("Updated description", getModelSnapshotsResponse2.snapshots().get(0).getDescription()); } public void testRevertModelSnapshot() throws IOException { String jobId = "test-revert-model-snapshot"; List<String> snapshotIds = new ArrayList<>(); String snapshotId1 = "1541587919"; String snapshotId2 = "1541588919"; String snapshotId3 = "1541589919"; snapshotIds.add(snapshotId1); snapshotIds.add(snapshotId2); snapshotIds.add(snapshotId3); createModelSnapshots(jobId, snapshotIds); MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); for (String snapshotId : snapshotIds){ RevertModelSnapshotRequest request = new RevertModelSnapshotRequest(jobId, snapshotId); if (randomBoolean()) { request.setDeleteInterveningResults(randomBoolean()); } RevertModelSnapshotResponse response = execute(request, machineLearningClient::revertModelSnapshot, machineLearningClient::revertModelSnapshotAsync); ModelSnapshot model = response.getModel(); assertEquals(snapshotId, model.getSnapshotId()); } } public void testFindFileStructure() throws IOException { String sample = "{\"logger\":\"controller\",\"timestamp\":1478261151445,\"level\":\"INFO\"," + "\"pid\":42,\"thread\":\"0x7fff7d2a8000\",\"message\":\"message 1\",\"class\":\"ml\"," + "\"method\":\"core::SomeNoiseMaker\",\"file\":\"Noisemaker.cc\",\"line\":333}\n" + "{\"logger\":\"controller\",\"timestamp\":1478261151445," + "\"level\":\"INFO\",\"pid\":42,\"thread\":\"0x7fff7d2a8000\",\"message\":\"message 2\",\"class\":\"ml\"," + "\"method\":\"core::SomeNoiseMaker\",\"file\":\"Noisemaker.cc\",\"line\":333}\n"; MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); FindFileStructureRequest request = new FindFileStructureRequest(); request.setSample(sample.getBytes(StandardCharsets.UTF_8)); FindFileStructureResponse response = execute(request, machineLearningClient::findFileStructure, machineLearningClient::findFileStructureAsync); FileStructure structure = response.getFileStructure(); assertEquals(2, structure.getNumLinesAnalyzed()); assertEquals(2, structure.getNumMessagesAnalyzed()); assertEquals(sample, structure.getSampleStart()); assertEquals(FileStructure.Format.NDJSON, structure.getFormat()); assertEquals(StandardCharsets.UTF_8.displayName(Locale.ROOT), structure.getCharset()); assertFalse(structure.getHasByteOrderMarker()); assertNull(structure.getMultilineStartPattern()); assertNull(structure.getExcludeLinesPattern()); assertNull(structure.getColumnNames()); assertNull(structure.getHasHeaderRow()); assertNull(structure.getDelimiter()); assertNull(structure.getQuote()); assertNull(structure.getShouldTrimFields()); assertNull(structure.getGrokPattern()); assertEquals(Collections.singletonList("UNIX_MS"), structure.getJavaTimestampFormats()); assertEquals(Collections.singletonList("UNIX_MS"), structure.getJodaTimestampFormats()); assertEquals("timestamp", structure.getTimestampField()); assertFalse(structure.needClientTimezone()); } public void testEnableUpgradeMode() throws Exception { MachineLearningClient machineLearningClient = highLevelClient().machineLearning(); MlInfoResponse mlInfoResponse = machineLearningClient.getMlInfo(new MlInfoRequest(), RequestOptions.DEFAULT); assertThat(mlInfoResponse.getInfo().get("upgrade_mode"), equalTo(false)); AcknowledgedResponse setUpgrademodeResponse = execute(new SetUpgradeModeRequest(true), machineLearningClient::setUpgradeMode, machineLearningClient::setUpgradeModeAsync); assertThat(setUpgrademodeResponse.isAcknowledged(), is(true)); mlInfoResponse = machineLearningClient.getMlInfo(new MlInfoRequest(), RequestOptions.DEFAULT); assertThat(mlInfoResponse.getInfo().get("upgrade_mode"), equalTo(true)); setUpgrademodeResponse = execute(new SetUpgradeModeRequest(false), machineLearningClient::setUpgradeMode, machineLearningClient::setUpgradeModeAsync); assertThat(setUpgrademodeResponse.isAcknowledged(), is(true)); mlInfoResponse = machineLearningClient.getMlInfo(new MlInfoRequest(), RequestOptions.DEFAULT); assertThat(mlInfoResponse.getInfo().get("upgrade_mode"), equalTo(false)); } @Override protected NamedXContentRegistry xContentRegistry() { return new NamedXContentRegistry(new MlInferenceNamedXContentProvider().getNamedXContentParsers()); } }
3e0a0071ad4b5d690a5e7f156f3c3d4d773c10b4
5,508
java
Java
src/main/java/com/pject/sources/parsing/InstagramSource.java
bobdenardd/twttwinbot
caad0349010f066a54aef96c6d57b4096e839b6c
[ "Apache-2.0" ]
null
null
null
src/main/java/com/pject/sources/parsing/InstagramSource.java
bobdenardd/twttwinbot
caad0349010f066a54aef96c6d57b4096e839b6c
[ "Apache-2.0" ]
null
null
null
src/main/java/com/pject/sources/parsing/InstagramSource.java
bobdenardd/twttwinbot
caad0349010f066a54aef96c6d57b4096e839b6c
[ "Apache-2.0" ]
1
2021-07-21T06:42:58.000Z
2021-07-21T06:42:58.000Z
36.966443
137
0.590595
4,249
package com.pject.sources.parsing; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import com.google.common.primitives.Ints; import com.pject.helpers.LogFormatHelper; import com.pject.helpers.StatsHelper; import com.pject.sources.Source; import org.apache.commons.lang3.StringUtils; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.util.List; /** * InstagramSource - Short description of the class * * @author Camille * Last: 29/09/2015 15:06 * @version $Id$ */ public class InstagramSource implements Source { private static final Logger LOGGER = Logger.getLogger(InstagramSource.class); private static final String NAME = "instagram"; private static final List<String> INSTA_URLS = Lists.newArrayList( "http://www.hashtagig.com/analytics/instagood", "http://www.hashtagig.com/analytics/love", "http://www.hashtagig.com/analytics/photooftheday", "http://www.hashtagig.com/analytics/beautiful" ); private static final int MAX_INSTAS_PER_TAG = 35; private List<String> sources = Lists.newArrayList(); public InstagramSource() { LOGGER.info("Initializing instagram source"); long start = System.currentTimeMillis(); for(String instaUrl : INSTA_URLS) { processHashTag(instaUrl); } StatsHelper.registerSource(NAME, System.currentTimeMillis() - start, this.sources.size()); LOGGER.info("Got " + this.sources.size() + " sources"); } private void processHashTag(String hashTagUrl) { if(LOGGER.isDebugEnabled()) { LOGGER.debug("Processing hashtag analytics " + hashTagUrl); } HttpGet httpGet = new HttpGet(hashTagUrl); try (CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = httpclient.execute(httpGet)){ if(response.getStatusLine().getStatusCode() == 200) { String raw = EntityUtils.toString(response.getEntity()); Document doc = Jsoup.parse(raw); int i = 0; for(Element element : doc.select("div.snapshot")) { if(i > MAX_INSTAS_PER_TAG) { break; } // Retrieving image String imageUrl = null; List<String> hashtags = null; Elements elements = element.select("img"); if(elements.size() > 0) { imageUrl = elements.get(0).attr("src"); hashtags = extractHashTags(elements.get(0).attr("title")); } // Building source String source = mergeTagsWithPicture(imageUrl, hashtags); if(source != null &&StringUtils.isNotEmpty(source)) { this.sources.add(source.replace("s150x150", "510x510")); i++; } } } } catch(IOException e) { LOGGER.error("Could not load instagram links: " + LogFormatHelper.formatExceptionMessage(e)); } } private List<String> extractHashTags(String text) { List<String> result = Lists.newArrayList(); if(StringUtils.isNotEmpty(text) && text.contains("#")) { for(String token : text.split("#")) { String potentialToken = StringUtils.trimToEmpty(token.replaceAll(" .*", StringUtils.EMPTY)); if(StringUtils.isNotEmpty(potentialToken)) { result.add("#" + potentialToken); } } } return result; } private String mergeTagsWithPicture(String pictureUrl, List<String> hashtags) { if(StringUtils.isEmpty(pictureUrl) || hashtags == null) { return null; } // Preordering the list of hashtags Ordering<String> o = new Ordering<String>() { @Override public int compare(String left, String right) { return Ints.compare(left.length(), right.length()); } }; // Merging stuff depending on the size int possible = 139 - pictureUrl.length(); StringBuilder source = new StringBuilder(); while (possible > 0 && hashtags.size() > 0) { String hash = o.min(hashtags); if(possible - hash.length() - 1 > 0) { source.append(hash).append(" "); hashtags.remove(hash); possible = possible - hash.length() - 1; } else { break; } } source.setLength(Math.max(source.length() - 1, 0)); source.append(" ").append(pictureUrl); return source.toString(); } @Override public String getTweet() { if(this.sources.size() > 0) { String source = this.sources.get(RANDOM.nextInt(this.sources.size())); this.sources.remove(source); return source; } return null; } }
3e0a014e635e92ad5a41d42c2e1e8b6dc9135bc6
690
java
Java
src/main/java/com/iexec/core/detector/Detector.java
mbettinger/iexec-core
4b967051db94525e810783a584e44293495b54f6
[ "ECL-2.0", "Apache-2.0" ]
27
2019-01-25T16:50:20.000Z
2021-07-31T21:36:04.000Z
src/main/java/com/iexec/core/detector/Detector.java
mbettinger/iexec-core
4b967051db94525e810783a584e44293495b54f6
[ "ECL-2.0", "Apache-2.0" ]
83
2019-01-28T09:59:11.000Z
2022-02-09T10:00:33.000Z
src/main/java/com/iexec/core/detector/Detector.java
mbettinger/iexec-core
4b967051db94525e810783a584e44293495b54f6
[ "ECL-2.0", "Apache-2.0" ]
6
2019-02-09T14:36:00.000Z
2020-06-06T16:10:20.000Z
30
75
0.736232
4,250
/* * Copyright 2020 IEXEC BLOCKCHAIN TECH * * 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.iexec.core.detector; public interface Detector { void detect(); }
3e0a01aef3625a270ec1a910afe488679cbfa995
1,219
java
Java
src/main/java/com/chenwz/design/pattern/creational/singleton/LazyDoubleCheckSingleton.java
ChenWeiZhao/design_pattern
982e9b09f20f8ade350978eace5da85fd04a0e70
[ "Apache-2.0" ]
null
null
null
src/main/java/com/chenwz/design/pattern/creational/singleton/LazyDoubleCheckSingleton.java
ChenWeiZhao/design_pattern
982e9b09f20f8ade350978eace5da85fd04a0e70
[ "Apache-2.0" ]
null
null
null
src/main/java/com/chenwz/design/pattern/creational/singleton/LazyDoubleCheckSingleton.java
ChenWeiZhao/design_pattern
982e9b09f20f8ade350978eace5da85fd04a0e70
[ "Apache-2.0" ]
null
null
null
33.861111
85
0.64233
4,251
package com.chenwz.design.pattern.creational.singleton; /** * 双重检查懒汉式 */ public class LazyDoubleCheckSingleton { /** * 解决下面重排序办法:1、加入volatile关键字,重排序被禁止;2、基于类初始化解决方案,即线程看不到另一个线程的重排序 * 多线程时,cpu也有共享内存,加了volatile,所有线程都能看到共享内存最新状态,保证内存可见性 * 用volatile修饰的共享变量,在进行写操作时,会多出一些汇编代码,作用: * 将当前处理器缓存行的数据写回系统内存中,这个写回内存的操作会使得其它cpu中缓存了该内存的数据无效, * 无效之后又从共享内存中同步数据,保证了内存的可见性,使用了缓存一致性协议 */ private volatile static LazyDoubleCheckSingleton lazyDoubleCheckSingleton = null; private LazyDoubleCheckSingleton() { } public static LazyDoubleCheckSingleton getInstance() { if (lazyDoubleCheckSingleton == null) { //锁定类 synchronized (LazyDoubleCheckSingleton.class) { if (lazyDoubleCheckSingleton == null) { lazyDoubleCheckSingleton = new LazyDoubleCheckSingleton(); //1.分配内存给这个对象,但是二三步骤顺序可能会颠倒 //3.设置lazyDoubleCheckSingleton 指向刚分配的内存地址 //2.初始化对象 //intra-thread semantics,保证重排序不会改变单线程内程序结果 // 3.设置lazyDoubleCheckSingleton 指向刚分配的内存地址 } } } return lazyDoubleCheckSingleton; } }
3e0a01bc1e03ee03e93ebe3e66c630760c6e9a5d
1,196
java
Java
contracts/src/main/java/com/template/states/CarState.java
ringaile/tesla-cordaapp
a3c88b1887bd880d5fbbe310b4430115a61e2a92
[ "Apache-2.0" ]
null
null
null
contracts/src/main/java/com/template/states/CarState.java
ringaile/tesla-cordaapp
a3c88b1887bd880d5fbbe310b4430115a61e2a92
[ "Apache-2.0" ]
null
null
null
contracts/src/main/java/com/template/states/CarState.java
ringaile/tesla-cordaapp
a3c88b1887bd880d5fbbe310b4430115a61e2a92
[ "Apache-2.0" ]
null
null
null
29.170732
83
0.706522
4,252
package com.template.states; import com.template.contracts.CarContract; import net.corda.core.contracts.BelongsToContract; import net.corda.core.contracts.ContractState; import net.corda.core.identity.AbstractParty; import net.corda.core.identity.Party; import java.util.Arrays; import java.util.List; // ********* // * State * // ********* @BelongsToContract(CarContract.class) public class CarState implements ContractState { //private variables private final String model; private final Party owner; private final Party manufacturer; /* Constructor of your Corda state */ public CarState(String model, Party owner, Party manufacturer) { this.model = model; this.owner = owner; this.manufacturer = manufacturer; } //getters public String getModel() { return model; } public Party getOwner() { return owner; } public Party getManufacturer() { return manufacturer; } /* This method will indicate who are the participants and required signers when * this state is used in a transaction. */ @Override public List<AbstractParty> getParticipants() { return Arrays.asList(owner, manufacturer); } }
3e0a020020035aa6f06bce3e54c51745adb702e3
703
java
Java
org.osgi.webapp.example/src/org/osgi/webapp/example/HelloWorldServlet.java
ingomohr/osgi-webapp-example
d5fc3aca65807bf8c5b6d36fe9bd0eaca96df5af
[ "MIT" ]
null
null
null
org.osgi.webapp.example/src/org/osgi/webapp/example/HelloWorldServlet.java
ingomohr/osgi-webapp-example
d5fc3aca65807bf8c5b6d36fe9bd0eaca96df5af
[ "MIT" ]
null
null
null
org.osgi.webapp.example/src/org/osgi/webapp/example/HelloWorldServlet.java
ingomohr/osgi-webapp-example
d5fc3aca65807bf8c5b6d36fe9bd0eaca96df5af
[ "MIT" ]
null
null
null
29.291667
93
0.763869
4,253
package org.osgi.webapp.example; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HelloWorldServlet extends HttpServlet { private static final long serialVersionUID = 4085391411655563165L; @Override protected void doGet(HttpServletRequest pRequest, HttpServletResponse pResponse) throws ServletException, IOException { try (final PrintWriter out = pResponse.getWriter()) { out.println("<html><body><h2>OSGi WebApp Example</h2><p>Hello World!</p></body></html>"); } } }
3e0a024959b37015070efde5d0db0c5826ec0eaf
386
java
Java
src/main/java/com/wizz/gift/mapper/CommentMapper.java
baijianruoliorz/gift
5189bd860c53479fd6b30448ac7313faceacb35a
[ "MIT" ]
6
2020-11-30T03:07:21.000Z
2021-07-27T15:15:21.000Z
src/main/java/com/wizz/gift/mapper/CommentMapper.java
baijianruoliorz/fuck-this-project
bd1e60f54152db4fca2135dba5de928c4678015d
[ "MIT" ]
1
2020-11-15T03:17:38.000Z
2020-11-23T01:23:35.000Z
src/main/java/com/wizz/gift/mapper/CommentMapper.java
baijianruoliorz/fuck-this-project
bd1e60f54152db4fca2135dba5de928c4678015d
[ "MIT" ]
null
null
null
18.380952
60
0.751295
4,254
package com.wizz.gift.mapper; import com.wizz.gift.entity.Comment; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; /** * <p> * Mapper 接口 * </p> * * @author liqiqiorz * @since 2020-11-15 */ @Repository @Mapper public interface CommentMapper extends BaseMapper<Comment> { }
3e0a02e5e45a7e43929fae45bf7e44e1bdaa6ab9
3,577
java
Java
foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/optimisticlocking/UpdateNullOneToOneValueTest.java
brettdavidson3/eclipselink.runtime
a992a67ce49ca56117df4632c9c0c70938a0b28e
[ "BSD-3-Clause" ]
null
null
null
foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/optimisticlocking/UpdateNullOneToOneValueTest.java
brettdavidson3/eclipselink.runtime
a992a67ce49ca56117df4632c9c0c70938a0b28e
[ "BSD-3-Clause" ]
null
null
null
foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/optimisticlocking/UpdateNullOneToOneValueTest.java
brettdavidson3/eclipselink.runtime
a992a67ce49ca56117df4632c9c0c70938a0b28e
[ "BSD-3-Clause" ]
null
null
null
37.652632
88
0.64719
4,255
/******************************************************************************* * Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * dminsky - initial API and implementation ******************************************************************************/ package org.eclipse.persistence.testing.tests.optimisticlocking; import org.eclipse.persistence.expressions.ExpressionBuilder; import org.eclipse.persistence.sessions.UnitOfWork; import org.eclipse.persistence.testing.framework.TestException; import org.eclipse.persistence.testing.models.optimisticlocking.Camera; import org.eclipse.persistence.testing.models.optimisticlocking.GamesConsole; import org.eclipse.persistence.testing.models.optimisticlocking.PowerSupplyUnit; /** * Test updating a value from a null DB value to a non-null value and back again. * EL bug 319759 * @author dminsky */ public class UpdateNullOneToOneValueTest extends SwitchableOptimisticLockingPolicyTest { protected GamesConsole original; protected GamesConsole original2; public UpdateNullOneToOneValueTest(Class optimisticLockingPolicyClass) { super(optimisticLockingPolicyClass); addClassToModify(GamesConsole.class); addClassToModify(Camera.class); } public void setup() { super.setup(); UnitOfWork uow = getSession().acquireUnitOfWork(); original = new GamesConsole(); original.setName("PloughStation"); original.setCamera(null); // null camera original.setPsu(new PowerSupplyUnit("0-123-456-789")); original2 = new GamesConsole(); original2.setName("Nintundo65"); uow.registerObject(original); uow.registerObject(original2); uow.commit(); } public void test() throws TestException { try { getSession().getIdentityMapAccessor().initializeAllIdentityMaps(); readObjectAndChangeAttributeValue(new Camera("lookcam", "black")); readObjectAndChangeAttributeValue(null); readObjectAndChangeAttributeValue(new Camera("barbeye", "pink")); readObjectAndChangeAttributeValue(new Camera("appleofmyeye", "white")); readObjectAndChangeAttributeValue(null); // delete the objects deleteObject(original); deleteObject(original2); } catch (Exception tle) { this.tlException = tle; this.tlException.printStackTrace(); } } public void readObjectAndChangeAttributeValue(Camera newCamera) { UnitOfWork uow = getSession().acquireUnitOfWork(); GamesConsole clone = (GamesConsole) uow.readObject( GamesConsole.class, new ExpressionBuilder().get("id").equal(this.original.getId())); assertNotNull("The object returned should be not null", clone); clone.setCamera(newCamera); uow.commit(); } public void reset() { super.reset(); this.original = null; this.original2 = null; } }
3e0a046846d5ecb9939776698dd77d18f1236990
9,940
java
Java
net/minecraft/entity/monster/EntityGhast.java
MinecraftModdedClients/Resilience-Client-Source
4a3b2bd906f17b99be9e5eceaf9d6fcfc1470c01
[ "WTFPL" ]
83
2017-01-27T07:04:00.000Z
2022-03-30T21:49:30.000Z
net/minecraft/entity/monster/EntityGhast.java
MinecraftModdedClients/Resilience-Client-Source
4a3b2bd906f17b99be9e5eceaf9d6fcfc1470c01
[ "WTFPL" ]
2
2020-10-02T12:01:34.000Z
2022-01-25T14:39:24.000Z
net/minecraft/entity/monster/EntityGhast.java
MinecraftModdedClients/Resilience-Client-Source
4a3b2bd906f17b99be9e5eceaf9d6fcfc1470c01
[ "WTFPL" ]
44
2017-03-17T07:26:18.000Z
2022-03-27T17:55:12.000Z
31.555556
155
0.587022
4,256
package net.minecraft.entity.monster; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityFlying; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.projectile.EntityLargeFireball; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.stats.AchievementList; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; import net.minecraft.world.EnumDifficulty; import net.minecraft.world.World; public class EntityGhast extends EntityFlying implements IMob { public int courseChangeCooldown; public double waypointX; public double waypointY; public double waypointZ; private Entity targetedEntity; /** Cooldown time between target loss and new target aquirement. */ private int aggroCooldown; public int prevAttackCounter; public int attackCounter; /** The explosion radius of spawned fireballs. */ private int explosionStrength = 1; private static final String __OBFID = "CL_00001689"; public EntityGhast(World par1World) { super(par1World); this.setSize(4.0F, 4.0F); this.isImmuneToFire = true; this.experienceValue = 5; } public boolean func_110182_bF() { return this.dataWatcher.getWatchableObjectByte(16) != 0; } /** * Called when the entity is attacked. */ public boolean attackEntityFrom(DamageSource par1DamageSource, float par2) { if (this.isEntityInvulnerable()) { return false; } else if ("fireball".equals(par1DamageSource.getDamageType()) && par1DamageSource.getEntity() instanceof EntityPlayer) { super.attackEntityFrom(par1DamageSource, 1000.0F); ((EntityPlayer)par1DamageSource.getEntity()).triggerAchievement(AchievementList.ghast); return true; } else { return super.attackEntityFrom(par1DamageSource, par2); } } protected void entityInit() { super.entityInit(); this.dataWatcher.addObject(16, Byte.valueOf((byte)0)); } protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(10.0D); } protected void updateEntityActionState() { if (!this.worldObj.isClient && this.worldObj.difficultySetting == EnumDifficulty.PEACEFUL) { this.setDead(); } this.despawnEntity(); this.prevAttackCounter = this.attackCounter; double var1 = this.waypointX - this.posX; double var3 = this.waypointY - this.posY; double var5 = this.waypointZ - this.posZ; double var7 = var1 * var1 + var3 * var3 + var5 * var5; if (var7 < 1.0D || var7 > 3600.0D) { this.waypointX = this.posX + (double)((this.rand.nextFloat() * 2.0F - 1.0F) * 16.0F); this.waypointY = this.posY + (double)((this.rand.nextFloat() * 2.0F - 1.0F) * 16.0F); this.waypointZ = this.posZ + (double)((this.rand.nextFloat() * 2.0F - 1.0F) * 16.0F); } if (this.courseChangeCooldown-- <= 0) { this.courseChangeCooldown += this.rand.nextInt(5) + 2; var7 = (double)MathHelper.sqrt_double(var7); if (this.isCourseTraversable(this.waypointX, this.waypointY, this.waypointZ, var7)) { this.motionX += var1 / var7 * 0.1D; this.motionY += var3 / var7 * 0.1D; this.motionZ += var5 / var7 * 0.1D; } else { this.waypointX = this.posX; this.waypointY = this.posY; this.waypointZ = this.posZ; } } if (this.targetedEntity != null && this.targetedEntity.isDead) { this.targetedEntity = null; } if (this.targetedEntity == null || this.aggroCooldown-- <= 0) { this.targetedEntity = this.worldObj.getClosestVulnerablePlayerToEntity(this, 100.0D); if (this.targetedEntity != null) { this.aggroCooldown = 20; } } double var9 = 64.0D; if (this.targetedEntity != null && this.targetedEntity.getDistanceSqToEntity(this) < var9 * var9) { double var11 = this.targetedEntity.posX - this.posX; double var13 = this.targetedEntity.boundingBox.minY + (double)(this.targetedEntity.height / 2.0F) - (this.posY + (double)(this.height / 2.0F)); double var15 = this.targetedEntity.posZ - this.posZ; this.renderYawOffset = this.rotationYaw = -((float)Math.atan2(var11, var15)) * 180.0F / (float)Math.PI; if (this.canEntityBeSeen(this.targetedEntity)) { if (this.attackCounter == 10) { this.worldObj.playAuxSFXAtEntity((EntityPlayer)null, 1007, (int)this.posX, (int)this.posY, (int)this.posZ, 0); } ++this.attackCounter; if (this.attackCounter == 20) { this.worldObj.playAuxSFXAtEntity((EntityPlayer)null, 1008, (int)this.posX, (int)this.posY, (int)this.posZ, 0); EntityLargeFireball var17 = new EntityLargeFireball(this.worldObj, this, var11, var13, var15); var17.field_92057_e = this.explosionStrength; double var18 = 4.0D; Vec3 var20 = this.getLook(1.0F); var17.posX = this.posX + var20.xCoord * var18; var17.posY = this.posY + (double)(this.height / 2.0F) + 0.5D; var17.posZ = this.posZ + var20.zCoord * var18; this.worldObj.spawnEntityInWorld(var17); this.attackCounter = -40; } } else if (this.attackCounter > 0) { --this.attackCounter; } } else { this.renderYawOffset = this.rotationYaw = -((float)Math.atan2(this.motionX, this.motionZ)) * 180.0F / (float)Math.PI; if (this.attackCounter > 0) { --this.attackCounter; } } if (!this.worldObj.isClient) { byte var21 = this.dataWatcher.getWatchableObjectByte(16); byte var12 = (byte)(this.attackCounter > 10 ? 1 : 0); if (var21 != var12) { this.dataWatcher.updateObject(16, Byte.valueOf(var12)); } } } /** * True if the ghast has an unobstructed line of travel to the waypoint. */ private boolean isCourseTraversable(double par1, double par3, double par5, double par7) { double var9 = (this.waypointX - this.posX) / par7; double var11 = (this.waypointY - this.posY) / par7; double var13 = (this.waypointZ - this.posZ) / par7; AxisAlignedBB var15 = this.boundingBox.copy(); for (int var16 = 1; (double)var16 < par7; ++var16) { var15.offset(var9, var11, var13); if (!this.worldObj.getCollidingBoundingBoxes(this, var15).isEmpty()) { return false; } } return true; } /** * Returns the sound this mob makes while it's alive. */ protected String getLivingSound() { return "mob.ghast.moan"; } /** * Returns the sound this mob makes when it is hurt. */ protected String getHurtSound() { return "mob.ghast.scream"; } /** * Returns the sound this mob makes on death. */ protected String getDeathSound() { return "mob.ghast.death"; } protected Item func_146068_u() { return Items.gunpowder; } /** * Drop 0-2 items of this living's type */ protected void dropFewItems(boolean par1, int par2) { int var3 = this.rand.nextInt(2) + this.rand.nextInt(1 + par2); int var4; for (var4 = 0; var4 < var3; ++var4) { this.func_145779_a(Items.ghast_tear, 1); } var3 = this.rand.nextInt(3) + this.rand.nextInt(1 + par2); for (var4 = 0; var4 < var3; ++var4) { this.func_145779_a(Items.gunpowder, 1); } } /** * Returns the volume for the sounds this mob makes. */ protected float getSoundVolume() { return 10.0F; } /** * Checks if the entity's current position is a valid location to spawn this entity. */ public boolean getCanSpawnHere() { return this.rand.nextInt(20) == 0 && super.getCanSpawnHere() && this.worldObj.difficultySetting != EnumDifficulty.PEACEFUL; } /** * Will return how many at most can spawn in a chunk at once. */ public int getMaxSpawnedInChunk() { return 1; } /** * (abstract) Protected helper method to write subclass entity data to NBT. */ public void writeEntityToNBT(NBTTagCompound par1NBTTagCompound) { super.writeEntityToNBT(par1NBTTagCompound); par1NBTTagCompound.setInteger("ExplosionPower", this.explosionStrength); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound par1NBTTagCompound) { super.readEntityFromNBT(par1NBTTagCompound); if (par1NBTTagCompound.func_150297_b("ExplosionPower", 99)) { this.explosionStrength = par1NBTTagCompound.getInteger("ExplosionPower"); } } }
3e0a04d610b624ab937dff298cd186092cfa1095
1,420
java
Java
managed/src/main/java/com/yugabyte/yw/models/AlertLabelKey.java
adil246/yugabyte-db
dc886cdd43497543e8ad2ad07bb77ad02e4cd4b1
[ "Apache-2.0", "CC0-1.0" ]
1
2021-06-11T10:23:00.000Z
2021-06-11T10:23:00.000Z
managed/src/main/java/com/yugabyte/yw/models/AlertLabelKey.java
adil246/yugabyte-db
dc886cdd43497543e8ad2ad07bb77ad02e4cd4b1
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
managed/src/main/java/com/yugabyte/yw/models/AlertLabelKey.java
adil246/yugabyte-db
dc886cdd43497543e8ad2ad07bb77ad02e4cd4b1
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
23.278689
100
0.690141
4,257
/* * Copyright 2021 YugaByte, Inc. and Contributors * * Licensed under the Polyform Free Trial License 1.0.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://github.com/YugaByte/yugabyte-db/blob/master/licenses/POLYFORM-FREE-TRIAL-LICENSE-1.0.0.txt */ package com.yugabyte.yw.models; import com.fasterxml.jackson.annotation.JsonIgnore; import io.ebean.Model; import javax.persistence.Embeddable; import java.util.Objects; import java.util.UUID; @Embeddable public class AlertLabelKey extends Model { @JsonIgnore private UUID alertUUID; private String name; public UUID getAlertUUID() { return alertUUID; } public void setAlertUUID(UUID alertUUID) { this.alertUUID = alertUUID; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AlertLabelKey that = (AlertLabelKey) o; return Objects.equals(alertUUID, that.alertUUID) && Objects.equals(name, that.name); } @Override public int hashCode() { return Objects.hash(alertUUID, name); } @Override public String toString() { return "AlertLabelKey{" + "alertUUID=" + alertUUID + ", name='" + name + '\'' + '}'; } }
3e0a04e44b095c009d65228f3691f94507effa22
128
java
Java
jasmine-gwt-wrapper/src/main/java/noo/testing/jasmine/client/rebind/TestClasses.java
gwt-noo/jasmine-wrapper
e6559e13061e8b4e315eb53a178d959084e62c72
[ "Apache-2.0" ]
1
2016-02-18T16:32:49.000Z
2016-02-18T16:32:49.000Z
jasmine-gwt-wrapper/src/main/java/noo/testing/jasmine/client/rebind/TestClasses.java
gwt-noo/jasmine-wrapper
e6559e13061e8b4e315eb53a178d959084e62c72
[ "Apache-2.0" ]
null
null
null
jasmine-gwt-wrapper/src/main/java/noo/testing/jasmine/client/rebind/TestClasses.java
gwt-noo/jasmine-wrapper
e6559e13061e8b4e315eb53a178d959084e62c72
[ "Apache-2.0" ]
null
null
null
14.222222
42
0.671875
4,258
package noo.testing.jasmine.client.rebind; /** * @author Tal Shani */ public @interface TestClasses { Class[] value(); }
3e0a074c7cb45dedfd607a34d59725a49c867164
76,775
java
Java
java/src/main/java/com/google/fhir/stu3/ProtoGenerator.java
ConsultingMD/fhir
9ce7761c12e2686c1600154ab624685bcf558eaa
[ "Apache-2.0" ]
null
null
null
java/src/main/java/com/google/fhir/stu3/ProtoGenerator.java
ConsultingMD/fhir
9ce7761c12e2686c1600154ab624685bcf558eaa
[ "Apache-2.0" ]
2
2018-12-03T22:07:19.000Z
2018-12-12T22:41:15.000Z
java/src/main/java/com/google/fhir/stu3/ProtoGenerator.java
ConsultingMD/fhir
9ce7761c12e2686c1600154ab624685bcf558eaa
[ "Apache-2.0" ]
1
2018-12-03T21:33:27.000Z
2018-12-03T21:33:27.000Z
44.533063
100
0.680208
4,259
// Copyright 2018 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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.fhir.stu3; import com.google.common.base.CaseFormat; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.MoreCollectors; import com.google.fhir.common.FhirVersion; import com.google.fhir.proto.PackageInfo; import com.google.fhir.stu3.proto.Annotations; import com.google.fhir.stu3.proto.CodeableConcept; import com.google.fhir.stu3.proto.CodingWithFixedCode; import com.google.fhir.stu3.proto.CodingWithFixedSystem; import com.google.fhir.stu3.proto.ElementDefinition; import com.google.fhir.stu3.proto.ElementDefinitionExplicitTypeName; import com.google.fhir.stu3.proto.ElementDefinitionRegex; import com.google.fhir.stu3.proto.StructureDefinition; import com.google.fhir.stu3.proto.StructureDefinitionKindCode; import com.google.fhir.stu3.proto.TypeDerivationRuleCode; import com.google.fhir.stu3.proto.Uri; import com.google.protobuf.DescriptorProtos.DescriptorProto; import com.google.protobuf.DescriptorProtos.EnumDescriptorProto; import com.google.protobuf.DescriptorProtos.EnumValueDescriptorProto; import com.google.protobuf.DescriptorProtos.FieldDescriptorProto; import com.google.protobuf.DescriptorProtos.FieldOptions; import com.google.protobuf.DescriptorProtos.FileDescriptorProto; import com.google.protobuf.DescriptorProtos.FileDescriptorProtoOrBuilder; import com.google.protobuf.DescriptorProtos.FileOptions; import com.google.protobuf.DescriptorProtos.MessageOptions; import com.google.protobuf.DescriptorProtos.OneofDescriptorProto; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Message; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; /** A class which turns FHIR StructureDefinitions into protocol messages. */ // TODO: Move a bunch of the public static methods into ProtoGeneratorUtils. public class ProtoGenerator { // The path for annotation definition of proto options. // TODO: Move the annotation to a general location. static final String ANNOTATION_PATH = "proto"; // Map of time-like primitive type ids to supported granularity private static final ImmutableMap<String, List<String>> TIME_LIKE_PRECISION_MAP = ImmutableMap.of( "date", ImmutableList.of("YEAR", "MONTH", "DAY"), "dateTime", ImmutableList.of("YEAR", "MONTH", "DAY", "SECOND", "MILLISECOND", "MICROSECOND"), "instant", ImmutableList.of("SECOND", "MILLISECOND", "MICROSECOND"), "time", ImmutableList.of("SECOND", "MILLISECOND", "MICROSECOND")); private static final ImmutableSet<String> TYPES_WITH_TIMEZONE = ImmutableSet.of("date", "dateTime", "instant"); // Certain field names are reserved symbols in various languages. private static final ImmutableSet<String> RESERVED_FIELD_NAMES = ImmutableSet.of("assert", "for", "hasAnswer", "package", "string", "class"); private static final EnumDescriptorProto PRECISION_ENUM = EnumDescriptorProto.newBuilder() .setName("Precision") .addValue( EnumValueDescriptorProto.newBuilder() .setName("PRECISION_UNSPECIFIED") .setNumber(0) .build()) .build(); private static final FieldDescriptorProto TIMEZONE_FIELD = FieldDescriptorProto.newBuilder() .setName("timezone") .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL) .setType(FieldDescriptorProto.Type.TYPE_STRING) .setNumber(2) .build(); private static final ImmutableMap<String, FieldDescriptorProto.Type> PRIMITIVE_TYPE_OVERRIDES = ImmutableMap.of( "base64Binary", FieldDescriptorProto.Type.TYPE_BYTES, "boolean", FieldDescriptorProto.Type.TYPE_BOOL, "integer", FieldDescriptorProto.Type.TYPE_SINT32, "positiveInt", FieldDescriptorProto.Type.TYPE_UINT32, "unsignedInt", FieldDescriptorProto.Type.TYPE_UINT32); // FHIR elements may have core constraint definitions that do not add // value to protocol buffers, so we exclude them. private static final ImmutableSet<String> EXCLUDED_FHIR_CONSTRAINTS = ImmutableSet.of("hasValue() | (children().count() > id.count())"); // Should we use custom types for constrained references? private static final boolean USE_TYPED_REFERENCES = false; // Mapping from urls for StructureDefinition to data about that StructureDefinition. private final ImmutableMap<String, StructureDefinitionData> structDefDataByUrl; // Mapping from id to StructureDefinition data about all known base (i.e., not profile) types. private final ImmutableMap<String, StructureDefinition> baseStructDefsById; // Mapping from ValueSet url to Descriptor for the message type it should be inlined as. private final ImmutableMap<String, Descriptor> valueSetTypesByUrl; private final ImmutableMap<String, Set<String>> coreTypeDefinitionsByFile; private static Set<String> getTypesDefinedInFile(FileDescriptor file) { return file.getMessageTypes().stream() .map(desc -> desc.getFullName()) .collect(Collectors.toSet()); } // The package to write new protos to. private final PackageInfo packageInfo; private final String fhirProtoRootPath; // The fhir version to use (e.g., DSTU2, STU3, R4). // This determines which core dependencies (e.g., datatypes.proto) to use. private final FhirVersion fhirVersion; private static class StructureDefinitionData { final StructureDefinition structDef; final String inlineType; final String protoPackage; StructureDefinitionData(StructureDefinition structDef, String inlineType, String protoPackage) { this.structDef = structDef; this.inlineType = inlineType; this.protoPackage = protoPackage; } } private static class QualifiedType { final String type; final String packageName; QualifiedType(String type, String packageName) { this.type = type; this.packageName = packageName; } } // Token in a id string. The sequence of tokens forms a heirarchical relationship, where each // dot-delimited token is of the form pathpart:slicename/reslicename. // See https://www.hl7.org/fhir/elementdefinition.html#id private static class IdToken { final String pathpart; final boolean isChoiceType; final String slicename; final String reslice; private IdToken(String pathpart, boolean isChoiceType, String slicename, String reslice) { this.pathpart = pathpart; this.isChoiceType = isChoiceType; this.slicename = slicename; this.reslice = reslice; } static IdToken fromTokenString(String tokenString) { List<String> colonSplit = Splitter.on(':').splitToList(tokenString); String pathpart = colonSplit.get(0); boolean isChoiceType = pathpart.endsWith("[x]"); if (isChoiceType) { pathpart = pathpart.substring(0, pathpart.length() - "[x]".length()); } if (colonSplit.size() == 1) { return new IdToken(pathpart, isChoiceType, null, null); } if (colonSplit.size() != 2) { throw new IllegalArgumentException("Bad token string: " + tokenString); } List<String> slashSplit = Splitter.on('/').splitToList(colonSplit.get(1)); if (slashSplit.size() == 1) { return new IdToken(pathpart, isChoiceType, slashSplit.get(0), null); } if (slashSplit.size() == 2) { return new IdToken(pathpart, isChoiceType, slashSplit.get(0), slashSplit.get(1)); } throw new IllegalArgumentException("Bad token string: " + tokenString); } } private static IdToken lastIdToken(String idString) { List<String> tokenStrings = Splitter.on('.').splitToList(idString); return IdToken.fromTokenString(Iterables.getLast(tokenStrings)); } public ProtoGenerator( PackageInfo packageInfo, String fhirProtoRootPath, Map<StructureDefinition, String> knownTypes) { this.packageInfo = packageInfo; this.fhirProtoRootPath = fhirProtoRootPath; this.fhirVersion = FhirVersion.fromPackageInfo(packageInfo.getFhirVersion()); // TODO: Do this with ValueSet resources once we have them. ImmutableMap.Builder<String, Descriptor> valueSetTypesByUrlBuilder = new ImmutableMap.Builder<>(); for (FileDescriptor desc : fhirVersion.codeTypeList) { valueSetTypesByUrlBuilder.putAll(loadCodeTypesFromFile(desc)); } this.valueSetTypesByUrl = valueSetTypesByUrlBuilder.build(); ImmutableMap.Builder<String, Set<String>> coreTypeBuilder = new ImmutableMap.Builder<>(); for (Map.Entry<String, FileDescriptor> entry : fhirVersion.coreTypeMap.entrySet()) { coreTypeBuilder.put(entry.getKey(), getTypesDefinedInFile(entry.getValue())); } this.coreTypeDefinitionsByFile = coreTypeBuilder.build(); Map<String, StructureDefinitionData> mutableStructDefDataByUrl = new HashMap<>(); for (Map.Entry<StructureDefinition, String> knownType : knownTypes.entrySet()) { StructureDefinition def = knownType.getKey(); String protoPackage = knownType.getValue(); String url = def.getUrl().getValue(); if (url.isEmpty()) { throw new IllegalArgumentException( "Invalid FHIR structure definition: " + def.getId().getValue() + " has no url"); } boolean isSimpleInternalExtension = isSimpleInternalExtension( def.getSnapshot().getElement(0), def.getSnapshot().getElementList()); String inlineType; String structDefPackage; if (isSimpleInternalExtension) { QualifiedType qualifiedType = getSimpleExtensionDefinitionType(def); inlineType = qualifiedType.type; structDefPackage = qualifiedType.packageName; } else { inlineType = getTypeName(def); structDefPackage = protoPackage; } StructureDefinitionData structDefData = new StructureDefinitionData(def, inlineType, structDefPackage); mutableStructDefDataByUrl.put(def.getUrl().getValue(), structDefData); } this.structDefDataByUrl = ImmutableMap.copyOf(mutableStructDefDataByUrl); this.baseStructDefsById = knownTypes.keySet().stream() .filter( def -> def.getDerivation().getValue() != TypeDerivationRuleCode.Value.CONSTRAINT) .collect(ImmutableMap.toImmutableMap(def -> def.getId().getValue(), def -> def)); } static Map<String, Descriptor> loadCodeTypesFromFile(FileDescriptor file) { return file.getMessageTypes().stream() .filter(d -> d.getOptions().hasExtension(Annotations.fhirValuesetUrl)) .collect( Collectors.toMap( d -> d.getOptions().getExtension(Annotations.fhirValuesetUrl), d -> d)); } // Map from StructureDefinition url to explicit renaming for the type that should be generated. // This is necessary for cases where the generated name type is problematic, e.g., when two // generated name types collide, or just to provide nicer names. private static final ImmutableMap<String, String> STRUCTURE_DEFINITION_RENAMINGS = ImmutableMap.of( "http://hl7.org/fhir/StructureDefinition/valueset-reference", "ValueSetReference", "http://hl7.org/fhir/StructureDefinition/codesystem-reference", "CodeSystemReference"); // Given a structure definition, gets the name of the top-level message that will be generated. public static String getTypeName(StructureDefinition def) { if (STRUCTURE_DEFINITION_RENAMINGS.containsKey(def.getUrl().getValue())) { return STRUCTURE_DEFINITION_RENAMINGS.get(def.getUrl().getValue()); } return isExtensionProfile(def) ? getProfileTypeName(def) : getTypeNameFromId(def.getId().getValue()); } // Given an id string, gets the name of the top-level message that will be generated. public static String getTypeNameFromId(String id) { return toFieldTypeCase(id); } /** * Generate a proto descriptor from a StructureDefinition, using the snapshot form of the * definition. For a more elaborate discussion of these versions, see * https://www.hl7.org/fhir/structuredefinition.html. */ public DescriptorProto generateProto(StructureDefinition def) { def = reconcileSnapshotAndDifferential(def); // Make sure the package the proto declared in is the same as it will be generated in. StructureDefinitionData structDefData = structDefDataByUrl.get(def.getUrl().getValue()); if (structDefData == null) { throw new IllegalArgumentException( "No StructureDefinition data found for: " + def.getUrl().getValue()); } if (!structDefData.protoPackage.equals(packageInfo.getProtoPackage()) && !isSingleTypedExtensionDefinition(structDefData.structDef)) { throw new IllegalArgumentException( "Inconsistent package name for " + def.getUrl().getValue() + ". Registered in --known_types in " + structDefData.protoPackage + " but being generated in " + packageInfo.getProtoPackage()); } List<ElementDefinition> elementList = def.getSnapshot().getElementList(); ElementDefinition root = elementList.get(0); boolean isPrimitive = def.getKind().getValue() == StructureDefinitionKindCode.Value.PRIMITIVE_TYPE; // Build a top-level message description. StringBuilder comment = new StringBuilder() .append("Auto-generated from StructureDefinition for ") .append(def.getName().getValue()); if (def.getMeta().hasLastUpdated()) { comment.append(", last updated ").append(new InstantWrapper(def.getMeta().getLastUpdated())); } comment.append("."); if (root.hasShort()) { String shortString = root.getShort().getValue(); if (!shortString.endsWith(".")) { shortString += "."; } comment.append("\n").append(shortString.replaceAll("[\\n\\r]", "\n")); } comment.append("\nSee ").append(def.getUrl().getValue()); // Add message-level annotations. DescriptorProto.Builder builder = DescriptorProto.newBuilder(); MessageOptions.Builder optionsBuilder = MessageOptions.newBuilder() .setExtension( Annotations.structureDefinitionKind, Annotations.StructureDefinitionKindValue.valueOf( "KIND_" + def.getKind().getValue())) .setExtension(Annotations.messageDescription, comment.toString()) .setExtension(Annotations.fhirStructureDefinitionUrl, def.getUrl().getValue()); if (def.getAbstract().getValue()) { optionsBuilder.setExtension(Annotations.isAbstractType, def.getAbstract().getValue()); } builder.setOptions(optionsBuilder); // If this is a primitive type, generate the value field first. if (isPrimitive) { generatePrimitiveValue(def, builder); } builder = generateMessage(root, elementList, builder).toBuilder(); if (isProfile(def)) { String name = getTypeName(def); // This is a profile on a pre-existing type. // Make sure any nested subtypes use the profile name, not the base name replaceType(builder, def.getType().getValue(), name); StructureDefinition defInChain = def; while (isProfile(defInChain)) { String baseUrl = defInChain.getBaseDefinition().getValue(); builder .setName(name) .getOptionsBuilder() .addExtension(Annotations.fhirProfileBase, baseUrl); defInChain = structDefDataByUrl.get(baseUrl).structDef; } } return builder.build(); } private static boolean isProfile(StructureDefinition def) { return def.getDerivation().getValue() == TypeDerivationRuleCode.Value.CONSTRAINT; } /** Generate a .proto file descriptor from a list of StructureDefinitions. */ public FileDescriptorProto generateFileDescriptor(List<StructureDefinition> defs) { FileDescriptorProto.Builder builder = FileDescriptorProto.newBuilder(); builder.setPackage(packageInfo.getProtoPackage()).setSyntax("proto3"); FileOptions.Builder options = FileOptions.newBuilder(); if (!packageInfo.getJavaProtoPackage().isEmpty()) { options.setJavaPackage(packageInfo.getJavaProtoPackage()).setJavaMultipleFiles(true); } if (!packageInfo.getGoProtoPackage().isEmpty()) { options.setGoPackage(packageInfo.getGoProtoPackage()); } builder.setOptions(options); for (StructureDefinition def : defs) { DescriptorProto proto = generateProto(def); builder.addMessageType(proto); } // Add imports. Annotations is always needed; datatypes is needed unless we are building them. builder.addDependency(new File(ANNOTATION_PATH, "annotations.proto").toString()); // Add the remaining FHIR dependencies if the file uses a type from the FHIR dep, but does not // define a type from that dep. for (Map.Entry<String, Set<String>> entry : coreTypeDefinitionsByFile.entrySet()) { String filename = entry.getKey(); Set<String> types = entry.getValue(); if (needsDep(builder, types)) { builder.addDependency(new File(fhirProtoRootPath, filename).toString()); } } return builder.build(); } // Returns true if the file proto uses a type from a set of types, but does not define it. private boolean needsDep(FileDescriptorProtoOrBuilder fileProto, Set<String> types) { for (DescriptorProto descriptor : fileProto.getMessageTypeList()) { if (types.contains(fhirVersion.coreFhirPackage + "." + descriptor.getName())) { // This file defines a type from the set. It can't depend on itself. return false; } } for (DescriptorProto proto : fileProto.getMessageTypeList()) { if (usesTypeFromSet(proto, types)) { return true; } } return false; } // Returns true if the file proto uses a type from a set of types. private boolean usesTypeFromSet(DescriptorProto proto, Set<String> types) { for (FieldDescriptorProto field : proto.getFieldList()) { // Drop leading dot before checking field type. if (!field.getTypeName().isEmpty() && types.contains(field.getTypeName().substring(1))) { return true; } for (DescriptorProto nested : proto.getNestedTypeList()) { if (usesTypeFromSet(nested, types)) { return true; } } } return false; } // Does a global find-and-replace of a given token in a message namespace. // This is necessary for profiles, since the StructureDefinition uses the base Resource name // throughout, but we wish to use the Profiled resource name. // So, for instance, for a profile MyProfiledResource on MyResource, this would be used to turn // some.package.MyResource.Submessage into some.package.MyProfiledResource.Submessage private void replaceType(DescriptorProto.Builder protoBuilder, String from, String to) { String fromWithDots = "." + from + "."; String toWithDots = "." + to + "."; for (FieldDescriptorProto.Builder field : protoBuilder.getFieldBuilderList()) { if (field.getTypeName().contains(fromWithDots)) { field.setTypeName(field.getTypeName().replaceFirst(fromWithDots, toWithDots)); } } for (DescriptorProto.Builder nested : protoBuilder.getNestedTypeBuilderList()) { replaceType(nested, from, to); } } /** * Returns a version of the passed-in FileDescriptor that contains a ContainedResource message, * which contains only the resource types present in the generated FileDescriptorProto. */ public FileDescriptorProto addContainedResource(FileDescriptorProto fileDescriptor) { DescriptorProto.Builder contained = DescriptorProto.newBuilder() .setName("ContainedResource") .addOneofDecl(OneofDescriptorProto.newBuilder().setName("oneof_resource")); if (packageInfo.getProtoPackage().equals(fhirVersion.coreFhirPackage)) { // When generating contained resources for the core type (resources.proto), // just iterate through all the non-abstract types, assigning tag numbers as you go int tagNumber = 1; for (DescriptorProto type : fileDescriptor.getMessageTypeList()) { if (!type.getOptions().getExtension(Annotations.isAbstractType)) { contained.addField( FieldDescriptorProto.newBuilder() .setName(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, type.getName())) .setNumber(tagNumber++) .setTypeName(type.getName()) .setType(FieldDescriptorProto.Type.TYPE_MESSAGE) .setOneofIndex(0 /* the oneof_resource */) .build()); } } } else { // For derived contained resources, make sure to keep the tag numbers from the base file for // resources that keep the same name. // In other words, if there is a profiled resource called "Patient", it will keep the tag // number of the field in the base contained resources for Patient. // Resources with no exact name matches are assigned field numbers that are greater than // the max used by the base ContainedResource. Descriptor baseContainedResources = fhirVersion.coreTypeMap.get("resources.proto").findMessageTypeByName("ContainedResource"); List<String> resourcesToInclude = fileDescriptor.getMessageTypeList().stream() .filter(desc -> !desc.getOptions().getExtension(Annotations.isAbstractType)) .map(desc -> desc.getName()) .collect(Collectors.toList()); for (FieldDescriptor field : baseContainedResources.getFields()) { String typename = field.getMessageType().getName(); if (resourcesToInclude.contains(typename)) { contained.addField(field.toProto().toBuilder().setTypeName(typename)); resourcesToInclude.remove(typename); } } int tagNumber = Iterables.getLast(baseContainedResources.getFields()).getNumber() + 1; for (String resourceType : resourcesToInclude) { contained.addField( FieldDescriptorProto.newBuilder() .setName(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, resourceType)) .setNumber(tagNumber++) .setTypeName(resourceType) .setType(FieldDescriptorProto.Type.TYPE_MESSAGE) .setOneofIndex(0 /* the oneof_resource */) .build()); } } return fileDescriptor.toBuilder().addMessageType(contained).build(); } private DescriptorProto generateMessage( ElementDefinition currentElement, List<ElementDefinition> elementList, DescriptorProto.Builder builder) { // Get the name of this message. List<String> messageNameParts = Splitter.on('.').splitToList(getContainerType(currentElement, elementList)); String messageName = messageNameParts.get(messageNameParts.size() - 1); builder.setName(messageName); // When generating a descriptor for a primitive type, the value part may already be present. int nextTag = builder.getFieldCount() + 1; // Some repeated fields can have profiled elements in them, that get inlined as fields. // The most common case of this is typed extensions. We defer adding these to the end of the // message, so that non-profiled messages will be binary compatiple with this proto. // Note that the inverse is not true - loading a profiled message bytes into the non-profiled // will result in the data in the typed fields being dropped. List<ElementDefinition> deferredElements = new ArrayList<>(); // Loop over the direct children of this element. for (ElementDefinition element : getDirectChildren(currentElement, elementList)) { if (element.getTypeCount() == 1 && element.getType(0).getCode().getValue().isEmpty()) { // This is a primitive field. Skip it, as primitive fields are handled specially. continue; } // Per spec, the fixed Extension.url on a top-level extension must match the // StructureDefinition url. Since that is already added to the message via the // fhir_structure_definition_url, we can skip over it here. if (element.getBase().getPath().getValue().equals("Extension.url") && element.getFixed().hasUri()) { continue; } if (!isChoiceType(element) && !isSingleType(element)) { throw new IllegalArgumentException( "Illegal field has multiple types but is not a Choice Type:\n" + element); } if (lastIdToken(element.getId().getValue()).slicename != null) { // This is a slie this field until the end of the message. deferredElements.add(element); } else { buildAndAddField(element, elementList, nextTag++, builder); } } for (ElementDefinition deferredElement : deferredElements) { buildAndAddField(deferredElement, elementList, nextTag++, builder); } return builder.build(); } private void buildAndAddField( ElementDefinition element, List<ElementDefinition> elementList, int tag, DescriptorProto.Builder builder) { // Generate the field. If this field doesn't actually exist in this version of the // message, for example, the max attribute is 0, buildField returns null and no field // should be added. FieldDescriptorProto field = buildField(element, elementList, tag); if (field != null) { Optional<DescriptorProto> optionalNestedType = buildNestedTypeIfNeeded(element, elementList, field); if (optionalNestedType.isPresent()) { builder.addNestedType(optionalNestedType.get()); // The nested type is defined in the local package, so replace the core FHIR package // with the local packageName in the field type. field = field .toBuilder() .setTypeName( field .getTypeName() .replace(fhirVersion.coreFhirPackage, packageInfo.getProtoPackage())) .build(); } builder.addField(field); } // TODO: for null fields, emit an "empty" field that just has a comment about the // dropped field, to make it more obvious why numbers are skipped } private Optional<DescriptorProto> buildNestedTypeIfNeeded( ElementDefinition element, List<ElementDefinition> elementList, FieldDescriptorProto field) { Optional<DescriptorProto> choiceType = getChoiceTypeIfRequired(element, elementList, field); if (choiceType.isPresent()) { return Optional.of(choiceType.get()); } // If this is a container type, or a complex internal extension, define the inner message. // If this is a CodeableConcept, check for fixed coding slices. Normally we don't add a // message for CodeableConcept because it's defined as a datatype, but if there are slices // on it we need to generate a custom version. if (isContainer(element) || isComplexInternalExtension(element, elementList)) { return Optional.of(generateMessage(element, elementList, DescriptorProto.newBuilder())); } else if (element.getTypeCount() == 1 && element.getType(0).getCode().getValue().equals("CodeableConcept")) { List<ElementDefinition> codingSlices = getDirectChildren(element, elementList).stream() .filter(candidateElement -> candidateElement.hasSliceName()) .collect(Collectors.toList()); if (!codingSlices.isEmpty()) { return Optional.of(addProfiledCodeableConcept(element, elementList, codingSlices)); } } return Optional.empty(); } // Generates the nested type descriptor proto for a choice type if required. private Optional<DescriptorProto> getChoiceTypeIfRequired( ElementDefinition element, List<ElementDefinition> elementList, FieldDescriptorProto field) { if (isChoiceTypeExtension(element, elementList)) { return Optional.of(makeChoiceType(getExtensionValueElement(element, elementList), field)); } Optional<ElementDefinition> choiceTypeBase = getChoiceTypeBase(element); if (choiceTypeBase.isPresent()) { List<ElementDefinition.TypeRef> baseTypes = choiceTypeBase.get().getTypeList(); Map<String, Integer> baseTypesToIndex = new HashMap<>(); for (int i = 0; i < baseTypes.size(); i++) { String code = baseTypes.get(i).getCode().getValue(); // Only add each code type once. This is only relevant for references, which can appear // multiple times. if (!baseTypesToIndex.containsKey(code)) { baseTypesToIndex.put(code, i); } } DescriptorProto baseChoiceType = makeChoiceType(choiceTypeBase.get(), field); final Set<String> uniqueTypes = new HashSet<>(); List<FieldDescriptorProto> matchingFields = element.getTypeList().stream() .filter(type -> uniqueTypes.add(type.getCode().getValue())) .map(type -> baseChoiceType.getField(baseTypesToIndex.get(type.getCode().getValue()))) .collect(Collectors.toList()); // TODO: If a choice type is a slice of another choice type (not a pure // constraint, but actual slice) we'll need to update the name and type name as well. return Optional.of( baseChoiceType.toBuilder().clearField().addAllField(matchingFields).build()); } if (isChoiceType(element)) { return Optional.of(makeChoiceType(element, field)); } return Optional.empty(); } private DescriptorProto addProfiledCodeableConcept( ElementDefinition element, List<ElementDefinition> elementList, List<ElementDefinition> codingSlices) { String codeableConceptStructDefUrl = CodeableConcept.getDescriptor() .getOptions() .getExtension(Annotations.fhirStructureDefinitionUrl); StructureDefinition codeableConceptDefinition = structDefDataByUrl.get(codeableConceptStructDefUrl).structDef; String fieldType = getQualifiedFieldType(element, elementList).type; DescriptorProto.Builder codeableConceptBuilder = generateMessage( codeableConceptDefinition.getSnapshot().getElementList().get(0), codeableConceptDefinition.getSnapshot().getElementList(), DescriptorProto.newBuilder()) .toBuilder(); codeableConceptBuilder.setName(fieldType.substring(fieldType.lastIndexOf(".") + 1)); codeableConceptBuilder .getOptionsBuilder() .clearExtension(Annotations.structureDefinitionKind) .clearExtension(Annotations.fhirStructureDefinitionUrl) .addExtension(Annotations.fhirProfileBase, codeableConceptStructDefUrl); for (ElementDefinition codingSlice : codingSlices) { String fixedSystem = null; ElementDefinition codeDefinition = null; for (ElementDefinition codingField : getDirectChildren(codingSlice, elementList)) { String basePath = codingField.getBase().getPath().getValue(); if (basePath.equals("Coding.system")) { fixedSystem = codingField.getFixed().getUri().getValue(); } if (basePath.equals("Coding.code")) { codeDefinition = codingField; } } if (fixedSystem == null || codeDefinition == null) { System.out.println( "Warning: Coding slicing not handled because it does not have both a fixed system and a" + " code slice:\n" + codingSlice.getId()); } if (codeDefinition.getFixed().hasCode()) { FieldDescriptorProto.Builder codingField = FieldDescriptorProto.newBuilder() .setType(FieldDescriptorProto.Type.TYPE_MESSAGE) .setTypeName(CodingWithFixedCode.getDescriptor().getFullName()) .setName(toFieldNameCase(codingSlice.getSliceName().getValue())) .setLabel(getFieldSize(codingSlice)) .setNumber(codeableConceptBuilder.getFieldCount() + 1); codingField .getOptionsBuilder() .setExtension(Annotations.fhirInlinedCodingSystem, fixedSystem) .setExtension( Annotations.fhirInlinedCodingCode, codeDefinition.getFixed().getCode().getValue()); codeableConceptBuilder.addField(codingField); } else { FieldDescriptorProto.Builder codingField = FieldDescriptorProto.newBuilder() .setType(FieldDescriptorProto.Type.TYPE_MESSAGE) .setTypeName(CodingWithFixedSystem.getDescriptor().getFullName()) .setName(toFieldNameCase(codingSlice.getSliceName().getValue())) .setLabel(getFieldSize(codingSlice)) .setNumber(codeableConceptBuilder.getFieldCount() + 1); codingField .getOptionsBuilder() .setExtension(Annotations.fhirInlinedCodingSystem, fixedSystem); codeableConceptBuilder.addField(codingField); } } return codeableConceptBuilder.build(); } private static List<ElementDefinition> getDirectChildren( ElementDefinition element, List<ElementDefinition> elementList) { List<String> messagePathParts = Splitter.on('.').splitToList(element.getId().getValue()); return getDescendants(element, elementList).stream() .filter( candidateElement -> { List<String> parts = Splitter.on('.').splitToList(candidateElement.getId().getValue()); // To be a direct child, the id should start with the parent id, and add a single // additional token. return parts.size() == messagePathParts.size() + 1; }) .collect(Collectors.toList()); } private static List<ElementDefinition> getDescendants( ElementDefinition element, List<ElementDefinition> elementList) { // The id of descendants should start with the parent id + at least one more token. String parentIdPrefix = element.getId().getValue() + "."; return elementList.stream() .filter(candidateElement -> candidateElement.getId().getValue().startsWith(parentIdPrefix)) .collect(Collectors.toList()); } private static final ElementDefinition.TypeRef STRING_TYPE = ElementDefinition.TypeRef.newBuilder().setCode(Uri.newBuilder().setValue("string")).build(); /** Generate the primitive value part of a datatype. */ private void generatePrimitiveValue(StructureDefinition def, DescriptorProto.Builder builder) { String defId = def.getId().getValue(); String valueFieldId = defId + ".value"; // Find the value field. ElementDefinition valueElement = getElementDefinitionById(valueFieldId, def.getSnapshot().getElementList()); // If a regex for this primitive type is present, add it as a message-level annotation. if (valueElement.getTypeCount() == 1) { List<ElementDefinitionRegex> regex = ExtensionWrapper.fromExtensionsIn(valueElement.getType(0)) .getMatchingExtensions(ElementDefinitionRegex.getDefaultInstance()); if (regex.size() == 1) { builder.setOptions( builder .getOptions() .toBuilder() .setExtension(Annotations.valueRegex, regex.get(0).getValueString().getValue()) .build()); } } // The value field sometimes has no type. We need to add a fake one here for buildField // to succeed. This will get overridden with the correct time, ElementDefinition elementWithType = valueElement.toBuilder().clearType().addType(STRING_TYPE).build(); FieldDescriptorProto field = buildField( elementWithType, new ArrayList<ElementDefinition>() /* no child ElementDefinition */, 1 /* nextTag */); if (field != null) { if (TIME_LIKE_PRECISION_MAP.containsKey(defId)) { // Handle time-like types differently. EnumDescriptorProto.Builder enumBuilder = PRECISION_ENUM.toBuilder(); for (String value : TIME_LIKE_PRECISION_MAP.get(defId)) { enumBuilder.addValue( EnumValueDescriptorProto.newBuilder() .setName(value) .setNumber(enumBuilder.getValueCount())); } builder.addEnumType(enumBuilder); builder.addField( field .toBuilder() .clearTypeName() .setType(FieldDescriptorProto.Type.TYPE_INT64) .setName("value_us")); if (TYPES_WITH_TIMEZONE.contains(defId)) { builder.addField(TIMEZONE_FIELD); } builder.addField( FieldDescriptorProto.newBuilder() .setName("precision") .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL) .setType(FieldDescriptorProto.Type.TYPE_ENUM) .setTypeName( "." + packageInfo.getProtoPackage() + "." + toFieldTypeCase(defId) + ".Precision") .setNumber(builder.getFieldCount() + 1)); } else { // Handle non-time-like types. // If they don't explicitly appear in the PRIMITIVE_TYPE_OVERRIDES, they are assumed // to be of type TYPE_STRING. FieldDescriptorProto.Type primitiveType = PRIMITIVE_TYPE_OVERRIDES.getOrDefault(defId, FieldDescriptorProto.Type.TYPE_STRING); builder.addField(field.toBuilder().clearTypeName().setType(primitiveType)); } } } /** * Fields of the abstract types Element or BackboneElement are containers, which contain internal * fields (including possibly nested containers). Also, the top-level message is a container. See * https://www.hl7.org/fhir/backboneelement.html for additional information. */ private static boolean isContainer(ElementDefinition element) { if (element.getTypeCount() != 1) { return false; } if (element.getId().getValue().indexOf('.') == -1) { return true; } String type = element.getType(0).getCode().getValue(); return type.equals("BackboneElement") || type.equals("Element"); } /** * Does this element have a single, well-defined type? For example: string, Patient or * Observation.ReferenceRange, as opposed to one of a set of types, most commonly encoded in field * with names like "value[x]". */ private static boolean isSingleType(ElementDefinition element) { // If the type of this element is defined by referencing another element, // then it has a single defined type. if (element.getTypeCount() == 0 && element.hasContentReference()) { return true; } // Loop through the list of types. There may be multiple copies of the same // high-level type, for example, multiple kinds of References. Set<String> types = new HashSet<>(); for (ElementDefinition.TypeRef type : element.getTypeList()) { if (type.hasCode()) { types.add(type.getCode().getValue()); } } return types.size() == 1; } /** Returns true if this ElementDefinition is an extension with a profile. */ private static boolean isExternalExtension(ElementDefinition element) { return element.getTypeCount() == 1 && element.getType(0).getCode().getValue().equals("Extension") && element.getType(0).hasProfile(); } private static boolean isExtensionProfile(StructureDefinition def) { return def.getType().getValue().equals("Extension") && def.getDerivation().getValue() == TypeDerivationRuleCode.Value.CONSTRAINT; } private static boolean isChoiceType(ElementDefinition element) { return lastIdToken(element.getId().getValue()).isChoiceType; } /** Extract the type of a container field, possibly by reference. */ private String getContainerType(ElementDefinition element, List<ElementDefinition> elementList) { if (element.hasContentReference()) { // Find the named element which was referenced. We'll use the type of that element. // Strip the first character from the content reference since it is a '#' String referencedElementId = element.getContentReference().getValue().substring(1); ElementDefinition referencedElement = getElementDefinitionById(referencedElementId, elementList); if (!isContainer(referencedElement)) { throw new IllegalArgumentException( "ContentReference does not reference a container: " + element.getContentReference()); } return getContainerType(referencedElement, elementList); } // The container type is the full type of the message that will be generated (minus package). // It is derived from the id (e.g., Medication.package.content), and these are usually equal // other than casing (e.g., Medication.Package.Content). // However, any parent in the path could have been renamed via a explicit type name extensions. // So, starting with the root, we need to check every element in the path, and append either the // name based on the path token, or an explicit renaming if present. // List we'll build up of actual id parts from the original id, starting from root List<String> idParts = new ArrayList<>(); // Final result we'll build up with one type name part for each id part, starting from root List<String> typeNameParts = new ArrayList<>(); for (String idPart : Splitter.on('.').split(element.getId().getValue())) { idParts.add(idPart); // Find the element corresponding to this chunk of the id. ElementDefinition idChunkElement = getElementDefinitionById(Joiner.on('.').join(idParts), elementList); // Check for explicit renamings on that element. List<ElementDefinitionExplicitTypeName> explicitTypeNames = ExtensionWrapper.fromExtensionsIn(idChunkElement) .getMatchingExtensions(ElementDefinitionExplicitTypeName.getDefaultInstance()); // Add explicit type name if present. Otherwise, use the field_name, converted to FieldType // casing, as the submessage name. String typeNamePart = explicitTypeNames.isEmpty() ? toFieldTypeCase(getJsonNameForElement(idChunkElement)) : explicitTypeNames.get(0).getValueString().getValue(); // We can't reuse field names in multiple parts in the path (e.g., Foo.bar.bar.baz) if (typeNameParts.contains(typeNamePart) || (!typeNameParts.isEmpty() && (typeNamePart.equals("Timing") || typeNamePart.equals("Age")))) { typeNamePart = typeNamePart + "Type"; } typeNameParts.add(typeNamePart); } return Joiner.on('.').join(typeNameParts); } /** * Gets the field type and package of a potentially complex element. This handles choice types, * types that reference other elements, references, profiles, etc. */ private QualifiedType getQualifiedFieldType( ElementDefinition element, List<ElementDefinition> elementList) { if (isContainer(element) || isChoiceType(element)) { return new QualifiedType( getContainerType(element, elementList), packageInfo.getProtoPackage()); } else if (element.hasContentReference()) { // Get the type for this container from a named reference to another element. return new QualifiedType( getContainerType(element, elementList), isLocalContentReference(element) ? packageInfo.getProtoPackage() : fhirVersion.coreFhirPackage); } else if (isExtensionBackboneElement(element)) { return getInternalExtensionType(element, elementList); } else if (element.getType(0).getCode().getValue().equals("Reference")) { return new QualifiedType( USE_TYPED_REFERENCES ? getTypedReferenceName(element.getTypeList()) : "Reference", fhirVersion.coreFhirPackage); } else { if (element.getTypeCount() > 1) { throw new IllegalArgumentException( "Unknown multiple type definition on element: " + element.getId()); } // Note: this is the "fhir type", e.g., Resource, BackboneElement, boolean, // not the field type name. String normalizedFhirTypeName = normalizeType(Iterables.getOnlyElement(element.getTypeList())); if (descendantsHaveSlices(element, elementList)) { // This is not a backbone element, but it has children that have slices. This means we // cannot use the "stock" FHIR datatype here. // A common example of this is CodeableConcepts. These are not themselves sliced, but the // repeated coding field on CodeableConcept can be. // This means we have to generate a nested CodeableConcept message that has these additional // fields. String containerType = getContainerType(element, elementList); int lastDotIndex = containerType.lastIndexOf("."); return new QualifiedType( containerType.substring(0, lastDotIndex + 1) + normalizedFhirTypeName + "For" + containerType.substring(lastDotIndex + 1), packageInfo.getProtoPackage()); } if (normalizedFhirTypeName.equals("Resource")) { // We represent "Resource" FHIR types as "ContainedResource" if (packageInfo.getLocalContainedResource()) { return new QualifiedType("ContainedResource", packageInfo.getProtoPackage()); } if (!packageInfo.getContainedResourcePackage().isEmpty()) { return new QualifiedType("ContainedResource", packageInfo.getContainedResourcePackage()); } return new QualifiedType("ContainedResource", fhirVersion.coreFhirPackage); } if (normalizedFhirTypeName.equals("Code")) { Optional<Descriptor> valueSetType = getBindingValueSetType(element); if (valueSetType.isPresent()) { return new QualifiedType( valueSetType.get().getName(), valueSetType.get().getFile().getPackage()); } } return new QualifiedType(normalizedFhirTypeName, fhirVersion.coreFhirPackage); } } private Optional<Descriptor> getBindingValueSetType(ElementDefinition element) { String url = element.getBinding().getValueSet().getReference().getUri().getValue(); if (url.isEmpty()) { url = element.getBinding().getValueSet().getUri().getValue(); } if (url.isEmpty()) { return Optional.empty(); } if (valueSetTypesByUrl.containsKey(url)) { return Optional.of(valueSetTypesByUrl.get(url)); } // TODO: Throw an error in strict mode. return Optional.empty(); } /** Build a single field for the proto. */ private FieldDescriptorProto buildField( ElementDefinition element, List<ElementDefinition> elementList, int nextTag) { FieldDescriptorProto.Label fieldSize = getFieldSize(element); if (fieldSize == null) { // This field has a max size of zero. Do not emit a field. return null; } FieldOptions.Builder options = FieldOptions.newBuilder(); // Add a short description of the field. if (element.hasShort()) { options.setExtension(Annotations.fieldDescription, element.getShort().getValue()); } // Is this field required? if (element.getMin().getValue() == 1) { options.setExtension( Annotations.validationRequirement, Annotations.Requirement.REQUIRED_BY_FHIR); } else if (element.getMin().getValue() != 0) { System.out.println("Unexpected minimum field count: " + element.getMin().getValue()); } String jsonFieldNameString = getJsonNameForElement(element); if (isExternalExtension(element)) { // This is an extension with a type defined by an external profile. // If we know about it, we'll inline a field for it. String profileUrl = element.getType(0).getProfile().getValue(); StructureDefinitionData profileData = structDefDataByUrl.get(profileUrl); if (profileData == null) { // Unrecognized url. // TODO: add a lenient mode that just ignores this extension. throw new IllegalArgumentException("Encountered unknown extension url: " + profileUrl); } jsonFieldNameString = resolveSliceNameConflicts(jsonFieldNameString, element, elementList); options.setExtension( Annotations.fhirInlinedExtensionUrl, element.getType(0).getProfile().getValue()); return buildFieldInternal( jsonFieldNameString, profileData.inlineType, profileData.protoPackage, nextTag, fieldSize, options.build()) .build(); } Optional<ElementDefinition> choiceTypeBase = getChoiceTypeBase(element); if (choiceTypeBase.isPresent()) { ElementDefinition choiceTypeBaseElement = choiceTypeBase.get(); String jsonName = getJsonNameForElement(choiceTypeBaseElement); String containerType = getContainerType(element, elementList); containerType = containerType.substring(0, containerType.lastIndexOf(".") + 1) + toFieldTypeCase(jsonName); return buildFieldInternal( jsonName, containerType, packageInfo.getProtoPackage(), nextTag, fieldSize, options.build()) .build(); } if (isExtensionBackboneElement(element)) { // This is a internally-defined extension slice that will be inlined as a nested type for // complex extensions, or as a primitive type simple extensions. // Since extensions are sliced on url, the url for the extension matches the slicename. // Since the field name is the slice name wherever possible, annotating the field with the // inlined extension url is usually redundant. // We will only add it if we have to rename the field name. This can happen if the slice // name is reserved (e.g., string or optional), or if the slice name conflicts with a field // on the base element (e.g., id or url), or if the slicename/url are in an unexpected casing. // If, for any reason, the urlField is not the camelCase version of the lower_underscore // field_name, add an annotation with the explicit name. jsonFieldNameString = resolveSliceNameConflicts(jsonFieldNameString, element, elementList); String url = getElementDefinitionById(element.getId().getValue() + ".url", elementList) .getFixed() .getUri() .getValue(); if (!jsonFieldNameString.equals(url)) { options.setExtension(Annotations.fhirInlinedExtensionUrl, url); } } QualifiedType fieldType = getQualifiedFieldType(element, elementList); boolean isChoiceType = isChoiceType(element) || isChoiceTypeExtension(element, elementList); // Add typed reference options if (!isChoiceType && element.getTypeCount() > 0 && element.getType(0).getCode().getValue().equals("Reference")) { for (ElementDefinition.TypeRef type : element.getTypeList()) { String referenceType = type.getTargetProfile().getValue(); if (!referenceType.isEmpty()) { addReferenceType(options, referenceType); } } } // Add any FHIRPath constraints from the definition. List<String> expressions = element.getConstraintList().stream() .filter(constraint -> constraint.hasExpression()) .map(constraint -> constraint.getExpression().getValue()) .filter(expression -> !EXCLUDED_FHIR_CONSTRAINTS.contains(expression)) .collect(Collectors.toList()); if (!expressions.isEmpty()) { options.setExtension(Annotations.fhirPathConstraint, expressions); } return buildFieldInternal( jsonFieldNameString, fieldType.type, fieldType.packageName, nextTag, fieldSize, options.build()) .build(); } private FieldDescriptorProto.Label getFieldSize(ElementDefinition element) { if (element.getMax().getValue().equals("0")) { // This field doesn't actually exist. return null; } return element.getMax().getValue().equals("1") ? FieldDescriptorProto.Label.LABEL_OPTIONAL : FieldDescriptorProto.Label.LABEL_REPEATED; } private boolean isLocalContentReference(ElementDefinition element) { // TODO: more sophisticated logic. This wouldn't handle references to fields in // other elements in a non-core package if (!element.hasContentReference()) { return false; } String rootType = Splitter.on(".").limit(2).splitToList(element.getId().getValue()).get(0); return element.getContentReference().getValue().startsWith("#" + rootType); } /** * Returns the field name that should be used for an element, in jsonCase. If element is a slice, * uses that slice name. Since the id token slice name is all-lowercase, uses the SliceName field. * Otherwise, uses the last token's pathpart. Logs a warning if the slice name in the id token * does not match the SliceName field. */ // TODO: Handle reslices. Could be as easy as adding it to the end of SliceName. private String getJsonNameForElement(ElementDefinition element) { IdToken lastToken = lastIdToken(element.getId().getValue()); if (lastToken.slicename == null) { return toJsonCase(lastToken.pathpart); } String sliceName = element.getSliceName().getValue(); if (!lastToken.slicename.equals(sliceName.toLowerCase())) { // TODO: pull this into a common validator that runs ealier. logDiscrepancies( "Warning: Inconsistent slice name for element with id " + element.getId().getValue() + " and slicename " + element.getSliceName()); } return toJsonCase(sliceName); } private static boolean descendantsHaveSlices( ElementDefinition element, List<ElementDefinition> elementList) { return getDescendants(element, elementList).stream() .anyMatch(candidate -> candidate.hasSliceName()); } // Given a potential slice field name and an element, returns true if that slice name would // conflict with the field name of any siblings to that elements. // TODO: This only checks against non-slice names. Theoretically, you could have // two identically-named slices of different base fields. private static String resolveSliceNameConflicts( String jsonFieldName, ElementDefinition element, List<ElementDefinition> elementList) { if (RESERVED_FIELD_NAMES.contains(jsonFieldName)) { return jsonFieldName + "Slice"; } String elementId = element.getId().getValue(); int lastDotIndex = elementId.lastIndexOf('.'); if (lastDotIndex == -1) { // This is a profile on a top-level Element. There can't be any conflicts. return jsonFieldName; } String parentElementId = elementId.substring(0, lastDotIndex); List<ElementDefinition> elementsWithIdsConflictingWithSliceName = getDirectChildren(getElementDefinitionById(parentElementId, elementList), elementList) .stream() .filter( candidateElement -> toFieldNameCase(lastIdToken(candidateElement.getId().getValue()).pathpart) .equals(jsonFieldName) && !candidateElement.getBase().getPath().getValue().equals("Extension.url")) .collect(Collectors.toList()); return elementsWithIdsConflictingWithSliceName.isEmpty() ? jsonFieldName : jsonFieldName + "Slice"; } // TODO: memoize private Optional<ElementDefinition> getChoiceTypeBase(ElementDefinition element) { if (!element.hasBase()) { return Optional.empty(); } String basePath = element.getBase().getPath().getValue(); if (basePath.equals("Extension.value[x]")) { // Extension value fields extend from choice-types, but since single-typed extensions will be // inlined as that type anyway, there's no point in generating a choice type for them. return Optional.empty(); } String baseType = Splitter.on(".").splitToList(basePath).get(0); if (basePath.endsWith("[x]")) { ElementDefinition choiceTypeBase = getElementDefinitionById( basePath, baseStructDefsById.get(baseType).getSnapshot().getElementList()); return Optional.of(choiceTypeBase); } if (!baseType.equals("Element")) { // Traverse up the tree to check for a choice type in this element's ancestry. if (!baseStructDefsById.containsKey(baseType)) { throw new IllegalArgumentException("Unknown StructureDefinition id: " + baseType); } return getChoiceTypeBase( getElementDefinitionById( basePath, baseStructDefsById.get(baseType).getSnapshot().getElementList())); } return Optional.empty(); } /** Add a choice type container message to the proto. */ private DescriptorProto makeChoiceType(ElementDefinition element, FieldDescriptorProto field) { List<String> typeNameParts = Splitter.on('.').splitToList(field.getTypeName()); DescriptorProto.Builder choiceType = DescriptorProto.newBuilder().setName(typeNameParts.get(typeNameParts.size() - 1)); choiceType.getOptionsBuilder().setExtension(Annotations.isChoiceType, true); OneofDescriptorProto.Builder oneof = choiceType.addOneofDeclBuilder().setName(field.getName()); int nextTag = 1; // Group types. List<ElementDefinition.TypeRef> types = new ArrayList<>(); List<String> referenceTypes = new ArrayList<>(); Set<String> foundTypes = new HashSet<>(); for (ElementDefinition.TypeRef type : element.getTypeList()) { if (!foundTypes.contains(type.getCode().getValue())) { types.add(type); foundTypes.add(type.getCode().getValue()); } if (type.getCode().getValue().equals("Reference")) { String referenceType = type.getTargetProfile().getValue(); if (!referenceType.isEmpty()) { referenceTypes.add(referenceType); } } } for (ElementDefinition.TypeRef t : types) { String fieldType = normalizeType(t); String fieldName = t.getCode().getValue(); // TODO: This assumes all types in a oneof are core FHIR types. In order to // support custom types, we'll need to load the structure definition for the type and check // against knownStructureDefinitionPackages FieldOptions.Builder options = FieldOptions.newBuilder(); if (fieldName.equals("Reference")) { for (String referenceType : referenceTypes) { addReferenceType(options, referenceType); } } FieldDescriptorProto.Builder fieldBuilder = buildFieldInternal( fieldName, fieldType, fhirVersion.coreFhirPackage, nextTag++, FieldDescriptorProto.Label.LABEL_OPTIONAL, options.build()) .setOneofIndex(0); // TODO: change the oneof name to avoid this. if (fieldBuilder.getName().equals(oneof.getName())) { fieldBuilder.setJsonName(fieldBuilder.getName()); fieldBuilder.setName(fieldBuilder.getName() + "_value"); } choiceType.addField(fieldBuilder); } return choiceType.build(); } private void addReferenceType(FieldOptions.Builder options, String referenceUrl) { options.addExtension( Annotations.validReferenceType, getBaseStructureDefinitionData(referenceUrl).inlineType); } /** * Given a structure definition url, returns the base (FHIR) structure definition data for that * type. */ private StructureDefinitionData getBaseStructureDefinitionData(String url) { StructureDefinitionData defData = structDefDataByUrl.get(url); while (isProfile(defData.structDef)) { defData = structDefDataByUrl.get(defData.structDef.getBaseDefinition().getValue()); } return defData; } private FieldDescriptorProto.Builder buildFieldInternal( String fieldJsonName, String fieldType, String fieldPackage, int tag, FieldDescriptorProto.Label size, FieldOptions options) { FieldDescriptorProto.Builder builder = FieldDescriptorProto.newBuilder() .setNumber(tag) .setType(FieldDescriptorProto.Type.TYPE_MESSAGE); builder.setLabel(size); List<String> fieldTypeParts = new ArrayList<>(); for (String part : Splitter.on('.').split(fieldType)) { fieldTypeParts.add(part); } builder.setTypeName("." + fieldPackage + "." + Joiner.on('.').join(fieldTypeParts)); if (RESERVED_FIELD_NAMES.contains(fieldJsonName)) { builder.setName(toFieldNameCase(fieldJsonName + "Value")).setJsonName(fieldJsonName); } else { builder.setName(toFieldNameCase(fieldJsonName)); } // Add annotations. if (!options.equals(FieldOptions.getDefaultInstance())) { builder.setOptions(options); } return builder; } private String normalizeType(ElementDefinition.TypeRef type) { if (!type.hasProfile()) { return toFieldTypeCase(type.getCode().getValue()); } else if (structDefDataByUrl.containsKey(type.getProfile().getValue())) { return structDefDataByUrl.get(type.getProfile().getValue()).inlineType; } else { throw new IllegalArgumentException( "Unable to deduce typename for profile: " + type.getProfile().getValue()); } } private static final Pattern WORD_BREAK_PATTERN = Pattern.compile("[-_ ]([A-Za-z])"); // Converts a FHIR id strings to UpperCamelCasing for FieldTypes using a regex pattern that // considers hyphen, underscore and space to be word breaks. private static String toFieldTypeCase(String type) { String normalizedType = type; if (Character.isLowerCase(type.charAt(0))) { normalizedType = type.substring(0, 1).toUpperCase() + type.substring(1); } Matcher matcher = WORD_BREAK_PATTERN.matcher(normalizedType); StringBuffer typeBuilder = new StringBuffer(); boolean foundMatch = false; while (matcher.find()) { foundMatch = true; matcher.appendReplacement(typeBuilder, matcher.group(1).toUpperCase()); } return foundMatch ? matcher.appendTail(typeBuilder).toString() : normalizedType; } private static String toFieldNameCase(String fieldName) { // Make sure the field name is snake case, as required by the proto style guide. String normalizedFieldName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, fieldName); // TODO: add more normalization here if necessary. I think this is enough for now. return normalizedFieldName; } private static String toJsonCase(String fieldName) { if (fieldName.contains("-")) { return CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, fieldName); } if (fieldName.contains("_")) { return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, fieldName); } return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, fieldName); } // Returns the only element in the list matching a given id. // Throws IllegalArgumentException if zero or more than one matching elements are found. private static ElementDefinition getElementDefinitionById( String id, List<ElementDefinition> elements) { return elements.stream() .filter(element -> element.getId().getValue().equals(id)) .collect(MoreCollectors.toOptional()) .orElseThrow(() -> new IllegalArgumentException("No element with id: " + id)); } private String getTypedReferenceName(List<ElementDefinition.TypeRef> typeList) { // Sort. Set<String> refTypes = new TreeSet<>(); for (ElementDefinition.TypeRef type : typeList) { refTypes.add(type.getTargetProfile().getValue()); } String refType = null; for (String r : refTypes) { if (!r.isEmpty()) { if (structDefDataByUrl.containsKey(r)) { r = structDefDataByUrl.get(r).inlineType; } else { throw new IllegalArgumentException("Unsupported reference profile: " + r); } if (refType == null) { refType = r; } else { refType = refType + "Or" + r; } } } if (refType != null && !refType.equals("Resource")) { // Specialize the reference type. return refType + "Reference"; } return "Reference"; } private static boolean isExtensionBackboneElement(ElementDefinition element) { // An element is an extension element if either // A) it is a root element with id "Extension" and is a derivation from a base element or // B) it is a slice on an extension that is not defined by an external profile. return (element.getId().getValue().equals("Extension") && element.hasBase()) || (element.getBase().getPath().getValue().endsWith(".extension") && lastIdToken(element.getId().getValue()).slicename != null && !element.getType(0).hasProfile()); } // Returns the QualifiedType (type + package) of a simple extension as a string. private QualifiedType getSimpleExtensionDefinitionType(StructureDefinition def) { if (!isExtensionProfile(def)) { throw new IllegalArgumentException( "StructureDefinition is not an extension profile: " + def.getId().getValue()); } ElementDefinition element = def.getSnapshot().getElement(0); List<ElementDefinition> elementList = def.getSnapshot().getElementList(); if (isSingleTypedExtensionDefinition(def)) { return getSimpleInternalExtensionType(element, elementList); } if (isChoiceTypeExtension(element, elementList)) { return new QualifiedType(getTypeName(def) + ".Value", packageInfo.getProtoPackage()); } throw new IllegalArgumentException( "StructureDefinition is not a simple extension: " + def.getId().getValue()); } private static ElementDefinition getExtensionValueElement( ElementDefinition element, List<ElementDefinition> elementList) { for (ElementDefinition child : getDirectChildren(element, elementList)) { if (child.getBase().getPath().getValue().equals("Extension.value[x]")) { return child; } } throw new IllegalArgumentException( "Element " + element.getId().getValue() + " has no value element"); } private QualifiedType getSimpleInternalExtensionType( ElementDefinition element, List<ElementDefinition> elementList) { ElementDefinition valueElement = getExtensionValueElement(element, elementList); if (valueElement.getMax().getValue().equals("0")) { // There is no value element, this is a complex extension return null; } if (getDistinctTypeCount(valueElement) == 1) { // This is a primitive extension with a single type String rawType = valueElement.getType(0).getCode().getValue(); if (rawType.equals("code")) { Optional<Descriptor> valueSetType = getBindingValueSetType(valueElement); if (valueSetType.isPresent()) { return new QualifiedType( valueSetType.get().getName(), valueSetType.get().getFile().getPackage()); } } return new QualifiedType(toFieldTypeCase(rawType), fhirVersion.coreFhirPackage); } // This is a choice-type extension that will be inlined as a message. return new QualifiedType(getContainerType(element, elementList), packageInfo.getProtoPackage()); } private static long getDistinctTypeCount(ElementDefinition element) { // Don't do fancier logic if fast logic is sufficient. if (element.getTypeCount() < 2 || USE_TYPED_REFERENCES) { return element.getTypeCount(); } return element.getTypeList().stream().map(type -> type.getCode()).distinct().count(); } private static boolean isChoiceTypeExtension( ElementDefinition element, List<ElementDefinition> elementList) { if (!isExtensionBackboneElement(element)) { return false; } ElementDefinition valueElement = getExtensionValueElement(element, elementList); return !valueElement.getMax().getValue().equals("0") && getDistinctTypeCount(valueElement) > 1; } // TODO: Clean up some of the terminology - 'internal' is misleading here. private static boolean isSimpleInternalExtension( ElementDefinition element, List<ElementDefinition> elementList) { return isExtensionBackboneElement(element) && !getExtensionValueElement(element, elementList).getMax().getValue().equals("0"); } private boolean isComplexInternalExtension( ElementDefinition element, List<ElementDefinition> elementList) { return isExtensionBackboneElement(element) && !isSimpleInternalExtension(element, elementList); } private boolean isSingleTypedExtensionDefinition(StructureDefinition def) { ElementDefinition element = def.getSnapshot().getElement(0); List<ElementDefinition> elementList = def.getSnapshot().getElementList(); return isSimpleInternalExtension(element, elementList) && getDistinctTypeCount(getExtensionValueElement(element, elementList)) == 1; } /** * Returns the type that should be used for an internal extension. If this is a simple internal * extension, uses the appropriate primitive type. If this is a complex internal extension, treats * the element like a backbone container. */ private QualifiedType getInternalExtensionType( ElementDefinition element, List<ElementDefinition> elementList) { return isSimpleInternalExtension(element, elementList) ? getSimpleInternalExtensionType(element, elementList) : new QualifiedType(getContainerType(element, elementList), packageInfo.getProtoPackage()); } /** * Derives a message type for a Profile. Uses the name field from the StructureDefinition. If the * StructureDefinition has a context indicating a single Element type, that type is used as a * prefix. If the element is a simple extension, returns the type defined by the extension. */ private static String getProfileTypeName(StructureDefinition def) { String name = toFieldTypeCase(def.getName().getValue()); Set<String> contexts = new HashSet<>(); Splitter splitter = Splitter.on('.').limit(2); for (com.google.fhir.stu3.proto.String context : def.getContextList()) { // Only interest in the top-level resource. contexts.add(splitter.splitToList(context.getValue()).get(0)); } if (contexts.size() == 1) { String context = Iterables.getOnlyElement(contexts); if (!context.equals("*")) { name = context + name; } } return toFieldTypeCase(name); } private static final boolean PRINT_SNAPSHOT_DISCREPANCIES = false; private static void logDiscrepancies(String msg) { if (PRINT_SNAPSHOT_DISCREPANCIES) { System.out.println(msg); } } // We generate protos based on the "Snapshot" view of the proto, but these are often // generated off of the "Differential" view, which can be buggy. So, before processing the // snapshot, do a pass over the differential and correct any inconsistencies in the snapshot. private static StructureDefinition reconcileSnapshotAndDifferential(StructureDefinition def) { // Generate a map from (element id) -> (element) for all elements in the Differential view. Map<String, ElementDefinition> diffs = def.getDifferential() .getElementList() .stream() .collect( Collectors.toMap((element) -> element.getId().getValue(), Function.identity())); StructureDefinition.Builder defBuilder = def.toBuilder(); defBuilder.getSnapshotBuilder().clearElement(); for (ElementDefinition element : def.getSnapshot().getElementList()) { ElementDefinition elementDiffs = diffs.get(element.getId().getValue()); defBuilder .getSnapshotBuilder() .addElement( elementDiffs == null ? element : (ElementDefinition) reconcileMessage( element, elementDiffs, def.getId().getValue(), element.getId().getValue(), "")); } return defBuilder.build(); } private static Message reconcileMessage( Message snapshot, Message differential, String structureDefinitionId, String elementId, String fieldpath) { Message.Builder reconciledElement = snapshot.toBuilder(); for (FieldDescriptor field : reconciledElement.getDescriptorForType().getFields()) { String subFieldpath = (fieldpath.isEmpty() ? "" : (fieldpath + ".")) + field.getJsonName(); if (!field.isRepeated() && differential.hasField(field) && !differential.getField(field).equals(reconciledElement.getField(field))) { if (AnnotationUtils.isPrimitiveType(field.getMessageType())) { reconciledElement.setField(field, differential.getField(field)); logDiscrepancies( "Warning: found inconsistent Snapshot for " + structureDefinitionId + ". Field \"" + subFieldpath + "\" on " + elementId + " has snapshot\n" + snapshot.getField(field) + "but differential\n" + differential.getField(field) + "Using differential value for protogeneration.\n"); } else { reconciledElement.setField( field, reconcileMessage( (Message) snapshot.getField(field), (Message) differential.getField(field), structureDefinitionId, elementId, subFieldpath)); } } else if (field.isRepeated()) { // For repeated fields, make sure each element in the differential appears in the snapshot. Set<Message> valuesInSnapshot = new HashSet<>(); for (int i = 0; i < snapshot.getRepeatedFieldCount(field); i++) { valuesInSnapshot.add((Message) snapshot.getRepeatedField(field, i)); } for (int i = 0; i < differential.getRepeatedFieldCount(field); i++) { Message differentialValue = (Message) differential.getRepeatedField(field, i); if (!valuesInSnapshot.contains(differentialValue)) { logDiscrepancies( "Warning: found inconsistent Snapshot for " + structureDefinitionId + ". Field \"" + subFieldpath + "\" on " + elementId + " has value on differential that is missing from snapshot:\n" + differentialValue + "Adding in for use in protogeneration.\n"); reconciledElement.addRepeatedField(field, differentialValue); } } } } return reconciledElement.build(); } }
3e0a07edd8d530a11530b06bee823a4de2aebe5a
615
java
Java
src/exception/ExceptionApiDemo.java
juststrive007/JAVA_SE
aa3acf6f243d9d8982f4e0f3a247a2c981da58bc
[ "Apache-2.0" ]
1
2020-12-14T15:10:01.000Z
2020-12-14T15:10:01.000Z
src/exception/ExceptionApiDemo.java
juststrive007/JAVA_SE
aa3acf6f243d9d8982f4e0f3a247a2c981da58bc
[ "Apache-2.0" ]
null
null
null
src/exception/ExceptionApiDemo.java
juststrive007/JAVA_SE
aa3acf6f243d9d8982f4e0f3a247a2c981da58bc
[ "Apache-2.0" ]
null
null
null
22.777778
55
0.55935
4,260
package exception; import org.omg.Messaging.SYNC_WITH_TRANSPORT; /** * 异常常见的方法 * @author wm */ public class ExceptionApiDemo { public static void main(String[] args) { System.out.println("program start"); try { String line="a"; System.out.println(Integer.parseInt(line)); }catch (Exception e){ System.out.println("error"); //输出错误堆栈信息 e.printStackTrace(); //获取错误消息 String message=e.getMessage(); System.out.println(message); } System.out.println("program end"); } }
3e0a0953d0a1c7ebf377b65b482540072350a5db
863
java
Java
app/src/main/java/wyman/com/civetweather/MainActivity.java
Wyman798/civetweather
14f37ecfa47716fb5519996307a0e9c805962081
[ "Apache-2.0" ]
1
2019-03-26T13:45:37.000Z
2019-03-26T13:45:37.000Z
app/src/main/java/wyman/com/civetweather/MainActivity.java
Wyman798/civetweather
14f37ecfa47716fb5519996307a0e9c805962081
[ "Apache-2.0" ]
null
null
null
app/src/main/java/wyman/com/civetweather/MainActivity.java
Wyman798/civetweather
14f37ecfa47716fb5519996307a0e9c805962081
[ "Apache-2.0" ]
null
null
null
31.962963
86
0.726535
4,261
package wyman.com.civetweather; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (BuildConfig.DEBUG) Log.d("MainActivity", "欢迎来到猫屎天气"); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (prefs.getString("weather",null) != null){ Intent intent = new Intent(this,WeatherActivity.class); startActivity(intent); finish(); } } }
3e0a0992e7d65daa3606b553fe398bf33604bd2a
242
java
Java
src/main/java/com/redsoft/idea/plugin/yapiv2/api/PathResolver.java
aqiu202/RedsoftYapiUpload
b51bc50c44d9133db7da57e0ddcc0debbf389b72
[ "Apache-2.0" ]
56
2019-08-03T07:33:13.000Z
2022-03-29T06:13:44.000Z
src/main/java/com/redsoft/idea/plugin/yapiv2/api/PathResolver.java
aqiu202/RedsoftYapiUpload
b51bc50c44d9133db7da57e0ddcc0debbf389b72
[ "Apache-2.0" ]
19
2020-04-28T03:00:34.000Z
2022-03-29T06:17:13.000Z
src/main/java/com/redsoft/idea/plugin/yapiv2/api/PathResolver.java
aqiu202/RedsoftYapiUpload
b51bc50c44d9133db7da57e0ddcc0debbf389b72
[ "Apache-2.0" ]
16
2020-06-30T12:28:56.000Z
2022-02-22T07:14:23.000Z
20.166667
56
0.743802
4,262
package com.redsoft.idea.plugin.yapiv2.api; import com.redsoft.idea.plugin.yapiv2.base.BaseResolver; /** * <b>路由相关信息解析(包括类、方法的路由解析和路由前缀添加)</b> * @author aqiu 2020/5/12 10:59 上午 **/ public interface PathResolver extends BaseResolver { }
3e0a09c30d0737cfef301eb05db52d4dd1c82214
764
java
Java
src/main/java/io/choerodon/iam/api/vo/AssignAdminVO.java
choerodon/base-service
50d39cffb2c306757b12c3af6dab97443386cfa4
[ "Apache-2.0" ]
5
2020-03-20T02:31:52.000Z
2020-07-25T02:35:23.000Z
src/main/java/io/choerodon/iam/api/vo/AssignAdminVO.java
choerodon/base-service
50d39cffb2c306757b12c3af6dab97443386cfa4
[ "Apache-2.0" ]
2
2020-04-13T02:46:40.000Z
2020-07-30T07:13:51.000Z
src/main/java/io/choerodon/iam/api/vo/AssignAdminVO.java
choerodon/base-service
50d39cffb2c306757b12c3af6dab97443386cfa4
[ "Apache-2.0" ]
15
2019-12-05T01:05:49.000Z
2020-09-27T02:43:39.000Z
19.589744
58
0.634817
4,263
package io.choerodon.iam.api.vo; import java.util.List; import io.swagger.annotations.ApiModelProperty; /** * 批量分配用户为admin时发送的saga载体 * * @author zmf * @since 19-12-24 */ public class AssignAdminVO { @ApiModelProperty("分配为admin的用户id") private List<Long> adminUserIds; public AssignAdminVO() { } public AssignAdminVO(List<Long> adminUserIds) { this.adminUserIds = adminUserIds; } public List<Long> getAdminUserIds() { return adminUserIds; } public void setAdminUserIds(List<Long> adminUserIds) { this.adminUserIds = adminUserIds; } @Override public String toString() { return "AssignAdminVO{" + "adminUserIds=" + adminUserIds + '}'; } }
3e0a0cc750d43c25e7eb1a38ad72766155fabdb1
443
java
Java
examples/android/src/dagger/application/DaggerApplication.java
christopherperry/dagger
2bbd60425946744e6057658ca0e1b351672ece0f
[ "Apache-2.0" ]
1
2019-10-25T23:15:35.000Z
2019-10-25T23:15:35.000Z
examples/android/src/dagger/application/DaggerApplication.java
christopherperry/dagger
2bbd60425946744e6057658ca0e1b351672ece0f
[ "Apache-2.0" ]
null
null
null
examples/android/src/dagger/application/DaggerApplication.java
christopherperry/dagger
2bbd60425946744e6057658ca0e1b351672ece0f
[ "Apache-2.0" ]
null
null
null
22.15
66
0.76298
4,264
package dagger.application; import android.app.Application; import dagger.ObjectGraph; import dagger.module.ApplicationModule; public class DaggerApplication extends Application { private static ObjectGraph objectGraph; @Override public void onCreate() { super.onCreate(); objectGraph = ObjectGraph.create(new ApplicationModule(this)); } public static <T> void inject(T instance) { objectGraph.inject(instance); } }
3e0a0cfb0b00146e00f9ec586d76d346cf74922f
952
java
Java
3rd/src/ch5_04/Cal.java
trattoria/java8
075dffaaa6ddcbace4430381d444045748cff91c
[ "MIT" ]
null
null
null
3rd/src/ch5_04/Cal.java
trattoria/java8
075dffaaa6ddcbace4430381d444045748cff91c
[ "MIT" ]
null
null
null
3rd/src/ch5_04/Cal.java
trattoria/java8
075dffaaa6ddcbace4430381d444045748cff91c
[ "MIT" ]
null
null
null
19.428571
91
0.632353
4,265
package ch5_04; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.YearMonth; /** * Q:ある月のカレンダーを表示するUnixのcalと同じプログラムを書きなさい。 * */ public class Cal { /** * * @param args */ public static void main(String[] args) { // 細かなコマンドライン引数のチェックは省略 if (args.length > 3) { // マニュアル表示して終了。マニュアル表示は省略。 System.exit(1); } YearMonth yearMonth = YearMonth.of(Integer.parseInt(args[1]), Integer.parseInt(args[0])); LocalDate day = yearMonth.atDay(1); LocalDate lastDay = yearMonth.atEndOfMonth(); // 先頭行をインデント int n = day.getDayOfWeek().getValue() - 1; for (int i = 0; i < n; i++) { System.out.print(" "); } // 日付を右寄せ while (day.isBefore(lastDay) || day.isEqual(lastDay)) { System.out.printf("%2d", day.getDayOfMonth()); // 1文字空ける or 改行 if (day.getDayOfWeek() == DayOfWeek.SUNDAY) { System.out.println(); } else { System.out.print(" "); } day = day.plusDays(1); } } }
3e0a0e164dd7825af6f174fcaf0f3cbc7a26edc0
5,723
java
Java
java/java-impl/src/com/intellij/ide/hierarchy/method/MethodHierarchyNodeDescriptor.java
liveqmock/platform-tools-idea
1c4b76108add6110898a7e3f8f70b970e352d3d4
[ "Apache-2.0" ]
2
2015-05-08T15:07:10.000Z
2022-03-09T05:47:53.000Z
java/java-impl/src/com/intellij/ide/hierarchy/method/MethodHierarchyNodeDescriptor.java
lshain-android-source/tools-idea
b37108d841684bcc2af45a2539b75dd62c4e283c
[ "Apache-2.0" ]
null
null
null
java/java-impl/src/com/intellij/ide/hierarchy/method/MethodHierarchyNodeDescriptor.java
lshain-android-source/tools-idea
b37108d841684bcc2af45a2539b75dd62c4e283c
[ "Apache-2.0" ]
2
2017-04-24T15:48:40.000Z
2022-03-09T05:48:05.000Z
32.890805
152
0.728289
4,266
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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.intellij.ide.hierarchy.method; import com.intellij.icons.AllIcons; import com.intellij.ide.IdeBundle; import com.intellij.ide.hierarchy.HierarchyNodeDescriptor; import com.intellij.ide.hierarchy.JavaHierarchyUtil; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ui.util.CompositeAppearance; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Iconable; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiModifier; import com.intellij.psi.presentation.java.ClassPresentationUtil; import com.intellij.ui.LayeredIcon; import com.intellij.ui.RowIcon; import javax.swing.*; import java.awt.*; public final class MethodHierarchyNodeDescriptor extends HierarchyNodeDescriptor { private Icon myRawIcon; private Icon myStateIcon; private MethodHierarchyTreeStructure myTreeStructure; public MethodHierarchyNodeDescriptor( final Project project, final HierarchyNodeDescriptor parentDescriptor, final PsiClass aClass, final boolean isBase, final MethodHierarchyTreeStructure treeStructure ){ super(project, parentDescriptor, aClass, isBase); myTreeStructure = treeStructure; } public final void setTreeStructure(final MethodHierarchyTreeStructure treeStructure) { myTreeStructure = treeStructure; } private PsiMethod getMethod(final PsiClass aClass, final boolean checkBases) { return MethodHierarchyUtil.findBaseMethodInClass(myTreeStructure.getBaseMethod(), aClass, checkBases); } public final PsiClass getPsiClass() { return (PsiClass)myElement; } /** * Element for OpenFileDescriptor */ public final PsiElement getTargetElement() { final PsiClass aClass = getPsiClass(); if (aClass == null || !aClass.isValid()) return null; final PsiMethod method = getMethod(aClass, false); if (method != null) return method; return aClass; } public final boolean isValid() { final PsiClass aClass = getPsiClass(); return aClass != null && aClass.isValid(); } public final boolean update() { int flags = Iconable.ICON_FLAG_VISIBILITY; if (isMarkReadOnly()){ flags |= Iconable.ICON_FLAG_READ_STATUS; } boolean changes = super.update(); final PsiClass psiClass = getPsiClass(); if (psiClass == null){ final String invalidPrefix = IdeBundle.message("node.hierarchy.invalid"); if (!myHighlightedText.getText().startsWith(invalidPrefix)) { myHighlightedText.getBeginning().addText(invalidPrefix, HierarchyNodeDescriptor.getInvalidPrefixAttributes()); } return true; } final Icon newRawIcon = psiClass.getIcon(flags); final Icon newStateIcon = calculateState(psiClass); if (changes || newRawIcon != myRawIcon || newStateIcon != myStateIcon) { changes = true; myRawIcon = newRawIcon; myStateIcon = newStateIcon; Icon newIcon = myRawIcon; if (myIsBase) { final LayeredIcon icon = new LayeredIcon(2); icon.setIcon(newIcon, 0); icon.setIcon(AllIcons.Hierarchy.Base, 1, -AllIcons.Hierarchy.Base.getIconWidth() / 2, 0); newIcon = icon; } if (myStateIcon != null) { final RowIcon icon = new RowIcon(2); icon.setIcon(myStateIcon, 0); icon.setIcon(newIcon, 1); newIcon = icon; } setIcon(newIcon); } final CompositeAppearance oldText = myHighlightedText; myHighlightedText = new CompositeAppearance(); TextAttributes classNameAttributes = null; if (myColor != null) { classNameAttributes = new TextAttributes(myColor, null, null, null, Font.PLAIN); } myHighlightedText.getEnding().addText(ClassPresentationUtil.getNameForClass(psiClass, false), classNameAttributes); myHighlightedText.getEnding().addText(" (" + JavaHierarchyUtil.getPackageName(psiClass) + ")", HierarchyNodeDescriptor.getPackageNameAttributes()); myName = myHighlightedText.getText(); if (!Comparing.equal(myHighlightedText, oldText)) { changes = true; } return changes; } private Icon calculateState(final PsiClass psiClass) { final PsiMethod method = getMethod(psiClass, false); if (method != null) { if (method.hasModifierProperty(PsiModifier.ABSTRACT)) { return null; } return AllIcons.Hierarchy.MethodDefined; } if (myTreeStructure.isSuperClassForBaseClass(psiClass)) { return AllIcons.Hierarchy.MethodNotDefined; } final boolean isAbstractClass = psiClass.hasModifierProperty(PsiModifier.ABSTRACT); // was it implemented is in superclasses? final PsiMethod baseClassMethod = getMethod(psiClass, true); final boolean hasBaseImplementation = baseClassMethod != null && !baseClassMethod.hasModifierProperty(PsiModifier.ABSTRACT); if (hasBaseImplementation || isAbstractClass) { return AllIcons.Hierarchy.MethodNotDefined; } else { return AllIcons.Hierarchy.ShouldDefineMethod; } } }
3e0a0f39dc6f5c2e3127880f4d3e741fce105e21
2,160
java
Java
weevent-governance/src/main/java/com/webank/weevent/governance/entity/base/RuleDatabaseBase.java
chent57/WeEvent
e6d4e3fd6414c1baeb5ccbda082ff735d797918c
[ "Apache-2.0" ]
731
2019-04-18T13:16:57.000Z
2021-11-30T08:10:56.000Z
weevent-governance/src/main/java/com/webank/weevent/governance/entity/base/RuleDatabaseBase.java
jasonsongguohui/WeEvent
4331fa5680fd5c19bee1bbe1877575aa3fe7adc0
[ "Apache-2.0" ]
225
2019-07-02T10:03:23.000Z
2021-10-01T12:57:22.000Z
weevent-governance/src/main/java/com/webank/weevent/governance/entity/base/RuleDatabaseBase.java
jasonsongguohui/WeEvent
4331fa5680fd5c19bee1bbe1877575aa3fe7adc0
[ "Apache-2.0" ]
188
2019-04-19T02:55:13.000Z
2021-11-24T07:40:51.000Z
25.714286
87
0.671759
4,267
package com.webank.weevent.governance.entity.base; import javax.persistence.Column; import javax.persistence.MappedSuperclass; import javax.validation.constraints.NotBlank; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import org.hibernate.validator.constraints.Length; /** * RuleDatabaseBase class * * @since 2019/10/15 */ @Getter @Setter @EqualsAndHashCode(callSuper = false) @MappedSuperclass public class RuleDatabaseBase extends BaseEntity { @Column(name = "user_id") private Integer userId; @Column(name = "broker_id") private Integer brokerId; @Column(name = "database_url") private String databaseUrl; @Column(name = "database_ip") private String databaseIp; @Column(name = "database_port") private String databasePort; @Column(name = "database_name") private String databaseName; @NotBlank @Column(name = "username") private String username; @NotBlank @Column(name = "password") private String password; @NotBlank @Column(name = "datasource_name") private String datasourceName; @Length(max = 256) @Column(name = "optional_parameter") private String optionalParameter; // 1 means the system @Column(name = "system_tag") private Boolean systemTag; @Column(name = "database_type") private Integer databaseType; public RuleDatabaseBase() { } public RuleDatabaseBase(Integer userId, Integer brokerId, @NotBlank String databaseUrl, @NotBlank String username, @NotBlank String password, @NotBlank String datasourceName, @Length(max = 256) String optionalParameter, Boolean systemTag, Integer databaseType) { this.userId = userId; this.brokerId = brokerId; this.databaseUrl = databaseUrl; this.username = username; this.password = password; this.datasourceName = datasourceName; this.optionalParameter = optionalParameter; this.systemTag = systemTag; this.databaseType = databaseType; } }
3e0a0f6f91b4359a3373f440995bc2e9057bdc88
3,539
java
Java
drools-wb-screens/drools-wb-guided-dtable-editor/drools-wb-guided-dtable-editor-backend/src/test/java/org/drools/workbench/screens/guided/dtable/backend/server/conversion/XLSMethodCallNumbersTest.java
tkobayas/drools-wb
6d304be0b88235e889e8cd4879fd81063f4d76a0
[ "Apache-2.0" ]
71
2017-04-04T18:03:17.000Z
2022-03-16T06:25:02.000Z
drools-wb-screens/drools-wb-guided-dtable-editor/drools-wb-guided-dtable-editor-backend/src/test/java/org/drools/workbench/screens/guided/dtable/backend/server/conversion/XLSMethodCallNumbersTest.java
tkobayas/drools-wb
6d304be0b88235e889e8cd4879fd81063f4d76a0
[ "Apache-2.0" ]
929
2017-03-13T15:06:55.000Z
2022-03-10T15:49:36.000Z
drools-wb-screens/drools-wb-guided-dtable-editor/drools-wb-guided-dtable-editor-backend/src/test/java/org/drools/workbench/screens/guided/dtable/backend/server/conversion/XLSMethodCallNumbersTest.java
mbiarnes/drools-wb
620dfc8bf23742221fe6f67ea6b99e40ab54f1c0
[ "Apache-2.0" ]
131
2017-03-22T09:45:37.000Z
2022-03-16T06:24:47.000Z
36.112245
124
0.68607
4,268
/* * Copyright 2021 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.workbench.screens.guided.dtable.backend.server.conversion; import org.apache.poi.ss.usermodel.Workbook; import org.drools.workbench.models.guided.dtable.backend.GuidedDTXMLPersistence; import org.drools.workbench.models.guided.dtable.shared.model.GuidedDecisionTable52; import org.junit.BeforeClass; import org.junit.Test; import static org.drools.workbench.screens.guided.dtable.backend.server.util.TestUtil.loadResource; import static org.junit.Assert.assertEquals; public class XLSMethodCallNumbersTest extends TestBase { @BeforeClass public static void setUp() throws Exception { final String xml = loadResource(XLSBuilderAttributesNegateTest.class.getResourceAsStream("NumbersInMethods.gdst")); final GuidedDecisionTable52 dtable = GuidedDTXMLPersistence.getInstance().unmarshal(xml); final XLSBuilder.BuildResult buildResult = new XLSBuilder(dtable, makeDMO()).build(); final Workbook workbook = buildResult.getWorkbook(); assertEquals(1, workbook.getNumberOfSheets()); sheet = workbook.iterator().next(); } @Test public void headers() { assertEquals("RuleSet", cell(1, 1).getStringCellValue()); assertEquals("mortgages.mortgages", cell(1, 2).getStringCellValue()); assertEquals("Import", cell(2, 1).getStringCellValue()); assertEquals("", sheet.getRow(2).getCell(2).getStringCellValue()); assertEquals("RuleTable NumbersInMethods", cell(4, 1).getStringCellValue()); } @Test public void columnTypes() { assertEquals("ACTION", cell(5, 1).getStringCellValue()); assertEquals("ACTION", cell(5, 2).getStringCellValue()); assertEquals("ACTION", cell(5, 3).getStringCellValue()); assertNullCell(5, 4); } @Test public void patterns() { assertNullCell(6, 1); assertNullCell(6, 2); assertNullCell(6, 3); } @Test public void constraints() { assertEquals("NumberWrapper a = new NumberWrapper(); insert( a );", cell(7, 1).getStringCellValue().trim()); assertEquals("a.assignTestId( new java.math.BigDecimal(\"$param\") );", cell(7, 2).getStringCellValue().trim()); assertEquals("a.assignBigInteger( new java.math.BigInteger(\"$param\") );", cell(7, 3).getStringCellValue().trim()); assertNullCell(7, 4); } @Test public void columnTitles() { assertEquals("", cell(8, 1).getStringCellValue()); assertEquals("Big Decimal", cell(8, 2).getStringCellValue()); assertEquals("Big Decimal", cell(8, 3).getStringCellValue()); assertNullCell(8, 4); } @Test public void content() { assertEquals("X", cell(9, 1).getStringCellValue()); assertEquals("11", cell(9, 2).getStringCellValue()); assertEquals("22", cell(9, 3).getStringCellValue()); assertNullCell(9, 4); } }
3e0a1037ca258b8d2c070b39c6c4ea59f6c61026
901
java
Java
src/main/java/ru/geekbrains/pocket/backend/domain/pub/UserContactPub.java
romanungefuk/pocket-java-backend
baee7749c7019ad48a500da3f01d1c9f508a3838
[ "Apache-2.0" ]
1
2021-10-21T13:32:35.000Z
2021-10-21T13:32:35.000Z
src/main/java/ru/geekbrains/pocket/backend/domain/pub/UserContactPub.java
romanungefuk/pocket-java-backend
baee7749c7019ad48a500da3f01d1c9f508a3838
[ "Apache-2.0" ]
null
null
null
src/main/java/ru/geekbrains/pocket/backend/domain/pub/UserContactPub.java
romanungefuk/pocket-java-backend
baee7749c7019ad48a500da3f01d1c9f508a3838
[ "Apache-2.0" ]
15
2019-01-25T11:08:35.000Z
2020-05-28T09:37:11.000Z
25.027778
68
0.647059
4,269
package ru.geekbrains.pocket.backend.domain.pub; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import ru.geekbrains.pocket.backend.domain.db.UserContact; import java.util.Date; @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class UserContactPub { private UserProfilePub contact; private String byname; private Date added_at; public UserContactPub(UserContact userContact){ this.contact = new UserProfilePub(userContact.getContact()); this.byname = userContact.getByName(); this.added_at = userContact.getAddedAt(); } @Override public String toString() { return "UserContact{" + "'contact':'" + contact + "'" + ", 'byname':'" + byname + "'" + ", 'added_at':'" + added_at + "'" + '}'; } }
3e0a12f9fd198230f92cd474c25aeb1860d8722d
1,209
java
Java
app/src/main/java/org/chromium/blink/mojom/ServiceWorkerStartStatus.java
jhonatasrm/chromium-android
d3fedab2b0a461076505133b5ade07517a43cb01
[ "FTL" ]
5
2019-06-13T19:39:52.000Z
2021-11-18T09:04:42.000Z
app/src/main/java/org/chromium/blink/mojom/ServiceWorkerStartStatus.java
agelessZeal/Rapusia-Android-Browser-Chromium
fdbb0cebbf6819ee9b6e3ce2af6253c5ad42d5ce
[ "MIT" ]
1
2021-05-25T07:22:30.000Z
2021-05-25T07:22:30.000Z
app/src/main/java/org/chromium/blink/mojom/ServiceWorkerStartStatus.java
jhonatasrm/chromium-android
d3fedab2b0a461076505133b5ade07517a43cb01
[ "FTL" ]
null
null
null
26.282609
86
0.684864
4,271
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file is autogenerated by: // mojo/public/tools/bindings/mojom_bindings_generator.py // For: // third_party/blink/public/mojom/service_worker/service_worker_event_status.mojom // package org.chromium.blink.mojom; import org.chromium.mojo.bindings.DeserializationException; public final class ServiceWorkerStartStatus { public static final int NORMAL_COMPLETION = 0; public static final int ABRUPT_COMPLETION = NORMAL_COMPLETION + 1; public static final int MIN_VALUE = (int) (0); public static final int MAX_VALUE = (int) (1); private static final boolean IS_EXTENSIBLE = false; public static boolean isKnownValue(int value) { switch (value) { case 0: case 1: return true; } return false; } public static void validate(int value) { if (IS_EXTENSIBLE || isKnownValue(value)) return; throw new DeserializationException("Invalid enum value."); } private ServiceWorkerStartStatus() {} }
3e0a145a60d2a233b1256727d79d313878868b24
3,594
java
Java
tis-solrcore-extend/src/main/java/com/qlangtech/tis/solrextend/fieldtype/s4supplygoods/Prefix8SplitTokenizerFactory.java
jhonyang/tis-solr
ab1dfe0bc4a4d2ab78709b2d271f153988285d30
[ "MIT" ]
1
2019-09-26T03:08:34.000Z
2019-09-26T03:08:34.000Z
tis-solrcore-extend/src/main/java/com/qlangtech/tis/solrextend/fieldtype/s4supplygoods/Prefix8SplitTokenizerFactory.java
jhonyang/tis-solr
ab1dfe0bc4a4d2ab78709b2d271f153988285d30
[ "MIT" ]
null
null
null
tis-solrcore-extend/src/main/java/com/qlangtech/tis/solrextend/fieldtype/s4supplygoods/Prefix8SplitTokenizerFactory.java
jhonyang/tis-solr
ab1dfe0bc4a4d2ab78709b2d271f153988285d30
[ "MIT" ]
null
null
null
34.228571
105
0.706733
4,272
/* * The MIT License * * Copyright (c) 2018-2022, qinglangtech Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.qlangtech.tis.solrextend.fieldtype.s4supplygoods; import org.apache.commons.io.IOUtils; import org.apache.lucene.analysis.Tokenizer; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.util.TokenizerFactory; import org.apache.lucene.util.AttributeFactory; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /* * <p> * <p> * <p> * <p> * 原始值为warehouseid_lastVer;[warehouseid_lastVer] * paser取内容中的warehouseid作为term * warehouseId 从第9位开始到最后一位 * warehouseId 前8位也就是selfentityid * * @author 百岁(baisui@qlangtech.com) * @date 2019年1月17日 */ public class Prefix8SplitTokenizerFactory extends TokenizerFactory { public Prefix8SplitTokenizerFactory(Map<String, String> args) { super(args); } @Override public Tokenizer create(AttributeFactory attributeFactory) { return new Prefix8SplitTokenizer(attributeFactory); } } class Prefix8SplitTokenizer extends Tokenizer { private final CharTermAttribute termAttr = (CharTermAttribute) addAttribute(CharTermAttribute.class); String[] stockInfoArray; private int termsIndex = 0; private int termsNum = 0; static final Pattern KV_PAIR_LIST_PATTERN = Pattern.compile("(\\d{8})(\\w+)_(\\d+)"); Prefix8SplitTokenizer(AttributeFactory factory) { super(factory); } @Override public boolean incrementToken() throws IOException { this.clearAttributes(); if (stockInfoArray == null) { Set<String> stockInfoTermSet = new HashSet<>(); Matcher kvPairMatcher = KV_PAIR_LIST_PATTERN.matcher(IOUtils.toString(this.input)); while (kvPairMatcher.find()) { assert (kvPairMatcher.groupCount() == 3); stockInfoTermSet.add(kvPairMatcher.group(1)); stockInfoTermSet.add(kvPairMatcher.group(2)); } termsIndex = 0; termsNum = stockInfoTermSet.size(); stockInfoArray = stockInfoTermSet.toArray(new String[termsNum]); } if (termsIndex >= termsNum) { termsIndex = -1; termsNum = 0; stockInfoArray = null; return false; } termAttr.setEmpty().append(stockInfoArray[termsIndex++]); return true; } }
3e0a14a3f929ae0af5f42c398aa7448ee6bdeaaa
652
java
Java
src/main/java/cardocha/github/io/cidadesEstadosMc/utils/Logger.java
cardocha/cidadesEstadosMc
f78282ab161ff805566bb2e84326f58b439fe204
[ "MIT" ]
null
null
null
src/main/java/cardocha/github/io/cidadesEstadosMc/utils/Logger.java
cardocha/cidadesEstadosMc
f78282ab161ff805566bb2e84326f58b439fe204
[ "MIT" ]
null
null
null
src/main/java/cardocha/github/io/cidadesEstadosMc/utils/Logger.java
cardocha/cidadesEstadosMc
f78282ab161ff805566bb2e84326f58b439fe204
[ "MIT" ]
null
null
null
23.285714
90
0.57362
4,273
package cardocha.github.io.cidadesEstadosMc.utils; import java.text.SimpleDateFormat; import java.util.Date; class Logger { private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yy HH:mm:ss"); void log(String msg, String param) { String logInstant = simpleDateFormat.format(new Date()); String logMsg = logInstant .concat(" ") .concat(msg); if (param != null) logMsg = logMsg .concat(" ") .concat(param); System.out.println(logMsg); } void log(String msg) { this.log(msg, null); } }
3e0a1510a580fd33794acf5f832925ed11bd0382
13,914
java
Java
src/main/java/org/point85/domain/email/EmailClient.java
point85/OEE-Domain
81ccaf652eba40aa20ae9206545a7bb9e69093ad
[ "MIT" ]
5
2019-03-14T11:45:11.000Z
2021-09-23T01:03:47.000Z
src/main/java/org/point85/domain/email/EmailClient.java
point85/OEE-Domain
81ccaf652eba40aa20ae9206545a7bb9e69093ad
[ "MIT" ]
12
2018-11-30T02:12:29.000Z
2022-03-15T03:30:35.000Z
src/main/java/org/point85/domain/email/EmailClient.java
point85/OEE-Domain
81ccaf652eba40aa20ae9206545a7bb9e69093ad
[ "MIT" ]
1
2020-04-06T02:48:45.000Z
2020-04-06T02:48:45.000Z
29.108787
100
0.717119
4,274
package org.point85.domain.email; import java.net.InetAddress; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import java.util.Properties; import java.util.Timer; import java.util.TimerTask; import javax.mail.BodyPart; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Store; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.search.FlagTerm; import org.point85.domain.messaging.ApplicationMessage; import org.point85.domain.messaging.BaseMessagingClient; import org.point85.domain.messaging.CollectorNotificationMessage; import org.point85.domain.messaging.MessageType; import org.point85.domain.messaging.NotificationSeverity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The EmailClient class has methods for communicating with an email server. It * supports both IMAP and POP3 protocols for receiving messages. * */ public class EmailClient extends BaseMessagingClient { private static final String MAIL_DEBUG = "mail.debug"; private static final String MAIL_TRUE = "true"; private static final String MAIL_FALSE = "false"; private static final String TEXT_PLAIN = "text/plain"; private static final String MAIL_INBOX = "INBOX"; private static final String IMAP_STORE = "imap"; private static final String POP3_STORE = "pop3"; // SMTP private static final String MAIL_SMTP_HOST = "mail.smtp.host"; private static final String MAIL_SMTP_PORT = "mail.smtp.port"; private static final String MAIL_SMTP_USER = "mail.smtp.user"; private static final String MAIL_SMTP_PASSWORD = "mail.smtp.password"; private static final String MAIL_SMTP_SSL_ENABLE = "mail.smtp.ssl.enable"; private static final String MAIL_SMTP_AUTH = "mail.smtp.auth"; private static final String MAIL_SMTP_START_TLS = "mail.smtp.starttls.enable"; // IMAP private static final String MAIL_IMAP_HOST = "mail.imap.host"; private static final String MAIL_IMAP_PORT = "mail.imap.port"; private static final String MAIL_IMAP_USER = "mail.imap.user"; private static final String MAIL_IMAP_PASSWORD = "mail.imap.password"; private static final String MAIL_IMAP_SSL_ENABLE = "mail.imap.ssl.enable"; // POP3 private static final String MAIL_POP3_HOST = "mail.pop3.host"; private static final String MAIL_POP3_PORT = "mail.pop3.port"; private static final String MAIL_POP3_USER = "mail.pop3.user"; private static final String MAIL_POP3_PASSWORD = "mail.pop3.password"; private static final String MAIL_POP3_SSL_ENABLE = "mail.pop3.ssl.enable"; // logger private static final Logger logger = LoggerFactory.getLogger(EmailClient.class); // default polling interval public static final int DEFAULT_POLLING_INTERVAL = 30000; // polling interval in milliseconds private int pollingInterval = DEFAULT_POLLING_INTERVAL; // SMTP, IMAP and POP3 properties private Properties smtpProperties = new Properties(); private Properties imapProperties = new Properties(); private Properties pop3Properties = new Properties(); // listener for received messages private EmailMessageListener listener; private String storeType; // polling timer private Timer pollingTimer; // polling flag private boolean isPolling = false; // email server private EmailSource source; /** * Constructor from an email server source * * @param source {@link EmailSource} */ public EmailClient(EmailSource source) { if (source != null) { configureSMTP(source); configureIMAP(source); configurePOP3(source); } this.source = source; } public boolean isSubscribed() { return isPolling; } public EmailSource getSource() { return this.source; } /** * Check for incoming emails with JSON serialized ApplicationMessage content * * @return List of {@link ApplicationMessage} * @throws Exception Exception */ public List<ApplicationMessage> receiveEmails() throws Exception { Properties properties = null; String user = null; String password = null; List<ApplicationMessage> appMessages = new ArrayList<>(); if (storeType.equals(IMAP_STORE)) { properties = imapProperties; user = imapProperties.getProperty(MAIL_IMAP_USER); password = imapProperties.getProperty(MAIL_IMAP_PASSWORD); } else { properties = pop3Properties; user = pop3Properties.getProperty(MAIL_POP3_USER); password = pop3Properties.getProperty(MAIL_POP3_PASSWORD); } if (logger.isInfoEnabled()) { logger.info("Checking for mail for user " + user); } // create session and store Session emailSession = Session.getInstance(properties); Store emailStore = emailSession.getStore(storeType); try { // connect to the server emailStore.connect(user, password); } catch (Exception e) { emailStore.close(); throw e; } // create the inbox and open it Folder emailFolder = emailStore.getFolder(MAIL_INBOX); emailFolder.open(Folder.READ_WRITE); // retrieve the messages from the inbox Message[] messages = emailFolder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); for (int i = 0; i < messages.length; i++) { Message message = messages[i]; if (logger.isInfoEnabled()) { logger.info("---------------------------------"); logger.info("Email Number " + (i + 1)); logger.info("Subject: " + message.getSubject()); logger.info("From: " + (message.getFrom() != null ? message.getFrom()[0] : "No From Field")); } Object content = message.getContent(); String json = null; if (content instanceof MimeMultipart) { MimeMultipart mime = (MimeMultipart) content; int count = mime.getCount(); for (int k = 0; k < count; k++) { BodyPart part = mime.getBodyPart(k); String ct = part.getContentType().toLowerCase(); if (ct.contains(TEXT_PLAIN)) { json = (String) part.getContent(); break; } } } else if (content instanceof String) { json = (String) content; } if (logger.isInfoEnabled()) { logger.info("Email content: \n" + json); } message.setFlag(Flags.Flag.SEEN, true); // serialize to ApplicationMessage ApplicationMessage appMessage = null; if (json.contains(MessageType.EQUIPMENT_EVENT.name())) { // equipment event appMessage = deserialize(MessageType.EQUIPMENT_EVENT, json); } else if (json.contains(MessageType.COMMAND.name())) { // command appMessage = deserialize(MessageType.COMMAND, json); } else if (json.contains(MessageType.STATUS.name())) { // command appMessage = deserialize(MessageType.STATUS, json); } else if (json.contains(MessageType.NOTIFICATION.name())) { // command appMessage = deserialize(MessageType.NOTIFICATION, json); } else if (json.contains(MessageType.RESOLVED_EVENT.name())) { // command appMessage = deserialize(MessageType.RESOLVED_EVENT, json); } else { logger.error("Unable to handle message!"); } if (appMessage != null) { appMessages.add(appMessage); } } // close the store and folder objects emailFolder.close(false); emailStore.close(); return appMessages; } private void configureSMTP(EmailSource source) { if (logger.isDebugEnabled()) { smtpProperties.put(MAIL_DEBUG, MAIL_TRUE); } smtpProperties.put(MAIL_SMTP_HOST, source.getSendHost()); smtpProperties.put(MAIL_SMTP_PORT, source.getSendPort()); smtpProperties.put(MAIL_SMTP_SSL_ENABLE, source.getSendSecurityPolicy().equals(EmailSecurityPolicy.SSL) ? MAIL_TRUE : MAIL_FALSE); if (source.getUserName() != null) { smtpProperties.put(MAIL_SMTP_USER, source.getUserName()); smtpProperties.put(MAIL_SMTP_PASSWORD, source.getUserPassword()); smtpProperties.put(MAIL_SMTP_AUTH, MAIL_TRUE); } else { smtpProperties.put(MAIL_SMTP_AUTH, MAIL_FALSE); } smtpProperties.put(MAIL_SMTP_START_TLS, MAIL_TRUE); if (logger.isInfoEnabled()) { logger.info("SMTP properties:"); for (Entry<Object, Object> property : smtpProperties.entrySet()) { if (!((String) property.getKey()).contains("password")) { logger.info(property.getKey() + ": " + property.getValue()); } else { logger.info(property.getKey() + ": <not null>"); } } } } private void configureIMAP(EmailSource source) { if (!source.getProtocol().equals(EmailProtocol.IMAP)) { return; } storeType = IMAP_STORE; if (logger.isDebugEnabled()) { imapProperties.put(MAIL_DEBUG, MAIL_TRUE); } imapProperties.put(MAIL_IMAP_HOST, source.getReceiveHost()); imapProperties.put(MAIL_IMAP_PORT, source.getReceivePort()); imapProperties.put(MAIL_IMAP_SSL_ENABLE, source.getReceiveSecurityPolicy().equals(EmailSecurityPolicy.SSL) ? MAIL_TRUE : MAIL_FALSE); if (source.getUserName() != null) { imapProperties.put(MAIL_IMAP_USER, source.getUserName()); imapProperties.put(MAIL_IMAP_PASSWORD, source.getUserPassword()); } if (logger.isInfoEnabled()) { logger.info("IMAP properties:"); for (Entry<Object, Object> property : imapProperties.entrySet()) { if (!((String) property.getKey()).contains("password")) { logger.info(property.getKey() + ": " + property.getValue()); } else { logger.info(property.getKey() + ": <not null>"); } } } } private void configurePOP3(EmailSource source) { if (!source.getProtocol().equals(EmailProtocol.POP3)) { return; } storeType = POP3_STORE; if (logger.isDebugEnabled()) { imapProperties.put(MAIL_DEBUG, MAIL_TRUE); } pop3Properties.put(MAIL_POP3_HOST, source.getReceiveHost()); pop3Properties.put(MAIL_POP3_PORT, source.getReceivePort()); pop3Properties.put(MAIL_POP3_SSL_ENABLE, source.getReceiveSecurityPolicy().equals(EmailSecurityPolicy.SSL) ? MAIL_TRUE : MAIL_FALSE); if (source.getUserName() != null) { pop3Properties.put(MAIL_POP3_USER, source.getUserName()); pop3Properties.put(MAIL_POP3_PASSWORD, source.getUserPassword()); } if (logger.isInfoEnabled()) { logger.info("POP3 properties:"); for (Entry<Object, Object> property : pop3Properties.entrySet()) { if (!((String) property.getKey()).contains("password")) { logger.info(property.getKey() + ": " + property.getValue()); } else { logger.info(property.getKey() + ": <not null>"); } } } } /** * Send a MimeMessage email with the specified content * * @param to Recipient * @param subject Subject * @param content Content * @throws Exception Exception */ public void sendMail(String to, String subject, String content) throws Exception { if (smtpProperties.isEmpty()) { logger.warn("SMTP properties are not defined."); return; } // create the session Session session = Session.getInstance(smtpProperties, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(smtpProperties.getProperty(MAIL_SMTP_USER), smtpProperties.getProperty(MAIL_SMTP_PASSWORD)); } }); // create the message MimeMessage message = new MimeMessage(session); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setText(content); message.setFrom(smtpProperties.getProperty(MAIL_SMTP_USER)); message.setContent(content, TEXT_PLAIN); // send message Transport.send(message); if (logger.isInfoEnabled()) { logger.info("Sent message to " + to); } } /** * Register a listener for messages * * @param listener {@link EmailMessageListener} */ public void registerListener(EmailMessageListener listener) { this.listener = listener; } /** * Unregister a previous message listener */ public void unregisterListener() { this.listener = null; } public int getPollingInterval() { return pollingInterval; } public void setPollingInterval(int pollingInterval) { this.pollingInterval = pollingInterval; } /** * Stop checking for emails */ public void stopPolling() { if (pollingTimer != null) { pollingTimer.cancel(); pollingTimer = null; } isPolling = false; } /** * Start checking for emails */ public void startPolling() { // delay up to 5 sec long delay = (long) (Math.random() * 5000.0d); pollingTimer = new Timer(); pollingTimer.schedule(new PollingTask(), delay, pollingInterval); isPolling = true; } /** * Send a notification message * * @param to Recipient * @param subject Subject * @param text Content * @param severity {@link NotificationSeverity} * @throws Exception Exception */ public void sendNotification(String to, String subject, String text, NotificationSeverity severity) throws Exception { InetAddress address = InetAddress.getLocalHost(); CollectorNotificationMessage message = new CollectorNotificationMessage(address.getHostName(), address.getHostAddress()); message.setText(text); message.setSeverity(severity); sendMail(to, subject, serialize(message)); } /** * Send an event application message * * @param to Recipient * @param subject Subject * @param message {@link ApplicationMessage} * @throws Exception Exception */ public void sendEvent(String to, String subject, ApplicationMessage message) throws Exception { sendMail(to, subject, serialize(message)); } private class PollingTask extends TimerTask { private PollingTask() { } @Override public void run() { try { onPoll(); } catch (Exception e) { logger.error(e.getClass().getSimpleName() + ": " + e.getMessage()); } } private void onPoll() throws Exception { List<ApplicationMessage> messages = receiveEmails(); if (listener != null) { for (ApplicationMessage message : messages) { listener.onEmailMessage(message); } } } } }
3e0a1529a81309fda68bc812d8727baf14aaa35a
1,182
java
Java
app/guts/pipes/EntityPipe.java
YuanhaoSun/Active-Learner
6378eaea0bcd13ff0b2a29a837c530f4055bbac5
[ "Apache-2.0" ]
2
2018-02-01T15:59:00.000Z
2018-12-17T06:09:48.000Z
app/guts/pipes/EntityPipe.java
YuanhaoSun/Active-Learner
6378eaea0bcd13ff0b2a29a837c530f4055bbac5
[ "Apache-2.0" ]
null
null
null
app/guts/pipes/EntityPipe.java
YuanhaoSun/Active-Learner
6378eaea0bcd13ff0b2a29a837c530f4055bbac5
[ "Apache-2.0" ]
null
null
null
29.55
95
0.752115
4,275
package guts.pipes; import java.util.regex.Pattern; import cc.mallet.pipe.CharSequence2TokenSequence; import cc.mallet.pipe.CharSequenceLowercase; import cc.mallet.pipe.CharSequenceReplace; import cc.mallet.pipe.FeatureSequence2AugmentableFeatureVector; import cc.mallet.pipe.Input2CharSequence; import cc.mallet.pipe.Noop; import cc.mallet.pipe.Pipe; import cc.mallet.pipe.PrintInputAndTarget; import cc.mallet.pipe.SerialPipes; import cc.mallet.pipe.Target2Label; import cc.mallet.pipe.TokenSequence2FeatureSequence; import cc.mallet.pipe.TokenSequenceRemoveStopwords; import cc.mallet.types.AugmentableFeatureVector; import cc.mallet.types.Instance; import cc.mallet.util.CharSequenceLexer; public class EntityPipe extends Pipe { private Pipe myPipe = new SerialPipes(new Pipe[] { new VanillaPipe("\\|\\|"), new OrthoPipe(), new Labelize(), // new PrintInputAndTarget(), }); public Instance pipe (Instance carrier) { return myPipe.pipe(carrier); } public java.util.Iterator<Instance> newIteratorFrom(java.util.Iterator<Instance> carrier) { return myPipe.newIteratorFrom(carrier); } }
3e0a17b9219434d667ac761fc2c4400ba42f2f95
5,096
java
Java
AndroidProject/dc/app/src/main/java/com/example/ershou/TabFragmentThree.java
CypHelp/TestNewWorldDemo
ee6f73df05756f191c1c56250fa290461fdd1b9a
[ "Apache-2.0" ]
null
null
null
AndroidProject/dc/app/src/main/java/com/example/ershou/TabFragmentThree.java
CypHelp/TestNewWorldDemo
ee6f73df05756f191c1c56250fa290461fdd1b9a
[ "Apache-2.0" ]
null
null
null
AndroidProject/dc/app/src/main/java/com/example/ershou/TabFragmentThree.java
CypHelp/TestNewWorldDemo
ee6f73df05756f191c1c56250fa290461fdd1b9a
[ "Apache-2.0" ]
null
null
null
42.823529
158
0.520604
4,276
package com.example.ershou; import android.app.AlertDialog; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.example.ershou.Util.SharedPreferencesUtils; import com.example.ershou.Util.UserClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; public class TabFragmentThree extends Fragment { private TextView username; private TextView nickname, guanyu, update; ImageView hj; TextView state; @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.tabfragmentfour, container, false); username = (TextView) v.findViewById(R.id.username); hj = v.findViewById(R.id.hj); state = v.findViewById(R.id.state); RequestParams ps = new RequestParams(); ps.add("zh", SharedPreferencesUtils.getParam(getActivity(), "zh", "").toString()); UserClient.get("hj/get", ps, new AsyncHttpResponseHandler() { @Override public void onSuccess(String content) { super.onSuccess(content); if (content.equals("1")) { } else { state.setText(content); new AlertDialog.Builder(getActivity()).setTitle("提示").setMessage(content).setPositiveButton("确定",null).show(); } } }); hj.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { RequestParams ps = new RequestParams(); ps.add("zh", SharedPreferencesUtils.getParam(getActivity(), "zh", "").toString()); UserClient.get("hj/get", ps, new AsyncHttpResponseHandler() { @Override public void onSuccess(String content) { super.onSuccess(content); if (content.equals("1")) { RequestParams pss = new RequestParams(); pss.add("zhuohao", SharedPreferencesUtils.getParam(getActivity(), "zh", "").toString()); UserClient.get("hj/add", pss, new AsyncHttpResponseHandler() { @Override public void onSuccess(String content) { super.onSuccess(content); state.setText(content); RequestParams ps = new RequestParams(); ps.add("zh", SharedPreferencesUtils.getParam(getActivity(), "zh", "").toString()); UserClient.get("hj/get", ps, new AsyncHttpResponseHandler() { @Override public void onSuccess(String content) { super.onSuccess(content); if (content.equals("1")) { } else { state.setText(content); new AlertDialog.Builder(getActivity()).setTitle("提示").setMessage(content).setPositiveButton("确定",null).show(); } } }); } }); } else { state.setText(content); } } }); } }); guanyu = (TextView) v.findViewById(R.id.guanyu); update = (TextView) v.findViewById(R.id.update); guanyu.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub startActivity(new Intent(getActivity(), guanyu.class)); } }); update.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub startActivity(new Intent(getActivity(), update.class)); } }); nickname = (TextView) v.findViewById(R.id.nickname); username.setText("帐号:" + SharedPreferencesUtils.getParam(getActivity(), "username", "")); nickname.setText("昵称:" + SharedPreferencesUtils.getParam(getActivity(), "nickname", "")); return v; } }
3e0a1839edf04ecda33c06bdb359f757b60230ea
246
java
Java
seed-starter-manager/src/main/java/com/hk/prj/seedsm/repo/VarietyRepository.java
kumarhemant10/sample-projects-springboot
01b444c96c77deacfdc152f58761afaa0af7f674
[ "Apache-2.0" ]
null
null
null
seed-starter-manager/src/main/java/com/hk/prj/seedsm/repo/VarietyRepository.java
kumarhemant10/sample-projects-springboot
01b444c96c77deacfdc152f58761afaa0af7f674
[ "Apache-2.0" ]
null
null
null
seed-starter-manager/src/main/java/com/hk/prj/seedsm/repo/VarietyRepository.java
kumarhemant10/sample-projects-springboot
01b444c96c77deacfdc152f58761afaa0af7f674
[ "Apache-2.0" ]
null
null
null
20.5
73
0.804878
4,277
package com.hk.prj.seedsm.repo; import org.springframework.data.jpa.repository.JpaRepository; import com.hk.prj.seedsm.model.Variety; public interface VarietyRepository extends JpaRepository<Variety, Long> { Variety findById(Integer id); }
3e0a18760f3b78b1f4b66675481d9f165ef41659
1,430
java
Java
chat/src/main/java/com/mengchat/chat/kit/conversation/ext/FingerGameExt.java
lovejhf/meng_chat
036ffdc74bdead45e3f9b5bcf29c746ae29cd05b
[ "ICU", "MIT" ]
null
null
null
chat/src/main/java/com/mengchat/chat/kit/conversation/ext/FingerGameExt.java
lovejhf/meng_chat
036ffdc74bdead45e3f9b5bcf29c746ae29cd05b
[ "ICU", "MIT" ]
null
null
null
chat/src/main/java/com/mengchat/chat/kit/conversation/ext/FingerGameExt.java
lovejhf/meng_chat
036ffdc74bdead45e3f9b5bcf29c746ae29cd05b
[ "ICU", "MIT" ]
null
null
null
24.237288
77
0.708392
4,278
package com.mengchat.chat.kit.conversation.ext; import android.content.Context; import android.content.Intent; import android.view.View; import com.mengchat.chat.R; import com.mengchat.chat.app.red_envelope.RedEnvelopeActivity; import com.mengchat.chat.kit.annotation.ExtContextMenuItem; import com.mengchat.chat.kit.conversation.ext.core.ConversationExt; import java.util.ArrayList; import java.util.List; import java.util.Random; import cn.wildfirechat.RedEnvelopeVo; import cn.wildfirechat.message.TypingMessageContent; import cn.wildfirechat.model.Conversation; import static android.app.Activity.RESULT_OK; public class FingerGameExt extends ConversationExt { /** * @param containerView 扩展view的container * @param conversation */ @ExtContextMenuItem(title = "[猜拳]") public void pickLocation(View containerView, Conversation conversation) { List<String> list = new ArrayList<>(); list.add("finger1"); list.add("finger2"); list.add("finger3"); Random rand = new Random(); String fingerName = list.get(rand.nextInt(list.size())); conversationViewModel.sendFingerMessage(fingerName); } @Override public int priority() { return 100; } @Override public int iconResId() { return R.mipmap.ic_fun_finger; } @Override public String title(Context context) { return "猜拳"; } }
3e0a1a0bd132419388cbbb2a8bd6ca75a2a64622
38,396
java
Java
app/build/generated/source/r/debug/com/google/android/gms/R.java
busrakbey/orbismobildepo
d7a634dc0a22305f0afb9a12cec6f05346a38409
[ "Apache-2.0" ]
null
null
null
app/build/generated/source/r/debug/com/google/android/gms/R.java
busrakbey/orbismobildepo
d7a634dc0a22305f0afb9a12cec6f05346a38409
[ "Apache-2.0" ]
null
null
null
app/build/generated/source/r/debug/com/google/android/gms/R.java
busrakbey/orbismobildepo
d7a634dc0a22305f0afb9a12cec6f05346a38409
[ "Apache-2.0" ]
null
null
null
65.410562
246
0.829878
4,279
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.google.android.gms; public final class R { public static final class attr { public static final int adSize = 0x7f010071; public static final int adSizes = 0x7f010072; public static final int adUnitId = 0x7f010073; public static final int allowShortcuts = 0x7f01014a; public static final int ambientEnabled = 0x7f01016a; public static final int appTheme = 0x7f0101ee; public static final int buttonSize = 0x7f0101b0; public static final int buyButtonAppearance = 0x7f0101f5; public static final int buyButtonHeight = 0x7f0101f2; public static final int buyButtonText = 0x7f0101f4; public static final int buyButtonWidth = 0x7f0101f3; public static final int cameraBearing = 0x7f01015b; public static final int cameraTargetLat = 0x7f01015c; public static final int cameraTargetLng = 0x7f01015d; public static final int cameraTilt = 0x7f01015e; public static final int cameraZoom = 0x7f01015f; public static final int castBackgroundColor = 0x7f010106; public static final int castButtonBackgroundColor = 0x7f010107; public static final int castButtonText = 0x7f010109; public static final int castButtonTextAppearance = 0x7f010108; public static final int castFocusRadius = 0x7f01010b; public static final int castIntroOverlayStyle = 0x7f01012d; public static final int castMiniControllerStyle = 0x7f01012e; public static final int castShowImageThumbnail = 0x7f01010c; public static final int castSubtitleTextAppearance = 0x7f01010d; public static final int castTitleTextAppearance = 0x7f01010a; public static final int circleCrop = 0x7f010158; public static final int colorScheme = 0x7f0101b1; public static final int contentProviderUri = 0x7f010128; public static final int corpusId = 0x7f010126; public static final int corpusVersion = 0x7f010127; public static final int defaultIntentAction = 0x7f010147; public static final int defaultIntentActivity = 0x7f010149; public static final int defaultIntentData = 0x7f010148; public static final int environment = 0x7f0101ef; public static final int featureType = 0x7f0101af; public static final int fragmentMode = 0x7f0101f1; public static final int fragmentStyle = 0x7f0101f0; public static final int imageAspectRatio = 0x7f010157; public static final int imageAspectRatioAdjust = 0x7f010156; public static final int indexPrefixes = 0x7f0101ac; public static final int inputEnabled = 0x7f01014d; public static final int liteMode = 0x7f010160; public static final int mapType = 0x7f01015a; public static final int maskedWalletDetailsBackground = 0x7f0101f8; public static final int maskedWalletDetailsButtonBackground = 0x7f0101fa; public static final int maskedWalletDetailsButtonTextAppearance = 0x7f0101f9; public static final int maskedWalletDetailsHeaderTextAppearance = 0x7f0101f7; public static final int maskedWalletDetailsLogoImageType = 0x7f0101fc; public static final int maskedWalletDetailsLogoTextColor = 0x7f0101fb; public static final int maskedWalletDetailsTextAppearance = 0x7f0101f6; public static final int noIndex = 0x7f0101aa; public static final int paramName = 0x7f01013c; public static final int paramValue = 0x7f01013d; public static final int perAccountTemplate = 0x7f01012c; public static final int schemaOrgProperty = 0x7f0101ae; public static final int schemaOrgType = 0x7f01012a; public static final int scopeUris = 0x7f0101b2; public static final int searchEnabled = 0x7f010144; public static final int searchLabel = 0x7f010145; public static final int sectionContent = 0x7f01014c; public static final int sectionFormat = 0x7f0101a9; public static final int sectionId = 0x7f0101a8; public static final int sectionType = 0x7f01014b; public static final int sectionWeight = 0x7f0101ab; public static final int semanticallySearchable = 0x7f01012b; public static final int settingsDescription = 0x7f010146; public static final int sourceClass = 0x7f01014e; public static final int subsectionSeparator = 0x7f0101ad; public static final int toAddressesSection = 0x7f010152; public static final int toolbarTextColorStyle = 0x7f010130; public static final int trimmable = 0x7f010129; public static final int uiCompass = 0x7f010161; public static final int uiMapToolbar = 0x7f010169; public static final int uiRotateGestures = 0x7f010162; public static final int uiScrollGestures = 0x7f010163; public static final int uiTiltGestures = 0x7f010164; public static final int uiZoomControls = 0x7f010165; public static final int uiZoomGestures = 0x7f010166; public static final int useViewLifecycle = 0x7f010167; public static final int userInputSection = 0x7f010150; public static final int userInputTag = 0x7f01014f; public static final int userInputValue = 0x7f010151; public static final int windowTransitionStyle = 0x7f01012f; public static final int zOrderOnTop = 0x7f010168; } public static final class color { public static final int cast_intro_overlay_background_color = 0x7f0c0035; public static final int cast_intro_overlay_button_background_color = 0x7f0c0036; public static final int cast_libraries_material_featurehighlight_outer_highlight_default_color = 0x7f0c0037; public static final int cast_libraries_material_featurehighlight_text_body_color = 0x7f0c0038; public static final int cast_libraries_material_featurehighlight_text_header_color = 0x7f0c0039; public static final int cast_mini_controller_main_background = 0x7f0c003a; public static final int common_google_signin_btn_text_dark = 0x7f0c0127; public static final int common_google_signin_btn_text_dark_default = 0x7f0c0044; public static final int common_google_signin_btn_text_dark_disabled = 0x7f0c0045; public static final int common_google_signin_btn_text_dark_focused = 0x7f0c0046; public static final int common_google_signin_btn_text_dark_pressed = 0x7f0c0047; public static final int common_google_signin_btn_text_light = 0x7f0c0128; public static final int common_google_signin_btn_text_light_default = 0x7f0c0048; public static final int common_google_signin_btn_text_light_disabled = 0x7f0c0049; public static final int common_google_signin_btn_text_light_focused = 0x7f0c004a; public static final int common_google_signin_btn_text_light_pressed = 0x7f0c004b; public static final int common_plus_signin_btn_text_dark = 0x7f0c0129; public static final int common_plus_signin_btn_text_dark_default = 0x7f0c004c; public static final int common_plus_signin_btn_text_dark_disabled = 0x7f0c004d; public static final int common_plus_signin_btn_text_dark_focused = 0x7f0c004e; public static final int common_plus_signin_btn_text_dark_pressed = 0x7f0c004f; public static final int common_plus_signin_btn_text_light = 0x7f0c012a; public static final int common_plus_signin_btn_text_light_default = 0x7f0c0050; public static final int common_plus_signin_btn_text_light_disabled = 0x7f0c0051; public static final int common_plus_signin_btn_text_light_focused = 0x7f0c0052; public static final int common_plus_signin_btn_text_light_pressed = 0x7f0c0053; public static final int place_autocomplete_prediction_primary_text = 0x7f0c00cd; public static final int place_autocomplete_prediction_primary_text_highlight = 0x7f0c00ce; public static final int place_autocomplete_prediction_secondary_text = 0x7f0c00cf; public static final int place_autocomplete_search_hint = 0x7f0c00d0; public static final int place_autocomplete_search_text = 0x7f0c00d1; public static final int place_autocomplete_separator = 0x7f0c00d2; public static final int wallet_bright_foreground_disabled_holo_light = 0x7f0c00fe; public static final int wallet_bright_foreground_holo_dark = 0x7f0c00ff; public static final int wallet_bright_foreground_holo_light = 0x7f0c0100; public static final int wallet_dim_foreground_disabled_holo_dark = 0x7f0c0101; public static final int wallet_dim_foreground_holo_dark = 0x7f0c0102; public static final int wallet_dim_foreground_inverse_disabled_holo_dark = 0x7f0c0103; public static final int wallet_dim_foreground_inverse_holo_dark = 0x7f0c0104; public static final int wallet_highlighted_text_holo_dark = 0x7f0c0105; public static final int wallet_highlighted_text_holo_light = 0x7f0c0106; public static final int wallet_hint_foreground_holo_dark = 0x7f0c0107; public static final int wallet_hint_foreground_holo_light = 0x7f0c0108; public static final int wallet_holo_blue_light = 0x7f0c0109; public static final int wallet_link_text_light = 0x7f0c010a; public static final int wallet_primary_text_holo_light = 0x7f0c012d; public static final int wallet_secondary_text_holo_dark = 0x7f0c012e; } public static final class dimen { public static final int cast_intro_overlay_button_margin_bottom = 0x7f0800b8; public static final int cast_intro_overlay_focus_radius = 0x7f0800b9; public static final int cast_intro_overlay_title_margin_top = 0x7f0800ba; public static final int cast_libraries_material_featurehighlight_center_horizontal_offset = 0x7f0800bb; public static final int cast_libraries_material_featurehighlight_center_threshold = 0x7f0800bc; public static final int cast_libraries_material_featurehighlight_inner_margin = 0x7f0800bd; public static final int cast_libraries_material_featurehighlight_inner_radius = 0x7f0800be; public static final int cast_libraries_material_featurehighlight_outer_padding = 0x7f0800bf; public static final int cast_libraries_material_featurehighlight_text_body_size = 0x7f0800c0; public static final int cast_libraries_material_featurehighlight_text_header_size = 0x7f0800c1; public static final int cast_libraries_material_featurehighlight_text_horizontal_margin = 0x7f0800c2; public static final int cast_libraries_material_featurehighlight_text_horizontal_offset = 0x7f0800c3; public static final int cast_libraries_material_featurehighlight_text_max_width = 0x7f0800c4; public static final int cast_libraries_material_featurehighlight_text_vertical_space = 0x7f0800c5; public static final int cast_mini_controller_font_size_line1 = 0x7f0800c6; public static final int cast_mini_controller_font_size_line2 = 0x7f0800c7; public static final int cast_mini_controller_icon_height = 0x7f0800c8; public static final int cast_mini_controller_icon_width = 0x7f0800c9; public static final int cast_notification_image_size = 0x7f0800ca; public static final int cast_tracks_chooser_dialog_no_message_text_size = 0x7f0800cb; public static final int cast_tracks_chooser_dialog_row_text_size = 0x7f0800cc; public static final int place_autocomplete_button_padding = 0x7f080121; public static final int place_autocomplete_powered_by_google_height = 0x7f080122; public static final int place_autocomplete_powered_by_google_start = 0x7f080123; public static final int place_autocomplete_prediction_height = 0x7f080124; public static final int place_autocomplete_prediction_horizontal_margin = 0x7f080125; public static final int place_autocomplete_prediction_primary_text = 0x7f080126; public static final int place_autocomplete_prediction_secondary_text = 0x7f080127; public static final int place_autocomplete_progress_horizontal_margin = 0x7f080128; public static final int place_autocomplete_progress_size = 0x7f080129; public static final int place_autocomplete_separator_start = 0x7f08012a; } public static final class drawable { public static final int cast_album_art_placeholder = 0x7f02007d; public static final int cast_album_art_placeholder_large = 0x7f02007e; public static final int cast_ic_mini_controller_pause = 0x7f02007f; public static final int cast_ic_mini_controller_play = 0x7f020080; public static final int cast_ic_mini_controller_stop = 0x7f020081; public static final int cast_ic_mini_controller_upcoming_play = 0x7f020082; public static final int cast_ic_mini_controller_upcoming_stop = 0x7f020083; public static final int cast_ic_notification_0 = 0x7f020084; public static final int cast_ic_notification_1 = 0x7f020085; public static final int cast_ic_notification_2 = 0x7f020086; public static final int cast_ic_notification_connecting = 0x7f020087; public static final int cast_ic_notification_disconnect = 0x7f020088; public static final int cast_ic_notification_forward = 0x7f020089; public static final int cast_ic_notification_forward10 = 0x7f02008a; public static final int cast_ic_notification_forward30 = 0x7f02008b; public static final int cast_ic_notification_on = 0x7f02008c; public static final int cast_ic_notification_pause = 0x7f02008d; public static final int cast_ic_notification_play = 0x7f02008e; public static final int cast_ic_notification_rewind = 0x7f02008f; public static final int cast_ic_notification_rewind10 = 0x7f020090; public static final int cast_ic_notification_rewind30 = 0x7f020091; public static final int cast_ic_notification_skip_next = 0x7f020092; public static final int cast_ic_notification_skip_prev = 0x7f020093; public static final int cast_ic_notification_small_icon = 0x7f020094; public static final int cast_ic_notification_stop_live_stream = 0x7f020095; public static final int cast_mini_controller_gradient_light = 0x7f020096; public static final int cast_mini_controller_img_placeholder = 0x7f020097; public static final int cast_mini_controller_progress_drawable = 0x7f020098; public static final int common_full_open_on_phone = 0x7f0200a2; public static final int common_google_signin_btn_icon_dark = 0x7f0200a3; public static final int common_google_signin_btn_icon_dark_disabled = 0x7f0200a4; public static final int common_google_signin_btn_icon_dark_focused = 0x7f0200a5; public static final int common_google_signin_btn_icon_dark_normal = 0x7f0200a6; public static final int common_google_signin_btn_icon_dark_pressed = 0x7f0200a7; public static final int common_google_signin_btn_icon_light = 0x7f0200a8; public static final int common_google_signin_btn_icon_light_disabled = 0x7f0200a9; public static final int common_google_signin_btn_icon_light_focused = 0x7f0200aa; public static final int common_google_signin_btn_icon_light_normal = 0x7f0200ab; public static final int common_google_signin_btn_icon_light_pressed = 0x7f0200ac; public static final int common_google_signin_btn_text_dark = 0x7f0200ad; public static final int common_google_signin_btn_text_dark_disabled = 0x7f0200ae; public static final int common_google_signin_btn_text_dark_focused = 0x7f0200af; public static final int common_google_signin_btn_text_dark_normal = 0x7f0200b0; public static final int common_google_signin_btn_text_dark_pressed = 0x7f0200b1; public static final int common_google_signin_btn_text_light = 0x7f0200b2; public static final int common_google_signin_btn_text_light_disabled = 0x7f0200b3; public static final int common_google_signin_btn_text_light_focused = 0x7f0200b4; public static final int common_google_signin_btn_text_light_normal = 0x7f0200b5; public static final int common_google_signin_btn_text_light_pressed = 0x7f0200b6; public static final int common_ic_googleplayservices = 0x7f0200b7; public static final int common_plus_signin_btn_icon_dark = 0x7f0200b8; public static final int common_plus_signin_btn_icon_dark_disabled = 0x7f0200b9; public static final int common_plus_signin_btn_icon_dark_focused = 0x7f0200ba; public static final int common_plus_signin_btn_icon_dark_normal = 0x7f0200bb; public static final int common_plus_signin_btn_icon_dark_pressed = 0x7f0200bc; public static final int common_plus_signin_btn_icon_light = 0x7f0200bd; public static final int common_plus_signin_btn_icon_light_disabled = 0x7f0200be; public static final int common_plus_signin_btn_icon_light_focused = 0x7f0200bf; public static final int common_plus_signin_btn_icon_light_normal = 0x7f0200c0; public static final int common_plus_signin_btn_icon_light_pressed = 0x7f0200c1; public static final int common_plus_signin_btn_text_dark = 0x7f0200c2; public static final int common_plus_signin_btn_text_dark_disabled = 0x7f0200c3; public static final int common_plus_signin_btn_text_dark_focused = 0x7f0200c4; public static final int common_plus_signin_btn_text_dark_normal = 0x7f0200c5; public static final int common_plus_signin_btn_text_dark_pressed = 0x7f0200c6; public static final int common_plus_signin_btn_text_light = 0x7f0200c7; public static final int common_plus_signin_btn_text_light_disabled = 0x7f0200c8; public static final int common_plus_signin_btn_text_light_focused = 0x7f0200c9; public static final int common_plus_signin_btn_text_light_normal = 0x7f0200ca; public static final int common_plus_signin_btn_text_light_pressed = 0x7f0200cb; public static final int ic_plusone_medium_off_client = 0x7f020118; public static final int ic_plusone_small_off_client = 0x7f020119; public static final int ic_plusone_standard_off_client = 0x7f02011a; public static final int ic_plusone_tall_off_client = 0x7f02011b; public static final int places_ic_clear = 0x7f020198; public static final int places_ic_search = 0x7f020199; public static final int powered_by_google_dark = 0x7f0201a0; public static final int powered_by_google_light = 0x7f0201a1; public static final int quantum_ic_cast_connected_white_24 = 0x7f0201a2; public static final int quantum_ic_cast_white_36 = 0x7f0201a3; public static final int quantum_ic_clear_white_24 = 0x7f0201a4; public static final int quantum_ic_forward_10_white_24 = 0x7f0201a5; public static final int quantum_ic_forward_30_white_24 = 0x7f0201a6; public static final int quantum_ic_pause_grey600_48 = 0x7f0201a7; public static final int quantum_ic_pause_white_24 = 0x7f0201a8; public static final int quantum_ic_play_arrow_grey600_48 = 0x7f0201a9; public static final int quantum_ic_play_arrow_white_24 = 0x7f0201aa; public static final int quantum_ic_refresh_white_24 = 0x7f0201ab; public static final int quantum_ic_replay_10_white_24 = 0x7f0201ac; public static final int quantum_ic_replay_30_white_24 = 0x7f0201ad; public static final int quantum_ic_replay_white_24 = 0x7f0201ae; public static final int quantum_ic_skip_next_white_24 = 0x7f0201af; public static final int quantum_ic_skip_previous_white_24 = 0x7f0201b0; public static final int quantum_ic_stop_grey600_48 = 0x7f0201b1; public static final int quantum_ic_stop_white_24 = 0x7f0201b2; } public static final class id { public static final int adjust_height = 0x7f0e0055; public static final int adjust_width = 0x7f0e0056; public static final int android_pay = 0x7f0e008b; public static final int android_pay_dark = 0x7f0e0082; public static final int android_pay_light = 0x7f0e0083; public static final int android_pay_light_with_border = 0x7f0e0084; public static final int audio_empty_message = 0x7f0e00ff; public static final int audio_list_view = 0x7f0e00fd; public static final int auto = 0x7f0e006f; public static final int book_now = 0x7f0e007b; public static final int button = 0x7f0e00f2; public static final int buyButton = 0x7f0e0078; public static final int buy_now = 0x7f0e007c; public static final int buy_with = 0x7f0e007d; public static final int buy_with_google = 0x7f0e007e; public static final int cast_featurehighlight_help_text_body_view = 0x7f0e0004; public static final int cast_featurehighlight_help_text_header_view = 0x7f0e0005; public static final int cast_featurehighlight_view = 0x7f0e0006; public static final int cast_notification_id = 0x7f0e0007; public static final int center = 0x7f0e001d; public static final int classic = 0x7f0e0085; public static final int contact = 0x7f0e0050; public static final int container_all = 0x7f0e00f3; public static final int container_current = 0x7f0e00f4; public static final int crash_reporting_present = 0x7f0e0008; public static final int dark = 0x7f0e0043; public static final int demote_common_words = 0x7f0e0066; public static final int demote_rfc822_hostnames = 0x7f0e0067; public static final int donate_with = 0x7f0e007f; public static final int donate_with_google = 0x7f0e0080; public static final int email = 0x7f0e0051; public static final int google_wallet_classic = 0x7f0e0086; public static final int google_wallet_grayscale = 0x7f0e0087; public static final int google_wallet_monochrome = 0x7f0e0088; public static final int grayscale = 0x7f0e0089; public static final int holo_dark = 0x7f0e0072; public static final int holo_light = 0x7f0e0073; public static final int html = 0x7f0e0062; public static final int hybrid = 0x7f0e0057; public static final int icon_only = 0x7f0e006c; public static final int icon_uri = 0x7f0e0046; public static final int icon_view = 0x7f0e00f5; public static final int index_entity_types = 0x7f0e0068; public static final int instant_message = 0x7f0e0052; public static final int intent_action = 0x7f0e0047; public static final int intent_activity = 0x7f0e0048; public static final int intent_data = 0x7f0e0049; public static final int intent_data_id = 0x7f0e004a; public static final int intent_extra_data = 0x7f0e004b; public static final int large_icon_uri = 0x7f0e004c; public static final int light = 0x7f0e0044; public static final int loading_view = 0x7f0e00f7; public static final int logo_only = 0x7f0e0081; public static final int match_global_nicknames = 0x7f0e0069; public static final int match_parent = 0x7f0e007a; public static final int monochrome = 0x7f0e008a; public static final int none = 0x7f0e001c; public static final int normal = 0x7f0e0021; public static final int omnibox_title_section = 0x7f0e006a; public static final int omnibox_url_section = 0x7f0e006b; public static final int place_autocomplete_clear_button = 0x7f0e0217; public static final int place_autocomplete_powered_by_google = 0x7f0e0219; public static final int place_autocomplete_prediction_primary_text = 0x7f0e021b; public static final int place_autocomplete_prediction_secondary_text = 0x7f0e021c; public static final int place_autocomplete_progress = 0x7f0e021a; public static final int place_autocomplete_search_button = 0x7f0e0215; public static final int place_autocomplete_search_input = 0x7f0e0216; public static final int place_autocomplete_separator = 0x7f0e0218; public static final int plain = 0x7f0e0063; public static final int play_pause = 0x7f0e00f6; public static final int production = 0x7f0e0074; public static final int progressBar = 0x7f0e00fa; public static final int radio = 0x7f0e00a8; public static final int rfc822 = 0x7f0e0064; public static final int sandbox = 0x7f0e0075; public static final int satellite = 0x7f0e0058; public static final int selectionDetails = 0x7f0e0079; public static final int slide = 0x7f0e0042; public static final int standard = 0x7f0e006d; public static final int strict_sandbox = 0x7f0e0076; public static final int subtitle_view = 0x7f0e00f9; public static final int tab_host = 0x7f0e00fb; public static final int terrain = 0x7f0e0059; public static final int test = 0x7f0e0077; public static final int text = 0x7f0e00e6; public static final int text1 = 0x7f0e004d; public static final int text2 = 0x7f0e004e; public static final int textTitle = 0x7f0e00f1; public static final int text_empty_message = 0x7f0e00fe; public static final int text_list_view = 0x7f0e00fc; public static final int thing_proto = 0x7f0e004f; public static final int title_view = 0x7f0e00f8; public static final int url = 0x7f0e0065; public static final int wide = 0x7f0e006e; public static final int wrap_content = 0x7f0e0034; } public static final class integer { public static final int cast_libraries_material_featurehighlight_pulse_base_alpha = 0x7f0a0006; public static final int google_play_services_version = 0x7f0a0007; } public static final class layout { public static final int cast_help_text = 0x7f040026; public static final int cast_intro_overlay = 0x7f040027; public static final int cast_mini_controller = 0x7f040028; public static final int cast_tracks_chooser_dialog_layout = 0x7f040029; public static final int cast_tracks_chooser_dialog_row_layout = 0x7f04002a; public static final int place_autocomplete_fragment = 0x7f040091; public static final int place_autocomplete_item_powered_by_google = 0x7f040092; public static final int place_autocomplete_item_prediction = 0x7f040093; public static final int place_autocomplete_progress = 0x7f040094; } public static final class raw { public static final int gtm_analytics = 0x7f060000; } public static final class string { public static final int accept = 0x7f070013; public static final int cast_casting_to_device = 0x7f070014; public static final int cast_disconnect = 0x7f070015; public static final int cast_forward = 0x7f070016; public static final int cast_forward_10 = 0x7f070017; public static final int cast_forward_30 = 0x7f070018; public static final int cast_intro_overlay_button_text = 0x7f070019; public static final int cast_mute = 0x7f07001a; public static final int cast_notification_connected_message = 0x7f07001b; public static final int cast_notification_connecting_message = 0x7f07001c; public static final int cast_notification_disconnect = 0x7f07001d; public static final int cast_pause = 0x7f07001e; public static final int cast_play = 0x7f07001f; public static final int cast_rewind = 0x7f070020; public static final int cast_rewind_10 = 0x7f070021; public static final int cast_rewind_30 = 0x7f070022; public static final int cast_skip_next = 0x7f070023; public static final int cast_skip_prev = 0x7f070024; public static final int cast_stop = 0x7f070025; public static final int cast_stop_live_stream = 0x7f070026; public static final int cast_tracks_chooser_dialog_audio = 0x7f070027; public static final int cast_tracks_chooser_dialog_cancel = 0x7f070028; public static final int cast_tracks_chooser_dialog_no_audio_tracks = 0x7f070029; public static final int cast_tracks_chooser_dialog_no_text_tracks = 0x7f07002a; public static final int cast_tracks_chooser_dialog_no_tracks_available = 0x7f07002b; public static final int cast_tracks_chooser_dialog_none = 0x7f07002c; public static final int cast_tracks_chooser_dialog_ok = 0x7f07002d; public static final int cast_tracks_chooser_dialog_subtitles = 0x7f07002e; public static final int cast_unmute = 0x7f07002f; public static final int common_google_play_services_api_unavailable_text = 0x7f070030; public static final int common_google_play_services_enable_button = 0x7f070031; public static final int common_google_play_services_enable_text = 0x7f070032; public static final int common_google_play_services_enable_title = 0x7f070033; public static final int common_google_play_services_install_button = 0x7f070034; public static final int common_google_play_services_install_text_phone = 0x7f070035; public static final int common_google_play_services_install_text_tablet = 0x7f070036; public static final int common_google_play_services_install_title = 0x7f070037; public static final int common_google_play_services_invalid_account_text = 0x7f070038; public static final int common_google_play_services_invalid_account_title = 0x7f070039; public static final int common_google_play_services_network_error_text = 0x7f07003a; public static final int common_google_play_services_network_error_title = 0x7f07003b; public static final int common_google_play_services_notification_ticker = 0x7f07003c; public static final int common_google_play_services_resolution_required_text = 0x7f07003d; public static final int common_google_play_services_resolution_required_title = 0x7f07003e; public static final int common_google_play_services_restricted_profile_text = 0x7f07003f; public static final int common_google_play_services_restricted_profile_title = 0x7f070040; public static final int common_google_play_services_sign_in_failed_text = 0x7f070041; public static final int common_google_play_services_sign_in_failed_title = 0x7f070042; public static final int common_google_play_services_unknown_issue = 0x7f070043; public static final int common_google_play_services_unsupported_text = 0x7f070044; public static final int common_google_play_services_unsupported_title = 0x7f070045; public static final int common_google_play_services_update_button = 0x7f070046; public static final int common_google_play_services_update_text = 0x7f070047; public static final int common_google_play_services_update_title = 0x7f070048; public static final int common_google_play_services_updating_text = 0x7f070049; public static final int common_google_play_services_updating_title = 0x7f07004a; public static final int common_google_play_services_wear_update_text = 0x7f07004b; public static final int common_open_on_phone = 0x7f07004c; public static final int common_signin_button_text = 0x7f07004d; public static final int common_signin_button_text_long = 0x7f07004e; public static final int create_calendar_message = 0x7f07004f; public static final int create_calendar_title = 0x7f070050; public static final int decline = 0x7f070051; public static final int place_autocomplete_clear_button = 0x7f07005d; public static final int place_autocomplete_search_hint = 0x7f07005e; public static final int store_picture_message = 0x7f070061; public static final int store_picture_title = 0x7f070062; public static final int tagmanager_preview_dialog_button = 0x7f070166; public static final int tagmanager_preview_dialog_message = 0x7f070167; public static final int tagmanager_preview_dialog_title = 0x7f070168; public static final int wallet_buy_button_place_holder = 0x7f070063; } public static final class style { public static final int CastIntroOverlay = 0x7f0900dc; public static final int CastMiniController = 0x7f0900dd; public static final int TextAppearance_CastIntroOverlay_Button = 0x7f09011a; public static final int TextAppearance_CastIntroOverlay_Title = 0x7f09011b; public static final int TextAppearance_CastMiniController_Subtitle = 0x7f09011c; public static final int TextAppearance_CastMiniController_Title = 0x7f09011d; public static final int Theme_AppInvite_Preview = 0x7f090136; public static final int Theme_AppInvite_Preview_Base = 0x7f090026; public static final int Theme_IAPTheme = 0x7f09013d; public static final int WalletFragmentDefaultButtonTextAppearance = 0x7f090147; public static final int WalletFragmentDefaultDetailsHeaderTextAppearance = 0x7f090148; public static final int WalletFragmentDefaultDetailsTextAppearance = 0x7f090149; public static final int WalletFragmentDefaultStyle = 0x7f09014a; } public static final class styleable { public static final int[] AdsAttrs = { 0x7f010071, 0x7f010072, 0x7f010073 }; public static final int AdsAttrs_adSize = 0; public static final int AdsAttrs_adSizes = 1; public static final int AdsAttrs_adUnitId = 2; public static final int[] AppDataSearch = { }; public static final int[] CastIntroOverlay = { 0x7f010106, 0x7f010107, 0x7f010108, 0x7f010109, 0x7f01010a, 0x7f01010b }; public static final int CastIntroOverlay_castBackgroundColor = 0; public static final int CastIntroOverlay_castButtonBackgroundColor = 1; public static final int CastIntroOverlay_castButtonText = 3; public static final int CastIntroOverlay_castButtonTextAppearance = 2; public static final int CastIntroOverlay_castFocusRadius = 5; public static final int CastIntroOverlay_castTitleTextAppearance = 4; public static final int[] CastMiniController = { 0x7f01010a, 0x7f01010c, 0x7f01010d }; public static final int CastMiniController_castShowImageThumbnail = 1; public static final int CastMiniController_castSubtitleTextAppearance = 2; public static final int CastMiniController_castTitleTextAppearance = 0; public static final int[] Corpus = { 0x7f010126, 0x7f010127, 0x7f010128, 0x7f010129, 0x7f01012a, 0x7f01012b, 0x7f01012c }; public static final int Corpus_contentProviderUri = 2; public static final int Corpus_corpusId = 0; public static final int Corpus_corpusVersion = 1; public static final int Corpus_perAccountTemplate = 6; public static final int Corpus_schemaOrgType = 4; public static final int Corpus_semanticallySearchable = 5; public static final int Corpus_trimmable = 3; public static final int[] CustomCastTheme = { 0x7f01012d, 0x7f01012e }; public static final int CustomCastTheme_castIntroOverlayStyle = 0; public static final int CustomCastTheme_castMiniControllerStyle = 1; public static final int[] CustomWalletTheme = { 0x7f01012f, 0x7f010130 }; public static final int CustomWalletTheme_toolbarTextColorStyle = 1; public static final int CustomWalletTheme_windowTransitionStyle = 0; public static final int[] FeatureParam = { 0x7f01013c, 0x7f01013d }; public static final int FeatureParam_paramName = 0; public static final int FeatureParam_paramValue = 1; public static final int[] GlobalSearch = { 0x7f010144, 0x7f010145, 0x7f010146, 0x7f010147, 0x7f010148, 0x7f010149 }; public static final int[] GlobalSearchCorpus = { 0x7f01014a }; public static final int GlobalSearchCorpus_allowShortcuts = 0; public static final int[] GlobalSearchSection = { 0x7f01014b, 0x7f01014c }; public static final int GlobalSearchSection_sectionContent = 1; public static final int GlobalSearchSection_sectionType = 0; public static final int GlobalSearch_defaultIntentAction = 3; public static final int GlobalSearch_defaultIntentActivity = 5; public static final int GlobalSearch_defaultIntentData = 4; public static final int GlobalSearch_searchEnabled = 0; public static final int GlobalSearch_searchLabel = 1; public static final int GlobalSearch_settingsDescription = 2; public static final int[] IMECorpus = { 0x7f01014d, 0x7f01014e, 0x7f01014f, 0x7f010150, 0x7f010151, 0x7f010152 }; public static final int IMECorpus_inputEnabled = 0; public static final int IMECorpus_sourceClass = 1; public static final int IMECorpus_toAddressesSection = 5; public static final int IMECorpus_userInputSection = 3; public static final int IMECorpus_userInputTag = 2; public static final int IMECorpus_userInputValue = 4; public static final int[] LoadingImageView = { 0x7f010156, 0x7f010157, 0x7f010158 }; public static final int LoadingImageView_circleCrop = 2; public static final int LoadingImageView_imageAspectRatio = 1; public static final int LoadingImageView_imageAspectRatioAdjust = 0; public static final int[] MapAttrs = { 0x7f01015a, 0x7f01015b, 0x7f01015c, 0x7f01015d, 0x7f01015e, 0x7f01015f, 0x7f010160, 0x7f010161, 0x7f010162, 0x7f010163, 0x7f010164, 0x7f010165, 0x7f010166, 0x7f010167, 0x7f010168, 0x7f010169, 0x7f01016a }; public static final int MapAttrs_ambientEnabled = 16; public static final int MapAttrs_cameraBearing = 1; public static final int MapAttrs_cameraTargetLat = 2; public static final int MapAttrs_cameraTargetLng = 3; public static final int MapAttrs_cameraTilt = 4; public static final int MapAttrs_cameraZoom = 5; public static final int MapAttrs_liteMode = 6; public static final int MapAttrs_mapType = 0; public static final int MapAttrs_uiCompass = 7; public static final int MapAttrs_uiMapToolbar = 15; public static final int MapAttrs_uiRotateGestures = 8; public static final int MapAttrs_uiScrollGestures = 9; public static final int MapAttrs_uiTiltGestures = 10; public static final int MapAttrs_uiZoomControls = 11; public static final int MapAttrs_uiZoomGestures = 12; public static final int MapAttrs_useViewLifecycle = 13; public static final int MapAttrs_zOrderOnTop = 14; public static final int[] Section = { 0x7f0101a8, 0x7f0101a9, 0x7f0101aa, 0x7f0101ab, 0x7f0101ac, 0x7f0101ad, 0x7f0101ae }; public static final int[] SectionFeature = { 0x7f0101af }; public static final int SectionFeature_featureType = 0; public static final int Section_indexPrefixes = 4; public static final int Section_noIndex = 2; public static final int Section_schemaOrgProperty = 6; public static final int Section_sectionFormat = 1; public static final int Section_sectionId = 0; public static final int Section_sectionWeight = 3; public static final int Section_subsectionSeparator = 5; public static final int[] SignInButton = { 0x7f0101b0, 0x7f0101b1, 0x7f0101b2 }; public static final int SignInButton_buttonSize = 0; public static final int SignInButton_colorScheme = 1; public static final int SignInButton_scopeUris = 2; public static final int[] WalletFragmentOptions = { 0x7f0101ee, 0x7f0101ef, 0x7f0101f0, 0x7f0101f1 }; public static final int WalletFragmentOptions_appTheme = 0; public static final int WalletFragmentOptions_environment = 1; public static final int WalletFragmentOptions_fragmentMode = 3; public static final int WalletFragmentOptions_fragmentStyle = 2; public static final int[] WalletFragmentStyle = { 0x7f0101f2, 0x7f0101f3, 0x7f0101f4, 0x7f0101f5, 0x7f0101f6, 0x7f0101f7, 0x7f0101f8, 0x7f0101f9, 0x7f0101fa, 0x7f0101fb, 0x7f0101fc }; public static final int WalletFragmentStyle_buyButtonAppearance = 3; public static final int WalletFragmentStyle_buyButtonHeight = 0; public static final int WalletFragmentStyle_buyButtonText = 2; public static final int WalletFragmentStyle_buyButtonWidth = 1; public static final int WalletFragmentStyle_maskedWalletDetailsBackground = 6; public static final int WalletFragmentStyle_maskedWalletDetailsButtonBackground = 8; public static final int WalletFragmentStyle_maskedWalletDetailsButtonTextAppearance = 7; public static final int WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance = 5; public static final int WalletFragmentStyle_maskedWalletDetailsLogoImageType = 10; public static final int WalletFragmentStyle_maskedWalletDetailsLogoTextColor = 9; public static final int WalletFragmentStyle_maskedWalletDetailsTextAppearance = 4; } }
3e0a1a78fa6dc921a4486ede9ca5a4eafe4ca01a
18,946
java
Java
core/src/main/java/org/apache/brooklyn/core/BrooklynVersion.java
johnmccabe/PRESPLIT-incubator-brooklyn
e6235d9bcfce0829e3160302a568422c1429c5ae
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
128
2015-01-06T13:58:09.000Z
2021-11-10T19:24:40.000Z
core/src/main/java/org/apache/brooklyn/core/BrooklynVersion.java
johnmccabe/PRESPLIT-incubator-brooklyn
e6235d9bcfce0829e3160302a568422c1429c5ae
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
743
2015-01-05T13:24:33.000Z
2016-05-26T13:16:54.000Z
core/src/main/java/org/apache/brooklyn/core/BrooklynVersion.java
johnmccabe/PRESPLIT-incubator-brooklyn
e6235d9bcfce0829e3160302a568422c1429c5ae
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
118
2015-01-06T15:30:12.000Z
2021-11-10T19:24:30.000Z
42.008869
132
0.62277
4,280
/* * 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.brooklyn.core; import static com.google.common.base.Preconditions.checkNotNull; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.Map; import java.util.Properties; import java.util.concurrent.atomic.AtomicReference; import java.util.jar.Attributes; import javax.annotation.Nullable; import org.osgi.framework.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Objects; import com.google.common.base.Optional; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import java.util.Arrays; import java.util.Dictionary; import java.util.Hashtable; import java.util.List; import org.apache.brooklyn.api.catalog.CatalogItem; import org.apache.brooklyn.api.mgmt.ManagementContext; import org.apache.brooklyn.core.mgmt.classloading.OsgiBrooklynClassLoadingContext; import org.apache.brooklyn.core.mgmt.ha.OsgiManager; import org.apache.brooklyn.core.mgmt.internal.ManagementContextInternal; import org.apache.brooklyn.util.core.ResourceUtils; import org.apache.brooklyn.rt.felix.ManifestHelper; import org.apache.brooklyn.util.core.osgi.Osgis; import org.apache.brooklyn.util.exceptions.Exceptions; import org.apache.brooklyn.util.guava.Maybe; import org.apache.brooklyn.util.stream.Streams; import org.apache.brooklyn.util.text.Strings; import org.osgi.framework.Bundle; import org.osgi.framework.FrameworkUtil; /** * Wraps the version of Brooklyn. * <p> * Also retrieves the SHA-1 from any OSGi bundle, and checks that the maven and osgi versions match. */ public class BrooklynVersion { private static final Logger log = LoggerFactory.getLogger(BrooklynVersion.class); private static final String MVN_VERSION_RESOURCE_FILE = "META-INF/maven/org.apache.brooklyn/brooklyn-core/pom.properties"; private static final String MANIFEST_PATH = "META-INF/MANIFEST.MF"; private static final String BROOKLYN_CORE_SYMBOLIC_NAME = "org.apache.brooklyn.core"; private static final String MVN_VERSION_PROPERTY_NAME = "version"; private static final String OSGI_VERSION_PROPERTY_NAME = Attributes.Name.IMPLEMENTATION_VERSION.toString(); private static final String OSGI_SHA1_PROPERTY_NAME = "Implementation-SHA-1"; // may be useful: // private static final String OSGI_BRANCH_PROPERTY_NAME = "Implementation-Branch"; private final static String VERSION_FROM_STATIC = "0.9.0-SNAPSHOT"; // BROOKLYN_VERSION private static final AtomicReference<Boolean> IS_DEV_ENV = new AtomicReference<Boolean>(); private static final String BROOKLYN_FEATURE_PREFIX = "Brooklyn-Feature-"; public static final BrooklynVersion INSTANCE = new BrooklynVersion(); private final Properties versionProperties = new Properties(); private BrooklynVersion() { // we read the maven pom metadata and osgi metadata and make sure it's sensible // everything is put into a single map for now (good enough, but should be cleaned up) readPropertiesFromMavenResource(BrooklynVersion.class.getClassLoader()); readPropertiesFromOsgiResource(); // TODO there is also build-metadata.properties used in ServerResource /v1/server/version endpoint // see comments on that about folding it into this class instead checkVersions(); } public void checkVersions() { String mvnVersion = getVersionFromMavenProperties(); if (mvnVersion != null && !VERSION_FROM_STATIC.equals(mvnVersion)) { throw new IllegalStateException("Version error: maven " + mvnVersion + " / code " + VERSION_FROM_STATIC); } String osgiVersion = versionProperties.getProperty(OSGI_VERSION_PROPERTY_NAME); // TODO does the OSGi version include other slightly differ gubbins/style ? if (osgiVersion != null && !VERSION_FROM_STATIC.equals(osgiVersion)) { throw new IllegalStateException("Version error: osgi " + osgiVersion + " / code " + VERSION_FROM_STATIC); } } /** * Returns version as inferred from classpath/osgi, if possible, or 0.0.0-SNAPSHOT. * See also {@link #getVersionFromMavenProperties()} and {@link #getVersionFromOsgiManifest()}. * * @deprecated since 0.7.0, in favour of the more specific methods (and does anyone need that default value?) */ @Deprecated public String getVersionFromClasspath() { String v = getVersionFromMavenProperties(); if (Strings.isNonBlank(v)) return v; v = getVersionFromOsgiManifest(); if (Strings.isNonBlank(v)) return v; return "0.0.0-SNAPSHOT"; } @Nullable public String getVersionFromMavenProperties() { return versionProperties.getProperty(MVN_VERSION_PROPERTY_NAME); } @Nullable public String getVersionFromOsgiManifest() { return versionProperties.getProperty(OSGI_VERSION_PROPERTY_NAME); } @Nullable /** SHA1 of the last commit to brooklyn at the time this build was made. * For SNAPSHOT builds of course there may have been further non-committed changes. */ public String getSha1FromOsgiManifest() { return versionProperties.getProperty(OSGI_SHA1_PROPERTY_NAME); } public String getVersion() { return VERSION_FROM_STATIC; } public boolean isSnapshot() { return (getVersion().indexOf("-SNAPSHOT") >= 0); } private void readPropertiesFromMavenResource(ClassLoader resourceLoader) { InputStream versionStream = null; try { versionStream = resourceLoader.getResourceAsStream(MVN_VERSION_RESOURCE_FILE); if (versionStream == null) { if (isDevelopmentEnvironment()) { // allowed for dev env log.trace("No maven resource file " + MVN_VERSION_RESOURCE_FILE + " available"); } else { log.warn("No maven resource file " + MVN_VERSION_RESOURCE_FILE + " available"); } return; } versionProperties.load(checkNotNull(versionStream)); } catch (IOException e) { log.warn("Error reading maven resource file " + MVN_VERSION_RESOURCE_FILE + ": " + e, e); } finally { Streams.closeQuietly(versionStream); } } /** * Reads main attributes properties from brooklyn-core's bundle manifest. */ private void readPropertiesFromOsgiResource() { if (Osgis.isBrooklynInsideFramework()) { Dictionary<String, String> headers = FrameworkUtil.getBundle(BrooklynVersion.class).getHeaders(); for (Enumeration<String> keys = headers.keys(); keys.hasMoreElements();) { String key = keys.nextElement(); versionProperties.put(key, headers.get(key)); } } else { Enumeration<URL> paths; try { paths = BrooklynVersion.class.getClassLoader().getResources(MANIFEST_PATH); } catch (IOException e) { // shouldn't happen throw Exceptions.propagate(e); } while (paths.hasMoreElements()) { URL u = paths.nextElement(); InputStream us = null; try { us = u.openStream(); ManifestHelper mh = ManifestHelper.forManifest(us); if (BROOKLYN_CORE_SYMBOLIC_NAME.equals(mh.getSymbolicName())) { Attributes attrs = mh.getManifest().getMainAttributes(); for (Object key : attrs.keySet()) { // key is an Attribute.Name; toString converts to string versionProperties.put(key.toString(), attrs.getValue(key.toString())); } return; } } catch (Exception e) { Exceptions.propagateIfFatal(e); log.warn("Error reading OSGi manifest from " + u + " when determining version properties: " + e, e); } finally { Streams.closeQuietly(us); } } if (isDevelopmentEnvironment()) { // allowed for dev env log.trace("No OSGi manifest available to determine version properties"); } else { log.warn("No OSGi manifest available to determine version properties"); } } } /** * Returns whether this is a Brooklyn dev environment, * specifically core/target/classes/ is on the classpath for the org.apache.brooklyn.core project. * <p/> * In a packaged or library build of Brooklyn (normal usage) this should return false, * and all OSGi components should be available. * <p/> * There is no longer any way to force this, * such as the old BrooklynDevelopmentMode class; * but that could easily be added if required (eg as a system property). */ public static boolean isDevelopmentEnvironment() { Boolean isDevEnv = IS_DEV_ENV.get(); if (isDevEnv != null) return isDevEnv; synchronized (IS_DEV_ENV) { isDevEnv = computeIsDevelopmentEnvironment(); IS_DEV_ENV.set(isDevEnv); return isDevEnv; } } private static boolean computeIsDevelopmentEnvironment() { Enumeration<URL> paths; try { paths = BrooklynVersion.class.getClassLoader().getResources("org/apache/brooklyn/core/BrooklynVersion.class"); } catch (IOException e) { // shouldn't happen throw Exceptions.propagate(e); } while (paths.hasMoreElements()) { URL u = paths.nextElement(); // running fram a classes directory (including coverage-classes for cobertura) triggers dev env if (u.getPath().endsWith("org/apache/brooklyn/core/BrooklynVersion.class")) { try { log.debug("Brooklyn dev/src environment detected: BrooklynVersion class is at: " + u); return true; } catch (Exception e) { Exceptions.propagateIfFatal(e); log.warn("Error reading manifest to determine whether this is a development environment: " + e, e); } } } return false; } public void logSummary() { log.debug("Brooklyn version " + getVersion() + " (git SHA1 " + getSha1FromOsgiManifest() + ")"); } /** * @deprecated since 0.7.0, redundant with {@link #get()} */ @Deprecated public static String getVersionFromStatic() { return VERSION_FROM_STATIC; } public static String get() { return INSTANCE.getVersion(); } /** * @param mgmt The context to search for features. * @return An iterable containing all features found in the management context's classpath and catalogue. */ public static Iterable<BrooklynFeature> getFeatures(ManagementContext mgmt) { if (Osgis.isBrooklynInsideFramework()) { List<Bundle> bundles = Arrays.asList( FrameworkUtil.getBundle(BrooklynVersion.class) .getBundleContext() .getBundles() ); Maybe<OsgiManager> osgi = ((ManagementContextInternal)mgmt).getOsgiManager(); for (CatalogItem<?, ?> catalogItem : mgmt.getCatalog().getCatalogItems()) { if (osgi.isPresentAndNonNull()) { for (CatalogItem.CatalogBundle catalogBundle : catalogItem.getLibraries()) { Maybe<Bundle> osgiBundle = osgi.get().findBundle(catalogBundle); if (osgiBundle.isPresentAndNonNull()) { bundles.add(osgiBundle.get()); } } } } // Set over list in case a bundle is reported more than once (e.g. from classpath and from OSGi). // Not sure of validity of this approach over just reporting duplicates. ImmutableSet.Builder<BrooklynFeature> features = ImmutableSet.builder(); for(Bundle bundle : bundles) { Optional<BrooklynFeature> fs = BrooklynFeature.newFeature(bundle.getHeaders()); if (fs.isPresent()) { features.add(fs.get()); } } return features.build(); } else { Iterable<URL> manifests = ResourceUtils.create(mgmt).getResources(MANIFEST_PATH); for (CatalogItem<?, ?> catalogItem : mgmt.getCatalog().getCatalogItems()) { OsgiBrooklynClassLoadingContext osgiContext = new OsgiBrooklynClassLoadingContext( mgmt, catalogItem.getCatalogItemId(), catalogItem.getLibraries()); manifests = Iterables.concat(manifests, osgiContext.getResources(MANIFEST_PATH)); } // Set over list in case a bundle is reported more than once (e.g. from classpath and from OSGi). // Not sure of validity of this approach over just reporting duplicates. ImmutableSet.Builder<BrooklynFeature> features = ImmutableSet.builder(); for (URL manifest : manifests) { ManifestHelper mh = null; try { mh = ManifestHelper.forManifest(manifest); } catch (Exception e) { Exceptions.propagateIfFatal(e); log.debug("Error reading OSGi manifest from " + manifest + " when determining version properties: " + e, e); } if (mh == null) continue; Attributes attrs = mh.getManifest().getMainAttributes(); Optional<BrooklynFeature> fs = BrooklynFeature.newFeature(attrs); if (fs.isPresent()) { features.add(fs.get()); } } return features.build(); } } public static class BrooklynFeature { private final String name; private final String symbolicName; private final String version; private final String lastModified; private final Map<String, String> additionalData; BrooklynFeature(String name, String symbolicName, String version, String lastModified, Map<String, String> additionalData) { this.symbolicName = checkNotNull(symbolicName, "symbolicName"); this.name = name; this.version = version; this.lastModified = lastModified; this.additionalData = ImmutableMap.copyOf(additionalData); } private static Optional<BrooklynFeature> newFeature(Attributes attrs) { // unfortunately Attributes is a Map<Object,Object> Dictionary<String,String> headers = new Hashtable<>(); for (Map.Entry<Object, Object> entry : attrs.entrySet()) { headers.put(entry.getKey().toString(), entry.getValue().toString()); } return newFeature(headers); } /** @return Present if any attribute name begins with {@link #BROOKLYN_FEATURE_PREFIX}, absent otherwise. */ private static Optional<BrooklynFeature> newFeature(Dictionary<String,String> headers) { Map<String, String> additionalData = Maps.newHashMap(); for (Enumeration<String> keys = headers.keys(); keys.hasMoreElements();) { String key = keys.nextElement(); if (key.startsWith(BROOKLYN_FEATURE_PREFIX)) { String value = headers.get(key); if (!Strings.isBlank(value)) { additionalData.put(key, value); } } } if (additionalData.isEmpty()) { return Optional.absent(); } // Name is special cased as it a useful way to indicate a feature without String nameKey = BROOKLYN_FEATURE_PREFIX + "Name"; String name = Optional.fromNullable(additionalData.remove(nameKey)) .or(Optional.fromNullable(Constants.BUNDLE_NAME)) .or(headers.get(Constants.BUNDLE_SYMBOLICNAME)); return Optional.of(new BrooklynFeature( name, headers.get(Constants.BUNDLE_SYMBOLICNAME), headers.get(Constants.BUNDLE_VERSION), headers.get("Bnd-LastModified"), additionalData)); } public String getLastModified() { return lastModified; } public String getName() { return name; } public String getSymbolicName() { return symbolicName; } public String getVersion() { return version; } /** @return an unmodifiable map */ public Map<String, String> getAdditionalData() { return additionalData; } @Override public String toString() { return getClass().getSimpleName() + "{" + symbolicName + (version != null ? ":" + version : "") + "}"; } @Override public int hashCode() { return Objects.hashCode(symbolicName, version); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; BrooklynFeature that = (BrooklynFeature) other; if (!symbolicName.equals(that.symbolicName)) { return false; } else if (version != null ? !version.equals(that.version) : that.version != null) { return false; } return true; } } }
3e0a1b0eccf479fc74e1c1154cec7e1a25c6cc1c
11,507
java
Java
src/net/benmann/evald/ArgFunction.java
Ben-Mann/evald
0a651beb55e18c6aafeff982da0406b3ef4eb015
[ "MIT" ]
1
2018-07-12T12:08:12.000Z
2018-07-12T12:08:12.000Z
src/net/benmann/evald/ArgFunction.java
Ben-Mann/evald
0a651beb55e18c6aafeff982da0406b3ef4eb015
[ "MIT" ]
3
2018-05-01T03:37:54.000Z
2018-07-18T06:46:31.000Z
src/net/benmann/evald/ArgFunction.java
Ben-Mann/evald
0a651beb55e18c6aafeff982da0406b3ef4eb015
[ "MIT" ]
1
2018-04-19T16:15:30.000Z
2018-04-19T16:15:30.000Z
40.375439
147
0.596072
4,281
package net.benmann.evald; import java.util.List; /** * Abstract base class for simplified user added functions. The ArgFunction subclasses eliminate any need to reference the expression's tree Nodes, * and provides automatic optimisation (elimination of functions with all constant inputs). * * Use one of the public subclasses when adding a function to an Evald instance. These subclasses * ({@link OneArgFunction}, {@link TwoArgFunction}, {@link ThreeArgFunction} and {@link NArgFunction}) * also provide a simplified interface for implementing custom functions, as there is no need to call {@link Node#get()} */ public abstract class ArgFunction { final int minArgs; final int maxArgs; final String token; final boolean isPure; protected ArgFunction(String token, int minArgs, int maxArgs, boolean isPure) { this.minArgs = minArgs; this.maxArgs = maxArgs; this.token = token; this.isPure = isPure; } abstract protected double get(Node[] inputs, double[] values); ValueNode createNode(final List<Node> args) { if (isPure) return new PureFunctionValueNode(args); return new ImpureFunctionValueNode(args); } private class ImpureFunctionValueNode extends PureFunctionValueNode { public ImpureFunctionValueNode(final List<Node> args) { super(args); } @Override Node collapse() { return this; } } private class PureFunctionValueNode extends ValueNode { protected Node[] inputs; protected double[] values; public PureFunctionValueNode(final List<Node> args) { super(false); inputs = args.toArray(new Node[] {}); values = new double[args.size()]; } @Override Node collapse() { boolean allConstant = true; for (int i = 0; i < inputs.length; i++) { inputs[i] = inputs[i].collapse(); if (!inputs[i].isConstant) allConstant = false; } if (!allConstant) return this; return new Constant(get()); } @Override String toTree(String prefix) { StringBuilder sb = new StringBuilder(); sb.append(prefix).append("UserFn ").append(token).append("\n"); for (Node input : inputs) { sb.append(input.toTree(prefix + " ")); } return sb.toString(); } @Override protected double get() { return ArgFunction.this.get(inputs, values); } } /** * An {@link ArgFunction} which allows for vararg functions. * * Override the {@link #get(double...)} method to implement desired custom functionality. * If a limited number of arguments are required, it's possible to throw an exception from {@link #get(double...)}, * which will detect the argument mismatch on a call to {@link Evald#evaluate()}. * A better option is to use {@link OneArgFunction}, {@link TwoArgFunction} or {@link ThreeArgFunction}, * which will raise a parse exception on the earlier call to {@link Evald#parse(String)}. */ static abstract public class NArgFunction extends ArgFunction { /** * Construct a function evaluator that takes multiple arguments * * @param token * the token to be used. Must be a valid token (start with [a-zA-Z_], contain only [a-zA-Z0-9_]) */ public NArgFunction(String token) { this(token, 0, NArgParser.NO_MAX); } /** * Construct a function evaluator that takes multiple arguments * * @param token * the token to be used. Must be a valid token (start with [a-zA-Z_], contain only [a-zA-Z0-9_]) * @param minArgs * minimum legal number of arguments. * @param maxArgs * maximum legal number of arguments, or {@link Parser#NO_MAX} if the maximum is unlimited. */ public NArgFunction(String token, int minArgs, int maxArgs) { super(token, minArgs, maxArgs, true); } @Override protected double get(Node[] inputs, double[] values) { for (int i = 0; i < inputs.length; i++) { values[i] = inputs[i].get(); } return get(values); } /** * Return the result of a custom function given the supplied arguments. * * @param args * A variable number of arguments, as supplied in the expression. Note that values may also be Inf, NaN or null. * @return the result of the custom function. */ abstract protected double get(double... args); } /** * An {@link ArgFunction} which allows for impure (non-deterministic) vararg functions. * * Override the {@link #get(double...)} method to implement desired custom functionality. * If a limited number of arguments are required, it's possible to throw an exception from {@link #get(double...)}, * which will detect the argument mismatch on a call to {@link Evald#evaluate()}. * A better option is to use {@link OneArgFunction}, {@link TwoArgFunction} or {@link ThreeArgFunction}, * which will raise a parse exception on the earlier call to {@link Evald#parse(String)}. * * Note that compared to {@link NArgFunction}, this version will not benefit from up-front * expression optimisation, and is useful when the implemented function may provide different * output given the same input. An example is a customised method using an external * data source or implementing a random number generator. */ static abstract public class ImpureNArgFunction extends ArgFunction { /** * Construct a function evaluator that takes multiple arguments * * @param token * the token to be used. Must be a valid token (start with [a-zA-Z_], contain only [a-zA-Z0-9_]) */ public ImpureNArgFunction(String token) { this(token, 0, NArgParser.NO_MAX); } /** * Construct a function evaluator that takes multiple arguments * * @param token * the token to be used. Must be a valid token (start with [a-zA-Z_], contain only [a-zA-Z0-9_]) * @param minArgs * minimum legal number of arguments. * @param maxArgs * maximum legal number of arguments, or {@link Parser#NO_MAX} if the maximum is unlimited. */ public ImpureNArgFunction(String token, int minArgs, int maxArgs) { super(token, minArgs, maxArgs, false); } @Override protected double get(Node[] inputs, double[] values) { for (int i = 0; i < inputs.length; i++) { values[i] = inputs[i].get(); } return get(values); } /** * Return the result of a custom function given the supplied arguments. * * @param args * A variable number of arguments, as supplied in the expression. Note that values may also be Inf, NaN or null. * @return the result of the custom function. */ abstract protected double get(double... args); } /** * An {@link ArgFunction} which allows for single-argument functions. * * Override the {@link #get(double)} method to implement desired custom functionality. * Allows for parsing checks for the correct number of arguments. */ static abstract public class OneArgFunction extends ArgFunction { /** * Construct a function evaluator that takes one argument * * @param token * the token to be used. Must be a valid token (start with [a-zA-Z_], contain only [a-zA-Z0-9_]) */ public OneArgFunction(String token) { super(token, 1, 1, true); } @Override protected double get(Node[] inputs, double[] values) { return get(inputs[0].get()); } /** * Return the result of a custom function given the supplied argument. * * @param value * The single argument supplied for this evaluation. Note that values may also be Inf, NaN or null. * @return the result of the custom function. */ abstract protected double get(double value); } /** * An {@link ArgFunction} which allows for two-argument functions. * * Override the {@link #get(double, double)} method to implement desired custom functionality. * Allows for parsing checks for the correct number of arguments. */ static abstract public class TwoArgFunction extends ArgFunction { /** * Construct a function evaluator that takes two arguments * * @param token * the token to be used. Must be a valid token (start with [a-zA-Z_], contain only [a-zA-Z0-9_]) */ public TwoArgFunction(String token) { super(token, 2, 2, true); } @Override protected double get(Node[] inputs, double[] values) { return get(inputs[0].get(), inputs[1].get()); } /** * Return the result of a custom function given the supplied arguments. * * @param arg1 * The first argument supplied for this evaluation. Note that values may also be Inf, NaN or null. * @param arg2 * The second argument supplied for this evaluation. Note that values may also be Inf, NaN or null. * @return the result of the custom function. */ abstract protected double get(double arg1, double arg2); } /** * An {@link ArgFunction} which allows for three-argument functions. * * Override the {@link #get(double, double, double)} method to implement desired custom functionality. * Allows for parsing checks for the correct number of arguments. */ static abstract public class ThreeArgFunction extends ArgFunction { /** * Construct a function evaluator that takes three arguments * * @param token * the token to be used. Must be a valid token (start with [a-zA-Z_], contain only [a-zA-Z0-9_]) */ public ThreeArgFunction(String token) { super(token, 3, 3, true); } @Override protected double get(Node[] inputs, double[] values) { return get(inputs[0].get(), inputs[1].get(), inputs[2].get()); } /** * Return the result of a custom function given the supplied arguments. * * @param arg1 * The first argument supplied for this evaluation. Note that values may also be Inf, NaN or null. * @param arg2 * The second argument supplied for this evaluation. Note that values may also be Inf, NaN or null. * @param arg3 * The third argument supplied for this evaluation. Note that values may also be Inf, NaN or null. * @return the result of the custom function. */ abstract protected double get(double arg1, double arg2, double arg3); } }
3e0a1e82021d850907c8e72d0dfe6115c07b2577
2,783
java
Java
darkcluster/src/main/java/com/linkedin/darkcluster/api/DarkClusterVerifier.java
sangm/rest.li
e2b59e19d7e845f0047c7640344be97960bcd6bf
[ "Apache-2.0" ]
1,682
2015-01-07T03:29:42.000Z
2022-03-30T22:50:53.000Z
darkcluster/src/main/java/com/linkedin/darkcluster/api/DarkClusterVerifier.java
sangm/rest.li
e2b59e19d7e845f0047c7640344be97960bcd6bf
[ "Apache-2.0" ]
312
2015-01-26T18:27:08.000Z
2022-03-28T16:23:12.000Z
darkcluster/src/main/java/com/linkedin/darkcluster/api/DarkClusterVerifier.java
sangm/rest.li
e2b59e19d7e845f0047c7640344be97960bcd6bf
[ "Apache-2.0" ]
441
2015-01-07T09:17:41.000Z
2022-03-26T23:14:12.000Z
31.269663
128
0.70212
4,282
/* Copyright (c) 2020 LinkedIn 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.linkedin.darkcluster.api; import com.linkedin.r2.message.rest.RestRequest; import com.linkedin.r2.message.rest.RestResponse; /** * Implementations of DarkClusterVerifier can compare the real response with that of the dark canaries. It is left up to the * implementations to decide what to do with that (emit metrics, logs, etc). * * @author Zhenkai Zhu * @author David Hoa */ public interface DarkClusterVerifier { /** * Invoked when the request has been forwarded to dark canary server(s) and the response or error from the real server arrives * @param request original request * @param response the response or error from real server */ void onResponse(RestRequest request, Response response); /** * Invoked when the response or error from the dark canary server arrives. * This could be invoked multiple times for the same request if the request is forwarded * to multiple dark canary servers. * @param request original request * @param darkResponse dark canary response */ void onDarkResponse(RestRequest request, DarkResponse darkResponse); /** * whether this verifier should be used to verify responses. */ boolean isEnabled(); /** * An object that represents the union of response or error. */ interface Response { /** * Returns {@code true} if this response has an error. Use {@link #getError()} to get the error. * * @return {@code true} if this response has an error. */ boolean hasError(); /** * Returns the underlying value for this response. If this response has an error then this method * will return {@code null}. * * @return the value for this response or {@code null} if this response has an error. */ RestResponse getResponse(); /** * If this response has an error, this method returns the error. Otherwise {@code null} is * returned. * * @return the response for this error or {@code null} if there is no error. */ Throwable getError(); } /** * Marker interface for Dark Cluster Response. */ interface DarkResponse extends Response { String getDarkClusterName(); } }
3e0a1eb978aea00c58a0e71bbed9baa8dca42897
294
java
Java
src/main/java/com/dio/jornada/model/CategoriaUsuario.java
jbdrumond/JavaWeb
8593235f11e12e7745c3cf6dc3e6cb3cbd8eee4d
[ "MIT" ]
null
null
null
src/main/java/com/dio/jornada/model/CategoriaUsuario.java
jbdrumond/JavaWeb
8593235f11e12e7745c3cf6dc3e6cb3cbd8eee4d
[ "MIT" ]
null
null
null
src/main/java/com/dio/jornada/model/CategoriaUsuario.java
jbdrumond/JavaWeb
8593235f11e12e7745c3cf6dc3e6cb3cbd8eee4d
[ "MIT" ]
null
null
null
13.363636
32
0.765306
4,283
package com.dio.jornada.model; import lombok.*; import javax.persistence.Entity; import javax.persistence.Id; @Getter @Setter @AllArgsConstructor @NoArgsConstructor @EqualsAndHashCode @Builder @Entity public class CategoriaUsuario { @Id private long id; private String nome; }
3e0a1fb2219718b1128434249e3d03c41a72de87
7,418
java
Java
GOP/GranuleJIDE/src/granulej/gui/action/SyntaxHighlighter.java
xjtu3c/GranuleJ
315b61259bb9f8f81cc2abb8f7439af15b12c92b
[ "Apache-2.0" ]
4
2017-01-06T09:11:39.000Z
2021-11-28T09:01:28.000Z
GOP/GranuleJIDE/src/granulej/gui/action/SyntaxHighlighter.java
xjtu3c/GranuleJ
315b61259bb9f8f81cc2abb8f7439af15b12c92b
[ "Apache-2.0" ]
null
null
null
GOP/GranuleJIDE/src/granulej/gui/action/SyntaxHighlighter.java
xjtu3c/GranuleJ
315b61259bb9f8f81cc2abb8f7439af15b12c92b
[ "Apache-2.0" ]
2
2017-03-31T14:08:26.000Z
2021-11-28T09:01:29.000Z
32.535088
166
0.670936
4,284
package granulej.gui.action; import java.awt.Color; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.swing.JTextPane; import javax.swing.SwingUtilities; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; public class SyntaxHighlighter implements DocumentListener { private Set<String> keywords; private Style keywordStyle; private Style normalStyle; private Style numberStyle; private Style commentStyle; public SyntaxHighlighter(JTextPane editor) { // 准备着色使用的样式 keywordStyle = ((StyledDocument) editor.getDocument()).addStyle("Keyword_Style", null); normalStyle = ((StyledDocument) editor.getDocument()).addStyle("Keyword_Style", null); numberStyle = ((StyledDocument) editor.getDocument()).addStyle("Number_Style", null); commentStyle = ((StyledDocument) editor.getDocument()).addStyle("Comment_Style", null); //StyleConstants.setForeground(keywordStyle, Color.red); StyleConstants.setForeground(keywordStyle, new Color(127, 0, 116)); StyleConstants.setForeground(normalStyle, Color.BLACK); StyleConstants.setBold(keywordStyle, true); StyleConstants.setForeground(normalStyle, Color.BLACK); StyleConstants.setBold(normalStyle, false); //StyleConstants.setForeground(numberStyle, Color.MAGENTA); StyleConstants.setForeground(numberStyle, new Color(127, 0, 116)); StyleConstants.setBold(numberStyle, false); StyleConstants.setForeground(commentStyle, new Color(13, 120, 101)); StyleConstants.setBold(commentStyle, false); // 准备关键字 keywords = new HashSet<String>(); keywords.add("import"); keywords.add("public"); keywords.add("protected"); keywords.add("private"); keywords.add("byte"); keywords.add("short"); keywords.add("int"); keywords.add("long"); keywords.add("char"); keywords.add("float"); keywords.add("double"); keywords.add("static"); keywords.add("granule"); keywords.add("class"); keywords.add("interface"); keywords.add("abstract"); keywords.add("extends"); keywords.add("implements"); keywords.add("void"); keywords.add("external"); keywords.add("within"); keywords.add("seed"); keywords.add("expands"); keywords.add("return"); keywords.add("this"); keywords.add("previous"); keywords.add("super"); keywords.add("if"); keywords.add("else"); keywords.add("void"); keywords.add("new"); keywords.add("try"); keywords.add("catch"); } public boolean isComment(StyledDocument doc, int pos) throws BadLocationException { String txt = doc.getText(0, doc.getLength()); int singleStart, multiStart; int commentStart, commentEnd = 0; boolean isThisCommentSingle = true; do { singleStart = txt.indexOf("//", commentEnd); multiStart = txt.indexOf("/*", commentEnd); if (singleStart == -1 && multiStart == -1) { return false; } else if (singleStart == -1 && multiStart != -1 || multiStart != -1 && multiStart < singleStart) { commentStart = multiStart; commentEnd = txt.indexOf("*/", commentStart + 2) == -1 ? txt.length() : txt.indexOf("*/", commentStart + 2) + 2; isThisCommentSingle = false; } else { commentStart = singleStart; commentEnd = txt.indexOf("\n", commentStart + 2) == -1 ? txt.length() : txt.indexOf("\n", commentStart + 2) + 1; isThisCommentSingle = true; } if (pos >= commentStart && pos < commentEnd) return true; } while (true); } public char getCharAt(Document doc, int pos) throws BadLocationException { return doc.getText(pos, 1).charAt(0); } public int CharacterType(Document doc, int pos) throws BadLocationException { char ch = getCharAt(doc, pos); if (Character.isLetter(ch) || Character.isDigit(ch) || ch == '_') return 0; else if (ch == '/') return 1; else if (ch == '\n') return 2; else return 3; } public int indexOfWordStart(Document doc, int pos) throws BadLocationException { int initialPos = pos; for (; pos > 0 && CharacterType(doc, pos - 1) == CharacterType(doc, initialPos); --pos) ; return pos; } public int indexOfWordEnd(Document doc, int pos) throws BadLocationException { int initialPos = pos; for (; pos < doc.getLength() && CharacterType(doc, pos) == CharacterType(doc, initialPos); ++pos) ; return pos; } public boolean isKeyWord(String word) { if (keywords.contains(word.toLowerCase())) return true; return false; } public void coloringWord(StyledDocument doc, int pos) throws BadLocationException { if (isComment(doc, pos)) { SwingUtilities.invokeLater(new ColouringTask(doc, pos, 1, commentStyle)); } else { int wordEnd = indexOfWordEnd(doc, pos); int wordStart = indexOfWordStart(doc, pos); String word = doc.getText(wordStart, wordEnd - wordStart); try { Integer.parseInt(word); SwingUtilities.invokeLater(new ColouringTask(doc, wordStart, wordEnd - wordStart, numberStyle)); } catch (NumberFormatException e) { if (isKeyWord(word)) { SwingUtilities.invokeLater(new ColouringTask(doc, wordStart, wordEnd - wordStart, keywordStyle)); } else SwingUtilities.invokeLater(new ColouringTask(doc, wordStart, wordEnd - wordStart, normalStyle)); } } } public void changedUpdate(DocumentEvent e) { } public void insertUpdate(DocumentEvent e) { try { Document doc = e.getDocument(); int processTo = Math.max(doc.getLength(), Math.max(doc.getText(0, doc.getLength()).indexOf("\n", e.getOffset()) + 1, doc.getText(0, doc.getLength()).indexOf("*/", e.getOffset()) + 2)); for (int i = e.getOffset(); i < processTo; i++) coloringWord((StyledDocument) doc, i); if (e.getOffset() + e.getLength() < e.getDocument().getLength()) coloringWord((StyledDocument) doc, e.getOffset() + e.getLength()); if (e.getOffset() - 1 >= 0) coloringWord((StyledDocument) doc, e.getOffset() - 1); } catch (Exception excp) { } } public void removeUpdate(DocumentEvent e) { try { int length = e.getLength(); Document doc = e.getDocument(); int processTo = Math.max(doc.getLength(), Math.max(doc.getText(0, doc.getLength()).indexOf("\n", e.getOffset()) + 1, doc.getText(0, doc.getLength()).indexOf("*/", e.getOffset()) + 2)); for (int i = e.getOffset(); i < processTo; i++) coloringWord((StyledDocument) doc, i); if (e.getOffset() + e.getLength() < e.getDocument().getLength()) coloringWord((StyledDocument) doc, e.getOffset() + e.getLength()); if (e.getOffset() - 1 >= 0) coloringWord((StyledDocument) doc, e.getOffset() - 1); } catch (Exception excp) { } } private class ColouringTask implements Runnable { private StyledDocument doc; private Style style; private int pos; private int len; public ColouringTask(StyledDocument doc, int pos, int len, Style style) { this.doc = doc; this.pos = pos; this.len = len; this.style = style; } public void run() { try { doc.setCharacterAttributes(pos, len, style, true); } catch (Exception e) { } } } }
3e0a1fe18eabc42481059cb0f7002b1fb42131fd
97
java
Java
src/main/java/org/frekele/fiscal/focus/nfe/client/auth/package-info.java
frekele/focusnfe-api-client
f0574c2b117dbe726d1266b490c8b7eafb631dad
[ "MIT" ]
6
2018-07-19T21:49:26.000Z
2021-07-17T00:59:04.000Z
src/main/java/org/frekele/fiscal/focus/nfe/client/auth/package-info.java
frekele/focusnfe-api-client
f0574c2b117dbe726d1266b490c8b7eafb631dad
[ "MIT" ]
null
null
null
src/main/java/org/frekele/fiscal/focus/nfe/client/auth/package-info.java
frekele/focusnfe-api-client
f0574c2b117dbe726d1266b490c8b7eafb631dad
[ "MIT" ]
3
2018-06-02T07:04:32.000Z
2020-11-09T22:31:42.000Z
19.4
49
0.742268
4,285
/** * Contém classes para Autenteticação. */ package org.frekele.fiscal.focus.nfe.client.auth;
3e0a203eabf7a9b67c3e9713e2f4dc76542462a7
2,263
java
Java
src/com/company/network.java
izzettunc/Bayesian-Network
18105debbb109f9db1643a1900c87b5c4be248b9
[ "MIT" ]
3
2021-03-02T14:47:47.000Z
2021-03-02T19:04:22.000Z
src/com/company/network.java
izzettunc/Bayesian-Network
18105debbb109f9db1643a1900c87b5c4be248b9
[ "MIT" ]
null
null
null
src/com/company/network.java
izzettunc/Bayesian-Network
18105debbb109f9db1643a1900c87b5c4be248b9
[ "MIT" ]
null
null
null
28.64557
75
0.52099
4,286
package com.company; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Hashtable; /* Basic graph structure */ public class network { node root; private Hashtable<String,node> nodes = new Hashtable<>(); public void add_node(String name) { nodes.put(name,new node(name)); } public void add_connection(String from,String to) { nodes.get(from).connect(nodes.get(to)); } public void set_root(String name) { root = nodes.get(name); } public node get_node(String name) { return nodes.get(name); } //reads and creates the graph public network(String path) { String row = null; BufferedReader csvReader = null; try { csvReader = new BufferedReader(new FileReader(path)); } catch (FileNotFoundException e) { System.out.print(e.getMessage()); gui.show_error_message(e.getMessage(),"FileNotFoundException"); } boolean f = true; while (true) { try { row = csvReader.readLine(); if (f && row != null) { String[] elements = row.split(","); for (int i = 0; i < elements.length; i++) { this.add_node(elements[i]); if(i==0) this.set_root(elements[i]); } f = false; row = csvReader.readLine(); } } catch (IOException e) { System.out.print(e.getMessage()); gui.show_error_message(e.getMessage(),"IOException"); } if (row == null) break; String[] elements = row.split(","); for (int i = 1; i < elements.length; i++) { this.add_connection(elements[0],elements[i]); } } try { csvReader.close(); } catch (IOException e) { System.out.print(e.getMessage()); gui.show_error_message(e.getMessage(),"IOException"); } } }
3e0a20776f7c400cd406e1acafa3b7a8d24bf58b
898
java
Java
src/main/java/carpet/mixins/SculkSensorBlock_rangeMixin.java
itsmemac/fabric-carpet
81d3b9e04f2f3acde2ab4fd27252af41227f383f
[ "MIT" ]
null
null
null
src/main/java/carpet/mixins/SculkSensorBlock_rangeMixin.java
itsmemac/fabric-carpet
81d3b9e04f2f3acde2ab4fd27252af41227f383f
[ "MIT" ]
null
null
null
src/main/java/carpet/mixins/SculkSensorBlock_rangeMixin.java
itsmemac/fabric-carpet
81d3b9e04f2f3acde2ab4fd27252af41227f383f
[ "MIT" ]
null
null
null
28.967742
77
0.733853
4,287
package carpet.mixins; import carpet.CarpetSettings; import net.minecraft.world.level.block.SculkSensorBlock; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(SculkSensorBlock.class) public class SculkSensorBlock_rangeMixin { @Shadow @Final private int listenerRange; @Inject( method = "getListenerRange()I", at = @At("HEAD"), cancellable = true ) public void getListenerRange(CallbackInfoReturnable<Integer> cir) { if (CarpetSettings.sculkSensorRange != this.listenerRange) { cir.setReturnValue(CarpetSettings.sculkSensorRange); } } }
3e0a2097935fbfa4e2f6f348812cc185254fc823
1,849
java
Java
camel-core/src/test/java/org/apache/camel/processor/SimpleTryFinallyTest.java
zangfuri/camel
661cd5be9d82292d4b2414c61b54c15ca5911d65
[ "Apache-2.0" ]
13
2018-08-29T09:51:58.000Z
2022-02-22T12:00:36.000Z
camel-core/src/test/java/org/apache/camel/processor/SimpleTryFinallyTest.java
zangfuri/camel
661cd5be9d82292d4b2414c61b54c15ca5911d65
[ "Apache-2.0" ]
12
2019-11-13T03:09:32.000Z
2022-02-01T01:05:20.000Z
camel-core/src/test/java/org/apache/camel/processor/SimpleTryFinallyTest.java
zangfuri/camel
661cd5be9d82292d4b2414c61b54c15ca5911d65
[ "Apache-2.0" ]
202
2020-07-23T14:34:26.000Z
2022-03-04T18:41:20.000Z
34.886792
75
0.656571
4,288
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.processor; import org.apache.camel.ContextTestSupport; import org.apache.camel.builder.RouteBuilder; /** * @version */ public class SimpleTryFinallyTest extends ContextTestSupport { public void testSimpleTryFinally() throws Exception { getMockEndpoint("mock:try").expectedMessageCount(1); getMockEndpoint("mock:finally").expectedMessageCount(1); getMockEndpoint("mock:result").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start") .doTry() .to("mock:try") .doFinally() .to("mock:finally") .end() .to("mock:result"); } }; } }
3e0a20c4f6442f4a39f8bdda60d8dad5170b2ff2
567
java
Java
src/rs/math/oop1/z110102/rukovanjeIzuzecima/z02/koriscenje/PokretanjeTryCatch.java
MatfOOP-I/primeri-predavanja-2021-22
bb0a8d076398a4979f5246133760ca7ffad7d5df
[ "MIT" ]
null
null
null
src/rs/math/oop1/z110102/rukovanjeIzuzecima/z02/koriscenje/PokretanjeTryCatch.java
MatfOOP-I/primeri-predavanja-2021-22
bb0a8d076398a4979f5246133760ca7ffad7d5df
[ "MIT" ]
null
null
null
src/rs/math/oop1/z110102/rukovanjeIzuzecima/z02/koriscenje/PokretanjeTryCatch.java
MatfOOP-I/primeri-predavanja-2021-22
bb0a8d076398a4979f5246133760ca7ffad7d5df
[ "MIT" ]
null
null
null
23.625
78
0.624339
4,289
package rs.math.oop1.z110102.rukovanjeIzuzecima.z02.koriscenje; public class PokretanjeTryCatch { public static void main( String[] args ) { int i = 13; int j = 80; System.out.println("Ulazimo u try/catch blok!"); try { System.out.println( "Usli smo u try blok sa " + "i = " + i + " j = " + j ); System.out.println( i / (j-j) ); System.out.println( "Izlazimo iz try bloka!" ); } catch (ArithmeticException e) { System.out.println( "Uhvacen je izuzetak " + e ); } System.out.println( "Izasli smo iz try/catch bloka!" ); } }
3e0a20d10540bf7ef11d5fa9bc44d6f4f1605a2c
1,207
java
Java
src/main/java/regalowl/simpledatalib/sql/SyncSQLWrite.java
zsgaming/SimpleDataLib-2
47b4bdf6eecbd991be878c6194a2b598ba2d77f2
[ "Apache-2.0" ]
1
2017-04-05T00:06:22.000Z
2017-04-05T00:06:22.000Z
src/main/java/regalowl/simpledatalib/sql/SyncSQLWrite.java
zsgaming/SimpleDataLib-2
47b4bdf6eecbd991be878c6194a2b598ba2d77f2
[ "Apache-2.0" ]
null
null
null
src/main/java/regalowl/simpledatalib/sql/SyncSQLWrite.java
zsgaming/SimpleDataLib-2
47b4bdf6eecbd991be878c6194a2b598ba2d77f2
[ "Apache-2.0" ]
5
2017-02-01T19:51:26.000Z
2021-01-21T03:28:23.000Z
24.632653
75
0.71251
4,290
package regalowl.simpledatalib.sql; import java.util.ArrayList; import regalowl.simpledatalib.sql.WriteResult.WriteResultType; public class SyncSQLWrite { private SQLWrite sw; private ConnectionPool pool; private ArrayList<WriteStatement> queue = new ArrayList<WriteStatement>(); public SyncSQLWrite(ConnectionPool pool, SQLWrite sw) { this.pool = pool; this.sw = sw; } public synchronized void addToQueue(WriteStatement statement) { if (statement != null) { queue.add(statement); } } public synchronized int getQueueSize() { return queue.size(); } public synchronized void writeQueue() { if (queue == null || queue.isEmpty()) {return;} DatabaseConnection database = pool.getDatabaseConnection(); WriteResult result = database.write(queue); if (result.getStatus() == WriteResultType.SUCCESS) { if (sw.logSQL() && result.hasSuccessfulSQL()) { for (WriteStatement ws:result.getSuccessfulSQL()) { ws.logStatement(); } } } else if (result.getStatus() == WriteResultType.ERROR) { if (sw.logWriteErrors()) { result.getFailedStatement().writeFailed(result.getException()); } } pool.returnConnection(database); queue.clear(); } }
3e0a20fa102c55c20cc422e5422734aef8a386c4
1,072
java
Java
src/main/java/cn/aethli/thoth/entity/DataVersion.java
AethLi/thoth_server
a127cb8191cd85bd374d7596deea67a427c5fcbb
[ "Apache-2.0" ]
null
null
null
src/main/java/cn/aethli/thoth/entity/DataVersion.java
AethLi/thoth_server
a127cb8191cd85bd374d7596deea67a427c5fcbb
[ "Apache-2.0" ]
null
null
null
src/main/java/cn/aethli/thoth/entity/DataVersion.java
AethLi/thoth_server
a127cb8191cd85bd374d7596deea67a427c5fcbb
[ "Apache-2.0" ]
null
null
null
23.304348
79
0.727612
4,291
package cn.aethli.thoth.entity; import cn.aethli.thoth.common.enums.VersionType; import java.time.LocalDate; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import lombok.Data; import org.hibernate.annotations.GenericGenerator; /** * @author Termite */ @Entity @Data @Table(name = "data_version") public class DataVersion { @Id @Column(name = "id", length = 36) @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "org.hibernate.id.UUIDGenerator") private String id; @Column(name = "version", nullable = false) private String version; @Column(name = "update_dt", nullable = false) private LocalDate updateDt; @Column(name = "type", nullable = false) private VersionType type; public DataVersion() { updateDt=LocalDate.of(2000,1,1); } public DataVersion(String version, VersionType type) { this.version = version; this.type = type; updateDt=LocalDate.of(2000,1,1); } }
3e0a21aca61b7c9668d884aa9c7658365fa91a06
653
java
Java
src/nierth/learnjava/BControlFlow/SimpleCalculator/Main.java
jdnierth/java-coding-exercises
ebfcac9c4f82de24f6a51f77ba24f3748b850a2f
[ "Apache-2.0" ]
null
null
null
src/nierth/learnjava/BControlFlow/SimpleCalculator/Main.java
jdnierth/java-coding-exercises
ebfcac9c4f82de24f6a51f77ba24f3748b850a2f
[ "Apache-2.0" ]
null
null
null
src/nierth/learnjava/BControlFlow/SimpleCalculator/Main.java
jdnierth/java-coding-exercises
ebfcac9c4f82de24f6a51f77ba24f3748b850a2f
[ "Apache-2.0" ]
null
null
null
40.8125
80
0.690658
4,292
package nierth.learnjava.BControlFlow.SimpleCalculator; public class Main { public static void main(String[] args) { SimpleCalculator calculator = new SimpleCalculator(); calculator.setFirstNumber(5.0); calculator.setSecondNumber(4); System.out.println("add= " + calculator.getAdditionResult()); System.out.println("subtract= " + calculator.getSubtractionResult()); calculator.setFirstNumber(5.25); calculator.setSecondNumber(0); System.out.println("multiply= " + calculator.getMultiplicationResult()); System.out.println("divide= " + calculator.getDivisionResult()); } }
3e0a21e8a3e0058e2bc0458f2a270cd714cdda26
1,308
java
Java
core/src/main/java/org/apache/accumulo/core/client/admin/compaction/CompactableFile.java
Umang228/accumulo
1b6e1ed5d075e2f538a2e0aedb76a56c9e92fa96
[ "Apache-2.0" ]
1
2019-08-21T12:04:54.000Z
2019-08-21T12:04:54.000Z
core/src/main/java/org/apache/accumulo/core/client/admin/compaction/CompactableFile.java
Umang228/accumulo
1b6e1ed5d075e2f538a2e0aedb76a56c9e92fa96
[ "Apache-2.0" ]
6
2015-07-17T21:39:44.000Z
2020-12-02T21:39:41.000Z
core/src/main/java/org/apache/accumulo/core/client/admin/compaction/CompactableFile.java
Umang228/accumulo
1b6e1ed5d075e2f538a2e0aedb76a56c9e92fa96
[ "Apache-2.0" ]
1
2021-01-15T12:22:39.000Z
2021-01-15T12:22:39.000Z
30.418605
85
0.754587
4,293
/* * 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.accumulo.core.client.admin.compaction; import java.net.URI; import org.apache.accumulo.core.metadata.CompactableFileImpl; /** * @since 2.1.0 */ public interface CompactableFile { public String getFileName(); public URI getUri(); public long getEstimatedSize(); public long getEstimatedEntries(); static CompactableFile create(URI uri, long estimatedSize, long estimatedEntries) { return new CompactableFileImpl(uri, estimatedSize, estimatedEntries); } }
3e0a227525dc60fb39d82502bca5295b641b671a
4,816
java
Java
TradeToday/src/nl/m4jit/tradetoday/presentation/transactions/ServiceTransactionIFrame.java
jorisdgff/Trade-Today
7cb42666691f06a7c4bf8b737bf3b131a3ae5870
[ "Unlicense" ]
null
null
null
TradeToday/src/nl/m4jit/tradetoday/presentation/transactions/ServiceTransactionIFrame.java
jorisdgff/Trade-Today
7cb42666691f06a7c4bf8b737bf3b131a3ae5870
[ "Unlicense" ]
null
null
null
TradeToday/src/nl/m4jit/tradetoday/presentation/transactions/ServiceTransactionIFrame.java
jorisdgff/Trade-Today
7cb42666691f06a7c4bf8b737bf3b131a3ae5870
[ "Unlicense" ]
null
null
null
31.272727
135
0.627907
4,294
package nl.m4jit.tradetoday.presentation.transactions; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.JOptionPane; import javax.swing.JTextField; import nl.m4jit.framework.ValidationException; import nl.m4jit.framework.presentation.swing.abstractdialogs.RecordDialog; import nl.m4jit.tradetoday.dataaccess.members.MemberGateway; import nl.m4jit.tradetoday.dataaccess.members.MemberTable; import nl.m4jit.tradetoday.dataaccess.transactions.TransactionGateway; import nl.m4jit.tradetoday.domainlogic.Application; import nl.m4jit.tradetoday.domainlogic.members.MemberModule; import nl.m4jit.tradetoday.domainlogic.transactions.TransactionModule; public class ServiceTransactionIFrame extends RecordDialog<TransactionGateway>{ private MemberGateway fromMember, toMember; public ServiceTransactionIFrame(){ super(new String[]{"25dlu", "75dlu"}, 5); addLabel("Afnemer:"); addTextField("fromnumber", 1); JTextField fromNameField = addTextField("fromname", 1); fromNameField.setEditable(false); fromNameField.addFocusListener(this); addLabel("Datum:"); addFormattedTextField("date", new SimpleDateFormat("d-M-yyyy"), 2); addLabel("Dienst:"); addTextField("service", 2); addLabel("Aanbieder:"); addTextField("tonumber", 1); JTextField toNameField = addTextField("toname", 1); toNameField.setEditable(false); toNameField.addFocusListener(this); addLabel("Punten:"); addTextField("points", 1); setUI(); } @Override public String getScreenTitle(boolean isNew) { return "Dienstverling invoeren"; } @Override public String getNotificationMessge(boolean isNew) { return "Dienstverling ingevoerd"; } @Override public Object getValue(String name) { if (name.equals("date")) { return Application.getInstance().getDefaultDate(); } else { return ""; } } @Override public void focusGainedEvent(String name) { if (name.equals("fromname")) { int number = Integer.parseInt(getTextValue("fromnumber")); MemberGateway tempMember = MemberTable.getInstance().retreive(number); if (tempMember == null) { setFocusOnComponent("fromnumber"); JOptionPane.showMessageDialog(this, "Lid niet gevonden"); } else if (tempMember.getDeregistrationdate() == null) { fromMember = tempMember; setTextValue("fromname", MemberModule.getFullname(fromMember)); setFocusOnComponent("date"); } else { setFocusOnComponent("fromnumber"); JOptionPane.showMessageDialog(this, "Lid is uitgeschreven"); } } else if (name.equals("toname")) { int number = Integer.parseInt(getTextValue("tonumber")); MemberGateway tempMember = MemberTable.getInstance().retreive(number); if (tempMember == null) { setFocusOnComponent("tonumber"); JOptionPane.showMessageDialog(this, "Lid niet gevonden"); } else if (tempMember.getDeregistrationdate() == null) { toMember = tempMember; setTextValue("toname", MemberModule.getFullname(toMember)); setFocusOnComponent("points"); } else { setFocusOnComponent("tonumber"); JOptionPane.showMessageDialog(this, "Lid is uitgeschreven"); } } } @Override protected TransactionGateway create() { String service = "Dienst: " + getTextValue("service"); Date date = (Date) getFormattedTextFieldValue("date"); int points = Integer.parseInt(getTextValue("points")); try{ return TransactionModule.getInstance().makeSimpleTransaction(fromMember, toMember, points, "S", service, date); }catch(ValidationException ex){ String message = ex.getMessage(); if(message.equals("no client")){ giveMessageAndSetFocus("Geen afnemer opgegeven", "fromnumber"); }else if(message.equals("no description")){ giveMessageAndSetFocus("Geen omschrijving opgegeven", "service"); }else if(message.equals("no provider")){ giveMessageAndSetFocus("Geen aanbieder opgegeven", "tonumber"); } return null; } } @Override protected void update() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
3e0a227d4d59631cbf6733831c225b49a13e36e5
8,269
java
Java
datumbox-framework-common/src/main/java/com/datumbox/framework/common/dataobjects/AssociativeArray.java
datumbox/datumbox-framework
740af95dd90f4f5408c371408543859401fcea1a
[ "Apache-2.0" ]
820
2015-01-01T02:45:32.000Z
2022-03-14T02:46:47.000Z
datumbox-framework-common/src/main/java/com/datumbox/framework/common/dataobjects/AssociativeArray.java
datumbox/datumbox-framework
740af95dd90f4f5408c371408543859401fcea1a
[ "Apache-2.0" ]
29
2015-03-28T22:35:12.000Z
2020-10-13T23:39:14.000Z
datumbox-framework-common/src/main/java/com/datumbox/framework/common/dataobjects/AssociativeArray.java
datumbox/datumbox-framework
740af95dd90f4f5408c371408543859401fcea1a
[ "Apache-2.0" ]
294
2015-01-03T06:04:39.000Z
2022-02-27T10:41:42.000Z
30.557196
99
0.623838
4,295
/** * Copyright (C) 2013-2020 Vasilis Vryniotis <hzdkv@example.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datumbox.framework.common.dataobjects; import java.util.*; /** * Data structure which stores internally a Map<Object, Object>. The class provides * a number of methods to access and modify the internal map. * * @author Vasilis Vryniotis <hzdkv@example.com> */ public class AssociativeArray extends AbstractDataStructureMap<Map<Object, Object>> { private static final long serialVersionUID = 1L; /** * Copies the provided AssociativeArray and builds a new which is unmodifiable. * * @param original * @return */ public static AssociativeArray copy2Unmodifiable(AssociativeArray original) { Map<Object, Object> internalData = new LinkedHashMap<>(); internalData.putAll(original.internalData); internalData = Collections.unmodifiableMap(internalData); return new AssociativeArray(internalData); } /** * Converts the internal data of the provided AssociativeArray to unmondifiable * but it does not copy its values. This means that if the original AssociativeArray * gets modified, the data of the new object will be modified too. This method * is not as safe as copy2Unmodifiable() but it should be preferred when speed * is crucial. * * @param original * @return */ public static AssociativeArray convert2Unmodifiable(AssociativeArray original) { return new AssociativeArray(Collections.unmodifiableMap(original.internalData)); } /** * Default constructor which initializes the internal data with a LinkedHashMap. */ public AssociativeArray() { super(new LinkedHashMap<>()); } /** * Constructor that initializes the internal data with the provided map. * * @param internalData */ public AssociativeArray(Map<Object, Object> internalData) { super(internalData); } /** {@inheritDoc} */ public AssociativeArray copy() { AssociativeArray copy = new AssociativeArray(); copy.internalData.putAll(this.internalData); return copy; } /** * Overwrites the contents of the internal data of this object with the ones * of the provided map. * * @param data */ public final void overwrite(Map<Object, Object> data) { internalData.clear(); internalData.putAll(data); } /** * Adds the provided associative array to the current object. All the columns * of this object should be numeric or boolean or else an exception is thrown. * * @param array */ public final void addValues(AssociativeArray array) { addRemoveValues(array, +1); } /** * Subtracts the provided associative array to the current object. All the columns * of this object should be numeric or boolean or else an exception is thrown. * * @param array */ public final void subtractValues(AssociativeArray array) { addRemoveValues(array, -1); } private void addRemoveValues(AssociativeArray array, int sign) { //assumes that the AssociativeArray stores only numerical fields, meaning //that an dataTransformation algorithm was run before calling the method //sign should be -1 or 1 for(Map.Entry<Object, Object> entry : array.entrySet()) { Object column = entry.getKey(); Double previousValue = TypeInference.toDouble(internalData.get(column)); if(previousValue==null) { previousValue=0.0; } internalData.put(column, previousValue+ sign*TypeInference.toDouble(entry.getValue())); } } /** * Multiplies the values of the object with a particular multiplier. All the columns * of this object should be numeric or boolean or else an exception is thrown. * * @param multiplier */ public final void multiplyValues(double multiplier) { for(Map.Entry<Object, Object> entry : internalData.entrySet()) { Double previousValue = TypeInference.toDouble(entry.getValue()); if(previousValue==null) { continue; } internalData.put(entry.getKey(), previousValue*multiplier); } } /** * Removes a particular key from the internal map and returns the value * associated with that key if present in the map. * * @param key * @return */ public final Object remove(Object key) { return internalData.remove(key); } /** * Returns the value which is associated with the provided key. * * @param key * @return */ public final Object get(Object key) { return internalData.get(key); } /** * Gets value of the particular key from the map and converts it into a Double. * If not found null is returned. The value must be numeric or boolean or else * an exception is thrown. * * @param key * @return */ public final Double getDouble(Object key) { return TypeInference.toDouble(internalData.get(key)); } /** * Adds a particular key-value into the internal map. It returns the previous * value which was associated with that key. * * @param key * @param value * @return */ public final Object put(Object key, Object value) { return internalData.put(key, value); } /** * Adds all the key-value combinations of the provided map in the internal map. * * @param m */ public void putAll(Map<? extends Object,? extends Object> m) { internalData.putAll(m); } /** * Returns the entrySet of the internal map. * * @return */ public final Set<Map.Entry<Object, Object>> entrySet() { return internalData.entrySet(); } /** * Returns the keySet of the internal map. * * @return */ public final Set<Object> keySet() { return internalData.keySet(); } /** * Returns the values of the internal map. * * @return */ public final Collection<Object> values() { return internalData.values(); } /** * Returns a FlatDataCollection with the values of the internal map. The method * does not copy the data. * * @return */ public FlatDataCollection toFlatDataCollection() { return new FlatDataCollection(internalData.values()); } /** * Returns a FlatDataList with the values of the internal map. The method * might require to copy the data. * * @return */ @SuppressWarnings("unchecked") public FlatDataList toFlatDataList() { Collection<Object> values = internalData.values(); List<Object> list; if (values instanceof List<?>) { list = (List<Object>)values; } else { list = new ArrayList(values); } return new FlatDataList(list); } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if ( this == o ) return true; if ( !(o instanceof AssociativeArray) ) return false; return internalData.equals(((AssociativeArray)o).internalData); } /** {@inheritDoc} */ @Override public int hashCode() { return internalData.hashCode(); } /** {@inheritDoc} */ @Override public String toString() { return internalData.toString(); } }
3e0a231fd24f91d97bbfa11d79cc8f7b3e7ec275
10,385
java
Java
stock.screener/main/java/com/ndr/app/stock/screener/dialog/IndexModelDialog.java
amikey/swing-nutch
e324b42b063ff34e9b9c295195c5d4b19882e8ad
[ "MIT" ]
null
null
null
stock.screener/main/java/com/ndr/app/stock/screener/dialog/IndexModelDialog.java
amikey/swing-nutch
e324b42b063ff34e9b9c295195c5d4b19882e8ad
[ "MIT" ]
null
null
null
stock.screener/main/java/com/ndr/app/stock/screener/dialog/IndexModelDialog.java
amikey/swing-nutch
e324b42b063ff34e9b9c295195c5d4b19882e8ad
[ "MIT" ]
null
null
null
44.762931
167
0.662398
4,296
package com.ndr.app.stock.screener.dialog; import com.ndr.app.stock.screener.ApplicationProxy; import com.ndr.app.stock.screener.action.RemoveIndexModelAction; import com.ndr.app.stock.screener.action.SaveIndexModelAction; import com.ndr.app.stock.screener.border.CompoundBorderFactory; import com.ndr.app.stock.screener.button.AddButton; import com.ndr.app.stock.screener.button.CloseButton; import com.ndr.app.stock.screener.button.EditButton; import com.ndr.app.stock.screener.button.OpenButton; import com.ndr.app.stock.screener.button.RemoveButton; import com.ndr.app.stock.screener.list.IndexModelList; import com.ndr.app.stock.screener.listener.IndexModelNoteListSelectionListener; import com.ndr.app.stock.screener.panel.IndexModelPanel; import com.ndr.app.stock.screener.panel.TimeSeriesChartPanel; import com.ndr.app.stock.screener.panel.TimeSeriesTablePanel; import com.ndr.app.stock.screener.resource.ResourceManager; import com.ndr.app.stock.screener.statusbar.TimeSeriesStatusBar; import com.ndr.app.stock.screener.text.NoteTextPane; import com.ndr.model.stock.screener.IndexModel; import com.ndr.model.stock.screener.TestEntityFactory; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; import javax.annotation.PostConstruct; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JViewport; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public final class IndexModelDialog extends JDialog { private static final long serialVersionUID = -2796234903306249105L; @Autowired private Frame frame; @Autowired private ResourceManager resourceManager; @Autowired private AddButton addButton; @Autowired private RemoveButton removeButton; @Autowired private EditButton editButton; @Autowired private OpenButton openButton; @Autowired private CloseButton closeButton; @Autowired private TimeSeriesChartPanel timeSeriesChartPanel; @Autowired private TimeSeriesTablePanel timeSeriesTablePanel; @Autowired private IndexModelPanel indexModelPanel; @Autowired private IndexModelList<IndexModel> indexModelList; @Autowired private NoteTextPane indexModelNoteTextPane; @Autowired private SaveIndexModelAction saveIndexModelAction; @Autowired private RemoveIndexModelAction removeIndexModelAction; @Autowired private CriteriaIndexModelDialog indexModelDialog; @Autowired private TimeSeriesStatusBar timeSeriesStatusBar; public void view() { indexModelList.setSelectedEntity(indexModelPanel.getModel()); setLocationRelativeTo(frame); setVisible(true); } public List<IndexModel> getIndexModels() { return indexModelList.getEntities(); } public void setIndexModels(List<IndexModel> indexModels) { indexModelList.setEntities(indexModels); } public IndexModel getSelectedIndexModel() { return indexModelList.getSelectedEntity(); } @PostConstruct protected void build() { indexModelList.addListSelectionListener(new IndexModelNoteListSelectionListener(indexModelList, indexModelNoteTextPane)); addWindowListener(new HideDialogWindowAdapter(this)); setIconImage(resourceManager.getImage("index.model.icon")); setTitle(resourceManager.getString("index.model.dialog.title")); setLayout(new BorderLayout()); setModal(true); add(buildPanel(), BorderLayout.CENTER); add(buildScrollableTextPane(), BorderLayout.SOUTH); pack(); } private JPanel buildPanel() { JPanel panel = new JPanel(); CompoundBorderFactory.instance.create(panel, resourceManager.getString("index.models")); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.add(buildScrollPane()); return panel; } private JScrollPane buildScrollPane() { JScrollPane scrollPane = new JScrollPane(indexModelList); scrollPane.setPreferredSize(new Dimension(275, 200)); JViewport viewport = new JViewport(); viewport.setView(buildButtonPanel()); scrollPane.setColumnHeader(viewport); return scrollPane; } private JPanel buildButtonPanel() { JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); panel.add(buildAddButton()); panel.add(Box.createRigidArea(new Dimension(2, 0))); panel.add(buildRemoveButton()); panel.add(Box.createRigidArea(new Dimension(2, 0))); panel.add(buildEditButton()); panel.add(Box.createRigidArea(new Dimension(2, 0))); panel.add(buildOpenButton()); panel.add(Box.createHorizontalGlue()); panel.add(buildCloseButton()); return panel; } private JScrollPane buildScrollableTextPane() { JScrollPane scrollPane = new JScrollPane(indexModelNoteTextPane); CompoundBorderFactory.instance.create(scrollPane, resourceManager.getString("note")); return scrollPane; } private JButton buildAddButton() { addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { indexModelDialog.setTitle(resourceManager.getString("add")); indexModelDialog.view((JButton) event.getSource(), "", ""); if (indexModelDialog.wasNotCanceled()) { IndexModel indexModel = TestEntityFactory.instance.newIndexModelTestInstance(indexModelDialog.getModelName(), ApplicationProxy.instance.getUser()); indexModel.setNote(indexModelDialog.getModelNote()); indexModelList.addEntity(indexModel); saveIndexModelAction.save(indexModel); } } }); return addButton; } private JButton buildRemoveButton() { removeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { if (indexModelList.isNotEmpty()) { IndexModel selectedIndexModel = indexModelList.getSelectedEntity(); int yes = JOptionPane.showConfirmDialog(frame, resourceManager.getString("index.model.dialog.index.model.confirm"), resourceManager.getString("index.model.dialog.index.model.title"), JOptionPane.YES_NO_OPTION); if (yes == JOptionPane.YES_OPTION) { removeIndexModelAction.remove(selectedIndexModel); indexModelList.removeEntity(selectedIndexModel); if (indexModelList.isEmpty()) { selectedIndexModel = TestEntityFactory.instance.newIndexModelTestInstance("default", ApplicationProxy.instance.getUser()); indexModelList.addEntity(selectedIndexModel); saveIndexModelAction.save(selectedIndexModel); indexModelPanel.setModel(selectedIndexModel); timeSeriesStatusBar.setIndexModelStatus(selectedIndexModel.getName()); } else { selectedIndexModel = (IndexModel) indexModelList.getSelectedValue(); indexModelPanel.setModel(selectedIndexModel); timeSeriesStatusBar.setIndexModelStatus(selectedIndexModel.getName()); timeSeriesChartPanel.reset(); timeSeriesTablePanel.reset(); } } } } }); return removeButton; } private JButton buildEditButton() { editButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { if (indexModelList.isNotEmpty()) { IndexModel selectedIndexModel = indexModelList.getSelectedEntity(); indexModelDialog.setTitle(resourceManager.getString("edit")); indexModelDialog.view((JButton) event.getSource(), selectedIndexModel.getName(), selectedIndexModel.getNote()); if (indexModelDialog.wasNotCanceled()) { selectedIndexModel.setName(indexModelDialog.getModelName()); selectedIndexModel.setNote(indexModelDialog.getModelNote()); indexModelList.updateEntity(selectedIndexModel); saveIndexModelAction.save(selectedIndexModel); indexModelNoteTextPane.setText(indexModelDialog.getModelNote()); timeSeriesStatusBar.setIndexModelStatus(selectedIndexModel.getName()); } } } }); return editButton; } private JButton buildOpenButton() { openButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { if (indexModelList.isNotEmpty()) { IndexModel selectedIndexModel = indexModelList.getSelectedEntity(); indexModelPanel.setModel(selectedIndexModel); timeSeriesStatusBar.setIndexModelStatus(selectedIndexModel.getName()); timeSeriesChartPanel.reset(); timeSeriesTablePanel.reset(); setVisible(false); } } }); return openButton; } private JButton buildCloseButton() { getRootPane().setDefaultButton(closeButton); closeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { setVisible(false); } }); return closeButton; } }
3e0a236b4ead9af42aee8b7e699ecdeb31057b59
3,276
java
Java
src/main/java/be/yildizgames/common/logging/logback/LogbackLogEngine.java
yildiz-online/common-logging-logback
43fec6b97715487865633f883c8e862b40404d9d
[ "MIT" ]
null
null
null
src/main/java/be/yildizgames/common/logging/logback/LogbackLogEngine.java
yildiz-online/common-logging-logback
43fec6b97715487865633f883c8e862b40404d9d
[ "MIT" ]
10
2019-02-10T07:45:24.000Z
2022-01-27T16:25:25.000Z
src/main/java/be/yildizgames/common/logging/logback/LogbackLogEngine.java
yildiz-online/common-logging-logback
43fec6b97715487865633f883c8e862b40404d9d
[ "MIT" ]
null
null
null
36.808989
120
0.724969
4,297
/* * This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT) * * Copyright (c) 2019 Grégory Van den Borre * * More infos available: https://engine.yildiz-games.be * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package be.yildizgames.common.logging.logback; import be.yildizgames.common.logging.LogEngine; import be.yildizgames.common.logging.LoggerConfiguration; import be.yildizgames.common.logging.PatternBuilder; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Objects; /** * Logback implementation for the LogEngine. * * @author Grégory Van den Borre */ public class LogbackLogEngine implements LogEngine { /** * Generator to build a configuration file. */ private final LogbackConfigFileGenerator generator = new LogbackConfigFileGenerator(); /** * Create a new instance. */ public LogbackLogEngine() { this.configureForJBoss(); } @Override public final PatternBuilder createPatternBuilder() { return new LogbackPatternBuilder(); } @Override public final void setConfigurationPath(final String path) { Objects.requireNonNull(path); System.setProperty("logging.config", Paths.get(path).toAbsolutePath().toString()); System.setProperty("logback.configurationFile", Paths.get(path).toAbsolutePath().toString()); } @Override public final void configureFromProperties(final LoggerConfiguration properties) throws IOException { Objects.requireNonNull(properties); String result = this.generator.generate(properties); Path path = Paths.get(properties.getLoggerConfigurationFile()); if(path.getParent() != null) { Files.createDirectories(path.getParent()); } Files.write(path, result.getBytes(StandardCharsets.UTF_8)); this.setConfigurationPath(properties.getLoggerConfigurationFile()); } /** * Force the systems from jboss to use slf4j and logback. */ private void configureForJBoss() { System.setProperty("org.jboss.logging.provider", "slf4j"); } }
3e0a23ecace0cb3e924d75b07eaf85f5ba8fbe04
1,546
java
Java
modules/ballerina-core/src/main/java/org/wso2/ballerina/core/interpreter/ConstantLocation.java
dnwick/ballerina
c100da398da270835e1476a05920afe4226b7842
[ "Apache-2.0" ]
null
null
null
modules/ballerina-core/src/main/java/org/wso2/ballerina/core/interpreter/ConstantLocation.java
dnwick/ballerina
c100da398da270835e1476a05920afe4226b7842
[ "Apache-2.0" ]
null
null
null
modules/ballerina-core/src/main/java/org/wso2/ballerina/core/interpreter/ConstantLocation.java
dnwick/ballerina
c100da398da270835e1476a05920afe4226b7842
[ "Apache-2.0" ]
null
null
null
30.313725
88
0.729625
4,298
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.ballerina.core.interpreter; import org.wso2.ballerina.core.model.Node; import org.wso2.ballerina.core.model.NodeExecutor; import org.wso2.ballerina.core.model.NodeVisitor; import org.wso2.ballerina.core.model.values.BValue; /** * {@code ConstantLocation} represents a location where a constant is stored at runtime. * * @since 0.8.0 */ public class ConstantLocation extends MemoryLocation implements Node { private int staticMemAddrOffset; public ConstantLocation(int staticMemAddrOffset) { this.staticMemAddrOffset = staticMemAddrOffset; } public int getStaticMemAddrOffset() { return staticMemAddrOffset; } @Override public void accept(NodeVisitor visitor) { visitor.visit(this); } @Override public BValue execute(NodeExecutor executor) { return executor.visit(this); } }
3e0a248ef61b3ca48fe598c6cf2d12deb7d95011
1,323
java
Java
src/main/java/com/xust/sims/entity/Student.java
LeeCue/sims
f47f04d9e663880e15ca69c34f295b4bb7b49e20
[ "Apache-2.0" ]
17
2020-06-16T14:40:24.000Z
2022-02-28T02:47:39.000Z
src/main/java/com/xust/sims/entity/Student.java
RenChuanQing/sims
3acd8605a98b4eeda97c896996d637dd7de08eb8
[ "Apache-2.0" ]
1
2020-12-25T03:22:36.000Z
2020-12-25T06:02:22.000Z
src/main/java/com/xust/sims/entity/Student.java
RenChuanQing/sims
3acd8605a98b4eeda97c896996d637dd7de08eb8
[ "Apache-2.0" ]
4
2020-06-23T05:16:12.000Z
2021-07-05T06:37:33.000Z
25.941176
73
0.711262
4,299
package com.xust.sims.entity; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.Date; /** * @author LeeCue * @date 2020-03-14 */ @Data @NoArgsConstructor public class Student implements Serializable { private static final long serialVersionUID = -6195864794816991937L; @NotEmpty(message = "学工号不能为空") private String id; @NotEmpty(message = "姓名不能为空") private String name; private String nation; private String sex; private Integer age; private String politicsStatus; private String idCard; private String phoneNum; @Email(message = "邮箱格式有误") private String email; private String avatar; private String description; @JsonFormat(pattern = "yyyy-MM-dd") private Date createTime; @JsonFormat(pattern = "yyyy-MM-dd") private Date updateTime; private Class classes; private Academy academy; private Major major; public Student(String id, String name, String idCard, String email) { this.id = id; this.name = name; this.idCard = idCard; this.email = email; } }
3e0a251e42c26dd6f2ec2863e621942555fbbee8
3,977
java
Java
src/main/java/io/github/thundzeng/miniemail/core/impl/BaseMiniEmail.java
THUNDZENG/mini-email
cb5587cd74594daeae2580af10c2a3a71f07f373
[ "Apache-2.0" ]
2
2021-09-25T03:41:34.000Z
2021-09-25T03:41:44.000Z
src/main/java/io/github/thundzeng/miniemail/core/impl/BaseMiniEmail.java
THUNDZENG/mini-email
cb5587cd74594daeae2580af10c2a3a71f07f373
[ "Apache-2.0" ]
null
null
null
src/main/java/io/github/thundzeng/miniemail/core/impl/BaseMiniEmail.java
THUNDZENG/mini-email
cb5587cd74594daeae2580af10c2a3a71f07f373
[ "Apache-2.0" ]
1
2022-03-02T10:43:38.000Z
2022-03-02T10:43:38.000Z
31.314961
145
0.636409
4,300
package io.github.thundzeng.miniemail.core.impl; import io.github.thundzeng.miniemail.core.MiniEmail; import io.github.thundzeng.miniemail.util.StringUtils; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Transport; import javax.mail.internet.*; import java.io.File; import java.net.URL; import java.util.Calendar; import java.util.logging.Level; import java.util.logging.Logger; /** * 基础邮件模板 * * @author thundzeng */ public abstract class BaseMiniEmail { protected static Logger log; static { log = Logger.getLogger("default"); // 日志输出默认关闭。需要源码调试时,可设置为 Level.INFO log.setLevel(Level.OFF); } private MimeMessage msg; private MimeMultipart cover; public BaseMiniEmail(MimeMessage msg, MimeMultipart cover) { this.msg = msg; this.cover = cover; } public void config(String subject, String fromName, String[] to) { try { if (null != subject) { msg.setSubject(subject, "UTF-8"); } if (null != fromName) { msg.setFrom(new InternetAddress(fromName)); } if (null != to) { InternetAddress[] parse = InternetAddress.parse(String.join(",", to)); msg.setRecipients(Message.RecipientType.TO, parse); } } catch (MessagingException e) { e.printStackTrace(); } } /** * 考虑到各邮件类型的不同,此方法留给子类去重写 * * @param content 发送内容 * @throws MessagingException */ protected abstract void addContent(String content) throws MessagingException; public void setContent(MimeBodyPart bodyPart) throws MessagingException { cover.addBodyPart(bodyPart); msg.setContent(cover); } protected MiniEmail addAttachment(MiniEmail miniEmail, File file, String fileName) throws MessagingException { FileDataSource fds = new FileDataSource(file); MimeBodyPart attachmentPart = new MimeBodyPart(); try { attachmentPart.setDataHandler(new DataHandler(fds)); attachmentPart.setFileName(StringUtils.isEmpty(fileName) ? MimeUtility.encodeText(fds.getName()) : MimeUtility.encodeText(fileName)); } catch (Exception e) { log.warning("添加邮件附件文件失败:" + fileName); } cover.addBodyPart(attachmentPart); return miniEmail; } protected MiniEmail addUrlAttachment(MiniEmail miniEmail, URL url, String urlName) throws MessagingException { DataHandler dataHandler = new DataHandler(url); MimeBodyPart attachmentPart = new MimeBodyPart(); try { attachmentPart.setDataHandler(dataHandler); attachmentPart.setFileName(StringUtils.isEmpty(urlName) ? MimeUtility.encodeText(dataHandler.getName()) : urlName); } catch (Exception e) { log.warning("添加邮件附件链接失败:" + urlName); } cover.addBodyPart(attachmentPart); return miniEmail; } public void send(String to, String content) { send(new String[]{to}, content); } public void send(String[] tos, String content) { log.info("邮件发送开始------>" + tos); try { config(null, null, tos); addContent(content); msg.setSentDate(Calendar.getInstance().getTime()); Transport.send(msg); } catch (MessagingException e) { log.warning("邮件发送失败:" + tos); } log.info("邮件发送结束------>" + tos); } public MiniEmail addCarbonCopy(MiniEmail miniEmail, String[] carbonCopies) throws MessagingException { if (null != carbonCopies && carbonCopies.length > 0) { InternetAddress[] parse = InternetAddress.parse(String.join(",", carbonCopies)); msg.setRecipients(Message.RecipientType.CC, parse); } return miniEmail; } }
3e0a26ca20698a3953a2d044782c1a57bf79ba56
3,122
java
Java
expectit-core/src/test/java/net/sf/expectit/SshJExample.java
Maple-mxf/expectit
d97888595ec66e9769006707f8c1d8742f854eb4
[ "Apache-2.0" ]
122
2015-02-04T08:00:23.000Z
2020-12-17T09:36:45.000Z
expectit-core/src/test/java/net/sf/expectit/SshJExample.java
zhishengzhang/ExpectIt
5acbe1f8f895fe1dbd63e29bf3ab8e5bbf0873c3
[ "Apache-2.0" ]
38
2015-01-22T01:03:28.000Z
2021-01-14T12:01:43.000Z
expectit-core/src/test/java/net/sf/expectit/SshJExample.java
zhishengzhang/ExpectIt
5acbe1f8f895fe1dbd63e29bf3ab8e5bbf0873c3
[ "Apache-2.0" ]
41
2015-02-21T11:10:17.000Z
2021-01-11T05:45:15.000Z
36.302326
86
0.610186
4,301
package net.sf.expectit; /* * #%L * ExpectIt * %% * Copyright (C) 2014 Alexey Gavrilov and 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. * #L% */ import static net.schmizz.sshj.connection.channel.direct.Session.Shell; import static net.sf.expectit.filter.Filters.removeColors; import static net.sf.expectit.filter.Filters.removeNonPrintable; import static net.sf.expectit.matcher.Matchers.contains; import static net.sf.expectit.matcher.Matchers.regexp; import java.io.IOException; import java.security.PublicKey; import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.connection.channel.direct.Session; import net.schmizz.sshj.transport.verification.HostKeyVerifier; /** * A ExpectIt example using sshj library. */ public class SshJExample { public static void main(String[] args) throws IOException { SSHClient ssh = new SSHClient(); ssh.addHostKeyVerifier( new HostKeyVerifier() { @Override public boolean verify(String s, int i, PublicKey publicKey) { return true; } }); ssh.connect("sdf.org"); ssh.authPassword("new", ""); Session session = ssh.startSession(); session.allocateDefaultPTY(); Shell shell = session.startShell(); Expect expect = new ExpectBuilder() .withOutput(shell.getOutputStream()) .withInputs(shell.getInputStream(), shell.getErrorStream()) .withEchoInput(System.out) .withEchoOutput(System.err) .withInputFilters(removeColors(), removeNonPrintable()) .withExceptionOnFailure() .build(); try { expect.expect(contains("[RETURN]")); expect.sendLine(); String ipAddress = expect.expect(regexp("Trying (.*)\\.\\.\\.")).group(1); System.out.println("Captured IP: " + ipAddress); expect.expect(contains("login:")); expect.sendLine("new"); expect.expect(contains("(Y/N)")); expect.send("N"); expect.expect(regexp(": $")); expect.send("\b"); expect.expect(regexp("\\(y\\/n\\)")); expect.sendLine("y"); expect.expect(contains("Would you like to sign the guestbook?")); expect.send("n"); expect.expect(contains("[RETURN]")); expect.sendLine(); } finally { expect.close(); session.close(); ssh.close(); } } }
3e0a26da89af1531c186e9c53bba029c55a81c82
1,488
java
Java
ip-black-list-service/src/main/java/ip/black/list/service/protocol/IpBlackListDubboServiceImpl.java
niuqinghua/ip-black-list
4637b93a6fc5c6dd20697dd8eff6c0ace443d14b
[ "Apache-2.0" ]
2
2017-10-23T09:38:02.000Z
2017-10-23T09:38:06.000Z
ip-black-list-service/src/main/java/ip/black/list/service/protocol/IpBlackListDubboServiceImpl.java
niuqinghua/ip-black-list
4637b93a6fc5c6dd20697dd8eff6c0ace443d14b
[ "Apache-2.0" ]
null
null
null
ip-black-list-service/src/main/java/ip/black/list/service/protocol/IpBlackListDubboServiceImpl.java
niuqinghua/ip-black-list
4637b93a6fc5c6dd20697dd8eff6c0ace443d14b
[ "Apache-2.0" ]
null
null
null
34.604651
89
0.777554
4,302
package ip.black.list.service.protocol; import ip.black.list.service.api.dto.IpBlackListDto; import ip.black.list.service.api.protocol.IpBlackListDubboService; import ip.black.list.service.domain.IpBlackList; import ip.black.list.service.service.IpBlackListService; import org.dozer.DozerBeanMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Created by niuqinghua on 2017/2/27. */ @Service("ipBlackListDubboService") public class IpBlackListDubboServiceImpl implements IpBlackListDubboService { private static final DozerBeanMapper dozerBeanMapper = new DozerBeanMapper(); @Autowired private IpBlackListService ipBlackListService; public void add(IpBlackListDto ipBlackListDto) { IpBlackList ipBlackList = dozerBeanMapper.map(ipBlackListDto, IpBlackList.class); ipBlackListService.add(ipBlackList); } public void remove(IpBlackListDto ipBlackListDto) { IpBlackList ipBlackList = dozerBeanMapper.map(ipBlackListDto, IpBlackList.class); ipBlackListService.remove(ipBlackList); } public boolean isInIpBlackList(String appId, String ip) { return ipBlackListService.isInIpBlackList(appId, ip); } public List<String> list(IpBlackListDto ipBlackListDto) { IpBlackList ipBlackList = dozerBeanMapper.map(ipBlackListDto, IpBlackList.class); return ipBlackListService.list(ipBlackList); } }
3e0a27524109c433b4b71df3e8fee696403b3631
4,163
java
Java
ruoyi-system/src/main/java/com/ruoyi/qichengtiyu/controller/QichengtiyuOrderRecordController.java
zyy422/Sign-in-admin
bdfc5066786c85e1ccf71fc472e187a15d537e65
[ "MIT" ]
4
2021-11-03T01:13:53.000Z
2021-12-04T03:25:57.000Z
ruoyi-system/src/main/java/com/ruoyi/qichengtiyu/controller/QichengtiyuOrderRecordController.java
zyy422/Sign-in-admin
bdfc5066786c85e1ccf71fc472e187a15d537e65
[ "MIT" ]
null
null
null
ruoyi-system/src/main/java/com/ruoyi/qichengtiyu/controller/QichengtiyuOrderRecordController.java
zyy422/Sign-in-admin
bdfc5066786c85e1ccf71fc472e187a15d537e65
[ "MIT" ]
1
2021-11-03T14:19:48.000Z
2021-11-03T14:19:48.000Z
39.647619
110
0.730723
4,303
package com.ruoyi.qichengtiyu.controller; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.qichengtiyu.domain.QichengtiyuCourse; import com.ruoyi.qichengtiyu.domain.QichengtiyuOrder; import com.ruoyi.qichengtiyu.domain.QichengtiyuUser; import com.ruoyi.qichengtiyu.service.IQichengtiyuOrderService; import com.ruoyi.qichengtiyu.service.IQichengtiyuUserService; import com.ruoyi.qichengtiyu.service.impl.QichengtiyuTeacherSignServiceImpl; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.math.BigDecimal; import java.text.ParseException; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller @RequestMapping("/qichengtiyu/orderRecord") public class QichengtiyuOrderRecordController implements InitializingBean { private Map<String, String> weekMap = new HashMap<>(); private String prefix = "qichengtiyu/orderRecord"; @Autowired private QichengtiyuTeacherSignServiceImpl qichengtiyuTeacherSignService; @Autowired private IQichengtiyuUserService iQichengtiyuUserService; @Autowired private IQichengtiyuOrderService iQichengtiyuOrderService; @GetMapping() public String course(Model model) { List<QichengtiyuCourse> courseNames = qichengtiyuTeacherSignService.queryAllCourse(); model.addAttribute("courseNames",courseNames); return prefix + "/orderRecord"; } @RequestMapping("/recordSubmit") @ResponseBody public AjaxResult recordSubmit(@RequestBody Map map, Model model) throws ParseException { long courseId = Long.parseLong((String) map.get("courseId")); String courseName = (String) map.get("courseName"); String studentId = (String) map.get("studentId"); String payAmt = (String) map.get("payAmt"); List<String> selectedWeekday = (List<String>) map.get("weekday"); long courseCount = Long.parseLong((String) map.get("courseCount")); QichengtiyuUser user = iQichengtiyuUserService.selectQichengtiyuUserByUserId(Long.valueOf(studentId)); QichengtiyuOrder order = new QichengtiyuOrder(); order.setCourseId(courseId); order.setCourseName(courseName); order.setStudentId(studentId); order.setPayAmt(new BigDecimal(payAmt)); order.setTotalCourse(courseCount); order.setRemainCourse(courseCount); order.setPayTime(new Date()); order.setUsername(user.getUsername()); order.setStudentNickname(user.getNickname()); StringBuilder weekday = new StringBuilder(); for (String eachSelected : selectedWeekday) { weekday.append(this.weekMap.get(eachSelected)).append("|"); } order.setCourseWeek(weekday.toString()); int indertedNo = iQichengtiyuOrderService.insertQichengtiyuOrder(order); return indertedNo == 1 ? AjaxResult.success(): AjaxResult.error(); } @RequestMapping("/queryStudentName") @ResponseBody public Object queryStudentName(@RequestBody Map map, Model model) throws ParseException { long studentId = Long.parseLong((String) map.get("studentId")); QichengtiyuUser students = iQichengtiyuUserService.selectQichengtiyuUserByUserId(studentId); Map res = new HashMap(); res.put("studentName", students==null ? "用户不存在!" : students.getUsername()); return res; } @Override public void afterPropertiesSet() throws Exception { weekMap.put("1","星期一"); weekMap.put("2","星期二"); weekMap.put("3","星期三"); weekMap.put("4","星期四"); weekMap.put("5","星期五"); weekMap.put("6","星期六"); weekMap.put("7","星期日"); } }
3e0a284d9c5481c625a8f81eba72ef8b7727a11f
709
java
Java
src/main/java/mfrf/magic_circle/magicutil/nodes/effectnode/EffectNodeBase.java
teacon2021-MFRF/Magic-Circle
72209593e9f4d6c000aaef4ea995b259eefc1aa1
[ "MIT" ]
4
2021-05-03T01:03:01.000Z
2021-05-09T02:09:50.000Z
src/main/java/mfrf/magic_circle/magicutil/nodes/effectnode/EffectNodeBase.java
teacon2021-MFRF/Magic-Circle
72209593e9f4d6c000aaef4ea995b259eefc1aa1
[ "MIT" ]
null
null
null
src/main/java/mfrf/magic_circle/magicutil/nodes/effectnode/EffectNodeBase.java
teacon2021-MFRF/Magic-Circle
72209593e9f4d6c000aaef4ea995b259eefc1aa1
[ "MIT" ]
null
null
null
29.541667
106
0.754584
4,304
package mfrf.magic_circle.magicutil.nodes.effectnode; import mfrf.magic_circle.magicutil.MagicNodeBase; import mfrf.magic_circle.magicutil.datastructure.MagicStreamMatrixNByN; import net.minecraft.nbt.CompoundNBT; public abstract class EffectNodeBase extends MagicNodeBase { public final EffectType effectType; public EffectNodeBase(EffectType effectType) { super(NodeType.EFFECT); this.effectType = effectType; } public static MagicNodeBase deserializeNBT(CompoundNBT nbt, int layer, MagicStreamMatrixNByN matrix) { return null; } public enum EffectType { REDSTONE, LIHUO, KANSHUI, KUNDI, GENSHAN, THUNDER, DUIZE, DRYSKY, SUNDAE, TAICHI; } }
3e0a2867a109e6071a3099bbe1eabac75071d356
1,377
java
Java
demo/demo-schema/src/main/java/org/apache/servicecomb/demo/smartcare/Response.java
MC-JY/servicecomb-java-chassis
6c769733220a2ea7b4f2161ee4e0451d9f289cc8
[ "Apache-2.0" ]
1,336
2018-11-10T14:52:16.000Z
2022-03-25T16:17:27.000Z
demo/demo-schema/src/main/java/org/apache/servicecomb/demo/smartcare/Response.java
MC-JY/servicecomb-java-chassis
6c769733220a2ea7b4f2161ee4e0451d9f289cc8
[ "Apache-2.0" ]
1,582
2018-11-09T09:44:51.000Z
2022-03-31T08:07:21.000Z
demo/demo-schema/src/main/java/org/apache/servicecomb/demo/smartcare/Response.java
MC-JY/servicecomb-java-chassis
6c769733220a2ea7b4f2161ee4e0451d9f289cc8
[ "Apache-2.0" ]
485
2018-11-12T01:58:35.000Z
2022-03-24T02:10:00.000Z
29.934783
82
0.735657
4,305
/* * 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.demo.smartcare; public class Response { private int resultCode; private String resultMessage; public int getResultCode() { return resultCode; } public void setResultCode(int resultCode) { this.resultCode = resultCode; } public String getResultMessage() { return resultMessage; } public void setResultMessage(String resultMessage) { this.resultMessage = resultMessage; } @Override public String toString() { return "resultCode: " + resultCode + "\n" + "resultMessage: " + resultMessage; } }
3e0a28f0f882f219dc3fcece56d49916afd5f68a
884
java
Java
sharding-jdbc-core/src/main/java/com/dangdang/ddframe/rdb/sharding/api/strategy/database/DatabaseShardingAlgorithm.java
292388900/sharding-jdbc_bak
82c3227b841f1ab9de410960332aa7a143abdc64
[ "Apache-2.0" ]
1
2020-07-31T07:43:20.000Z
2020-07-31T07:43:20.000Z
sharding-jdbc-core/src/main/java/com/dangdang/ddframe/rdb/sharding/api/strategy/database/DatabaseShardingAlgorithm.java
teddyjoan/sharding-jdbc
5cf4d8b87e3ff9ec4cd299068e582abeab56dfe9
[ "Apache-2.0" ]
1
2022-01-21T23:48:24.000Z
2022-01-21T23:48:24.000Z
sharding-jdbc-core/src/main/java/com/dangdang/ddframe/rdb/sharding/api/strategy/database/DatabaseShardingAlgorithm.java
teddyjoan/sharding-jdbc
5cf4d8b87e3ff9ec4cd299068e582abeab56dfe9
[ "Apache-2.0" ]
1
2021-03-03T03:42:06.000Z
2021-03-03T03:42:06.000Z
30.482759
79
0.742081
4,306
/** * Copyright 1999-2015 dangdang.com. * <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 com.dangdang.ddframe.rdb.sharding.api.strategy.database; import com.dangdang.ddframe.rdb.sharding.api.strategy.common.ShardingAlgorithm; /** * 分库算法接口. * * @author zhangliang */ public interface DatabaseShardingAlgorithm extends ShardingAlgorithm { }
3e0a2a2ae2bd80b4c540674d35cc90120739eab5
23,269
java
Java
tool/src/test/java/protobuf/test/SearchRequest.java
qifanyang/tool
541a0153ac55e20efa3c40766abac9c966a6af1c
[ "MIT" ]
null
null
null
tool/src/test/java/protobuf/test/SearchRequest.java
qifanyang/tool
541a0153ac55e20efa3c40766abac9c966a6af1c
[ "MIT" ]
null
null
null
tool/src/test/java/protobuf/test/SearchRequest.java
qifanyang/tool
541a0153ac55e20efa3c40766abac9c966a6af1c
[ "MIT" ]
null
null
null
33.577201
132
0.636039
4,307
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: seachRequest.proto package protobuf.test; public final class SearchRequest { private SearchRequest() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } public interface SearchRequestProtoOrBuilder extends com.google.protobuf.MessageOrBuilder { // required string query = 1; /** * <code>required string query = 1;</code> */ boolean hasQuery(); /** * <code>required string query = 1;</code> */ java.lang.String getQuery(); /** * <code>required string query = 1;</code> */ com.google.protobuf.ByteString getQueryBytes(); // optional int32 page_number = 2; /** * <code>optional int32 page_number = 2;</code> */ boolean hasPageNumber(); /** * <code>optional int32 page_number = 2;</code> */ int getPageNumber(); // optional int32 result_per_page = 3; /** * <code>optional int32 result_per_page = 3;</code> */ boolean hasResultPerPage(); /** * <code>optional int32 result_per_page = 3;</code> */ int getResultPerPage(); } /** * Protobuf type {@code SearchRequestProto} */ public static final class SearchRequestProto extends com.google.protobuf.GeneratedMessage implements SearchRequestProtoOrBuilder { // Use SearchRequestProto.newBuilder() to construct. private SearchRequestProto(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private SearchRequestProto(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final SearchRequestProto defaultInstance; public static SearchRequestProto getDefaultInstance() { return defaultInstance; } public SearchRequestProto getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private SearchRequestProto( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { bitField0_ |= 0x00000001; query_ = input.readBytes(); break; } case 16: { bitField0_ |= 0x00000002; pageNumber_ = input.readInt32(); break; } case 24: { bitField0_ |= 0x00000004; resultPerPage_ = input.readInt32(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return protobuf.test.SearchRequest.internal_static_SearchRequestProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return protobuf.test.SearchRequest.internal_static_SearchRequestProto_fieldAccessorTable .ensureFieldAccessorsInitialized( protobuf.test.SearchRequest.SearchRequestProto.class, protobuf.test.SearchRequest.SearchRequestProto.Builder.class); } public static com.google.protobuf.Parser<SearchRequestProto> PARSER = new com.google.protobuf.AbstractParser<SearchRequestProto>() { public SearchRequestProto parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new SearchRequestProto(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<SearchRequestProto> getParserForType() { return PARSER; } private int bitField0_; // required string query = 1; public static final int QUERY_FIELD_NUMBER = 1; private java.lang.Object query_; /** * <code>required string query = 1;</code> */ public boolean hasQuery() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required string query = 1;</code> */ public java.lang.String getQuery() { java.lang.Object ref = query_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { query_ = s; } return s; } } /** * <code>required string query = 1;</code> */ public com.google.protobuf.ByteString getQueryBytes() { java.lang.Object ref = query_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); query_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // optional int32 page_number = 2; public static final int PAGE_NUMBER_FIELD_NUMBER = 2; private int pageNumber_; /** * <code>optional int32 page_number = 2;</code> */ public boolean hasPageNumber() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional int32 page_number = 2;</code> */ public int getPageNumber() { return pageNumber_; } // optional int32 result_per_page = 3; public static final int RESULT_PER_PAGE_FIELD_NUMBER = 3; private int resultPerPage_; /** * <code>optional int32 result_per_page = 3;</code> */ public boolean hasResultPerPage() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional int32 result_per_page = 3;</code> */ public int getResultPerPage() { return resultPerPage_; } private void initFields() { query_ = ""; pageNumber_ = 0; resultPerPage_ = 0; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasQuery()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeBytes(1, getQueryBytes()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeInt32(2, pageNumber_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeInt32(3, resultPerPage_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(1, getQueryBytes()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(2, pageNumber_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(3, resultPerPage_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static protobuf.test.SearchRequest.SearchRequestProto parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static protobuf.test.SearchRequest.SearchRequestProto parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static protobuf.test.SearchRequest.SearchRequestProto parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static protobuf.test.SearchRequest.SearchRequestProto parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static protobuf.test.SearchRequest.SearchRequestProto parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static protobuf.test.SearchRequest.SearchRequestProto parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static protobuf.test.SearchRequest.SearchRequestProto parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static protobuf.test.SearchRequest.SearchRequestProto parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static protobuf.test.SearchRequest.SearchRequestProto parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static protobuf.test.SearchRequest.SearchRequestProto parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(protobuf.test.SearchRequest.SearchRequestProto prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code SearchRequestProto} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements protobuf.test.SearchRequest.SearchRequestProtoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return protobuf.test.SearchRequest.internal_static_SearchRequestProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return protobuf.test.SearchRequest.internal_static_SearchRequestProto_fieldAccessorTable .ensureFieldAccessorsInitialized( protobuf.test.SearchRequest.SearchRequestProto.class, protobuf.test.SearchRequest.SearchRequestProto.Builder.class); } // Construct using protobuf.test.SearchRequest.SearchRequestProto.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); query_ = ""; bitField0_ = (bitField0_ & ~0x00000001); pageNumber_ = 0; bitField0_ = (bitField0_ & ~0x00000002); resultPerPage_ = 0; bitField0_ = (bitField0_ & ~0x00000004); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return protobuf.test.SearchRequest.internal_static_SearchRequestProto_descriptor; } public protobuf.test.SearchRequest.SearchRequestProto getDefaultInstanceForType() { return protobuf.test.SearchRequest.SearchRequestProto.getDefaultInstance(); } public protobuf.test.SearchRequest.SearchRequestProto build() { protobuf.test.SearchRequest.SearchRequestProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public protobuf.test.SearchRequest.SearchRequestProto buildPartial() { protobuf.test.SearchRequest.SearchRequestProto result = new protobuf.test.SearchRequest.SearchRequestProto(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.query_ = query_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.pageNumber_ = pageNumber_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.resultPerPage_ = resultPerPage_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof protobuf.test.SearchRequest.SearchRequestProto) { return mergeFrom((protobuf.test.SearchRequest.SearchRequestProto)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(protobuf.test.SearchRequest.SearchRequestProto other) { if (other == protobuf.test.SearchRequest.SearchRequestProto.getDefaultInstance()) return this; if (other.hasQuery()) { bitField0_ |= 0x00000001; query_ = other.query_; onChanged(); } if (other.hasPageNumber()) { setPageNumber(other.getPageNumber()); } if (other.hasResultPerPage()) { setResultPerPage(other.getResultPerPage()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasQuery()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { protobuf.test.SearchRequest.SearchRequestProto parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (protobuf.test.SearchRequest.SearchRequestProto) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // required string query = 1; private java.lang.Object query_ = ""; /** * <code>required string query = 1;</code> */ public boolean hasQuery() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required string query = 1;</code> */ public java.lang.String getQuery() { java.lang.Object ref = query_; if (!(ref instanceof java.lang.String)) { java.lang.String s = ((com.google.protobuf.ByteString) ref) .toStringUtf8(); query_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>required string query = 1;</code> */ public com.google.protobuf.ByteString getQueryBytes() { java.lang.Object ref = query_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); query_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>required string query = 1;</code> */ public Builder setQuery( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; query_ = value; onChanged(); return this; } /** * <code>required string query = 1;</code> */ public Builder clearQuery() { bitField0_ = (bitField0_ & ~0x00000001); query_ = getDefaultInstance().getQuery(); onChanged(); return this; } /** * <code>required string query = 1;</code> */ public Builder setQueryBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; query_ = value; onChanged(); return this; } // optional int32 page_number = 2; private int pageNumber_ ; /** * <code>optional int32 page_number = 2;</code> */ public boolean hasPageNumber() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional int32 page_number = 2;</code> */ public int getPageNumber() { return pageNumber_; } /** * <code>optional int32 page_number = 2;</code> */ public Builder setPageNumber(int value) { bitField0_ |= 0x00000002; pageNumber_ = value; onChanged(); return this; } /** * <code>optional int32 page_number = 2;</code> */ public Builder clearPageNumber() { bitField0_ = (bitField0_ & ~0x00000002); pageNumber_ = 0; onChanged(); return this; } // optional int32 result_per_page = 3; private int resultPerPage_ ; /** * <code>optional int32 result_per_page = 3;</code> */ public boolean hasResultPerPage() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional int32 result_per_page = 3;</code> */ public int getResultPerPage() { return resultPerPage_; } /** * <code>optional int32 result_per_page = 3;</code> */ public Builder setResultPerPage(int value) { bitField0_ |= 0x00000004; resultPerPage_ = value; onChanged(); return this; } /** * <code>optional int32 result_per_page = 3;</code> */ public Builder clearResultPerPage() { bitField0_ = (bitField0_ & ~0x00000004); resultPerPage_ = 0; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:SearchRequestProto) } static { defaultInstance = new SearchRequestProto(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:SearchRequestProto) } private static com.google.protobuf.Descriptors.Descriptor internal_static_SearchRequestProto_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_SearchRequestProto_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\022seachRequest.proto\"Q\n\022SearchRequestPro" + "to\022\r\n\005query\030\001 \002(\t\022\023\n\013page_number\030\002 \001(\005\022\027" + "\n\017result_per_page\030\003 \001(\005B\036\n\rprotobuf.test" + "B\rSearchRequest" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; internal_static_SearchRequestProto_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_SearchRequestProto_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_SearchRequestProto_descriptor, new java.lang.String[] { "Query", "PageNumber", "ResultPerPage", }); return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); } // @@protoc_insertion_point(outer_class_scope) }
3e0a2a5b5bcf840f7ffdcee9eaef6a8f01964c94
17,227
java
Java
bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer/dynamodb/AddLSIDialog.java
mmusti1234/aws-toolkit-eclipse
85417f68e1eb6d90d46e145229e390cf55a4a554
[ "Apache-2.0" ]
202
2015-01-23T09:41:51.000Z
2022-03-22T02:27:20.000Z
bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer/dynamodb/AddLSIDialog.java
mmusti1234/aws-toolkit-eclipse
85417f68e1eb6d90d46e145229e390cf55a4a554
[ "Apache-2.0" ]
209
2015-03-18T15:34:48.000Z
2022-03-02T22:23:55.000Z
bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer/dynamodb/AddLSIDialog.java
mmusti1234/aws-toolkit-eclipse
85417f68e1eb6d90d46e145229e390cf55a4a554
[ "Apache-2.0" ]
166
2015-01-02T20:12:00.000Z
2022-03-20T22:35:53.000Z
45.334211
196
0.67104
4,308
/* * Copyright 2013 Amazon Technologies, 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://aws.amazon.com/apache2.0 * * 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.eclipse.explorer.dynamodb; import java.util.Arrays; import java.util.LinkedList; import org.eclipse.core.databinding.AggregateValidationStatus; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.PojoObservables; import org.eclipse.core.databinding.observable.ChangeEvent; import org.eclipse.core.databinding.observable.IChangeListener; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.jface.databinding.viewers.ObservableListContentProvider; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.ListViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.databinding.ChainValidator; import com.amazonaws.eclipse.databinding.NotEmptyValidator; import com.amazonaws.eclipse.dynamodb.AbstractAddNewAttributeDialog; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.LocalSecondaryIndex; import com.amazonaws.services.dynamodbv2.model.Projection; public class AddLSIDialog extends TitleAreaDialog { /** Widget used as data-binding targets **/ private Text attributeNameText; private Text indexNameText; private Combo attributeTypeCombo; private Combo projectionTypeCombo; private Button addAttributeButton; private Button okButton; /** The data objects that will be used to generate the service request **/ private final LocalSecondaryIndex localSecondaryIndex; private final AttributeDefinition indexRangeKeyAttributeDefinition; private final DataBindingContext bindingContext = new DataBindingContext(); /** The model value objects for data-binding **/ private final IObservableValue indexNameModel; private final IObservableValue indexRangeKeyNameInKeySchemaDefinitionModel; private final IObservableValue indexRangeKeyNameInAttributeDefinitionsModel; private final IObservableValue indexRangeKeyAttributeTypeModel; private final IObservableValue projectionTypeModel; private final String primaryRangeKeyName; private final int primaryRangeKeyTypeComboIndex; private static final String[] DATA_TYPE_STRINGS = new String[] { "String", "Number", "Binary" }; private static final String[] PROJECTED_ATTRIBUTES = new String[] { "All Attributes", "Table and Index Keys", "Specify Attributes" }; public AddLSIDialog(Shell parentShell, CreateTableDataModel dataModel) { super(parentShell); // Initialize the variable necessary for data-binding localSecondaryIndex = new LocalSecondaryIndex(); // The index range key to be defined by the user KeySchemaElement rangeKeySchemaDefinition = new KeySchemaElement() .withAttributeName(null) .withKeyType(KeyType.RANGE); localSecondaryIndex.withKeySchema( new KeySchemaElement() .withAttributeName(dataModel.getHashKeyName()) .withKeyType(KeyType.HASH), rangeKeySchemaDefinition); localSecondaryIndex.setProjection(new Projection()); // The attribute definition for the index range key indexRangeKeyAttributeDefinition = new AttributeDefinition(); // Initialize IObservableValue objects that keep track of data variables indexNameModel = PojoObservables.observeValue(localSecondaryIndex, "indexName"); indexRangeKeyNameInKeySchemaDefinitionModel = PojoObservables.observeValue(rangeKeySchemaDefinition, "attributeName"); indexRangeKeyAttributeTypeModel = PojoObservables.observeValue(indexRangeKeyAttributeDefinition, "attributeType"); indexRangeKeyNameInAttributeDefinitionsModel = PojoObservables.observeValue(indexRangeKeyAttributeDefinition, "attributeName"); projectionTypeModel = PojoObservables.observeValue(localSecondaryIndex.getProjection(), "projectionType"); // Get the information of the primary range key if (dataModel.getEnableRangeKey()) { primaryRangeKeyName = dataModel.getRangeKeyName(); primaryRangeKeyTypeComboIndex = Arrays.<String>asList(DATA_TYPE_STRINGS).indexOf(dataModel.getRangeKeyType()); } else { primaryRangeKeyName = null; primaryRangeKeyTypeComboIndex = -1; } setShellStyle(SWT.RESIZE); } @Override protected Control createContents(Composite parent) { Control contents = super.createContents(parent); setTitle("Add Local Secondary Index"); setTitleImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_LOGO)); okButton = getButton(IDialogConstants.OK_ID); okButton.setEnabled(false); return contents; } @Override protected void configureShell(Shell shell) { super.configureShell(shell); shell.setText("Add Local Secondary Index"); shell.setMinimumSize(400, 500); } @Override protected Control createDialogArea(Composite parent) { Composite composite = (Composite) super.createDialogArea(parent); GridDataFactory.fillDefaults().grab(true, true).applyTo(composite); composite.setLayout(new GridLayout()); composite = new Composite(composite, SWT.NULL); GridDataFactory.fillDefaults().grab(true, true).applyTo(composite); composite.setLayout(new GridLayout(2, false)); // Index range key attribute name new Label(composite, SWT.NONE | SWT.READ_ONLY).setText("Attribute to Index:"); attributeNameText = new Text(composite, SWT.BORDER); bindingContext.bindValue(SWTObservables.observeText(attributeNameText, SWT.Modify), indexRangeKeyNameInKeySchemaDefinitionModel); ChainValidator<String> attributeNameValidationStatusProvider = new ChainValidator<>(indexRangeKeyNameInKeySchemaDefinitionModel, new NotEmptyValidator("Please provide an attribute name")); bindingContext.addValidationStatusProvider(attributeNameValidationStatusProvider); bindingContext.bindValue(SWTObservables.observeText(attributeNameText, SWT.Modify), indexRangeKeyNameInAttributeDefinitionsModel); attributeNameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { if (attributeNameText.getText().equals(primaryRangeKeyName) && attributeTypeCombo != null && primaryRangeKeyTypeComboIndex > -1) { attributeTypeCombo.select(primaryRangeKeyTypeComboIndex); attributeTypeCombo.setEnabled(false); } else if (attributeTypeCombo != null) { attributeTypeCombo.setEnabled(true); } } }); GridDataFactory.fillDefaults().grab(true, false).applyTo(attributeNameText); // Index range key attribute type new Label(composite, SWT.NONE | SWT.READ_ONLY).setText("Attribute Type:"); attributeTypeCombo = new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY); attributeTypeCombo.setItems(DATA_TYPE_STRINGS); attributeTypeCombo.select(0); bindingContext.bindValue(SWTObservables.observeSelection(attributeTypeCombo), indexRangeKeyAttributeTypeModel); // Index name new Label(composite, SWT.NONE | SWT.READ_ONLY).setText("Index Name:"); indexNameText = new Text(composite, SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).applyTo(indexNameText); bindingContext.bindValue(SWTObservables.observeText(indexNameText, SWT.Modify), indexNameModel); ChainValidator<String> indexNameValidationStatusProvider = new ChainValidator<>(indexNameModel, new NotEmptyValidator("Please provide an index name")); bindingContext.addValidationStatusProvider(indexNameValidationStatusProvider); // Projection type new Label(composite, SWT.NONE | SWT.READ_ONLY).setText("Projected Attributes:"); projectionTypeCombo = new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY); projectionTypeCombo.setItems(PROJECTED_ATTRIBUTES); projectionTypeCombo.select(0); bindingContext.bindValue(SWTObservables.observeSelection(projectionTypeCombo), projectionTypeModel); projectionTypeCombo.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { if (projectionTypeCombo.getSelectionIndex() == 2) { // Enable the list for adding non-key attributes to the projection addAttributeButton.setEnabled(true); } else { addAttributeButton.setEnabled(false); } } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); // Non-key attributes in the projection final AttributeList attributeList = new AttributeList(composite); GridDataFactory.fillDefaults().grab(true, true).hint(SWT.DEFAULT, SWT.DEFAULT).applyTo(attributeList); addAttributeButton = new Button(composite, SWT.PUSH); addAttributeButton.setText("Add Attribute"); addAttributeButton.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING)); addAttributeButton.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_ADD)); addAttributeButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { AddNewAttributeDialog newAttributeTable = new AddNewAttributeDialog(); if (newAttributeTable.open() == 0) { // lazy-initialize the list if (null == localSecondaryIndex.getProjection().getNonKeyAttributes()) { localSecondaryIndex.getProjection().setNonKeyAttributes(new LinkedList<String>()); } localSecondaryIndex.getProjection().getNonKeyAttributes().add(newAttributeTable.getNewAttributeName()); attributeList.refresh(); } } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); addAttributeButton.setEnabled(false); // Finally provide aggregate status reporting for the entire wizard page final AggregateValidationStatus aggregateValidationStatus = new AggregateValidationStatus(bindingContext, AggregateValidationStatus.MAX_SEVERITY); aggregateValidationStatus.addChangeListener(new IChangeListener() { @Override public void handleChange(ChangeEvent event) { Object value = aggregateValidationStatus.getValue(); if (value instanceof IStatus == false) return; IStatus status = (IStatus) value; if (status.getSeverity() == Status.ERROR) { setErrorMessage(status.getMessage()); if (okButton != null) { okButton.setEnabled(false); } } else { setErrorMessage(null); if (okButton != null) { okButton.setEnabled(true); } } } }); bindingContext.updateModels(); return composite; } public LocalSecondaryIndex getLocalSecondaryIndex() { return localSecondaryIndex; } /** * Get the AttributeDefinition of the index range key as specified in this dialog. */ public AttributeDefinition getIndexRangeKeyAttributeDefinition() { return indexRangeKeyAttributeDefinition; } private class AddNewAttributeDialog extends AbstractAddNewAttributeDialog { @Override public void validate() { if (getButton(0) == null) return; if (getNewAttributeName().length() == 0) { getButton(0).setEnabled(false); return; } getButton(0).setEnabled(true); return; } } /** The list widget for adding projected non-key attributes. **/ private class AttributeList extends Composite { private ListViewer viewer; private AttributeListContentProvider attributeListContentProvider; public AttributeList(Composite parent) { super(parent, SWT.NONE); this.setLayout(new GridLayout()); viewer = new ListViewer(this, SWT.BORDER | SWT.V_SCROLL | SWT.READ_ONLY); attributeListContentProvider = new AttributeListContentProvider(); viewer.setContentProvider(attributeListContentProvider); viewer.setLabelProvider(new LabelProvider()); GridDataFactory.fillDefaults().grab(true, true).applyTo(viewer.getList()); viewer.getList().setVisible(true); MenuManager menuManager = new MenuManager("#PopupMenu"); menuManager.setRemoveAllWhenShown(true); menuManager.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { if (viewer.getList().getSelectionCount() > 0) { manager.add(new Action() { @Override public ImageDescriptor getImageDescriptor() { return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE); } @Override public void run() { // In theory, this should never be null. if (null != localSecondaryIndex.getProjection().getNonKeyAttributes()) { localSecondaryIndex.getProjection().getNonKeyAttributes().remove(viewer.getList().getSelectionIndex()); } refresh(); } @Override public String getText() { return "Delete Attribute"; } }); } } }); viewer.getList().setMenu(menuManager.createContextMenu(viewer.getList())); } // Enforce to call getElements to update list public void refresh() { viewer.setInput(new Object()); } } private class AttributeListContentProvider extends ObservableListContentProvider { @Override public void dispose() { } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } @Override public Object[] getElements(Object inputElement) { return localSecondaryIndex.getProjection().getNonKeyAttributes() != null ? localSecondaryIndex.getProjection().getNonKeyAttributes().toArray() : new String[] {}; } } }
3e0a2b4aa1944be3462468f100e9ea61dc15c689
26,167
java
Java
build/src/main/java/com/mypurecloud/sdk/v2/api/WebChatApiAsync.java
Dschinds/platform-client-sdk-java
8fbf2b9bb4ef89347e0e71d1c874737201d7e58b
[ "MIT" ]
null
null
null
build/src/main/java/com/mypurecloud/sdk/v2/api/WebChatApiAsync.java
Dschinds/platform-client-sdk-java
8fbf2b9bb4ef89347e0e71d1c874737201d7e58b
[ "MIT" ]
null
null
null
build/src/main/java/com/mypurecloud/sdk/v2/api/WebChatApiAsync.java
Dschinds/platform-client-sdk-java
8fbf2b9bb4ef89347e0e71d1c874737201d7e58b
[ "MIT" ]
null
null
null
37.923188
193
0.680819
4,309
package com.mypurecloud.sdk.v2.api; import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.SettableFuture; import com.mypurecloud.sdk.v2.AsyncApiCallback; import com.mypurecloud.sdk.v2.ApiException; import com.mypurecloud.sdk.v2.ApiClient; import com.mypurecloud.sdk.v2.ApiRequest; import com.mypurecloud.sdk.v2.ApiResponse; import com.mypurecloud.sdk.v2.Configuration; import com.mypurecloud.sdk.v2.model.*; import com.mypurecloud.sdk.v2.Pair; import com.mypurecloud.sdk.v2.model.ErrorBody; import com.mypurecloud.sdk.v2.model.WebChatDeployment; import com.mypurecloud.sdk.v2.model.WebChatDeploymentEntityListing; import com.mypurecloud.sdk.v2.model.WebChatSettings; import com.mypurecloud.sdk.v2.api.request.DeleteWebchatDeploymentRequest; import com.mypurecloud.sdk.v2.api.request.DeleteWebchatSettingsRequest; import com.mypurecloud.sdk.v2.api.request.GetWebchatDeploymentRequest; import com.mypurecloud.sdk.v2.api.request.GetWebchatDeploymentsRequest; import com.mypurecloud.sdk.v2.api.request.GetWebchatSettingsRequest; import com.mypurecloud.sdk.v2.api.request.PostWebchatDeploymentsRequest; import com.mypurecloud.sdk.v2.api.request.PutWebchatDeploymentRequest; import com.mypurecloud.sdk.v2.api.request.PutWebchatSettingsRequest; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Future; public class WebChatApiAsync { private final ApiClient pcapiClient; public WebChatApiAsync() { this(Configuration.getDefaultApiClient()); } public WebChatApiAsync(ApiClient apiClient) { this.pcapiClient = apiClient; } /** * Delete a WebChat deployment * * @param request the request object * @param callback the action to perform when the request is completed * @return the future indication when the request has completed */ public Future<Void> deleteWebchatDeploymentAsync(DeleteWebchatDeploymentRequest request, final AsyncApiCallback<Void> callback) { try { final SettableFuture<Void> future = SettableFuture.create(); final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors(); pcapiClient.invokeAsync(request.withHttpInfo(), null, new AsyncApiCallback<ApiResponse<Void>>() { @Override public void onCompleted(ApiResponse<Void> response) { notifySuccess(future, callback, response.getBody()); } @Override public void onFailed(Throwable exception) { if (shouldThrowErrors) { notifyFailure(future, callback, exception); } else { notifySuccess(future, callback, null); } } }); return future; } catch (Throwable exception) { return Futures.immediateFailedFuture(exception); } } /** * Delete a WebChat deployment * * @param request the request object * @param callback the action to perform when the request is completed * @return the future indication when the request has completed */ public Future<ApiResponse<Void>> deleteWebchatDeploymentAsync(ApiRequest<Void> request, final AsyncApiCallback<ApiResponse<Void>> callback) { try { final SettableFuture<ApiResponse<Void>> future = SettableFuture.create(); final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors(); pcapiClient.invokeAsync(request, null, new AsyncApiCallback<ApiResponse<Void>>() { @Override public void onCompleted(ApiResponse<Void> response) { notifySuccess(future, callback, response); } @Override public void onFailed(Throwable exception) { if (exception instanceof ApiException) { @SuppressWarnings("unchecked") ApiResponse<Void> response = (ApiResponse<Void>)(ApiResponse<?>)exception; notifySuccess(future, callback, response); } if (shouldThrowErrors) { notifyFailure(future, callback, exception); } else { @SuppressWarnings("unchecked") ApiResponse<Void> response = (ApiResponse<Void>)(ApiResponse<?>)(new ApiException(exception)); notifySuccess(future, callback, response); } } }); return future; } catch (Throwable exception) { return Futures.immediateFailedFuture(exception); } } /** * Remove WebChat deployment settings * * @param request the request object * @param callback the action to perform when the request is completed * @return the future indication when the request has completed */ public Future<Void> deleteWebchatSettingsAsync(DeleteWebchatSettingsRequest request, final AsyncApiCallback<Void> callback) { try { final SettableFuture<Void> future = SettableFuture.create(); final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors(); pcapiClient.invokeAsync(request.withHttpInfo(), null, new AsyncApiCallback<ApiResponse<Void>>() { @Override public void onCompleted(ApiResponse<Void> response) { notifySuccess(future, callback, response.getBody()); } @Override public void onFailed(Throwable exception) { if (shouldThrowErrors) { notifyFailure(future, callback, exception); } else { notifySuccess(future, callback, null); } } }); return future; } catch (Throwable exception) { return Futures.immediateFailedFuture(exception); } } /** * Remove WebChat deployment settings * * @param request the request object * @param callback the action to perform when the request is completed * @return the future indication when the request has completed */ public Future<ApiResponse<Void>> deleteWebchatSettingsAsync(ApiRequest<Void> request, final AsyncApiCallback<ApiResponse<Void>> callback) { try { final SettableFuture<ApiResponse<Void>> future = SettableFuture.create(); final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors(); pcapiClient.invokeAsync(request, null, new AsyncApiCallback<ApiResponse<Void>>() { @Override public void onCompleted(ApiResponse<Void> response) { notifySuccess(future, callback, response); } @Override public void onFailed(Throwable exception) { if (exception instanceof ApiException) { @SuppressWarnings("unchecked") ApiResponse<Void> response = (ApiResponse<Void>)(ApiResponse<?>)exception; notifySuccess(future, callback, response); } if (shouldThrowErrors) { notifyFailure(future, callback, exception); } else { @SuppressWarnings("unchecked") ApiResponse<Void> response = (ApiResponse<Void>)(ApiResponse<?>)(new ApiException(exception)); notifySuccess(future, callback, response); } } }); return future; } catch (Throwable exception) { return Futures.immediateFailedFuture(exception); } } /** * Get a WebChat deployment * * @param request the request object * @param callback the action to perform when the request is completed * @return the future indication when the request has completed */ public Future<WebChatDeployment> getWebchatDeploymentAsync(GetWebchatDeploymentRequest request, final AsyncApiCallback<WebChatDeployment> callback) { try { final SettableFuture<WebChatDeployment> future = SettableFuture.create(); final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors(); pcapiClient.invokeAsync(request.withHttpInfo(), new TypeReference<WebChatDeployment>() {}, new AsyncApiCallback<ApiResponse<WebChatDeployment>>() { @Override public void onCompleted(ApiResponse<WebChatDeployment> response) { notifySuccess(future, callback, response.getBody()); } @Override public void onFailed(Throwable exception) { if (shouldThrowErrors) { notifyFailure(future, callback, exception); } else { notifySuccess(future, callback, null); } } }); return future; } catch (Throwable exception) { return Futures.immediateFailedFuture(exception); } } /** * Get a WebChat deployment * * @param request the request object * @param callback the action to perform when the request is completed * @return the future indication when the request has completed */ public Future<ApiResponse<WebChatDeployment>> getWebchatDeploymentAsync(ApiRequest<Void> request, final AsyncApiCallback<ApiResponse<WebChatDeployment>> callback) { try { final SettableFuture<ApiResponse<WebChatDeployment>> future = SettableFuture.create(); final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors(); pcapiClient.invokeAsync(request, new TypeReference<WebChatDeployment>() {}, new AsyncApiCallback<ApiResponse<WebChatDeployment>>() { @Override public void onCompleted(ApiResponse<WebChatDeployment> response) { notifySuccess(future, callback, response); } @Override public void onFailed(Throwable exception) { if (exception instanceof ApiException) { @SuppressWarnings("unchecked") ApiResponse<WebChatDeployment> response = (ApiResponse<WebChatDeployment>)(ApiResponse<?>)exception; notifySuccess(future, callback, response); } if (shouldThrowErrors) { notifyFailure(future, callback, exception); } else { @SuppressWarnings("unchecked") ApiResponse<WebChatDeployment> response = (ApiResponse<WebChatDeployment>)(ApiResponse<?>)(new ApiException(exception)); notifySuccess(future, callback, response); } } }); return future; } catch (Throwable exception) { return Futures.immediateFailedFuture(exception); } } /** * List WebChat deployments * * @param request the request object * @param callback the action to perform when the request is completed * @return the future indication when the request has completed */ public Future<WebChatDeploymentEntityListing> getWebchatDeploymentsAsync(GetWebchatDeploymentsRequest request, final AsyncApiCallback<WebChatDeploymentEntityListing> callback) { try { final SettableFuture<WebChatDeploymentEntityListing> future = SettableFuture.create(); final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors(); pcapiClient.invokeAsync(request.withHttpInfo(), new TypeReference<WebChatDeploymentEntityListing>() {}, new AsyncApiCallback<ApiResponse<WebChatDeploymentEntityListing>>() { @Override public void onCompleted(ApiResponse<WebChatDeploymentEntityListing> response) { notifySuccess(future, callback, response.getBody()); } @Override public void onFailed(Throwable exception) { if (shouldThrowErrors) { notifyFailure(future, callback, exception); } else { notifySuccess(future, callback, null); } } }); return future; } catch (Throwable exception) { return Futures.immediateFailedFuture(exception); } } /** * List WebChat deployments * * @param request the request object * @param callback the action to perform when the request is completed * @return the future indication when the request has completed */ public Future<ApiResponse<WebChatDeploymentEntityListing>> getWebchatDeploymentsAsync(ApiRequest<Void> request, final AsyncApiCallback<ApiResponse<WebChatDeploymentEntityListing>> callback) { try { final SettableFuture<ApiResponse<WebChatDeploymentEntityListing>> future = SettableFuture.create(); final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors(); pcapiClient.invokeAsync(request, new TypeReference<WebChatDeploymentEntityListing>() {}, new AsyncApiCallback<ApiResponse<WebChatDeploymentEntityListing>>() { @Override public void onCompleted(ApiResponse<WebChatDeploymentEntityListing> response) { notifySuccess(future, callback, response); } @Override public void onFailed(Throwable exception) { if (exception instanceof ApiException) { @SuppressWarnings("unchecked") ApiResponse<WebChatDeploymentEntityListing> response = (ApiResponse<WebChatDeploymentEntityListing>)(ApiResponse<?>)exception; notifySuccess(future, callback, response); } if (shouldThrowErrors) { notifyFailure(future, callback, exception); } else { @SuppressWarnings("unchecked") ApiResponse<WebChatDeploymentEntityListing> response = (ApiResponse<WebChatDeploymentEntityListing>)(ApiResponse<?>)(new ApiException(exception)); notifySuccess(future, callback, response); } } }); return future; } catch (Throwable exception) { return Futures.immediateFailedFuture(exception); } } /** * Get WebChat deployment settings * * @param request the request object * @param callback the action to perform when the request is completed * @return the future indication when the request has completed */ public Future<WebChatSettings> getWebchatSettingsAsync(GetWebchatSettingsRequest request, final AsyncApiCallback<WebChatSettings> callback) { try { final SettableFuture<WebChatSettings> future = SettableFuture.create(); final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors(); pcapiClient.invokeAsync(request.withHttpInfo(), new TypeReference<WebChatSettings>() {}, new AsyncApiCallback<ApiResponse<WebChatSettings>>() { @Override public void onCompleted(ApiResponse<WebChatSettings> response) { notifySuccess(future, callback, response.getBody()); } @Override public void onFailed(Throwable exception) { if (shouldThrowErrors) { notifyFailure(future, callback, exception); } else { notifySuccess(future, callback, null); } } }); return future; } catch (Throwable exception) { return Futures.immediateFailedFuture(exception); } } /** * Get WebChat deployment settings * * @param request the request object * @param callback the action to perform when the request is completed * @return the future indication when the request has completed */ public Future<ApiResponse<WebChatSettings>> getWebchatSettingsAsync(ApiRequest<Void> request, final AsyncApiCallback<ApiResponse<WebChatSettings>> callback) { try { final SettableFuture<ApiResponse<WebChatSettings>> future = SettableFuture.create(); final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors(); pcapiClient.invokeAsync(request, new TypeReference<WebChatSettings>() {}, new AsyncApiCallback<ApiResponse<WebChatSettings>>() { @Override public void onCompleted(ApiResponse<WebChatSettings> response) { notifySuccess(future, callback, response); } @Override public void onFailed(Throwable exception) { if (exception instanceof ApiException) { @SuppressWarnings("unchecked") ApiResponse<WebChatSettings> response = (ApiResponse<WebChatSettings>)(ApiResponse<?>)exception; notifySuccess(future, callback, response); } if (shouldThrowErrors) { notifyFailure(future, callback, exception); } else { @SuppressWarnings("unchecked") ApiResponse<WebChatSettings> response = (ApiResponse<WebChatSettings>)(ApiResponse<?>)(new ApiException(exception)); notifySuccess(future, callback, response); } } }); return future; } catch (Throwable exception) { return Futures.immediateFailedFuture(exception); } } /** * Create WebChat deployment * * @param request the request object * @param callback the action to perform when the request is completed * @return the future indication when the request has completed */ public Future<WebChatDeployment> postWebchatDeploymentsAsync(PostWebchatDeploymentsRequest request, final AsyncApiCallback<WebChatDeployment> callback) { try { final SettableFuture<WebChatDeployment> future = SettableFuture.create(); final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors(); pcapiClient.invokeAsync(request.withHttpInfo(), new TypeReference<WebChatDeployment>() {}, new AsyncApiCallback<ApiResponse<WebChatDeployment>>() { @Override public void onCompleted(ApiResponse<WebChatDeployment> response) { notifySuccess(future, callback, response.getBody()); } @Override public void onFailed(Throwable exception) { if (shouldThrowErrors) { notifyFailure(future, callback, exception); } else { notifySuccess(future, callback, null); } } }); return future; } catch (Throwable exception) { return Futures.immediateFailedFuture(exception); } } /** * Create WebChat deployment * * @param request the request object * @param callback the action to perform when the request is completed * @return the future indication when the request has completed */ public Future<ApiResponse<WebChatDeployment>> postWebchatDeploymentsAsync(ApiRequest<WebChatDeployment> request, final AsyncApiCallback<ApiResponse<WebChatDeployment>> callback) { try { final SettableFuture<ApiResponse<WebChatDeployment>> future = SettableFuture.create(); final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors(); pcapiClient.invokeAsync(request, new TypeReference<WebChatDeployment>() {}, new AsyncApiCallback<ApiResponse<WebChatDeployment>>() { @Override public void onCompleted(ApiResponse<WebChatDeployment> response) { notifySuccess(future, callback, response); } @Override public void onFailed(Throwable exception) { if (exception instanceof ApiException) { @SuppressWarnings("unchecked") ApiResponse<WebChatDeployment> response = (ApiResponse<WebChatDeployment>)(ApiResponse<?>)exception; notifySuccess(future, callback, response); } if (shouldThrowErrors) { notifyFailure(future, callback, exception); } else { @SuppressWarnings("unchecked") ApiResponse<WebChatDeployment> response = (ApiResponse<WebChatDeployment>)(ApiResponse<?>)(new ApiException(exception)); notifySuccess(future, callback, response); } } }); return future; } catch (Throwable exception) { return Futures.immediateFailedFuture(exception); } } /** * Update a WebChat deployment * * @param request the request object * @param callback the action to perform when the request is completed * @return the future indication when the request has completed */ public Future<WebChatDeployment> putWebchatDeploymentAsync(PutWebchatDeploymentRequest request, final AsyncApiCallback<WebChatDeployment> callback) { try { final SettableFuture<WebChatDeployment> future = SettableFuture.create(); final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors(); pcapiClient.invokeAsync(request.withHttpInfo(), new TypeReference<WebChatDeployment>() {}, new AsyncApiCallback<ApiResponse<WebChatDeployment>>() { @Override public void onCompleted(ApiResponse<WebChatDeployment> response) { notifySuccess(future, callback, response.getBody()); } @Override public void onFailed(Throwable exception) { if (shouldThrowErrors) { notifyFailure(future, callback, exception); } else { notifySuccess(future, callback, null); } } }); return future; } catch (Throwable exception) { return Futures.immediateFailedFuture(exception); } } /** * Update a WebChat deployment * * @param request the request object * @param callback the action to perform when the request is completed * @return the future indication when the request has completed */ public Future<ApiResponse<WebChatDeployment>> putWebchatDeploymentAsync(ApiRequest<WebChatDeployment> request, final AsyncApiCallback<ApiResponse<WebChatDeployment>> callback) { try { final SettableFuture<ApiResponse<WebChatDeployment>> future = SettableFuture.create(); final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors(); pcapiClient.invokeAsync(request, new TypeReference<WebChatDeployment>() {}, new AsyncApiCallback<ApiResponse<WebChatDeployment>>() { @Override public void onCompleted(ApiResponse<WebChatDeployment> response) { notifySuccess(future, callback, response); } @Override public void onFailed(Throwable exception) { if (exception instanceof ApiException) { @SuppressWarnings("unchecked") ApiResponse<WebChatDeployment> response = (ApiResponse<WebChatDeployment>)(ApiResponse<?>)exception; notifySuccess(future, callback, response); } if (shouldThrowErrors) { notifyFailure(future, callback, exception); } else { @SuppressWarnings("unchecked") ApiResponse<WebChatDeployment> response = (ApiResponse<WebChatDeployment>)(ApiResponse<?>)(new ApiException(exception)); notifySuccess(future, callback, response); } } }); return future; } catch (Throwable exception) { return Futures.immediateFailedFuture(exception); } } /** * Update WebChat deployment settings * * @param request the request object * @param callback the action to perform when the request is completed * @return the future indication when the request has completed */ public Future<WebChatSettings> putWebchatSettingsAsync(PutWebchatSettingsRequest request, final AsyncApiCallback<WebChatSettings> callback) { try { final SettableFuture<WebChatSettings> future = SettableFuture.create(); final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors(); pcapiClient.invokeAsync(request.withHttpInfo(), new TypeReference<WebChatSettings>() {}, new AsyncApiCallback<ApiResponse<WebChatSettings>>() { @Override public void onCompleted(ApiResponse<WebChatSettings> response) { notifySuccess(future, callback, response.getBody()); } @Override public void onFailed(Throwable exception) { if (shouldThrowErrors) { notifyFailure(future, callback, exception); } else { notifySuccess(future, callback, null); } } }); return future; } catch (Throwable exception) { return Futures.immediateFailedFuture(exception); } } /** * Update WebChat deployment settings * * @param request the request object * @param callback the action to perform when the request is completed * @return the future indication when the request has completed */ public Future<ApiResponse<WebChatSettings>> putWebchatSettingsAsync(ApiRequest<WebChatSettings> request, final AsyncApiCallback<ApiResponse<WebChatSettings>> callback) { try { final SettableFuture<ApiResponse<WebChatSettings>> future = SettableFuture.create(); final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors(); pcapiClient.invokeAsync(request, new TypeReference<WebChatSettings>() {}, new AsyncApiCallback<ApiResponse<WebChatSettings>>() { @Override public void onCompleted(ApiResponse<WebChatSettings> response) { notifySuccess(future, callback, response); } @Override public void onFailed(Throwable exception) { if (exception instanceof ApiException) { @SuppressWarnings("unchecked") ApiResponse<WebChatSettings> response = (ApiResponse<WebChatSettings>)(ApiResponse<?>)exception; notifySuccess(future, callback, response); } if (shouldThrowErrors) { notifyFailure(future, callback, exception); } else { @SuppressWarnings("unchecked") ApiResponse<WebChatSettings> response = (ApiResponse<WebChatSettings>)(ApiResponse<?>)(new ApiException(exception)); notifySuccess(future, callback, response); } } }); return future; } catch (Throwable exception) { return Futures.immediateFailedFuture(exception); } } private <T> void notifySuccess(SettableFuture<T> future, AsyncApiCallback<T> callback, T result) { if (callback != null) { try { callback.onCompleted(result); future.set(result); } catch (Throwable exception) { future.setException(exception); } } else { future.set(result); } } private <T> void notifyFailure(SettableFuture<T> future, AsyncApiCallback<T> callback, Throwable exception) { if (callback != null) { try { callback.onFailed(exception); future.setException(exception); } catch (Throwable callbackException) { future.setException(callbackException); } } else { future.setException(exception); } } }
3e0a2bc8f974249840de585e775ab108ca61b918
2,651
java
Java
src/main/java/org/openapitools/client/model/AuthenticateAuthenticateV2ResponseMPayload.java
eZmaxinc/eZmax-SDK-android
4a0134c2e5870fe5b49c74e61770ec66e00f93ab
[ "MIT" ]
1
2021-03-30T00:51:33.000Z
2021-03-30T00:51:33.000Z
src/main/java/org/openapitools/client/model/AuthenticateAuthenticateV2ResponseMPayload.java
eZmaxinc/eZmax-SDK-android
4a0134c2e5870fe5b49c74e61770ec66e00f93ab
[ "MIT" ]
null
null
null
src/main/java/org/openapitools/client/model/AuthenticateAuthenticateV2ResponseMPayload.java
eZmaxinc/eZmax-SDK-android
4a0134c2e5870fe5b49c74e61770ec66e00f93ab
[ "MIT" ]
1
2021-03-30T00:51:38.000Z
2021-03-30T00:51:38.000Z
31.595238
199
0.712509
4,310
/** * eZmax API Definition * This API expose all the functionnalities for the eZmax and eZsign applications. * * The version of the OpenAPI document: 1.1.3 * Contact: nnheo@example.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.client.model; import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; /** * Payload for the /2/module/authenticate/authenticate API Request **/ @ApiModel(description = "Payload for the /2/module/authenticate/authenticate API Request") public class AuthenticateAuthenticateV2ResponseMPayload { @SerializedName("sAuthorization") private String sAuthorization = null; @SerializedName("sSecret") private String sSecret = null; /** * The Authorization key **/ @ApiModelProperty(required = true, value = "The Authorization key") public String getSAuthorization() { return sAuthorization; } public void setSAuthorization(String sAuthorization) { this.sAuthorization = sAuthorization; } /** * The secret key **/ @ApiModelProperty(required = true, value = "The secret key") public String getSSecret() { return sSecret; } public void setSSecret(String sSecret) { this.sSecret = sSecret; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AuthenticateAuthenticateV2ResponseMPayload authenticateAuthenticateV2ResponseMPayload = (AuthenticateAuthenticateV2ResponseMPayload) o; return (this.sAuthorization == null ? authenticateAuthenticateV2ResponseMPayload.sAuthorization == null : this.sAuthorization.equals(authenticateAuthenticateV2ResponseMPayload.sAuthorization)) && (this.sSecret == null ? authenticateAuthenticateV2ResponseMPayload.sSecret == null : this.sSecret.equals(authenticateAuthenticateV2ResponseMPayload.sSecret)); } @Override public int hashCode() { int result = 17; result = 31 * result + (this.sAuthorization == null ? 0: this.sAuthorization.hashCode()); result = 31 * result + (this.sSecret == null ? 0: this.sSecret.hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AuthenticateAuthenticateV2ResponseMPayload {\n"); sb.append(" sAuthorization: ").append(sAuthorization).append("\n"); sb.append(" sSecret: ").append(sSecret).append("\n"); sb.append("}\n"); return sb.toString(); } }
3e0a2be8126b142571cba03b0aae3757255ebf66
1,517
java
Java
src/main/java/outofmemory/toparquet/lib/domain/ConversionTasks.java
brentcodes/toparquet
eab909b540c7dbe900e8578719ff4821bf06c172
[ "Apache-2.0" ]
null
null
null
src/main/java/outofmemory/toparquet/lib/domain/ConversionTasks.java
brentcodes/toparquet
eab909b540c7dbe900e8578719ff4821bf06c172
[ "Apache-2.0" ]
null
null
null
src/main/java/outofmemory/toparquet/lib/domain/ConversionTasks.java
brentcodes/toparquet
eab909b540c7dbe900e8578719ff4821bf06c172
[ "Apache-2.0" ]
null
null
null
34.477273
144
0.701384
4,311
/* Copyright 2021 brentcodes 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 outofmemory.toparquet.lib.domain; import outofmemory.toparquet.lib.structure.TaskQueue; import java.util.SortedMap; import java.util.TreeMap; public class ConversionTasks { private SortedMap<ConversionTask.InputType, TaskQueue<ConversionTask>> tasks = new TreeMap<>((inputType, queue) -> inputType.getPriority()); public synchronized TaskQueue<ConversionTask> getQueue(ConversionTask.InputType inputType) { return tasks.computeIfAbsent(inputType, key -> new TaskQueue<>()); } public synchronized int size() { return tasks.values().stream().mapToInt(queue -> queue.size()).sum(); } static final TaskQueue<ConversionTask> EMPTY = null; public synchronized TaskQueue<ConversionTask> nextQueue() { for (TaskQueue<ConversionTask> q : tasks.values()) { if (q.size() > 0) { return q; } } return EMPTY; } }
3e0a2c5c95fa6231c8f107c5da549f66674e4749
2,718
java
Java
hazelcast/src/main/java/com/hazelcast/executor/impl/RunnableAdapter.java
ldziedziul-gh-tests/hazelcast
3a7382ac8164bc17836fc9b1f852b2667e7bef96
[ "ECL-2.0", "Apache-2.0" ]
4,283
2015-01-02T03:56:10.000Z
2022-03-29T23:07:45.000Z
hazelcast/src/main/java/com/hazelcast/executor/impl/RunnableAdapter.java
ldziedziul-gh-tests/hazelcast
3a7382ac8164bc17836fc9b1f852b2667e7bef96
[ "ECL-2.0", "Apache-2.0" ]
14,014
2015-01-01T04:29:38.000Z
2022-03-31T21:47:55.000Z
hazelcast/src/main/java/com/hazelcast/executor/impl/RunnableAdapter.java
ldziedziul-gh-tests/hazelcast
3a7382ac8164bc17836fc9b1f852b2667e7bef96
[ "ECL-2.0", "Apache-2.0" ]
1,608
2015-01-04T09:57:08.000Z
2022-03-31T12:05:26.000Z
26.910891
89
0.691685
4,312
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.executor.impl; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.HazelcastInstanceAware; import com.hazelcast.partition.PartitionAware; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.IdentifiedDataSerializable; import java.io.IOException; import java.util.concurrent.Callable; /** * An adapter that adapts a {@link Runnable} to become a {@link Callable}. * * @param <V> */ public final class RunnableAdapter<V> implements IdentifiedDataSerializable, Callable<V>, HazelcastInstanceAware, PartitionAware { private Runnable task; public RunnableAdapter() { } public RunnableAdapter(Runnable task) { this.task = task; } public Runnable getRunnable() { return task; } public void setRunnable(Runnable runnable) { task = runnable; } @Override public V call() { task.run(); return null; } @Override public Object getPartitionKey() { if (task instanceof PartitionAware) { return ((PartitionAware) task).getPartitionKey(); } return null; } @Override public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { if (task instanceof HazelcastInstanceAware) { HazelcastInstanceAware instanceAwareTask = (HazelcastInstanceAware) task; instanceAwareTask.setHazelcastInstance(hazelcastInstance); } } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeObject(task); } @Override public void readData(ObjectDataInput in) throws IOException { task = in.readObject(); } @Override public int getFactoryId() { return ExecutorDataSerializerHook.F_ID; } @Override public int getClassId() { return ExecutorDataSerializerHook.RUNNABLE_ADAPTER; } @Override public String toString() { return "RunnableAdapter" + "{task=" + task + '}'; } }
3e0a2c9213723da1d79c5de45efb4ecf6d91b9b1
969
java
Java
mall-coupon/src/main/java/com/touch/air/mall/coupon/entity/HomeAdvEntity.java
dongdong1018645785/touch-air-mall
cc75e5e75690bda9d20d23c192c0576cbafe17f0
[ "Apache-2.0" ]
1
2021-07-16T02:15:44.000Z
2021-07-16T02:15:44.000Z
mall-coupon/src/main/java/com/touch/air/mall/coupon/entity/HomeAdvEntity.java
dongdong1018645785/touch-air-mall
cc75e5e75690bda9d20d23c192c0576cbafe17f0
[ "Apache-2.0" ]
null
null
null
mall-coupon/src/main/java/com/touch/air/mall/coupon/entity/HomeAdvEntity.java
dongdong1018645785/touch-air-mall
cc75e5e75690bda9d20d23c192c0576cbafe17f0
[ "Apache-2.0" ]
null
null
null
13.273973
53
0.635707
4,313
package com.touch.air.mall.coupon.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * 首页轮播广告 * * @author bin.wang * @email lyhxr@example.com * @date 2020-12-04 13:47:36 */ @Data @TableName("sms_home_adv") public class HomeAdvEntity implements Serializable { private static final long serialVersionUID = 1L; /** * id */ @TableId private Long id; /** * 名字 */ private String name; /** * 图片地址 */ private String pic; /** * 开始时间 */ private Date startTime; /** * 结束时间 */ private Date endTime; /** * 状态 */ private Integer status; /** * 点击数 */ private Integer clickCount; /** * 广告详情连接地址 */ private String url; /** * 备注 */ private String note; /** * 排序 */ private Integer sort; /** * 发布者 */ private Long publisherId; /** * 审核者 */ private Long authId; }
3e0a2ce32cdb14781668112c59b5c688f5b67bfc
3,368
java
Java
src/daos/OrdenadoresDAOImpl.java
josedvm95/OnlineStore
4a4d3d2582bb663dbc94f9df5f7d7deaed720705
[ "BSD-3-Clause" ]
null
null
null
src/daos/OrdenadoresDAOImpl.java
josedvm95/OnlineStore
4a4d3d2582bb663dbc94f9df5f7d7deaed720705
[ "BSD-3-Clause" ]
null
null
null
src/daos/OrdenadoresDAOImpl.java
josedvm95/OnlineStore
4a4d3d2582bb663dbc94f9df5f7d7deaed720705
[ "BSD-3-Clause" ]
null
null
null
32.699029
161
0.774644
4,314
package daos; import java.util.HashMap; import java.util.List; import javax.sql.DataSource; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import constantes.ConstantesSQL; import mappers.OrdenadoresMapper; import modelo.Ordenador; public class OrdenadoresDAOImpl implements OrdenadoresDAO { private DataSource elDataSource; private SimpleJdbcInsert simpleInsert; private JdbcTemplate jdbcTemplate; public DataSource getElDataSource() { return elDataSource; } public void setElDataSource(DataSource elDataSource) { this.elDataSource = elDataSource; simpleInsert = new SimpleJdbcInsert(elDataSource); simpleInsert.setTableName("tabla_ordenadores"); simpleInsert.usingGeneratedKeyColumns("id"); jdbcTemplate = new JdbcTemplate(elDataSource); } @Override public int registrarOrdenador(Ordenador o) { HashMap<String, Object> valores = new HashMap<String, Object>(); valores.put("marca", o.getMarca()); valores.put("modelo", o.getModelo()); valores.put("procesador", o.getProcesador()); valores.put("grafica", o.getGrafica()); valores.put("pulgadas", o.getPulgadas()); valores.put("precio", o.getPrecio()); valores.put("stock", o.getStock()); int idGenerado = simpleInsert.executeAndReturnKey(valores).intValue(); return idGenerado; } @Override public List<Ordenador> obtenerOrdenadores() { String sql = ConstantesSQL.SQL_SELECCION_ORDENADORES; List<Ordenador> ordenadores = (List<Ordenador>) jdbcTemplate.query(sql, new BeanPropertyRowMapper(Ordenador.class)); return ordenadores; } @Override public void modificarOrdenador(Ordenador o) { String sql = ConstantesSQL.SQL_EDICION_ORDENADORES; jdbcTemplate.update(sql, o.getMarca(), o.getModelo(), o.getProcesador(), o.getGrafica(), o.getPulgadas(), o.getPrecio(), o.getStock(), o.getId()); } @Override public void borrarOrdenador(int id) { String sql = ConstantesSQL.SQL_BORRADO_ORDENADORES; jdbcTemplate.update(sql, id); } @Override public Ordenador obtenerOrdenadorPorId(int id) { String valores[] = {String.valueOf(id)}; Ordenador ordenador = (Ordenador) jdbcTemplate.queryForObject(ConstantesSQL.SQL_OBTENER_ORDENADOR_POR_ID, valores, new BeanPropertyRowMapper(Ordenador.class)); return ordenador; } @Override public List<Ordenador> obtenerOrdenadores(int comienzo, int cuantos) { Integer[] valores = {comienzo, cuantos}; List<Ordenador> ordenadores = jdbcTemplate.query(ConstantesSQL.SQL_SELECCION_ORDENADORES_INICIO_CUANTOS, valores, new BeanPropertyRowMapper(Ordenador.class)); return ordenadores; } @Override public int obtenerTotalOrdenadores() { int total = jdbcTemplate.queryForInt(ConstantesSQL.SQL_TOTAL_ORDENADORES); return total; } @Override public int obtenerTotalOrdenadores(String busqueda) { int total = jdbcTemplate.queryForInt(ConstantesSQL.SQL_TOTAL_ORDENADORES_BUSQUEDA, "%" + busqueda + "%"); return total; } @Override public List<Ordenador> obtenerOrdenadores(int comienzo, int cuantos, String busqueda) { Object[] valores = {"%" + busqueda + "%", comienzo, cuantos}; List<Ordenador> ordenadores = jdbcTemplate.query(ConstantesSQL.SQL_SELECCION_ORDENADORES_INICIO_CUANTOS_BUSQUEDA, valores, new OrdenadoresMapper()); return ordenadores; } }
3e0a2ce52fadf8e24f72363ffbb5375722fb769d
6,827
java
Java
tony-spring-boot-starter-common/src/main/java/com/tony/common/utils/file/FileUploadUtils.java
xuzhijvn/spring-boot-tony-starters
9020de94097fb1a0176826381d1a5652364c7a42
[ "MIT" ]
168
2021-12-06T00:14:14.000Z
2022-03-01T07:25:02.000Z
tony-spring-boot-starter-common/src/main/java/com/tony/common/utils/file/FileUploadUtils.java
xuzhijvn/spring-boot-tony-starters
9020de94097fb1a0176826381d1a5652364c7a42
[ "MIT" ]
null
null
null
tony-spring-boot-starter-common/src/main/java/com/tony/common/utils/file/FileUploadUtils.java
xuzhijvn/spring-boot-tony-starters
9020de94097fb1a0176826381d1a5652364c7a42
[ "MIT" ]
50
2021-12-06T00:14:56.000Z
2021-12-08T21:58:45.000Z
33.965174
111
0.64655
4,315
package com.tony.common.utils.file; import com.tony.common.CommonConfig; import com.tony.common.constant.Constants; import com.tony.common.exception.file.FileNameLengthLimitExceededException; import com.tony.common.exception.file.FileSizeLimitExceededException; import com.tony.common.exception.file.InvalidExtensionException; import com.tony.common.utils.DateUtils; import com.tony.common.utils.StringUtils; import com.tony.common.utils.uuid.IdUtils; import org.apache.commons.io.FilenameUtils; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; /** * 文件上传工具类 * * @author tony */ public class FileUploadUtils { /** * 默认大小 50M */ public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024; /** * 默认的文件名最大长度 100 */ public static final int DEFAULT_FILE_NAME_LENGTH = 100; /** * 默认上传的地址 */ private static String defaultBaseDir = CommonConfig.getProfile(); public static void setDefaultBaseDir(String defaultBaseDir) { FileUploadUtils.defaultBaseDir = defaultBaseDir; } public static String getDefaultBaseDir() { return defaultBaseDir; } /** * 以默认配置进行文件上传 * * @param file 上传的文件 * @return 文件名称 * @throws Exception */ public static final String upload(MultipartFile file) throws IOException { try { return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); } catch (Exception e) { throw new IOException(e.getMessage(), e); } } /** * 根据文件路径上传 * * @param baseDir 相对应用的基目录 * @param file 上传的文件 * @return 文件名称 * @throws IOException */ public static final String upload(String baseDir, MultipartFile file) throws IOException { try { return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); } catch (Exception e) { throw new IOException(e.getMessage(), e); } } /** * 文件上传 * * @param baseDir 相对应用的基目录 * @param file 上传的文件 * @param allowedExtension 上传文件类型 * @return 返回上传成功的文件名 * @throws FileSizeLimitExceededException 如果超出最大大小 * @throws FileNameLengthLimitExceededException 文件名太长 * @throws IOException 比如读写文件出错时 * @throws InvalidExtensionException 文件校验异常 */ public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension) throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException, InvalidExtensionException { int fileNamelength = file.getOriginalFilename().length(); if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) { throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH); } assertAllowed(file, allowedExtension); String fileName = extractFilename(file); File desc = getAbsoluteFile(baseDir, fileName); file.transferTo(desc); String pathFileName = getPathFileName(baseDir, fileName); return pathFileName; } /** * 编码文件名 */ public static final String extractFilename(MultipartFile file) { String fileName = file.getOriginalFilename(); String extension = getExtension(file); fileName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension; return fileName; } public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException { File desc = new File(uploadDir + File.separator + fileName); if (!desc.exists()) { if (!desc.getParentFile().exists()) { desc.getParentFile().mkdirs(); } } return desc; } public static final String getPathFileName(String uploadDir, String fileName) throws IOException { int dirLastIndex = CommonConfig.getProfile().length() + 1; String currentDir = StringUtils.substring(uploadDir, dirLastIndex); String pathFileName = Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName; return pathFileName; } /** * 文件大小校验 * * @param file 上传的文件 * @return * @throws FileSizeLimitExceededException 如果超出最大大小 * @throws InvalidExtensionException */ public static final void assertAllowed(MultipartFile file, String[] allowedExtension) throws FileSizeLimitExceededException, InvalidExtensionException { long size = file.getSize(); if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE) { throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024); } String fileName = file.getOriginalFilename(); String extension = getExtension(file); if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) { if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) { throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension, fileName); } else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) { throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension, fileName); } else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) { throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension, fileName); } else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION) { throw new InvalidExtensionException.InvalidVideoExtensionException(allowedExtension, extension, fileName); } else { throw new InvalidExtensionException(allowedExtension, extension, fileName); } } } /** * 判断MIME类型是否是允许的MIME类型 * * @param extension * @param allowedExtension * @return */ public static final boolean isAllowedExtension(String extension, String[] allowedExtension) { for (String str : allowedExtension) { if (str.equalsIgnoreCase(extension)) { return true; } } return false; } /** * 获取文件名的后缀 * * @param file 表单文件 * @return 后缀名 */ public static final String getExtension(MultipartFile file) { String extension = FilenameUtils.getExtension(file.getOriginalFilename()); if (StringUtils.isEmpty(extension)) { extension = MimeTypeUtils.getExtension(file.getContentType()); } return extension; } }
3e0a2d46cc0e4db8cec17797aa9faf8e8b0e1e49
519
java
Java
src/test/java/io/github/rerorero/kafka/connect/transform/encrypt/config/Base64StringValidatorTest.java
rerorero/kafka-connect-transform-encrypt
3545042c8897a402852a21efa264566de4cba8b0
[ "Apache-2.0" ]
2
2021-06-28T10:00:05.000Z
2021-12-05T11:00:33.000Z
src/test/java/io/github/rerorero/kafka/connect/transform/encrypt/config/Base64StringValidatorTest.java
rerorero/kafka-connect-transform-encrypt
3545042c8897a402852a21efa264566de4cba8b0
[ "Apache-2.0" ]
11
2021-05-21T13:13:22.000Z
2021-06-28T11:31:07.000Z
src/test/java/io/github/rerorero/kafka/connect/transform/encrypt/config/Base64StringValidatorTest.java
rerorero/kafka-connect-transform-encrypt
3545042c8897a402852a21efa264566de4cba8b0
[ "Apache-2.0" ]
null
null
null
32.4375
77
0.728324
4,316
package io.github.rerorero.kafka.connect.transform.encrypt.config; import org.apache.kafka.common.config.ConfigException; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class Base64StringValidatorTest { @Test public void testBase64StringValidator() { Base64StringValidator v = Base64StringValidator.singleton; assertDoesNotThrow(() -> v.ensureValid("a", "dGVzdA==")); assertThrows(ConfigException.class, () -> v.ensureValid("b", "ねむい")); } }
3e0a2eaec18cf35ef7f60aed1f0937645a398e69
1,427
java
Java
prost-loader/src/test/java/loader/utilities/HdfsUtilities.java
tf-dbis-uni-freiburg/PRoST
564660ef57c9e8e77bc26438b08f2b00f2604ebc
[ "MIT" ]
14
2017-12-29T17:00:54.000Z
2021-12-15T21:37:25.000Z
prost-loader/src/test/java/loader/utilities/HdfsUtilities.java
tf-dbis-uni-freiburg/PRoST
564660ef57c9e8e77bc26438b08f2b00f2604ebc
[ "MIT" ]
38
2018-01-15T01:35:54.000Z
2021-12-09T21:39:14.000Z
prost-loader/src/test/java/loader/utilities/HdfsUtilities.java
tf-dbis-uni-freiburg/PRoST
564660ef57c9e8e77bc26438b08f2b00f2604ebc
[ "MIT" ]
5
2017-12-03T14:06:27.000Z
2020-10-21T13:09:56.000Z
33.97619
135
0.735109
4,317
package loader.utilities; import java.io.IOException; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; /** * Utilities for manipulation of files within the HDFS (only for test scope) * * @author Victor Anthony Arrascue Ayala */ public class HdfsUtilities { /** * This method puts the file in an HDFS folder, so that this can be used for * applications working on top of Hadoop. In case the HDFS folder passed as * argument exists, this will be deleted. * */ public static void putFileToHDFS(final String localPath, final String hdfsFolderPath, final JavaSparkContext jsc) throws IOException { // TODO: improve. Using the Hadoop API didn't work (see commented code). // fs.copyFromLocalFile(new // Path(triplesMoreThan3Resources.getAbsolutePath()), new // Path("/triplesMoreThanThreeElements")); // FileUtil.copy(fs, new // Path(triplesMoreThan3Resources.getAbsolutePath()), fs, new // Path("/triplesMoreThanThreeElements"), false, // sc.hadoopConfiguration()); final FileSystem fs = FileSystem.get(jsc.hadoopConfiguration()); if (fs.exists(new Path(hdfsFolderPath))) { fs.delete(new Path(hdfsFolderPath), true); } final JavaRDD<String> lines = jsc.textFile(localPath); lines.map(x -> x.replace("[", "").replace("]", "")).saveAsTextFile(hdfsFolderPath); } }
3e0a2f2d6f43bc4fa2087cf7a404ef1d566cccb1
2,020
java
Java
componentservice/src/main/java/com/nhzw/rx/RxTransformer.java
xinayida/homabuy
fa0f27c37e0bbfd951f42bbbe97c73d7d0181674
[ "Apache-2.0" ]
3
2018-01-14T13:37:12.000Z
2018-07-12T12:50:51.000Z
componentservice/src/main/java/com/nhzw/rx/RxTransformer.java
xinayida/homabuy
fa0f27c37e0bbfd951f42bbbe97c73d7d0181674
[ "Apache-2.0" ]
null
null
null
componentservice/src/main/java/com/nhzw/rx/RxTransformer.java
xinayida/homabuy
fa0f27c37e0bbfd951f42bbbe97c73d7d0181674
[ "Apache-2.0" ]
null
null
null
32.580645
92
0.54703
4,318
package com.nhzw.rx; import org.json.JSONObject; import io.reactivex.ObservableTransformer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; /** * 错误预处理+切换线程 * Created by ww on 2017/10/27. */ public class RxTransformer<T> { /** * 切换线程、处理异常以及提取data */ public static <T> ObservableTransformer<Response<T>, T> trans() { return responseObservable -> responseObservable.map(new Function<Response<T>, T>() { @Override public T apply(@NonNull Response<T> tResponse) throws Exception { if (!tResponse.success()) { //Log.d("Stefan", "response failed: " + tResponse); if ("auth.error".equalsIgnoreCase(tResponse.code)) { throw new AuthException(tResponse.code, tResponse.msg); } throw new Exception(tResponse.msg); } if (tResponse.data == null) { tResponse.data = (T) new JSONObject(); } return tResponse.data; } }) // .onErrorResumeNext(throwable -> { // return Observable.error(throwable); // }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } /** * 切换线程和处理异常 */ public static <T> ObservableTransformer<T, T> switchSchedulers() { return observable -> observable.map(new Function<T, T>() { @Override public T apply(@NonNull T t) throws Exception { if (t instanceof Response && !((Response) t).success()) { throw new Exception(((Response) t).msg); } return t; } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } }