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
3e0cc84386d73fb41af0618880f10b28d937be70
2,988
java
Java
user-service/src/main/java/kr/wallaby/springcloud/userservice/security/AuthenticationFilter.java
wallaby83/spring-cloud
2c4961ac62c7b677970ce11e42ed70a43b4b3e68
[ "MIT" ]
null
null
null
user-service/src/main/java/kr/wallaby/springcloud/userservice/security/AuthenticationFilter.java
wallaby83/spring-cloud
2c4961ac62c7b677970ce11e42ed70a43b4b3e68
[ "MIT" ]
null
null
null
user-service/src/main/java/kr/wallaby/springcloud/userservice/security/AuthenticationFilter.java
wallaby83/spring-cloud
2c4961ac62c7b677970ce11e42ed70a43b4b3e68
[ "MIT" ]
null
null
null
45.272727
139
0.718876
5,425
package kr.wallaby.springcloud.userservice.security; import com.fasterxml.jackson.databind.ObjectMapper; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import kr.wallaby.springcloud.userservice.dto.UserDto; import kr.wallaby.springcloud.userservice.service.UserService; import kr.wallaby.springcloud.userservice.vo.RequestLogin; import lombok.RequiredArgsConstructor; import org.springframework.core.env.Environment; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.User; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Date; @RequiredArgsConstructor public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter { private final AuthenticationManager authenticationManager; private final UserService userService; private final Environment env; @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { try { RequestLogin credential = new ObjectMapper().readValue(request.getInputStream(), RequestLogin.class); return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken( credential.getEmail(), credential.getPassword(), new ArrayList<>() )); } catch (IOException e) { throw new RuntimeException(e); } } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { String userName = ((User)authResult.getPrincipal()).getUsername(); UserDto userDetail = this.userService.getUserDetailsByEmail(userName); String token = Jwts.builder() .setSubject(userDetail.getUserId()) .setExpiration(new Date(System.currentTimeMillis() + Long.parseLong(env.getProperty("token.expiration_time", "86400000")))) .signWith(SignatureAlgorithm.HS512, env.getProperty("token.secret")) .compact(); response.setHeader("token", token); response.setHeader("userId", userDetail.getUserId()); } }
3e0cc9b8cbe4c49a3d6c56c800024ba2aa8489d4
2,933
java
Java
src/main/java/org/primefaces/component/bubblechart/BubbleChartRenderer.java
sergi-mm/primefaces
3e194101fa1171000a9839f26533f44d3f2a9d79
[ "Apache-2.0" ]
null
null
null
src/main/java/org/primefaces/component/bubblechart/BubbleChartRenderer.java
sergi-mm/primefaces
3e194101fa1171000a9839f26533f44d3f2a9d79
[ "Apache-2.0" ]
null
null
null
src/main/java/org/primefaces/component/bubblechart/BubbleChartRenderer.java
sergi-mm/primefaces
3e194101fa1171000a9839f26533f44d3f2a9d79
[ "Apache-2.0" ]
null
null
null
38.592105
135
0.707126
5,426
/** * Copyright 2009-2019 PrimeTek. * * 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.primefaces.component.bubblechart; import java.io.IOException; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import org.primefaces.component.charts.ChartRenderer; import org.primefaces.model.charts.bubble.BubbleChartOptions; import org.primefaces.util.WidgetBuilder; public class BubbleChartRenderer extends ChartRenderer { @Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { BubbleChart chart = (BubbleChart) component; String clientId = chart.getClientId(context); String style = chart.getStyle(); String styleClass = chart.getStyleClass(); encodeMarkup(context, clientId, style, styleClass); encodeScript(context, chart); } protected void encodeScript(FacesContext context, BubbleChart chart) throws IOException { String clientId = chart.getClientId(context); WidgetBuilder wb = getWidgetBuilder(context); wb.init("BubbleChart", chart.resolveWidgetVar(), clientId); encodeConfig(context, chart.getModel()); encodeClientBehaviors(context, chart); wb.finish(); } @Override protected void encodeOptions(FacesContext context, String type, Object options) throws IOException { ResponseWriter writer = context.getResponseWriter(); if (options == null) { return; } BubbleChartOptions bubbleOptions = (BubbleChartOptions) options; writer.write(",\"options\":{"); encodeScales(context, type, bubbleOptions.getScales(), false); encodeElements(context, bubbleOptions.getElements(), bubbleOptions.getScales() != null); encodeTitle(context, bubbleOptions.getTitle(), (bubbleOptions.getScales() != null || bubbleOptions.getElements() != null)); encodeTooltip(context, bubbleOptions.getTooltip(), (bubbleOptions.getScales() != null || bubbleOptions.getElements() != null || bubbleOptions.getTitle() != null)); encodeLegend(context, bubbleOptions.getLegend(), (bubbleOptions.getScales() != null || bubbleOptions.getElements() != null || bubbleOptions.getTitle() != null || bubbleOptions.getTooltip() != null)); writer.write("}"); } }
3e0cc9ce6703882be53bedb481d64bfce6070a2c
8,444
java
Java
src/main/java/net/centro/rtb/monitoringcenter/metrics/C3P0PooledDataSourceMetricSet.java
waleed-dawood/monitoring-center
b875d6b278fbfa7bb5007387c7f837ed26722e64
[ "Apache-2.0" ]
22
2016-11-24T01:29:42.000Z
2021-12-10T14:32:23.000Z
src/main/java/net/centro/rtb/monitoringcenter/metrics/C3P0PooledDataSourceMetricSet.java
waleed-dawood/monitoring-center
b875d6b278fbfa7bb5007387c7f837ed26722e64
[ "Apache-2.0" ]
8
2017-08-06T00:54:58.000Z
2021-04-12T18:18:37.000Z
src/main/java/net/centro/rtb/monitoringcenter/metrics/C3P0PooledDataSourceMetricSet.java
waleed-dawood/monitoring-center
b875d6b278fbfa7bb5007387c7f837ed26722e64
[ "Apache-2.0" ]
10
2016-11-18T17:10:33.000Z
2021-04-01T20:08:35.000Z
36.08547
121
0.568451
5,427
/* * Copyright 2016 Centro, Inc. * * 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 net.centro.rtb.monitoringcenter.metrics; import com.codahale.metrics.Gauge; import com.codahale.metrics.Metric; import com.codahale.metrics.MetricSet; import com.google.common.base.Preconditions; import com.mchange.v2.c3p0.ComboPooledDataSource; import com.mchange.v2.c3p0.PooledDataSource; import net.centro.rtb.monitoringcenter.util.MetricNamingUtil; import java.sql.SQLException; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class C3P0PooledDataSourceMetricSet implements MetricSet { private PooledDataSource pooledDataSource; private ComboPooledDataSource comboPooledDataSource; public C3P0PooledDataSourceMetricSet(PooledDataSource pooledDataSource) { Preconditions.checkNotNull(pooledDataSource); this.pooledDataSource = pooledDataSource; if (ComboPooledDataSource.class.isInstance(pooledDataSource)) { this.comboPooledDataSource = ComboPooledDataSource.class.cast(pooledDataSource); } } @Override public Map<String, Metric> getMetrics() { Map<String, Metric> metricsByNames = new HashMap<>(); // ----- Connections ----- String connectionsNamespace = "connections"; metricsByNames.put(MetricNamingUtil.join(connectionsNamespace, "currentCount"), new Gauge<Integer>() { @Override public Integer getValue() { try { return pooledDataSource.getNumConnectionsAllUsers(); } catch (SQLException ignore) { return -1; } } }); metricsByNames.put(MetricNamingUtil.join(connectionsNamespace, "busy"), new Gauge<Integer>() { @Override public Integer getValue() { try { return pooledDataSource.getNumBusyConnectionsAllUsers(); } catch (SQLException ignore) { return -1; } } }); metricsByNames.put(MetricNamingUtil.join(connectionsNamespace, "idle"), new Gauge<Integer>() { @Override public Integer getValue() { try { return pooledDataSource.getNumIdleConnectionsAllUsers(); } catch (SQLException ignore) { return -1; } } }); metricsByNames.put(MetricNamingUtil.join(connectionsNamespace, "unclosedOrphaned"), new Gauge<Integer>() { @Override public Integer getValue() { try { return pooledDataSource.getNumUnclosedOrphanedConnectionsAllUsers(); } catch (SQLException ignore) { return -1; } } }); metricsByNames.put(MetricNamingUtil.join(connectionsNamespace, "failedCheckouts"), new Gauge<Long>() { @Override public Long getValue() { try { return pooledDataSource.getNumFailedCheckoutsDefaultUser(); } catch (SQLException ignore) { return -1L; } } }); metricsByNames.put(MetricNamingUtil.join(connectionsNamespace, "failedCheckins"), new Gauge<Long>() { @Override public Long getValue() { try { return pooledDataSource.getNumFailedCheckinsDefaultUser(); } catch (SQLException ignore) { return -1L; } } }); metricsByNames.put(MetricNamingUtil.join(connectionsNamespace, "failedIdleTests"), new Gauge<Long>() { @Override public Long getValue() { try { return pooledDataSource.getNumFailedIdleTestsDefaultUser(); } catch (SQLException ignore) { return -1L; } } }); metricsByNames.put(MetricNamingUtil.join(connectionsNamespace, "threadsAwaitingCheckout"), new Gauge<Integer>() { @Override public Integer getValue() { try { return pooledDataSource.getNumThreadsAwaitingCheckoutDefaultUser(); } catch (SQLException ignore) { return -1; } } }); if (comboPooledDataSource != null) { metricsByNames.put(MetricNamingUtil.join(connectionsNamespace, "max"), new Gauge<Integer>() { @Override public Integer getValue() { return comboPooledDataSource.getMaxPoolSize(); } }); metricsByNames.put(MetricNamingUtil.join(connectionsNamespace, "min"), new Gauge<Integer>() { @Override public Integer getValue() { return comboPooledDataSource.getMinPoolSize(); } }); } // ----- Threads ----- String helperThreadPoolNamespace = "helperThreadPool"; metricsByNames.put(MetricNamingUtil.join(helperThreadPoolNamespace, "size"), new Gauge<Integer>() { @Override public Integer getValue() { try { return pooledDataSource.getThreadPoolSize(); } catch (SQLException ignore) { return -1; } } }); metricsByNames.put(MetricNamingUtil.join(helperThreadPoolNamespace, "busyThreads"), new Gauge<Integer>() { @Override public Integer getValue() { try { return pooledDataSource.getThreadPoolNumActiveThreads(); } catch (SQLException ignore) { return -1; } } }); metricsByNames.put(MetricNamingUtil.join(helperThreadPoolNamespace, "idleThreads"), new Gauge<Integer>() { @Override public Integer getValue() { try { return pooledDataSource.getThreadPoolNumIdleThreads(); } catch (SQLException ignore) { return -1; } } }); metricsByNames.put(MetricNamingUtil.join(helperThreadPoolNamespace, "pendingTasks"), new Gauge<Integer>() { @Override public Integer getValue() { try { return pooledDataSource.getThreadPoolNumTasksPending(); } catch (SQLException ignore) { return -1; } } }); // ----- Statement Cache ----- String statementCacheNamespace = "statementCache"; metricsByNames.put(MetricNamingUtil.join(statementCacheNamespace, "size"), new Gauge<Integer>() { @Override public Integer getValue() { try { return pooledDataSource.getStatementCacheNumStatementsAllUsers(); } catch (SQLException ignore) { return -1; } } }); if (comboPooledDataSource != null) { metricsByNames.put(MetricNamingUtil.join(statementCacheNamespace, "maxSize"), new Gauge<Integer>() { @Override public Integer getValue() { return comboPooledDataSource.getMaxStatements(); } }); } return Collections.unmodifiableMap(metricsByNames); } }
3e0cca37401ac350e9e1bd9bf4b4ad264b00f4de
2,644
java
Java
src/main/java/com/alexcomeau/utils/ReadToken.java
alexm622/WeatherBot
cd82db37368170497abd3f2afb152f157b6e5b35
[ "MIT" ]
1
2021-03-29T20:42:37.000Z
2021-03-29T20:42:37.000Z
src/main/java/com/alexcomeau/utils/ReadToken.java
alexm622/WeatherBot
cd82db37368170497abd3f2afb152f157b6e5b35
[ "MIT" ]
1
2021-07-04T06:19:24.000Z
2021-07-04T06:19:24.000Z
src/main/java/com/alexcomeau/utils/ReadToken.java
alexm622/WeatherBot
cd82db37368170497abd3f2afb152f157b6e5b35
[ "MIT" ]
null
null
null
28.430108
78
0.541604
5,428
package com.alexcomeau.utils; import com.alexcomeau.sql.LoginDetails; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class ReadToken { public static String DiscordToken(){ String tokenPath = "/tokens/weatherbot.txt"; String token; try{ BufferedReader br = new BufferedReader(new FileReader(tokenPath)); token = br.readLine(); br.close(); } catch (IOException e) { Debug.debug(e.toString(), true); token = "0"; return token; } return token; } public static String WeatherToken(){ String tokenPath = "/tokens/openweather.txt"; String token; try{ BufferedReader br = new BufferedReader(new FileReader(tokenPath)); token = br.readLine(); br.close(); } catch (IOException e) { Debug.debug(e.toString(), true); token = "0"; return token; } return token; } public static String GeoCodingToken(){ String tokenPath = "/tokens/geocoding.txt"; String token; try{ BufferedReader br = new BufferedReader(new FileReader(tokenPath)); token = br.readLine(); br.close(); } catch (IOException e) { Debug.debug(e.toString(), true); token = "0"; return token; } return token; } public static LoginDetails getSql(){ String tokenPath = "/tokens/sql.txt"; String temp; LoginDetails logDets = new LoginDetails(); try{ BufferedReader br = new BufferedReader(new FileReader(tokenPath)); temp = br.readLine(); String[] fields = temp.split("/"); logDets.setIp(fields[0]); logDets.setUsername(fields[1]); logDets.setPassword(fields[2]); br.close(); } catch (Exception e) { logDets.setIp("127.0.0.1"); logDets.setUsername("none"); logDets.setPassword("none"); } return logDets; } public static String TomTomToken() { String tokenPath = "/tokens/tomtom.txt"; String token; try{ BufferedReader br = new BufferedReader(new FileReader(tokenPath)); token = br.readLine(); br.close(); } catch (IOException e) { Debug.debug(e.toString(), true); token = "0"; return token; } return token; } }
3e0ccc8e1e24cf559407d46a3750b52a126b9d3e
13,095
java
Java
src/test/java/org/dyn4j/collision/shapes/PolygonCapsuleTest.java
dyn4j/dyn4j
e84915a16994fab43b2eb4f9ba052d3ae1cf2947
[ "BSD-3-Clause" ]
291
2017-11-23T09:36:58.000Z
2022-03-13T19:14:01.000Z
src/test/java/org/dyn4j/collision/shapes/PolygonCapsuleTest.java
dyn4j/dyn4j
e84915a16994fab43b2eb4f9ba052d3ae1cf2947
[ "BSD-3-Clause" ]
138
2017-11-19T02:26:31.000Z
2022-01-08T02:35:47.000Z
src/test/java/org/dyn4j/collision/shapes/PolygonCapsuleTest.java
dyn4j/dyn4j
e84915a16994fab43b2eb4f9ba052d3ae1cf2947
[ "BSD-3-Clause" ]
54
2017-11-27T06:43:53.000Z
2022-03-13T13:46:05.000Z
39.206587
109
0.673692
5,429
/* * Copyright (c) 2010-2020 William Bittle http://www.dyn4j.org/ * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.dyn4j.collision.shapes; import org.dyn4j.collision.manifold.ClippingManifoldSolver; import org.dyn4j.collision.manifold.Manifold; import org.dyn4j.collision.manifold.ManifoldPoint; import org.dyn4j.collision.narrowphase.Gjk; import org.dyn4j.collision.narrowphase.Penetration; import org.dyn4j.collision.narrowphase.Separation; import org.dyn4j.geometry.Capsule; import org.dyn4j.geometry.Geometry; import org.dyn4j.geometry.Polygon; import org.dyn4j.geometry.Transform; import org.dyn4j.geometry.Vector2; import org.junit.Before; import org.junit.Test; import junit.framework.TestCase; /** * Test case for {@link Polygon} - {@link Capsule} collision detection. * @author William Bittle * @version 3.1.5 * @since 3.1.5 */ public class PolygonCapsuleTest extends AbstractNarrowphaseShapeTest { /** The test {@link Polygon} */ private Polygon polygon; /** The test {@link Capsule} */ private Capsule capsule; /** * Sets up the test. */ @Before public void setup() { this.polygon = Geometry.createUnitCirclePolygon(5, 0.5); this.capsule = new Capsule(1.0, 0.5); } /** * Tests that sat is unsupported. */ @Test public void detectSat() { Penetration p = new Penetration(); Transform t1 = new Transform(); Transform t2 = new Transform(); Vector2 n = null; // test containment TestCase.assertTrue(this.sat.detect(polygon, t1, capsule, t2, p)); TestCase.assertTrue(this.sat.detect(polygon, t1, capsule, t2)); n = p.getNormal(); TestCase.assertEquals( 0.000, n.x, 1.0e-3); TestCase.assertEquals( 1.000, n.y, 1.0e-3); TestCase.assertEquals( 0.725, p.getDepth(), 1.0e-3); // try reversing the shapes TestCase.assertTrue(this.sat.detect(capsule, t2, polygon, t1, p)); TestCase.assertTrue(this.sat.detect(capsule, t2, polygon, t1)); n = p.getNormal(); TestCase.assertEquals( 0.000, n.x, 1.0e-3); TestCase.assertEquals(-1.000, n.y, 1.0e-3); TestCase.assertEquals( 0.725, p.getDepth(), 1.0e-3); // test overlap t1.translate(-0.5, 0.0); TestCase.assertTrue(this.sat.detect(polygon, t1, capsule, t2, p)); TestCase.assertTrue(this.sat.detect(polygon, t1, capsule, t2)); n = p.getNormal(); TestCase.assertEquals( 0.809, n.x, 1.0e-3); TestCase.assertEquals( 0.587, n.y, 1.0e-3); TestCase.assertEquals( 0.452, p.getDepth(), 1.0e-3); // try reversing the shapes TestCase.assertTrue(this.sat.detect(capsule, t2, polygon, t1, p)); TestCase.assertTrue(this.sat.detect(capsule, t2, polygon, t1)); n = p.getNormal(); TestCase.assertEquals(-0.809, n.x, 1.0e-3); TestCase.assertEquals(-0.587, n.y, 1.0e-3); TestCase.assertEquals( 0.452, p.getDepth(), 1.0e-3); // test AABB overlap t2.translate(0.3, 0.4); TestCase.assertFalse(this.sat.detect(polygon, t1, capsule, t2, p)); TestCase.assertFalse(this.sat.detect(polygon, t1, capsule, t2)); // try reversing the shapes TestCase.assertFalse(this.sat.detect(capsule, t2, polygon, t1, p)); TestCase.assertFalse(this.sat.detect(capsule, t2, polygon, t1)); // test no overlap t2.translate(1.0, 0.0); TestCase.assertFalse(this.sat.detect(polygon, t1, capsule, t2, p)); TestCase.assertFalse(this.sat.detect(polygon, t1, capsule, t2)); // try reversing the shapes TestCase.assertFalse(this.sat.detect(capsule, t2, polygon, t1, p)); TestCase.assertFalse(this.sat.detect(capsule, t2, polygon, t1)); } /** * Tests {@link Gjk}. */ @Test public void detectGjk() { Penetration p = new Penetration(); Transform t1 = new Transform(); Transform t2 = new Transform(); Vector2 n = null; // test containment TestCase.assertTrue(this.gjk.detect(polygon, t1, capsule, t2, p)); TestCase.assertTrue(this.gjk.detect(polygon, t1, capsule, t2)); n = p.getNormal(); TestCase.assertEquals( 0.000, n.x, 1.0e-3); TestCase.assertEquals(-1.000, n.y, 1.0e-3); TestCase.assertEquals( 0.725, p.getDepth(), 1.0e-3); // try reversing the shapes TestCase.assertTrue(this.gjk.detect(capsule, t2, polygon, t1, p)); TestCase.assertTrue(this.gjk.detect(capsule, t2, polygon, t1)); n = p.getNormal(); TestCase.assertEquals( 0.000, n.x, 1.0e-3); TestCase.assertEquals( 1.000, n.y, 1.0e-3); TestCase.assertEquals( 0.725, p.getDepth(), 1.0e-3); // test overlap t1.translate(-0.5, 0.0); TestCase.assertTrue(this.gjk.detect(polygon, t1, capsule, t2, p)); TestCase.assertTrue(this.gjk.detect(polygon, t1, capsule, t2)); n = p.getNormal(); TestCase.assertEquals( 0.809, n.x, 1.0e-3); TestCase.assertEquals( 0.587, n.y, 1.0e-3); TestCase.assertEquals( 0.452, p.getDepth(), 1.0e-3); // try reversing the shapes TestCase.assertTrue(this.gjk.detect(capsule, t2, polygon, t1, p)); TestCase.assertTrue(this.gjk.detect(capsule, t2, polygon, t1)); n = p.getNormal(); TestCase.assertEquals(-0.809, n.x, 1.0e-3); TestCase.assertEquals(-0.587, n.y, 1.0e-3); TestCase.assertEquals( 0.452, p.getDepth(), 1.0e-3); // test AABB overlap t2.translate(0.3, 0.4); TestCase.assertFalse(this.gjk.detect(polygon, t1, capsule, t2, p)); TestCase.assertFalse(this.gjk.detect(polygon, t1, capsule, t2)); // try reversing the shapes TestCase.assertFalse(this.gjk.detect(capsule, t2, polygon, t1, p)); TestCase.assertFalse(this.gjk.detect(capsule, t2, polygon, t1)); // test no overlap t2.translate(1.0, 0.0); TestCase.assertFalse(this.gjk.detect(polygon, t1, capsule, t2, p)); TestCase.assertFalse(this.gjk.detect(polygon, t1, capsule, t2)); // try reversing the shapes TestCase.assertFalse(this.gjk.detect(capsule, t2, polygon, t1, p)); TestCase.assertFalse(this.gjk.detect(capsule, t2, polygon, t1)); } /** * Tests the {@link Gjk} distance method. */ @Test public void gjkDistance() { Separation s = new Separation(); Transform t1 = new Transform(); Transform t2 = new Transform(); Vector2 n = null; Vector2 p1 = null; Vector2 p2 = null; // test containment TestCase.assertFalse(this.gjk.distance(polygon, t1, capsule, t2, s)); // try reversing the shapes TestCase.assertFalse(this.gjk.distance(capsule, t2, polygon, t1, s)); // test overlap t1.translate(-0.5, 0.0); TestCase.assertFalse(this.gjk.distance(polygon, t1, capsule, t2, s)); // try reversing the shapes TestCase.assertFalse(this.gjk.distance(capsule, t2, polygon, t1, s)); // test AABB overlap t2.translate(0.3, 0.4); TestCase.assertTrue(this.gjk.distance(polygon, t1, capsule, t2, s)); n = s.getNormal(); p1 = s.getPoint1(); p2 = s.getPoint2(); TestCase.assertEquals( 0.025, s.getDistance(), 1.0e-3); TestCase.assertEquals( 0.809, n.x, 1.0e-3); TestCase.assertEquals( 0.587, n.y, 1.0e-3); TestCase.assertEquals(-0.172, p1.x, 1.0e-3); TestCase.assertEquals( 0.238, p1.y, 1.0e-3); TestCase.assertEquals(-0.152, p2.x, 1.0e-3); TestCase.assertEquals( 0.253, p2.y, 1.0e-3); // try reversing the shapes TestCase.assertTrue(this.gjk.distance(capsule, t2, polygon, t1, s)); n = s.getNormal(); p1 = s.getPoint1(); p2 = s.getPoint2(); TestCase.assertEquals( 0.025, s.getDistance(), 1.0e-3); TestCase.assertEquals(-0.809, n.x, 1.0e-3); TestCase.assertEquals(-0.587, n.y, 1.0e-3); TestCase.assertEquals(-0.152, p1.x, 1.0e-3); TestCase.assertEquals( 0.253, p1.y, 1.0e-3); TestCase.assertEquals(-0.172, p2.x, 1.0e-3); TestCase.assertEquals( 0.238, p2.y, 1.0e-3); // test no overlap t2.translate(1.0, 0.0); TestCase.assertTrue(this.gjk.distance(polygon, t1, capsule, t2, s)); n = s.getNormal(); p1 = s.getPoint1(); p2 = s.getPoint2(); TestCase.assertEquals( 0.873, s.getDistance(), 1.0e-3); TestCase.assertEquals( 0.934, n.x, 1.0e-3); TestCase.assertEquals( 0.356, n.y, 1.0e-3); TestCase.assertEquals( 0.000, p1.x, 1.0e-3); TestCase.assertEquals( 0.000, p1.y, 1.0e-3); TestCase.assertEquals( 0.816, p2.x, 1.0e-3); TestCase.assertEquals( 0.311, p2.y, 1.0e-3); // try reversing the shapes TestCase.assertTrue(this.gjk.distance(capsule, t2, polygon, t1, s)); n = s.getNormal(); p1 = s.getPoint1(); p2 = s.getPoint2(); TestCase.assertEquals( 0.873, s.getDistance(), 1.0e-3); TestCase.assertEquals(-0.934, n.x, 1.0e-3); TestCase.assertEquals(-0.356, n.y, 1.0e-3); TestCase.assertEquals( 0.816, p1.x, 1.0e-3); TestCase.assertEquals( 0.311, p1.y, 1.0e-3); TestCase.assertEquals( 0.000, p2.x, 1.0e-3); TestCase.assertEquals( 0.000, p2.y, 1.0e-3); } /** * Test the {@link ClippingManifoldSolver}. */ @Test public void getClipManifold() { Manifold m = new Manifold(); Penetration p = new Penetration(); Transform t1 = new Transform(); Transform t2 = new Transform(); ManifoldPoint mp1; Vector2 p1; // test containment gjk this.gjk.detect(polygon, t1, capsule, t2, p); TestCase.assertTrue(this.cmfs.getManifold(p, polygon, t1, capsule, t2, m)); TestCase.assertEquals(2, m.getPoints().size()); // try reversing the shapes this.gjk.detect(capsule, t2, polygon, t1, p); TestCase.assertTrue(this.cmfs.getManifold(p, capsule, t2, polygon, t1, m)); TestCase.assertEquals(2, m.getPoints().size()); // test containment sat this.sat.detect(polygon, t1, capsule, t2, p); TestCase.assertTrue(this.cmfs.getManifold(p, polygon, t1, capsule, t2, m)); TestCase.assertEquals(2, m.getPoints().size()); // try reversing the shapes this.sat.detect(capsule, t2, polygon, t1, p); TestCase.assertTrue(this.cmfs.getManifold(p, capsule, t2, polygon, t1, m)); TestCase.assertEquals(2, m.getPoints().size()); t1.translate(-0.5, 0.0); // test overlap gjk this.gjk.detect(polygon, t1, capsule, t2, p); TestCase.assertTrue(this.cmfs.getManifold(p, polygon, t1, capsule, t2, m)); TestCase.assertEquals(1, m.getPoints().size()); mp1 = m.getPoints().get(0); p1 = mp1.getPoint(); TestCase.assertEquals(-0.452, p1.x, 1.0e-3); TestCase.assertEquals(-0.146, p1.y, 1.0e-3); TestCase.assertEquals( 0.452, mp1.getDepth(), 1.0e-3); // try reversing the shapes this.gjk.detect(capsule, t2, polygon, t1, p); TestCase.assertTrue(this.cmfs.getManifold(p, capsule, t2, polygon, t1, m)); TestCase.assertEquals(1, m.getPoints().size()); mp1 = m.getPoints().get(0); p1 = mp1.getPoint(); TestCase.assertEquals(-0.452, p1.x, 1.0e-3); TestCase.assertEquals(-0.146, p1.y, 1.0e-3); TestCase.assertEquals( 0.452, mp1.getDepth(), 1.0e-3); // test overlap sat p.clear(); m.clear(); this.sat.detect(polygon, t1, capsule, t2, p); TestCase.assertTrue(this.cmfs.getManifold(p, polygon, t1, capsule, t2, m)); TestCase.assertEquals(1, m.getPoints().size()); mp1 = m.getPoints().get(0); p1 = mp1.getPoint(); TestCase.assertEquals(-0.452, p1.x, 1.0e-3); TestCase.assertEquals(-0.146, p1.y, 1.0e-3); TestCase.assertEquals( 0.452, mp1.getDepth(), 1.0e-3); // try reversing the shapes this.sat.detect(capsule, t2, polygon, t1, p); TestCase.assertTrue(this.cmfs.getManifold(p, capsule, t2, polygon, t1, m)); TestCase.assertEquals(1, m.getPoints().size()); mp1 = m.getPoints().get(0); p1 = mp1.getPoint(); TestCase.assertEquals(-0.452, p1.x, 1.0e-3); TestCase.assertEquals(-0.146, p1.y, 1.0e-3); TestCase.assertEquals( 0.452, mp1.getDepth(), 1.0e-3); } }
3e0ccd3d5a8d881c8a844ddfaaf6d82b0456db3e
29,665
java
Java
jdi-light/src/main/java/com/epam/jdi/light/actions/ActionHelper.java
Syzygy9/jdi-light
0a7bc51e7ddbefe5e9bb2f58cc4f02c4d7caf8b3
[ "MIT" ]
null
null
null
jdi-light/src/main/java/com/epam/jdi/light/actions/ActionHelper.java
Syzygy9/jdi-light
0a7bc51e7ddbefe5e9bb2f58cc4f02c4d7caf8b3
[ "MIT" ]
null
null
null
jdi-light/src/main/java/com/epam/jdi/light/actions/ActionHelper.java
Syzygy9/jdi-light
0a7bc51e7ddbefe5e9bb2f58cc4f02c4d7caf8b3
[ "MIT" ]
null
null
null
44.422156
147
0.607367
5,430
package com.epam.jdi.light.actions; import com.epam.jdi.light.asserts.generic.JAssert; import com.epam.jdi.light.common.JDIAction; import com.epam.jdi.light.elements.base.DriverBase; import com.epam.jdi.light.elements.base.JDIBase; import com.epam.jdi.light.elements.common.Alerts; import com.epam.jdi.light.elements.common.UIElement; import com.epam.jdi.light.elements.composite.WebPage; import com.epam.jdi.light.elements.interfaces.base.IBaseElement; import com.epam.jdi.light.elements.interfaces.base.ICoreElement; import com.epam.jdi.light.elements.interfaces.base.INamed; import com.epam.jdi.light.elements.pageobjects.annotations.VisualCheck; import com.epam.jdi.light.logger.HighlightStrategy; import com.epam.jdi.light.logger.LogLevels; import com.epam.jdi.tools.LinqUtils; import com.epam.jdi.tools.PrintUtils; import com.epam.jdi.tools.Safe; import com.epam.jdi.tools.Timer; import com.epam.jdi.tools.func.JAction1; import com.epam.jdi.tools.func.JFunc; import com.epam.jdi.tools.func.JFunc1; import com.epam.jdi.tools.func.JFunc2; import com.epam.jdi.tools.map.MapArray; import com.epam.jdi.tools.pairs.Pair; import io.qameta.allure.Step; import org.apache.commons.lang3.ObjectUtils; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.reflect.MethodSignature; import org.openqa.selenium.WebDriver; import org.openqa.selenium.logging.LogEntry; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import static com.epam.jdi.light.actions.ActionProcessor.jStack; import static com.epam.jdi.light.common.Exceptions.exception; import static com.epam.jdi.light.common.Exceptions.safeException; import static com.epam.jdi.light.common.OutputTemplates.*; import static com.epam.jdi.light.common.PageChecks.NONE; import static com.epam.jdi.light.common.VisualCheckAction.ON_VISUAL_ACTION; import static com.epam.jdi.light.common.VisualCheckPage.CHECK_NEW_PAGE; import static com.epam.jdi.light.driver.ScreenshotMaker.takeRobotScreenshot; import static com.epam.jdi.light.driver.ScreenshotMaker.takeScreen; import static com.epam.jdi.light.driver.WebDriverFactory.getDriver; import static com.epam.jdi.light.elements.common.WindowsManager.getWindows; import static com.epam.jdi.light.elements.composite.WebPage.setCurrentPage; import static com.epam.jdi.light.elements.composite.WebPage.visualWindowCheck; import static com.epam.jdi.light.logger.AllureLogger.*; import static com.epam.jdi.light.logger.LogLevels.*; import static com.epam.jdi.light.logger.Strategy.*; import static com.epam.jdi.light.settings.JDISettings.*; import static com.epam.jdi.light.settings.WebSettings.*; import static com.epam.jdi.tools.JsonUtils.beautifyJson; import static com.epam.jdi.tools.LinqUtils.*; import static com.epam.jdi.tools.PrintUtils.print; import static com.epam.jdi.tools.ReflectionUtils.*; import static com.epam.jdi.tools.StringUtils.*; import static com.epam.jdi.tools.Timer.nowTime; import static com.epam.jdi.tools.map.MapArray.IGNORE_NOT_UNIQUE; import static com.epam.jdi.tools.map.MapArray.map; import static com.epam.jdi.tools.pairs.Pair.$; import static com.epam.jdi.tools.switcher.SwitchActions.*; import static io.qameta.allure.aspects.StepsAspects.getLifecycle; import static java.lang.Character.toUpperCase; import static java.lang.String.format; import static java.lang.System.currentTimeMillis; import static java.lang.Thread.currentThread; import static java.util.Arrays.asList; import static java.util.Collections.reverse; import static org.apache.commons.lang3.StringUtils.*; /** * Created by Roman Iovlev on 14.02.2018 * Email: ychag@example.com; Skype: roman.iovlev */ public class ActionHelper { public static JFunc1<JoinPoint, String> GET_ACTION_NAME = ActionHelper::getActionName; public static JFunc1<JoinPoint, MapArray<String, Object>> LOG_VALUES = ActionHelper::getLogOptions; public static Safe<Boolean> isAssert = new Safe<>(null); static String getTemplate(LogLevels level) { if (LOGS.logInfoDetails != null) { switch (LOGS.logInfoDetails) { case NONE: return STEP_TEMPLATE; case NAME: return NAME_TEMPLATE; case LOCATOR: return LOCATOR_TEMPLATE; case CONTEXT: return CONTEXT_TEMPLATE; case ELEMENT: return ELEMENT_TEMPLATE; } } return level.equalOrMoreThan(STEP) ? STEP_TEMPLATE : ELEMENT_TEMPLATE; } public static int CUT_STEP_TEXT = 70; public static String getActionName(JoinPoint jp) { try { MethodSignature method = getJpMethod(jp); String template = methodNameTemplate(method); return isBlank(template) ? getDefaultName(jp, method) : fillTemplate(template, jp, method); } catch (Throwable ex) { takeScreen(); throw exception(ex, "Surround method issue: Can't get action name: " + getClassMethodName(jp)); } } public static String fillTemplate(String template, JoinPoint jp, MethodSignature method) { String filledTemplate = template; try { if (filledTemplate.contains("{0")) { Object[] args = getArgs(jp); filledTemplate = msgFormat(filledTemplate, args); } else if (filledTemplate.contains("%s")) { filledTemplate = format(filledTemplate, getArgs(jp)); } if (filledTemplate.contains("{")) { MapArray<String, Object> obj = toMap(() -> new MapArray<>("this", getElementName(jp))); MapArray<String, Object> args = methodArgs(jp, method); MapArray<String, Object> core = core(jp); MapArray<String, Object> fields = classFields(jp.getThis()); MapArray<String, Object> methods = classMethods(jp.getThis()); filledTemplate = getActionNameFromTemplate(method, filledTemplate, obj, args, core, fields, methods); if (filledTemplate.contains("{{VALUE}}") && args.size() > 0) { filledTemplate = filledTemplate.replaceAll("\\{\\{VALUE}}", args.get(0).toString()); } if (filledTemplate.contains("{failElement}")) { filledTemplate = filledTemplate.replaceAll("\\{failElement}", obj.get(0).value.toString()); } } return filledTemplate; } catch (Exception ex) { throw exception(ex, "Surround method issue: Can't fill JDIAction template: " + template + " for method: " + getClassMethodName(jp)); } } public static JFunc1<String, String> TRANSFORM_LOG_STRING = s -> s; static Safe<List<String>> allureSteps = new Safe<>(ArrayList::new); public static void beforeJdiAction(ActionObject jInfo) { JoinPoint jp = jInfo.jp(); String message = TRANSFORM_LOG_STRING.execute(getBeforeLogString(jp)); if (LOGS.writeToAllure && logLevel(jInfo).equalOrMoreThan(INFO) && (allureSteps.get().isEmpty() || !allureSteps.get().contains(message))) { jInfo.stepUId = startStep(message); allureSteps.get().add(message); } if (jInfo.topLevel()) { processBeforeAction(message, jInfo); } } protected static void processBeforeAction(String message, ActionObject jInfo) { allureSteps.reset(); JoinPoint jp = jInfo.jp(); if (LOGS.writeToLog) { logger.toLog(message, logLevel(jInfo)); } if (ObjectUtils.isNotEmpty(ELEMENT.highlight) && !ELEMENT.highlight.contains(HighlightStrategy.OFF)) { if (ELEMENT.highlight.contains(HighlightStrategy.ACTION) && !isAssert(jInfo) || ELEMENT.highlight.contains(HighlightStrategy.ASSERT) && isAssert(jInfo)) { try { jInfo.core().highlight(); } catch (Exception ignore) { } } } if (PAGE.checkPageOpen != NONE || VISUAL_PAGE_STRATEGY == CHECK_NEW_PAGE || LOGS.screenStrategy.contains(NEW_PAGE)) { processPage(jInfo); } if (VISUAL_ACTION_STRATEGY == ON_VISUAL_ACTION) { visualValidation(jp, message); } if (LOGS.screenStrategy.contains(ASSERT)) { if (isAssert(jInfo)) { performAssert(jInfo); } else { isAssert.set(false); } } } private static void performAssert(ActionObject jInfo) { boolean lastActionIsNotAssert = isAssert.get() == null || !isAssert.get(); isAssert.set(true); if (lastActionIsNotAssert) { String screenName = "Validate" + capitalize(jInfo.methodName()); createAttachment(screenName, isClass(jInfo.jpClass(), Alerts.class)); } } public static boolean isAssert(ActionObject jInfo) { return isInterface(jInfo.jpClass(), JAssert.class) || jInfo.isAssertAnnotation(); } public static void beforeStepAction(JoinPoint jp) { String message = TRANSFORM_LOG_STRING.execute(getBeforeLogString(jp)); logger.toLog(message, logLevel(new ActionObject(jp))); } private static void visualValidation(JoinPoint jp, String message) { Object obj = jp.getThis(); if (obj == null) { if (getJpMethod(jp).getMethod().getAnnotation(VisualCheck.class) != null) try { visualWindowCheck(); } catch (Exception ex) { logger.debug("BEFORE: Can't do visualWindowCheck"); } } else { if (isInterface(obj.getClass(), JAssert.class)) { JDIBase element = ((IBaseElement) obj).base(); try { element.visualCheck(message); } catch (Exception ex) { logger.debug("BEFORE: Can't do visualCheck for element"); } } } } public static JAction1<ActionObject> BEFORE_JDI_ACTION = ActionHelper::beforeJdiAction; public static Object afterStepAction(ActionObject jInfo, Object result) { afterAction(jInfo, result); passStep(jInfo.stepUId); return result; } public static Object afterJdiAction(ActionObject jInfo, Object result) { afterAction(jInfo, result); passStep(jInfo.stepUId); return result; } static void afterAction(ActionObject jInfo, Object result) { JoinPoint jp = jInfo.jp(); if (logResult(jp)) { LogLevels logLevel = logLevel(jInfo); if (result == null || isInterface(getJpClass(jp), JAssert.class) || isInterface(firstInfo(jInfo).jpClass(), JAssert.class)) logger.debug("Done"); else { String text = result.toString(); if (jInfo.topLevel()) { String message = ">>> " + (logLevel == STEP && text.length() > CUT_STEP_TEXT + 5 ? text.substring(0, CUT_STEP_TEXT) + "..." : text); logger.toLog(message, logLevel); } if (LOGS.writeToAllure && isNotBlank(jInfo.stepUId)) { attachText("Actual result", "text/plain", text); } } } waitAfterAction(jInfo); TIMEOUTS.element.reset(); } private static void waitAfterAction(ActionObject jInfo) { IBaseElement element = jInfo.element(); if (element == null) return; Pair<String, Integer> waitAfter = element.base().waitAfter(); if (isNotBlank(waitAfter.key) && jInfo.methodName().equalsIgnoreCase(waitAfter.key) && waitAfter.value > 0) { Timer.sleep(waitAfter.value * 1000); } } public static JFunc2<ActionObject, Object, Object> AFTER_STEP_ACTION = ActionHelper::afterStepAction; public static JFunc2<ActionObject, Object, Object> AFTER_JDI_ACTION = ActionHelper::afterJdiAction; static boolean logResult(JoinPoint jp) { if (!LOGS.writeToLog) return false; JDIAction ja = getJdiAction(jp); return ja != null && ja.logResult(); } static JDIAction getJdiAction(JoinPoint jp) { return ((MethodSignature)jp.getSignature()).getMethod().getAnnotation(JDIAction.class); } protected static Class<?> getJpClass(JoinPoint jp) { return jp.getThis() != null ? jp.getThis().getClass() : jp.getSignature().getDeclaringType(); } //region Private public static String getBeforeLogString(JoinPoint jp) { String actionName = GET_ACTION_NAME.execute(jp); String logString; if (jp.getThis() == null) { logString = actionName; } else { MapArray<String, Object> logOptions = LOG_VALUES.execute(jp); logOptions.add("action", actionName); logString = msgFormat(getTemplate(LOGS.logLevel), logOptions); } return toUpperCase(logString.charAt(0)) + logString.substring(1); } public static MapArray<String, Object> getLogOptions(JoinPoint jp) { MapArray<String, Object> map = new MapArray<>(); JFunc<String> elementName = () -> getElementName(jp); map.add("name", elementName); JFunc<String> element = () -> getFullInfo(jp); map.add("element", element); JFunc<String> context = () -> getElementContext(jp); map.add("context", context); JFunc<String> locator = () -> getElementLocator(jp); map.add("locator", locator); return map; } public static void processPage(ActionObject jInfo) { getWindows(); Object element = jInfo.jp().getThis(); if (element != null && !isClass(element.getClass(), WebPage.class)) { WebPage page = getPage(element); if (page != null) { setCurrentPage(page); PAGE.beforeEachStep.execute(page); } } } public static List<String> failedMethods = new ArrayList<>(); public static RuntimeException actionFailed(ActionObject jInfo, Throwable ex) { addFailedMethod(jInfo.jp()); if (jInfo.topLevel()) { logFailure(jInfo); reverse(failedMethods); List<String> chainActions = new ArrayList<>(failedMethods); try { logger.error("Url: " + WebPage.getUrl()); } catch (Exception ignore) { } logger.error("Failed actions chain: " + print(chainActions, " > ")); } else { if (LOGS.writeToAllure && isNotBlank(jInfo.stepUId)) getLifecycle().stopStep(jInfo.stepUId); } return exception(ex, getExceptionAround(ex, jInfo)); } public static JFunc2<ActionObject, Throwable, RuntimeException> ACTION_FAILED = ActionHelper::actionFailed; public static void logFailure(ActionObject jInfo) { logger.toLog(">>> " + jInfo.object().toString(), ERROR); String screenPath = ""; String htmlSnapshot = ""; String errors = ""; if (ObjectUtils.isNotEmpty(ELEMENT.highlight) && !ELEMENT.highlight.contains(HighlightStrategy.OFF)) { if (ELEMENT.highlight.contains(HighlightStrategy.FAIL)) { try { jInfo.core().highlight(); } catch (Exception ignore) { } } } if (LOGS.screenStrategy.contains(FAIL)) screenPath = SCREEN.tool.equalsIgnoreCase("robot") ? takeRobotScreenshot() : takeScreen("Failed"+capitalize(jInfo.methodName())); if (LOGS.htmlCodeStrategy.contains(FAIL)) htmlSnapshot = takeHtmlCodeOnFailure(); if (LOGS.requestsStrategy.contains(FAIL)) { WebDriver driver = jInfo.element() != null ? jInfo.element().base().driver() : getDriver(); List<LogEntry> requests = driver.manage().logs().get("performance").getAll(); List<String> errorEntries = LinqUtils.map(filter(requests, LOGS.filterHttpRequests), logEntry -> beautifyJson(logEntry.getMessage())); errors = print(errorEntries); } failStep(jInfo.stepUId, screenPath, htmlSnapshot, errors); } static WebPage getPage(Object element) { if (isInterface(element.getClass(), IBaseElement.class)) return ((IBaseElement) element).base().getPage(); if (isClass(element.getClass(), WebPage.class)) return (WebPage) element; if (isClass(element.getClass(), DriverBase.class)) return ((DriverBase)element).getPage(); return null; } public static MethodSignature getJpMethod(JoinPoint joinPoint) { return (MethodSignature) joinPoint.getSignature(); } public static String getMethodName(JoinPoint jp) { try { return getJpMethod(jp).getName(); } catch (Exception ignore) { return "Unknown method"; } } static String methodNameTemplate(MethodSignature method) { try { Method m = method.getMethod(); if (m.isAnnotationPresent(JDIAction.class)) { return m.getAnnotation(JDIAction.class).value(); } if (m.isAnnotationPresent(Step.class)) { return m.getAnnotation(Step.class).value(); } return null; } catch (Exception ex) { throw exception(ex, "Surround method issue: Can't get method name template"); } } static LogLevels logLevel(ActionObject jInfo) { LogLevels currentLevel = logLevel(jInfo.jp()); LogLevels topLevel = firstInfo(jInfo).logLevel(); return currentLevel.equalOrLessThan(topLevel) ? currentLevel : topLevel; } static LogLevels logLevel(JoinPoint jp) { Method m = getJpMethod(jp).getMethod(); return m.isAnnotationPresent(JDIAction.class) ? m.getAnnotation(JDIAction.class).level() : INFO; } static String getDefaultName(JoinPoint jp, MethodSignature method) { MapArray<String, Object> args = methodArgs(jp, method); String methodName = splitCamelCase(getMethodName(jp)); if (args.size() == 0) return methodName; return format("%s%s", methodName, argsToString(args)); } static String argsToString(MapArray<String, Object> args) { return args.size() == 1 ? argToString(args) : "("+args.toString()+")"; } static String argToString(MapArray<String, Object> args) { return args.get(0).value.getClass().isArray() ? arrayToString(args.get(0).value) : "("+args.get(0).value+")"; } static MapArray<String, Object> methodArgs(JoinPoint joinPoint, MethodSignature method) { return toMap(() -> new MapArray<>(method.getParameterNames(), getArgs(joinPoint))); } static MapArray<String, Object> toMap(JFunc<MapArray<String, Object>> getMap) { IGNORE_NOT_UNIQUE = true; MapArray<String, Object> map = getMap.execute(); IGNORE_NOT_UNIQUE = false; return map; } static Object[] getArgs(JoinPoint jp) { Object[] args = jp.getArgs(); if (args.length == 1 && args[0] == null) return new Object[] {}; Object[] result = new Object[args.length]; for (int i = 0; i< args.length; i++) result[i] = Switch(args[i]).get( Case(Objects::isNull, null), Case(arg -> arg.getClass().isArray(), PrintUtils::printArray), Case(arg -> isInterface(arg.getClass(), List.class), PrintUtils::printList), Default(arg -> arg)); return result; } static MapArray<String, Object> core(JoinPoint jp) { Object instance = jp.getThis(); if (instance != null && isInterface(instance.getClass(), ICoreElement.class)) { UIElement el = ((ICoreElement) instance).core(); return getAllFields(el); } return new MapArray<>(); } static MapArray<String, Object> classFields(Object obj) { return obj != null ? getAllFields(obj) : new MapArray<>(); } static MapArray<String, Object> classMethods(Object obj) { return obj != null ? getMethods(obj) : new MapArray<>(); } private static MapArray<String, Object> getMethods(Object obj) { return new MapArray<>(obj.getClass().getMethods(), method -> method.getName() + "()", v -> func(obj, v), true); } private static JFunc<String> func(Object obj, Method m) { return () -> m.invoke(obj).toString(); } static String getElementName(JoinPoint jp) { try { Object obj = jp.getThis(); if (obj == null) return jp.getSignature().getDeclaringType().getSimpleName(); return isInterface(getJpClass(jp), INamed.class) ? ((INamed) obj).getName() : obj.toString(); } catch (Throwable ex) { return "Can't get element name"; } } static String getElementContext(JoinPoint jp) { try { Object obj = jp.getThis(); if (obj == null) return jp.getSignature().getDeclaringType().getSimpleName(); if (isInterface(getJpClass(jp), IBaseElement.class)) return ((IBaseElement) obj).base().printFullLocator(); return isInterface(getJpClass(jp), INamed.class) ? ((INamed) obj).getName() : obj.toString(); } catch (Throwable ex) { return "Can't get context locator"; } } static String getFullInfo(JoinPoint jp) { try { Object obj = jp.getThis(); if (obj == null) return jp.getSignature().getDeclaringType().getSimpleName(); if (isInterface(getJpClass(jp), IBaseElement.class)) return ((IBaseElement) obj).base().toString(); return isInterface(getJpClass(jp), INamed.class) ? ((INamed) obj).getName() : obj.toString(); } catch (Throwable ex) { return "Can't get context locator"; } } static String getElementLocator(JoinPoint jp) { try { Object obj = jp.getThis(); if (obj == null) return jp.getSignature().getDeclaringType().getSimpleName(); if (isInterface(getJpClass(jp), IBaseElement.class)) return ((IBaseElement) obj).base().locator.toString(); return isInterface(getJpClass(jp), INamed.class) ? ((INamed) obj).getName() : obj.toString(); } catch (Throwable ex) { return "Can't get element locator"; } } static String getActionNameFromTemplate(MethodSignature method, String value, MapArray<String, Object>... args) { String result; try { if (isBlank(value)) { result = splitLowerCase(method.getMethod().getName()); if (args[1].size() == 1) result += " '" + args[1].values().get(0) + "'"; } else { result = value; for (MapArray<String, Object> params : args) result = msgFormat(result, params); } return result; } catch (Exception ex) { throw exception(ex, "Surround method issue: Can't get action name"); } } //endregion public static void addFailedMethod(JoinPoint jp) { String[] s = jp.toString().split("\\."); String result = format("%s.%s%s", s[s.length-2], s[s.length-1].replaceAll("\\)\\)", ""), printArgs(getArgs(jp))); if (!failedMethods.contains(result)) failedMethods.add(result); } private static String printArgs(Object[] args) { return args.length == 0 ? ")" : format(":'%s')", print(asList(args), Object::toString)); } public static String getExceptionAround(Throwable ex, ActionObject jInfo) { String result = safeException(ex); while (result.contains("\n\n")) result = result.replaceFirst("\\n\\n", LINE_BREAK); result = result.replace("java.lang.RuntimeException:", "").trim(); Object[] args = jInfo.jp().getArgs(); if (result.contains("{{VALUE}}") && args.length > 0) { result = result.replaceAll("\\{\\{VALUE}}", args[0].toString()); } if (jInfo.topLevel()) result = "[" + nowTime("mm:ss.S") + "] " + result.replaceFirst("\n", ""); return result; } private static List<StackTraceElement> arounds() { List<StackTraceElement> arounds = where(currentThread().getStackTrace(), s -> s.getMethodName().equals("jdiAround")); Collections.reverse(arounds); return arounds; } public static boolean notThisAround(String name) { return !arounds().get(0).getClassName().equals(name); } public static int aroundCount() { return where(currentThread().getStackTrace(), s -> s.getMethodName().equals("jdiAround")) .size(); } static String getClassMethodName(JoinPoint jp) { String className = getJpClass(jp).getSimpleName(); String methodName = getMethodName(jp); return className + "." + methodName; } public static Class<?> getJpClass(ProceedingJoinPoint jp) { return jp.getThis() != null ? jp.getThis().getClass() : jp.getSignature().getDeclaringType(); } public static Object defaultAction(ActionObject jInfo) throws Throwable { logger.debug("defaultAction: " + getClassMethodName(jInfo.jp())); jInfo.setElementTimeout(); return jInfo.overrideAction() != null ? jInfo.overrideAction().execute(jInfo.object()) : jInfo.execute(); } public static Object stableAction(ActionObject jInfo) { logger.debug("stableAction: " + getClassMethodName(jInfo.jp())); String exceptionMsg = ""; jInfo.setElementTimeout(); long start = currentTimeMillis(); Throwable exception = null; do { try { logger.debug("do-while: " + getClassMethodName(jInfo.jp())); Object result = jInfo.overrideAction() != null ? jInfo.overrideAction().execute(jInfo.object()) : jInfo.execute(); if (!condition(jInfo.jp())) continue; return result; } catch (Throwable ex) { exception = ex; try { exceptionMsg = safeException(ex); Thread.sleep(200); } catch (Exception ignore) { } } } while (currentTimeMillis() - start < jInfo.timeout() * 1000); throw exception(exception, getFailedMessage(jInfo, exceptionMsg)); } static String getFailedMessage(ActionObject jInfo, String exception) { MethodSignature method = getJpMethod(jInfo.jp()); try { String result = msgFormat(FAILED_ACTION_TEMPLATE, map( $("exception", exception), $("timeout", jInfo.timeout()), $("action", getClassMethodName(jInfo.jp())) )); return fillTemplate(result, jInfo.jp(), method); } catch (Exception ex) { throw exception(ex, "Surround method issue: Can't get failed message"); } } static String getConditionName(JoinPoint jp) { JDIAction ja = getJdiAction(jp); return ja != null ? ja.condition() : ""; } public static MapArray<String, JFunc1<Object, Boolean>> CONDITIONS = map( $("", result -> true), $("true", result -> result instanceof Boolean && (Boolean) result), $("false", result -> result instanceof Boolean && !(Boolean) result), $("not empty", result -> result instanceof List && ((List) result).size() > 0), $("empty", result -> result instanceof List && ((List) result).size() == 0) ); static boolean condition(JoinPoint jp) { String conditionName = getConditionName(jp); return CONDITIONS.has(conditionName) && CONDITIONS.get(conditionName).execute(jp) || !CONDITIONS.has(conditionName) && true; } public static ActionObject newInfo(ProceedingJoinPoint jp) { try { return newInfo(new ActionObject(jp)); } catch (Throwable ex) { throw exception(ex, "Failed to init pjp aspect: "); } } public static ActionObject newInfo(JoinPoint jp) { try { return newInfo(new ActionObject(jp)); } catch (Throwable ex) { throw exception(ex, "Failed to init jp aspect: "); } } public static ActionObject newInfo(ActionObject jInfo) { if (jInfo.topLevel()) { jStack.set(newList(jInfo)); } else { jStack.get().add(jInfo); } return jInfo; } public static ActionObject firstInfo(ActionObject jInfo) { try { return jStack.get().get(0); } catch (Exception ignore) { return jInfo; } } }
3e0ccdd9b1db558d5d7a62455d07d6d5b650014a
4,500
java
Java
sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/actorpropagation/ActorPropagationTest.java
tydhot/opentelemetry-java
7a89a197003df3be2dca9796f7d95f49a6a8fab2
[ "Apache-2.0" ]
1,189
2019-05-01T19:16:45.000Z
2022-03-31T09:42:31.000Z
sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/actorpropagation/ActorPropagationTest.java
tydhot/opentelemetry-java
7a89a197003df3be2dca9796f7d95f49a6a8fab2
[ "Apache-2.0" ]
3,239
2019-05-01T20:08:06.000Z
2022-03-31T23:12:43.000Z
sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/actorpropagation/ActorPropagationTest.java
tydhot/opentelemetry-java
7a89a197003df3be2dca9796f7d95f49a6a8fab2
[ "Apache-2.0" ]
548
2019-05-01T19:16:41.000Z
2022-03-31T05:47:18.000Z
39.130435
98
0.716667
5,431
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.sdk.trace.testbed.actorpropagation; import static org.assertj.core.api.Assertions.assertThat; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanKind; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.context.Scope; import io.opentelemetry.sdk.testing.junit5.OpenTelemetryExtension; import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.testbed.TestUtils; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.Phaser; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; /** * These tests are intended to simulate the kind of async models that are common in java async * frameworks. * * <p>For improved readability, ignore the phaser lines as those are there to ensure deterministic * execution for the tests without sleeps. */ @SuppressWarnings("FutureReturnValueIgnored") class ActorPropagationTest { @RegisterExtension static final OpenTelemetryExtension otelTesting = OpenTelemetryExtension.create(); private final Tracer tracer = otelTesting.getOpenTelemetry().getTracer(ActorPropagationTest.class.getName()); private Phaser phaser; @BeforeEach void before() { phaser = new Phaser(); } @Test void testActorTell() { try (Actor actor = new Actor(tracer, phaser)) { phaser.register(); Span parent = tracer.spanBuilder("actorTell").setSpanKind(SpanKind.PRODUCER).startSpan(); parent.setAttribute("component", "example-actor"); try (Scope ignored = parent.makeCurrent()) { actor.tell("my message 1"); actor.tell("my message 2"); } finally { parent.end(); } phaser.arriveAndAwaitAdvance(); // child tracer started assertThat(otelTesting.getSpans()).hasSize(1); phaser.arriveAndAwaitAdvance(); // continue... phaser.arriveAndAwaitAdvance(); // child tracer finished assertThat(otelTesting.getSpans()).hasSize(3); assertThat(TestUtils.getByKind(otelTesting.getSpans(), SpanKind.CONSUMER)).hasSize(2); phaser.arriveAndDeregister(); // continue... List<SpanData> finished = otelTesting.getSpans(); assertThat(finished.size()).isEqualTo(3); assertThat(finished.get(0).getTraceId()).isEqualTo(finished.get(1).getTraceId()); assertThat(TestUtils.getByKind(finished, SpanKind.CONSUMER)).hasSize(2); assertThat(TestUtils.getOneByKind(finished, SpanKind.PRODUCER)).isNotNull(); assertThat(Span.current()).isSameAs(Span.getInvalid()); } } @Test void testActorAsk() throws ExecutionException, InterruptedException { try (Actor actor = new Actor(tracer, phaser)) { phaser.register(); Future<String> future1; Future<String> future2; Span span = tracer.spanBuilder("actorAsk").setSpanKind(SpanKind.PRODUCER).startSpan(); span.setAttribute("component", "example-actor"); try (Scope ignored = span.makeCurrent()) { future1 = actor.ask("my message 1"); future2 = actor.ask("my message 2"); } finally { span.end(); } phaser.arriveAndAwaitAdvance(); // child tracer started assertThat(otelTesting.getSpans().size()).isEqualTo(1); phaser.arriveAndAwaitAdvance(); // continue... phaser.arriveAndAwaitAdvance(); // child tracer finished assertThat(otelTesting.getSpans().size()).isEqualTo(3); assertThat(TestUtils.getByKind(otelTesting.getSpans(), SpanKind.CONSUMER)).hasSize(2); phaser.arriveAndDeregister(); // continue... List<SpanData> finished = otelTesting.getSpans(); String message1 = future1.get(); // This really should be a non-blocking callback... String message2 = future2.get(); // This really should be a non-blocking callback... assertThat(message1).isEqualTo("received my message 1"); assertThat(message2).isEqualTo("received my message 2"); assertThat(finished.size()).isEqualTo(3); assertThat(finished.get(0).getTraceId()).isEqualTo(finished.get(1).getTraceId()); assertThat(TestUtils.getByKind(finished, SpanKind.CONSUMER)).hasSize(2); assertThat(TestUtils.getOneByKind(finished, SpanKind.PRODUCER)).isNotNull(); assertThat(Span.current()).isSameAs(Span.getInvalid()); } } }
3e0cce151556e05ab45e3ab3759699470abc1c3c
3,489
java
Java
app/src/main/java/com/spade/ja/ui/Home/directory/venues/viewholder/AllVenuesViewHolder.java
ehabhelmy/jedaah_attractions
4bbabf185976f7ab5037ceaab250eb6c1ce121a4
[ "MIT" ]
null
null
null
app/src/main/java/com/spade/ja/ui/Home/directory/venues/viewholder/AllVenuesViewHolder.java
ehabhelmy/jedaah_attractions
4bbabf185976f7ab5037ceaab250eb6c1ce121a4
[ "MIT" ]
null
null
null
app/src/main/java/com/spade/ja/ui/Home/directory/venues/viewholder/AllVenuesViewHolder.java
ehabhelmy/jedaah_attractions
4bbabf185976f7ab5037ceaab250eb6c1ce121a4
[ "MIT" ]
1
2021-09-17T19:59:28.000Z
2021-09-17T19:59:28.000Z
33.873786
188
0.667527
5,432
package com.spade.ja.ui.Home.directory.venues.viewholder; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.View; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.bumptech.glide.request.target.SimpleTarget; import com.bumptech.glide.request.transition.Transition; import com.spade.ja.R; import com.spade.ja.datalayer.pojo.response.allvenues.Venue; import com.spade.ja.ui.Base.BaseViewHolder; import com.spade.ja.ui.Base.listener.RecyclerViewItemListener; import com.spade.ja.ui.Home.eventsinner.eventcheckout.adapter.TicketListener; import com.spade.ja.ui.widget.ImageLayout; import com.like.LikeButton; import com.like.OnLikeListener; import butterknife.BindView; /** * Created by Roma on 1/22/2018. */ public class AllVenuesViewHolder extends BaseViewHolder<Venue> { @BindView(R.id.venuImage) ImageLayout venueImage; @BindView(R.id.venueContainer) LinearLayout venueContainer; @BindView(R.id.sponsored) FrameLayout sponsored; @BindView(R.id.favourite) LikeButton favourite; @BindView(R.id.venueName) TextView venuName; @BindView(R.id.cats) TextView cats; public AllVenuesViewHolder(View itemView) { super(itemView); } @Override public void bind(Venue baseModel, RecyclerViewItemListener.onViewListener onViewListener, RecyclerViewItemListener.onFavouriteListener onFavouriteListener) { if (baseModel.getIsSponsored() != 1) { sponsored.setVisibility(View.GONE); } venuName.setText(baseModel.getTitle()); StringBuilder cat = new StringBuilder(); for (int i = 0 ; i < baseModel.getCategories().size() ; i++ ) { cat.append(baseModel.getCategories().get(i) != null ? baseModel.getCategories().get(i):""); try { cat.append(" | "); cat.append(baseModel.getSubCategories().get(i)); }catch (Exception e){ cat.append(""); }finally { if (i != baseModel.getCategories().size() - 1) { cat.append(" , "); } } } cats.setText(cat); Glide.with(venueImage.getContext()).load(baseModel.getImage()).apply(new RequestOptions().placeholder(R.mipmap.myimage).error(R.mipmap.myimage)).into(new SimpleTarget<Drawable>() { @Override public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) { venueImage.setBackground(resource); } }); favourite.setLiked(baseModel.getIsLiked()); favourite.setOnLikeListener(new OnLikeListener() { @Override public void liked(LikeButton likeButton) { onFavouriteListener.onFavouriteClicked(baseModel.getId()); } @Override public void unLiked(LikeButton likeButton) { onFavouriteListener.onFavouriteClicked(baseModel.getId()); } }); venueContainer.setOnClickListener(view -> { onViewListener.onViewClicked(baseModel.getId()); }); } @Override public void bind(Venue baseModel, int position, TicketListener ticketListener) { } }
3e0cce26b659acd29c1e8b41ea25153c92a6d50c
5,803
java
Java
src/main/java/io/github/tofodroid/mods/mimi/client/midi/MidiInputManager.java
tofodroid/mimi-mod
3ca05d9a72d56b46a8e3e4d7351fbd03b9dbe226
[ "MIT" ]
5
2021-08-06T06:55:12.000Z
2022-01-26T17:09:11.000Z
src/main/java/io/github/tofodroid/mods/mimi/client/midi/MidiInputManager.java
tofodroid/mimi-mod
3ca05d9a72d56b46a8e3e4d7351fbd03b9dbe226
[ "MIT" ]
37
2021-07-02T20:53:22.000Z
2022-02-28T17:56:58.000Z
src/main/java/io/github/tofodroid/mods/mimi/client/midi/MidiInputManager.java
tofodroid/mimi-mod
3ca05d9a72d56b46a8e3e4d7351fbd03b9dbe226
[ "MIT" ]
null
null
null
38.430464
178
0.671894
5,433
package io.github.tofodroid.mods.mimi.client.midi; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.ImmutablePair; import io.github.tofodroid.mods.mimi.common.block.BlockInstrument; import io.github.tofodroid.mods.mimi.common.item.ItemInstrument; import io.github.tofodroid.mods.mimi.common.item.ItemMidiSwitchboard; import io.github.tofodroid.mods.mimi.common.item.ModItems; import io.github.tofodroid.mods.mimi.common.midi.AMidiInputManager; import io.github.tofodroid.mods.mimi.common.network.TransmitterNotePacket.TransmitMode; import io.github.tofodroid.mods.mimi.common.tile.TileInstrument; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraftforge.client.event.ClientPlayerNetworkEvent.LoggedOutEvent; import net.minecraftforge.event.TickEvent.Phase; import net.minecraftforge.event.TickEvent.PlayerTickEvent; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.LogicalSide; public class MidiInputManager extends AMidiInputManager { public final MidiInputDeviceManager inputDeviceManager; public final MidiPlaylistManager playlistManager; private Boolean hasTransmitter = false; private List<Object> localInstrumentToPlay = new ArrayList<>(); public MidiInputManager() { this.inputDeviceManager = new MidiInputDeviceManager(); this.playlistManager = new MidiPlaylistManager(); this.playlistManager.open(); this.inputDeviceManager.open(); } public Boolean hasTransmitter() { return hasTransmitter; } public TransmitMode getTransmitMode() { return playlistManager.getTransmitMode(); } public List<Pair<Byte,ItemStack>> getLocalInstrumentsForMidiDevice(Player player, Byte channel) { return localInstrumentToPlay.stream().map(data -> { ItemStack switchStack = ItemStack.EMPTY; Byte instrumentId = null; if(data instanceof ItemStack) { switchStack = ItemInstrument.getSwitchboardStack((ItemStack)data); instrumentId = ItemInstrument.getInstrumentId((ItemStack)data); } else if(data instanceof TileInstrument) { switchStack = ((TileInstrument)data).getSwitchboardStack(); instrumentId = ((TileInstrument)data).getInstrumentId(); } if(ModItems.SWITCHBOARD.equals(switchStack.getItem()) && ItemMidiSwitchboard.getSysInput(switchStack) && ItemMidiSwitchboard.isChannelEnabled(switchStack, channel)) { return new ImmutablePair<>(instrumentId,switchStack); } return null; }) .filter(b -> b != null).collect(Collectors.toList()); } @SubscribeEvent public void handleTick(PlayerTickEvent event) { if(event.phase != Phase.END || event.side != LogicalSide.CLIENT || !event.player.isLocalPlayer()) { return; } if(hasTransmitter(event.player)) { this.hasTransmitter = true; } else { if(this.hasTransmitter) { this.playlistManager.stop(); } this.hasTransmitter = false; } this.localInstrumentToPlay = localInstrumentsToPlay(event.player); } @SubscribeEvent public void handleSelfLogOut(LoggedOutEvent event) { if(event.getPlayer() != null && event.getPlayer().isLocalPlayer()) { this.playlistManager.stop(); } } @SubscribeEvent public void onDeathDevent(LivingDeathEvent event) { if(EntityType.PLAYER.equals(event.getEntity().getType()) && ((Player)event.getEntity()).isLocalPlayer()) { this.playlistManager.stop(); } } protected Boolean hasTransmitter(Player player) { if(player.getInventory() != null) { // Off-hand isn't part of hotbar, so check it explicitly if(ModItems.TRANSMITTER.equals(player.getItemInHand(InteractionHand.OFF_HAND).getItem())) { return true; } // check hotbar for(int i = 0; i < 9; i++) { ItemStack invStack = player.getInventory().getItem(i); if(invStack != null && ModItems.TRANSMITTER.equals(invStack.getItem())) { return true; } } // check mouse item if(player.getInventory().getSelected() != null && ModItems.TRANSMITTER.equals(player.getInventory().getSelected().getItem())) { return hasTransmitter; } } return false; } protected List<Object> localInstrumentsToPlay(Player player) { List<Object> result = new ArrayList<>(); // Check for seated instrument TileInstrument instrumentEntity = BlockInstrument.getTileInstrumentForEntity(player); if(instrumentEntity != null && instrumentEntity.hasSwitchboard()) { result.add(instrumentEntity); } // Check for held instruments ItemStack mainHand = ItemInstrument.getEntityHeldInstrumentStack(player, InteractionHand.MAIN_HAND); if(mainHand != null && ItemInstrument.hasSwitchboard(mainHand)) { result.add(mainHand); } ItemStack offHand = ItemInstrument.getEntityHeldInstrumentStack(player, InteractionHand.OFF_HAND); if(offHand != null && ItemInstrument.hasSwitchboard(offHand)) { result.add(offHand); } return result; } }
3e0ccf17ce63c908ebb2526eec4ffca230967363
3,490
java
Java
src/main/java/org/jabref/model/texparser/TexBibEntriesResolverResult.java
marloncalvo/jabref
445af8d0638fa36182967ece50fae8e3c0310d52
[ "MIT" ]
1
2021-03-11T13:58:18.000Z
2021-03-11T13:58:18.000Z
src/main/java/org/jabref/model/texparser/TexBibEntriesResolverResult.java
Siedlerchr/jabref
6b97d6783c3b492412247974e36358c0dcf163a6
[ "MIT" ]
6
2019-11-22T12:35:16.000Z
2019-12-13T02:08:14.000Z
src/main/java/org/jabref/model/texparser/TexBibEntriesResolverResult.java
Siedlerchr/jabref
6b97d6783c3b492412247974e36358c0dcf163a6
[ "MIT" ]
null
null
null
28.145161
132
0.651576
5,434
package org.jabref.model.texparser; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Set; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import com.google.common.collect.Multimap; public class TexBibEntriesResolverResult { private final TexParserResult texParserResult; private final List<String> unresolvedKeys; private final List<BibEntry> newEntries; private int crossRefsCount; public TexBibEntriesResolverResult(TexParserResult texParserResult) { this.texParserResult = texParserResult; this.unresolvedKeys = new ArrayList<>(); this.newEntries = new ArrayList<>(); this.crossRefsCount = 0; } public TexParserResult getTexParserResult() { return texParserResult; } public List<String> getUnresolvedKeys() { return unresolvedKeys; } public List<BibEntry> getNewEntries() { return newEntries; } public int getCrossRefsCount() { return crossRefsCount; } /** * Return the citations multimap from the TexParserResult object. */ public Multimap<String, Citation> getCitations() { return texParserResult.getCitations(); } /** * Return a set of strings with the keys of the citations multimap from the TexParserResult object. */ public Set<String> getCitationsKeySet() { return texParserResult.getCitationsKeySet(); } /** * Add an unresolved key to the list. */ public void addUnresolvedKey(String key) { unresolvedKeys.add(key); } /** * Check if an entry with the given key is not present in the list of new entries. */ public boolean isNotKeyIntoNewEntries(String key) { return newEntries.stream().noneMatch(entry -> key.equals(entry.getCiteKeyOptional().orElse(null))); } /** * Add 1 to the cross references counter. */ public void increaseCrossRefsCount() { crossRefsCount++; } /** * Insert into the list of new entries an entry with the given key. */ public void insertEntry(BibDatabase masterDatabase, String key) { masterDatabase.getEntryByKey(key).ifPresent(this::insertEntry); } /** * Insert into the list of new entries the given entry. */ public void insertEntry(BibEntry entry) { newEntries.add(entry); } @Override public String toString() { return String.format("TexBibEntriesResolverResult{texParserResult=%s, unresolvedKeys=%s, newEntries=%s, crossRefsCount=%s}", this.texParserResult, this.unresolvedKeys, this.newEntries, this.crossRefsCount); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } TexBibEntriesResolverResult that = (TexBibEntriesResolverResult) obj; return Objects.equals(texParserResult, that.texParserResult) && Objects.equals(unresolvedKeys, that.unresolvedKeys) && Objects.equals(newEntries, that.newEntries) && Objects.equals(crossRefsCount, that.crossRefsCount); } @Override public int hashCode() { return Objects.hash(texParserResult, unresolvedKeys, newEntries, crossRefsCount); } }
3e0ccf69fe8ef3722c6987c0fb34c31075526bfe
1,244
java
Java
src/main/java/com/werken/xpath/impl/ParentStep.java
Obsidian-StudiosInc/werken-xpath
21ce6ed9e1d93f4a4f382d10a475f4bc69e1a0bf
[ "Apache-2.0" ]
null
null
null
src/main/java/com/werken/xpath/impl/ParentStep.java
Obsidian-StudiosInc/werken-xpath
21ce6ed9e1d93f4a4f382d10a475f4bc69e1a0bf
[ "Apache-2.0" ]
null
null
null
src/main/java/com/werken/xpath/impl/ParentStep.java
Obsidian-StudiosInc/werken-xpath
21ce6ed9e1d93f4a4f382d10a475f4bc69e1a0bf
[ "Apache-2.0" ]
null
null
null
19.138462
83
0.633441
5,435
package com.werken.xpath.impl; import org.jdom2.Element; import java.util.Set; import java.util.HashSet; import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; public class ParentStep extends AbbrStep { public ParentStep() { } public Context applyTo(Context context) { context.setNodeSet( ParentStep.findParents( context.getNodeSet() ) ); return context; } static public Object findParent(Object node) { if ( node instanceof Element ) { return ((Element)node).getParentElement(); } return null; } static public List findParents(List nodeSet) { // FIXME: Unable to find parents of anything // except Element at this point. Set results = new HashSet(); Iterator elemIter = nodeSet.iterator(); Object each = null; Element parent = null; while (elemIter.hasNext()) { each = elemIter.next(); if ( each instanceof Element ) { parent = ((Element)each).getParentElement(); if (parent != null) { results.add(parent); } } } return ( results.isEmpty() ? Collections.EMPTY_LIST : new ArrayList(results) ); } }
3e0ccfe9795b1245a2df072401ab6973042f7ea1
314
java
Java
aflib/src/main/java/com/af/lib/http/exception/ApiException.java
tang5011235/AFArms
dc08093026a707c579fac6384cfd32915a5b0c1e
[ "Apache-2.0" ]
6
2018-05-11T15:26:02.000Z
2018-05-15T09:25:31.000Z
aflib/src/main/java/com/af/lib/http/exception/ApiException.java
tang5011235/AFArms
dc08093026a707c579fac6384cfd32915a5b0c1e
[ "Apache-2.0" ]
null
null
null
aflib/src/main/java/com/af/lib/http/exception/ApiException.java
tang5011235/AFArms
dc08093026a707c579fac6384cfd32915a5b0c1e
[ "Apache-2.0" ]
null
null
null
22.428571
61
0.684713
5,436
package com.af.lib.http.exception; public class ApiException extends RuntimeException { private int mErrorCode; public ApiException(int errorCode, String errorMessage) { super(errorMessage); mErrorCode = errorCode; } public int getErrorCode() { return mErrorCode; } }
3e0cd1379704d0cb836ed9d6343b88570901a4d1
893
java
Java
wca/src/main/java/com/lsj/weixin/bean/transbean/SendMsgOrImgResponse.java
ouero/lsjwechat
76d31ae39cbbf9b40968e8d28c11ba9fe152a3b3
[ "Apache-2.0" ]
null
null
null
wca/src/main/java/com/lsj/weixin/bean/transbean/SendMsgOrImgResponse.java
ouero/lsjwechat
76d31ae39cbbf9b40968e8d28c11ba9fe152a3b3
[ "Apache-2.0" ]
null
null
null
wca/src/main/java/com/lsj/weixin/bean/transbean/SendMsgOrImgResponse.java
ouero/lsjwechat
76d31ae39cbbf9b40968e8d28c11ba9fe152a3b3
[ "Apache-2.0" ]
null
null
null
20.767442
60
0.660694
5,437
package com.lsj.weixin.bean.transbean; import com.alibaba.fastjson.annotation.JSONField; import com.lsj.weixin.bean.basebean.BaseResponse; /** * Created by Chan on 2016/8/13. */ public class SendMsgOrImgResponse { @JSONField(name = "BaseResponse") private BaseResponse baseResponse; @JSONField(name = "MsgID") private String msgID; @JSONField(name = "LocalID") private String localID; public BaseResponse getBaseResponse() { return baseResponse; } public void setBaseResponse(BaseResponse baseResponse) { this.baseResponse = baseResponse; } public String getMsgID() { return msgID; } public void setMsgID(String msgID) { this.msgID = msgID; } public String getLocalID() { return localID; } public void setLocalID(String localID) { this.localID = localID; } }
3e0cd1806ad1f118c215488279909fc05e5bc8cd
763
java
Java
src/main/java/io/actor4j/core/supervisor/SupervisorStrategyDirective.java
Manuki-San/actor4j-core
3173ef4d9053c2a0052186d88ad273ce1aae5760
[ "Apache-2.0" ]
52
2017-11-25T23:52:28.000Z
2022-01-21T02:55:42.000Z
src/main/java/io/actor4j/core/supervisor/SupervisorStrategyDirective.java
Manuki-San/actor4j-core
3173ef4d9053c2a0052186d88ad273ce1aae5760
[ "Apache-2.0" ]
3
2020-07-01T19:36:04.000Z
2021-12-20T21:46:53.000Z
src/main/java/io/actor4j/core/supervisor/SupervisorStrategyDirective.java
Manuki-San/actor4j-core
3173ef4d9053c2a0052186d88ad273ce1aae5760
[ "Apache-2.0" ]
9
2018-08-25T15:53:42.000Z
2020-11-13T07:37:31.000Z
36.333333
76
0.726081
5,438
/* * Copyright (c) 2015-2017, David A. Bauer. 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 io.actor4j.core.supervisor; public enum SupervisorStrategyDirective { RESUME, RESTART, STOP, ESCALATE }
3e0cd259b902493445818775dbd437d57a9eef72
2,078
java
Java
bubolo/test/bubolo/graphics/SpriteTest.java
BU-CS673/bubolo
1074a1df63a04e69c85f13ba366c90ea76f36721
[ "MIT" ]
null
null
null
bubolo/test/bubolo/graphics/SpriteTest.java
BU-CS673/bubolo
1074a1df63a04e69c85f13ba366c90ea76f36721
[ "MIT" ]
1
2016-05-25T19:02:34.000Z
2016-05-25T21:18:36.000Z
bubolo/test/bubolo/graphics/SpriteTest.java
BU-CS673/bubolo
1074a1df63a04e69c85f13ba366c90ea76f36721
[ "MIT" ]
3
2016-02-02T23:55:45.000Z
2021-02-21T17:11:01.000Z
19.06422
70
0.679981
5,439
package bubolo.graphics; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.SpriteBatch; public class SpriteTest { private SpriteBatch batch; private Camera camera; private boolean isComplete; private boolean passed; @Before public void setUp() { LibGdxAppTester.createApp(); Gdx.app.postRunnable(new Runnable() { @Override public void run() { batch = new SpriteBatch(); camera = new OrthographicCamera(100, 100); Graphics g = new Graphics(50, 500); } }); } @Test public void testDrawTextureRegion() { isComplete = false; passed = false; Gdx.app.postRunnable(new Runnable() { @Override public void run() { Sprite sprite = new MockSpriteTextureRegion(); batch.begin(); sprite.draw(batch, camera, sprite.getDrawLayer()); passed = true; isComplete = true; } }); while (!isComplete) { Thread.yield(); } assertTrue(passed); } @Test public void testColor() { isComplete = false; passed = false; Gdx.app.postRunnable(new Runnable() { @Override public void run() { Sprite sprite = new BackgroundSprite(1, 1); assertEquals(Color.WHITE, sprite.getColor()); sprite.setColor(Color.BLACK); assertEquals(Color.BLACK, sprite.getColor()); passed = true; isComplete = true; } }); while (!isComplete) { Thread.yield(); } assertTrue(passed); } @Test public void testDrawTextureRegionWrongLayer() { Gdx.app.postRunnable(new Runnable() { @Override public void run() { Camera cam = new OrthographicCamera(); SpriteBatch spriteBatch = new SpriteBatch(); Sprite sprite = new MockSpriteTextureRegion(); DrawLayer wrongLayer = (sprite.getDrawLayer() != DrawLayer.FIRST) ? DrawLayer.FIRST : DrawLayer.SECOND; sprite.draw(spriteBatch, cam, wrongLayer); } }); } }
3e0cd2a30da7aadda5987138033189b698ac7762
5,965
java
Java
app/src/main/java/com/zork/common/Controller.java
zork/tictactoe
0baa883e12c43e8d9bde2b54ec3265f5d65d444d
[ "MIT" ]
6
2018-05-08T22:28:29.000Z
2020-08-13T17:06:00.000Z
app/src/main/java/com/zork/common/Controller.java
zork/tictactoe
0baa883e12c43e8d9bde2b54ec3265f5d65d444d
[ "MIT" ]
null
null
null
app/src/main/java/com/zork/common/Controller.java
zork/tictactoe
0baa883e12c43e8d9bde2b54ec3265f5d65d444d
[ "MIT" ]
1
2020-08-13T17:06:38.000Z
2020-08-13T17:06:38.000Z
28.136792
100
0.732607
5,440
package com.zork.common; import android.app.Activity; import android.content.Context; import android.content.res.AssetManager; import android.os.Bundle; import android.os.Handler; import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; import android.support.v4.widget.ExploreByTouchHelper; import android.view.MotionEvent; import android.view.View; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; import java.util.LinkedList; import java.util.List; public class Controller extends ExploreByTouchHelper { public Controller(Activity activity, View view) { super(view); mActivity = activity; mAccessibilityManager = (AccessibilityManager) activity.getSystemService(Context.ACCESSIBILITY_SERVICE); mView = view; } // Delegated from Activity void onCreate() { nativeCreate( this, mActivity.getAssets(), mActivity.getExternalFilesDir(null).getAbsolutePath()); } void onPause() { nativePause(); } void onResume() { nativeResume(); } void onDestroy() { nativeDestroy(); } public void postUiTask(long task, long delay) { class NativeUiTask implements Runnable { private NativeUiTask(long task) { mTask = task; } public void run() { nativeRunUiTask(mTask); } private long mTask; } Handler main_handler = new Handler(mActivity.getMainLooper()); main_handler.postDelayed(new NativeUiTask(task), delay); } // Delegated from View boolean onKeyDown(int keyCode) { return nativeOnKeyDown(keyCode); } boolean onKeyUp(int keyCode) { return nativeOnKeyUp(keyCode); } boolean onTouchEvent(final MotionEvent event) { int index = event.getActionIndex(); switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: nativeTouchStart( event.getPointerId(index), (int) event.getX(index), (int) event.getY(index)); break; case MotionEvent.ACTION_MOVE: for (int i = 0; i < event.getPointerCount(); ++i) { nativeTouchMove(event.getPointerId(i), (int) event.getX(i), (int) event.getY(i)); } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: nativeTouchEnd(event.getPointerId(index), (int) event.getX(index), (int) event.getY(index)); break; } return true; } boolean onBackPressed() { return nativeOnBackPressed(); } // Delegated from Renderer void RenderInit() { nativeRenderInit(); } public void Resize(int w, int h) { nativeResize(w, h); } public void Render() { nativeRender(); } @Override protected int getVirtualViewAt(float x, float y) { return nativeGetVirtualViewAt(x, y); } @Override protected void getVisibleVirtualViews(List<Integer> virtualViewIds) { nativeGetVisibleVirtualViews(virtualViewIds); } @Override protected void onPopulateEventForVirtualView(int virtualViewId, AccessibilityEvent event) { nativeOnPopulateEvent(virtualViewId, event); } @Override protected void onPopulateNodeForVirtualView(int virtualViewId, AccessibilityNodeInfoCompat node) { nativeOnPopulateNode(virtualViewId, node); List<Integer> virtualViewIds = new LinkedList<>(); int parentId = nativeGetVirtualViewParent(virtualViewId); node.setParent(mView, parentId); nativeGetVirtualViewChildren(virtualViewId, virtualViewIds); for (Integer id : virtualViewIds) { node.addChild(mView, id); } } @Override protected boolean onPerformActionForVirtualView(int virtualViewId, int action, Bundle arguments) { return nativeOnPerformAction(virtualViewId, action, arguments); } void sendAccessibilityEvent(int type, CharSequence text) { if (mAccessibilityManager.isEnabled()) { AccessibilityEvent event = AccessibilityEvent.obtain(); event.setEventType(type); event.setContentDescription(text); mAccessibilityManager.sendAccessibilityEvent(event); } } void accessibilityAnnounce(CharSequence text) { mView.announceForAccessibility(text); } private final Activity mActivity; private final View mView; private final AccessibilityManager mAccessibilityManager; // Activity private static native void nativeCreate( Controller controller, AssetManager assetManager, String dataDirectory); private static native void nativePause(); private static native void nativeResume(); private static native void nativeDestroy(); private static native void nativeRunUiTask(long task); // View private static native boolean nativeOnKeyDown(int keyCode); private static native boolean nativeOnKeyUp(int keyCode); private static native void nativeTouchStart(int id, int x, int y); private static native void nativeTouchMove(int id, int x, int y); private static native void nativeTouchEnd(int id, int x, int y); private static native boolean nativeOnBackPressed(); // Renderer private static native void nativeRenderInit(); private static native void nativeResize(int w, int h); private static native void nativeRender(); // Accessibility private static native int nativeGetVirtualViewAt(float x, float y); private static native void nativeGetVisibleVirtualViews(List<Integer> virtualViewIds); private static native int nativeGetVirtualViewParent(int virtualViewId); private static native void nativeGetVirtualViewChildren( int virtualViewId, List<Integer> virtualViewIds); private static native void nativeOnPopulateEvent(int virtualViewId, AccessibilityEvent event); private static native void nativeOnPopulateNode( int virtualViewId, AccessibilityNodeInfoCompat node); private static native boolean nativeOnPerformAction( int virtualViewId, int action, Bundle arguments); static { System.loadLibrary("game"); } }
3e0cd321d3b18eecc4e9b5f04f156e745d706fa8
1,225
java
Java
src/UiElements/EndGameAnnouncementWindow.java
Bill4377/BattleShip
4cf64708b0c35f66e332246bb6a859f2d2a1f27f
[ "MIT" ]
null
null
null
src/UiElements/EndGameAnnouncementWindow.java
Bill4377/BattleShip
4cf64708b0c35f66e332246bb6a859f2d2a1f27f
[ "MIT" ]
null
null
null
src/UiElements/EndGameAnnouncementWindow.java
Bill4377/BattleShip
4cf64708b0c35f66e332246bb6a859f2d2a1f27f
[ "MIT" ]
null
null
null
24.019608
80
0.604898
5,441
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package UiElements; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.stage.Modality; import javafx.stage.Stage; /** * * @author Bill */ public class EndGameAnnouncementWindow { /** * Creates a Window to announce the winner of the Game. * * @param stage * @param name */ public void event(Stage stage, String name) { Stage window = new Stage(); BorderPane pane = new BorderPane(); Label label = new Label(name + " has Won!"); pane.setCenter(label); pane.setStyle("-fx-background-color: #559ad8;"); label.setStyle("-fx-text-fill: #93bce1;" + "-fx-font-size: 20pt;"); Scene scene = new Scene(pane); window.setScene(scene); window.setHeight(200); window.setWidth(500); window.initModality(Modality.WINDOW_MODAL); window.initOwner(stage); window.show(); } }
3e0cd33ceca84cdb57bd8eb130ad8e8520e3d581
2,416
java
Java
src/main/java/com/gh/mygreen/xlsmapper/SavingWorkObject.java
tjpanda88/xlsmapper
435ae778fbbb901d58c6eb8795469ea4c29ccf31
[ "Apache-2.0" ]
37
2015-03-17T03:41:23.000Z
2022-01-06T15:36:52.000Z
src/main/java/com/gh/mygreen/xlsmapper/SavingWorkObject.java
tjpanda88/xlsmapper
435ae778fbbb901d58c6eb8795469ea4c29ccf31
[ "Apache-2.0" ]
98
2015-01-01T02:57:06.000Z
2022-01-01T02:51:42.000Z
src/main/java/com/gh/mygreen/xlsmapper/SavingWorkObject.java
tjpanda88/xlsmapper
435ae778fbbb901d58c6eb8795469ea4c29ccf31
[ "Apache-2.0" ]
21
2015-12-25T07:38:44.000Z
2020-06-06T09:58:38.000Z
30.2
146
0.663907
5,442
package com.gh.mygreen.xlsmapper; import java.util.ArrayList; import java.util.List; import org.apache.poi.ss.usermodel.Cell; import com.gh.mygreen.xlsmapper.cellconverter.TypeBindException; import com.gh.mygreen.xlsmapper.util.CellPosition; import com.gh.mygreen.xlsmapper.validation.SheetBindingErrors; import com.gh.mygreen.xlsmapper.xml.AnnotationReader; /** * 書き込み処理中で持ち回すオブジェクトを保持するクラス。 * */ public class SavingWorkObject { private AnnotationReader annoReader; private final List<NeedProcess> needPostProcesses = new ArrayList<>(); private SheetBindingErrors<?> errors; public AnnotationReader getAnnoReader() { return annoReader; } public void setAnnoReader(AnnotationReader annoReader) { this.annoReader = annoReader; } public void addNeedPostProcess(NeedProcess needProcess) { this.needPostProcesses.add(needProcess); } public List<NeedProcess> getNeedPostProcesses() { return needPostProcesses; } public SheetBindingErrors<?> getErrors() { return errors; } public void setErrors(SheetBindingErrors<?> errors) { this.errors = errors; } /** * 型変換エラーを追加します。 * @param bindException 型変換エラー * @param cell マッピング元となったセル * @param fieldName マッピング先のフィールド名 * @param label ラベル。省略する場合は、nullを指定します。 */ public void addTypeBindError(final TypeBindException bindException, final Cell cell, final String fieldName, final String label) { addTypeBindError(bindException, CellPosition.of(cell), fieldName, label); } /** * 型変換エラーを追加します。 * @param bindException 型変換エラー * @param address マッピング元となったセルのアドレス * @param fieldName マッピング先のフィールド名 * @param label ラベル。省略する場合は、nullを指定します。 */ public void addTypeBindError(final TypeBindException bindException, final CellPosition address, final String fieldName, final String label) { this.errors.createFieldConversionError(fieldName, bindException.getBindClass(), bindException.getTargetValue()) .variables(bindException.getMessageVars()) .variables("validatedValue", bindException.getTargetValue()) .address(address) .label(label) .buildAndAddError(); } }
3e0cd38b362801c306e2ea6151bfd11c318ad39a
1,418
java
Java
src/test/java/com/wangchl/test/papers/ShellPushPapersTest.java
p19971018/AutoUpdate
4e0827f954b659cf7f1f56f2650c50c58b28d6e3
[ "Apache-2.0" ]
null
null
null
src/test/java/com/wangchl/test/papers/ShellPushPapersTest.java
p19971018/AutoUpdate
4e0827f954b659cf7f1f56f2650c50c58b28d6e3
[ "Apache-2.0" ]
5
2021-12-14T20:53:19.000Z
2022-01-04T16:45:31.000Z
src/test/java/com/wangchl/test/papers/ShellPushPapersTest.java
p19971018/AutoUpdate
4e0827f954b659cf7f1f56f2650c50c58b28d6e3
[ "Apache-2.0" ]
null
null
null
34.585366
114
0.763752
5,443
package com.wangchl.test.papers; import java.io.IOException; import org.junit.Test; import com.jcraft.jsch.JSchException; import com.wangchl.lord.PapersOperatAchieve; import com.wangchl.papers.ShellPushPapers; import com.wangchl.thread.domain.TaskResult; import com.wangchl.utils.domain.SftpConnParam; import com.wangchl.utils.domain.SftpFileParam; public class ShellPushPapersTest { static SftpConnParam connParam = new SftpConnParam.Builder().host("127.0.01").port(22) .user("root").password("123456.").build(); SftpFileParam papersParma = new SftpFileParam.Builder().papersPath("F:\\A_01_test\\test.sh") .depositaryPath("/data/").papersName("test.sh") .netPapersPath("http://www.wangchunlong.cn/attachment/20200408/e6cd1f0e8e9d424cbb2f8b1ff7001e97.jpg") .build(); @SuppressWarnings("unchecked") @Test public void executePushPapersParam() throws JSchException, IOException { SftpFileParam papersParma = new SftpFileParam.Builder(). papersPath("F:\\A_01_test\\") .depositaryPath("/data/").papersName("test.sh") .netPapersPath("http://www.wangchunlong.cn/attachment/20200408/e6cd1f0e8e9d424cbb2f8b1ff7001e97.jpg") .run(true).wget(true).shellTimeOut(3000) .build(); @SuppressWarnings("rawtypes") TaskResult<?> pushPapers = new PapersOperatAchieve().executeOperat(new ShellPushPapers(connParam, papersParma)); System.out.println(pushPapers.toString()); } }
3e0cd3fa9e07e4f00cf1f54eacc92a7c96578d83
36,122
java
Java
app/src/main/java/login/page/RecommendedSeeAll.java
Kkiranandroid/exam
76cfb50c8f2282539c469da1f9350884d71a58f7
[ "MIT" ]
null
null
null
app/src/main/java/login/page/RecommendedSeeAll.java
Kkiranandroid/exam
76cfb50c8f2282539c469da1f9350884d71a58f7
[ "MIT" ]
null
null
null
app/src/main/java/login/page/RecommendedSeeAll.java
Kkiranandroid/exam
76cfb50c8f2282539c469da1f9350884d71a58f7
[ "MIT" ]
null
null
null
45.898348
200
0.56096
5,444
package login.page; import android.content.Intent; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.android.volley.NoConnectionError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import Commmon.Methods.CommonMethods; import Commmon.Methods.CustomRequest; import adapter.RecommendedAdapter; import adapter.SubscribedAdapter; import eniversity.com.CorseInfo; import eniversity.com.ExploreClass; import get.set.HomeCategoryGetSet; import get.set.RecommendedGetSet; import get.set.SubscribedGetSet; import com.eniversity.app.R; import com.facebook.GraphResponse; import static com.eniversity.app.R.id.progressbarLoadExploreCourse; public class RecommendedSeeAll extends AppCompatActivity { GridView SeeAllDetailsGridView; ProgressBar detailsProgressBar; ProgressBar progressbarMoreLoadLandingDetails; private ImageView imageViewBackIcon; private TextView textViewRecommandedNoCourseFound; TextView textViewHeading; TextView textViewHeading2; private ImageView imageViewSearchIcon; private TextView editTextSearch; private int myLastVisiblePos; private ArrayList<RecommendedGetSet> recommendeditems; private ArrayList<RecommendedGetSet> recommendedMainitems; private ArrayList<RecommendedGetSet> Mainitems; private ArrayList<RecommendedGetSet> searchMainArray; private int pageSize = 1; private int searchPageSize = 1; private String searchText = ""; private String isFrom=""; private String edittextValue = ""; private boolean loading = false; private RecommendedAdapter adapter; private int previousTotal = 0; private int visibleThreshold = 5; private CoordinatorLayout coordinatorLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.recommended_list); /*****************************Toolbar************************************/ Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); imageViewBackIcon = (ImageView) toolbar.findViewById(R.id.imageViewBackIcon); imageViewBackIcon.setVisibility(View.VISIBLE); imageViewBackIcon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent=new Intent(RecommendedSeeAll.this,LoginMainPage.class); startActivity(intent); finish(); } }); imageViewSearchIcon = (ImageView) toolbar.findViewById(R.id.imageViewSearchIcon); editTextSearch = (EditText) toolbar.findViewById(R.id.editTextSearch); textViewHeading = (TextView) toolbar.findViewById(R.id.textViewHeading); textViewHeading.setVisibility(View.GONE); textViewHeading2 = (TextView) toolbar.findViewById(R.id.textViewHeading1); textViewHeading2.setVisibility(View.VISIBLE); textViewHeading2.setText("Recommended Courses"); /*************************************************************************/ textViewRecommandedNoCourseFound= (TextView) findViewById(R.id.textViewRecommandedNoCourseFound); SeeAllDetailsGridView = (GridView) findViewById(R.id.gridViewDetails); myLastVisiblePos = SeeAllDetailsGridView.getFirstVisiblePosition(); detailsProgressBar = (ProgressBar) findViewById(R.id.progressbarLoadLandingDetails); progressbarMoreLoadLandingDetails = (ProgressBar) findViewById(R.id.progressbarMoreLoadLandingDetails); coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout); Mainitems = new ArrayList<>(); searchMainArray = new ArrayList<>(); searchText = "1=1"; recommendeditems = new ArrayList<>(); recommendedMainitems = new ArrayList<>(); Mainitems = new ArrayList<>(); searchText=getIntent().getExtras().getString("wherecondition"); if(searchText.equals("1=1")){ getRecommendedDetails(searchText, pageSize); }else{ imageViewSearchIcon.setImageDrawable(getResources().getDrawable(R.drawable.ic_clear_black_white)); textViewHeading2.setVisibility(View.INVISIBLE); editTextSearch.setVisibility(View.VISIBLE); imageViewBackIcon.setVisibility(View.GONE); Mainitems = new ArrayList<>(); editTextSearch.setText(getIntent().getExtras().getString("searchtext")); editTextSearch.requestFocus(); getRecommendedSearchDetails(searchText, 1,"0"); } /*if(CommonMethods.userid.length() > 0) { toolbar.setNavigationIcon(R.drawable.ic_action_back); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(editTextSearch.getVisibility() == View.VISIBLE) { textViewHeading.setVisibility(View.VISIBLE); editTextSearch.setVisibility(View.GONE); } else { finish(); } } }); } else { toolbar.setNavigationIcon(R.drawable.ic_action_back); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(editTextSearch.getVisibility() == View.VISIBLE) { textViewHeading.setVisibility(View.VISIBLE); editTextSearch.setVisibility(View.GONE); } else { finish(); } } }); }*/ /*public void onClick(View v) { if (editTextSearch.getVisibility() == View.VISIBLE *//*&& editTextSearch.length()>0*//*) { edittextValue = "c.coursename like '%" + editTextSearch.getText().toString() + "%'"; imageViewBackIcon.setVisibility(View.VISIBLE); subscribeditems = new ArrayList<>(); subscribeditems.clear(); editTextSearch.setVisibility(View.GONE); // textViewHeading.setVisibility(View.VISIBLE); textViewHeading1.setVisibility(View.VISIBLE); imageViewSearchIcon.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_search_white)); CommonMethods.hideKeyboard(SeeAllDetails.this, (SeeAllDetails.this).getCurrentFocus()); //getSubScriberSearchDetails(edittextValue); } else { imageViewSearchIcon.setImageDrawable(getResources().getDrawable(R.drawable.ic_clear_black_white)); //textViewHeading.setVisibility(View.INVISIBLE); textViewHeading1.setVisibility(View.INVISIBLE); editTextSearch.setVisibility(View.VISIBLE); imageViewBackIcon.setVisibility(View.GONE); editTextSearch.setText(""); editTextSearch.requestFocus(); CommonMethods.showKeyboard(SeeAllDetails.this,(SeeAllDetails.this).getCurrentFocus()); subscribeditems = new ArrayList<>(); subscribeditems.clear(); // getSubScriberDetails(); } }*/ /*imageViewSearchIcon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // textViewRecommandedNoCourseFound.setVisibility(View.GONE); if (editTextSearch.getVisibility() == View.VISIBLE) { imageViewBackIcon.setVisibility(View.VISIBLE); textViewHeading.setVisibility(View.VISIBLE); imageViewSearchIcon.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_search_white)); CommonMethods.hideKeyboard(RecommendedSeeAll.this, (RecommendedSeeAll.this).getCurrentFocus()); //edittextValue = "c.coursename like '%" + editTextSearch.getText().toString() + "%'"; recommendedMainitems=new ArrayList(); recommendedMainitems.clear(); getRecommendedSearchDetails("1=1", searchPageSize); } else { imageViewSearchIcon.setImageDrawable(getResources().getDrawable(R.drawable.ic_clear_black_white)); textViewHeading.setVisibility(View.INVISIBLE); editTextSearch.setVisibility(View.VISIBLE); imageViewBackIcon.setVisibility(View.GONE); getRecommendedDetails(searchText, pageSize); } } });*/ imageViewSearchIcon.setOnClickListener(onClickListener); editTextSearch.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { /* if (s.toString().trim().length() != 0) { Mainitems = new ArrayList<>(); searchMainArray = new ArrayList<>(); //Mainitems.clear(); searchText = "c.coursename like '%" + s.toString() + "%'"; getRecommendedSearchDetails(searchText, searchPageSize); //new SearchCourseAsyncTask().execute(searchText, String.valueOf(searchPageSize)); } else { //Mainitems.clear(); getRecommendedDetails("1=1", searchPageSize); //new SearchCourseAsyncTask().execute("1=1", String.valueOf(searchPageSize)); }*/ try { searchPageSize = 1; edittextValue = "c.coursename like '%" + s.toString() + "%'"; searchMainArray = new ArrayList<>(); searchMainArray.clear(); Mainitems = new ArrayList<>(); if (editTextSearch.length() > 0) { getRecommendedSearchDetails(edittextValue, searchPageSize,"0"); } else{ isFrom="ontextchanged"; searchText="1=1"; pageSize=1; getRecommendedDetails(searchText, pageSize); } } catch (Exception e) { e.printStackTrace(); } } @Override public void afterTextChanged(Editable s) { } }); /* SeeAllDetailsGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Intent intent= new Intent(RecommendedSeeAll.this, CorseInfo.class); intent.putExtra("courseid", Mainitems.get(i).getCourseid()); intent.putExtra("coursename" ,Mainitems.get(i).getCourseName()); startActivity(intent); } }); */ } /* AdapterView.OnItemClickListener SeeAllDetailsGridViewlistner= new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Intent intent= new Intent(RecommendedSeeAll.this, CorseInfo.class); intent.putExtra("courseid", Mainitems.get(i).getCourseid()); intent.putExtra("coursename" ,Mainitems.get(i).getCourseName()); startActivity(intent); } };*/ /*public class SearchCourseAsyncTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... voids) { getRecommendedSearchDetails(voids[0],Integer.parseInt(voids[1])); return null; } }*/ View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View v) { if (editTextSearch.getVisibility() == View.VISIBLE && editTextSearch.length() > 0) { edittextValue = "c.coursename like '%" + editTextSearch.getText().toString() + "%'"; imageViewBackIcon.setVisibility(View.VISIBLE); /* recommendedMainitems = new ArrayList(); recommendedMainitems.clear();*/ searchText = "1=1"; Mainitems.clear(); editTextSearch.setText(""); searchPageSize = 1; searchMainArray.clear(); searchMainArray = new ArrayList<>(); Mainitems = new ArrayList<RecommendedGetSet>(); Mainitems.clear(); searchMainArray = new ArrayList<RecommendedGetSet>(); //if (edittextValue.length() > 0) { // } // textViewHeading.setVisibility(View.VISIBLE); textViewHeading2.setVisibility(View.VISIBLE); editTextSearch.setVisibility(View.GONE); imageViewSearchIcon.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_search_white)); // CommonMethods.hideKeyboard(RecommendedSeeAll.this, (RecommendedSeeAll.this).getCurrentFocus()); //getSubScriberSearchDetails(edittextValue); } else { imageViewSearchIcon.setImageDrawable(getResources().getDrawable(R.drawable.ic_clear_black_white)); textViewHeading2.setVisibility(View.INVISIBLE); editTextSearch.setVisibility(View.VISIBLE); imageViewBackIcon.setVisibility(View.GONE); searchMainArray = new ArrayList<>(); Mainitems = new ArrayList<>(); searchText="1=1"; editTextSearch.setText(""); editTextSearch.requestFocus(); CommonMethods.showKeyboard(RecommendedSeeAll.this, (RecommendedSeeAll.this).getCurrentFocus()); imageViewSearchIcon.setOnClickListener(finishSearchlistener); // getSubScriberDetails(); } } }; private View.OnClickListener finishSearchlistener = new View.OnClickListener() { @Override public void onClick(View v) { try { CommonMethods.hideKeyboard(RecommendedSeeAll.this, (RecommendedSeeAll.this).getCurrentFocus()); textViewHeading2.setVisibility(View.VISIBLE); editTextSearch.setVisibility(View.INVISIBLE); imageViewBackIcon.setVisibility(View.VISIBLE); editTextSearch.setText(""); pageSize = 1; searchMainArray = new ArrayList<>(); Mainitems = new ArrayList<>(); searchText = "1=1"; if(isFrom.equals("ontextchanged")){ } else { //CommonMethods.showKeyboard(ExploreClass.this,(ExploreClass.this).getCurrentFocus()); getRecommendedDetails(searchText, pageSize); } // iamgeViewNavigationdrawer.setVisibility(View.GONE); //drawerToggle.setDrawerIndicatorEnabled(true); imageViewSearchIcon.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_search_white)); imageViewSearchIcon.setOnClickListener(onClickListener); } catch (Exception e) { e.printStackTrace(); } } }; public void getRecommendedSearchDetails(String edittextValue, int searchPageSize, final String fromScroll) { try { recommendeditems = new ArrayList<>(); textViewRecommandedNoCourseFound.setVisibility(View.GONE); //detailsProgressBar.setVisibility(View.VISIBLE); // progressbarLoadLandingDetails.setVisibility(View.VISIBLE); //{"action":"getsubcribedcourses","userid":"11"/*,"courseid":"4"*/} JSONObject sendObject = new JSONObject(); sendObject.put("action", "getrecommendedcourses"); sendObject.put("userid", CommonMethods.userid); sendObject.put("wherecondition", edittextValue); sendObject.put("pagesize", "5"); sendObject.put("pagenumber", String.valueOf(searchPageSize)); Log.i("the request is ", sendObject.toString()); if (!loading) { progressbarMoreLoadLandingDetails.setVisibility(View.GONE); } else { } if (searchPageSize == 1) { progressbarMoreLoadLandingDetails.setVisibility(View.GONE); detailsProgressBar.setVisibility(View.VISIBLE); } else if (searchPageSize > 1) { progressbarMoreLoadLandingDetails.setVisibility(View.VISIBLE); detailsProgressBar.setVisibility(View.GONE); } if(fromScroll.equals("0")){ searchMainArray = new ArrayList<>(); searchMainArray.clear(); Log.e("searchMainArray","searchMainArray is cleared"); } RequestQueue requestQueue = Volley.newRequestQueue(RecommendedSeeAll.this); CustomRequest customres = new CustomRequest(Request.Method.POST, CommonMethods.url, sendObject, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.i("the request is ", response.toString()); try { if(fromScroll.equals("0")){ searchMainArray = new ArrayList<>(); searchMainArray.clear(); Log.e("searchMainArray","searchMainArray is cleared"); } recommendeditems = new ArrayList<>(); recommendeditems.clear(); String browseCatalogueitems = response.getString("RecommendedCourses"); JSONArray browseArray = new JSONArray(browseCatalogueitems); for (int i = 0; i < browseArray.length(); i++) { RecommendedGetSet recommendedGetSet = new RecommendedGetSet(); recommendedGetSet.setCourseImage(browseArray.getJSONObject(i).getString("courseimage")); recommendedGetSet.setCourseid(browseArray.getJSONObject(i).getString("courseid")); recommendedGetSet.setCourseName(browseArray.getJSONObject(i).getString("coursename")); recommendedGetSet.setCoursePrice(browseArray.getJSONObject(i).getString("totalfees")); recommendedGetSet.setCourseUsers(browseArray.getJSONObject(i).getString("noofsubcribers")); recommendedGetSet.setRating(browseArray.getJSONObject(i).getString("rating")); recommendeditems.add(recommendedGetSet); } detailsProgressBar.setVisibility(View.GONE); //Mainitems.clear(); searchMainArray.addAll(recommendeditems); if(searchMainArray.size()==0){ textViewRecommandedNoCourseFound.setVisibility(View.VISIBLE); } progressbarMoreLoadLandingDetails.setVisibility(View.GONE); // gridViweBrouwseCatalog.setAdapter(new GridAdapterClass(LoginMainPage.this, categoryItemsList, "exploreclass")); if (!loading) { Log.e("searchMainArray size", "" + searchMainArray.size()); SeeAllDetailsGridView.setAdapter(null); adapter = new RecommendedAdapter(RecommendedSeeAll.this, searchMainArray); SeeAllDetailsGridView.setAdapter(adapter); // SeeAllDetailsGridView.setOnItemClickListener(SeeAllDetailsGridViewlistner); if (searchMainArray.size() > 1) { // adapter=new RecommendedAdapter(RecommendedSeeAll.this, Mainitems); // SeeAllDetailsGridView.setAdapter(adapter); loading = false; SeeAllDetailsGridView.setOnScrollListener(scrollListener); } else { // adapter=new RecommendedAdapter(RecommendedSeeAll.this, Mainitems); // SeeAllDetailsGridView.setAdapter(adapter); loading = false; SeeAllDetailsGridView.setOnScrollListener(null); } progressbarMoreLoadLandingDetails.setVisibility(View.GONE); detailsProgressBar.setVisibility(View.GONE); } else { runOnUiThread( new Runnable() { @Override public void run() { Log.v("the boolean value is ", String.valueOf(loading)); try { loading = false; adapter.notifyDataSetInvalidated(); adapter.notifyDataSetChanged(); } catch (Exception w) { w.printStackTrace(); } } }); } if (recommendeditems.size() <= 1) { SeeAllDetailsGridView.setOnScrollListener(null); detailsProgressBar.setVisibility(View.GONE); progressbarMoreLoadLandingDetails.setVisibility(View.GONE); loading = false; } } catch (Exception e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { detailsProgressBar.setVisibility(View.GONE); error.printStackTrace(); } }); requestQueue.add(customres); } catch (Exception e) { e.printStackTrace(); } } public void getRecommendedDetails(final String searchText, final int pageSize) { try { searchMainArray = new ArrayList<>(); searchMainArray.clear(); recommendeditems = new ArrayList<>(); recommendedMainitems = new ArrayList<>(); recommendeditems = new ArrayList<>(); textViewRecommandedNoCourseFound.setVisibility(View.GONE); detailsProgressBar.setVisibility(View.VISIBLE); // progressbarLoadLandingDetails.setVisibility(View.VISIBLE); //{"action":"getsubcribedcourses","userid":"11"/*,"courseid":"4"*/} JSONObject sendObject = new JSONObject(); sendObject.put("action", "getrecommendedcourses"); sendObject.put("userid", CommonMethods.userid); sendObject.put("wherecondition", searchText); sendObject.put("pagesize", "5"); sendObject.put("pagenumber", String.valueOf(pageSize)); Log.i("the request is ", sendObject.toString()); if (!loading) { progressbarMoreLoadLandingDetails.setVisibility(View.GONE); } else { if (pageSize == 1) { //progressbarMoreLoadLandingDetails.setVisibility(View.VISIBLE); detailsProgressBar.setVisibility(View.VISIBLE); } else if (pageSize > 1) { // progressbarMoreLoadLandingDetails.setVisibility(View.GONE); detailsProgressBar.setVisibility(View.GONE); } } RequestQueue requestQueue = Volley.newRequestQueue(RecommendedSeeAll.this); CustomRequest customres = new CustomRequest(Request.Method.POST, CommonMethods.url, sendObject, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.i("the request is ", response.toString()); try { recommendeditems = new ArrayList<>(); recommendeditems.clear(); String browseCatalogueitems = response.getString("RecommendedCourses"); JSONArray browseArray = new JSONArray(browseCatalogueitems); for (int i = 0; i < browseArray.length(); i++) { RecommendedGetSet recommendedGetSet = new RecommendedGetSet(); recommendedGetSet.setCourseImage(browseArray.getJSONObject(i).getString("courseimage")); recommendedGetSet.setCourseid(browseArray.getJSONObject(i).getString("courseid")); recommendedGetSet.setCourseName(browseArray.getJSONObject(i).getString("coursename")); recommendedGetSet.setCoursePrice(browseArray.getJSONObject(i).getString("totalfees")); recommendedGetSet.setCourseUsers(browseArray.getJSONObject(i).getString("noofsubcribers")); recommendedGetSet.setRating(browseArray.getJSONObject(i).getString("rating")); recommendeditems.add(recommendedGetSet); } detailsProgressBar.setVisibility(View.GONE); Mainitems.addAll(recommendeditems); progressbarMoreLoadLandingDetails.setVisibility(View.GONE); if(Mainitems.size()==0){ textViewRecommandedNoCourseFound.setVisibility(View.VISIBLE); } // gridViweBrouwseCatalog.setAdapter(new GridAdapterClass(LoginMainPage.this, categoryItemsList, "exploreclass")); if (!loading) { Log.e("Mainitems size", "" + Mainitems.size()); adapter = new RecommendedAdapter(RecommendedSeeAll.this, Mainitems); SeeAllDetailsGridView.setAdapter(adapter); // SeeAllDetailsGridView.setOnItemClickListener(SeeAllDetailsGridViewlistner); if (recommendeditems.size() > 1) { // adapter=new RecommendedAdapter(RecommendedSeeAll.this, Mainitems); // SeeAllDetailsGridView.setAdapter(adapter); loading = false; SeeAllDetailsGridView.setOnScrollListener(scrollListener); } else { // adapter=new RecommendedAdapter(RecommendedSeeAll.this, Mainitems); // SeeAllDetailsGridView.setAdapter(adapter); loading = false; SeeAllDetailsGridView.setOnScrollListener(null); } progressbarMoreLoadLandingDetails.setVisibility(View.GONE); detailsProgressBar.setVisibility(View.GONE); } else { runOnUiThread(new Runnable() { @Override public void run() { Log.v("the boolean value is ", String.valueOf(loading)); try { loading = false; adapter.notifyDataSetInvalidated(); adapter.notifyDataSetChanged(); } catch (Exception w) { w.printStackTrace(); } } }); // progressbarMoreLoadLandingDetails.setVisibility(View.GONE); } if (recommendeditems.size() <= 1) { SeeAllDetailsGridView.setOnScrollListener(null); detailsProgressBar.setVisibility(View.GONE); progressbarMoreLoadLandingDetails.setVisibility(View.GONE); loading = false; } } catch (Exception e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (error instanceof NoConnectionError) { Log.v("error", error.toString()); Snackbar snackbar = Snackbar .make(coordinatorLayout, getApplicationContext().getResources().getString(R.string.no_internet), Snackbar.LENGTH_INDEFINITE) .setActionTextColor(Color.WHITE).setAction("RETRY", new View.OnClickListener() { @Override public void onClick(View view) { getRecommendedDetails(searchText, pageSize); } }); snackbar.show(); detailsProgressBar.setVisibility(View.GONE); error.printStackTrace(); } else { Log.v("error", error.toString()); Snackbar snackbar = Snackbar .make(coordinatorLayout, getApplicationContext().getResources().getString(R.string.tryagain), Snackbar.LENGTH_INDEFINITE) .setActionTextColor(Color.WHITE).setAction("RETRY", new View.OnClickListener() { @Override public void onClick(View view) { getRecommendedDetails(searchText, pageSize); } }); snackbar.show(); detailsProgressBar.setVisibility(View.GONE); error.printStackTrace(); } } }); requestQueue.add(customres); } catch (Exception e) { } } private AbsListView.OnScrollListener scrollListener = new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { /* Log.e("SeeAllDetailsGridView.getLastVisiblePosition()",""+SeeAllDetailsGridView.getLastVisiblePosition()); Log.e("SeeAllDetailsGridView.getAdapter().getCount() - 1",""+(SeeAllDetailsGridView.getAdapter().getCount() - 1)); Log.e("SeeAllDetailsGridView.getChildAt(SeeAllDetailsGridView.getChildCount() - 1).getBottom()",""+SeeAllDetailsGridView.getChildAt(SeeAllDetailsGridView.getChildCount() - 1).getBottom()); Log.e("SeeAllDetailsGridView.getHeight()",""+SeeAllDetailsGridView.getHeight());*/ /* if((SeeAllDetailsGridView.getLastVisiblePosition() == SeeAllDetailsGridView.getAdapter().getCount() - 1 && SeeAllDetailsGridView.getChildAt(SeeAllDetailsGridView.getChildCount() - 1).getBottom() <= SeeAllDetailsGridView.getHeight())) { progressbarMoreLoadLandingDetails.setVisibility(View.VISIBLE); detailsProgressBar.setVisibility(View.GONE); pageSize++; Log.e("pagesize",""+pageSize); loading = true; getRecommendedDetails(searchText, pageSize); }*/ /* if (SeeAllDetailsGridView.getLastVisiblePosition() + 1 == totalItemCount && !loading) { progressbarMoreLoadLandingDetails.setVisibility(View.VISIBLE); detailsProgressBar.setVisibility(View.GONE); pageSize++; Log.e("pagesize",""+pageSize); loading = true; getRecommendedDetails(searchText, pageSize); } else { loading = false; }*/ int lastInScreen = firstVisibleItem + visibleItemCount; if ((lastInScreen == totalItemCount) && !(loading)) { progressbarMoreLoadLandingDetails.setVisibility(View.VISIBLE); detailsProgressBar.setVisibility(View.GONE); if (editTextSearch.length() > 0) { searchPageSize++; loading = true; getRecommendedSearchDetails("c.coursename like '%" + editTextSearch.getText().toString() + "%'", searchPageSize,"1"); } else { pageSize++; Log.e("pagesize", "" + pageSize); loading = true; getRecommendedDetails("1=1", pageSize); } } } }; /*private AbsListView.OnScrollListener scrollListenerInSearch = new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { int lastInScreen = firstVisibleItem + visibleItemCount; if ((lastInScreen == totalItemCount) && !(loading)) { progressbarMoreLoadLandingDetails.setVisibility(View.VISIBLE); detailsProgressBar.setVisibility(View.GONE); searchPageSize++; Log.e("pagesize", "" + pageSize); loading = true; getRecommendedSearchDetails(searchText, pageSize); } } };*/ }
3e0cd43c8a6b8789f452bc7afaae853fadcdf67f
2,441
java
Java
src/test/java/com/test/FindRouteServiceTest.java
patrickpycheung/coding-puzzles
cf38c5658c53ab991e117fd26de9894fa82fc96a
[ "MIT" ]
null
null
null
src/test/java/com/test/FindRouteServiceTest.java
patrickpycheung/coding-puzzles
cf38c5658c53ab991e117fd26de9894fa82fc96a
[ "MIT" ]
null
null
null
src/test/java/com/test/FindRouteServiceTest.java
patrickpycheung/coding-puzzles
cf38c5658c53ab991e117fd26de9894fa82fc96a
[ "MIT" ]
null
null
null
24.41
67
0.741909
5,445
package com.test; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.LinkedList; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import com.test.service.findRouteService.FindRouteService; import com.test.service.findRouteService.Graph; import com.test.service.findRouteService.Node; @SpringBootTest public class FindRouteServiceTest { @Autowired private FindRouteService findRouteService; @Test public void shoudBeAbleToDetermineIfARouteExistBetweenTwoNodes() { // Input Node node01 = new Node(1); Node node02 = new Node(2); Node node03 = new Node(3); Node node04 = new Node(4); Node node05 = new Node(5); Node node06 = new Node(6); Node node07 = new Node(7); Node node08 = new Node(8); Node node09 = new Node(9); // Configure the node network LinkedList<Node> nodeList01 = new LinkedList<>(); nodeList01.add(node02); nodeList01.add(node04); LinkedList<Node> nodeList02 = new LinkedList<>(); nodeList02.add(node03); nodeList02.add(node05); LinkedList<Node> nodeList03 = new LinkedList<>(); nodeList03.add(node06); LinkedList<Node> nodeList04 = new LinkedList<>(); nodeList04.add(node05); nodeList04.add(node07); LinkedList<Node> nodeList05 = new LinkedList<>(); nodeList05.add(node06); nodeList05.add(node08); LinkedList<Node> nodeList06 = new LinkedList<>(); nodeList06.add(node09); LinkedList<Node> nodeList07 = new LinkedList<>(); nodeList07.add(node08); LinkedList<Node> nodeList08 = new LinkedList<>(); nodeList08.add(node09); node01.setNextNodes(nodeList01); node02.setNextNodes(nodeList02); node03.setNextNodes(nodeList03); node04.setNextNodes(nodeList04); node05.setNextNodes(nodeList05); node06.setNextNodes(nodeList06); node07.setNextNodes(nodeList07); node08.setNextNodes(nodeList08); // Build graph LinkedList<Node> allNodeList = new LinkedList<>(); allNodeList.add(node01); allNodeList.add(node02); allNodeList.add(node03); allNodeList.add(node04); allNodeList.add(node05); allNodeList.add(node06); allNodeList.add(node07); allNodeList.add(node08); allNodeList.add(node09); Graph graph = new Graph(); graph.setNodes(allNodeList); // Actual result boolean result = findRouteService.search(graph, node01, node09); // Assertion assertTrue(result); } }
3e0cd497c4353db0a5eaaf8a5c18f1395cca5b6f
2,502
java
Java
common/src/main/java/com/rabtman/common/utils/RxUtil.java
LiycJia/AcgClub
6e48b621b350cd84f195f9acbdeeb2b747d60ced
[ "MIT" ]
1
2018-04-21T11:26:20.000Z
2018-04-21T11:26:20.000Z
common/src/main/java/com/rabtman/common/utils/RxUtil.java
LiycJia/AcgClub
6e48b621b350cd84f195f9acbdeeb2b747d60ced
[ "MIT" ]
null
null
null
common/src/main/java/com/rabtman/common/utils/RxUtil.java
LiycJia/AcgClub
6e48b621b350cd84f195f9acbdeeb2b747d60ced
[ "MIT" ]
null
null
null
30.512195
104
0.618305
5,446
package com.rabtman.common.utils; import io.reactivex.BackpressureStrategy; import io.reactivex.Completable; import io.reactivex.CompletableTransformer; import io.reactivex.Flowable; import io.reactivex.FlowableEmitter; import io.reactivex.FlowableOnSubscribe; import io.reactivex.FlowableTransformer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; public class RxUtil { /** * Flowable线程切换简化 */ public static <T> FlowableTransformer<T, T> rxSchedulerHelper() { //compose简化线程 return new FlowableTransformer<T, T>() { @Override public Flowable<T> apply(Flowable<T> observable) { return observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } }; } /** * Completable线程切换简化 */ public static CompletableTransformer completableSchedulerHelper() { return new CompletableTransformer() { @Override public Completable apply(Completable observable) { return observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } }; } /** * 统一返回结果处理 * @param <T> * @return */ /*public static <T> FlowableTransformer<GoldHttpResponse<T>, T> handleGoldResult() { //compose判断结果 return new FlowableTransformer<GoldHttpResponse<T>, T>() { @Override public Flowable<T> apply(Flowable<GoldHttpResponse<T>> httpResponseFlowable) { return httpResponseFlowable.flatMap(new Function<GoldHttpResponse<T>, Flowable<T>>() { @Override public Flowable<T> apply(GoldHttpResponse<T> tGoldHttpResponse) { if(tGoldHttpResponse.getResults() != null) { return createData(tGoldHttpResponse.getResults()); } else { return Flowable.error(new ApiException("服务器返回error")); } } }); } }; }*/ /** * 生成Flowable */ public static <T> Flowable<T> createData(final T t) { return Flowable.create(new FlowableOnSubscribe<T>() { @Override public void subscribe(FlowableEmitter<T> emitter) throws Exception { try { emitter.onNext(t); emitter.onComplete(); } catch (Exception e) { emitter.onError(e); } } }, BackpressureStrategy.BUFFER); } }
3e0cd65e4c046053c1b1c00107e482a60393b296
3,423
java
Java
src/main/java/top/misec/task/ServerPush.java
kiki20567/JunzhouLiu
15eb977180e81eef91f0775cb110753a1b7de079
[ "MIT" ]
42
2021-05-05T05:39:04.000Z
2022-02-01T08:48:29.000Z
src/main/java/top/misec/task/ServerPush.java
kiki20567/JunzhouLiu
15eb977180e81eef91f0775cb110753a1b7de079
[ "MIT" ]
4
2021-08-13T15:20:25.000Z
2021-12-27T13:07:24.000Z
src/main/java/top/misec/task/ServerPush.java
kiki20567/JunzhouLiu
15eb977180e81eef91f0775cb110753a1b7de079
[ "MIT" ]
132
2021-03-31T09:03:53.000Z
2022-02-02T05:52:03.000Z
32.6
121
0.552439
5,447
package top.misec.task; import com.google.gson.JsonObject; import lombok.extern.log4j.Log4j2; import top.misec.apiquery.ApiList; import top.misec.login.ServerVerify; import top.misec.utils.HttpUtil; import top.misec.utils.LoadFileResource; /** * @author @JunzhouLiu @Kurenai * @create 2020/10/21 17:39 */ @Log4j2 public class ServerPush { private String pushToken = null; public void pushServerChan(String text, String desp) { String url; String pushBody; if (pushToken == null) { pushToken = ServerVerify.getFtkey(); } if (pushToken.contains("SCU")) { url = ApiList.ServerPush + pushToken + ".send"; pushBody = "text=" + text + "&desp=" + desp; log.info("采用旧版server酱推送渠道推送"); } else { url = ApiList.ServerPushV2 + pushToken + ".send"; pushBody = "title=" + text + "&desp=" + desp; log.info("采用Turbo版server酱推送渠道推送"); } int retryTimes = 3; while (retryTimes > 0) { retryTimes--; try { JsonObject jsonObject = HttpUtil.doPost(url, pushBody); if (jsonObject.get("code").getAsInt() == 0 || "success".equals(jsonObject.get("errmsg").getAsString())) { log.info("任务状态推送成功"); break; } else { log.info("任务状态推送失败,开始第{}次重试", 3 - retryTimes); log.debug(jsonObject); } } catch (Exception e) { e.printStackTrace(); } } } public static void doServerPush() { if (ServerVerify.getFtkey() != null && ServerVerify.getChatId() == null) { ServerPush serverPush = new ServerPush(); log.info("Server酱旧版推送渠道即将下线,请前往[sct.ftqq.com](http://sct.ftqq.com/)使用Turbo版本的推送Key"); serverPush.pushServerChan("BILIBILI-HELPER任务简报", LoadFileResource.loadFile("logs/daily.log")); log.info("本次执行推送日志到微信"); } else if (ServerVerify.getFtkey() != null && ServerVerify.getChatId() != null) { ServerPush serverPush = new ServerPush(); serverPush.pushTelegramMsg("BILIBILI-HELPER任务简报\n" + LoadFileResource.loadFile("logs/daily.log")); log.info("本次执行推送日志到Telegram"); } else { log.info("未配置server酱,本次执行不推送日志到微信"); log.info("未配置Telegram,本次执行不推送日志到Telegram"); } } private void pushTelegramMsg(String text) { String url = ApiList.ServerPushTelegram + ServerVerify.getFtkey() + "/sendMessage"; String pushBody = "chat_id=" + ServerVerify.getChatId() + "&text=" + text; int retryTimes = 3; while (retryTimes > 0) { retryTimes--; try { JsonObject jsonObject = HttpUtil.doPost(url, pushBody); if (jsonObject != null && "true".equals(jsonObject.get("ok").getAsString())) { log.info("任务状态推送Telegram成功"); break; } else { log.info("任务状态推送Telegram失败,开始第{}次重试", 3 - retryTimes); } } catch (Exception e) { e.printStackTrace(); } } } public void addOtherMsg(String msg) { log.info(msg); } public void setPushToken(String pushToken) { this.pushToken = pushToken; } }
3e0cd6661d337cd2e472332193917f2c68d8ed0b
22,739
java
Java
dao/src/main/java/org/thingsboard/server/dao/user/UserServiceImpl.java
liuyibin23/iovVis
db1182a3c238e83e95258bd331a44ee8cfbbc629
[ "Apache-2.0", "MIT" ]
null
null
null
dao/src/main/java/org/thingsboard/server/dao/user/UserServiceImpl.java
liuyibin23/iovVis
db1182a3c238e83e95258bd331a44ee8cfbbc629
[ "Apache-2.0", "MIT" ]
null
null
null
dao/src/main/java/org/thingsboard/server/dao/user/UserServiceImpl.java
liuyibin23/iovVis
db1182a3c238e83e95258bd331a44ee8cfbbc629
[ "Apache-2.0", "MIT" ]
null
null
null
47.176349
160
0.653943
5,448
/** * Copyright © 2016-2018 The Thingsboard Authors * <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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.thingsboard.server.dao.user; import com.google.common.util.concurrent.ListenableFuture; import joptsimple.internal.Strings; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.page.TextPageData; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.security.UserCredentials; import org.thingsboard.server.dao.customer.CustomerDao; import org.thingsboard.server.dao.entity.AbstractEntityService; import org.thingsboard.server.dao.exception.DataValidationException; import org.thingsboard.server.dao.exception.IncorrectParameterException; import org.thingsboard.server.dao.model.ModelConstants; import org.thingsboard.server.dao.service.DataValidator; import org.thingsboard.server.dao.service.PaginatedRemover; import org.thingsboard.server.dao.tenant.TenantDao; import java.util.List; import java.util.UUID; import static org.thingsboard.server.dao.service.Validator.validateId; import static org.thingsboard.server.dao.service.Validator.validatePageLink; import static org.thingsboard.server.dao.service.Validator.validateString; @Service @Slf4j public class UserServiceImpl extends AbstractEntityService implements UserService { private static final int DEFAULT_TOKEN_LENGTH = 30; public static final String INCORRECT_USER_ID = "Incorrect userId "; public static final String INCORRECT_TENANT_ID = "Incorrect tenantId "; @Value("${security.user_login_case_sensitive:true}") private boolean userLoginCaseSensitive; @Autowired private UserDao userDao; @Autowired private UserCredentialsDao userCredentialsDao; @Autowired private TenantDao tenantDao; @Autowired private CustomerDao customerDao; @Override public User findUserByEmail(TenantId tenantId, String email) { log.trace("Executing findUserByEmail [{}]", email); validateString(email, "Incorrect email " + email); if (userLoginCaseSensitive) { return userDao.findByEmail(tenantId, email); } else { return userDao.findByEmail(tenantId, email.toLowerCase()); } } @Override public User findUserByFirstName(TenantId tenantId, String firstName) { log.trace("Executing findUserByFirstName [{}]", firstName); validateString(firstName, "Incorrect firstName " + firstName); return userDao.findUserByFirstName(firstName); } @Override public User findUserById(TenantId tenantId, UserId userId) { log.trace("Executing findUserById [{}]", userId); validateId(userId, INCORRECT_USER_ID + userId); return userDao.findById(tenantId, userId.getId()); } @Override public ListenableFuture<User> findUserByIdAsync(TenantId tenantId, UserId userId) { log.trace("Executing findUserByIdAsync [{}]", userId); validateId(userId, INCORRECT_USER_ID + userId); return userDao.findByIdAsync(tenantId, userId.getId()); } @Override public User saveUser(User user) { log.trace("Executing saveUser [{}]", user); userValidator.validate(user, User::getTenantId); if (user.getId() == null && !userLoginCaseSensitive) { user.setEmail(user.getEmail().toLowerCase()); } User savedUser = userDao.save(user.getTenantId(), user); if (user.getId() == null) { UserCredentials userCredentials = new UserCredentials(); userCredentials.setEnabled(false); userCredentials.setActivateToken(RandomStringUtils.randomAlphanumeric(DEFAULT_TOKEN_LENGTH)); userCredentials.setUserId(new UserId(savedUser.getUuidId())); userCredentialsDao.save(user.getTenantId(), userCredentials); } return savedUser; } @Override public UserCredentials findUserCredentialsByUserId(TenantId tenantId, UserId userId) { log.trace("Executing findUserCredentialsByUserId [{}]", userId); validateId(userId, INCORRECT_USER_ID + userId); return userCredentialsDao.findByUserId(tenantId, userId.getId()); } @Override public UserCredentials findUserCredentialsByActivateToken(TenantId tenantId, String activateToken) { log.trace("Executing findUserCredentialsByActivateToken [{}]", activateToken); validateString(activateToken, "Incorrect activateToken " + activateToken); return userCredentialsDao.findByActivateToken(tenantId, activateToken); } @Override public UserCredentials findUserCredentialsByResetToken(TenantId tenantId, String resetToken) { log.trace("Executing findUserCredentialsByResetToken [{}]", resetToken); validateString(resetToken, "Incorrect resetToken " + resetToken); return userCredentialsDao.findByResetToken(tenantId, resetToken); } @Override public UserCredentials saveUserCredentials(TenantId tenantId, UserCredentials userCredentials) { log.trace("Executing saveUserCredentials [{}]", userCredentials); userCredentialsValidator.validate(userCredentials, data -> tenantId); return userCredentialsDao.save(tenantId, userCredentials); } @Override public UserCredentials activateUserCredentials(TenantId tenantId, String activateToken, String password) { log.trace("Executing activateUserCredentials activateToken [{}], password [{}]", activateToken, password); validateString(activateToken, "Incorrect activateToken " + activateToken); validateString(password, "Incorrect password " + password); UserCredentials userCredentials = userCredentialsDao.findByActivateToken(tenantId, activateToken); if (userCredentials == null) { throw new IncorrectParameterException(String.format("Unable to find user credentials by activateToken [%s]", activateToken)); } if (userCredentials.isEnabled()) { throw new IncorrectParameterException("User credentials already activated"); } userCredentials.setEnabled(true); userCredentials.setActivateToken(null); userCredentials.setPassword(password); return saveUserCredentials(tenantId, userCredentials); } @Override public UserCredentials requestPasswordReset(TenantId tenantId, String email) { log.trace("Executing requestPasswordReset email [{}]", email); validateString(email, "Incorrect email " + email); User user = userDao.findByEmail(tenantId, email); if (user == null) { throw new IncorrectParameterException(String.format("Unable to find user by email [%s]", email)); } UserCredentials userCredentials = userCredentialsDao.findByUserId(tenantId, user.getUuidId()); if (!userCredentials.isEnabled()) { throw new IncorrectParameterException("Unable to reset password for inactive user"); } userCredentials.setResetToken(RandomStringUtils.randomAlphanumeric(DEFAULT_TOKEN_LENGTH)); return saveUserCredentials(tenantId, userCredentials); } @Override public void deleteUser(TenantId tenantId, UserId userId) { log.trace("Executing deleteUser [{}]", userId); validateId(userId, INCORRECT_USER_ID + userId); UserCredentials userCredentials = userCredentialsDao.findByUserId(tenantId, userId.getId()); userCredentialsDao.removeById(tenantId, userCredentials.getUuidId()); deleteEntityRelations(tenantId, userId); userDao.removeById(tenantId, userId.getId()); } @Override public TextPageData<User> findUsers(TextPageLink pageLink) { log.trace("Executing findUsers, pageLink [{}]", pageLink); validatePageLink(pageLink, "Incorrect page link " + pageLink); List<User> users = userDao.findUsers(pageLink); return new TextPageData<>(users, pageLink); } @Override public List<User> findUserByTenantIdAndAuthority(TenantId tenantId, Authority authority) { return userDao.findUserByTenantIdAndAuthority(tenantId.getId(), authority); } @Override public TextPageData<User> findTenantAdmins(TenantId tenantId, TextPageLink pageLink) { log.trace("Executing findTenantAdmins, tenantId [{}], pageLink [{}]", tenantId, pageLink); validateId(tenantId, INCORRECT_TENANT_ID + tenantId); validatePageLink(pageLink, "Incorrect page link " + pageLink); List<User> users = userDao.findTenantAdmins(tenantId.getId(), pageLink); return new TextPageData<>(users, pageLink); } @Override public void deleteTenantAdmins(TenantId tenantId) { log.trace("Executing deleteTenantAdmins, tenantId [{}]", tenantId); validateId(tenantId, INCORRECT_TENANT_ID + tenantId); tenantAdminsRemover.removeEntities(tenantId, tenantId); } @Override public TextPageData<User> findCustomerUsers(TenantId tenantId, CustomerId customerId, TextPageLink pageLink) { log.trace("Executing findUsersByTenantIdAndCustomerId, tenantId [{}], customerId [{}], pageLink [{}]", tenantId, customerId, pageLink); validateId(tenantId, INCORRECT_TENANT_ID + tenantId); validateId(customerId, "Incorrect customerId " + customerId); validatePageLink(pageLink, "Incorrect page link " + pageLink); List<User> users = userDao.findCustomerUsers(tenantId.getId(), customerId.getId(), pageLink); return new TextPageData<>(users, pageLink); } @Override public TextPageData<User> findCustomerUsers(CustomerId customerId, TextPageLink pageLink) { log.trace("Executing findUsersByTenantIdAndCustomerId, customerId [{}], pageLink [{}]", customerId, pageLink); validateId(customerId, "Incorrect customerId " + customerId); validatePageLink(pageLink, "Incorrect page link " + pageLink); List<User> users = userDao.findCustomerUsers(customerId.getId(), pageLink); return new TextPageData<>(users, pageLink); } // @Override // public List<User> findUsers() { // return userDao.findUsers(); // } @Override public TextPageData<User> findUsersByTenantIdAndCustomerId(TenantId tenantId, CustomerId customerId, TextPageLink pageLink) { log.trace("Executing findUsersByTenantIdAndCustomerId, customerId [{}]", customerId); validateId(customerId, "Incorrect customerId " + customerId); List<User> users = userDao.findUsersByTenantIdAndCustomerId(tenantId.getId(), customerId.getId(), pageLink); return new TextPageData<>(users, pageLink); } @Override public TextPageData<User> findTenantUsers(TenantId tenantId, TextPageLink pageLink) { log.trace("Executing findTenantUsers, TenantId [{}]", tenantId); validateId(tenantId, "Incorrect tenantId " + tenantId); List<User> users = userDao.findUsersByTenantId(tenantId.getId(), pageLink); return new TextPageData<>(users, pageLink); } @Override public void deleteCustomerUsers(TenantId tenantId, CustomerId customerId) { log.trace("Executing deleteCustomerUsers, customerId [{}]", customerId); validateId(tenantId, INCORRECT_TENANT_ID + tenantId); validateId(customerId, "Incorrect customerId " + customerId); customerUsersRemover.removeEntities(tenantId, customerId); } @Override public int countByTenantId(String tenantId) { return userDao.countTenant(tenantId); } @Override public int countByTenantIdAndCustomerId(String tenantId, String customerId) { return userDao.countCustomerUsers(tenantId, customerId); } @Override public int countTenantAdminByTenantId(String tenantId) { return userDao.countTenantAdmin(tenantId); } @Override public int countTenantUserByTenantId(String tenantId) { return userDao.countTenantUser(tenantId); } @Override public List<User> findUsersByFirstNameLikeAndLastNameLike(String firstName, String lastName) { return userDao.findUsersByFirstNameLikeAndLastNameLike(firstName, lastName); } @Override public List<User> findUsersByFirstNameLike(String firstName) { return userDao.findUsersByFirstNameLike(firstName); } @Override public User findFirstUserByCustomerId(CustomerId customerId) { return userDao.findFirstUserByCustomerId(customerId.getId()); } @Override public TextPageData<User> findUsersByAuthority(TenantId tenantId, CustomerId customerId, Authority authority, TextPageLink pageLink) { UUID tenantUUID; UUID customerUUID; if (tenantId == null || tenantId.getId() == null) { tenantUUID = null; } else { tenantUUID = tenantId.getId(); } if (customerId == null || customerId.getId() == null) { customerUUID = null; } else { customerUUID = customerId.getId(); } List<User> users = userDao.findUsersByAuthority(tenantUUID, customerUUID, authority, pageLink); return new TextPageData<>(users, pageLink); } private DataValidator<User> userValidator = new DataValidator<User>() { @Override protected void validateDataImpl(TenantId requestTenantId, User user) { if (StringUtils.isEmpty(user.getEmail())) { // throw new DataValidationException("User email should be specified!"); throw new ThingsboardException("User email should be specified!", ThingsboardErrorCode.USER_EMAIL_NOT_SPECIFIED); } if (Strings.isNullOrEmpty(user.getFirstName())) { throw new ThingsboardException("User name should be specified!", ThingsboardErrorCode.USER_NAME_NOT_SPECIFIED); } try { validateEmail(user.getEmail()); } catch (Exception e) { throw new ThingsboardException("Invalid email address format '" + user.getEmail() + "'!", ThingsboardErrorCode.USER_EMAIL_FORMAT_ERROR); } Authority authority = user.getAuthority(); if (authority == null) { throw new DataValidationException("User authority isn't defined!"); } TenantId tenantId = user.getTenantId(); if (tenantId == null) { tenantId = new TenantId(ModelConstants.NULL_UUID); user.setTenantId(tenantId); } CustomerId customerId = user.getCustomerId(); if (customerId == null) { customerId = new CustomerId(ModelConstants.NULL_UUID); user.setCustomerId(customerId); } switch (authority) { case SYS_ADMIN: if (!tenantId.getId().equals(ModelConstants.NULL_UUID) || !customerId.getId().equals(ModelConstants.NULL_UUID)) { throw new DataValidationException("System administrator can't be assigned neither to tenant nor to customer!"); } break; case TENANT_ADMIN: if (tenantId.getId().equals(ModelConstants.NULL_UUID)) { throw new DataValidationException("Tenant administrator should be assigned to tenant!"); } else if (!customerId.getId().equals(ModelConstants.NULL_UUID)) { throw new DataValidationException("Tenant administrator can't be assigned to customer!"); } break; case CUSTOMER_USER: if (tenantId.getId().equals(ModelConstants.NULL_UUID) || customerId.getId().equals(ModelConstants.NULL_UUID)) { throw new DataValidationException("Customer user should be assigned to customer!"); } break; default: break; } User existentUserWithFirstName = findUserByFirstName(tenantId, user.getFirstName()); if (existentUserWithFirstName != null && !isSameData(existentUserWithFirstName, user)) { throw new ThingsboardException("User with firstName '" + user.getFirstName() + "' " + " already present in database!", ThingsboardErrorCode.USER_NAME_ALREADY_PRESENT); } User existentUserWithEmail = findUserByEmail(tenantId, user.getEmail()); if (existentUserWithEmail != null && !isSameData(existentUserWithEmail, user)) { throw new ThingsboardException("User with email '" + user.getEmail() + "' " + " already present in database!", ThingsboardErrorCode.USER_EMAIL_ALREADY_PRESENT); // throw new DataValidationException("User with email '" + user.getEmail() + "' " // + " already present in database!"); } if (!tenantId.getId().equals(ModelConstants.NULL_UUID)) { Tenant tenant = tenantDao.findById(tenantId, user.getTenantId().getId()); if (tenant == null) { throw new DataValidationException("User is referencing to non-existent tenant!"); } } if (!customerId.getId().equals(ModelConstants.NULL_UUID)) { Customer customer = customerDao.findById(tenantId, user.getCustomerId().getId()); if (customer == null) { throw new DataValidationException("User is referencing to non-existent customer!"); } else if (!customer.getTenantId().getId().equals(tenantId.getId())) { throw new DataValidationException("User can't be assigned to customer from different tenant!"); } } } }; private DataValidator<UserCredentials> userCredentialsValidator = new DataValidator<UserCredentials>() { @Override protected void validateCreate(TenantId tenantId, UserCredentials userCredentials) { throw new IncorrectParameterException("Creation of new user credentials is prohibited."); } @Override protected void validateDataImpl(TenantId tenantId, UserCredentials userCredentials) { if (userCredentials.getUserId() == null) { throw new DataValidationException("User credentials should be assigned to user!"); } if (userCredentials.isEnabled()) { if (StringUtils.isEmpty(userCredentials.getPassword())) { throw new DataValidationException("Enabled user credentials should have password!"); } if (StringUtils.isNotEmpty(userCredentials.getActivateToken())) { throw new DataValidationException("Enabled user credentials can't have activate token!"); } } UserCredentials existingUserCredentialsEntity = userCredentialsDao.findById(tenantId, userCredentials.getId().getId()); if (existingUserCredentialsEntity == null) { throw new DataValidationException("Unable to update non-existent user credentials!"); } User user = findUserById(tenantId, userCredentials.getUserId()); if (user == null) { throw new DataValidationException("Can't assign user credentials to non-existent user!"); } } }; private PaginatedRemover<TenantId, User> tenantAdminsRemover = new PaginatedRemover<TenantId, User>() { @Override protected List<User> findEntities(TenantId tenantId, TenantId id, TextPageLink pageLink) { return userDao.findTenantAdmins(id.getId(), pageLink); } @Override protected void removeEntity(TenantId tenantId, User entity) { deleteUser(tenantId, new UserId(entity.getUuidId())); } }; private PaginatedRemover<CustomerId, User> customerUsersRemover = new PaginatedRemover<CustomerId, User>() { @Override protected List<User> findEntities(TenantId tenantId, CustomerId id, TextPageLink pageLink) { return userDao.findCustomerUsers(tenantId.getId(), id.getId(), pageLink); } @Override protected void removeEntity(TenantId tenantId, User entity) { deleteUser(tenantId, new UserId(entity.getUuidId())); } }; }
3e0cd855a6612726944a645514873e7b4404c111
2,215
java
Java
opaf-framework/src/main/java/inescid/opaf/framework/CollectorOfAsyncResponses.java
nfreire/Open-Data-Acquisition-Lab
171460d4612deaa0d16ae41c4f550c7527825c68
[ "Apache-2.0" ]
null
null
null
opaf-framework/src/main/java/inescid/opaf/framework/CollectorOfAsyncResponses.java
nfreire/Open-Data-Acquisition-Lab
171460d4612deaa0d16ae41c4f550c7527825c68
[ "Apache-2.0" ]
4
2020-03-04T21:44:46.000Z
2021-12-09T19:48:41.000Z
opaf-framework/src/main/java/inescid/opaf/framework/CollectorOfAsyncResponses.java
nfreire/Open-Data-Acquisition-Framework
171460d4612deaa0d16ae41c4f550c7527825c68
[ "Apache-2.0" ]
null
null
null
25.170455
107
0.638375
5,449
package inescid.opaf.framework; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeUnit; public class CollectorOfAsyncResponses implements Runnable { private static final int MAX_HANDLINGS = 10; private static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(CollectorOfAsyncResponses.class); private Thread running; private boolean close; private CrawlingSession session; private ResponseHandler handler; Throwable runError=null; private final Set<FetchRequest> handling=Collections.synchronizedSet(new HashSet<>()); protected CollectorOfAsyncResponses(CrawlingSession session, ResponseHandler handler) { super(); this.session = session; this.handler = handler; } protected void close() { this.close=true; } @Override public void run() { try { running=Thread.currentThread(); while(!close) { FetchRequest fetch=null; try { fetch = session.takeAsyncResult(30, TimeUnit.SECONDS); } catch (InterruptedException e) { close=true; } if(fetch!=null) { final FetchRequest fetchFinal=fetch; while(handling.size()>MAX_HANDLINGS) { Thread.sleep(100); } handling.add(fetchFinal); new Thread(new Runnable() { @Override public void run() { try { handler.handle(fetchFinal); } catch (Throwable e) { log.error(fetchFinal.getUrl(), e); }finally{ handling.remove(fetchFinal); try { fetchFinal.getResponse().close(); } catch (Throwable e) { log.error(fetchFinal.getUrl(), e); } } } }).start(); } } //wait for handlers to finish while(!handling.isEmpty()) { Thread.sleep(500); log.debug("Waiting to exit. Responses pending: "+handling.size()); } } catch (Throwable e) { runError=e; log.error("Error in Response Collector. Exiting collector", e); } log.debug("Exiting "+getClass().getSimpleName()); } public Thread getRunning() { return running; } public Throwable getRunError() { return runError; } }
3e0cd8973e761faea98a251dab46b4f1017e8568
2,917
java
Java
apps/linkprops/src/main/java/org/onosproject/linkprops/LinkPropApp.java
mary-grace/onos
c0e351f8b84537bb7562e148d4cb2b9f06e8a727
[ "Apache-2.0" ]
1,091
2015-01-06T11:10:40.000Z
2022-03-30T09:09:05.000Z
apps/linkprops/src/main/java/org/onosproject/linkprops/LinkPropApp.java
mary-grace/onos
c0e351f8b84537bb7562e148d4cb2b9f06e8a727
[ "Apache-2.0" ]
39
2015-02-13T19:58:32.000Z
2022-03-02T02:38:07.000Z
apps/linkprops/src/main/java/org/onosproject/linkprops/LinkPropApp.java
mary-grace/onos
c0e351f8b84537bb7562e148d4cb2b9f06e8a727
[ "Apache-2.0" ]
914
2015-01-05T19:42:35.000Z
2022-03-30T09:25:18.000Z
33.528736
77
0.71649
5,450
/* * Copyright 2017-present Open Networking Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.linkprops; import com.google.common.collect.ImmutableList; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.onosproject.ui.UiExtension; import org.onosproject.ui.UiExtensionService; import org.onosproject.ui.UiMessageHandlerFactory; import org.onosproject.ui.UiTopoOverlayFactory; import org.onosproject.ui.UiView; import org.onosproject.ui.UiViewHidden; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; /** * Skeletal ONOS UI Topology-Overlay application component. */ @Component(immediate = true) public class LinkPropApp { private static final ClassLoader CL = LinkPropApp.class.getClassLoader(); private static final String VIEW_ID = "lpTopov"; private final Logger log = LoggerFactory.getLogger(getClass()); @Reference(cardinality = ReferenceCardinality.MANDATORY) protected UiExtensionService uiExtensionService; // List of application views private final List<UiView> uiViews = ImmutableList.of( new UiViewHidden(VIEW_ID) ); // Factory for UI message handlers private final UiMessageHandlerFactory messageHandlerFactory = () -> ImmutableList.of( new LinkPropsTopovMessageHandler() ); // Factory for UI topology overlays private final UiTopoOverlayFactory topoOverlayFactory = () -> ImmutableList.of( new LinkPropsTopovOverlay() ); // Application UI extension protected UiExtension extension = new UiExtension.Builder(CL, uiViews) .resourcePath(VIEW_ID) .messageHandlerFactory(messageHandlerFactory) .topoOverlayFactory(topoOverlayFactory) .build(); @Activate protected void activate() { uiExtensionService.register(extension); log.info("Started"); } @Deactivate protected void deactivate() { uiExtensionService.unregister(extension); log.info("Stopped"); } }
3e0cda4aedbddeb3bf3dd4b0e5626f4b3ceb3916
6,327
java
Java
extensions-contrib/virtual-columns/src/test/java/org/apache/druid/segment/MapVirtualColumnGroupByTest.java
lightghli/druid
a7924a9dee055aaaa26c46af93e493f4feb04c71
[ "Apache-2.0" ]
5,813
2015-01-01T14:14:54.000Z
2018-07-06T11:13:03.000Z
extensions-contrib/virtual-columns/src/test/java/org/apache/druid/segment/MapVirtualColumnGroupByTest.java
lightghli/druid
a7924a9dee055aaaa26c46af93e493f4feb04c71
[ "Apache-2.0" ]
4,320
2015-01-02T18:37:24.000Z
2018-07-06T14:51:01.000Z
extensions-contrib/virtual-columns/src/test/java/org/apache/druid/segment/MapVirtualColumnGroupByTest.java
lightghli/druid
a7924a9dee055aaaa26c46af93e493f4feb04c71
[ "Apache-2.0" ]
1,601
2015-01-05T05:37:05.000Z
2018-07-06T11:13:04.000Z
36.154286
110
0.703177
5,451
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.druid.segment; import com.google.common.collect.ImmutableList; import org.apache.druid.collections.DefaultBlockingPool; import org.apache.druid.collections.StupidPool; import org.apache.druid.data.input.MapBasedRow; import org.apache.druid.jackson.DefaultObjectMapper; import org.apache.druid.java.util.common.DateTimes; import org.apache.druid.java.util.common.Intervals; import org.apache.druid.java.util.common.granularity.Granularities; import org.apache.druid.query.DruidProcessingConfig; import org.apache.druid.query.QueryPlus; import org.apache.druid.query.QueryRunner; import org.apache.druid.query.QueryRunnerTestHelper; import org.apache.druid.query.TableDataSource; import org.apache.druid.query.aggregation.CountAggregatorFactory; import org.apache.druid.query.dimension.DefaultDimensionSpec; import org.apache.druid.query.groupby.GroupByQuery; import org.apache.druid.query.groupby.GroupByQueryConfig; import org.apache.druid.query.groupby.GroupByQueryQueryToolChest; import org.apache.druid.query.groupby.GroupByQueryRunnerFactory; import org.apache.druid.query.groupby.ResultRow; import org.apache.druid.query.groupby.strategy.GroupByStrategySelector; import org.apache.druid.query.groupby.strategy.GroupByStrategyV2; import org.apache.druid.query.spec.MultipleIntervalSegmentSpec; import org.apache.druid.segment.incremental.IncrementalIndex; import org.apache.druid.testing.InitializedNullHandlingTest; import org.apache.druid.timeline.SegmentId; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; import java.util.stream.Collectors; public class MapVirtualColumnGroupByTest extends InitializedNullHandlingTest { @Rule public ExpectedException expectedException = ExpectedException.none(); private QueryRunner<ResultRow> runner; @Before public void setup() throws IOException { final IncrementalIndex incrementalIndex = MapVirtualColumnTestBase.generateIndex(); final GroupByStrategySelector strategySelector = new GroupByStrategySelector( GroupByQueryConfig::new, null, new GroupByStrategyV2( new DruidProcessingConfig() { @Override public String getFormatString() { return null; } @Override public int intermediateComputeSizeBytes() { return 10 * 1024 * 1024; } @Override public int getNumMergeBuffers() { return 1; } @Override public int getNumThreads() { return 1; } }, GroupByQueryConfig::new, new StupidPool<>("map-virtual-column-groupby-test", () -> ByteBuffer.allocate(1024)), new DefaultBlockingPool<>(() -> ByteBuffer.allocate(1024), 1), new DefaultObjectMapper(), QueryRunnerTestHelper.NOOP_QUERYWATCHER ) ); final GroupByQueryRunnerFactory factory = new GroupByQueryRunnerFactory( strategySelector, new GroupByQueryQueryToolChest(strategySelector) ); runner = QueryRunnerTestHelper.makeQueryRunner( factory, SegmentId.dummy("index"), new IncrementalIndexSegment(incrementalIndex, SegmentId.dummy("index")), "incremental" ); } @Test public void testWithMapColumn() { final GroupByQuery query = new GroupByQuery( new TableDataSource(QueryRunnerTestHelper.DATA_SOURCE), new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of("2011/2012"))), VirtualColumns.create(ImmutableList.of(new MapVirtualColumn("keys", "values", "params"))), null, Granularities.ALL, ImmutableList.of(new DefaultDimensionSpec("params", "params")), ImmutableList.of(new CountAggregatorFactory("count")), null, null, null, null, null ); expectedException.expect(UnsupportedOperationException.class); expectedException.expectMessage("Map column doesn't support getRow()"); runner.run(QueryPlus.wrap(query)).toList(); } @Test public void testWithSubColumn() { final GroupByQuery query = new GroupByQuery( new TableDataSource(QueryRunnerTestHelper.DATA_SOURCE), new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of("2011/2012"))), VirtualColumns.create(ImmutableList.of(new MapVirtualColumn("keys", "values", "params"))), null, Granularities.ALL, ImmutableList.of(new DefaultDimensionSpec("params.key3", "params.key3")), ImmutableList.of(new CountAggregatorFactory("count")), null, null, null, null, null ); final List<ResultRow> result = runner.run(QueryPlus.wrap(query)).toList(); final List<ResultRow> expected = ImmutableList.of( new MapBasedRow( DateTimes.of("2011-01-12T00:00:00.000Z"), MapVirtualColumnTestBase.mapOf("count", 1L, "params.key3", "value3") ), new MapBasedRow(DateTimes.of("2011-01-12T00:00:00.000Z"), MapVirtualColumnTestBase.mapOf("count", 2L)) ).stream().map(row -> ResultRow.fromLegacyRow(row, query)).collect(Collectors.toList()); Assert.assertEquals(expected, result); } }
3e0cdaabe1962632a77e69dc61c98b0be7d7fe60
4,964
java
Java
spring-boot-case/fund/src/main/java/org/luvx/fund/task/FundTask.java
LuVx21/luvx_trial
8de853c7ba62f2c2af3e499f7c1079f75ca0cdf3
[ "MIT" ]
1
2019-10-22T03:17:05.000Z
2019-10-22T03:17:05.000Z
spring-boot-case/fund/src/main/java/org/luvx/fund/task/FundTask.java
LuVx21/luvx_trial
8de853c7ba62f2c2af3e499f7c1079f75ca0cdf3
[ "MIT" ]
3
2019-11-13T06:15:49.000Z
2020-04-27T13:52:20.000Z
spring-boot-case/fund/src/main/java/org/luvx/fund/task/FundTask.java
LuVx21/luvx_trial
8de853c7ba62f2c2af3e499f7c1079f75ca0cdf3
[ "MIT" ]
2
2019-01-16T09:13:49.000Z
2019-10-22T03:17:22.000Z
35.457143
111
0.64444
5,452
package org.luvx.fund.task; import java.math.BigDecimal; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.annotation.Resource; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptException; import org.luvx.app.config.TaskScheduler; import org.luvx.fund.constant.DataType; import org.luvx.fund.entity.Fund; import org.luvx.fund.entity.FundData; import org.luvx.fund.service.FundDataService; import org.luvx.fund.service.FundService; import org.luvx.fund.util.RequestUtils; import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON; import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.config.annotation.NacosValue; import com.alibaba.nacos.api.config.listener.Listener; import com.alibaba.nacos.api.exception.NacosException; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.google.common.util.concurrent.RateLimiter; import io.vavr.control.Option; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; @Slf4j @Service public class FundTask { @Resource private FundService fundService; @Resource private FundDataService fundDataService; @NacosInjected private ConfigService configService; @Resource private TaskScheduler taskScheduler; @NacosValue(value = "${nacos.config.data-id:aaa}", autoRefreshed = true) private String dataId; @NacosValue(value = "${nacos.config.group:aaa}", autoRefreshed = true) private String group; @NacosValue(value = "${task.ids}", autoRefreshed = true) private List<Integer> ids; @NacosValue(value = "${task.crons}", autoRefreshed = true) private List<String> crons; @PostConstruct public void onMessage() throws NacosException { addCronTask(); configService.addListener(dataId, group, new Listener() { @SneakyThrows @Override public void receiveConfigInfo(String configInfo) { TimeUnit.SECONDS.sleep(5); taskScheduler.cancelAll(); addCronTask(); } @Override public Executor getExecutor() { return null; } }); // exec(); } private void addCronTask() { for (int i = 0; i < ids.size(); i++) { taskScheduler.addTriggerTask(ids.get(i), crons.get(i), this::exec); } } public void exec() { RateLimiter rateLimiter = RateLimiter.create(0.5); List<Fund> funds = fundService.getBaseMapper().selectList(new QueryWrapper<Fund>().orderByAsc("code")); funds.forEach(fund -> { log.info("fund: {}:{}", fund.getCode(), fund.getName()); rateLimiter.acquire(); readRequest(fund.getCode()); }); log.info("fund data catch finish..."); } @SneakyThrows public void readRequest(String code) { NashornScriptEngineFactory factory = new NashornScriptEngineFactory(); ScriptEngine engine = factory.getScriptEngine(); String json = RequestUtils.getJson(code); engine.eval(json); extracted(engine); } private void extracted(ScriptEngine engine) throws ScriptException, NoSuchMethodException { if (engine instanceof Invocable invocable) { String json = (String) invocable.invokeFunction("data"); Fund fund = JSON.parseObject(json, Fund.class); fundService.saveOrUpdate(fund); handleWorthOrGrand(fund, DataType.WORTH); handleWorthOrGrand(fund, DataType.GRAND); } } private void handleWorthOrGrand(Fund fund, DataType dataType) { String code = fund.getCode(); int type = dataType.getValue(); FundData one = fundDataService.getOne( new QueryWrapper<FundData>().eq("code", code) .eq("type", type) .orderByDesc("x") .last("limit 1") ); Long maxX = Option.of(one).map(FundData::getX).getOrElse(0L); List<List<BigDecimal>> data = dataType == DataType.WORTH ? fund.getWorth() : fund.getGrand(); List<FundData> collect = data.stream() .filter(l -> l != null && l.size() >= 2) .filter(l -> l.get(0).longValue() > maxX) .map(l -> FundData.builder().code(code) .type(type) .x(l.get(0).longValue()) .y(l.get(1)) .build()) .collect(Collectors.toList()); fundDataService.saveBatch(collect); } }
3e0cdad46b9333b48ca37290683fe73445919abb
3,171
java
Java
Milestone 1/Geocit/Geocit134/src/main/java/com/softserveinc/geocitizen/controller/api/UsersRestController.java
eugenia-ponomarenko/DevOpsChernivtsi
92fdc807373cd74053a466e5e843cc6cce837815
[ "MIT" ]
null
null
null
Milestone 1/Geocit/Geocit134/src/main/java/com/softserveinc/geocitizen/controller/api/UsersRestController.java
eugenia-ponomarenko/DevOpsChernivtsi
92fdc807373cd74053a466e5e843cc6cce837815
[ "MIT" ]
null
null
null
Milestone 1/Geocit/Geocit134/src/main/java/com/softserveinc/geocitizen/controller/api/UsersRestController.java
eugenia-ponomarenko/DevOpsChernivtsi
92fdc807373cd74053a466e5e843cc6cce837815
[ "MIT" ]
5
2022-02-03T10:14:52.000Z
2022-03-30T22:04:50.000Z
35.244444
130
0.777743
5,453
/* * The following code have been created by Yaroslav Zhyravov (shrralis). * The code can be used in non-commercial way for everyone. * But for any commercial way it needs a author's agreement. * Please contact the author for that: * - https://t.me/Shrralis * - https://twitter.com/Shrralis * - anpch@example.com * * Copyright (c) 2017 by shrralis (Yaroslav Zhyravov). */ package com.softserveinc.geocitizen.controller.api; import com.softserveinc.geocitizen.dto.EditUserDTO; import com.softserveinc.geocitizen.exception.BadFieldFormatException; import com.softserveinc.geocitizen.exception.IllegalParameterException; import com.softserveinc.geocitizen.security.model.AuthorizedUser; import com.softserveinc.geocitizen.service.interfaces.IImageService; import com.softserveinc.geocitizen.service.interfaces.IUserService; import com.softserveinc.tools.model.JsonResponse; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.LocaleResolver; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import java.io.IOException; @RestController @RequestMapping("/users") public class UsersRestController { private final IUserService service; private final IImageService imageService; private final LocaleResolver localeResolver; @Autowired public UsersRestController(IUserService service, IImageService imageService, LocaleResolver localeResolver) { this.service = service; this.imageService = imageService; this.localeResolver = localeResolver; } @GetMapping public JsonResponse allUsers() { return new JsonResponse(service.getAllUsers()); } @GetMapping("/{id}") public JsonResponse user(@PathVariable int id) { return new JsonResponse(service.getUser(id)); } @GetMapping("/profile/{id}") public JsonResponse userProfile(@PathVariable int id) { return new JsonResponse(service.getUserProfile(id)); } @PutMapping("/edit") public JsonResponse edit(@RequestBody @Valid EditUserDTO dto) { service.edit(dto); return new JsonResponse(service.getUser(AuthorizedUser.getCurrent().getId())); } @ApiOperation(hidden = true, value = "Return language for user") @GetMapping("/currentLang") public JsonResponse currentLang(HttpServletRequest request) { return new JsonResponse(localeResolver.resolveLocale(request)); } @GetMapping(value = "/image/{userId}", produces = MediaType.IMAGE_JPEG_VALUE) public byte[] userImage(@PathVariable("userId") int userId) throws IOException { return imageService.getUserImageInByte(userId); } @PutMapping("/image") public JsonResponse issue(@RequestParam("image") MultipartFile image) throws IllegalParameterException, BadFieldFormatException { if (image == null) { throw new IllegalParameterException("image"); } service.updateImage(imageService.parseImage(image)); return new JsonResponse(service.getUser(AuthorizedUser.getCurrent().getId())); } }
3e0cdbd925cf52cf465528866f11ac5b6c8f7e92
4,301
java
Java
src/java/com/chinamobile/bcbsp/BSPControllerRunner.java
hellolvs/bc-bsp-2.0
bcfe20e2d7fe6df07773b5929b19574b560d8add
[ "Apache-2.0" ]
1
2017-01-02T06:17:21.000Z
2017-01-02T06:17:21.000Z
src/java/com/chinamobile/bcbsp/BSPControllerRunner.java
hellolvs/bc-bsp-2.0
bcfe20e2d7fe6df07773b5929b19574b560d8add
[ "Apache-2.0" ]
null
null
null
src/java/com/chinamobile/bcbsp/BSPControllerRunner.java
hellolvs/bc-bsp-2.0
bcfe20e2d7fe6df07773b5929b19574b560d8add
[ "Apache-2.0" ]
1
2018-09-28T06:04:07.000Z
2018-09-28T06:04:07.000Z
26.714286
79
0.606603
5,454
/** * CopyRight by Chinamobile * * BSPControllerRunner.java */ package com.chinamobile.bcbsp; import com.chinamobile.bcbsp.bspcontroller.BSPController; import com.chinamobile.bcbsp.util.SystemInfo; import java.net.InetAddress; import java.net.UnknownHostException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; /** * BSPControllerRunner This class starts and runs the BSPController. It is * relative with the shell command. * * * */ public class BSPControllerRunner extends Configured implements Tool { /** * StartupShutdownPretreatment This class is used to do some prepare work * before starting BSPController and cleanup after shutting down * BSPController. * * * */ public class StartupShutdownPretreatment extends Thread { /** State Log */ private final Log log; /** State host name */ private final String hostName; /** State class name */ private final String className; /** State BSPController */ private BSPController bspController; /** * constructor * @param clazz * Class<?> * @param log * org.apache.commons.logging.Log */ public StartupShutdownPretreatment(Class<?> clazz, final org.apache.commons.logging.Log log) { this.log = log; this.hostName = getHostname(); this.className = clazz.getSimpleName(); this.log.info(toStartupShutdownMessage("STARTUP_MSG: ", new String[] { "Starting " + this.className, " host = " + this.hostName, " version = " + SystemInfo.getVersionInfo(), " source = " + SystemInfo.getSourceCodeInfo(), " compiler = " + SystemInfo.getCompilerInfo()})); } public void setHandler(BSPController bspController) { this.bspController = bspController; } @Override public void run() { try { this.bspController.shutdown(); this.log.info(toStartupShutdownMessage("SHUTDOWN_MSG: ", new String[] {"Shutting down " + this.className + " at " + this.hostName})); } catch (Exception e) { // this.log.error("Shutdown Abnormally", e); throw new RuntimeException("Shutdown Abnormally", e); } } /** * get the host name * @return * host name */ private String getHostname() { try { return "" + InetAddress.getLocalHost(); } catch (UnknownHostException uhe) { return "" + uhe; } } /** * toString * @param prefix * the initial contents of the buffer. * @param msg * String[] * @return * String */ private String toStartupShutdownMessage(String prefix, String[] msg) { StringBuffer b = new StringBuffer(prefix); b.append("\n/****************************************" + "********************"); for (String s : msg) { b.append("\n" + prefix + s); b.append("\n******************************" + "******************************/"); } return b.toString(); } } /** Define Log variable output messages */ public static final Log LOG = LogFactory.getLog(BSPControllerRunner.class); @Override public int run(String[] args) throws Exception { StartupShutdownPretreatment pretreatment = new StartupShutdownPretreatment( BSPController.class, LOG); if (args.length != 0) { System .out .println("usage: BSPControllerRunner"); System.exit(-1); } try { BSPConfiguration conf = new BSPConfiguration(getConf()); BSPController bspController = BSPController.startMaster(conf); pretreatment.setHandler(bspController); Runtime.getRuntime().addShutdownHook(pretreatment); bspController.offerService(); } catch (Exception e) { LOG.fatal("Start Abnormally", e); return -1; } return 0; } /** * @param args * a * @throws Exception */ public static void main(String[] args) throws Exception { int exitCode = ToolRunner.run(new BSPControllerRunner(), args); System.exit(exitCode); } }
3e0cdc1de87dce7f43c9d9e25033dc0ab8d71696
776
java
Java
src/com/talk_to_your_phone/horloge/AlarmReceiver.java
warrior90/malvoyants
2a1726443a14f2324b1377fc313f134bc4998965
[ "MIT" ]
null
null
null
src/com/talk_to_your_phone/horloge/AlarmReceiver.java
warrior90/malvoyants
2a1726443a14f2324b1377fc313f134bc4998965
[ "MIT" ]
null
null
null
src/com/talk_to_your_phone/horloge/AlarmReceiver.java
warrior90/malvoyants
2a1726443a14f2324b1377fc313f134bc4998965
[ "MIT" ]
null
null
null
27.714286
87
0.708763
5,455
package com.talk_to_your_phone.horloge; import com.project.talk_to_your_phone.Main; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class AlarmReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { try { //Toast.makeText(context, "C'est l'heure !!!",Toast.LENGTH_LONG).show(); Intent i2 = new Intent(context,Alarme_notif.class); i2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); context.startActivity(i2); } catch (Exception r) { Toast.makeText(context, "Erreur.",Toast.LENGTH_SHORT).show(); r.printStackTrace(); } } }
3e0cdcb23a89c78386c6ff9f64648744186b2d53
1,251
java
Java
parent-project/java-core/src/main/java/com/ziyang/producerconsumer/taskstring/TaskStringProducerTimerTask.java
oopsmails/spring-main
8248e1f2c202ef94cef50368b419bb55f461fc56
[ "MIT" ]
1
2019-03-29T11:25:30.000Z
2019-03-29T11:25:30.000Z
parent-project/java-core/src/main/java/com/ziyang/producerconsumer/taskstring/TaskStringProducerTimerTask.java
oopsmails/spring-main
8248e1f2c202ef94cef50368b419bb55f461fc56
[ "MIT" ]
null
null
null
parent-project/java-core/src/main/java/com/ziyang/producerconsumer/taskstring/TaskStringProducerTimerTask.java
oopsmails/spring-main
8248e1f2c202ef94cef50368b419bb55f461fc56
[ "MIT" ]
null
null
null
28.431818
97
0.710631
5,456
package com.ziyang.producerconsumer.taskstring; import java.util.TimerTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ziyang.producerconsumer.TaskObjQueueManager; public class TaskStringProducerTimerTask extends TimerTask { private static final Logger logger = LoggerFactory.getLogger(TaskStringProducerTimerTask.class); // @Autowired // @Inject private TaskObjQueueManager taskObjQueueManager; public TaskObjQueueManager getTaskObjQueueManager() { return taskObjQueueManager; } public void setTaskObjQueueManager(TaskObjQueueManager taskObjQueueManager) { this.taskObjQueueManager = taskObjQueueManager; } @Override public void run() { logger.info("############### start putting Strings #################"); try { for (int i = 0; i < 10; i++) { TaskObjString taskObjString = new TaskObjString("" + i); boolean sent = taskObjQueueManager.addItem(taskObjString); if (!sent) { logger.error("Error when sending TaskObj to Queue, taskObjString = " + taskObjString); } } } catch (InterruptedException e) { logger.error("Error when sending TaskObj to Queue!", e); e.printStackTrace(); } logger.info("############### finish putting Strings #################"); } }
3e0cde13acf744d504c2fc62c69cb6447a3be97c
93,891
java
Java
org.hl7.fhir.r5/src/main/java/org/hl7/fhir/r5/model/DeviceMetric.java
bdenton/org.hl7.fhir.core
9e693b6a0380c5c3106f15cc463f7103ea3061d9
[ "Apache-2.0" ]
98
2019-03-01T21:59:41.000Z
2022-03-23T15:52:06.000Z
org.hl7.fhir.r5/src/main/java/org/hl7/fhir/r5/model/DeviceMetric.java
bdenton/org.hl7.fhir.core
9e693b6a0380c5c3106f15cc463f7103ea3061d9
[ "Apache-2.0" ]
573
2019-02-27T17:51:31.000Z
2022-03-31T21:18:44.000Z
org.hl7.fhir.r5/src/main/java/org/hl7/fhir/r5/model/DeviceMetric.java
bdenton/org.hl7.fhir.core
9e693b6a0380c5c3106f15cc463f7103ea3061d9
[ "Apache-2.0" ]
112
2019-01-31T10:50:26.000Z
2022-03-21T09:55:06.000Z
49.080502
703
0.646271
5,457
package org.hl7.fhir.r5.model; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, \ are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this \ list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, \ this list of conditions and the following disclaimer in the documentation \ and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND \ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED \ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. \ IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, \ INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT \ NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR \ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, \ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE \ POSSIBILITY OF SUCH DAMAGE. */ // Generated on Tue, Dec 28, 2021 07:16+1100 for FHIR v5.0.0-snapshot1 import java.util.ArrayList; import java.util.Date; import java.util.List; import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.r5.model.Enumerations.*; import org.hl7.fhir.instance.model.api.IBaseBackboneElement; import org.hl7.fhir.exceptions.FHIRException; import org.hl7.fhir.instance.model.api.ICompositeType; import ca.uhn.fhir.model.api.annotation.ResourceDef; import ca.uhn.fhir.model.api.annotation.SearchParamDefinition; import org.hl7.fhir.instance.model.api.IBaseBackboneElement; import ca.uhn.fhir.model.api.annotation.Child; import ca.uhn.fhir.model.api.annotation.ChildOrder; import ca.uhn.fhir.model.api.annotation.Description; import ca.uhn.fhir.model.api.annotation.Block; /** * Describes a measurement, calculation or setting capability of a medical device. */ @ResourceDef(name="DeviceMetric", profile="http://hl7.org/fhir/StructureDefinition/DeviceMetric") public class DeviceMetric extends DomainResource { public enum DeviceMetricCalibrationState { /** * The metric has not been calibrated. */ NOTCALIBRATED, /** * The metric needs to be calibrated. */ CALIBRATIONREQUIRED, /** * The metric has been calibrated. */ CALIBRATED, /** * The state of calibration of this metric is unspecified. */ UNSPECIFIED, /** * added to help the parsers with the generic types */ NULL; public static DeviceMetricCalibrationState fromCode(String codeString) throws FHIRException { if (codeString == null || "".equals(codeString)) return null; if ("not-calibrated".equals(codeString)) return NOTCALIBRATED; if ("calibration-required".equals(codeString)) return CALIBRATIONREQUIRED; if ("calibrated".equals(codeString)) return CALIBRATED; if ("unspecified".equals(codeString)) return UNSPECIFIED; if (Configuration.isAcceptInvalidEnums()) return null; else throw new FHIRException("Unknown DeviceMetricCalibrationState code '"+codeString+"'"); } public String toCode() { switch (this) { case NOTCALIBRATED: return "not-calibrated"; case CALIBRATIONREQUIRED: return "calibration-required"; case CALIBRATED: return "calibrated"; case UNSPECIFIED: return "unspecified"; default: return "?"; } } public String getSystem() { switch (this) { case NOTCALIBRATED: return "http://hl7.org/fhir/metric-calibration-state"; case CALIBRATIONREQUIRED: return "http://hl7.org/fhir/metric-calibration-state"; case CALIBRATED: return "http://hl7.org/fhir/metric-calibration-state"; case UNSPECIFIED: return "http://hl7.org/fhir/metric-calibration-state"; default: return "?"; } } public String getDefinition() { switch (this) { case NOTCALIBRATED: return "The metric has not been calibrated."; case CALIBRATIONREQUIRED: return "The metric needs to be calibrated."; case CALIBRATED: return "The metric has been calibrated."; case UNSPECIFIED: return "The state of calibration of this metric is unspecified."; default: return "?"; } } public String getDisplay() { switch (this) { case NOTCALIBRATED: return "Not Calibrated"; case CALIBRATIONREQUIRED: return "Calibration Required"; case CALIBRATED: return "Calibrated"; case UNSPECIFIED: return "Unspecified"; default: return "?"; } } } public static class DeviceMetricCalibrationStateEnumFactory implements EnumFactory<DeviceMetricCalibrationState> { public DeviceMetricCalibrationState fromCode(String codeString) throws IllegalArgumentException { if (codeString == null || "".equals(codeString)) if (codeString == null || "".equals(codeString)) return null; if ("not-calibrated".equals(codeString)) return DeviceMetricCalibrationState.NOTCALIBRATED; if ("calibration-required".equals(codeString)) return DeviceMetricCalibrationState.CALIBRATIONREQUIRED; if ("calibrated".equals(codeString)) return DeviceMetricCalibrationState.CALIBRATED; if ("unspecified".equals(codeString)) return DeviceMetricCalibrationState.UNSPECIFIED; throw new IllegalArgumentException("Unknown DeviceMetricCalibrationState code '"+codeString+"'"); } public Enumeration<DeviceMetricCalibrationState> fromType(Base code) throws FHIRException { if (code == null) return null; if (code.isEmpty()) return new Enumeration<DeviceMetricCalibrationState>(this); String codeString = ((PrimitiveType) code).asStringValue(); if (codeString == null || "".equals(codeString)) return null; if ("not-calibrated".equals(codeString)) return new Enumeration<DeviceMetricCalibrationState>(this, DeviceMetricCalibrationState.NOTCALIBRATED); if ("calibration-required".equals(codeString)) return new Enumeration<DeviceMetricCalibrationState>(this, DeviceMetricCalibrationState.CALIBRATIONREQUIRED); if ("calibrated".equals(codeString)) return new Enumeration<DeviceMetricCalibrationState>(this, DeviceMetricCalibrationState.CALIBRATED); if ("unspecified".equals(codeString)) return new Enumeration<DeviceMetricCalibrationState>(this, DeviceMetricCalibrationState.UNSPECIFIED); throw new FHIRException("Unknown DeviceMetricCalibrationState code '"+codeString+"'"); } public String toCode(DeviceMetricCalibrationState code) { if (code == DeviceMetricCalibrationState.NOTCALIBRATED) return "not-calibrated"; if (code == DeviceMetricCalibrationState.CALIBRATIONREQUIRED) return "calibration-required"; if (code == DeviceMetricCalibrationState.CALIBRATED) return "calibrated"; if (code == DeviceMetricCalibrationState.UNSPECIFIED) return "unspecified"; return "?"; } public String toSystem(DeviceMetricCalibrationState code) { return code.getSystem(); } } public enum DeviceMetricCalibrationType { /** * Metric calibration method has not been identified. */ UNSPECIFIED, /** * Offset metric calibration method. */ OFFSET, /** * Gain metric calibration method. */ GAIN, /** * Two-point metric calibration method. */ TWOPOINT, /** * added to help the parsers with the generic types */ NULL; public static DeviceMetricCalibrationType fromCode(String codeString) throws FHIRException { if (codeString == null || "".equals(codeString)) return null; if ("unspecified".equals(codeString)) return UNSPECIFIED; if ("offset".equals(codeString)) return OFFSET; if ("gain".equals(codeString)) return GAIN; if ("two-point".equals(codeString)) return TWOPOINT; if (Configuration.isAcceptInvalidEnums()) return null; else throw new FHIRException("Unknown DeviceMetricCalibrationType code '"+codeString+"'"); } public String toCode() { switch (this) { case UNSPECIFIED: return "unspecified"; case OFFSET: return "offset"; case GAIN: return "gain"; case TWOPOINT: return "two-point"; default: return "?"; } } public String getSystem() { switch (this) { case UNSPECIFIED: return "http://hl7.org/fhir/metric-calibration-type"; case OFFSET: return "http://hl7.org/fhir/metric-calibration-type"; case GAIN: return "http://hl7.org/fhir/metric-calibration-type"; case TWOPOINT: return "http://hl7.org/fhir/metric-calibration-type"; default: return "?"; } } public String getDefinition() { switch (this) { case UNSPECIFIED: return "Metric calibration method has not been identified."; case OFFSET: return "Offset metric calibration method."; case GAIN: return "Gain metric calibration method."; case TWOPOINT: return "Two-point metric calibration method."; default: return "?"; } } public String getDisplay() { switch (this) { case UNSPECIFIED: return "Unspecified"; case OFFSET: return "Offset"; case GAIN: return "Gain"; case TWOPOINT: return "Two Point"; default: return "?"; } } } public static class DeviceMetricCalibrationTypeEnumFactory implements EnumFactory<DeviceMetricCalibrationType> { public DeviceMetricCalibrationType fromCode(String codeString) throws IllegalArgumentException { if (codeString == null || "".equals(codeString)) if (codeString == null || "".equals(codeString)) return null; if ("unspecified".equals(codeString)) return DeviceMetricCalibrationType.UNSPECIFIED; if ("offset".equals(codeString)) return DeviceMetricCalibrationType.OFFSET; if ("gain".equals(codeString)) return DeviceMetricCalibrationType.GAIN; if ("two-point".equals(codeString)) return DeviceMetricCalibrationType.TWOPOINT; throw new IllegalArgumentException("Unknown DeviceMetricCalibrationType code '"+codeString+"'"); } public Enumeration<DeviceMetricCalibrationType> fromType(Base code) throws FHIRException { if (code == null) return null; if (code.isEmpty()) return new Enumeration<DeviceMetricCalibrationType>(this); String codeString = ((PrimitiveType) code).asStringValue(); if (codeString == null || "".equals(codeString)) return null; if ("unspecified".equals(codeString)) return new Enumeration<DeviceMetricCalibrationType>(this, DeviceMetricCalibrationType.UNSPECIFIED); if ("offset".equals(codeString)) return new Enumeration<DeviceMetricCalibrationType>(this, DeviceMetricCalibrationType.OFFSET); if ("gain".equals(codeString)) return new Enumeration<DeviceMetricCalibrationType>(this, DeviceMetricCalibrationType.GAIN); if ("two-point".equals(codeString)) return new Enumeration<DeviceMetricCalibrationType>(this, DeviceMetricCalibrationType.TWOPOINT); throw new FHIRException("Unknown DeviceMetricCalibrationType code '"+codeString+"'"); } public String toCode(DeviceMetricCalibrationType code) { if (code == DeviceMetricCalibrationType.UNSPECIFIED) return "unspecified"; if (code == DeviceMetricCalibrationType.OFFSET) return "offset"; if (code == DeviceMetricCalibrationType.GAIN) return "gain"; if (code == DeviceMetricCalibrationType.TWOPOINT) return "two-point"; return "?"; } public String toSystem(DeviceMetricCalibrationType code) { return code.getSystem(); } } public enum DeviceMetricCategory { /** * DeviceObservations generated for this DeviceMetric are measured. */ MEASUREMENT, /** * DeviceObservations generated for this DeviceMetric is a setting that will influence the behavior of the Device. */ SETTING, /** * DeviceObservations generated for this DeviceMetric are calculated. */ CALCULATION, /** * The category of this DeviceMetric is unspecified. */ UNSPECIFIED, /** * added to help the parsers with the generic types */ NULL; public static DeviceMetricCategory fromCode(String codeString) throws FHIRException { if (codeString == null || "".equals(codeString)) return null; if ("measurement".equals(codeString)) return MEASUREMENT; if ("setting".equals(codeString)) return SETTING; if ("calculation".equals(codeString)) return CALCULATION; if ("unspecified".equals(codeString)) return UNSPECIFIED; if (Configuration.isAcceptInvalidEnums()) return null; else throw new FHIRException("Unknown DeviceMetricCategory code '"+codeString+"'"); } public String toCode() { switch (this) { case MEASUREMENT: return "measurement"; case SETTING: return "setting"; case CALCULATION: return "calculation"; case UNSPECIFIED: return "unspecified"; default: return "?"; } } public String getSystem() { switch (this) { case MEASUREMENT: return "http://hl7.org/fhir/metric-category"; case SETTING: return "http://hl7.org/fhir/metric-category"; case CALCULATION: return "http://hl7.org/fhir/metric-category"; case UNSPECIFIED: return "http://hl7.org/fhir/metric-category"; default: return "?"; } } public String getDefinition() { switch (this) { case MEASUREMENT: return "DeviceObservations generated for this DeviceMetric are measured."; case SETTING: return "DeviceObservations generated for this DeviceMetric is a setting that will influence the behavior of the Device."; case CALCULATION: return "DeviceObservations generated for this DeviceMetric are calculated."; case UNSPECIFIED: return "The category of this DeviceMetric is unspecified."; default: return "?"; } } public String getDisplay() { switch (this) { case MEASUREMENT: return "Measurement"; case SETTING: return "Setting"; case CALCULATION: return "Calculation"; case UNSPECIFIED: return "Unspecified"; default: return "?"; } } } public static class DeviceMetricCategoryEnumFactory implements EnumFactory<DeviceMetricCategory> { public DeviceMetricCategory fromCode(String codeString) throws IllegalArgumentException { if (codeString == null || "".equals(codeString)) if (codeString == null || "".equals(codeString)) return null; if ("measurement".equals(codeString)) return DeviceMetricCategory.MEASUREMENT; if ("setting".equals(codeString)) return DeviceMetricCategory.SETTING; if ("calculation".equals(codeString)) return DeviceMetricCategory.CALCULATION; if ("unspecified".equals(codeString)) return DeviceMetricCategory.UNSPECIFIED; throw new IllegalArgumentException("Unknown DeviceMetricCategory code '"+codeString+"'"); } public Enumeration<DeviceMetricCategory> fromType(Base code) throws FHIRException { if (code == null) return null; if (code.isEmpty()) return new Enumeration<DeviceMetricCategory>(this); String codeString = ((PrimitiveType) code).asStringValue(); if (codeString == null || "".equals(codeString)) return null; if ("measurement".equals(codeString)) return new Enumeration<DeviceMetricCategory>(this, DeviceMetricCategory.MEASUREMENT); if ("setting".equals(codeString)) return new Enumeration<DeviceMetricCategory>(this, DeviceMetricCategory.SETTING); if ("calculation".equals(codeString)) return new Enumeration<DeviceMetricCategory>(this, DeviceMetricCategory.CALCULATION); if ("unspecified".equals(codeString)) return new Enumeration<DeviceMetricCategory>(this, DeviceMetricCategory.UNSPECIFIED); throw new FHIRException("Unknown DeviceMetricCategory code '"+codeString+"'"); } public String toCode(DeviceMetricCategory code) { if (code == DeviceMetricCategory.MEASUREMENT) return "measurement"; if (code == DeviceMetricCategory.SETTING) return "setting"; if (code == DeviceMetricCategory.CALCULATION) return "calculation"; if (code == DeviceMetricCategory.UNSPECIFIED) return "unspecified"; return "?"; } public String toSystem(DeviceMetricCategory code) { return code.getSystem(); } } public enum DeviceMetricColor { /** * Color for representation - black. */ BLACK, /** * Color for representation - red. */ RED, /** * Color for representation - green. */ GREEN, /** * Color for representation - yellow. */ YELLOW, /** * Color for representation - blue. */ BLUE, /** * Color for representation - magenta. */ MAGENTA, /** * Color for representation - cyan. */ CYAN, /** * Color for representation - white. */ WHITE, /** * added to help the parsers with the generic types */ NULL; public static DeviceMetricColor fromCode(String codeString) throws FHIRException { if (codeString == null || "".equals(codeString)) return null; if ("black".equals(codeString)) return BLACK; if ("red".equals(codeString)) return RED; if ("green".equals(codeString)) return GREEN; if ("yellow".equals(codeString)) return YELLOW; if ("blue".equals(codeString)) return BLUE; if ("magenta".equals(codeString)) return MAGENTA; if ("cyan".equals(codeString)) return CYAN; if ("white".equals(codeString)) return WHITE; if (Configuration.isAcceptInvalidEnums()) return null; else throw new FHIRException("Unknown DeviceMetricColor code '"+codeString+"'"); } public String toCode() { switch (this) { case BLACK: return "black"; case RED: return "red"; case GREEN: return "green"; case YELLOW: return "yellow"; case BLUE: return "blue"; case MAGENTA: return "magenta"; case CYAN: return "cyan"; case WHITE: return "white"; default: return "?"; } } public String getSystem() { switch (this) { case BLACK: return "http://hl7.org/fhir/metric-color"; case RED: return "http://hl7.org/fhir/metric-color"; case GREEN: return "http://hl7.org/fhir/metric-color"; case YELLOW: return "http://hl7.org/fhir/metric-color"; case BLUE: return "http://hl7.org/fhir/metric-color"; case MAGENTA: return "http://hl7.org/fhir/metric-color"; case CYAN: return "http://hl7.org/fhir/metric-color"; case WHITE: return "http://hl7.org/fhir/metric-color"; default: return "?"; } } public String getDefinition() { switch (this) { case BLACK: return "Color for representation - black."; case RED: return "Color for representation - red."; case GREEN: return "Color for representation - green."; case YELLOW: return "Color for representation - yellow."; case BLUE: return "Color for representation - blue."; case MAGENTA: return "Color for representation - magenta."; case CYAN: return "Color for representation - cyan."; case WHITE: return "Color for representation - white."; default: return "?"; } } public String getDisplay() { switch (this) { case BLACK: return "Color Black"; case RED: return "Color Red"; case GREEN: return "Color Green"; case YELLOW: return "Color Yellow"; case BLUE: return "Color Blue"; case MAGENTA: return "Color Magenta"; case CYAN: return "Color Cyan"; case WHITE: return "Color White"; default: return "?"; } } } public static class DeviceMetricColorEnumFactory implements EnumFactory<DeviceMetricColor> { public DeviceMetricColor fromCode(String codeString) throws IllegalArgumentException { if (codeString == null || "".equals(codeString)) if (codeString == null || "".equals(codeString)) return null; if ("black".equals(codeString)) return DeviceMetricColor.BLACK; if ("red".equals(codeString)) return DeviceMetricColor.RED; if ("green".equals(codeString)) return DeviceMetricColor.GREEN; if ("yellow".equals(codeString)) return DeviceMetricColor.YELLOW; if ("blue".equals(codeString)) return DeviceMetricColor.BLUE; if ("magenta".equals(codeString)) return DeviceMetricColor.MAGENTA; if ("cyan".equals(codeString)) return DeviceMetricColor.CYAN; if ("white".equals(codeString)) return DeviceMetricColor.WHITE; throw new IllegalArgumentException("Unknown DeviceMetricColor code '"+codeString+"'"); } public Enumeration<DeviceMetricColor> fromType(Base code) throws FHIRException { if (code == null) return null; if (code.isEmpty()) return new Enumeration<DeviceMetricColor>(this); String codeString = ((PrimitiveType) code).asStringValue(); if (codeString == null || "".equals(codeString)) return null; if ("black".equals(codeString)) return new Enumeration<DeviceMetricColor>(this, DeviceMetricColor.BLACK); if ("red".equals(codeString)) return new Enumeration<DeviceMetricColor>(this, DeviceMetricColor.RED); if ("green".equals(codeString)) return new Enumeration<DeviceMetricColor>(this, DeviceMetricColor.GREEN); if ("yellow".equals(codeString)) return new Enumeration<DeviceMetricColor>(this, DeviceMetricColor.YELLOW); if ("blue".equals(codeString)) return new Enumeration<DeviceMetricColor>(this, DeviceMetricColor.BLUE); if ("magenta".equals(codeString)) return new Enumeration<DeviceMetricColor>(this, DeviceMetricColor.MAGENTA); if ("cyan".equals(codeString)) return new Enumeration<DeviceMetricColor>(this, DeviceMetricColor.CYAN); if ("white".equals(codeString)) return new Enumeration<DeviceMetricColor>(this, DeviceMetricColor.WHITE); throw new FHIRException("Unknown DeviceMetricColor code '"+codeString+"'"); } public String toCode(DeviceMetricColor code) { if (code == DeviceMetricColor.BLACK) return "black"; if (code == DeviceMetricColor.RED) return "red"; if (code == DeviceMetricColor.GREEN) return "green"; if (code == DeviceMetricColor.YELLOW) return "yellow"; if (code == DeviceMetricColor.BLUE) return "blue"; if (code == DeviceMetricColor.MAGENTA) return "magenta"; if (code == DeviceMetricColor.CYAN) return "cyan"; if (code == DeviceMetricColor.WHITE) return "white"; return "?"; } public String toSystem(DeviceMetricColor code) { return code.getSystem(); } } public enum DeviceMetricOperationalStatus { /** * The DeviceMetric is operating and will generate DeviceObservations. */ ON, /** * The DeviceMetric is not operating. */ OFF, /** * The DeviceMetric is operating, but will not generate any DeviceObservations. */ STANDBY, /** * The DeviceMetric was entered in error. */ ENTEREDINERROR, /** * added to help the parsers with the generic types */ NULL; public static DeviceMetricOperationalStatus fromCode(String codeString) throws FHIRException { if (codeString == null || "".equals(codeString)) return null; if ("on".equals(codeString)) return ON; if ("off".equals(codeString)) return OFF; if ("standby".equals(codeString)) return STANDBY; if ("entered-in-error".equals(codeString)) return ENTEREDINERROR; if (Configuration.isAcceptInvalidEnums()) return null; else throw new FHIRException("Unknown DeviceMetricOperationalStatus code '"+codeString+"'"); } public String toCode() { switch (this) { case ON: return "on"; case OFF: return "off"; case STANDBY: return "standby"; case ENTEREDINERROR: return "entered-in-error"; default: return "?"; } } public String getSystem() { switch (this) { case ON: return "http://hl7.org/fhir/metric-operational-status"; case OFF: return "http://hl7.org/fhir/metric-operational-status"; case STANDBY: return "http://hl7.org/fhir/metric-operational-status"; case ENTEREDINERROR: return "http://hl7.org/fhir/metric-operational-status"; default: return "?"; } } public String getDefinition() { switch (this) { case ON: return "The DeviceMetric is operating and will generate DeviceObservations."; case OFF: return "The DeviceMetric is not operating."; case STANDBY: return "The DeviceMetric is operating, but will not generate any DeviceObservations."; case ENTEREDINERROR: return "The DeviceMetric was entered in error."; default: return "?"; } } public String getDisplay() { switch (this) { case ON: return "On"; case OFF: return "Off"; case STANDBY: return "Standby"; case ENTEREDINERROR: return "Entered In Error"; default: return "?"; } } } public static class DeviceMetricOperationalStatusEnumFactory implements EnumFactory<DeviceMetricOperationalStatus> { public DeviceMetricOperationalStatus fromCode(String codeString) throws IllegalArgumentException { if (codeString == null || "".equals(codeString)) if (codeString == null || "".equals(codeString)) return null; if ("on".equals(codeString)) return DeviceMetricOperationalStatus.ON; if ("off".equals(codeString)) return DeviceMetricOperationalStatus.OFF; if ("standby".equals(codeString)) return DeviceMetricOperationalStatus.STANDBY; if ("entered-in-error".equals(codeString)) return DeviceMetricOperationalStatus.ENTEREDINERROR; throw new IllegalArgumentException("Unknown DeviceMetricOperationalStatus code '"+codeString+"'"); } public Enumeration<DeviceMetricOperationalStatus> fromType(Base code) throws FHIRException { if (code == null) return null; if (code.isEmpty()) return new Enumeration<DeviceMetricOperationalStatus>(this); String codeString = ((PrimitiveType) code).asStringValue(); if (codeString == null || "".equals(codeString)) return null; if ("on".equals(codeString)) return new Enumeration<DeviceMetricOperationalStatus>(this, DeviceMetricOperationalStatus.ON); if ("off".equals(codeString)) return new Enumeration<DeviceMetricOperationalStatus>(this, DeviceMetricOperationalStatus.OFF); if ("standby".equals(codeString)) return new Enumeration<DeviceMetricOperationalStatus>(this, DeviceMetricOperationalStatus.STANDBY); if ("entered-in-error".equals(codeString)) return new Enumeration<DeviceMetricOperationalStatus>(this, DeviceMetricOperationalStatus.ENTEREDINERROR); throw new FHIRException("Unknown DeviceMetricOperationalStatus code '"+codeString+"'"); } public String toCode(DeviceMetricOperationalStatus code) { if (code == DeviceMetricOperationalStatus.ON) return "on"; if (code == DeviceMetricOperationalStatus.OFF) return "off"; if (code == DeviceMetricOperationalStatus.STANDBY) return "standby"; if (code == DeviceMetricOperationalStatus.ENTEREDINERROR) return "entered-in-error"; return "?"; } public String toSystem(DeviceMetricOperationalStatus code) { return code.getSystem(); } } @Block() public static class DeviceMetricCalibrationComponent extends BackboneElement implements IBaseBackboneElement { /** * Describes the type of the calibration method. */ @Child(name = "type", type = {CodeType.class}, order=1, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="unspecified | offset | gain | two-point", formalDefinition="Describes the type of the calibration method." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/metric-calibration-type") protected Enumeration<DeviceMetricCalibrationType> type; /** * Describes the state of the calibration. */ @Child(name = "state", type = {CodeType.class}, order=2, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="not-calibrated | calibration-required | calibrated | unspecified", formalDefinition="Describes the state of the calibration." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/metric-calibration-state") protected Enumeration<DeviceMetricCalibrationState> state; /** * Describes the time last calibration has been performed. */ @Child(name = "time", type = {InstantType.class}, order=3, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Describes the time last calibration has been performed", formalDefinition="Describes the time last calibration has been performed." ) protected InstantType time; private static final long serialVersionUID = 1163986578L; /** * Constructor */ public DeviceMetricCalibrationComponent() { super(); } /** * @return {@link #type} (Describes the type of the calibration method.). This is the underlying object with id, value and extensions. The accessor "getType" gives direct access to the value */ public Enumeration<DeviceMetricCalibrationType> getTypeElement() { if (this.type == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DeviceMetricCalibrationComponent.type"); else if (Configuration.doAutoCreate()) this.type = new Enumeration<DeviceMetricCalibrationType>(new DeviceMetricCalibrationTypeEnumFactory()); // bb return this.type; } public boolean hasTypeElement() { return this.type != null && !this.type.isEmpty(); } public boolean hasType() { return this.type != null && !this.type.isEmpty(); } /** * @param value {@link #type} (Describes the type of the calibration method.). This is the underlying object with id, value and extensions. The accessor "getType" gives direct access to the value */ public DeviceMetricCalibrationComponent setTypeElement(Enumeration<DeviceMetricCalibrationType> value) { this.type = value; return this; } /** * @return Describes the type of the calibration method. */ public DeviceMetricCalibrationType getType() { return this.type == null ? null : this.type.getValue(); } /** * @param value Describes the type of the calibration method. */ public DeviceMetricCalibrationComponent setType(DeviceMetricCalibrationType value) { if (value == null) this.type = null; else { if (this.type == null) this.type = new Enumeration<DeviceMetricCalibrationType>(new DeviceMetricCalibrationTypeEnumFactory()); this.type.setValue(value); } return this; } /** * @return {@link #state} (Describes the state of the calibration.). This is the underlying object with id, value and extensions. The accessor "getState" gives direct access to the value */ public Enumeration<DeviceMetricCalibrationState> getStateElement() { if (this.state == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DeviceMetricCalibrationComponent.state"); else if (Configuration.doAutoCreate()) this.state = new Enumeration<DeviceMetricCalibrationState>(new DeviceMetricCalibrationStateEnumFactory()); // bb return this.state; } public boolean hasStateElement() { return this.state != null && !this.state.isEmpty(); } public boolean hasState() { return this.state != null && !this.state.isEmpty(); } /** * @param value {@link #state} (Describes the state of the calibration.). This is the underlying object with id, value and extensions. The accessor "getState" gives direct access to the value */ public DeviceMetricCalibrationComponent setStateElement(Enumeration<DeviceMetricCalibrationState> value) { this.state = value; return this; } /** * @return Describes the state of the calibration. */ public DeviceMetricCalibrationState getState() { return this.state == null ? null : this.state.getValue(); } /** * @param value Describes the state of the calibration. */ public DeviceMetricCalibrationComponent setState(DeviceMetricCalibrationState value) { if (value == null) this.state = null; else { if (this.state == null) this.state = new Enumeration<DeviceMetricCalibrationState>(new DeviceMetricCalibrationStateEnumFactory()); this.state.setValue(value); } return this; } /** * @return {@link #time} (Describes the time last calibration has been performed.). This is the underlying object with id, value and extensions. The accessor "getTime" gives direct access to the value */ public InstantType getTimeElement() { if (this.time == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DeviceMetricCalibrationComponent.time"); else if (Configuration.doAutoCreate()) this.time = new InstantType(); // bb return this.time; } public boolean hasTimeElement() { return this.time != null && !this.time.isEmpty(); } public boolean hasTime() { return this.time != null && !this.time.isEmpty(); } /** * @param value {@link #time} (Describes the time last calibration has been performed.). This is the underlying object with id, value and extensions. The accessor "getTime" gives direct access to the value */ public DeviceMetricCalibrationComponent setTimeElement(InstantType value) { this.time = value; return this; } /** * @return Describes the time last calibration has been performed. */ public Date getTime() { return this.time == null ? null : this.time.getValue(); } /** * @param value Describes the time last calibration has been performed. */ public DeviceMetricCalibrationComponent setTime(Date value) { if (value == null) this.time = null; else { if (this.time == null) this.time = new InstantType(); this.time.setValue(value); } return this; } protected void listChildren(List<Property> children) { super.listChildren(children); children.add(new Property("type", "code", "Describes the type of the calibration method.", 0, 1, type)); children.add(new Property("state", "code", "Describes the state of the calibration.", 0, 1, state)); children.add(new Property("time", "instant", "Describes the time last calibration has been performed.", 0, 1, time)); } @Override public Property getNamedProperty(int _hash, String _name, boolean _checkValid) throws FHIRException { switch (_hash) { case 3575610: /*type*/ return new Property("type", "code", "Describes the type of the calibration method.", 0, 1, type); case 109757585: /*state*/ return new Property("state", "code", "Describes the state of the calibration.", 0, 1, state); case 3560141: /*time*/ return new Property("time", "instant", "Describes the time last calibration has been performed.", 0, 1, time); default: return super.getNamedProperty(_hash, _name, _checkValid); } } @Override public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException { switch (hash) { case 3575610: /*type*/ return this.type == null ? new Base[0] : new Base[] {this.type}; // Enumeration<DeviceMetricCalibrationType> case 109757585: /*state*/ return this.state == null ? new Base[0] : new Base[] {this.state}; // Enumeration<DeviceMetricCalibrationState> case 3560141: /*time*/ return this.time == null ? new Base[0] : new Base[] {this.time}; // InstantType default: return super.getProperty(hash, name, checkValid); } } @Override public Base setProperty(int hash, String name, Base value) throws FHIRException { switch (hash) { case 3575610: // type value = new DeviceMetricCalibrationTypeEnumFactory().fromType(TypeConvertor.castToCode(value)); this.type = (Enumeration) value; // Enumeration<DeviceMetricCalibrationType> return value; case 109757585: // state value = new DeviceMetricCalibrationStateEnumFactory().fromType(TypeConvertor.castToCode(value)); this.state = (Enumeration) value; // Enumeration<DeviceMetricCalibrationState> return value; case 3560141: // time this.time = TypeConvertor.castToInstant(value); // InstantType return value; default: return super.setProperty(hash, name, value); } } @Override public Base setProperty(String name, Base value) throws FHIRException { if (name.equals("type")) { value = new DeviceMetricCalibrationTypeEnumFactory().fromType(TypeConvertor.castToCode(value)); this.type = (Enumeration) value; // Enumeration<DeviceMetricCalibrationType> } else if (name.equals("state")) { value = new DeviceMetricCalibrationStateEnumFactory().fromType(TypeConvertor.castToCode(value)); this.state = (Enumeration) value; // Enumeration<DeviceMetricCalibrationState> } else if (name.equals("time")) { this.time = TypeConvertor.castToInstant(value); // InstantType } else return super.setProperty(name, value); return value; } @Override public Base makeProperty(int hash, String name) throws FHIRException { switch (hash) { case 3575610: return getTypeElement(); case 109757585: return getStateElement(); case 3560141: return getTimeElement(); default: return super.makeProperty(hash, name); } } @Override public String[] getTypesForProperty(int hash, String name) throws FHIRException { switch (hash) { case 3575610: /*type*/ return new String[] {"code"}; case 109757585: /*state*/ return new String[] {"code"}; case 3560141: /*time*/ return new String[] {"instant"}; default: return super.getTypesForProperty(hash, name); } } @Override public Base addChild(String name) throws FHIRException { if (name.equals("type")) { throw new FHIRException("Cannot call addChild on a primitive type DeviceMetric.calibration.type"); } else if (name.equals("state")) { throw new FHIRException("Cannot call addChild on a primitive type DeviceMetric.calibration.state"); } else if (name.equals("time")) { throw new FHIRException("Cannot call addChild on a primitive type DeviceMetric.calibration.time"); } else return super.addChild(name); } public DeviceMetricCalibrationComponent copy() { DeviceMetricCalibrationComponent dst = new DeviceMetricCalibrationComponent(); copyValues(dst); return dst; } public void copyValues(DeviceMetricCalibrationComponent dst) { super.copyValues(dst); dst.type = type == null ? null : type.copy(); dst.state = state == null ? null : state.copy(); dst.time = time == null ? null : time.copy(); } @Override public boolean equalsDeep(Base other_) { if (!super.equalsDeep(other_)) return false; if (!(other_ instanceof DeviceMetricCalibrationComponent)) return false; DeviceMetricCalibrationComponent o = (DeviceMetricCalibrationComponent) other_; return compareDeep(type, o.type, true) && compareDeep(state, o.state, true) && compareDeep(time, o.time, true) ; } @Override public boolean equalsShallow(Base other_) { if (!super.equalsShallow(other_)) return false; if (!(other_ instanceof DeviceMetricCalibrationComponent)) return false; DeviceMetricCalibrationComponent o = (DeviceMetricCalibrationComponent) other_; return compareValues(type, o.type, true) && compareValues(state, o.state, true) && compareValues(time, o.time, true) ; } public boolean isEmpty() { return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(type, state, time); } public String fhirType() { return "DeviceMetric.calibration"; } } /** * Unique instance identifiers assigned to a device by the device or gateway software, manufacturers, other organizations or owners. For example: handle ID. */ @Child(name = "identifier", type = {Identifier.class}, order=0, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="Instance identifier", formalDefinition="Unique instance identifiers assigned to a device by the device or gateway software, manufacturers, other organizations or owners. For example: handle ID." ) protected List<Identifier> identifier; /** * Describes the type of the metric. For example: Heart Rate, PEEP Setting, etc. */ @Child(name = "type", type = {CodeableConcept.class}, order=1, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="Identity of metric, for example Heart Rate or PEEP Setting", formalDefinition="Describes the type of the metric. For example: Heart Rate, PEEP Setting, etc." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/devicemetric-type") protected CodeableConcept type; /** * Describes the unit that an observed value determined for this metric will have. For example: Percent, Seconds, etc. */ @Child(name = "unit", type = {CodeableConcept.class}, order=2, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Unit of Measure for the Metric", formalDefinition="Describes the unit that an observed value determined for this metric will have. For example: Percent, Seconds, etc." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/devicemetric-type") protected CodeableConcept unit; /** * Describes the link to the Device that this DeviceMetric belongs to and that contains administrative device information such as manufacturer, serial number, etc. */ @Child(name = "source", type = {Device.class}, order=3, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Describes the link to the source Device", formalDefinition="Describes the link to the Device that this DeviceMetric belongs to and that contains administrative device information such as manufacturer, serial number, etc." ) protected Reference source; /** * Describes the link to the Device that this DeviceMetric belongs to and that provide information about the location of this DeviceMetric in the containment structure of the parent Device. An example would be a Device that represents a Channel. This reference can be used by a client application to distinguish DeviceMetrics that have the same type, but should be interpreted based on their containment location. */ @Child(name = "parent", type = {Device.class}, order=4, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Describes the link to the parent Device", formalDefinition="Describes the link to the Device that this DeviceMetric belongs to and that provide information about the location of this DeviceMetric in the containment structure of the parent Device. An example would be a Device that represents a Channel. This reference can be used by a client application to distinguish DeviceMetrics that have the same type, but should be interpreted based on their containment location." ) protected Reference parent; /** * Indicates current operational state of the device. For example: On, Off, Standby, etc. */ @Child(name = "operationalStatus", type = {CodeType.class}, order=5, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="on | off | standby | entered-in-error", formalDefinition="Indicates current operational state of the device. For example: On, Off, Standby, etc." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/metric-operational-status") protected Enumeration<DeviceMetricOperationalStatus> operationalStatus; /** * Describes the color representation for the metric. This is often used to aid clinicians to track and identify parameter types by color. In practice, consider a Patient Monitor that has ECG/HR and Pleth for example; the parameters are displayed in different characteristic colors, such as HR-blue, BP-green, and PR and SpO2- magenta. */ @Child(name = "color", type = {CodeType.class}, order=6, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="black | red | green | yellow | blue | magenta | cyan | white", formalDefinition="Describes the color representation for the metric. This is often used to aid clinicians to track and identify parameter types by color. In practice, consider a Patient Monitor that has ECG/HR and Pleth for example; the parameters are displayed in different characteristic colors, such as HR-blue, BP-green, and PR and SpO2- magenta." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/metric-color") protected Enumeration<DeviceMetricColor> color; /** * Indicates the category of the observation generation process. A DeviceMetric can be for example a setting, measurement, or calculation. */ @Child(name = "category", type = {CodeType.class}, order=7, min=1, max=1, modifier=false, summary=true) @Description(shortDefinition="measurement | setting | calculation | unspecified", formalDefinition="Indicates the category of the observation generation process. A DeviceMetric can be for example a setting, measurement, or calculation." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/metric-category") protected Enumeration<DeviceMetricCategory> category; /** * Describes the measurement repetition time. This is not necessarily the same as the update period. The measurement repetition time can range from milliseconds up to hours. An example for a measurement repetition time in the range of milliseconds is the sampling rate of an ECG. An example for a measurement repetition time in the range of hours is a NIBP that is triggered automatically every hour. The update period may be different than the measurement repetition time, if the device does not update the published observed value with the same frequency as it was measured. */ @Child(name = "measurementPeriod", type = {Timing.class}, order=8, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Describes the measurement repetition time", formalDefinition="Describes the measurement repetition time. This is not necessarily the same as the update period. The measurement repetition time can range from milliseconds up to hours. An example for a measurement repetition time in the range of milliseconds is the sampling rate of an ECG. An example for a measurement repetition time in the range of hours is a NIBP that is triggered automatically every hour. The update period may be different than the measurement repetition time, if the device does not update the published observed value with the same frequency as it was measured." ) protected Timing measurementPeriod; /** * Describes the calibrations that have been performed or that are required to be performed. */ @Child(name = "calibration", type = {}, order=9, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="Describes the calibrations that have been performed or that are required to be performed", formalDefinition="Describes the calibrations that have been performed or that are required to be performed." ) protected List<DeviceMetricCalibrationComponent> calibration; private static final long serialVersionUID = 2132964036L; /** * Constructor */ public DeviceMetric() { super(); } /** * Constructor */ public DeviceMetric(CodeableConcept type, DeviceMetricCategory category) { super(); this.setType(type); this.setCategory(category); } /** * @return {@link #identifier} (Unique instance identifiers assigned to a device by the device or gateway software, manufacturers, other organizations or owners. For example: handle ID.) */ public List<Identifier> getIdentifier() { if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); return this.identifier; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public DeviceMetric setIdentifier(List<Identifier> theIdentifier) { this.identifier = theIdentifier; return this; } public boolean hasIdentifier() { if (this.identifier == null) return false; for (Identifier item : this.identifier) if (!item.isEmpty()) return true; return false; } public Identifier addIdentifier() { //3 Identifier t = new Identifier(); if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); this.identifier.add(t); return t; } public DeviceMetric addIdentifier(Identifier t) { //3 if (t == null) return this; if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); this.identifier.add(t); return this; } /** * @return The first repetition of repeating field {@link #identifier}, creating it if it does not already exist {3} */ public Identifier getIdentifierFirstRep() { if (getIdentifier().isEmpty()) { addIdentifier(); } return getIdentifier().get(0); } /** * @return {@link #type} (Describes the type of the metric. For example: Heart Rate, PEEP Setting, etc.) */ public CodeableConcept getType() { if (this.type == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DeviceMetric.type"); else if (Configuration.doAutoCreate()) this.type = new CodeableConcept(); // cc return this.type; } public boolean hasType() { return this.type != null && !this.type.isEmpty(); } /** * @param value {@link #type} (Describes the type of the metric. For example: Heart Rate, PEEP Setting, etc.) */ public DeviceMetric setType(CodeableConcept value) { this.type = value; return this; } /** * @return {@link #unit} (Describes the unit that an observed value determined for this metric will have. For example: Percent, Seconds, etc.) */ public CodeableConcept getUnit() { if (this.unit == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DeviceMetric.unit"); else if (Configuration.doAutoCreate()) this.unit = new CodeableConcept(); // cc return this.unit; } public boolean hasUnit() { return this.unit != null && !this.unit.isEmpty(); } /** * @param value {@link #unit} (Describes the unit that an observed value determined for this metric will have. For example: Percent, Seconds, etc.) */ public DeviceMetric setUnit(CodeableConcept value) { this.unit = value; return this; } /** * @return {@link #source} (Describes the link to the Device that this DeviceMetric belongs to and that contains administrative device information such as manufacturer, serial number, etc.) */ public Reference getSource() { if (this.source == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DeviceMetric.source"); else if (Configuration.doAutoCreate()) this.source = new Reference(); // cc return this.source; } public boolean hasSource() { return this.source != null && !this.source.isEmpty(); } /** * @param value {@link #source} (Describes the link to the Device that this DeviceMetric belongs to and that contains administrative device information such as manufacturer, serial number, etc.) */ public DeviceMetric setSource(Reference value) { this.source = value; return this; } /** * @return {@link #parent} (Describes the link to the Device that this DeviceMetric belongs to and that provide information about the location of this DeviceMetric in the containment structure of the parent Device. An example would be a Device that represents a Channel. This reference can be used by a client application to distinguish DeviceMetrics that have the same type, but should be interpreted based on their containment location.) */ public Reference getParent() { if (this.parent == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DeviceMetric.parent"); else if (Configuration.doAutoCreate()) this.parent = new Reference(); // cc return this.parent; } public boolean hasParent() { return this.parent != null && !this.parent.isEmpty(); } /** * @param value {@link #parent} (Describes the link to the Device that this DeviceMetric belongs to and that provide information about the location of this DeviceMetric in the containment structure of the parent Device. An example would be a Device that represents a Channel. This reference can be used by a client application to distinguish DeviceMetrics that have the same type, but should be interpreted based on their containment location.) */ public DeviceMetric setParent(Reference value) { this.parent = value; return this; } /** * @return {@link #operationalStatus} (Indicates current operational state of the device. For example: On, Off, Standby, etc.). This is the underlying object with id, value and extensions. The accessor "getOperationalStatus" gives direct access to the value */ public Enumeration<DeviceMetricOperationalStatus> getOperationalStatusElement() { if (this.operationalStatus == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DeviceMetric.operationalStatus"); else if (Configuration.doAutoCreate()) this.operationalStatus = new Enumeration<DeviceMetricOperationalStatus>(new DeviceMetricOperationalStatusEnumFactory()); // bb return this.operationalStatus; } public boolean hasOperationalStatusElement() { return this.operationalStatus != null && !this.operationalStatus.isEmpty(); } public boolean hasOperationalStatus() { return this.operationalStatus != null && !this.operationalStatus.isEmpty(); } /** * @param value {@link #operationalStatus} (Indicates current operational state of the device. For example: On, Off, Standby, etc.). This is the underlying object with id, value and extensions. The accessor "getOperationalStatus" gives direct access to the value */ public DeviceMetric setOperationalStatusElement(Enumeration<DeviceMetricOperationalStatus> value) { this.operationalStatus = value; return this; } /** * @return Indicates current operational state of the device. For example: On, Off, Standby, etc. */ public DeviceMetricOperationalStatus getOperationalStatus() { return this.operationalStatus == null ? null : this.operationalStatus.getValue(); } /** * @param value Indicates current operational state of the device. For example: On, Off, Standby, etc. */ public DeviceMetric setOperationalStatus(DeviceMetricOperationalStatus value) { if (value == null) this.operationalStatus = null; else { if (this.operationalStatus == null) this.operationalStatus = new Enumeration<DeviceMetricOperationalStatus>(new DeviceMetricOperationalStatusEnumFactory()); this.operationalStatus.setValue(value); } return this; } /** * @return {@link #color} (Describes the color representation for the metric. This is often used to aid clinicians to track and identify parameter types by color. In practice, consider a Patient Monitor that has ECG/HR and Pleth for example; the parameters are displayed in different characteristic colors, such as HR-blue, BP-green, and PR and SpO2- magenta.). This is the underlying object with id, value and extensions. The accessor "getColor" gives direct access to the value */ public Enumeration<DeviceMetricColor> getColorElement() { if (this.color == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DeviceMetric.color"); else if (Configuration.doAutoCreate()) this.color = new Enumeration<DeviceMetricColor>(new DeviceMetricColorEnumFactory()); // bb return this.color; } public boolean hasColorElement() { return this.color != null && !this.color.isEmpty(); } public boolean hasColor() { return this.color != null && !this.color.isEmpty(); } /** * @param value {@link #color} (Describes the color representation for the metric. This is often used to aid clinicians to track and identify parameter types by color. In practice, consider a Patient Monitor that has ECG/HR and Pleth for example; the parameters are displayed in different characteristic colors, such as HR-blue, BP-green, and PR and SpO2- magenta.). This is the underlying object with id, value and extensions. The accessor "getColor" gives direct access to the value */ public DeviceMetric setColorElement(Enumeration<DeviceMetricColor> value) { this.color = value; return this; } /** * @return Describes the color representation for the metric. This is often used to aid clinicians to track and identify parameter types by color. In practice, consider a Patient Monitor that has ECG/HR and Pleth for example; the parameters are displayed in different characteristic colors, such as HR-blue, BP-green, and PR and SpO2- magenta. */ public DeviceMetricColor getColor() { return this.color == null ? null : this.color.getValue(); } /** * @param value Describes the color representation for the metric. This is often used to aid clinicians to track and identify parameter types by color. In practice, consider a Patient Monitor that has ECG/HR and Pleth for example; the parameters are displayed in different characteristic colors, such as HR-blue, BP-green, and PR and SpO2- magenta. */ public DeviceMetric setColor(DeviceMetricColor value) { if (value == null) this.color = null; else { if (this.color == null) this.color = new Enumeration<DeviceMetricColor>(new DeviceMetricColorEnumFactory()); this.color.setValue(value); } return this; } /** * @return {@link #category} (Indicates the category of the observation generation process. A DeviceMetric can be for example a setting, measurement, or calculation.). This is the underlying object with id, value and extensions. The accessor "getCategory" gives direct access to the value */ public Enumeration<DeviceMetricCategory> getCategoryElement() { if (this.category == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DeviceMetric.category"); else if (Configuration.doAutoCreate()) this.category = new Enumeration<DeviceMetricCategory>(new DeviceMetricCategoryEnumFactory()); // bb return this.category; } public boolean hasCategoryElement() { return this.category != null && !this.category.isEmpty(); } public boolean hasCategory() { return this.category != null && !this.category.isEmpty(); } /** * @param value {@link #category} (Indicates the category of the observation generation process. A DeviceMetric can be for example a setting, measurement, or calculation.). This is the underlying object with id, value and extensions. The accessor "getCategory" gives direct access to the value */ public DeviceMetric setCategoryElement(Enumeration<DeviceMetricCategory> value) { this.category = value; return this; } /** * @return Indicates the category of the observation generation process. A DeviceMetric can be for example a setting, measurement, or calculation. */ public DeviceMetricCategory getCategory() { return this.category == null ? null : this.category.getValue(); } /** * @param value Indicates the category of the observation generation process. A DeviceMetric can be for example a setting, measurement, or calculation. */ public DeviceMetric setCategory(DeviceMetricCategory value) { if (this.category == null) this.category = new Enumeration<DeviceMetricCategory>(new DeviceMetricCategoryEnumFactory()); this.category.setValue(value); return this; } /** * @return {@link #measurementPeriod} (Describes the measurement repetition time. This is not necessarily the same as the update period. The measurement repetition time can range from milliseconds up to hours. An example for a measurement repetition time in the range of milliseconds is the sampling rate of an ECG. An example for a measurement repetition time in the range of hours is a NIBP that is triggered automatically every hour. The update period may be different than the measurement repetition time, if the device does not update the published observed value with the same frequency as it was measured.) */ public Timing getMeasurementPeriod() { if (this.measurementPeriod == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create DeviceMetric.measurementPeriod"); else if (Configuration.doAutoCreate()) this.measurementPeriod = new Timing(); // cc return this.measurementPeriod; } public boolean hasMeasurementPeriod() { return this.measurementPeriod != null && !this.measurementPeriod.isEmpty(); } /** * @param value {@link #measurementPeriod} (Describes the measurement repetition time. This is not necessarily the same as the update period. The measurement repetition time can range from milliseconds up to hours. An example for a measurement repetition time in the range of milliseconds is the sampling rate of an ECG. An example for a measurement repetition time in the range of hours is a NIBP that is triggered automatically every hour. The update period may be different than the measurement repetition time, if the device does not update the published observed value with the same frequency as it was measured.) */ public DeviceMetric setMeasurementPeriod(Timing value) { this.measurementPeriod = value; return this; } /** * @return {@link #calibration} (Describes the calibrations that have been performed or that are required to be performed.) */ public List<DeviceMetricCalibrationComponent> getCalibration() { if (this.calibration == null) this.calibration = new ArrayList<DeviceMetricCalibrationComponent>(); return this.calibration; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public DeviceMetric setCalibration(List<DeviceMetricCalibrationComponent> theCalibration) { this.calibration = theCalibration; return this; } public boolean hasCalibration() { if (this.calibration == null) return false; for (DeviceMetricCalibrationComponent item : this.calibration) if (!item.isEmpty()) return true; return false; } public DeviceMetricCalibrationComponent addCalibration() { //3 DeviceMetricCalibrationComponent t = new DeviceMetricCalibrationComponent(); if (this.calibration == null) this.calibration = new ArrayList<DeviceMetricCalibrationComponent>(); this.calibration.add(t); return t; } public DeviceMetric addCalibration(DeviceMetricCalibrationComponent t) { //3 if (t == null) return this; if (this.calibration == null) this.calibration = new ArrayList<DeviceMetricCalibrationComponent>(); this.calibration.add(t); return this; } /** * @return The first repetition of repeating field {@link #calibration}, creating it if it does not already exist {3} */ public DeviceMetricCalibrationComponent getCalibrationFirstRep() { if (getCalibration().isEmpty()) { addCalibration(); } return getCalibration().get(0); } protected void listChildren(List<Property> children) { super.listChildren(children); children.add(new Property("identifier", "Identifier", "Unique instance identifiers assigned to a device by the device or gateway software, manufacturers, other organizations or owners. For example: handle ID.", 0, java.lang.Integer.MAX_VALUE, identifier)); children.add(new Property("type", "CodeableConcept", "Describes the type of the metric. For example: Heart Rate, PEEP Setting, etc.", 0, 1, type)); children.add(new Property("unit", "CodeableConcept", "Describes the unit that an observed value determined for this metric will have. For example: Percent, Seconds, etc.", 0, 1, unit)); children.add(new Property("source", "Reference(Device)", "Describes the link to the Device that this DeviceMetric belongs to and that contains administrative device information such as manufacturer, serial number, etc.", 0, 1, source)); children.add(new Property("parent", "Reference(Device)", "Describes the link to the Device that this DeviceMetric belongs to and that provide information about the location of this DeviceMetric in the containment structure of the parent Device. An example would be a Device that represents a Channel. This reference can be used by a client application to distinguish DeviceMetrics that have the same type, but should be interpreted based on their containment location.", 0, 1, parent)); children.add(new Property("operationalStatus", "code", "Indicates current operational state of the device. For example: On, Off, Standby, etc.", 0, 1, operationalStatus)); children.add(new Property("color", "code", "Describes the color representation for the metric. This is often used to aid clinicians to track and identify parameter types by color. In practice, consider a Patient Monitor that has ECG/HR and Pleth for example; the parameters are displayed in different characteristic colors, such as HR-blue, BP-green, and PR and SpO2- magenta.", 0, 1, color)); children.add(new Property("category", "code", "Indicates the category of the observation generation process. A DeviceMetric can be for example a setting, measurement, or calculation.", 0, 1, category)); children.add(new Property("measurementPeriod", "Timing", "Describes the measurement repetition time. This is not necessarily the same as the update period. The measurement repetition time can range from milliseconds up to hours. An example for a measurement repetition time in the range of milliseconds is the sampling rate of an ECG. An example for a measurement repetition time in the range of hours is a NIBP that is triggered automatically every hour. The update period may be different than the measurement repetition time, if the device does not update the published observed value with the same frequency as it was measured.", 0, 1, measurementPeriod)); children.add(new Property("calibration", "", "Describes the calibrations that have been performed or that are required to be performed.", 0, java.lang.Integer.MAX_VALUE, calibration)); } @Override public Property getNamedProperty(int _hash, String _name, boolean _checkValid) throws FHIRException { switch (_hash) { case -1618432855: /*identifier*/ return new Property("identifier", "Identifier", "Unique instance identifiers assigned to a device by the device or gateway software, manufacturers, other organizations or owners. For example: handle ID.", 0, java.lang.Integer.MAX_VALUE, identifier); case 3575610: /*type*/ return new Property("type", "CodeableConcept", "Describes the type of the metric. For example: Heart Rate, PEEP Setting, etc.", 0, 1, type); case 3594628: /*unit*/ return new Property("unit", "CodeableConcept", "Describes the unit that an observed value determined for this metric will have. For example: Percent, Seconds, etc.", 0, 1, unit); case -896505829: /*source*/ return new Property("source", "Reference(Device)", "Describes the link to the Device that this DeviceMetric belongs to and that contains administrative device information such as manufacturer, serial number, etc.", 0, 1, source); case -995424086: /*parent*/ return new Property("parent", "Reference(Device)", "Describes the link to the Device that this DeviceMetric belongs to and that provide information about the location of this DeviceMetric in the containment structure of the parent Device. An example would be a Device that represents a Channel. This reference can be used by a client application to distinguish DeviceMetrics that have the same type, but should be interpreted based on their containment location.", 0, 1, parent); case -2103166364: /*operationalStatus*/ return new Property("operationalStatus", "code", "Indicates current operational state of the device. For example: On, Off, Standby, etc.", 0, 1, operationalStatus); case 94842723: /*color*/ return new Property("color", "code", "Describes the color representation for the metric. This is often used to aid clinicians to track and identify parameter types by color. In practice, consider a Patient Monitor that has ECG/HR and Pleth for example; the parameters are displayed in different characteristic colors, such as HR-blue, BP-green, and PR and SpO2- magenta.", 0, 1, color); case 50511102: /*category*/ return new Property("category", "code", "Indicates the category of the observation generation process. A DeviceMetric can be for example a setting, measurement, or calculation.", 0, 1, category); case -1300332387: /*measurementPeriod*/ return new Property("measurementPeriod", "Timing", "Describes the measurement repetition time. This is not necessarily the same as the update period. The measurement repetition time can range from milliseconds up to hours. An example for a measurement repetition time in the range of milliseconds is the sampling rate of an ECG. An example for a measurement repetition time in the range of hours is a NIBP that is triggered automatically every hour. The update period may be different than the measurement repetition time, if the device does not update the published observed value with the same frequency as it was measured.", 0, 1, measurementPeriod); case 1421318634: /*calibration*/ return new Property("calibration", "", "Describes the calibrations that have been performed or that are required to be performed.", 0, java.lang.Integer.MAX_VALUE, calibration); default: return super.getNamedProperty(_hash, _name, _checkValid); } } @Override public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException { switch (hash) { case -1618432855: /*identifier*/ return this.identifier == null ? new Base[0] : this.identifier.toArray(new Base[this.identifier.size()]); // Identifier case 3575610: /*type*/ return this.type == null ? new Base[0] : new Base[] {this.type}; // CodeableConcept case 3594628: /*unit*/ return this.unit == null ? new Base[0] : new Base[] {this.unit}; // CodeableConcept case -896505829: /*source*/ return this.source == null ? new Base[0] : new Base[] {this.source}; // Reference case -995424086: /*parent*/ return this.parent == null ? new Base[0] : new Base[] {this.parent}; // Reference case -2103166364: /*operationalStatus*/ return this.operationalStatus == null ? new Base[0] : new Base[] {this.operationalStatus}; // Enumeration<DeviceMetricOperationalStatus> case 94842723: /*color*/ return this.color == null ? new Base[0] : new Base[] {this.color}; // Enumeration<DeviceMetricColor> case 50511102: /*category*/ return this.category == null ? new Base[0] : new Base[] {this.category}; // Enumeration<DeviceMetricCategory> case -1300332387: /*measurementPeriod*/ return this.measurementPeriod == null ? new Base[0] : new Base[] {this.measurementPeriod}; // Timing case 1421318634: /*calibration*/ return this.calibration == null ? new Base[0] : this.calibration.toArray(new Base[this.calibration.size()]); // DeviceMetricCalibrationComponent default: return super.getProperty(hash, name, checkValid); } } @Override public Base setProperty(int hash, String name, Base value) throws FHIRException { switch (hash) { case -1618432855: // identifier this.getIdentifier().add(TypeConvertor.castToIdentifier(value)); // Identifier return value; case 3575610: // type this.type = TypeConvertor.castToCodeableConcept(value); // CodeableConcept return value; case 3594628: // unit this.unit = TypeConvertor.castToCodeableConcept(value); // CodeableConcept return value; case -896505829: // source this.source = TypeConvertor.castToReference(value); // Reference return value; case -995424086: // parent this.parent = TypeConvertor.castToReference(value); // Reference return value; case -2103166364: // operationalStatus value = new DeviceMetricOperationalStatusEnumFactory().fromType(TypeConvertor.castToCode(value)); this.operationalStatus = (Enumeration) value; // Enumeration<DeviceMetricOperationalStatus> return value; case 94842723: // color value = new DeviceMetricColorEnumFactory().fromType(TypeConvertor.castToCode(value)); this.color = (Enumeration) value; // Enumeration<DeviceMetricColor> return value; case 50511102: // category value = new DeviceMetricCategoryEnumFactory().fromType(TypeConvertor.castToCode(value)); this.category = (Enumeration) value; // Enumeration<DeviceMetricCategory> return value; case -1300332387: // measurementPeriod this.measurementPeriod = TypeConvertor.castToTiming(value); // Timing return value; case 1421318634: // calibration this.getCalibration().add((DeviceMetricCalibrationComponent) value); // DeviceMetricCalibrationComponent return value; default: return super.setProperty(hash, name, value); } } @Override public Base setProperty(String name, Base value) throws FHIRException { if (name.equals("identifier")) { this.getIdentifier().add(TypeConvertor.castToIdentifier(value)); } else if (name.equals("type")) { this.type = TypeConvertor.castToCodeableConcept(value); // CodeableConcept } else if (name.equals("unit")) { this.unit = TypeConvertor.castToCodeableConcept(value); // CodeableConcept } else if (name.equals("source")) { this.source = TypeConvertor.castToReference(value); // Reference } else if (name.equals("parent")) { this.parent = TypeConvertor.castToReference(value); // Reference } else if (name.equals("operationalStatus")) { value = new DeviceMetricOperationalStatusEnumFactory().fromType(TypeConvertor.castToCode(value)); this.operationalStatus = (Enumeration) value; // Enumeration<DeviceMetricOperationalStatus> } else if (name.equals("color")) { value = new DeviceMetricColorEnumFactory().fromType(TypeConvertor.castToCode(value)); this.color = (Enumeration) value; // Enumeration<DeviceMetricColor> } else if (name.equals("category")) { value = new DeviceMetricCategoryEnumFactory().fromType(TypeConvertor.castToCode(value)); this.category = (Enumeration) value; // Enumeration<DeviceMetricCategory> } else if (name.equals("measurementPeriod")) { this.measurementPeriod = TypeConvertor.castToTiming(value); // Timing } else if (name.equals("calibration")) { this.getCalibration().add((DeviceMetricCalibrationComponent) value); } else return super.setProperty(name, value); return value; } @Override public Base makeProperty(int hash, String name) throws FHIRException { switch (hash) { case -1618432855: return addIdentifier(); case 3575610: return getType(); case 3594628: return getUnit(); case -896505829: return getSource(); case -995424086: return getParent(); case -2103166364: return getOperationalStatusElement(); case 94842723: return getColorElement(); case 50511102: return getCategoryElement(); case -1300332387: return getMeasurementPeriod(); case 1421318634: return addCalibration(); default: return super.makeProperty(hash, name); } } @Override public String[] getTypesForProperty(int hash, String name) throws FHIRException { switch (hash) { case -1618432855: /*identifier*/ return new String[] {"Identifier"}; case 3575610: /*type*/ return new String[] {"CodeableConcept"}; case 3594628: /*unit*/ return new String[] {"CodeableConcept"}; case -896505829: /*source*/ return new String[] {"Reference"}; case -995424086: /*parent*/ return new String[] {"Reference"}; case -2103166364: /*operationalStatus*/ return new String[] {"code"}; case 94842723: /*color*/ return new String[] {"code"}; case 50511102: /*category*/ return new String[] {"code"}; case -1300332387: /*measurementPeriod*/ return new String[] {"Timing"}; case 1421318634: /*calibration*/ return new String[] {}; default: return super.getTypesForProperty(hash, name); } } @Override public Base addChild(String name) throws FHIRException { if (name.equals("identifier")) { return addIdentifier(); } else if (name.equals("type")) { this.type = new CodeableConcept(); return this.type; } else if (name.equals("unit")) { this.unit = new CodeableConcept(); return this.unit; } else if (name.equals("source")) { this.source = new Reference(); return this.source; } else if (name.equals("parent")) { this.parent = new Reference(); return this.parent; } else if (name.equals("operationalStatus")) { throw new FHIRException("Cannot call addChild on a primitive type DeviceMetric.operationalStatus"); } else if (name.equals("color")) { throw new FHIRException("Cannot call addChild on a primitive type DeviceMetric.color"); } else if (name.equals("category")) { throw new FHIRException("Cannot call addChild on a primitive type DeviceMetric.category"); } else if (name.equals("measurementPeriod")) { this.measurementPeriod = new Timing(); return this.measurementPeriod; } else if (name.equals("calibration")) { return addCalibration(); } else return super.addChild(name); } public String fhirType() { return "DeviceMetric"; } public DeviceMetric copy() { DeviceMetric dst = new DeviceMetric(); copyValues(dst); return dst; } public void copyValues(DeviceMetric dst) { super.copyValues(dst); if (identifier != null) { dst.identifier = new ArrayList<Identifier>(); for (Identifier i : identifier) dst.identifier.add(i.copy()); }; dst.type = type == null ? null : type.copy(); dst.unit = unit == null ? null : unit.copy(); dst.source = source == null ? null : source.copy(); dst.parent = parent == null ? null : parent.copy(); dst.operationalStatus = operationalStatus == null ? null : operationalStatus.copy(); dst.color = color == null ? null : color.copy(); dst.category = category == null ? null : category.copy(); dst.measurementPeriod = measurementPeriod == null ? null : measurementPeriod.copy(); if (calibration != null) { dst.calibration = new ArrayList<DeviceMetricCalibrationComponent>(); for (DeviceMetricCalibrationComponent i : calibration) dst.calibration.add(i.copy()); }; } protected DeviceMetric typedCopy() { return copy(); } @Override public boolean equalsDeep(Base other_) { if (!super.equalsDeep(other_)) return false; if (!(other_ instanceof DeviceMetric)) return false; DeviceMetric o = (DeviceMetric) other_; return compareDeep(identifier, o.identifier, true) && compareDeep(type, o.type, true) && compareDeep(unit, o.unit, true) && compareDeep(source, o.source, true) && compareDeep(parent, o.parent, true) && compareDeep(operationalStatus, o.operationalStatus, true) && compareDeep(color, o.color, true) && compareDeep(category, o.category, true) && compareDeep(measurementPeriod, o.measurementPeriod, true) && compareDeep(calibration, o.calibration, true); } @Override public boolean equalsShallow(Base other_) { if (!super.equalsShallow(other_)) return false; if (!(other_ instanceof DeviceMetric)) return false; DeviceMetric o = (DeviceMetric) other_; return compareValues(operationalStatus, o.operationalStatus, true) && compareValues(color, o.color, true) && compareValues(category, o.category, true); } public boolean isEmpty() { return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(identifier, type, unit, source , parent, operationalStatus, color, category, measurementPeriod, calibration); } @Override public ResourceType getResourceType() { return ResourceType.DeviceMetric; } /** * Search parameter: <b>category</b> * <p> * Description: <b>The category of the metric</b><br> * Type: <b>token</b><br> * Path: <b>DeviceMetric.category</b><br> * </p> */ @SearchParamDefinition(name="category", path="DeviceMetric.category", description="The category of the metric", type="token" ) public static final String SP_CATEGORY = "category"; /** * <b>Fluent Client</b> search parameter constant for <b>category</b> * <p> * Description: <b>The category of the metric</b><br> * Type: <b>token</b><br> * Path: <b>DeviceMetric.category</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam CATEGORY = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_CATEGORY); /** * Search parameter: <b>identifier</b> * <p> * Description: <b>The identifier of the metric</b><br> * Type: <b>token</b><br> * Path: <b>DeviceMetric.identifier</b><br> * </p> */ @SearchParamDefinition(name="identifier", path="DeviceMetric.identifier", description="The identifier of the metric", type="token" ) public static final String SP_IDENTIFIER = "identifier"; /** * <b>Fluent Client</b> search parameter constant for <b>identifier</b> * <p> * Description: <b>The identifier of the metric</b><br> * Type: <b>token</b><br> * Path: <b>DeviceMetric.identifier</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam IDENTIFIER = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_IDENTIFIER); /** * Search parameter: <b>parent</b> * <p> * Description: <b>The parent DeviceMetric resource</b><br> * Type: <b>reference</b><br> * Path: <b>DeviceMetric.parent</b><br> * </p> */ @SearchParamDefinition(name="parent", path="DeviceMetric.parent", description="The parent DeviceMetric resource", type="reference", target={Device.class } ) public static final String SP_PARENT = "parent"; /** * <b>Fluent Client</b> search parameter constant for <b>parent</b> * <p> * Description: <b>The parent DeviceMetric resource</b><br> * Type: <b>reference</b><br> * Path: <b>DeviceMetric.parent</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam PARENT = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_PARENT); /** * Constant for fluent queries to be used to add include statements. Specifies * the path value of "<b>DeviceMetric:parent</b>". */ public static final ca.uhn.fhir.model.api.Include INCLUDE_PARENT = new ca.uhn.fhir.model.api.Include("DeviceMetric:parent").toLocked(); /** * Search parameter: <b>source</b> * <p> * Description: <b>The device resource</b><br> * Type: <b>reference</b><br> * Path: <b>DeviceMetric.source</b><br> * </p> */ @SearchParamDefinition(name="source", path="DeviceMetric.source", description="The device resource", type="reference", target={Device.class } ) public static final String SP_SOURCE = "source"; /** * <b>Fluent Client</b> search parameter constant for <b>source</b> * <p> * Description: <b>The device resource</b><br> * Type: <b>reference</b><br> * Path: <b>DeviceMetric.source</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam SOURCE = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_SOURCE); /** * Constant for fluent queries to be used to add include statements. Specifies * the path value of "<b>DeviceMetric:source</b>". */ public static final ca.uhn.fhir.model.api.Include INCLUDE_SOURCE = new ca.uhn.fhir.model.api.Include("DeviceMetric:source").toLocked(); /** * Search parameter: <b>type</b> * <p> * Description: <b>The component type</b><br> * Type: <b>token</b><br> * Path: <b>DeviceMetric.type</b><br> * </p> */ @SearchParamDefinition(name="type", path="DeviceMetric.type", description="The component type", type="token" ) public static final String SP_TYPE = "type"; /** * <b>Fluent Client</b> search parameter constant for <b>type</b> * <p> * Description: <b>The component type</b><br> * Type: <b>token</b><br> * Path: <b>DeviceMetric.type</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam TYPE = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_TYPE); }
3e0cdfaea8d73519758572c93303653eaa1b3118
4,866
java
Java
app/src/main/java/com/amsavarthan/dudepolice/utils/UserDatabase.java
amsavarthan/DUDE-POLICE
58025167dde3df29f17f49553660a547ae39e292
[ "MIT" ]
null
null
null
app/src/main/java/com/amsavarthan/dudepolice/utils/UserDatabase.java
amsavarthan/DUDE-POLICE
58025167dde3df29f17f49553660a547ae39e292
[ "MIT" ]
null
null
null
app/src/main/java/com/amsavarthan/dudepolice/utils/UserDatabase.java
amsavarthan/DUDE-POLICE
58025167dde3df29f17f49553660a547ae39e292
[ "MIT" ]
null
null
null
39.560976
129
0.662557
5,458
package com.amsavarthan.dudepolice.utils; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.HashMap; public class UserDatabase extends SQLiteOpenHelper { public static final String DATABASE_NAME = "users.db"; public static final String CONTACTS_TABLE_NAME = "user"; public static final String CONTACTS_COLUMN_ID = "id"; public static final String CONTACTS_COLUMN_NAME = "name"; public static final String CONTACTS_COLUMN_PHONE = "phone"; public static final String CONTACTS_COLUMN_POST = "posting"; public static final String CONTACTS_COLUMN_CITY = "city"; public static final String CONTACTS_COLUMN_STATE = "state"; public static final String CONTACTS_COLUMN_AGE = "age"; private HashMap hp; public UserDatabase(Context context) { super(context, DATABASE_NAME , null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL( "create table user " + "(id integer primary key,name text,phone text,age text,posting text,city text,state text)" ); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS user"); onCreate(db); } public void insertContact(String name,String phone,String city,String posting,String state,String age) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", name); contentValues.put("phone", phone); contentValues.put("city", city); contentValues.put("posting", posting); contentValues.put("state", state); contentValues.put("age", age); db.insert("user", null, contentValues); } public Cursor getData(int id) { SQLiteDatabase db = this.getReadableDatabase(); return db.rawQuery( "select * from user where id="+id+"", null ); } public boolean updateContact(Integer id,String name,String phone,String city,String posting,String state,String age) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", name); contentValues.put("phone", phone); contentValues.put("city", city); contentValues.put("posting", posting); contentValues.put("state", state); contentValues.put("age", age); db.update("user", contentValues, "id = ? ", new String[] { Integer.toString(id) } ); return true; } public void updateContactName(Integer id, String name) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", name); db.update("user", contentValues, "id = ? ", new String[] { Integer.toString(id) } ); } public void updateContactPhone(Integer id, String phone) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("phone", phone); db.update("user", contentValues, "id = ? ", new String[] { Integer.toString(id) } ); } public void updateContactCity(Integer id, String city) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("city", city); db.update("user", contentValues, "id = ? ", new String[] { Integer.toString(id) } ); } public void updateContactState(Integer id, String state) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("state", state); db.update("user", contentValues, "id = ? ", new String[] { Integer.toString(id) } ); } public void updateContactAge(Integer id, String age) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("age", age); db.update("user", contentValues, "id = ? ", new String[] { Integer.toString(id) } ); } public void updateContactPost(Integer id, String posting) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("posting", posting); db.update("user", contentValues, "id = ? ", new String[] { Integer.toString(id) } ); } public Integer deleteContact (Integer id) { SQLiteDatabase db = this.getWritableDatabase(); return db.delete("user", "id = ? ", new String[] { Integer.toString(id) }); } }
3e0cdfaf19c3465a388c2d4035b44b48c4652ad1
5,768
java
Java
jOOQ/src/main/java/org/jooq/impl/AbstractStore.java
owyke/jOOQ
7ede9dca6295da3ab0cce3ed31bc4d7b9923a586
[ "Apache-2.0" ]
4,617
2015-01-02T13:36:14.000Z
2022-03-31T12:30:15.000Z
jOOQ/src/main/java/org/jooq/impl/AbstractStore.java
owyke/jOOQ
7ede9dca6295da3ab0cce3ed31bc4d7b9923a586
[ "Apache-2.0" ]
9,812
2015-01-02T17:27:10.000Z
2022-03-31T14:13:20.000Z
jOOQ/src/main/java/org/jooq/impl/AbstractStore.java
owyke/jOOQ
7ede9dca6295da3ab0cce3ed31bc4d7b9923a586
[ "Apache-2.0" ]
1,268
2015-01-06T16:30:05.000Z
2022-03-30T22:29:40.000Z
31.178378
107
0.499133
5,459
/* * 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. * * Other licenses: * ----------------------------------------------------------------------------- * Commercial licenses for this work are available. These replace the above * ASL 2.0 and offer limited warranties, support, maintenance, and commercial * database integrations. * * For more information, please visit: http://www.jooq.org/licenses * * * * * * * * * * * * * * * * */ package org.jooq.impl; import java.util.Arrays; // ... import org.jooq.Attachable; import org.jooq.Configuration; import org.jooq.DSLContext; import org.jooq.JSONFormat; import org.jooq.Record; import org.jooq.XMLFormat; /** * A common base class for {@link Record} and {@link ArrayRecord} * <p> * This base class takes care of implementing similar {@link Attachable} and * {@link Object#equals(Object)}, {@link Object#hashCode()} behaviour. * * @author Lukas Eder */ abstract class AbstractStore extends AbstractFormattable { AbstractStore() { this(null); } AbstractStore(Configuration configuration) { super(configuration); } // ------------------------------------------------------------------------- // The Attachable API // ------------------------------------------------------------------------- /** * This method is used in generated code! * * @deprecated - 3.11.0 - [#6720] [#6721] - Use {@link Attachable#configuration()} and * {@link Configuration#dsl()} instead. */ @Deprecated protected final DSLContext create() { return DSL.using(configuration()); } // ------------------------------------------------------------------------- // The Formattable API // ------------------------------------------------------------------------- @Override final JSONFormat defaultJSONFormat() { return Tools.configuration(this).formattingProvider().jsonFormatForRecords(); } @Override final XMLFormat defaultXMLFormat() { return Tools.configuration(this).formattingProvider().xmlFormatForRecords(); } // ------------------------------------------------------------------------- // equals and hashCode // ------------------------------------------------------------------------- /** * This method coincides with {@link Record#size()} and * {@link ArrayRecord#size()} */ abstract int size(); /** * This method coincides with {@link Record#get(int)} and * <code>ArrayRecordImpl.getValue(int)</code> */ abstract Object get(int index); @Override public int hashCode() { int hashCode = 1; for (int i = 0; i < size(); i++) { final Object obj = get(i); if (obj == null) hashCode = 31 * hashCode; // [#985] [#2045] Don't use obj.hashCode() on arrays, but avoid // calculating it as byte[] (BLOBs) can be quite large else if (obj.getClass().isArray()) hashCode = 31 * hashCode; else hashCode = 31 * hashCode + obj.hashCode(); } return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; // Note: keep this implementation in-sync with AbstractRecord.compareTo()! if (obj instanceof AbstractStore) { AbstractStore that = (AbstractStore) obj; if (size() == that.size()) { for (int i = 0; i < size(); i++) { final Object thisValue = get(i); final Object thatValue = that.get(i); // [#1850] Only return false early. In all other cases, // continue checking the remaining fields if (thisValue == null && thatValue == null) continue; else if (thisValue == null || thatValue == null) return false; // [#985] Compare arrays too. else if (thisValue.getClass().isArray() && thatValue.getClass().isArray()) { // Might be byte[] if (thisValue.getClass() == byte[].class && thatValue.getClass() == byte[].class) { if (!Arrays.equals((byte[]) thisValue, (byte[]) thatValue)) return false; } // Other primitive types are not expected else if (!thisValue.getClass().getComponentType().isPrimitive() && !thatValue.getClass().getComponentType().isPrimitive()) { if (!Arrays.equals((Object[]) thisValue, (Object[]) thatValue)) return false; } else return false; } else if (!thisValue.equals(thatValue)) return false; } // If we got through the above loop, the two records are equal return true; } } return false; } }
3e0ce0c05a04dfbbc2a96bced8d0fce25c1a3039
3,187
java
Java
src/main/java/com/gudden/maven/model/KGramIndex.java
CECS429-SearchEngine/Guddengine
ff652b6979862b3ae5b7dbdd05b2c8bfd6d26ed8
[ "MIT" ]
1
2017-12-09T21:21:18.000Z
2017-12-09T21:21:18.000Z
src/main/java/com/gudden/maven/model/KGramIndex.java
CECS429-SearchEngine/Guddengine
ff652b6979862b3ae5b7dbdd05b2c8bfd6d26ed8
[ "MIT" ]
3
2017-10-17T18:34:46.000Z
2017-10-22T15:41:42.000Z
src/main/java/com/gudden/maven/model/KGramIndex.java
CECS429-SearchEngine/Guddengine
ff652b6979862b3ae5b7dbdd05b2c8bfd6d26ed8
[ "MIT" ]
null
null
null
27.95614
106
0.424223
5,460
package com.gudden.maven.model; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; public class KGramIndex extends Index<Set<String>> { private Map<String, Set<String>> index; private Set<String> termSet; // ------------------------------------------------------------------------------------------------------ public KGramIndex() { this.index = new HashMap<String, Set<String>>(); this.termSet = new HashSet<String>(); } // ------------------------------------------------------------------------------------------------------ public void add(String type) { if (!termSet.contains(type)) { String specialType = encapsulate(type); for (int k = 1; k <= 3; k++) { List<String> grams = generateGrams(k, specialType); addPosting(grams, type); } this.termSet.add(type); } this.index.remove("$"); } // ------------------------------------------------------------------------------------------------------ public static List<String> generateGrams(int k, String type) { List<String> grams = new ArrayList<String>(); for (int i = 0; i <= type.length() - k; i++) { String gram = type.substring(i, i + k); grams.add(gram); } return grams; } // ------------------------------------------------------------------------------------------------------ @Override public String[] getDictionary() { SortedSet<String> grams = new TreeSet<String>(this.index.keySet()); return grams.toArray(new String[grams.size()]); } // ------------------------------------------------------------------------------------------------------ @Override public Set<String> getPostings(String term) { return this.index.get(term); } // ------------------------------------------------------------------------------------------------------ @Override public void resetIndex() { this.index = new HashMap<String, Set<String>>(); } // ------------------------------------------------------------------------------------------------------ @Override public int size() { return this.index.size(); } // ------------------------------------------------------------------------------------------------------ private void addPosting(List<String> grams, String term) { for (String gram : grams) { if (!contains(gram)) createPosting(gram); getPostings(gram).add(term); } } // ------------------------------------------------------------------------------------------------------ private String encapsulate(String term) { StringBuilder sb = new StringBuilder(); sb.append('$'); sb.append(term); sb.append('$'); return sb.toString(); } // ------------------------------------------------------------------------------------------------------ @Override protected boolean contains(String gram) { return this.index.containsKey(gram); } // ------------------------------------------------------------------------------------------------------ @Override protected void createPosting(String gram) { this.index.put(gram, new HashSet<String>()); } }
3e0ce149cc34090e3114e5ae7655f87edfbaea5e
710
java
Java
kie-wb-common-forms/kie-wb-common-forms-core/kie-wb-common-forms-fields/src/test/java/org/kie/workbench/common/forms/fields/MyTestEnum.java
alepintus/kie-wb-common
52f4225b6fa54d04435c8f5f59bee5894af23b7e
[ "Apache-2.0" ]
34
2017-05-21T11:28:40.000Z
2021-07-03T13:15:03.000Z
kie-wb-common-forms/kie-wb-common-forms-core/kie-wb-common-forms-fields/src/test/java/org/kie/workbench/common/forms/fields/MyTestEnum.java
alepintus/kie-wb-common
52f4225b6fa54d04435c8f5f59bee5894af23b7e
[ "Apache-2.0" ]
2,576
2017-03-14T00:57:07.000Z
2022-03-29T07:52:38.000Z
kie-wb-common-forms/kie-wb-common-forms-core/kie-wb-common-forms-fields/src/test/java/org/kie/workbench/common/forms/fields/MyTestEnum.java
alepintus/kie-wb-common
52f4225b6fa54d04435c8f5f59bee5894af23b7e
[ "Apache-2.0" ]
158
2017-03-15T08:55:40.000Z
2021-11-19T14:07:17.000Z
33.809524
75
0.73662
5,461
/* * Copyright 2017 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.kie.workbench.common.forms.fields; public enum MyTestEnum { VAL1, VAL2 }
3e0ce18413c0e30ee8a1a7a2777ee5fabf52b161
328
java
Java
microservice-alipay/src/main/java/com/yiluyouni/cloud/service/ProductService.java
zengqingshan/sparksOfFireCloud
7de7339f9ab251041f8c8b49dbd145a91942c858
[ "Apache-2.0" ]
null
null
null
microservice-alipay/src/main/java/com/yiluyouni/cloud/service/ProductService.java
zengqingshan/sparksOfFireCloud
7de7339f9ab251041f8c8b49dbd145a91942c858
[ "Apache-2.0" ]
null
null
null
microservice-alipay/src/main/java/com/yiluyouni/cloud/service/ProductService.java
zengqingshan/sparksOfFireCloud
7de7339f9ab251041f8c8b49dbd145a91942c858
[ "Apache-2.0" ]
null
null
null
14.26087
49
0.70122
5,462
package com.yiluyouni.cloud.service; import com.yiluyouni.cloud.entity.Product; import java.util.List; public interface ProductService { /** * 获取所有产品列表 * @return */ public List<Product> getProducts(); /** * 根据产品ID查询产品详情 * @param productId * @return */ public Product getProductById(String productId); }
3e0ce1e8f4a87bd2bf468e0eaa0f5f72c53d8cd3
438
java
Java
src/main/java/cn/wildfirechat/app/webhook/gitee/pojo/Branch.java
Sadakhatali/robot_server-master
bf9316f8c716ef8d6394aeb59ebcfd2bf3de01f6
[ "Apache-2.0" ]
46
2019-04-01T02:22:18.000Z
2021-12-28T04:46:00.000Z
src/main/java/cn/wildfirechat/app/webhook/gitee/pojo/Branch.java
Sadakhatali/robot_server-master
bf9316f8c716ef8d6394aeb59ebcfd2bf3de01f6
[ "Apache-2.0" ]
5
2019-09-23T02:14:04.000Z
2021-12-29T12:57:36.000Z
src/main/java/cn/wildfirechat/app/webhook/gitee/pojo/Branch.java
Sadakhatali/robot_server-master
bf9316f8c716ef8d6394aeb59ebcfd2bf3de01f6
[ "Apache-2.0" ]
132
2019-03-29T02:05:48.000Z
2022-03-22T09:17:22.000Z
25.764706
81
0.657534
5,463
package cn.wildfirechat.app.webhook.gitee.pojo; public class Branch { public String label; public String ref; public String sha; public User user; public Project repo; /* label: String, # 分支标记。eg:oschina:master ref: String, # 分支名。eg:master sha: String, # git 提交记录中 sha 值。eg:51b1acb1b4044fcdb2ff8a75ad15a4b655101754 user: *user, # 分支所在仓库的所有者信息 repo: *project # 分支所在仓库的信息 */ }
3e0ce278e91d7568d05fa4851d98d6a7a2c0b4e9
5,938
java
Java
fag-ark-persistering-test-jooq-spring/src/main/java/no/mesan/ark/persistering/Faghelg.java
mesan/fag-ark-persistering-test-jooq
b48d87a1f2cc6a7ad6a89d35a051f64d88ab6498
[ "Unlicense" ]
1
2015-11-04T08:51:42.000Z
2015-11-04T08:51:42.000Z
fag-ark-persistering-test-jooq-spring/src/main/java/no/mesan/ark/persistering/Faghelg.java
mesan/fag-ark-persistering-test-jooq
b48d87a1f2cc6a7ad6a89d35a051f64d88ab6498
[ "Unlicense" ]
null
null
null
fag-ark-persistering-test-jooq-spring/src/main/java/no/mesan/ark/persistering/Faghelg.java
mesan/fag-ark-persistering-test-jooq
b48d87a1f2cc6a7ad6a89d35a051f64d88ab6498
[ "Unlicense" ]
null
null
null
31.252632
95
0.704278
5,464
package no.mesan.ark.persistering; import static no.mesan.ark.persistering.generated.Tables.ACTOR; import static no.mesan.ark.persistering.generated.Tables.CATEGORY; import static no.mesan.ark.persistering.generated.Tables.FILM; import static no.mesan.ark.persistering.generated.Tables.FILM_CATEGORY; import static no.mesan.ark.persistering.generated.Tables.LANGUAGE; import static org.jooq.impl.DSL.select; import java.sql.Timestamp; import java.util.List; import java.util.Map; import java.util.function.Consumer; import javax.sql.DataSource; import org.jooq.DSLContext; import org.jooq.Result; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import no.mesan.ark.persistering.generated.enums.MpaaRating; import no.mesan.ark.persistering.generated.tables.Category; import no.mesan.ark.persistering.generated.tables.Film; import no.mesan.ark.persistering.generated.tables.FilmCategory; import no.mesan.ark.persistering.generated.tables.Language; import no.mesan.ark.persistering.generated.tables.records.ActorRecord; import no.mesan.ark.persistering.generated.tables.records.FilmRecord; @Component public class Faghelg { private final DSLContext dsl; private final NamedParameterJdbcOperations jdbcTemplate; @Autowired public Faghelg(DataSource dataSource) { dsl = DSL.using(dataSource, SQLDialect.POSTGRES); jdbcTemplate = new NamedParameterJdbcTemplate(dataSource); } @Transactional public void run() { //@formatter:off Result<FilmRecord> films = dsl .selectFrom(FILM) .where(FILM.FILM_ID.in( select(FILM_CATEGORY.FILM_ID) .from(FILM_CATEGORY.join(CATEGORY) .on(FILM_CATEGORY.CATEGORY_ID.equal(CATEGORY.CATEGORY_ID))) .where(CATEGORY.NAME.equal("Action")))) .and(FILM.LANGUAGE_ID.equal( select(LANGUAGE.LANGUAGE_ID) .from(LANGUAGE) .where(LANGUAGE.NAME.equal("English")))) .and(FILM.RATING.greaterOrEqual(MpaaRating.PG_13)) .fetch(); //@formatter:on System.out.println("Antall filmer jOOQ: " + films.size()); System.out.println(films.format()); } @Transactional public void doNotRunMe() { //@formatter:off FilmRecord film = dsl .selectFrom(FILM) .where(FILM.FILM_ID.equal(12345)) .fetchOne(); //@formatter:on film.setRating(MpaaRating.G); film.update(); Timestamp timestamp = null; Consumer<? super ActorRecord> action = null; //@formatter:off dsl.insertInto(ACTOR, ACTOR.ACTOR_ID, ACTOR.FIRST_NAME, ACTOR.LAST_NAME, ACTOR.LAST_UPDATE) .values(123, "Ole", "Brumm", timestamp) .execute(); //@formatter:on //@formatter:off dsl.insertInto(ACTOR).values(123, "Ole", "Brumm", timestamp).execute(); //@formatter:on Result<ActorRecord> result = dsl.insertInto(ACTOR, ACTOR.ACTOR_ID, ACTOR.FIRST_NAME, ACTOR.LAST_NAME, ACTOR.LAST_UPDATE) .values(123, "Ole", "Brumm", timestamp) .values(456, "Nasse", "Nøff", timestamp) .returning() .fetch(); result.stream().forEach(action); // dsl.deleteFrom(FILM).where(FILM.FILM_ID.between(123, 456)); // dsl.truncate(FILM).execute(); //@formatter:off Film film2 = dsl .selectFrom(FILM) .where(FILM.FILM_ID.equal(12345)) .fetchOneInto(Film.class); //@formatter:on //@formatter:off Map<MpaaRating, List<Film>> filmsByRating = dsl .selectFrom(FILM) .fetch() .intoGroups(FILM.RATING, Film.class); //@formatter:on dsl.batch( dsl.insertInto(ACTOR, ACTOR.ACTOR_ID, ACTOR.FIRST_NAME, ACTOR.LAST_NAME, ACTOR.LAST_UPDATE) .values(123, "Ole", "Brumm", timestamp), dsl.insertInto(ACTOR, ACTOR.ACTOR_ID, ACTOR.FIRST_NAME, ACTOR.LAST_NAME, ACTOR.LAST_UPDATE) .values(124, "Nasse", "Nøff", timestamp), dsl.insertInto(ACTOR, ACTOR.ACTOR_ID, ACTOR.FIRST_NAME, ACTOR.LAST_NAME, ACTOR.LAST_UPDATE) .values(125, "Kristoffer", "Robin", timestamp)) .execute(); } @Transactional public void runAlias() { Film f = FILM.as("f"); FilmCategory fc = FILM_CATEGORY.as("fc"); Category c = CATEGORY.as("c"); Language l = LANGUAGE.as("l"); //@formatter:off Result<FilmRecord> films = dsl .selectFrom(f) .where(f.FILM_ID.in( select(fc.FILM_ID) .from(fc.join(c) .on(fc.CATEGORY_ID.equal(c.CATEGORY_ID))) .where(c.NAME.equal("Action")))) .and(f.LANGUAGE_ID.equal( select(l.LANGUAGE_ID) .from(l) .where(l.NAME.equal("English")))) .and(f.RATING.greaterOrEqual(MpaaRating.PG_13)) .fetch(); //@formatter:on System.out.println("Antall filmer jOOQ: " + films.size()); System.out.println(films.format()); } @Transactional public void runJDBC() { MapSqlParameterSource parameters = new MapSqlParameterSource(); parameters.addValue("category_name", "Action"); parameters.addValue("language_name", "English"); parameters.addValue("film_rating", "PG-13"); //@formatter:off List<Map<String, Object>> results = jdbcTemplate.queryForList( "SELECT * " + "FROM film f " + "WHERE f.film_id in (" + " SELECT film_id" + " FROM film_category fc join category c " + " ON fc.category_id = c.category_id " + " WHERE c.name = :category_name " + " ) " + "AND f.language_id = (" + " SELECT language_id" + " FROM language" + " WHERE name = :language_name" + " )" + "AND f.rating >= :film_rating::mpaa_rating", parameters); //@formatter:on System.out.println("Antall filmer JDBC: " + results.size()); results.stream().forEach(System.out::println); } }
3e0ce2b7f80786a3aa4582385520c075e140f28b
2,615
java
Java
business-center/workflow-center/src/main/java/com/open/capacity/workflow/domain/dto/ProcessDefinitionDTO.java
jecinfo2016/open-capacity-platform-backend
bfcb2cee2e8b47a40555a7ec7749b8e23a66a2ad
[ "Apache-2.0" ]
1
2021-01-30T06:06:43.000Z
2021-01-30T06:06:43.000Z
business-center/workflow-center/src/main/java/com/open/capacity/workflow/domain/dto/ProcessDefinitionDTO.java
jecinfo2016/open-capacity-platform-backend
bfcb2cee2e8b47a40555a7ec7749b8e23a66a2ad
[ "Apache-2.0" ]
null
null
null
business-center/workflow-center/src/main/java/com/open/capacity/workflow/domain/dto/ProcessDefinitionDTO.java
jecinfo2016/open-capacity-platform-backend
bfcb2cee2e8b47a40555a7ec7749b8e23a66a2ad
[ "Apache-2.0" ]
1
2021-03-13T21:19:24.000Z
2021-03-13T21:19:24.000Z
23.141593
117
0.67457
5,465
package com.open.capacity.workflow.domain.dto; import com.fasterxml.jackson.annotation.JsonFormat; import com.open.capacity.workflow.constant.BaseEntity; import com.open.capacity.workflow.domain.vo.ActReDeploymentVO; import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntityImpl; import java.util.Date; public class ProcessDefinitionDTO extends BaseEntity { private static final long serialVersionUID = 1L; private String id; private String name; private String key; private int version; private String deploymentId; private String resourceName; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date deploymentTime; /** 流程实例状态 1 激活 2 挂起 */ private Integer suspendState; public ProcessDefinitionDTO() { } public ProcessDefinitionDTO(ProcessDefinitionEntityImpl processDefinition, ActReDeploymentVO actReDeploymentVO) { this.id = processDefinition.getId(); this.name = processDefinition.getName(); this.key = processDefinition.getKey(); this.version = processDefinition.getVersion(); this.deploymentId = processDefinition.getDeploymentId(); this.resourceName = processDefinition.getResourceName(); this.deploymentTime = actReDeploymentVO.getDeployTime(); this.suspendState = processDefinition.getSuspensionState(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getResourceName() { return resourceName; } public void setResourceName(String resourceName) { this.resourceName = resourceName; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public Date getDeploymentTime() { return deploymentTime; } public void setDeploymentTime(Date deploymentTime) { this.deploymentTime = deploymentTime; } public Integer getSuspendState() { return suspendState; } public void setSuspendState(Integer suspendState) { this.suspendState = suspendState; } }
3e0ce3910a68efe2dda789c7bffaee2c01700046
278
java
Java
day09/src/com/github/thread2/demo5/Call.java
AncientFairy/java-core
2596fee5f5c575f30c1486c1792acea5b3c60c4c
[ "Apache-2.0" ]
null
null
null
day09/src/com/github/thread2/demo5/Call.java
AncientFairy/java-core
2596fee5f5c575f30c1486c1792acea5b3c60c4c
[ "Apache-2.0" ]
1
2021-10-22T02:03:53.000Z
2021-10-22T02:03:53.000Z
day09/src/com/github/thread2/demo5/Call.java
AncientFairy/java-core
2596fee5f5c575f30c1486c1792acea5b3c60c4c
[ "Apache-2.0" ]
null
null
null
17.375
47
0.658273
5,466
package com.github.thread2.demo5; import java.util.concurrent.Callable; /** * @author 许大仙 * @version 1.0 * @since 2021-09-17 15:46 */ public class Call implements Callable<String> { @Override public String call() throws Exception { return "你好,世界"; } }
3e0ce41d634e8a2cf8ab12df678fd1fe104fd029
2,582
java
Java
bukkit/src/main/java/me/lucko/luckperms/bukkit/vault/VaultExecutor.java
fengzhiwenisgod/LuckPerms
265d011979ce40a9e71ea60e733b090724496a93
[ "MIT" ]
46
2017-08-06T10:01:43.000Z
2022-03-31T13:28:02.000Z
bukkit/src/main/java/me/lucko/luckperms/bukkit/vault/VaultExecutor.java
juzijun233/LuckPerms
265d011979ce40a9e71ea60e733b090724496a93
[ "MIT" ]
null
null
null
bukkit/src/main/java/me/lucko/luckperms/bukkit/vault/VaultExecutor.java
juzijun233/LuckPerms
265d011979ce40a9e71ea60e733b090724496a93
[ "MIT" ]
72
2018-01-18T04:51:17.000Z
2022-03-20T04:59:55.000Z
30.690476
98
0.650116
5,467
/* * This file is part of LuckPerms, licensed under the MIT License. * * Copyright (c) lucko (Luck) <efpyi@example.com> * Copyright (c) contributors * * 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 me.lucko.luckperms.bukkit.vault; import me.lucko.luckperms.bukkit.LPBukkitPlugin; import org.bukkit.scheduler.BukkitTask; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; /** * Sequential executor for Vault modifications */ public class VaultExecutor implements Runnable, Executor { private BukkitTask task = null; private final List<Runnable> tasks = new ArrayList<>(); public VaultExecutor(LPBukkitPlugin plugin) { task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, this, 1L, 1L); } @Override public void execute(Runnable r) { synchronized (tasks) { tasks.add(r); } } @Override public void run() { List<Runnable> toRun; synchronized (tasks) { if (tasks.isEmpty()) { return; } toRun = new ArrayList<>(tasks.size()); toRun.addAll(tasks); tasks.clear(); } for (Runnable runnable : toRun) { try { runnable.run(); } catch (Exception e) { e.printStackTrace(); } } } public void close() { if (task != null) { task.cancel(); task = null; } } }
3e0ce46427750845ec9e97addaddd5d2f4345a10
244
java
Java
MACSAirport/src/main/java/com/revature/dao/CommentDao.java
1801Jan22Java/team-hapa
0912289d573474b7ee74fe36755cf9e1e0bd1208
[ "MIT" ]
null
null
null
MACSAirport/src/main/java/com/revature/dao/CommentDao.java
1801Jan22Java/team-hapa
0912289d573474b7ee74fe36755cf9e1e0bd1208
[ "MIT" ]
4
2018-02-27T01:20:38.000Z
2018-03-06T03:16:31.000Z
MACSAirport/src/main/java/com/revature/dao/CommentDao.java
1801Jan22Java/team-hapa
0912289d573474b7ee74fe36755cf9e1e0bd1208
[ "MIT" ]
null
null
null
16.266667
39
0.770492
5,468
package com.revature.dao; import java.util.List; import com.revature.domain.Comment; public interface CommentDao { public void createComment(Comment c); public Comment getCommentById(int id); public List<Comment> getAllComments(); }
3e0ce4859f266df86848173907ee766a6197cdd8
1,944
java
Java
examples/src/main/java/org/bc/crypto/BufferedAsymmetricBlockCipher.java
merchoco/gm-jsse
e158a0568bd78259e08b25fda70e8882e4f78a5e
[ "Apache-2.0" ]
2
2021-12-02T08:01:07.000Z
2021-12-02T08:01:09.000Z
examples/src/main/java/org/bc/crypto/BufferedAsymmetricBlockCipher.java
merchoco/gm-jsse
e158a0568bd78259e08b25fda70e8882e4f78a5e
[ "Apache-2.0" ]
null
null
null
examples/src/main/java/org/bc/crypto/BufferedAsymmetricBlockCipher.java
merchoco/gm-jsse
e158a0568bd78259e08b25fda70e8882e4f78a5e
[ "Apache-2.0" ]
1
2021-12-02T08:01:10.000Z
2021-12-02T08:01:10.000Z
27
92
0.610082
5,469
package org.bc.crypto; public class BufferedAsymmetricBlockCipher { protected byte[] buf; protected int bufOff; private final AsymmetricBlockCipher cipher; public BufferedAsymmetricBlockCipher(AsymmetricBlockCipher var1) { this.cipher = var1; } public AsymmetricBlockCipher getUnderlyingCipher() { return this.cipher; } public int getBufferPosition() { return this.bufOff; } public void init(boolean var1, CipherParameters var2) { this.reset(); this.cipher.init(var1, var2); this.buf = new byte[this.cipher.getInputBlockSize() + (var1 ? 1 : 0)]; this.bufOff = 0; } public int getInputBlockSize() { return this.cipher.getInputBlockSize(); } public int getOutputBlockSize() { return this.cipher.getOutputBlockSize(); } public void processByte(byte var1) { if (this.bufOff >= this.buf.length) { throw new DataLengthException("attempt to process message too long for cipher"); } else { this.buf[this.bufOff++] = var1; } } public void processBytes(byte[] var1, int var2, int var3) { if (var3 != 0) { if (var3 < 0) { throw new IllegalArgumentException("Can't have a negative input length!"); } else if (this.bufOff + var3 > this.buf.length) { throw new DataLengthException("attempt to process message too long for cipher"); } else { System.arraycopy(var1, var2, this.buf, this.bufOff, var3); this.bufOff += var3; } } } public byte[] doFinal() throws InvalidCipherTextException { byte[] var1 = this.cipher.processBlock(this.buf, 0, this.bufOff); this.reset(); return var1; } public void reset() { if (this.buf != null) { for(int var1 = 0; var1 < this.buf.length; ++var1) { this.buf[var1] = 0; } } this.bufOff = 0; } }
3e0ce4f808b43d8511eb3312667a2ce63be93cab
1,171
java
Java
ecs-mgmt-client/src/test/java/com/emc/ecs/management/entity/VdcTests.java
carone1/ecs-dashboard
2d8b7036bb88047eeb1bcd568de5d0a7afcb8881
[ "MIT" ]
7
2016-09-15T10:15:55.000Z
2022-01-07T04:30:54.000Z
ecs-mgmt-client/src/test/java/com/emc/ecs/management/entity/VdcTests.java
carone1/ecs-dashboard
2d8b7036bb88047eeb1bcd568de5d0a7afcb8881
[ "MIT" ]
3
2016-08-19T16:08:42.000Z
2017-04-17T15:28:51.000Z
ecs-mgmt-client/src/test/java/com/emc/ecs/management/entity/VdcTests.java
carone1/ecs-dashboard
2d8b7036bb88047eeb1bcd568de5d0a7afcb8881
[ "MIT" ]
2
2016-09-12T23:42:34.000Z
2017-10-26T16:47:27.000Z
23.897959
95
0.629377
5,470
package com.emc.ecs.management.entity; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.net.URI; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import org.junit.Test; import org.junit.Assert; public class VdcTests { @Test public void testVdcXml() throws Exception { String expectedOutput = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<vdc>" + "<id>id</id>" + "<link>link</link>" + "</vdc>"; Vdc vdc = new Vdc(); vdc.setId(new URI("id")); vdc.setLink("link"); JAXBContext jaxbContext = JAXBContext.newInstance( Vdc.class ); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, false ); OutputStream byteOut = new ByteArrayOutputStream(); jaxbMarshaller.marshal( vdc, byteOut ); String bytesOutStr = byteOut.toString(); System.out.println(bytesOutStr); Assert.assertEquals( "xml is not matching", expectedOutput, bytesOutStr); } }
3e0ce5883499a0e14a784733e7f548e26671ce05
11,656
java
Java
src/main/java/nz/co/fortytwo/signalk/artemis/subscription/Subscription.java
blackbox-dev/artemis-server
4fb46e87172370c0107fa85ecc85da373e4447c5
[ "Apache-2.0" ]
null
null
null
src/main/java/nz/co/fortytwo/signalk/artemis/subscription/Subscription.java
blackbox-dev/artemis-server
4fb46e87172370c0107fa85ecc85da373e4447c5
[ "Apache-2.0" ]
17
2018-11-20T11:35:04.000Z
2021-01-21T07:25:30.000Z
src/main/java/nz/co/fortytwo/signalk/artemis/subscription/Subscription.java
blackbox-dev/artemis-server
4fb46e87172370c0107fa85ecc85da373e4447c5
[ "Apache-2.0" ]
7
2018-07-10T17:59:20.000Z
2021-02-05T01:40:01.000Z
27.356808
139
0.692209
5,471
/* * * Copyright (C) 2012-2014 R T Huitema. All Rights Reserved. * Web: www.42.co.nz * Email: efpyi@example.com * Author: R T Huitema * * This file is part of the signalk-server-java project * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * 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 nz.co.fortytwo.signalk.artemis.subscription; import static nz.co.fortytwo.signalk.artemis.util.SignalKConstants.skey; import static nz.co.fortytwo.signalk.artemis.util.SignalKConstants.vessels; import java.util.ArrayList; //import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.Set; import java.util.TimerTask; import java.util.concurrent.ConcurrentSkipListMap; import java.util.regex.Pattern; import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.google.common.collect.ImmutableList; import io.netty.util.internal.ConcurrentSet; import mjson.Json; import nz.co.fortytwo.signalk.artemis.tdb.InfluxDbService; import nz.co.fortytwo.signalk.artemis.tdb.TDBService; import nz.co.fortytwo.signalk.artemis.util.Config; import nz.co.fortytwo.signalk.artemis.util.SecurityUtils; import nz.co.fortytwo.signalk.artemis.util.SignalKConstants; import nz.co.fortytwo.signalk.artemis.util.SignalkMapConvertor; import nz.co.fortytwo.signalk.artemis.util.Util; /** * Holds subscription data, wsSessionId, path, period If a subscription is made * via REST before the websocket is started then the wsSocket will hold the * sessionId. This must be swapped for the wsSessionId when the websocket * starts. The subscription will be in an inactive state when submitted by REST * if sessionId = sessionId * * @author robert * */ public class Subscription { private static Logger logger = LogManager.getLogger(Subscription.class); private static TDBService influx = new InfluxDbService(); String sessionId = null; String path = null; long period = -1; private String startTime = null; private long playbackPeriod = -1; boolean active = true; private long minPeriod; private String format; private String policy; private String token; private String roles; ArrayList<String> allowed; ArrayList<String> denied; private Pattern pathPattern = null; private Pattern uuidPattern = null; private String vesselPath; Set<String> subscribedPaths = new ConcurrentSet<String>(); private String routeId; private String destination; private TimerTask task; private String table; private String uuid; private Map<String, String> map = new ConcurrentSkipListMap<>(); private String correlation; public Subscription(String sessionId, String destination, String path, long period, long minPeriod, String format, String policy, String correlation, String token,String startTime, double playbackRate) throws Exception { this.sessionId = sessionId; this.path = Util.sanitizePath(path); String context = Util.getContext(path); this.table = StringUtils.substringBefore(context, "."); this.uuid = StringUtils.substringAfter(context, "."); uuidPattern = Util.regexPath(uuid); pathPattern = Util.regexPath(StringUtils.substring(path, context.length() + 1)); this.period = period; this.minPeriod = minPeriod; this.format = format; this.policy = policy; this.token = token; Json rolesJson =SecurityUtils.getRoles(token); this.allowed = SecurityUtils.getAllowedReadPaths(rolesJson); this.denied = SecurityUtils.getDeniedReadPaths(rolesJson); this.roles=rolesJson.toString(); this.destination = destination; this.setCorrelation(correlation); if(StringUtils.isNotBlank(startTime)) { this.startTime=startTime; this.playbackPeriod=(long) (period/playbackRate); } map.put("uuid", uuidPattern.toString()); map.put(skey, pathPattern.toString()); SubscriptionManagerFactory.getInstance().createTempQueue(destination); task = new TimerTask() { private long queryTime=StringUtils.isNotBlank(startTime)?Util.getMillisFromIsoTime(startTime):System.currentTimeMillis(); private NavigableMap<String, Json> rslt = new ConcurrentSkipListMap<String, Json>(); private Json json = Json.object(); @Override public void run() { if (logger.isDebugEnabled()) { logger.debug("Running for client:{}, {}" , destination, getPath()); logger.debug("Running for session:{}" , sessionId); } try { if (!active) { cancel(); return; } // get a map of the current subs values // select * from vessels where // uuid='urn:mrn:imo:mmsi:209023000' AND skey=~/nav.*cou/ // group by skey,uuid,sourceRef,owner,grp order by time desc // limit 1 if(StringUtils.isNotBlank(startTime)) { influx.loadDataSnapshot(rslt, table, map, queryTime); if(queryTime<System.currentTimeMillis()) { queryTime=queryTime+period; } }else { influx.loadData(rslt, table, map); } if (logger.isDebugEnabled()) logger.debug("rslt map = {}" , rslt); //trim for security SecurityUtils.trimMap(rslt, allowed, denied); //format if (SignalKConstants.FORMAT_DELTA.equals(format)) { json = SignalkMapConvertor.mapToUpdatesDelta(rslt); if (logger.isDebugEnabled()) logger.debug("Delta json = {}", json); } if (SignalKConstants.FORMAT_FULL.equals(format)) { json = SignalkMapConvertor.mapToFull(rslt); if (logger.isDebugEnabled()) logger.debug("Full json = {}", json); } //Clear the result. rslt.clear(); try{ SubscriptionManagerFactory.getInstance().send( destination, format, correlation, token, roles, json); json.clear(true); }catch(ActiveMQException amq){ logger.error(amq,amq); setActive(false); } } catch (Exception e) { logger.error(e.getMessage(), e); } } }; //now send hello if (logger.isDebugEnabled()) logger.debug("Sending hello: {}", Config.getHelloMsg()); try{ SubscriptionManagerFactory.getInstance().send( destination, format, correlation, token, roles, Config.getHelloMsg()); }catch(ActiveMQException amq){ logger.error(amq,amq); setActive(false); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((path == null) ? 0 : path.hashCode()); result = prime * result + (int) (period ^ (period >>> 32)); result = prime * result + ((sessionId == null) ? 0 : sessionId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Subscription other = (Subscription) obj; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; if (period != other.period) return false; if (sessionId == null) { if (other.sessionId != null) return false; } else if (!sessionId.equals(other.sessionId)) return false; return true; } public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public String getPath() { return path; } public void setPath(String path) { this.path = Util.sanitizePath(path); } public long getPeriod() { return period; } public void setPeriod(long period) { this.period = period; } @Override public String toString() { return "Subscription [sessionId=" + sessionId + ", path=" + path + ", period=" + period + ", routeId=" + routeId + ", format=" + format + ", active=" + active + ", destination=" + destination + "]"; } public boolean isActive() { return active; } public void setActive(boolean active) throws Exception { this.active = active; if (logger.isDebugEnabled()) logger.debug("Set active:{}, {}", active, this); if (active) { if(StringUtils.isNotBlank(startTime)) { SubscriptionManagerFactory.getInstance().schedule(task, playbackPeriod); }else { SubscriptionManagerFactory.getInstance().schedule(task, getPeriod()); } if (logger.isDebugEnabled()) logger.debug("Scheduled:{}" , getPeriod()); } } public boolean isSameRoute(Subscription sub) { if (period != sub.period) return false; if (sessionId == null) { if (sub.sessionId != null) return false; } else if (!sessionId.equals(sub.sessionId)) return false; if (path != sub.path) return false; if (path == null) { if (sub.path != null) return false; } else if (!path.equals(sub.path)) return false; if (format == null) { if (sub.format != null) return false; } else if (!format.equals(sub.format)) return false; if (policy == null) { if (sub.policy != null) return false; } else if (!policy.equals(sub.policy)) return false; return true; } public boolean isSameVessel(Subscription sub) { if (getVesselPath() != null && getVesselPath().equals(sub.getVesselPath())) return true; return false; } /** * Gets the context path, eg vessels.motu, vessel.*, or vessels.2933?? * * @param path * @return */ public String getVesselPath() { if (vesselPath == null) { if (!path.startsWith(vessels)) return null; int pos = path.indexOf(".") + 1; // could be just 'vessels' if (pos < 1) return null; pos = path.indexOf(".", pos); // could be just one .\dot. vessels.123456789 if (pos < 0) return path; vesselPath = path.substring(0, pos); } return vesselPath; } /** * Returns true if this subscription is interested in this path * * @param key * @return */ public boolean isSubscribed(String key) { return pathPattern.matcher(key).find(); } public long getMinPeriod() { return minPeriod; } public String getFormat() { return format; } public String getPolicy() { return policy; } /** * Returns a list of paths that this subscription is currently providing. * The list is filtered by the key if it is not null or empty in which case * a full list is returned, * * @param key * @return */ public List<String> getSubscribed(String key) { if (StringUtils.isBlank(key)) { return ImmutableList.copyOf(subscribedPaths); } List<String> paths = new ArrayList<String>(); for (String p : subscribedPaths) { if (p.startsWith(key)) { if (logger.isDebugEnabled()) logger.debug("Adding path:{}", p); paths.add(p); } } return paths; } public void setRouteId(String routeId) { this.routeId = routeId; } public String getRouteId() { return routeId; } public String getDestination() { return destination; } public void setDestination(String destination) { this.destination = destination; } public String getCorrelation() { return correlation; } public void setCorrelation(String correlation) { this.correlation = correlation; } }
3e0ce5ad383725da97406713467bf92eeff5d144
8,469
java
Java
src/equinox/controller/EditUserPermissionsPanel.java
muratartim/Equinox
c769724c157b0a87a929cf8150562d5fcd868f24
[ "Apache-2.0" ]
30
2018-08-02T07:32:44.000Z
2022-03-31T15:19:59.000Z
src/equinox/controller/EditUserPermissionsPanel.java
muratartim/Equinox
c769724c157b0a87a929cf8150562d5fcd868f24
[ "Apache-2.0" ]
17
2018-08-07T08:38:16.000Z
2018-10-20T07:55:17.000Z
src/equinox/controller/EditUserPermissionsPanel.java
muratartim/Equinox
c769724c157b0a87a929cf8150562d5fcd868f24
[ "Apache-2.0" ]
11
2018-10-09T15:06:26.000Z
2022-03-20T07:11:34.000Z
25.829268
141
0.741029
5,472
/* * Copyright 2018 Murat Artim (ychag@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 equinox.controller; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.ResourceBundle; import org.controlsfx.control.CheckListView; import org.controlsfx.control.PopOver; import org.controlsfx.control.PopOver.ArrowLocation; import equinox.controller.InputPanel.InternalInputSubPanel; import equinox.controller.ScheduleTaskPanel.SchedulingPanel; import equinox.data.EquinoxTheme; import equinox.data.input.UserProfile; import equinox.font.IconicFont; import equinox.serverUtilities.Permission; import equinox.task.EditUserPermissions; import equinox.task.GetUserPermissions; import equinox.task.GetUserPermissions.UserPermissionRequestingPanel; import equinox.task.SaveTask; import equinox.utility.Utility; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.control.Accordion; import javafx.scene.control.ComboBox; import javafx.scene.control.SplitMenuButton; import javafx.scene.control.TextField; import javafx.scene.layout.VBox; /** * Class for edit user permissions panel controller. * * @author Murat Artim * @date 6 Apr 2018 * @time 01:36:28 */ public class EditUserPermissionsPanel implements InternalInputSubPanel, SchedulingPanel, UserPermissionRequestingPanel { /** The owner panel. */ private InputPanel owner_; @FXML private VBox root_; @FXML private TextField alias_; @FXML private ComboBox<UserProfile> profiles_; @FXML private CheckListView<Permission> permissions_; @FXML private Accordion accordion_; @FXML private SplitMenuButton ok_; @Override public void initialize(URL location, ResourceBundle resources) { // set user profiles profiles_.setItems(FXCollections.observableArrayList(UserProfile.values())); // set non-admin permissions ArrayList<Permission> nonAdminPerms = new ArrayList<>(); for (Permission p : Permission.values()) { if (!p.isAdminPermission()) { nonAdminPerms.add(p); } } permissions_.setItems(FXCollections.observableArrayList(nonAdminPerms)); // expand first pane accordion_.setExpandedPane(accordion_.getPanes().get(0)); } @Override public InputPanel getOwner() { return owner_; } @Override public Parent getRoot() { return root_; } @Override public void start() { // no implementation } @Override public void showing() { onResetClicked(); } @Override public String getHeader() { return "Edit User Permissions"; } @Override public void setTaskScheduleDate(boolean runNow, Date scheduleDate) { // get user info String alias = alias_.getText(); // get permissions ObservableList<Permission> permissions = permissions_.getCheckModel().getCheckedItems(); // check inputs if (!checkInputs(alias, permissions)) return; // create and start task ActiveTasksPanel tm = owner_.getOwner().getActiveTasksPanel(); // run now if (runNow) { tm.runTaskInParallel(new EditUserPermissions(alias, permissions.toArray(new Permission[permissions.size()]))); } else { tm.runTaskInParallel(new SaveTask(new EditUserPermissions(alias, permissions.toArray(new Permission[permissions.size()])), scheduleDate)); } // get back to files view owner_.showSubPanel(InputPanel.FILE_VIEW_PANEL); } @Override public void setUserPermissions(String alias, Permission[] permissions) { // reset user info alias_.setText(alias); // reset permissions permissions_.getCheckModel().clearChecks(); profiles_.getSelectionModel().clearSelection(); // set permissions for (Permission p : permissions) { permissions_.getCheckModel().check(p); } // expand first pane accordion_.setExpandedPane(accordion_.getPanes().get(1)); } @FXML private void onOKClicked() { setTaskScheduleDate(true, null); } @FXML private void onSaveTaskClicked() { setTaskScheduleDate(false, null); } @FXML private void onScheduleTaskClicked() { PopOver popOver = new PopOver(); popOver.setArrowLocation(ArrowLocation.BOTTOM_CENTER); popOver.setDetachable(false); popOver.setContentNode(ScheduleTaskPanel.load(popOver, this, null)); popOver.setHideOnEscape(true); popOver.setAutoHide(true); popOver.show(ok_); } @FXML private void onCancelClicked() { owner_.showSubPanel(InputPanel.FILE_VIEW_PANEL); } @FXML private void onResetClicked() { // reset user info alias_.clear(); // reset permissions permissions_.getCheckModel().clearChecks(); profiles_.getSelectionModel().clearSelection(); // expand first pane accordion_.setExpandedPane(accordion_.getPanes().get(0)); } @FXML private void onProfileSelected() { // clear permissions permissions_.getCheckModel().clearChecks(); // no profile selected if (profiles_.getSelectionModel().isEmpty()) return; // get selected profile UserProfile selected = profiles_.getSelectionModel().getSelectedItem(); // set permissions for (Permission p : selected.getPermissions()) { permissions_.getCheckModel().check(p); } } @FXML private void onGoClicked() { // alias String alias = alias_.getText(); if (alias == null || alias.trim().isEmpty()) { String message = "Please enter valid user alias to proceed."; PopOver popOver = new PopOver(); popOver.setArrowLocation(ArrowLocation.TOP_LEFT); popOver.setDetachable(false); popOver.setContentNode(NotificationPanel1.load(message, 30, NotificationPanel1.WARNING)); popOver.setHideOnEscape(true); popOver.setAutoHide(true); popOver.show(alias_); return; } // request user permissions ActiveTasksPanel tm = owner_.getOwner().getActiveTasksPanel(); tm.runTaskSilently(new GetUserPermissions(alias, this), false); } /** * Checks user inputs. * * @param alias * User alias. * @param permissions * User permissions. * @return True if inputs are valid. */ private boolean checkInputs(String alias, ObservableList<Permission> permissions) { // alias if (alias == null || alias.trim().isEmpty()) { String message = "Please enter valid user alias to proceed."; PopOver popOver = new PopOver(); popOver.setArrowLocation(ArrowLocation.TOP_LEFT); popOver.setDetachable(false); popOver.setContentNode(NotificationPanel1.load(message, 30, NotificationPanel1.WARNING)); popOver.setHideOnEscape(true); popOver.setAutoHide(true); popOver.show(alias_); return false; } // permissions if (permissions == null || permissions.isEmpty()) { String message = "Please select at least one user permission to proceed."; PopOver popOver = new PopOver(); popOver.setArrowLocation(ArrowLocation.TOP_LEFT); popOver.setDetachable(false); popOver.setContentNode(NotificationPanel1.load(message, 30, NotificationPanel1.WARNING)); popOver.setHideOnEscape(true); popOver.setAutoHide(true); popOver.show(permissions_); return false; } // valid inputs return true; } /** * Loads and returns file CDF set panel. * * @param owner * The owner panel. * @return The newly loaded file CDF set panel. */ public static EditUserPermissionsPanel load(InputPanel owner) { try { // load fxml file FXMLLoader fxmlLoader = new FXMLLoader(EquinoxTheme.getFXMLResource("EditUserPermissionsPanel.fxml")); fxmlLoader.setResources(IconicFont.FONT_KEYS); Parent root = (Parent) fxmlLoader.load(); // speed caching Utility.setupSpeedCaching(root, null); // get controller EditUserPermissionsPanel controller = (EditUserPermissionsPanel) fxmlLoader.getController(); // set owner controller.owner_ = owner; // return controller return controller; } // exception occurred during loading catch (IOException e) { throw new RuntimeException(e); } } }
3e0ce5af73cc92ea8d0aaa4a5b8c27b65620b9b5
483
java
Java
w3log-backend/src/main/java/com/wanzhk/api/mapper/RolePermissionMapper.java
VolzK/W3log
aa8fc8a1620ed4b7b2a0a105f3ede2aecc54161c
[ "Apache-2.0" ]
null
null
null
w3log-backend/src/main/java/com/wanzhk/api/mapper/RolePermissionMapper.java
VolzK/W3log
aa8fc8a1620ed4b7b2a0a105f3ede2aecc54161c
[ "Apache-2.0" ]
1
2022-02-09T22:26:15.000Z
2022-02-09T22:26:15.000Z
w3log-backend/src/main/java/com/wanzhk/api/mapper/RolePermissionMapper.java
VolzK/W3log
aa8fc8a1620ed4b7b2a0a105f3ede2aecc54161c
[ "Apache-2.0" ]
null
null
null
24.15
85
0.784679
5,473
package com.wanzhk.api.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.wanzhk.api.modules.entity.TbRolePermission; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; /** * @author wangzhiheng * <p> * 2020-05-14 */ @Mapper public interface RolePermissionMapper extends BaseMapper<TbRolePermission> { List<Integer> getPermissionIdsByRoleIds(@Param("roleIds") List<Integer> roleIds); }
3e0ce6107530f0e23f38d2428ff9a547d6dd535f
804
java
Java
src/main/java/edu/cmu/cs/mvelezce/evaluation/approaches/bruteforce/execute/adapter/find/BFFindAdapter.java
miguelvelezmj25/ConfigCrusher
0a67b0fdab3cd32c365b0383be92d0d1be6ee94f
[ "MIT" ]
null
null
null
src/main/java/edu/cmu/cs/mvelezce/evaluation/approaches/bruteforce/execute/adapter/find/BFFindAdapter.java
miguelvelezmj25/ConfigCrusher
0a67b0fdab3cd32c365b0383be92d0d1be6ee94f
[ "MIT" ]
null
null
null
src/main/java/edu/cmu/cs/mvelezce/evaluation/approaches/bruteforce/execute/adapter/find/BFFindAdapter.java
miguelvelezmj25/ConfigCrusher
0a67b0fdab3cd32c365b0383be92d0d1be6ee94f
[ "MIT" ]
1
2021-05-13T14:50:55.000Z
2021-05-13T14:50:55.000Z
30.923077
108
0.722637
5,474
package edu.cmu.cs.mvelezce.evaluation.approaches.bruteforce.execute.adapter.find; import edu.cmu.cs.mvelezce.tool.execute.java.adapter.find.FindAdapter; import java.io.IOException; import java.util.Set; public class BFFindAdapter extends FindAdapter { public BFFindAdapter(String programName, String entryPoint, String dir) { super(programName, entryPoint, dir); } @Override public void execute(Set<String> configuration, int iteration) throws IOException, InterruptedException { String[] args = this.configurationAsMainArguments(configuration); String[] newArgs = new String[args.length + 1]; newArgs[0] = iteration + ""; System.arraycopy(args, 0, newArgs, 1, args.length); this.execute(BFFindMain.BF_FIND_MAIN, newArgs); } }
3e0ce6c811bc5eac6a0823a9130fb927e3fe93cc
5,960
java
Java
scala/runners/src/org/jetbrains/plugins/scala/testingSupport/uTest/UTestSuite540Runner.java
domdorn/intellij-scala
0631720570cfca1ea25735821a7893c8ae54e9f1
[ "Apache-2.0" ]
2
2018-08-19T02:34:41.000Z
2018-08-19T02:35:04.000Z
scala/runners/src/org/jetbrains/plugins/scala/testingSupport/uTest/UTestSuite540Runner.java
smarter/intellij-scala
11887455c2f4a8f4af46b4e160c01298e9fed16e
[ "Apache-2.0" ]
null
null
null
scala/runners/src/org/jetbrains/plugins/scala/testingSupport/uTest/UTestSuite540Runner.java
smarter/intellij-scala
11887455c2f4a8f4af46b4e160c01298e9fed16e
[ "Apache-2.0" ]
1
2018-09-24T23:40:48.000Z
2018-09-24T23:40:48.000Z
38.205128
151
0.653859
5,475
package org.jetbrains.plugins.scala.testingSupport.uTest; import scala.collection.JavaConverters; import scala.collection.Seq; import scala.runtime.BoxedUnit; import utest.TestRunner; import utest.Tests; import utest.framework.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.*; public class UTestSuite540Runner extends UTestSuiteRunner { public void runTestSuites(String className, Collection<UTestPath> tests, UTestReporter reporter) { Collection<UTestPath> testsToRun; Class clazz; Object testObject; try { clazz = Class.forName(className); Class testObjClass = Class.forName(className + "$"); testObject = testObjClass.getField("MODULE$").get(null); } catch (ClassNotFoundException e) { System.out.println("ClassNotFoundException for " + className + ": " + e.getMessage()); return; } catch (IllegalAccessException e) { System.out.println("IllegalAccessException for instance field of " + className + ": " + e.getMessage()); return; } catch (NoSuchFieldException e) { System.out.println("ClassNotFoundException for instance field of " + className + ": " + e.getMessage()); return; } if (!tests.isEmpty()) { testsToRun = tests; } else { testsToRun = new LinkedList<UTestPath>(); for (Method method : clazz.getMethods()) { if (method.getReturnType().equals(Tests.class) && method.getParameterTypes().length == 0) { testsToRun.add(new UTestPath(className, method)); } } } reporter.reportClassSuiteStarted(className); Set<Method> testMethods = new HashSet<Method>(); List<UTestPath> leafTests = new LinkedList<UTestPath>(); Map<UTestPath, Integer> childrenCount = new HashMap<UTestPath, Integer>(); Map<UTestPath, Tests> pathToResolvedTests = new HashMap<UTestPath, Tests>(); //collect test data required to perform test launch without scope duplication for (UTestPath testPath : testsToRun) { testMethods.add(testPath.getMethod()); Method test = testPath.getMethod(); Tests testTree; try { assert(Modifier.isStatic(test.getModifiers())); testTree = (Tests) test.invoke(null); } catch (IllegalAccessException e) { System.out.println("IllegalAccessException on test initialization for " + clazz.getName() + ": " + e.getMessage()); return; } catch (InvocationTargetException e) { System.out.println("InvocationTargetException on test initialization for " + clazz.getName() + ": " + e.getMessage()); e.printStackTrace(); return; } //first, descend to the current path Tree<String> current = testTree.nameTree(); for (String name : testPath.getPath()) { boolean changed = false; for (scala.collection.Iterator<Tree<String>> it = current.children().iterator(); it.hasNext();) { Tree<String> child = it.next(); if (child.value().equals(name)) { current = child; changed = true; break; } } if (!changed) { throw new RuntimeException("Failure in test pathing for test " + testPath); } } traverseTestTreeDown(current, testPath, leafTests); pathToResolvedTests.put(testPath, testTree); } countTests(childrenCount, leafTests); reporter.registerTestClass(className, testMethods.size()); for (UTestPath testPath : testsToRun) { Tests resolveResult = pathToResolvedTests.get(testPath); for (UTestPath leafTest : leafTests) { //open all leaf tests and their outer scopes if (!reporter.isStarted(leafTest)) { reporter.reportStarted(leafTest, false); } } scala.Function2<Seq<String>, Result, BoxedUnit> reportFunction = getReportFunction(reporter, testPath.getMethodPath(), leafTests, childrenCount); Tree<String> subtree = findSubtree(resolveResult.nameTree(), testPath); List<Tree<String>> treeList = new LinkedList<Tree<String>>(); if (subtree != null) { treeList.add(subtree); } TestRunner.runAsync(resolveResult, reportFunction, JavaConverters.asScalaBufferConverter(treeList).asScala(), (Executor) testObject, ExecutionContext.RunNow$.MODULE$); } } private Tree<String> findSubtree(Tree<String> root, UTestPath path) { Tree<String> current = root; List<String> walkupNodes = new LinkedList<String>(); if (path.getPath().isEmpty()) return null; for (String node: path.getPath()) { scala.collection.Seq<Tree<String>> children = current.children(); boolean changed = false; for (scala.collection.Iterator<Tree<String>> it = children.iterator(); it.hasNext();) { Tree<String> check = it.next(); if (check.value().equals(node)) { if (current != root) { walkupNodes.add(current.value()); } current = check; changed = true; break; } } if (!changed) return null; } Collections.reverse(walkupNodes); for (String walkup : walkupNodes) { List<Tree<String>> dummyList = new LinkedList<Tree<String>>(); dummyList.add(current); current = new Tree<String>(walkup, JavaConverters.asScalaBufferConverter(dummyList).asScala()); } return current; } private void traverseTestTreeDown(Tree<String> names, UTestPath currentPath, List<UTestPath> leafTests) { //TODO fix this highlighting error scala.collection.Seq<Tree<String>> children = names.children(); if (children.isEmpty()) { leafTests.add(currentPath); } else { for (int i = 0; i < children.size(); i++) { Tree<String> child = children.apply(i); traverseTestTreeDown(child, currentPath.append(child.value()), leafTests); } } } }
3e0ce741e93713eab129873a2c03b0df7ea81d46
854
java
Java
java/src/main/java/com/genexus/ws/security/GXWSSignature.java
dalvarellos/JavaClasses
6fe9e9643c91ff5f101a78ab6334c3e60c932e57
[ "Apache-2.0" ]
21
2019-06-01T02:25:26.000Z
2022-01-13T02:20:18.000Z
java/src/main/java/com/genexus/ws/security/GXWSSignature.java
dalvarellos/JavaClasses
6fe9e9643c91ff5f101a78ab6334c3e60c932e57
[ "Apache-2.0" ]
415
2019-05-03T23:09:08.000Z
2022-03-31T22:08:16.000Z
java/src/main/java/com/genexus/ws/security/GXWSSignature.java
dalvarellos/JavaClasses
6fe9e9643c91ff5f101a78ab6334c3e60c932e57
[ "Apache-2.0" ]
17
2019-05-21T16:02:28.000Z
2022-02-06T17:39:59.000Z
17.428571
59
0.761124
5,476
package com.genexus.ws.security; import com.genexus.common.interfaces.IGXWSSignature; import com.genexus.common.interfaces.IGXWSSecurityKeyStore; public class GXWSSignature implements IGXWSSignature { private IGXWSSecurityKeyStore keystore; private String alias; private int keyIdentifierType; public GXWSSignature() { alias = ""; keystore = new GXWSSecurityKeyStore(); } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias.trim(); } public IGXWSSecurityKeyStore getKeystore() { return keystore; } public void setKeystore(IGXWSSecurityKeyStore keystore) { this.keystore = keystore; } public int getKeyIdentifierType() { return keyIdentifierType; } public void setKeyIdentifierType(int keyIdentifierType) { this.keyIdentifierType = keyIdentifierType; } }
3e0ce7542f90649cb3bf14fc745e96492e2b641d
353
java
Java
src/main/java/pl/kkowalewski/occupationalapi/OccupationalApiApplication.java
KKowalewski24/OccupationalAPI
f1ebbb0ad5bd4e360678e396764ef90ab27210bb
[ "MIT" ]
null
null
null
src/main/java/pl/kkowalewski/occupationalapi/OccupationalApiApplication.java
KKowalewski24/OccupationalAPI
f1ebbb0ad5bd4e360678e396764ef90ab27210bb
[ "MIT" ]
7
2020-02-21T15:53:32.000Z
2020-06-03T16:28:12.000Z
src/main/java/pl/kkowalewski/occupationalapi/OccupationalApiApplication.java
KKowalewski24/OccupationalAPI
f1ebbb0ad5bd4e360678e396764ef90ab27210bb
[ "MIT" ]
null
null
null
25.214286
70
0.807365
5,477
package pl.kkowalewski.occupationalapi; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class OccupationalApiApplication { public static void main(String[] args) { SpringApplication.run(OccupationalApiApplication.class, args); } }
3e0ce767939c022009e835d43881b10bb66c2170
2,796
java
Java
app/src/main/java/com/scriptsbundle/nokri/manager/Nokri_FullScreenAlertDialog.java
vimalcvs/NOKRI
0a52c13b40f40ae3d74e00b2fd461fb137bbeb98
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/scriptsbundle/nokri/manager/Nokri_FullScreenAlertDialog.java
vimalcvs/NOKRI
0a52c13b40f40ae3d74e00b2fd461fb137bbeb98
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/scriptsbundle/nokri/manager/Nokri_FullScreenAlertDialog.java
vimalcvs/NOKRI
0a52c13b40f40ae3d74e00b2fd461fb137bbeb98
[ "Apache-2.0" ]
null
null
null
31.772727
92
0.689914
5,478
package com.scriptsbundle.nokri.manager; import android.app.Dialog; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.NonNull; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import com.scriptsbundle.nokri.R; public class Nokri_FullScreenAlertDialog extends Dialog { private Nokri_FontManager fontManager; private String customTex = null; private ProgressBar progressBar; private TextView alertTexView; public Nokri_FullScreenAlertDialog(@NonNull Context context, int themeResId) { super(context, themeResId); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dialog_layout); fontManager = new Nokri_FontManager(); alertTexView = findViewById(R.id.txt_alert); progressBar = findViewById(R.id.progress_bar); alertTexView.setText("Please Wait"); if(customTex!=null) { alertTexView.setText(customTex); } fontManager.nokri_setOpenSenseFontTextView(alertTexView,getContext().getAssets()); } @Override public void onStart() { super.onStart(); /* Dialog dialog = this; if (dialog != null) { int width = ViewGroup.LayoutParams.MATCH_PARENT; int height = ViewGroup.LayoutParams.MATCH_PARENT; dialog.getWindow().setLayout(width, height); }*/ this.setCancelable(false);} public void showError(){ // ProgressBar progressBar = getView().findViewById(R.id.progress_bar); progressBar.setVisibility(View.INVISIBLE); // TextView alertTexView = getView().findViewById(R.id.txt_alert); alertTexView.setText("Error"); alertTexView.setTextColor(getContext().getResources().getColor(R.color.google_red)); } public void showSuccess(){ // ProgressBar progressBar = getView().findViewById(R.id.progress_bar); progressBar.setVisibility(View.INVISIBLE); // TextView alertTexView = getView().findViewById(R.id.txt_alert); alertTexView.setText("Successfull"); alertTexView.setTextColor(Color.GREEN); } public void showCustomMessage(){ // ProgressBar progressBar = getView().findViewById(R.id.progress_bar); progressBar.setVisibility(View.INVISIBLE); // TextView alertTexView = getView().findViewById(R.id.txt_alert); alertTexView.setText(customTex); alertTexView.setTextColor(getContext().getResources().getColor(R.color.google_red)); } public void setCustomMessage(String customMessage){ this.customTex = customMessage; } }
3e0ce779d58eda482fd9effce4534b3814260196
288
java
Java
src/battleodds/main/Effect.java
ThreefoldBurly/battle-odds
458a3923c97e07bbdede2a86c8278d5304cce511
[ "MIT" ]
1
2018-05-19T02:26:19.000Z
2018-05-19T02:26:19.000Z
src/battleodds/main/Effect.java
ThreefoldBurly/battle-odds
458a3923c97e07bbdede2a86c8278d5304cce511
[ "MIT" ]
null
null
null
src/battleodds/main/Effect.java
ThreefoldBurly/battle-odds
458a3923c97e07bbdede2a86c8278d5304cce511
[ "MIT" ]
null
null
null
13.714286
40
0.621528
5,479
package battleodds.main; public abstract class Effect { private final int id; private final String name; public Effect(int aID, String aName) { id = aID; name = aName; } public String getName() { return name; } public int getID() { return id; } }
3e0ce80f315f23a2954743bd500be78cb471daab
1,293
java
Java
response-datastore/response-server-service/src/main/java/com/google/cloud/healthcare/fdamystudies/config/AuthenticationEntryPointImpl.java
nobmizue-jcloudce/fda-mystudies
6b0d752eeba2c1a8b871d2dc931fdd81dbd854c9
[ "MIT" ]
1
2021-01-13T06:38:15.000Z
2021-01-13T06:38:15.000Z
response-datastore/response-server-service/src/main/java/com/google/cloud/healthcare/fdamystudies/config/AuthenticationEntryPointImpl.java
nobmizue-jcloudce/fda-mystudies
6b0d752eeba2c1a8b871d2dc931fdd81dbd854c9
[ "MIT" ]
2
2021-01-17T11:50:01.000Z
2021-01-18T17:26:28.000Z
response-datastore/response-server-service/src/main/java/com/google/cloud/healthcare/fdamystudies/config/AuthenticationEntryPointImpl.java
nobmizue-jcloudce/fda-mystudies
6b0d752eeba2c1a8b871d2dc931fdd81dbd854c9
[ "MIT" ]
1
2021-01-24T15:56:30.000Z
2021-01-24T15:56:30.000Z
33.153846
95
0.779582
5,480
/* * Copyright 2020 Google LLC * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ package com.google.cloud.healthcare.fdamystudies.config; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; import org.springframework.stereotype.Component; @Component public class AuthenticationEntryPointImpl extends BasicAuthenticationEntryPoint { @Override public void commence( HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx) throws IOException { response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName()); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); PrintWriter writer = response.getWriter(); writer.println("HTTP Status 401 - " + authEx.getMessage()); } @Override public void afterPropertiesSet() { // RealmName appears in the login window (Firefox). setRealmName("response-datastore"); super.afterPropertiesSet(); } }
3e0ce8312526e9b2f2d1598393acad24d47d5701
5,783
java
Java
components/camel-kafka/src/test/java/org/apache/camel/component/kafka/integration/KafkaConsumerAsyncManualCommitIT.java
colin-mullikin/camel
ee6a51b9118361ac7a44d6f9eef9de6c842655cc
[ "Apache-2.0" ]
4,262
2015-01-01T15:28:37.000Z
2022-03-31T04:46:41.000Z
components/camel-kafka/src/test/java/org/apache/camel/component/kafka/integration/KafkaConsumerAsyncManualCommitIT.java
colin-mullikin/camel
ee6a51b9118361ac7a44d6f9eef9de6c842655cc
[ "Apache-2.0" ]
3,408
2015-01-03T02:11:17.000Z
2022-03-31T20:07:56.000Z
components/camel-kafka/src/test/java/org/apache/camel/component/kafka/integration/KafkaConsumerAsyncManualCommitIT.java
dhlparcel/camel
3aea09efaf1db4d424b52a813312bee86c1225e9
[ "Apache-2.0" ]
5,505
2015-01-02T14:58:12.000Z
2022-03-30T19:23:41.000Z
40.725352
118
0.661421
5,481
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.kafka.integration; import java.util.Collections; import java.util.Properties; import org.apache.camel.Endpoint; import org.apache.camel.EndpointInject; import org.apache.camel.Exchange; import org.apache.camel.builder.AggregationStrategies; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.kafka.DefaultKafkaManualAsyncCommitFactory; import org.apache.camel.component.kafka.KafkaConstants; import org.apache.camel.component.kafka.KafkaEndpoint; import org.apache.camel.component.kafka.KafkaManualCommit; import org.apache.camel.component.mock.MockEndpoint; import org.apache.kafka.clients.producer.ProducerRecord; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.RepeatedTest; import static org.junit.jupiter.api.Assertions.assertNotNull; public class KafkaConsumerAsyncManualCommitIT extends BaseEmbeddedKafkaTestSupport { public static final String TOPIC = "testManualCommitTest"; @EndpointInject("kafka:" + TOPIC + "?groupId=group1&sessionTimeoutMs=30000&autoCommitEnable=false" + "&allowManualCommit=true&autoOffsetReset=earliest") private Endpoint from; @EndpointInject("mock:result") private MockEndpoint to; @EndpointInject("mock:resultBar") private MockEndpoint toBar; private org.apache.kafka.clients.producer.KafkaProducer<String, String> producer; @BeforeEach public void before() { Properties props = getDefaultProperties(); producer = new org.apache.kafka.clients.producer.KafkaProducer<>(props); } @AfterEach public void after() { if (producer != null) { producer.close(); } // clean all test topics kafkaAdminClient.deleteTopics(Collections.singletonList(TOPIC)); } @Override protected RouteBuilder createRouteBuilder() throws Exception { ((KafkaEndpoint) from).getComponent().setKafkaManualCommitFactory(new DefaultKafkaManualAsyncCommitFactory()); return new RouteBuilder() { @Override public void configure() { from(from).routeId("foo").to("direct:aggregate"); // With sync manual commit, this would throw a concurrent modification exception // It can be usesd in aggregator with completion timeout/interval for instance // WARN: records from one partition must be processed by one unique thread from("direct:aggregate").routeId("aggregate").to(to) .aggregate() .constant(true) .completionTimeout(1) .aggregationStrategy(AggregationStrategies.groupedExchange()) .split().body() .process(e -> { KafkaManualCommit manual = e.getMessage().getBody(Exchange.class) .getMessage().getHeader(KafkaConstants.MANUAL_COMMIT, KafkaManualCommit.class); assertNotNull(manual); manual.commit(); }); from(from).routeId("bar").autoStartup(false).to(toBar); } }; } @RepeatedTest(4) public void kafkaManualCommit() throws Exception { to.expectedMessageCount(5); to.expectedBodiesReceivedInAnyOrder("message-0", "message-1", "message-2", "message-3", "message-4"); // The LAST_RECORD_BEFORE_COMMIT header should include a value as we use // manual commit to.allMessages().header(KafkaConstants.LAST_RECORD_BEFORE_COMMIT).isNotNull(); for (int k = 0; k < 5; k++) { String msg = "message-" + k; ProducerRecord<String, String> data = new ProducerRecord<>(TOPIC, "1", msg); producer.send(data); } to.assertIsSatisfied(3000); to.reset(); // Second step: We shut down our route, we expect nothing will be recovered by our route context.getRouteController().stopRoute("foo"); to.expectedMessageCount(0); // Third step: While our route is stopped, we send 3 records more to Kafka test topic for (int k = 5; k < 8; k++) { String msg = "message-" + k; ProducerRecord<String, String> data = new ProducerRecord<>(TOPIC, "1", msg); producer.send(data); } to.assertIsSatisfied(3000); to.reset(); // Fourth step: We start again our route, since we have been committing the offsets from the first step, // we will expect to consume from the latest committed offset e.g from offset 5 context.getRouteController().startRoute("foo"); to.expectedMessageCount(3); to.expectedBodiesReceivedInAnyOrder("message-5", "message-6", "message-7"); to.assertIsSatisfied(3000); } }
3e0ce92ea0948910f706cd4db032046052ddb5fb
3,268
java
Java
src/test/java/io/jigson/json/filter/strategy/KeepMatchingAndPrimitivesStrategyTest.java
daniel-zarzeczny/jigson-project
1e58e4e63e78895ea77bbd5b4f10973b8248dd4f
[ "Apache-2.0" ]
3
2018-03-18T19:17:58.000Z
2019-04-19T17:35:05.000Z
src/test/java/io/jigson/json/filter/strategy/KeepMatchingAndPrimitivesStrategyTest.java
daniel-zarzeczny/jigson
1e58e4e63e78895ea77bbd5b4f10973b8248dd4f
[ "Apache-2.0" ]
null
null
null
src/test/java/io/jigson/json/filter/strategy/KeepMatchingAndPrimitivesStrategyTest.java
daniel-zarzeczny/jigson
1e58e4e63e78895ea77bbd5b4f10973b8248dd4f
[ "Apache-2.0" ]
null
null
null
34.041667
111
0.670747
5,482
package io.jigson.json.filter.strategy; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import io.jigson.core.JigsonConfigHolder; import org.junit.Before; import org.junit.Test; import static com.google.common.truth.Truth.assertThat; import static io.jigson.utils.JsonUtils.getMapper; public class KeepMatchingAndPrimitivesStrategyTest { private static final String JSON_ARRAY = "[{\"firstName\":\"John\",\"lastName\":\"Snow\", \"age\" : 25}," + "{\"firstName\":\"Sansa\",\"lastName\":\"Stark\", \"age\" : 20}]"; private static final String JSON_ARRAY_WITH_PRIMITIVES = "[\"Winterfell\", \"Castle Black\",{\"firstName\":\"John\",\"lastName\":\"Snow\", \"age\" : 25}," + "{\"firstName\":\"Sansa\",\"lastName\":\"Stark\", \"age\" : 20}]"; private final KeepMatchingAndPrimitivesStrategy filter = KeepMatchingAndPrimitivesStrategy.INSTANCE; private JsonArray jsonArray; private JsonArray jsonArrayWithPrimitives; @Before public void init() { this.jsonArray = getMapper().fromJson(JSON_ARRAY, JsonArray.class); this.jsonArrayWithPrimitives = getMapper().fromJson(JSON_ARRAY_WITH_PRIMITIVES, JsonArray.class); JigsonConfigHolder.init(); } @Test public void shouldFilterOutElement_WhenOneDoesNotMatchCriterion() { // given final String criterion = "firstName=John"; // when final JsonElement actualElement = filter.filter(jsonArray, criterion); // then assertThat(actualElement).isNotNull(); assertThat(actualElement.isJsonNull()).isFalse(); assertThat(actualElement).isNotSameAs(jsonArray); assertThat(actualElement.getAsJsonArray().size()).isEqualTo(1); } @Test public void shouldProduceJsonNull_WhenNoneObjectMatchesCriterion() { // given final String criterion = "age<10"; // when final JsonElement actualElement = filter.filter(jsonArray, criterion); // then assertThat(actualElement).isNotNull(); assertThat(actualElement.isJsonNull()).isTrue(); assertThat(actualElement).isNotSameAs(jsonArray); } @Test public void shouldFilterOutElementAndKeepPrimitives_WhenOneDoesNotMatchCriterion() { // given final String criterion = "firstName=John"; // when final JsonElement actualElement = filter.filter(jsonArrayWithPrimitives, criterion); // then assertThat(actualElement).isNotNull(); assertThat(actualElement.isJsonNull()).isFalse(); assertThat(actualElement).isNotSameAs(jsonArray); assertThat(actualElement.getAsJsonArray().size()).isEqualTo(3); } @Test public void shouldKeepOnlyPrimitives_WhenNoneObjectMeetsCriterion() { // given final String criterion = "age>50"; // when final JsonElement actualElement = filter.filter(jsonArrayWithPrimitives, criterion); // then assertThat(actualElement).isNotNull(); assertThat(actualElement.isJsonNull()).isFalse(); assertThat(actualElement).isNotSameAs(jsonArray); assertThat(actualElement.getAsJsonArray().size()).isEqualTo(2); } }
3e0ce951243d75bdce87de08412b9a8e82de0611
922
java
Java
src/main/java/br/com/helberbelmiro/reader/CategoryLineFilter.java
hbelmiro/taco-ibge-extractor
34ad083dfa06cdafd82982a6b954dfd7a747d7af
[ "Apache-2.0" ]
1
2020-09-12T16:21:07.000Z
2020-09-12T16:21:07.000Z
src/main/java/br/com/helberbelmiro/reader/CategoryLineFilter.java
hbelmiro/taco-ibge-extractor
34ad083dfa06cdafd82982a6b954dfd7a747d7af
[ "Apache-2.0" ]
null
null
null
src/main/java/br/com/helberbelmiro/reader/CategoryLineFilter.java
hbelmiro/taco-ibge-extractor
34ad083dfa06cdafd82982a6b954dfd7a747d7af
[ "Apache-2.0" ]
null
null
null
24.263158
61
0.591106
5,483
package br.com.helberbelmiro.reader; import br.com.helberbelmiro.parsing.FoodParser; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.util.ArrayList; import java.util.Collections; import java.util.List; @ApplicationScoped public class CategoryLineFilter { @Inject private FoodParser foodParser; public List<String> filter(List<String> lines) { String lastFoodLine = null; final List<String> categoryLines = new ArrayList<>(); for (String line : lines) { if (!line.isBlank()) { if (foodParser.isFoodLine(line)) { lastFoodLine = line; } else { if (lastFoodLine != null) { categoryLines.add(line); } } } } return Collections.unmodifiableList(categoryLines); } }
3e0ce9653f5a7a32184b1a51dc6b8fca4ae1a51d
9,593
java
Java
api/src/main/java/org/jboss/shrinkwrap/api/Filters.java
kenfinnigan/shrinkwrap
112375e4f3f599f2260838db93df661ca7b20951
[ "Apache-2.0" ]
48
2015-03-01T09:39:35.000Z
2021-04-18T14:55:18.000Z
api/src/main/java/org/jboss/shrinkwrap/api/Filters.java
kenfinnigan/shrinkwrap
112375e4f3f599f2260838db93df661ca7b20951
[ "Apache-2.0" ]
54
2015-09-13T18:30:21.000Z
2022-02-06T21:13:48.000Z
api/src/main/java/org/jboss/shrinkwrap/api/Filters.java
kenfinnigan/shrinkwrap
112375e4f3f599f2260838db93df661ca7b20951
[ "Apache-2.0" ]
34
2015-03-27T14:21:58.000Z
2022-03-24T00:55:50.000Z
40.133891
130
0.619787
5,484
/* * JBoss, Home of Professional Open Source * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.shrinkwrap.api; import java.util.Collection; import java.util.regex.Pattern; import javax.annotation.processing.Filer; /** * Factory class for the creation of new {@link Filter} instances. Filter instances using this shorthand class will be * created using the {@link ClassLoader} associated with the default {@link Domain}'s {@link Configuration}. * * * @author <a href="mailto:upchh@example.com">Aslak Knutsen</a> * @version $Revision: $ */ public final class Filters { // -------------------------------------------------------------------------------------|| // Class Members ----------------------------------------------------------------------|| // -------------------------------------------------------------------------------------|| private static final String IMPL_CLASS_NAME_INCLUDE_ALL_PATHS = "org.jboss.shrinkwrap.impl.base.filter.IncludeAllPaths"; private static final String IMPL_CLASS_NAME_INCLUDE_REGEXP_PATHS = "org.jboss.shrinkwrap.impl.base.filter.IncludeRegExpPaths"; private static final String IMPL_CLASS_NAME_EXCLUDE_REGEXP_PATHS = "org.jboss.shrinkwrap.impl.base.filter.ExcludeRegExpPaths"; private static final String IMPL_CLASS_NAME_INCLUDE_PATHS = "org.jboss.shrinkwrap.impl.base.filter.IncludePaths"; private static final String IMPL_CLASS_NAME_EXCLUDE_PATHS = "org.jboss.shrinkwrap.impl.base.filter.ExcludePaths"; /** * {@link Filter} that includes all {@link ArchivePath}s. * * Only meant to be used internally. * * @return A {@link Filter} that always return true */ public static Filter<ArchivePath> includeAll() { return getFilterInstance(IMPL_CLASS_NAME_INCLUDE_ALL_PATHS, new Class<?>[] {}, new Object[] {}); } /** * {@link Filer} that include all {@link ArchivePath}s that match the given Regular Expression {@link Pattern}. * * @param regexp * The expression to include * @return A Regular Expression based include {@link Filter} */ public static Filter<ArchivePath> include(String regexp) { return getFilterInstance(IMPL_CLASS_NAME_INCLUDE_REGEXP_PATHS, new Class<?>[] { String.class }, new Object[] { regexp }); } /** * {@link Filter} that exclude all {@link ArchivePath}s that match a given Regular Expression {@link Pattern}. * * @param regexp * The expression to exclude * @return A Regular Expression based exclude {@link Filter} */ public static Filter<ArchivePath> exclude(final String regexp) { return getFilterInstance(IMPL_CLASS_NAME_EXCLUDE_REGEXP_PATHS, new Class<?>[] { String.class }, new Object[] { regexp }); } /** * {@link Filer} that include all {@link ArchivePath}s that match the given List of paths.. * * @param paths * The paths to included * @return A Path list based include {@link Filter} */ public static Filter<ArchivePath> includePaths(final String... paths) { return getFilterInstance(IMPL_CLASS_NAME_INCLUDE_PATHS, new Class<?>[] { String[].class }, new Object[] { paths }); } /** * {@link Filer} that include all {@link ArchivePath}s that match the given List of paths.. * * @param paths * The paths to included * @return A Path list based include {@link Filter} */ public static Filter<ArchivePath> includePaths(final Collection<String> paths) { return getFilterInstance(IMPL_CLASS_NAME_INCLUDE_PATHS, new Class<?>[] { Collection.class }, new Object[] { paths }); } /** * {@link Filter} that exclude all {@link ArchivePath}s that match the given List of paths. * * @param paths * The paths to exclude * @return A Path list based exclude {@link Filter} */ public static Filter<ArchivePath> excludePaths(final String... paths) { return getFilterInstance(IMPL_CLASS_NAME_EXCLUDE_PATHS, new Class<?>[] { String[].class }, new Object[] { paths }); } /** * {@link Filter} that exclude all {@link ArchivePath}s that match the given List of paths. * * @param paths * The paths to exclude * @return A Path list based exclude {@link Filter} */ public static Filter<ArchivePath> excludePaths(final Collection<String> paths) { return getFilterInstance(IMPL_CLASS_NAME_EXCLUDE_PATHS, new Class<?>[] { Collection.class }, new Object[] { paths }); } /** * {@link Filter} that includes listed {@link Package}. * * @param packages * To be included * @return */ public static Filter<ArchivePath> exclude(Package... packages) { return createRegExpFilter(IMPL_CLASS_NAME_EXCLUDE_REGEXP_PATHS, packages); } /** * {@link Filter} that excludes listed {@link Package}. * * @param packages * To be excluded * @return */ public static Filter<ArchivePath> include(Package... packages) { return createRegExpFilter(IMPL_CLASS_NAME_INCLUDE_REGEXP_PATHS, packages); } private static Filter<ArchivePath> createRegExpFilter(String filterClassName, Package... packages) { StringBuilder classExpression = new StringBuilder(); for (Package pack : packages) { classExpression.append("|"); classExpression.append("(.*" + pack.getName().replaceAll("\\.", "\\.") + ".*)"); } classExpression.deleteCharAt(0); return getFilterInstance(filterClassName, new Class<?>[] { String.class }, new Object[] { classExpression.toString() }); } /** * {@link Filter} that includes listed {@link Class}. * * @param classes * To be included * @return */ public static Filter<ArchivePath> include(Class<?>... classes) { return createRegExpFilter(IMPL_CLASS_NAME_INCLUDE_REGEXP_PATHS, classes); } /** * {@link Filter} that excludes listed {@link Class}. * * @param classes * To be excluded * @return */ public static Filter<ArchivePath> exclude(Class<?>... classes) { return createRegExpFilter(IMPL_CLASS_NAME_EXCLUDE_REGEXP_PATHS, classes); } private static Filter<ArchivePath> createRegExpFilter(String regExpFilterImplName, Class<?>... classes) { StringBuilder classExpression = new StringBuilder(); for (Class<?> clazz : classes) { classExpression.append("|"); classExpression.append("(.*" + clazz.getName().replaceAll("\\.", "\\.") + "\\.class)"); } classExpression.deleteCharAt(0); return getFilterInstance(regExpFilterImplName, new Class<?>[] { String.class }, new Object[] { classExpression.toString() }); } /** * Creates a new {@link Filter} instance using the given impl class name, constructor arguments and type * * @param filterClassName * @param ctorTypes * @param ctorArguments * @return */ @SuppressWarnings("unchecked") private static Filter<ArchivePath> getFilterInstance(final String filterClassName, final Class<?>[] ctorTypes, final Object[] ctorArguments) { // Precondition checks assert filterClassName != null && filterClassName.length() > 0 : "Filter class name must be specified"; assert ctorTypes != null : "Construction types must be specified"; assert ctorArguments != null : "Construction arguments must be specified"; assert ctorTypes.length == ctorArguments.length : "The number of ctor arguments and their types must match"; // Find the filter impl class in the configured CLs final Class<Filter<ArchivePath>> filterClass; try { filterClass = (Class<Filter<ArchivePath>>) ClassLoaderSearchUtil.findClassFromClassLoaders(filterClassName, ShrinkWrap.getDefaultDomain().getConfiguration().getClassLoaders()); } catch (final ClassNotFoundException cnfe) { throw new IllegalStateException("Could not find filter implementation class " + filterClassName + " in any of the configured CLs", cnfe); } // Make the new instance return SecurityActions.newInstance(filterClass, ctorTypes, ctorArguments, Filter.class); } // -------------------------------------------------------------------------------------|| // Constructor ------------------------------------------------------------------------|| // -------------------------------------------------------------------------------------|| /** * No instantiation */ private Filters() { } }
3e0ce9f40184c414681b17f803c16789b36f59ba
3,813
java
Java
KalturaClient/src/main/java/com/kaltura/client/types/FairplayEntryContextPluginData.java
fahadnasrullah109/KalturaClient-Android
f753b968023e55b7629ccefce845e2482d2f6dae
[ "MIT" ]
null
null
null
KalturaClient/src/main/java/com/kaltura/client/types/FairplayEntryContextPluginData.java
fahadnasrullah109/KalturaClient-Android
f753b968023e55b7629ccefce845e2482d2f6dae
[ "MIT" ]
null
null
null
KalturaClient/src/main/java/com/kaltura/client/types/FairplayEntryContextPluginData.java
fahadnasrullah109/KalturaClient-Android
f753b968023e55b7629ccefce845e2482d2f6dae
[ "MIT" ]
null
null
null
32.87069
121
0.671912
5,485
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // // Copyright (C) 2006-2018 Kaltura Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // @ignore // =================================================================================================== package com.kaltura.client.types; import android.os.Parcel; import com.google.gson.JsonObject; import com.kaltura.client.Params; import com.kaltura.client.utils.GsonParser; import com.kaltura.client.utils.request.MultiRequestBuilder; /** * This class was generated using exec.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") @MultiRequestBuilder.Tokenizer(FairplayEntryContextPluginData.Tokenizer.class) public class FairplayEntryContextPluginData extends PluginData { public interface Tokenizer extends PluginData.Tokenizer { String publicCertificate(); } /** * For fairplay (and maybe in the future other drm providers) we need to return a public certificate to encrypt the request from the player to the server. */ private String publicCertificate; // publicCertificate: public String getPublicCertificate(){ return this.publicCertificate; } public void setPublicCertificate(String publicCertificate){ this.publicCertificate = publicCertificate; } public void publicCertificate(String multirequestToken){ setToken("publicCertificate", multirequestToken); } public FairplayEntryContextPluginData() { super(); } public FairplayEntryContextPluginData(JsonObject jsonObject) throws APIException { super(jsonObject); if(jsonObject == null) return; // set members values: publicCertificate = GsonParser.parseString(jsonObject.get("publicCertificate")); } public Params toParams() { Params kparams = super.toParams(); kparams.add("objectType", "KalturaFairplayEntryContextPluginData"); kparams.add("publicCertificate", this.publicCertificate); return kparams; } public static final Creator<FairplayEntryContextPluginData> CREATOR = new Creator<FairplayEntryContextPluginData>() { @Override public FairplayEntryContextPluginData createFromParcel(Parcel source) { return new FairplayEntryContextPluginData(source); } @Override public FairplayEntryContextPluginData[] newArray(int size) { return new FairplayEntryContextPluginData[size]; } }; @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeString(this.publicCertificate); } public FairplayEntryContextPluginData(Parcel in) { super(in); this.publicCertificate = in.readString(); } }
3e0cea285f532d26a9726ba0f4bfcb957016c026
722
java
Java
superhttp/src/main/java/com/qpg/superhttp/cookie/store/CookieStore.java
qiaodashaoye/SuperHttp
3ef46e10f47c236fe5a6326f056e28e9394beaea
[ "Apache-2.0" ]
129
2017-11-20T08:40:25.000Z
2021-03-01T04:49:53.000Z
superhttp/src/main/java/com/qpg/superhttp/cookie/store/CookieStore.java
qiaodashaoye/SuperHttp
3ef46e10f47c236fe5a6326f056e28e9394beaea
[ "Apache-2.0" ]
null
null
null
superhttp/src/main/java/com/qpg/superhttp/cookie/store/CookieStore.java
qiaodashaoye/SuperHttp
3ef46e10f47c236fe5a6326f056e28e9394beaea
[ "Apache-2.0" ]
3
2019-06-10T08:05:29.000Z
2020-03-13T17:42:20.000Z
21.235294
54
0.682825
5,486
package com.qpg.superhttp.cookie.store; import java.util.List; import okhttp3.Cookie; import okhttp3.HttpUrl; public interface CookieStore { /** 保存url对应所有cookie */ void saveCookie(HttpUrl url, List<Cookie> cookie); /** 保存url对应所有cookie */ void saveCookie(HttpUrl url, Cookie cookie); /** 加载url所有的cookie */ List<Cookie> loadCookie(HttpUrl url); /** 获取当前所有保存的cookie */ List<Cookie> getAllCookie(); /** 获取当前url对应的所有的cookie */ List<Cookie> getCookie(HttpUrl url); /** 根据url和cookie移除对应的cookie */ boolean removeCookie(HttpUrl url, Cookie cookie); /** 根据url移除所有的cookie */ boolean removeCookie(HttpUrl url); /** 移除所有的cookie */ boolean removeAllCookie(); }
3e0ceb535abce9b73480e5ba405553c81540aac1
1,983
java
Java
Hulu/src/main/java/net/hcriots/hcfactions/listener/NetherPortalListener.java
AndyReckt/Old-Code
200501c7eb4aaf5709b4adceb053fee6707173fa
[ "Apache-2.0" ]
1
2022-01-09T21:29:19.000Z
2022-01-09T21:29:19.000Z
Hulu/src/main/java/net/hcriots/hcfactions/listener/NetherPortalListener.java
AndyReckt/Old-Code
200501c7eb4aaf5709b4adceb053fee6707173fa
[ "Apache-2.0" ]
null
null
null
Hulu/src/main/java/net/hcriots/hcfactions/listener/NetherPortalListener.java
AndyReckt/Old-Code
200501c7eb4aaf5709b4adceb053fee6707173fa
[ "Apache-2.0" ]
null
null
null
33.05
101
0.629854
5,487
/* * Copyright (c) 2020. * Created by YoloSanta * Created On 10/22/20, 1:23 AM */ package net.hcriots.hcfactions.listener; import net.hcriots.hcfactions.Hulu; import net.hcriots.hcfactions.team.Team; import net.hcriots.hcfactions.team.claims.LandBoard; import net.hcriots.hcfactions.team.dtr.DTRBitmask; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerPortalEvent; import org.bukkit.event.player.PlayerTeleportEvent; public class NetherPortalListener implements Listener { @EventHandler public void onPlayerPortal(PlayerPortalEvent event) { Player player = event.getPlayer(); if (event.getCause() != PlayerTeleportEvent.TeleportCause.NETHER_PORTAL) { return; } if (event.getTo().getWorld().getEnvironment() == World.Environment.NORMAL) { if (DTRBitmask.SAFE_ZONE.appliesAt(event.getFrom())) { event.setCancelled(true); player.teleport(Hulu.getInstance().getServer().getWorld("world").getSpawnLocation()); player.sendMessage(ChatColor.GREEN + "Teleported to overworld spawn!"); } } Location to = event.getTo(); if (DTRBitmask.ROAD.appliesAt(to)) { Team team = LandBoard.getInstance().getTeam(to); if (team.getName().contains("North")) { to.add(20, 0, 0); // add 20 on the X axis } else if (team.getName().contains("South")) { to.subtract(20, 0, 0); // subtract 20 on the X axis } else if (team.getName().contains("East")) { to.add(0, 0, 20); // add 20 on the Z axis } else if (team.getName().contains("West")) { to.subtract(0, 0, 20); // subtract 20 on the Z axis } } event.setTo(to); } }
3e0cec6686564c8f79dcdca185c0e06764ea0955
3,125
java
Java
xworker_dataobject/src/main/java/xworker/dataObject/query/DataObjectQueryActions.java
x-meta/xworker
430fba081a78b5d3871669bf6fcb1e952ad258b2
[ "Apache-2.0" ]
2
2015-01-03T18:14:59.000Z
2015-08-05T10:11:21.000Z
xworker_dataobject/src/main/java/xworker/dataObject/query/DataObjectQueryActions.java
x-meta/xworker
430fba081a78b5d3871669bf6fcb1e952ad258b2
[ "Apache-2.0" ]
16
2020-05-15T21:54:11.000Z
2021-08-14T06:42:58.000Z
xworker_dataobject/src/main/java/xworker/dataObject/query/DataObjectQueryActions.java
x-meta/xworker
430fba081a78b5d3871669bf6fcb1e952ad258b2
[ "Apache-2.0" ]
2
2015-06-24T07:39:35.000Z
2015-08-05T10:11:23.000Z
30.339806
118
0.68736
5,488
package xworker.dataObject.query; import java.util.List; import org.xmeta.ActionContext; import org.xmeta.ActionException; import org.xmeta.Thing; import org.xmeta.World; import org.xmeta.util.UtilAction; import org.xmeta.util.UtilData; import org.xmeta.util.UtilMap; import ognl.OgnlException; import xworker.dataObject.DataObject; import xworker.lang.executor.Executor; public class DataObjectQueryActions { private static final String TAG = DataObjectQueryActions.class.getName(); /** * 获取数据对象。 * * @param actionContext * @return * @throws OgnlException */ public static Object getDataObject(ActionContext actionContext) throws OgnlException{ Thing self = (Thing) actionContext.get("self"); //先从属性获取 Object obj = UtilData.getData(self, "dataObject", actionContext); if(obj instanceof Thing){ return obj; }else if(obj instanceof String && !"".equals(obj)){ return World.getInstance().getThing((String) obj); } //然后从子事物获取 Thing dataObjects = self.getThing("DataObjects@0"); if(dataObjects != null && dataObjects.getChilds().size() > 0){ return dataObjects.getChilds().get(0); } return null; } public static Object getConditionConfig(ActionContext actionContext) throws OgnlException{ Thing self = (Thing) actionContext.get("self"); //先从属性获取 Object obj = UtilData.getData(self, "condition", actionContext); if(obj instanceof Thing){ return obj; }else if(obj instanceof String && !"".equals(obj)){ return World.getInstance().getThing((String) obj); } //然后从子事物获取 return self.getThing("Condition@0"); } /** * 查询。 * * @param actionContext * @return */ @SuppressWarnings("unchecked") public static List<DataObject> query(ActionContext actionContext){ Thing self = (Thing) actionContext.get("self"); boolean debug = UtilAction.getDebugLog(self, actionContext); Thing dataObject = (Thing) self.doAction("getDataObject", actionContext); if(dataObject == null){ throw new ActionException("DataObject cannt be null, path=" + self.getMetadata().getPath()); } Object conditionConfig = self.doAction("getConditionConfig", actionContext); Object conditionData = actionContext.get("conditionData"); Object pageInfo = actionContext.get("pageInfo"); if(debug){ Executor.info(TAG, "DataObject query: dataObjectPath=" + dataObject.getMetadata().getPath()); Executor.info(TAG, " condition=" + conditionConfig); Executor.info(TAG, " conditionData=" + conditionData); Executor.info(TAG, " pageInfo=" + pageInfo); } List<DataObject> datas = (List<DataObject>) dataObject.doAction("query", actionContext, UtilMap.toMap( new Object[]{"conditionConfig", conditionConfig, "conditionData", conditionData, "pageInfo", pageInfo})); if(datas == null){ throw new ActionException("DataObject query return null, dataObject error, path=" + self.getMetadata().getPath()); } if(debug){ Executor.info(TAG, " dataSize=" + datas.size()); } return datas; } }
3e0cec9a630ba475cac7e71cef5ac42097246fc1
2,325
java
Java
src/main/java/com/rewe/digital/messaging/KafkaMessageHandler.java
wschne/kafka-browser
e0ed47b0347ac232923ecd30bc0bcee99651a68b
[ "MIT" ]
1
2022-02-17T09:47:12.000Z
2022-02-17T09:47:12.000Z
src/main/java/com/rewe/digital/messaging/KafkaMessageHandler.java
wschne/kafka-browser
e0ed47b0347ac232923ecd30bc0bcee99651a68b
[ "MIT" ]
null
null
null
src/main/java/com/rewe/digital/messaging/KafkaMessageHandler.java
wschne/kafka-browser
e0ed47b0347ac232923ecd30bc0bcee99651a68b
[ "MIT" ]
null
null
null
36.328125
113
0.664946
5,489
package com.rewe.digital.messaging; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import com.rewe.digital.kafka.KafkaQueryExecutor; import com.rewe.digital.messaging.events.querying.ExecuteQueryEvent; import com.rewe.digital.messaging.events.querying.QueryExecutionFinishedEvent; import com.rewe.digital.messaging.events.querying.ShowQueryResultEvent; import com.rewe.digital.messaging.events.querying.ShowQueryingErrorEvent; import com.victorlaerte.asynctask.AsyncTask; import lombok.val; import org.apache.spark.sql.AnalysisException; import javax.inject.Inject; public class KafkaMessageHandler implements MessageHandler { private final EventBus eventBus; private final KafkaQueryExecutor kafkaQueryExecutor; @Inject public KafkaMessageHandler(final EventBus eventBus, final KafkaQueryExecutor kafkaQueryExecutor) { this.eventBus = eventBus; this.kafkaQueryExecutor = kafkaQueryExecutor; this.eventBus.register(this); } @Subscribe private void executeQueryAndShowResult(final ExecuteQueryEvent executeQueryEvent) { AsyncTask executeQueryTask = new AsyncTask() { @Override public void onPreExecute() { } @Override public Object doInBackground(Object[] params) { try { val result = kafkaQueryExecutor.executeQuery(executeQueryEvent.getQuery()); val topicName = executeQueryEvent.getQuery().getTopic(); val resultEvent = new ShowQueryResultEvent(executeQueryEvent.getTarget(), topicName, result); eventBus.post(resultEvent); } catch (AnalysisException e) { val errorMessage = e.getSimpleMessage(); eventBus.post(new ShowQueryingErrorEvent(errorMessage)); } return null; } @Override public void onPostExecute(Object resultEvent) { eventBus.post(new QueryExecutionFinishedEvent(executeQueryEvent.getQuery().getTopic())); } @Override public void progressCallback(Object[] params) { } }; executeQueryTask.execute(); } }
3e0cec9e98a2e8de33881ae6c9bddf5ace833723
2,434
java
Java
nuxeo-features/nuxeo-platform-imaging-tiling/nuxeo-platform-imaging-tiling-preview/src/test/java/org/nuxeo/ecm/platform/pictures/tiles/gwt/client/GwtTestTilingInfo.java
sailfly/nuxeo
24aa96d078be77ce09973b08b38ee1498c0903bf
[ "Apache-2.0" ]
1
2021-02-15T19:07:59.000Z
2021-02-15T19:07:59.000Z
nuxeo-features/nuxeo-platform-imaging-tiling/nuxeo-platform-imaging-tiling-preview/src/test/java/org/nuxeo/ecm/platform/pictures/tiles/gwt/client/GwtTestTilingInfo.java
sampisamuel/nuxeo
7ec7c164e508223eef05bb198066920399440efe
[ "Apache-2.0" ]
null
null
null
nuxeo-features/nuxeo-platform-imaging-tiling/nuxeo-platform-imaging-tiling-preview/src/test/java/org/nuxeo/ecm/platform/pictures/tiles/gwt/client/GwtTestTilingInfo.java
sampisamuel/nuxeo
7ec7c164e508223eef05bb198066920399440efe
[ "Apache-2.0" ]
null
null
null
39.258065
127
0.52424
5,490
/* * (C) Copyright 2006-2008 Nuxeo SA (http://nuxeo.com/) and others. * * 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. * * Contributors: * Alexandre Russel * * $Id$ */ package org.nuxeo.ecm.platform.pictures.tiles.gwt.client; import org.nuxeo.ecm.platform.pictures.tiles.gwt.client.model.TilingInfo; import com.google.gwt.junit.client.GWTTestCase; /** * @author Alexandre Russel */ public class GwtTestTilingInfo extends GWTTestCase { private TilingInfo info = new TilingInfo("docId", "repoId", "/nuxeo"); @Override public String getModuleName() { return "org.nuxeo.ecm.platform.pictures.tiles.gwt.TilingPreview"; } public void testParseResponse() { info.parseResponse(jsonString); assertTrue(info.getZoom() > 0.2); assertTrue(info.getZoom() < 0.3); } private static String jsonString = "{" + " \"originalImage\": {" + " \"width\": 2386," + " \"height\": 3567," + " \"format\": \"JPEG\"" + " }," + " \"additionalInfo\": {" + " \"XTiles\": \"3\"," + " \"outputDirPath\": \"/tmp/default_8c3fb786-a397-44f1-9ef6-c425195b9f43_file_content/tiles-200-200-4\"," + " \"YTiles\": \"4\"," + " \"TilesWidth\": \"200\"," + " \"TilesHeight\": \"200\"," + " \"MaxTiles\": \"4\"" + " }," + " \"srcImage\": {" + " \"width\": 1193," + " \"height\": 1784," + " \"format\": \"JPEG\"" + " }," + " \"tileInfo\": {" + " \"zoom\": 0.25146690011024475," + " \"xtiles\": 3," + " \"maxtiles\": 4," + " \"ytiles\": 4," + " \"tileHeight\": 200," + " \"tileWidth\": 200" + " }" + " }"; }
3e0ced03010c773bdee4b56424d9cb27cba6a576
2,062
java
Java
src/main/java/com/qa/ims/persistence/domain/Order.java
sarahkgh/IMS-Starter
4d4cc076dbef465d7a694570c9e7e37192a9541d
[ "MIT" ]
null
null
null
src/main/java/com/qa/ims/persistence/domain/Order.java
sarahkgh/IMS-Starter
4d4cc076dbef465d7a694570c9e7e37192a9541d
[ "MIT" ]
null
null
null
src/main/java/com/qa/ims/persistence/domain/Order.java
sarahkgh/IMS-Starter
4d4cc076dbef465d7a694570c9e7e37192a9541d
[ "MIT" ]
null
null
null
20.62
113
0.697866
5,491
package com.qa.ims.persistence.domain; import java.util.Objects; public class Order { private long orderId; private Customer customer; private long orderQuantity; private Item item; public Order(long orderId, Customer customer, long orderQuantity, Item item) { this.orderId = orderId; this.customer = customer; this.orderQuantity = orderQuantity; this.item = item; } public Order(long orderId, long orderQuantity) { this.setOrderId(orderId); this.setOrderQuantity(orderQuantity); } public Order(Customer customer, long orderQuantity) { super(); this.customer = customer; this.orderQuantity = orderQuantity; } public Order(long orderId, Item item) { super(); this.orderId = orderId; this.item = item; } public Order(long orderId, long orderQuantity, Item item) { super(); this.orderId = orderId; this.orderQuantity = orderQuantity; this.item = item; } public long getOrderId() { return orderId; } public void setOrderId(long orderId) { this.orderId = orderId; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public long getOrderQuantity() { return orderQuantity; } public void setOrderQuantity(long orderQuantity) { this.orderQuantity = orderQuantity; } public Item getItem() { return item; } public void setItem(Item item) { this.item = item; } @Override public String toString() { return "Order [orderId=" + orderId + ", customer=" + customer + ", orderQuantity=" + orderQuantity + ", item=" + item + "]"; } @Override public int hashCode() { return Objects.hash(customer, item, orderId, orderQuantity); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Order other = (Order) obj; return Objects.equals(customer, other.customer) && Objects.equals(item, other.item) && orderId == other.orderId && orderQuantity == other.orderQuantity; } }
3e0ced8c907eecf003c3898cde5f018ed371307d
276
java
Java
pvmanager/datasource-sys/src/main/java/org/diirt/datasource/sys/package-info.java
wrapper755/diirt
77ad809b390410f05482dccdeae8005b92e56539
[ "MIT" ]
null
null
null
pvmanager/datasource-sys/src/main/java/org/diirt/datasource/sys/package-info.java
wrapper755/diirt
77ad809b390410f05482dccdeae8005b92e56539
[ "MIT" ]
null
null
null
pvmanager/datasource-sys/src/main/java/org/diirt/datasource/sys/package-info.java
wrapper755/diirt
77ad809b390410f05482dccdeae8005b92e56539
[ "MIT" ]
null
null
null
30.666667
91
0.713768
5,492
/** * Copyright (C) 2010-14 diirt developers. See COPYRIGHT.TXT * All rights reserved. Use is subject to license terms. See LICENSE.TXT */ /** * DataSource for system data (<a href="doc-files/sys-datasource.html">channel syntax</a>). */ package org.diirt.datasource.sys;
3e0cee5e90fc65e274c3cb991cc1b755e981904b
474
java
Java
library/src/main/java/com/climate/mirage/exceptions/MirageOomException.java
jdannhausenbrun/mirage
3621fbb1e58a913e91de6559cddb14fc2c728a40
[ "Apache-2.0" ]
12
2015-07-16T02:49:11.000Z
2021-09-17T11:05:21.000Z
library/src/main/java/com/climate/mirage/exceptions/MirageOomException.java
jdannhausenbrun/mirage
3621fbb1e58a913e91de6559cddb14fc2c728a40
[ "Apache-2.0" ]
1
2017-02-27T23:36:19.000Z
2017-02-27T23:36:19.000Z
library/src/main/java/com/climate/mirage/exceptions/MirageOomException.java
jdannhausenbrun/mirage
3621fbb1e58a913e91de6559cddb14fc2c728a40
[ "Apache-2.0" ]
6
2016-01-19T21:51:04.000Z
2020-08-05T21:07:17.000Z
18.96
85
0.765823
5,493
package com.climate.mirage.exceptions; import com.climate.mirage.Mirage; public class MirageOomException extends RuntimeException implements MirageException { private Mirage.Source source; public MirageOomException(Mirage.Source source) { super(); this.source = source; } public MirageOomException(Mirage.Source source, Throwable throwable) { super(throwable); this.source = source; } @Override public Mirage.Source getSource() { return source; } }
3e0ceea8e7ea1d20bf97908c4d735fcab39b4edb
5,013
java
Java
src/com/ugiant/jfinalext/controller/tpb/sys/auth/TpbSysUserController.java
zhechu/ugiant_simple
42807377cb0415b31cee1c7d90dfcca43d4f7157
[ "MIT" ]
null
null
null
src/com/ugiant/jfinalext/controller/tpb/sys/auth/TpbSysUserController.java
zhechu/ugiant_simple
42807377cb0415b31cee1c7d90dfcca43d4f7157
[ "MIT" ]
null
null
null
src/com/ugiant/jfinalext/controller/tpb/sys/auth/TpbSysUserController.java
zhechu/ugiant_simple
42807377cb0415b31cee1c7d90dfcca43d4f7157
[ "MIT" ]
null
null
null
31.727848
126
0.720726
5,494
package com.ugiant.jfinalext.controller.tpb.sys.auth; import java.util.List; import com.jfinal.aop.Before; import com.jfinal.plugin.activerecord.Record; import com.jfinal.plugin.activerecord.tx.Tx; import com.ugiant.constant.base.SessionAttriKey; import com.ugiant.constant.base.Status; import com.ugiant.exception.MyException; import com.ugiant.jfinalbase.BaseController; import com.ugiant.jfinalbase.annotation.RequiresAuthentication; import com.ugiant.jfinalbase.annotation.RequiresPermissions; import com.ugiant.jfinalext.interceptor.UserMenuBtnAllInterceptor; import com.ugiant.jfinalext.model.base.LoginUserInfo; import com.ugiant.jfinalext.model.base.ResponseModel; import com.ugiant.jfinalext.model.tpb.TpbSysUser; import com.ugiant.jfinalext.service.tpb.SystemService; import com.ugiant.jfinalext.validator.admin.tpb.ResetPwdValidator; import com.ugiant.jfinalext.validator.admin.tpb.TpbSysUserValidator; import com.ugiant.jfinalext.validator.common.IdValidator; /** * 后台用户 控制器 * @author lingyuwang * */ @RequiresAuthentication public class TpbSysUserController extends BaseController { private SystemService systemService = SystemService.service; // 系统管理业务 service /** * 进入后台用户管理页 */ @RequiresPermissions({"sys:manage:sysuser:view"}) @Before(UserMenuBtnAllInterceptor.class) public void index(){ this.render("tpb_sys_user_manage.ftl"); } /** * 进入修改密码页 */ public void to_reset_password(){ this.render("to_reset_password.ftl"); } /** * 修改密码 */ @Before({ResetPwdValidator.class, Tx.class}) public void reset_password(){ ResponseModel rm = new ResponseModel(); String old_password = this.getPara("old_password"); String new_password = this.getPara("new_password"); LoginUserInfo loginUserInfo = (LoginUserInfo) this.getSession().getAttribute(SessionAttriKey.LOGIN_USER_INFO); if (loginUserInfo == null) { throw new MyException("用户未登陆"); } boolean flag = systemService.resetPwd(loginUserInfo.getUsername(), old_password, new_password, loginUserInfo.getUserId()); if (!flag) { throw new MyException("修改密码失败"); } rm.msgSuccess("修改密码成功"); this.renderJson(rm); } /** * 获取后台用户数据 */ @RequiresPermissions({"sys:manage:sysuser:view"}) public void data(){ List<Record> data = systemService.findTpbSysUser(); this.setAttr("rows", data); this.renderJson(); } /** * 进入添加用户页面 */ @RequiresPermissions({"sys:manage:sysuser:add"}) public void toAdd(){ Integer id = this.getParaToInt("id"); Record sysUser = systemService.findSysUserDetailById(id); if (sysUser != null) { this.setAttr("tpbSysUser", sysUser); } this.render("tpb_sys_user_add.ftl"); } /** * 添加或更新 */ @RequiresPermissions({"sys:manage:sysuser:add", "sys:manage:sysuser:edit"}) @Before({TpbSysUserValidator.class, Tx.class}) public void save(){ ResponseModel rm = new ResponseModel(); LoginUserInfo loginUserInfo = (LoginUserInfo) getSession().getAttribute(SessionAttriKey.LOGIN_USER_INFO); Integer currentUserId = loginUserInfo.getUserId(); // 当前用户 id TpbSysUser sysUser = this.getModel(TpbSysUser.class); Integer[] roleIds = this.getParaValuesToInt("roleIds"); String password = this.getPara("password"); Integer id = sysUser.getInt("id"); if (id != null) { // 更新 systemService.updateSysUser(id, sysUser.getStr("username"), sysUser.getStr("nickname"), password, roleIds, currentUserId); } else { // 添加 systemService.addSysUser(sysUser, password, roleIds, currentUserId); } rm.msgSuccess("操作后台用户成功"); this.renderJson(rm); } /** * 禁用 */ @RequiresPermissions({"sys:manage:sysuser:forbidden"}) @Before({IdValidator.class, Tx.class}) public void forbidden(){ ResponseModel rm = new ResponseModel(); Integer id = this.getParaToInt("id"); LoginUserInfo loginUserInfo = (LoginUserInfo) getSession().getAttribute(SessionAttriKey.LOGIN_USER_INFO); Integer currentUserId = loginUserInfo.getUserId(); // 当前用户 id systemService.updateSysUserStatus(id, Status.FORBIDDEN, currentUserId); rm.msgSuccess("禁用成功"); this.renderJson(rm); } /** * 启用 */ @RequiresPermissions({"sys:manage:sysuser:normal"}) @Before({IdValidator.class, Tx.class}) public void normal(){ ResponseModel rm = new ResponseModel(); Integer id = this.getParaToInt("id"); LoginUserInfo loginUserInfo = (LoginUserInfo) getSession().getAttribute(SessionAttriKey.LOGIN_USER_INFO); Integer currentUserId = loginUserInfo.getUserId(); // 当前用户 id systemService.updateSysUserStatus(id, Status.NORMAL, currentUserId); rm.msgSuccess("启用成功"); this.renderJson(rm); } /** * 删除 */ @RequiresPermissions({"sys:manage:sysuser:del"}) @Before({IdValidator.class, Tx.class}) public void remove(){ ResponseModel rm = new ResponseModel(); Integer id = this.getParaToInt("id"); systemService.deleteSysUser(id); rm.msgSuccess("删除成功"); this.renderJson(rm); } }
3e0ceeaf3834f5d9c2e853c98053bd36cdab24c1
2,347
java
Java
src/main/java/de/taimos/pipeline/aws/PluginImpl.java
smcavallo/pipeline-aws-plugin
2cbd6200a8545ecde900f421288d514435a8ce9a
[ "Apache-2.0" ]
425
2016-11-04T10:42:22.000Z
2022-02-23T10:15:45.000Z
src/main/java/de/taimos/pipeline/aws/PluginImpl.java
smcavallo/pipeline-aws-plugin
2cbd6200a8545ecde900f421288d514435a8ce9a
[ "Apache-2.0" ]
232
2016-11-23T23:12:30.000Z
2022-03-14T09:54:45.000Z
src/main/java/de/taimos/pipeline/aws/PluginImpl.java
smcavallo/pipeline-aws-plugin
2cbd6200a8545ecde900f421288d514435a8ce9a
[ "Apache-2.0" ]
223
2016-11-18T22:00:47.000Z
2022-03-24T10:32:55.000Z
25.236559
106
0.754154
5,495
/* * - * #%L * Pipeline: AWS Steps * %% * Copyright (C) 2016 Taimos GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package de.taimos.pipeline.aws; import hudson.Extension; import hudson.ExtensionList; import static hudson.model.Descriptor.FormException; import jenkins.model.GlobalConfiguration; import javax.annotation.Nonnull; import net.sf.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.StaplerRequest; import org.jenkinsci.Symbol; /** * Global configuration */ @Extension @Symbol("pipelineStepsAWS") public class PluginImpl extends GlobalConfiguration { private boolean enableCredentialsFromNode; /** * Default constructor. */ @DataBoundConstructor public PluginImpl() { load(); } @Override public boolean configure(StaplerRequest req, JSONObject json) throws FormException { json = json.getJSONObject("enableCredentialsFromNode"); enableCredentialsFromNode = json.getBoolean("enableCredentialsFromNode"); save(); return true; } /** * Whether or not to retrieve credentials from the node. Defaults to using the master's instance profile. * @return True if enabled. */ public boolean isEnableCredentialsFromNode() { return this.enableCredentialsFromNode; } /** * Return the singleton instance. * * @return the one. */ @Nonnull public static PluginImpl getInstance() { return ExtensionList.lookup(PluginImpl.class).get(0); } /** * Set enableCredentialsFromNode * Default value is false. * * @param enableCredentialsFromNode whether to retrieve credentials from node or from master */ @DataBoundSetter public void setEnableCredentialsFromNode(boolean enableCredentialsFromNode) { this.enableCredentialsFromNode = enableCredentialsFromNode; } }
3e0ceefae2486684f8218f76da3907327ad88ded
6,733
java
Java
de.dc.javafx.xcore.lang.ide/src/de/dc/javafx/xcore/lang/ide/wizards/BaseWizardPage.java
chqu1012/de.dc.emf.javafx.xtext.lang
c6e6c8686285c8cb852c057693427b47e3662b84
[ "Apache-2.0" ]
5
2019-04-14T12:15:30.000Z
2019-05-17T15:19:29.000Z
de.dc.javafx.xcore.lang.ide/src/de/dc/javafx/xcore/lang/ide/wizards/BaseWizardPage.java
chqu1012/de.dc.emf.javafx.xtext.lang
c6e6c8686285c8cb852c057693427b47e3662b84
[ "Apache-2.0" ]
456
2019-04-09T08:22:26.000Z
2019-06-29T09:19:32.000Z
de.dc.javafx.xcore.lang.ide/src/de/dc/javafx/xcore/lang/ide/wizards/BaseWizardPage.java
chqu1012/de.dc.emf.javafx.xtext.lang
c6e6c8686285c8cb852c057693427b47e3662b84
[ "Apache-2.0" ]
null
null
null
30.604545
156
0.699688
5,496
package de.dc.javafx.xcore.lang.ide.wizards; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.internal.core.JavaElement; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; 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.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.ContainerSelectionDialog; public abstract class BaseWizardPage<T> extends WizardPage{ public static final String DEFAULT_DESCRIPTION = "This wizard creates a new file with *.javafxlang extension that can be opened by a JavaFX Lang Editor."; public static final String DEFAULT_FILE_EXTENSTION = "javafxlang"; protected T model; protected ISelection selection; protected Text containerText; protected Text fileText; protected Text packageText; protected BaseWizardPage(ISelection selection, T model) { super("wizardPage"); this.model = model; setTitle(title()); setDescription(description()); this.selection = selection; } private String description() { return DEFAULT_DESCRIPTION; } protected abstract String title(); @Override public void createControl(Composite parent) { Composite container = new Composite(parent, SWT.NULL); GridLayout layout = new GridLayout(); container.setLayout(layout); layout.numColumns = 3; layout.verticalSpacing = 9; Label label = new Label(container, SWT.NULL); label.setText("&Container:"); containerText = new Text(container, SWT.BORDER | SWT.SINGLE); GridData gd = new GridData(GridData.FILL_HORIZONTAL); containerText.setLayoutData(gd); containerText.addModifyListener(e -> dialogChanged()); Button button = new Button(container, SWT.PUSH); button.setText("Browse..."); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleBrowse(); } }); fileText = createLabelText(container, "&File name"); packageText = createLabelText(container, "Package"); createContent(container); initialize(); dialogChanged(); setControl(container); } protected Combo createLabelCombo(Composite parent, String labelContent) { new Label(parent, SWT.NONE).setText(labelContent+":"); Combo text = new Combo(parent, SWT.BORDER); text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); text.addModifyListener(e -> dialogChanged()); new Label(parent, SWT.NONE); return text; } protected Text createLabelText(Composite parent, String labelContent) { new Label(parent, SWT.NONE).setText(labelContent+":"); Text text = new Text(parent, SWT.BORDER); text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); text.addModifyListener(e -> dialogChanged()); new Label(parent, SWT.NONE); return text; } protected Button createLabelCheck(Composite parent, String labelContent) { new Label(parent, SWT.NONE); Button button = new Button(parent, SWT.CHECK); button.setText(labelContent); button.setLayoutData(new GridData(SWT.FILL, SWT.LEFT, true, false, 1, 1)); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { dialogChanged(); } }); new Label(parent, SWT.NONE); return button; } protected abstract void createContent(Composite container); private void handleBrowse() { ContainerSelectionDialog dialog = new ContainerSelectionDialog( getShell(), ResourcesPlugin.getWorkspace().getRoot(), false, "Select new file container"); if (dialog.open() == ContainerSelectionDialog.OK) { Object[] result = dialog.getResult(); if (result.length == 1) { containerText.setText(((Path) result[0]).toString()); } } } private void dialogChanged() { IResource container = ResourcesPlugin.getWorkspace().getRoot() .findMember(new Path(getContainerName())); String fileName = getFileName(); if (getContainerName().length() == 0) { updateStatus("File container must be specified"); return; } if (container == null || (container.getType() & (IResource.PROJECT | IResource.FOLDER)) == 0) { updateStatus("File container must exist"); return; } if (!container.isAccessible()) { updateStatus("Project must be writable"); return; } if (fileName.length() == 0) { updateStatus("File name must be specified"); return; } if (fileName.replace('\\', '/').indexOf('/', 1) > 0) { updateStatus("File name must be valid"); return; } int dotLoc = fileName.lastIndexOf('.'); if (dotLoc != -1) { String ext = fileName.substring(dotLoc + 1); if (!ext.equalsIgnoreCase(getFileExtension())) { updateStatus("File extension must be \""+getFileExtension()+"\""); return; } } fillModel(); updateStatus(null); } protected String getFileExtension() { return DEFAULT_FILE_EXTENSTION; } protected abstract void fillModel(); private void updateStatus(String message) { setErrorMessage(message); setPageComplete(message == null); } protected void initialize() { if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) { IStructuredSelection ssel = (IStructuredSelection) selection; if (ssel.size() > 1) return; Object obj = ssel.getFirstElement(); if (obj instanceof IResource) { IContainer container; if (obj instanceof IContainer) container = (IContainer) obj; else container = ((IResource) obj).getParent(); packageText.setText(container.getProject().getName()); containerText.setText(container.getFullPath().toString()); }else if (obj instanceof JavaElement) { JavaElement fragment = (JavaElement) obj; packageText.setText(fragment.getJavaProject().getElementName()); containerText.setText(fragment.getPath().toFile().getPath()); } } fileText.setText("chart.javafxlang"); } public String getContainerName() { return containerText.getText(); } public String getFileName() { return fileText.getText(); } }
3e0cefa597864dec5e27e7cad51e3aa825b5cfe9
10,391
java
Java
src/main/java/com/android/tools/build/bundletool/model/ManifestEditor.java
syslogic/bundletool
de1765e1cd4a2155f2b478909512412b04e5cfc9
[ "Apache-2.0" ]
null
null
null
src/main/java/com/android/tools/build/bundletool/model/ManifestEditor.java
syslogic/bundletool
de1765e1cd4a2155f2b478909512412b04e5cfc9
[ "Apache-2.0" ]
null
null
null
src/main/java/com/android/tools/build/bundletool/model/ManifestEditor.java
syslogic/bundletool
de1765e1cd4a2155f2b478909512412b04e5cfc9
[ "Apache-2.0" ]
null
null
null
44.788793
112
0.770186
5,497
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.android.tools.build.bundletool.model; import static com.android.tools.build.bundletool.model.AndroidManifest.ACTIVITY_ELEMENT_NAME; import static com.android.tools.build.bundletool.model.AndroidManifest.APPLICATION_ELEMENT_NAME; import static com.android.tools.build.bundletool.model.AndroidManifest.EXTRACT_NATIVE_LIBS_ATTRIBUTE_NAME; import static com.android.tools.build.bundletool.model.AndroidManifest.EXTRACT_NATIVE_LIBS_RESOURCE_ID; import static com.android.tools.build.bundletool.model.AndroidManifest.GL_ES_VERSION_RESOURCE_ID; import static com.android.tools.build.bundletool.model.AndroidManifest.GL_VERSION_ATTRIBUTE_NAME; import static com.android.tools.build.bundletool.model.AndroidManifest.HAS_CODE_RESOURCE_ID; import static com.android.tools.build.bundletool.model.AndroidManifest.IS_FEATURE_SPLIT_RESOURCE_ID; import static com.android.tools.build.bundletool.model.AndroidManifest.MAX_SDK_VERSION_ATTRIBUTE_NAME; import static com.android.tools.build.bundletool.model.AndroidManifest.MAX_SDK_VERSION_RESOURCE_ID; import static com.android.tools.build.bundletool.model.AndroidManifest.META_DATA_ELEMENT_NAME; import static com.android.tools.build.bundletool.model.AndroidManifest.META_DATA_KEY_FUSED_MODULE_NAMES; import static com.android.tools.build.bundletool.model.AndroidManifest.MIN_SDK_VERSION_ATTRIBUTE_NAME; import static com.android.tools.build.bundletool.model.AndroidManifest.MIN_SDK_VERSION_RESOURCE_ID; import static com.android.tools.build.bundletool.model.AndroidManifest.NAME_RESOURCE_ID; import static com.android.tools.build.bundletool.model.AndroidManifest.PROVIDER_ELEMENT_NAME; import static com.android.tools.build.bundletool.model.AndroidManifest.SERVICE_ELEMENT_NAME; import static com.android.tools.build.bundletool.model.AndroidManifest.SPLIT_NAME_RESOURCE_ID; import static com.android.tools.build.bundletool.model.AndroidManifest.SUPPORTS_GL_TEXTURE_ELEMENT_NAME; import static com.android.tools.build.bundletool.model.AndroidManifest.TARGET_SANDBOX_VERSION_RESOURCE_ID; import static com.android.tools.build.bundletool.model.AndroidManifest.USES_FEATURE_ELEMENT_NAME; import static com.android.tools.build.bundletool.model.AndroidManifest.USES_SDK_ELEMENT_NAME; import static com.android.tools.build.bundletool.model.AndroidManifest.VALUE_RESOURCE_ID; import static com.android.tools.build.bundletool.model.AndroidManifest.VERSION_CODE_RESOURCE_ID; import static com.android.tools.build.bundletool.utils.xmlproto.XmlProtoAttributeBuilder.createAndroidAttribute; import static com.android.tools.build.bundletool.utils.xmlproto.XmlProtoElement.ANDROID_NAMESPACE_URI; import static com.android.tools.build.bundletool.utils.xmlproto.XmlProtoElement.NO_NAMESPACE_URI; import static java.util.stream.Collectors.joining; import com.android.tools.build.bundletool.utils.xmlproto.XmlProtoElementBuilder; import com.android.tools.build.bundletool.utils.xmlproto.XmlProtoNode; import com.android.tools.build.bundletool.utils.xmlproto.XmlProtoNodeBuilder; import com.google.common.collect.ImmutableList; import javax.annotation.CheckReturnValue; /** Modifies the manifest in the protocol buffer format. */ public class ManifestEditor { private static final int OPEN_GL_VERSION_MULTIPLIER = 0x10000; private static final ImmutableList<String> SPLIT_NAME_ELEMENT_NAMES = ImmutableList.of(ACTIVITY_ELEMENT_NAME, SERVICE_ELEMENT_NAME, PROVIDER_ELEMENT_NAME); private final XmlProtoNodeBuilder rootNode; private final XmlProtoElementBuilder manifestElement; public ManifestEditor(XmlProtoNode rootNode) { this.rootNode = rootNode.toBuilder(); this.manifestElement = this.rootNode.getElement(); } public XmlProtoElementBuilder getRawProto() { return manifestElement; } /** Sets the minSdkVersion attribute. */ public ManifestEditor setMinSdkVersion(int minSdkVersion) { return setUsesSdkAttribute( MIN_SDK_VERSION_ATTRIBUTE_NAME, MIN_SDK_VERSION_RESOURCE_ID, minSdkVersion); } /** Sets the maxSdkVersion attribute. */ public ManifestEditor setMaxSdkVersion(int maxSdkVersion) { return setUsesSdkAttribute( MAX_SDK_VERSION_ATTRIBUTE_NAME, MAX_SDK_VERSION_RESOURCE_ID, maxSdkVersion); } /** Sets split id and related manifest entries for feature/master split. */ public ManifestEditor setSplitIdForFeatureSplit(String splitId) { if (isBaseSplit(splitId)) { manifestElement.removeAttribute(NO_NAMESPACE_URI, "split"); manifestElement.removeAttribute(ANDROID_NAMESPACE_URI, "isFeatureSplit"); } else { manifestElement.getOrCreateAttribute("split").setValueAsString(splitId); manifestElement .getOrCreateAndroidAttribute("isFeatureSplit", IS_FEATURE_SPLIT_RESOURCE_ID) .setValueAsBoolean(true); } manifestElement.removeAttribute(NO_NAMESPACE_URI, "configForSplit"); return this; } public ManifestEditor setHasCode(boolean value) { // Stamp hasCode="false" on the Application element in the Manifest. // This attribute's default is "true" even if absent. manifestElement .getOrCreateChildElement(APPLICATION_ELEMENT_NAME) .getOrCreateAndroidAttribute("hasCode", HAS_CODE_RESOURCE_ID) .setValueAsBoolean(value); return this; } public ManifestEditor setPackage(String packageName) { manifestElement.getOrCreateAttribute("package").setValueAsString(packageName); return this; } public ManifestEditor setVersionCode(int versionCode) { manifestElement .getOrCreateAndroidAttribute("versionCode", VERSION_CODE_RESOURCE_ID) .setValueAsDecimalInteger(versionCode); return this; } public ManifestEditor setConfigForSplit(String featureSplitId) { manifestElement.getOrCreateAttribute("configForSplit").setValueAsString(featureSplitId); return this; } public ManifestEditor setSplitId(String splitId) { manifestElement.getOrCreateAttribute("split").setValueAsString(splitId); return this; } public ManifestEditor setTargetSandboxVersion(int version) { manifestElement .getOrCreateAndroidAttribute("targetSandboxVersion", TARGET_SANDBOX_VERSION_RESOURCE_ID) .setValueAsDecimalInteger(version); return this; } public ManifestEditor addMetaDataString(String key, String value) { manifestElement .getOrCreateChildElement(APPLICATION_ELEMENT_NAME) .addChildElement( XmlProtoElementBuilder.create("meta-data") .addAttribute( createAndroidAttribute("name", NAME_RESOURCE_ID).setValueAsString(key)) .addAttribute( createAndroidAttribute("value", VALUE_RESOURCE_ID).setValueAsString(value))); return this; } public ManifestEditor addMetaDataInteger(String key, int value) { manifestElement .getOrCreateChildElement(APPLICATION_ELEMENT_NAME) .addChildElement( XmlProtoElementBuilder.create("meta-data") .addAttribute( createAndroidAttribute("name", NAME_RESOURCE_ID).setValueAsString(key)) .addAttribute( createAndroidAttribute("value", VALUE_RESOURCE_ID) .setValueAsDecimalInteger(value))); return this; } /** * Sets the 'android:extractNativeLibs' value in the {@code application} tag. * * <p>Note: the {@code application} tag is created if not found. */ public ManifestEditor setExtractNativeLibsValue(boolean value) { manifestElement .getOrCreateChildElement(APPLICATION_ELEMENT_NAME) .getOrCreateAndroidAttribute( EXTRACT_NATIVE_LIBS_ATTRIBUTE_NAME, EXTRACT_NATIVE_LIBS_RESOURCE_ID) .setValueAsBoolean(value); return this; } /** * Sets names of the fused modules as a {@code <meta-data android:name="..." * android:value="module1,module2,..."/>} element inside the {@code <application>} element. */ public ManifestEditor setFusedModuleNames(ImmutableList<String> moduleNames) { // Make sure the names are unique and sort for deterministic behavior. String moduleNamesString = moduleNames.stream().sorted().distinct().collect(joining(",")); manifestElement .getOrCreateChildElement(APPLICATION_ELEMENT_NAME) .addChildElement( XmlProtoElementBuilder.create(META_DATA_ELEMENT_NAME) .addAttribute( createAndroidAttribute("name", NAME_RESOURCE_ID) .setValueAsString(META_DATA_KEY_FUSED_MODULE_NAMES)) .addAttribute( createAndroidAttribute("value", VALUE_RESOURCE_ID) .setValueAsString(moduleNamesString))); return this; } /** * Removes the {@code splitName} attribute from activities, services and providers. * * <p>This is useful for converting between install and instant splits. */ public ManifestEditor removeSplitName() { manifestElement .getOrCreateChildElement(APPLICATION_ELEMENT_NAME) .getChildrenElements(el -> SPLIT_NAME_ELEMENT_NAMES.contains(el.getName())) .forEach(element -> element.removeAndroidAttribute(SPLIT_NAME_RESOURCE_ID)); return this; } /** Generates the modified manifest. */ @CheckReturnValue public AndroidManifest save() { return AndroidManifest.create(rootNode.build()); } private ManifestEditor setUsesSdkAttribute(String attributeName, int attributeResId, int value) { manifestElement .getOrCreateChildElement(USES_SDK_ELEMENT_NAME) .getOrCreateAndroidAttribute(attributeName, attributeResId) .setValueAsDecimalInteger(value); return this; } private static boolean isBaseSplit(String splitId) { return splitId.isEmpty(); } }
3e0cf192563e279a335f476f78ed3610e0f01109
917
java
Java
src/chapter23/SieveOfEratosthenes.java
a-flying-pig/Introduction-to-Java-Programming
6ba6df7b5f3086a64ae6262bfa1a44488e25ad61
[ "Apache-2.0" ]
null
null
null
src/chapter23/SieveOfEratosthenes.java
a-flying-pig/Introduction-to-Java-Programming
6ba6df7b5f3086a64ae6262bfa1a44488e25ad61
[ "Apache-2.0" ]
null
null
null
src/chapter23/SieveOfEratosthenes.java
a-flying-pig/Introduction-to-Java-Programming
6ba6df7b5f3086a64ae6262bfa1a44488e25ad61
[ "Apache-2.0" ]
null
null
null
21.325581
62
0.534351
5,498
package chapter23; import java.util.Scanner; public class SieveOfEratosthenes { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Find all prime numbers <= n, enter n: "); int n = input.nextInt(); input.close(); boolean[] primes = new boolean[n + 1]; // Prime number sieve // Initialize primes[i] to true for (int i = 0; i < primes.length; i++) { primes[i] = true; } for (int k = 2; k <= n / k; k++) { if (primes[k]) { for (int i = k; i <= n / k; i++) { primes[k * i] = false; // k * i is not prime } } } int count = 0; for (int i = 2; i < primes.length; i++) { if (primes[i]) { count++; if (count % 10 == 0) { System.out.printf("%7d\n", i); } else { System.out.printf("%7d", i); } } } System.out.println("\n" + count + " prime(s) less than or equal to " + n); } }
3e0cf24fd6d400fe407a03e41ddb2c7aa72f0ff8
469
java
Java
shopping-store-back/src/main/java/com/gtt/shoppingstoreback/dao/OrderDetailMapper.java
taotaomima/Shopping0224
18aefa06a32c2e8b6703dff06e281c0b20971f44
[ "Apache-2.0" ]
null
null
null
shopping-store-back/src/main/java/com/gtt/shoppingstoreback/dao/OrderDetailMapper.java
taotaomima/Shopping0224
18aefa06a32c2e8b6703dff06e281c0b20971f44
[ "Apache-2.0" ]
null
null
null
shopping-store-back/src/main/java/com/gtt/shoppingstoreback/dao/OrderDetailMapper.java
taotaomima/Shopping0224
18aefa06a32c2e8b6703dff06e281c0b20971f44
[ "Apache-2.0" ]
null
null
null
24.684211
56
0.793177
5,499
package com.gtt.shoppingstoreback.dao; import com.gtt.shoppingstoreback.po.OrderDetail; public interface OrderDetailMapper { int deleteByPrimaryKey(Long orderId); int insert(OrderDetail record); int insertSelective(OrderDetail record); OrderDetail selectByPrimaryKey(Long orderId); int updateByPrimaryKeySelective(OrderDetail record); int updateByPrimaryKeyWithBLOBs(OrderDetail record); int updateByPrimaryKey(OrderDetail record); }
3e0cf3375725e13896b140468f7c802c455e06dc
1,934
java
Java
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201405/ApiException.java
david-gorisse/googleads-java-lib
03b8c7e83bc5a361e374d345afdd93290d143c34
[ "Apache-2.0" ]
null
null
null
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201405/ApiException.java
david-gorisse/googleads-java-lib
03b8c7e83bc5a361e374d345afdd93290d143c34
[ "Apache-2.0" ]
null
null
null
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201405/ApiException.java
david-gorisse/googleads-java-lib
03b8c7e83bc5a361e374d345afdd93290d143c34
[ "Apache-2.0" ]
null
null
null
26.135135
141
0.628749
5,500
package com.google.api.ads.dfp.jaxws.v201405; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * Exception class for holding a list of service errors. * * * <p>Java class for ApiException complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ApiException"> * &lt;complexContent> * &lt;extension base="{https://www.google.com/apis/ads/publisher/v201405}ApplicationException"> * &lt;sequence> * &lt;element name="errors" type="{https://www.google.com/apis/ads/publisher/v201405}ApiError" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ApiException", propOrder = { "errors" }) public class ApiException extends ApplicationException { protected List<ApiError> errors; /** * Gets the value of the errors property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the errors property. * * <p> * For example, to add a new item, do as follows: * <pre> * getErrors().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ApiError } * * */ public List<ApiError> getErrors() { if (errors == null) { errors = new ArrayList<ApiError>(); } return this.errors; } }
3e0cf33dd88de1de49411715444e1e16aed41970
10,542
java
Java
components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/throttling/ThrottleDataHolder.java
miyurud/carbon-apimgt
0990a1eac7c7ca648d763f79330d39eea0417d40
[ "Apache-2.0" ]
2
2019-09-19T11:30:08.000Z
2019-10-27T07:38:16.000Z
components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/throttling/ThrottleDataHolder.java
miyurud/carbon-apimgt
0990a1eac7c7ca648d763f79330d39eea0417d40
[ "Apache-2.0" ]
null
null
null
components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/throttling/ThrottleDataHolder.java
miyurud/carbon-apimgt
0990a1eac7c7ca648d763f79330d39eea0417d40
[ "Apache-2.0" ]
null
null
null
35.735593
113
0.6679
5,501
/* * Copyright (c) 2016, 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.carbon.apimgt.gateway.throttling; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.impl.dto.ConditionDto; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * This class will hold throttle data per given node. All throttle handler objects should refer values from this. * When throttle data holder initialize it should read complete throttle decision table from global policy engine * via web service calls. In addition to that it should subscribe to topic and listen throttle updates. */ public class ThrottleDataHolder { private static final Log log = LogFactory.getLog(ThrottleDataHolder.class); private Map<String, String> blockedAPIConditionsMap = new ConcurrentHashMap<String, String>(); private Map<String, String> blockedApplicationConditionsMap = new ConcurrentHashMap<String, String>(); private Map<String, String> blockedUserConditionsMap = new ConcurrentHashMap<String, String>(); private Map<String, String> blockedIpConditionsMap = new ConcurrentHashMap<String, String>(); private Map<String, String> keyTemplateMap = new ConcurrentHashMap<String, String>(); private boolean isBlockingConditionsPresent = false; private boolean isKeyTemplatesPresent = false; private Map<String, Long> throttleDataMap = new ConcurrentHashMap<String, Long>(); private Map<String,Long> throttledAPIKeysMap = new ConcurrentHashMap<String, Long>(); private Map<String, Map<String, List<ConditionDto>>> conditionDtoMap = new ConcurrentHashMap<>(); public void addThrottleData(String key, Long value) { throttleDataMap.put(key, value); } public void addThrottleDataFromMap(Map<String, Long> data) { throttleDataMap.putAll(data); } public void addThrottledAPIKey(String key, Long value){ throttledAPIKeysMap.put(key,value); } public void addThrottledApiConditions(String key, String conditionKey, List<ConditionDto> conditionValue) { Map<String, List<ConditionDto>> conditionMap; if (conditionDtoMap.containsKey(key)) { conditionMap = conditionDtoMap.get(key); } else { conditionMap = new ConcurrentHashMap<>(); conditionDtoMap.put(key, conditionMap); } if (!conditionMap.containsKey(conditionKey)) { conditionMap.put(conditionKey, conditionValue); } } public void removeThrottledApiConditions(String key, String conditionKey) { if (conditionDtoMap.containsKey(key)) { Map<String, List<ConditionDto>> conditionMap = conditionDtoMap.get(key); conditionMap.remove(conditionKey); if (conditionMap.isEmpty()) { conditionDtoMap.remove(key); } } } public void removeThrottledAPIKey(String key){ throttledAPIKeysMap.remove(key); } public boolean isAPIThrottled(String apiKey){ boolean isThrottled = this.throttledAPIKeysMap.containsKey(apiKey); if(isThrottled) { long currentTime = System.currentTimeMillis(); long timestamp = this.throttledAPIKeysMap.get(apiKey); if(timestamp >= currentTime) { return isThrottled; } else { this.throttledAPIKeysMap.remove(apiKey); this.conditionDtoMap.remove(apiKey); return false; } } else { return isThrottled; } } public boolean isConditionsAvailable(String key) { return conditionDtoMap.containsKey(key); } public Map<String,List<ConditionDto>> getConditionDtoMap(String key){ return conditionDtoMap.get(key); } public void removeThrottleData(String key) { throttleDataMap.remove(key); } public void addAPIBlockingCondition(String name, String value) { isBlockingConditionsPresent = true; blockedAPIConditionsMap.put(name, value); } public void addApplicationBlockingCondition(String name, String value) { isBlockingConditionsPresent = true; blockedApplicationConditionsMap.put(name, value); } public void addUserBlockingCondition(String name, String value) { isBlockingConditionsPresent = true; blockedUserConditionsMap.put(name, value); } public void addIplockingCondition(String name, String value) { isBlockingConditionsPresent = true; blockedIpConditionsMap.put(name, value); } public void addUserBlockingConditionsFromMap(Map<String, String> data) { if(data.size() > 0) { blockedUserConditionsMap.putAll(data); isBlockingConditionsPresent = true; } } public void addIplockingConditionsFromMap(Map<String, String> data) { if(data.size() > 0) { blockedIpConditionsMap.putAll(data); isBlockingConditionsPresent = true; } } public void addAPIBlockingConditionsFromMap(Map<String, String> data) { if(data.size() > 0) { blockedAPIConditionsMap.putAll(data); isBlockingConditionsPresent = true; } } public void addApplicationBlockingConditionsFromMap(Map<String, String> data) { if(data.size() > 0) { blockedApplicationConditionsMap.putAll(data); isBlockingConditionsPresent = true; } } public void removeAPIBlockingCondition(String name) { blockedAPIConditionsMap.remove(name); if(isAnyBlockedMapContainsData()) { isBlockingConditionsPresent = true; } else { isBlockingConditionsPresent = false; } } public void removeApplicationBlockingCondition(String name) { blockedApplicationConditionsMap.remove(name); if(isAnyBlockedMapContainsData()) { isBlockingConditionsPresent = true; } else { isBlockingConditionsPresent = false; } } public void removeUserBlockingCondition(String name) { blockedUserConditionsMap.remove(name); if(isAnyBlockedMapContainsData()) { isBlockingConditionsPresent = true; } else { isBlockingConditionsPresent = false; } } public void removeIpBlockingCondition(String name) { blockedIpConditionsMap.remove(name); if(isAnyBlockedMapContainsData()) { isBlockingConditionsPresent = true; } else { isBlockingConditionsPresent = false; } } public void addKeyTemplate(String key, String value) { keyTemplateMap.put(key, value); isKeyTemplatesPresent = true; } public void addKeyTemplateFromMap(Map<String, String> data) { if(data.size() > 0) { keyTemplateMap.putAll(data); isKeyTemplatesPresent = true; } } public void removeKeyTemplate(String name) { keyTemplateMap.remove(name); if(keyTemplateMap.size() > 0) { isKeyTemplatesPresent = true; } else { isKeyTemplatesPresent = false; } } public Map<String, String> getKeyTemplateMap() { return keyTemplateMap; } public boolean isRequestBlocked(String apiBlockingKey, String applicationBlockingKey, String userBlockingKey, String ipBlockingKey) { return (blockedAPIConditionsMap.containsKey(apiBlockingKey) || blockedApplicationConditionsMap.containsKey(applicationBlockingKey) || blockedUserConditionsMap.containsKey(userBlockingKey) || blockedIpConditionsMap.containsKey(ipBlockingKey)); } /** * This method will check given key in throttle data Map. Throttle data map need to be update from topic * subscriber with all latest updates from global policy engine. This method will perfoem only local map * lookup and return results. * * @param key String unique key of throttle event. * @return Return true if event throttled(means key is available in throttle data map). * false if key is not there in throttle map(that means its not throttled). */ public boolean isThrottled(String key) { boolean isThrottled = this.throttleDataMap.containsKey(key); if(isThrottled) { long currentTime = System.currentTimeMillis(); long timestamp = this.throttleDataMap.get(key); if(timestamp >= currentTime) { return isThrottled; } else { this.throttleDataMap.remove(key); return false; } } else { return isThrottled; } } /** * This method used to get the next access timestamp of a given key * * @param key String unique key of throttle event. * @return throttle next access timestamp */ public long getThrottleNextAccessTimestamp(String key) { return this.throttleDataMap.get(key); } public boolean isBlockingConditionsPresent() { return isBlockingConditionsPresent; } public void setBlockingConditionsPresent(boolean blockingConditionsPresent) { isBlockingConditionsPresent = blockingConditionsPresent; } private boolean isAnyBlockedMapContainsData() { if (blockedAPIConditionsMap.size() > 0 || blockedIpConditionsMap.size() > 0 || blockedApplicationConditionsMap.size() > 0 || blockedUserConditionsMap.size() > 0) { return true; } return false; } public boolean isKeyTemplatesPresent() { return isKeyTemplatesPresent; } public void setKeyTemplatesPresent(boolean keyTemplatesPresent) { isKeyTemplatesPresent = keyTemplatesPresent; } }
3e0cf3800e9bf13e29e1e57f05a52695f13ee2f2
1,120
java
Java
core-examples/src/main/java/io/vertx/example/core/http/proxy/Client.java
niaomingjian/vertx-examples
1029c5fd1bc16cdf1fc25793de4b83de51d2e13b
[ "Apache-2.0" ]
3,643
2015-02-25T16:51:32.000Z
2022-03-31T14:52:32.000Z
core-examples/src/main/java/io/vertx/example/core/http/proxy/Client.java
niaomingjian/vertx-examples
1029c5fd1bc16cdf1fc25793de4b83de51d2e13b
[ "Apache-2.0" ]
373
2015-03-10T19:28:48.000Z
2022-03-30T02:53:40.000Z
core-examples/src/main/java/io/vertx/example/core/http/proxy/Client.java
niaomingjian/vertx-examples
1029c5fd1bc16cdf1fc25793de4b83de51d2e13b
[ "Apache-2.0" ]
2,586
2015-01-26T23:46:18.000Z
2022-03-31T14:52:34.000Z
29.473684
87
0.617857
5,502
package io.vertx.example.core.http.proxy; import io.vertx.core.AbstractVerticle; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpMethod; import io.vertx.example.util.Runner; /* * @author <a href="http://tfox.org">Tim Fox</a> */ public class Client extends AbstractVerticle { // Convenience method so you can run it in your IDE public static void main(String[] args) { Runner.runExample(Client.class); } @Override public void start() throws Exception { HttpClient client = vertx.createHttpClient(); client.request(HttpMethod.GET, 8080, "localhost", "/") .compose(request -> { request.setChunked(true); for (int i = 0; i < 10; i++) { request.write("client-chunk-" + i); } request.end(); return request.response().compose(resp -> { System.out.println("Got response " + resp.statusCode()); return resp.body(); }); } ) .onSuccess(body -> System.out.println("Got data " + body.toString("ISO-8859-1"))) .onFailure(err -> err.printStackTrace()); } }
3e0cf40c0b761397b81ad06d747a399b40fe9826
2,999
java
Java
bobas.businessobjectscommon/src/main/java/org/colorcoding/ibas/bobas/approval/ApprovalProcessManager.java
NiurenZhu/ibas-framework-0.1.1
4c48e437abceacebf11925c96b5b9e87de247f25
[ "MIT" ]
1
2017-05-31T05:07:04.000Z
2017-05-31T05:07:04.000Z
bobas.businessobjectscommon/src/main/java/org/colorcoding/ibas/bobas/approval/ApprovalProcessManager.java
NiurenZhu/ibas-framework-0.1.1
4c48e437abceacebf11925c96b5b9e87de247f25
[ "MIT" ]
null
null
null
bobas.businessobjectscommon/src/main/java/org/colorcoding/ibas/bobas/approval/ApprovalProcessManager.java
NiurenZhu/ibas-framework-0.1.1
4c48e437abceacebf11925c96b5b9e87de247f25
[ "MIT" ]
null
null
null
25.415254
89
0.702234
5,503
package org.colorcoding.ibas.bobas.approval; import java.util.Iterator; import org.colorcoding.ibas.bobas.bo.IBODocument; import org.colorcoding.ibas.bobas.bo.IBODocumentLine; import org.colorcoding.ibas.bobas.bo.IBOTagCanceled; import org.colorcoding.ibas.bobas.bo.IBOTagDeleted; import org.colorcoding.ibas.bobas.core.IBORepository; import org.colorcoding.ibas.bobas.data.emApprovalStatus; import org.colorcoding.ibas.bobas.data.emDocumentStatus; import org.colorcoding.ibas.bobas.data.emYesNo; import org.colorcoding.ibas.bobas.messages.RuntimeLog; /** * 默认流程管理员 * * @author Niuren.Zhu * */ public abstract class ApprovalProcessManager implements IApprovalProcessManager { @Override public IApprovalProcess checkProcess(IApprovalData data, IBORepository repository) { if (data == null) { return null; } if (!data.isNew()) { // 不是新建查看是否存在审批 IApprovalProcess aProcess = this.loadApprovalProcess(data.getIdentifiers()); if (aProcess != null) { aProcess.setApprovalData(data); aProcess.setRepository(repository); return aProcess; } } // 创建审批流程并尝试开始 if (this.checkDataStatus(data)) { Iterator<IApprovalProcess> process = this.createApprovalProcess(data.getObjectCode()); while (process != null && process.hasNext()) { IApprovalProcess aProcess = process.next(); aProcess.setRepository(repository); if (aProcess.start(data)) { RuntimeLog.log(RuntimeLog.MSG_APPROVAL_PROCESS_STARTED, data, aProcess.getName()); return aProcess;// 审批流程开始 } } } // 没有符合的审批流程 if (data.getApprovalStatus() != emApprovalStatus.Unaffected && data.isNew()) { // 重置数据状态 data.setApprovalStatus(emApprovalStatus.Unaffected); } return null; } /** * 检查数据状态,是否进行审批流程 * * @param data * @return */ protected boolean checkDataStatus(IApprovalData data) { if (data.isDeleted()) { return false; } if (data instanceof IBODocument) { // 单据类型 IBODocument docData = (IBODocument) data; if (docData.getDocumentStatus() == emDocumentStatus.Planned) { // 计划状态 return false; } } if (data instanceof IBODocumentLine) { // 单据行 IBODocumentLine lineData = (IBODocumentLine) data; if (lineData.getLineStatus() == emDocumentStatus.Planned) { // 计划状态 return false; } } if (data instanceof IBOTagDeleted) { // 引用数据,已标记删除的,不影响业务逻辑 IBOTagDeleted refData = (IBOTagDeleted) data; if (refData.getDeleted() == emYesNo.Yes) { return false; } } if (data instanceof IBOTagCanceled) { // 引用数据,已标记取消的,不影响业务逻辑 IBOTagCanceled refData = (IBOTagCanceled) data; if (refData.getCanceled() == emYesNo.Yes) { return false; } } return true; } /** * 创建审批流程 * * @param boCode * 业务对象编码 * @return */ protected abstract Iterator<IApprovalProcess> createApprovalProcess(String boCode); /** * 加载审批流程 * * @param boKey * 业务对象标记 * @return */ protected abstract IApprovalProcess loadApprovalProcess(String boKey); }
3e0cf44b132ec355820be852b4c450441bf735ef
2,914
java
Java
bootique-cayenne41/src/test/java/io/bootique/cayenne/v41/CayenneModule_DataChannelFiltersIT.java
dmitars/bootique-cayenne
ab9eeb3089bc70c7fb15ac0626ecde93dd9072fd
[ "Apache-2.0" ]
2
2017-11-30T19:57:34.000Z
2018-02-16T18:30:36.000Z
bootique-cayenne41/src/test/java/io/bootique/cayenne/v41/CayenneModule_DataChannelFiltersIT.java
dmitars/bootique-cayenne
ab9eeb3089bc70c7fb15ac0626ecde93dd9072fd
[ "Apache-2.0" ]
75
2016-08-07T10:10:31.000Z
2022-01-14T10:44:20.000Z
bootique-cayenne41/src/test/java/io/bootique/cayenne/v41/CayenneModule_DataChannelFiltersIT.java
dmitars/bootique-cayenne
ab9eeb3089bc70c7fb15ac0626ecde93dd9072fd
[ "Apache-2.0" ]
6
2016-10-21T10:58:02.000Z
2020-03-12T07:48:02.000Z
33.113636
117
0.691489
5,504
/* * Licensed to ObjectStyle LLC under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ObjectStyle LLC licenses * this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.bootique.cayenne.v41; import io.bootique.di.BQModule; import io.bootique.junit5.BQTest; import io.bootique.junit5.BQTestFactory; import io.bootique.junit5.BQTestTool; import org.apache.cayenne.*; import org.apache.cayenne.configuration.server.ServerRuntime; import org.apache.cayenne.graph.GraphDiff; import org.junit.jupiter.api.Test; import java.util.Arrays; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.*; // DataChannelFilter is deprecated in Cayenne @Deprecated @BQTest public class CayenneModule_DataChannelFiltersIT { @BQTestTool final BQTestFactory testFactory = new BQTestFactory(); private ServerRuntime runtimeWithFilters(DataChannelFilter... filters) { BQModule filtersModule = (binder) -> { CayenneModuleExtender extender = CayenneModule.extend(binder); Arrays.asList(filters).forEach(extender::addFilter); }; return testFactory.app("--config=classpath:genericconfig.yml") .autoLoadModules() .module(filtersModule) .createRuntime() .getInstance(ServerRuntime.class); } @Test public void testFilters() { DataChannelFilter f = mock(DataChannelFilter.class); when(f.onSync(any(), any(), anyInt(), (DataChannelSyncFilterChain) any())).thenReturn(mock(GraphDiff.class)); CayenneDataObject o1 = new CayenneDataObject(); o1.setObjectId(new ObjectId("T1")); o1.writeProperty("name", "n" + 1); CayenneDataObject o2 = new CayenneDataObject(); o2.setObjectId(new ObjectId("T1")); o2.writeProperty("name", "n" + 2); ServerRuntime runtime = runtimeWithFilters(f); try { ObjectContext c = runtime.newContext(); c.registerNewObject(o1); c.registerNewObject(o2); c.commitChanges(); } finally { runtime.shutdown(); } verify(f).onSync(any(), any(), anyInt(), (DataChannelSyncFilterChain) any()); } }
3e0cf527f9e9473c8a76fc3d0d2737ad5f39b773
27,825
java
Java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessor.java
DouShiYang/apache-dubbo
52b6801646744b774dae794c8e351ad22604c54d
[ "Apache-2.0" ]
null
null
null
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessor.java
DouShiYang/apache-dubbo
52b6801646744b774dae794c8e351ad22604c54d
[ "Apache-2.0" ]
null
null
null
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessor.java
DouShiYang/apache-dubbo
52b6801646744b774dae794c8e351ad22604c54d
[ "Apache-2.0" ]
null
null
null
43.476563
171
0.70487
5,505
/* * 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.dubbo.config.spring.beans.factory.annotation; import com.alibaba.spring.util.AnnotationUtils; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.Constants; import org.apache.dubbo.config.MethodConfig; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.config.annotation.Method; import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.config.spring.ServiceBean; import org.apache.dubbo.config.spring.context.annotation.DubboClassPathBeanDefinitionScanner; import org.apache.dubbo.config.spring.schema.AnnotationBeanDefinitionParser; import org.apache.dubbo.config.spring.util.DubboAnnotationUtils; import org.apache.dubbo.config.spring.util.SpringCompatUtils; import org.springframework.beans.BeansException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.SingletonBeanRegistry; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; import org.springframework.beans.factory.support.BeanNameGenerator; import org.springframework.beans.factory.xml.BeanDefinitionParser; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.EnvironmentAware; import org.springframework.context.ResourceLoaderAware; import org.springframework.context.annotation.AnnotationBeanNameGenerator; import org.springframework.context.annotation.AnnotationConfigUtils; import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; import org.springframework.context.annotation.ConfigurationClassPostProcessor; import org.springframework.core.env.Environment; import org.springframework.core.io.ResourceLoader; import org.springframework.core.type.MethodMetadata; import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.core.type.filter.TypeFilter; import org.springframework.util.CollectionUtils; import java.io.IOException; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import static com.alibaba.spring.util.ObjectUtils.of; import static java.util.Arrays.asList; import static org.apache.dubbo.common.utils.AnnotationUtils.filterDefaultValues; import static org.apache.dubbo.common.utils.AnnotationUtils.findAnnotation; import static org.apache.dubbo.config.spring.beans.factory.annotation.ServiceBeanNameBuilder.create; import static org.apache.dubbo.config.spring.util.DubboAnnotationUtils.resolveInterfaceName; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; import static org.springframework.context.annotation.AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR; import static org.springframework.util.ClassUtils.resolveClassName; /** *一个 {@link BeanFactoryPostProcessor} 用于处理 {@link Service @Service} 注释类和 java 配置类中的注释 bean。 * 也是<dubbbo:annotation>上XML {@link BeanDefinitionParser}的基础类 * * @see AnnotationBeanDefinitionParser * @see BeanDefinitionRegistryPostProcessor * @since 2.7.7 */ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPostProcessor, EnvironmentAware, ResourceLoaderAware, BeanClassLoaderAware, ApplicationContextAware, InitializingBean { public static final String BEAN_NAME = "dubboServiceAnnotationPostProcessor"; private final static List<Class<? extends Annotation>> serviceAnnotationTypes = asList( // @since 2.7.7 Add the @DubboService , the issue : https://github.com/apache/dubbo/issues/6007 DubboService.class, // @since 2.7.0 the substitute @com.alibaba.dubbo.config.annotation.Service Service.class, // @since 2.7.3 Add the compatibility for legacy Dubbo's @Service , the issue : https://github.com/apache/dubbo/issues/4330 com.alibaba.dubbo.config.annotation.Service.class ); private final Logger logger = LoggerFactory.getLogger(getClass()); protected final Set<String> packagesToScan; private Set<String> resolvedPackagesToScan; private Environment environment; private ResourceLoader resourceLoader; private ClassLoader classLoader; private BeanDefinitionRegistry registry; private ServicePackagesHolder servicePackagesHolder; private volatile boolean scaned = false; public ServiceAnnotationPostProcessor(String... packagesToScan) { this(asList(packagesToScan)); } public ServiceAnnotationPostProcessor(Collection<String> packagesToScan) { this(new LinkedHashSet<>(packagesToScan)); } public ServiceAnnotationPostProcessor(Set<String> packagesToScan) { this.packagesToScan = packagesToScan; } @Override public void afterPropertiesSet() throws Exception { this.resolvedPackagesToScan = resolvePackagesToScan(packagesToScan); } @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { this.registry = registry; scanServiceBeans(resolvedPackagesToScan, registry); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { if (this.registry == null) { // 在 spring 3.x 中,可能不会调用 postProcessBeanDefinitionRegistry() this.registry = (BeanDefinitionRegistry) beanFactory; } // 扫描bean String[] beanNames = beanFactory.getBeanDefinitionNames(); for (String beanName : beanNames) { BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); //获取注解中的属性值 Map<String, Object> annotationAttributes = getServiceAnnotationAttributes(beanDefinition); if (annotationAttributes != null) { // 在 java-config @bean 方法中处理 @DubboService // processAnnotatedBeanDefinition(beanName, (AnnotatedBeanDefinition) beanDefinition, annotationAttributes); } } if (!scaned) { // 在spring 3.x中,可能不会调用postProcessBeanDefinitionRegistry(),所以这里扫描服务类 scanServiceBeans(resolvedPackagesToScan, registry); } } /** * 扫描并注册类被注解的服务 bean {@link Service} * * @param packagesToScan The base packages to scan * @param registry {@link BeanDefinitionRegistry} */ private void scanServiceBeans(Set<String> packagesToScan, BeanDefinitionRegistry registry) { scaned = true; if (CollectionUtils.isEmpty(packagesToScan)) { if (logger.isWarnEnabled()) { logger.warn("packagesToScan is empty , ServiceBean registry will be ignored!"); } return; } DubboClassPathBeanDefinitionScanner scanner = new DubboClassPathBeanDefinitionScanner(registry, environment, resourceLoader); BeanNameGenerator beanNameGenerator = resolveBeanNameGenerator(registry); scanner.setBeanNameGenerator(beanNameGenerator); for (Class<? extends Annotation> annotationType : serviceAnnotationTypes) { scanner.addIncludeFilter(new AnnotationTypeFilter(annotationType)); } ScanExcludeFilter scanExcludeFilter = new ScanExcludeFilter(); scanner.addExcludeFilter(scanExcludeFilter); for (String packageToScan : packagesToScan) { // avoid duplicated scans if (servicePackagesHolder.isPackageScanned(packageToScan)) { if (logger.isInfoEnabled()) { logger.info("Ignore package who has already bean scanned: " + packageToScan); } continue; } // Registers @Service Bean first scanner.scan(packageToScan); // Finds all BeanDefinitionHolders of @Service whether @ComponentScan scans or not. Set<BeanDefinitionHolder> beanDefinitionHolders = findServiceBeanDefinitionHolders(scanner, packageToScan, registry, beanNameGenerator); if (!CollectionUtils.isEmpty(beanDefinitionHolders)) { if (logger.isInfoEnabled()) { List<String> serviceClasses = new ArrayList<>(beanDefinitionHolders.size()); for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitionHolders) { serviceClasses.add(beanDefinitionHolder.getBeanDefinition().getBeanClassName()); } logger.info("Found " + beanDefinitionHolders.size() + " classes annotated by Dubbo @Service under package [" + packageToScan + "]: " + serviceClasses); } for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitionHolders) { processScannedBeanDefinition(beanDefinitionHolder, registry, scanner); servicePackagesHolder.addScannedClass(beanDefinitionHolder.getBeanDefinition().getBeanClassName()); } } else { if (logger.isWarnEnabled()) { logger.warn("No class annotated by Dubbo @Service was found under package [" + packageToScan + "], ignore re-scanned classes: " + scanExcludeFilter.getExcludedCount()); } } servicePackagesHolder.addScannedPackage(packageToScan); } } /** * It'd better to use BeanNameGenerator instance that should reference * {@link ConfigurationClassPostProcessor#componentScanBeanNameGenerator}, * thus it maybe a potential problem on bean name generation. * * @param registry {@link BeanDefinitionRegistry} * @return {@link BeanNameGenerator} instance * @see SingletonBeanRegistry * @see AnnotationConfigUtils#CONFIGURATION_BEAN_NAME_GENERATOR * @see ConfigurationClassPostProcessor#processConfigBeanDefinitions * @since 2.5.8 */ private BeanNameGenerator resolveBeanNameGenerator(BeanDefinitionRegistry registry) { BeanNameGenerator beanNameGenerator = null; if (registry instanceof SingletonBeanRegistry) { SingletonBeanRegistry singletonBeanRegistry = SingletonBeanRegistry.class.cast(registry); beanNameGenerator = (BeanNameGenerator) singletonBeanRegistry.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR); } if (beanNameGenerator == null) { if (logger.isInfoEnabled()) { logger.info("BeanNameGenerator bean can't be found in BeanFactory with name [" + CONFIGURATION_BEAN_NAME_GENERATOR + "]"); logger.info("BeanNameGenerator will be a instance of " + AnnotationBeanNameGenerator.class.getName() + " , it maybe a potential problem on bean name generation."); } beanNameGenerator = new AnnotationBeanNameGenerator(); } return beanNameGenerator; } /** * Finds a {@link Set} of {@link BeanDefinitionHolder BeanDefinitionHolders} whose bean type annotated * {@link Service} Annotation. * * @param scanner {@link ClassPathBeanDefinitionScanner} * @param packageToScan pachage to scan * @param registry {@link BeanDefinitionRegistry} * @return non-null * @since 2.5.8 */ private Set<BeanDefinitionHolder> findServiceBeanDefinitionHolders( ClassPathBeanDefinitionScanner scanner, String packageToScan, BeanDefinitionRegistry registry, BeanNameGenerator beanNameGenerator) { Set<BeanDefinition> beanDefinitions = scanner.findCandidateComponents(packageToScan); Set<BeanDefinitionHolder> beanDefinitionHolders = new LinkedHashSet<>(beanDefinitions.size()); for (BeanDefinition beanDefinition : beanDefinitions) { String beanName = beanNameGenerator.generateBeanName(beanDefinition, registry); BeanDefinitionHolder beanDefinitionHolder = new BeanDefinitionHolder(beanDefinition, beanName); beanDefinitionHolders.add(beanDefinitionHolder); } return beanDefinitionHolders; } /** * Registers {@link ServiceBean} from new annotated {@link Service} {@link BeanDefinition} * * @param beanDefinitionHolder * @param registry * @param scanner * @see ServiceBean * @see BeanDefinition */ private void processScannedBeanDefinition(BeanDefinitionHolder beanDefinitionHolder, BeanDefinitionRegistry registry, DubboClassPathBeanDefinitionScanner scanner) { Class<?> beanClass = resolveClass(beanDefinitionHolder); Annotation service = findServiceAnnotation(beanClass); // The attributes of @Service annotation Map<String, Object> serviceAnnotationAttributes = AnnotationUtils.getAttributes(service, true); String serviceInterface = resolveInterfaceName(serviceAnnotationAttributes, beanClass); String annotatedServiceBeanName = beanDefinitionHolder.getBeanName(); // ServiceBean Bean name String beanName = generateServiceBeanName(serviceAnnotationAttributes, serviceInterface); AbstractBeanDefinition serviceBeanDefinition = buildServiceBeanDefinition(serviceAnnotationAttributes, serviceInterface, annotatedServiceBeanName); registerServiceBeanDefinition(beanName, serviceBeanDefinition, serviceInterface); } /** * Find the {@link Annotation annotation} of @Service * * @param beanClass the {@link Class class} of Bean * @return <code>null</code> if not found * @since 2.7.3 */ private Annotation findServiceAnnotation(Class<?> beanClass) { return serviceAnnotationTypes .stream() .map(annotationType -> findAnnotation(beanClass, annotationType)) .filter(Objects::nonNull) .findFirst() .orElse(null); } /** * Generates the bean name of {@link ServiceBean} * * @param serviceAnnotationAttributes * @param serviceInterface the class of interface annotated {@link Service} * @return ServiceBean@interfaceClassName#annotatedServiceBeanName * @since 2.7.3 */ private String generateServiceBeanName(Map<String, Object> serviceAnnotationAttributes, String serviceInterface) { ServiceBeanNameBuilder builder = create(serviceInterface, environment) .group((String) serviceAnnotationAttributes.get("group")) .version((String) serviceAnnotationAttributes.get("version")); return builder.build(); } private Class<?> resolveClass(BeanDefinitionHolder beanDefinitionHolder) { BeanDefinition beanDefinition = beanDefinitionHolder.getBeanDefinition(); return resolveClass(beanDefinition); } private Class<?> resolveClass(BeanDefinition beanDefinition) { String beanClassName = beanDefinition.getBeanClassName(); return resolveClassName(beanClassName, classLoader); } private Set<String> resolvePackagesToScan(Set<String> packagesToScan) { Set<String> resolvedPackagesToScan = new LinkedHashSet<String>(packagesToScan.size()); for (String packageToScan : packagesToScan) { if (StringUtils.hasText(packageToScan)) { String resolvedPackageToScan = environment.resolvePlaceholders(packageToScan.trim()); resolvedPackagesToScan.add(resolvedPackageToScan); } } return resolvedPackagesToScan; } /** * Build the {@link AbstractBeanDefinition Bean Definition} * * * @param serviceAnnotationAttributes * @param serviceInterface * @param refServiceBeanName * @return * @since 2.7.3 */ private AbstractBeanDefinition buildServiceBeanDefinition(Map<String, Object> serviceAnnotationAttributes, String serviceInterface, String refServiceBeanName) { BeanDefinitionBuilder builder = rootBeanDefinition(ServiceBean.class); AbstractBeanDefinition beanDefinition = builder.getBeanDefinition(); MutablePropertyValues propertyValues = beanDefinition.getPropertyValues(); String[] ignoreAttributeNames = of("provider", "monitor", "application", "module", "registry", "protocol", "interface", "interfaceName", "parameters"); propertyValues.addPropertyValues(new AnnotationPropertyValuesAdapter(serviceAnnotationAttributes, environment, ignoreAttributeNames)); //set config id, for ConfigManager cache key //builder.addPropertyValue("id", beanName); // References "ref" property to annotated-@Service Bean addPropertyReference(builder, "ref", refServiceBeanName); // Set interface builder.addPropertyValue("interface", serviceInterface); // Convert parameters into map builder.addPropertyValue("parameters", DubboAnnotationUtils.convertParameters((String[]) serviceAnnotationAttributes.get("parameters"))); // Add methods parameters List<MethodConfig> methodConfigs = convertMethodConfigs(serviceAnnotationAttributes.get("methods")); if (!methodConfigs.isEmpty()) { builder.addPropertyValue("methods", methodConfigs); } // convert provider to providerIds String providerConfigId = (String) serviceAnnotationAttributes.get("provider"); if (StringUtils.hasText(providerConfigId)) { addPropertyValue(builder, "providerIds", providerConfigId); } // Convert registry[] to registryIds String[] registryConfigIds = (String[]) serviceAnnotationAttributes.get("registry"); if (registryConfigIds != null && registryConfigIds.length > 0) { resolveStringArray(registryConfigIds); builder.addPropertyValue("registryIds", StringUtils.join(registryConfigIds, ',')); } // Convert protocol[] to protocolIds String[] protocolConfigIds = (String[]) serviceAnnotationAttributes.get("protocol"); if (protocolConfigIds != null && protocolConfigIds.length > 0) { resolveStringArray(protocolConfigIds); builder.addPropertyValue("protocolIds", StringUtils.join(protocolConfigIds, ',')); } // TODO Could we ignore these attributes: applicatin/monitor/module ? Use global config // monitor reference String monitorConfigId = (String) serviceAnnotationAttributes.get("monitor"); if (StringUtils.hasText(monitorConfigId)) { addPropertyReference(builder, "monitor", monitorConfigId); } // application reference String applicationConfigId = (String) serviceAnnotationAttributes.get("application"); if (StringUtils.hasText(applicationConfigId)) { addPropertyReference(builder, "application", applicationConfigId); } // module reference String moduleConfigId = (String) serviceAnnotationAttributes.get("module"); if (StringUtils.hasText(moduleConfigId)) { addPropertyReference(builder, "module", moduleConfigId); } return builder.getBeanDefinition(); } private String[] resolveStringArray(String[] strs) { if (strs == null) { return null; } for (int i = 0; i < strs.length; i++) { strs[i] = environment.resolvePlaceholders(strs[i]); } return strs; } private List convertMethodConfigs(Object methodsAnnotation) { if (methodsAnnotation == null) { return Collections.EMPTY_LIST; } return MethodConfig.constructMethodConfig((Method[]) methodsAnnotation); } private void addPropertyReference(BeanDefinitionBuilder builder, String propertyName, String beanName) { String resolvedBeanName = environment.resolvePlaceholders(beanName); builder.addPropertyReference(propertyName, resolvedBeanName); } private void addPropertyValue(BeanDefinitionBuilder builder, String propertyName, String value) { String resolvedBeanName = environment.resolvePlaceholders(value); builder.addPropertyValue(propertyName, resolvedBeanName); } /** * 在java-config @bean 方法中获取dubbo 服务注解类 * @return 找到则返回服务注解属性映射,未找到则返回null。 */ private Map<String, Object> getServiceAnnotationAttributes(BeanDefinition beanDefinition) { if (beanDefinition instanceof AnnotatedBeanDefinition) { AnnotatedBeanDefinition annotatedBeanDefinition = (AnnotatedBeanDefinition) beanDefinition; MethodMetadata factoryMethodMetadata = SpringCompatUtils.getFactoryMethodMetadata(annotatedBeanDefinition); if (factoryMethodMetadata != null) { // try all dubbo service annotation types for (Class<? extends Annotation> annotationType : serviceAnnotationTypes) { if (factoryMethodMetadata.isAnnotated(annotationType.getName())) { // Since Spring 5.2 // return factoryMethodMetadata.getAnnotations().get(annotationType).filterDefaultValues().asMap(); // Compatible with Spring 4.x Map<String, Object> annotationAttributes = factoryMethodMetadata.getAnnotationAttributes(annotationType.getName()); return filterDefaultValues(annotationType, annotationAttributes); } } } } return null; } /** * 处理 * process @DubboService at java-config @bean method * <pre class="code"> * &#064;Configuration * public class ProviderConfig { * &#064;Bean * &#064;DubboService(group="demo", version="1.2.3") * public DemoService demoService() { * return new DemoServiceImpl(); * } * } * </pre> * @param refServiceBeanName bean名称 * @param refServiceBeanDefinition bean的定义类 * @param attributes 属性值 */ private void processAnnotatedBeanDefinition(String refServiceBeanName, AnnotatedBeanDefinition refServiceBeanDefinition, Map<String, Object> attributes) { Map<String, Object> serviceAnnotationAttributes = new LinkedHashMap<>(attributes); //从返回类型获取 bean 类 String returnTypeName = SpringCompatUtils.getFactoryMethodReturnType(refServiceBeanDefinition); //从classLoader中 获取 返回的类信息 Class<?> beanClass = resolveClassName(returnTypeName, classLoader); String serviceInterface = resolveInterfaceName(serviceAnnotationAttributes, beanClass); // ServiceBean Bean name String serviceBeanName = generateServiceBeanName(serviceAnnotationAttributes, serviceInterface); AbstractBeanDefinition serviceBeanDefinition = buildServiceBeanDefinition(serviceAnnotationAttributes, serviceInterface, refServiceBeanName); // set id serviceBeanDefinition.getPropertyValues().add(Constants.ID, serviceBeanName); registerServiceBeanDefinition(serviceBeanName, serviceBeanDefinition, serviceInterface); } private void registerServiceBeanDefinition(String serviceBeanName, AbstractBeanDefinition serviceBeanDefinition, String serviceInterface) { // check service bean if (registry.containsBeanDefinition(serviceBeanName)) { BeanDefinition existingDefinition = registry.getBeanDefinition(serviceBeanName); if (existingDefinition.equals(serviceBeanDefinition)) { // exist equipment bean definition return; } String msg = "Found duplicated BeanDefinition of service interface [" + serviceInterface + "] with bean name [" + serviceBeanName + "], existing definition [ " + existingDefinition + "], new definition [" + serviceBeanDefinition + "]"; logger.error(msg); throw new BeanDefinitionStoreException(serviceBeanDefinition.getResourceDescription(), serviceBeanName, msg); } registry.registerBeanDefinition(serviceBeanName, serviceBeanDefinition); if (logger.isInfoEnabled()) { logger.info("Register ServiceBean[" + serviceBeanName + "]: " + serviceBeanDefinition); } } @Override public void setEnvironment(Environment environment) { this.environment = environment; } @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } @Override public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.servicePackagesHolder = applicationContext.getBean(ServicePackagesHolder.BEAN_NAME, ServicePackagesHolder.class); } private class ScanExcludeFilter implements TypeFilter { private int excludedCount; @Override public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException { String className = metadataReader.getClassMetadata().getClassName(); boolean excluded = servicePackagesHolder.isClassScanned(className); if (excluded) { excludedCount ++; } return excluded; } public int getExcludedCount() { return excludedCount; } } }
3e0cf5e96c98e1a207870b5128814c4a21b13966
495
java
Java
src/main/java/ru/mse/itmo/lala/language/completion/LaLaCompletionContributor.java
zhvkgj/LaLa-plugin
f88aea395c5c59042aec32a0dc5c2edbb051ab1a
[ "MIT" ]
null
null
null
src/main/java/ru/mse/itmo/lala/language/completion/LaLaCompletionContributor.java
zhvkgj/LaLa-plugin
f88aea395c5c59042aec32a0dc5c2edbb051ab1a
[ "MIT" ]
null
null
null
src/main/java/ru/mse/itmo/lala/language/completion/LaLaCompletionContributor.java
zhvkgj/LaLa-plugin
f88aea395c5c59042aec32a0dc5c2edbb051ab1a
[ "MIT" ]
null
null
null
41.25
115
0.838384
5,506
package ru.mse.itmo.lala.language.completion; import com.intellij.codeInsight.completion.CompletionContributor; import com.intellij.codeInsight.completion.CompletionType; import ru.mse.itmo.lala.language.completion.providers.LaLaKeywordsCompletionProvider; public class LaLaCompletionContributor extends CompletionContributor { public LaLaCompletionContributor() { extend(CompletionType.BASIC, LaLaKeywordsCompletionProvider.PATTERN, new LaLaKeywordsCompletionProvider()); } }
3e0cf7758f3f4cb72f0e6d94eadee19cbea9f85e
44
java
Java
src/main/java/com/infinityraider/ninjagear/api/v0/package-info.java
InfinityRaider/NinjaGear
a892e57c0feb9f742ae48d2dbcb7c726e05c3da2
[ "MIT" ]
7
2016-05-27T15:08:02.000Z
2021-12-11T22:47:55.000Z
src/main/java/com/infinityraider/ninjagear/api/v0/package-info.java
InfinityRaider/NinjaGear
a892e57c0feb9f742ae48d2dbcb7c726e05c3da2
[ "MIT" ]
10
2016-05-29T17:57:17.000Z
2021-06-28T08:50:43.000Z
src/main/java/com/infinityraider/ninjagear/api/v0/package-info.java
InfinityRaider/NinjaGear
a892e57c0feb9f742ae48d2dbcb7c726e05c3da2
[ "MIT" ]
3
2016-05-27T15:08:06.000Z
2018-06-23T23:05:00.000Z
44
44
0.863636
5,507
package com.infinityraider.ninjagear.api.v0;
3e0cf854b5f3694cef577cbb5d3025a395394868
5,194
java
Java
taucoinj-core/src/main/java/io/taucoin/net/swarm/Util.java
Tau-Coin/taucoin-mobile-mining-ipfs
010c70f89dd1799134aae03a4b7f3d65ef8d67c1
[ "MIT" ]
3
2019-12-27T19:03:46.000Z
2020-04-13T16:19:15.000Z
taucoinj-core/src/main/java/io/taucoin/net/swarm/Util.java
iceXCN/taucoin-mobile-mining
197de24588ff28ff80887055aabfb75c6f2b96de
[ "MIT" ]
1
2020-03-05T09:10:02.000Z
2022-02-16T16:23:51.000Z
taucoinj-core/src/main/java/io/taucoin/net/swarm/Util.java
iceXCN/taucoin-mobile-mining
197de24588ff28ff80887055aabfb75c6f2b96de
[ "MIT" ]
5
2019-11-02T14:21:20.000Z
2019-12-27T19:03:48.000Z
31.289157
97
0.556026
5,508
package io.taucoin.net.swarm; import io.taucoin.util.ByteUtil; import io.taucoin.util.RLP; import io.taucoin.util.RLPElement; import io.taucoin.util.Utils; import java.nio.charset.StandardCharsets; import java.util.concurrent.LinkedBlockingQueue; import static java.lang.Math.min; /** * Created by Admin on 17.06.2015. */ public class Util { public static class ChunkConsumer extends LinkedBlockingQueue<Chunk> { ChunkStore destination; boolean synchronous = true; public ChunkConsumer(ChunkStore destination) { this.destination = destination; } @Override public boolean add(Chunk chunk) { if (synchronous) { destination.put(chunk); return true; } else { return super.add(chunk); } } } public static class ArrayReader implements SectionReader { byte[] arr; public ArrayReader(byte[] arr) { this.arr = arr; } @Override public long seek(long offset, int whence) { throw new RuntimeException("Not implemented"); } @Override public int read(byte[] dest, int destOff) { return readAt(dest, destOff, 0); } @Override public int readAt(byte[] dest, int destOff, long readerOffset) { int len = min(dest.length - destOff, arr.length - (int)readerOffset); System.arraycopy(arr, (int) readerOffset, dest, destOff, len); return len; } @Override public long getSize() { return arr.length; } } // for testing purposes when the timer might be changed // to manage current time according to test scenarios public static Timer TIMER = new Timer(); public static class Timer { public long curTime() { return System.currentTimeMillis(); } } public static String getCommonPrefix(String s1, String s2) { int pos = 0; while(pos < s1.length() && pos < s2.length() && s1.charAt(pos) == s2.charAt(pos)) pos++; return s1.substring(0, pos); } public static String ipBytesToString(byte[] ipAddr) { StringBuilder sip = new StringBuilder(); for (int i = 0; i < ipAddr.length; i++) { sip.append(i == 0 ? "" : ".").append(0xFF & ipAddr[i]); } return sip.toString(); } public static <P extends StringTrie.TrieNode<P>> String dumpTree(P n) { return dumpTree(n, 0); } private static <P extends StringTrie.TrieNode<P>> String dumpTree(P n, int indent) { String ret = Utils.repeat(" ", indent) + "[" + n.path + "] " + n + "\n"; for (P c: n.getChildren()) { ret += dumpTree(c, indent + 1); } return ret; } public static byte[] uInt16ToBytes(int uInt16) { return new byte[] {(byte) ((uInt16 >> 8) & 0xFF), (byte) (uInt16 & 0xFF)}; } public static long curTime() { return TIMER.curTime();} public static byte[] rlpEncodeLong(long n) { // TODO for now leaving int cast return RLP.encodeInt((int) n); } public static byte rlpDecodeByte(RLPElement elem) { return (byte) rlpDecodeInt(elem); } public static long rlpDecodeLong(RLPElement elem) { return rlpDecodeInt(elem); } public static int rlpDecodeInt(RLPElement elem) { byte[] b = elem.getRLPData(); if (b == null) return 0; return ByteUtil.byteArrayToInt(b); } public static String rlpDecodeString(RLPElement elem) { byte[] b = elem.getRLPData(); if (b == null) return null; return new String(b); } public static byte[] rlpEncodeList(Object ... elems) { byte[][] encodedElems = new byte[elems.length][]; for (int i =0; i < elems.length; i++) { if (elems[i] instanceof Byte) { encodedElems[i] = RLP.encodeByte((Byte) elems[i]); } else if (elems[i] instanceof Integer) { encodedElems[i] = RLP.encodeInt((Integer) elems[i]); } else if (elems[i] instanceof Long) { encodedElems[i] = rlpEncodeLong((Long) elems[i]); } else if (elems[i] instanceof String) { encodedElems[i] = RLP.encodeString((String) elems[i]); } else if (elems[i] instanceof byte[]) { encodedElems[i] = ((byte[]) elems[i]); } else { throw new RuntimeException("Unsupported object: " + elems[i]); } } return RLP.encodeList(encodedElems); } public static SectionReader stringToReader(String s) { return new ArrayReader(s.getBytes(StandardCharsets.UTF_8)); } public static String readerToString(SectionReader sr) { byte[] bb = new byte[(int) sr.getSize()]; sr.read(bb, 0); String s = new String(bb, StandardCharsets.UTF_8); return s; } }
3e0cf8893dfa957f9988372d5a4a9eba395c315b
256
java
Java
centurion/src/main/java/centurion/util/IDCheckDontTouchPls.java
drgrieve/StS-TheCenturion
e1c0b8bf659c3a015d7082f26dd0191ecc8930db
[ "MIT" ]
null
null
null
centurion/src/main/java/centurion/util/IDCheckDontTouchPls.java
drgrieve/StS-TheCenturion
e1c0b8bf659c3a015d7082f26dd0191ecc8930db
[ "MIT" ]
null
null
null
centurion/src/main/java/centurion/util/IDCheckDontTouchPls.java
drgrieve/StS-TheCenturion
e1c0b8bf659c3a015d7082f26dd0191ecc8930db
[ "MIT" ]
null
null
null
23.272727
44
0.765625
5,509
package centurion.util; public class IDCheckDontTouchPls { public String DEFAULTID; public String DEVID; public String EXCEPTION; public String PACKAGE_EXCEPTION; public String RESOURCE_FOLDER_EXCEPTION; public String RESOURCES; }
3e0cf8972838b71074053ad37f89738b28a926a4
2,674
java
Java
src/main/java/io/spring/concourse/artifactoryresource/command/payload/Source.java
spring-io/artifactory-resource
671548d308bab66db9dbc222be25fcd9a64d372b
[ "Apache-2.0" ]
18
2017-09-12T17:24:03.000Z
2022-01-18T04:30:11.000Z
src/main/java/io/spring/concourse/artifactoryresource/command/payload/Source.java
spring-io/artifactory-resource
671548d308bab66db9dbc222be25fcd9a64d372b
[ "Apache-2.0" ]
92
2017-10-06T00:41:28.000Z
2021-08-10T21:47:22.000Z
src/main/java/io/spring/concourse/artifactoryresource/command/payload/Source.java
spring-io/artifactory-resource
671548d308bab66db9dbc222be25fcd9a64d372b
[ "Apache-2.0" ]
18
2018-02-01T18:39:23.000Z
2021-07-21T06:23:58.000Z
27.56701
114
0.744203
5,510
/* * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 io.spring.concourse.artifactoryresource.command.payload; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.Proxy.Type; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import org.springframework.core.style.ToStringCreator; import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** * The source payload containing shared configuration. * * @author Phillip Webb * @author Madhura Bhave * @author Gabriel Petrovay */ public class Source { private final String uri; private final String username; private final String password; private final String buildName; private final Proxy proxy; @JsonCreator public Source(@JsonProperty("uri") String uri, @JsonProperty("username") String username, @JsonProperty("password") String password, @JsonProperty("build_name") String buildName, @JsonProperty("proxy_host") String proxyHost, @JsonProperty("proxy_port") Integer proxyPort) { Assert.hasText(uri, "URI must not be empty"); Assert.hasText(buildName, "Build Name must not be empty"); this.uri = uri; this.username = username; this.password = password; this.buildName = buildName; this.proxy = (StringUtils.hasText(proxyHost)) ? createProxy(proxyHost, proxyPort) : null; } private Proxy createProxy(String host, Integer port) { Assert.notNull(port, "Proxy port must be provided"); return new Proxy(Type.HTTP, new InetSocketAddress(host, port)); } public String getUri() { return this.uri; } public String getUsername() { return this.username; } public String getPassword() { return this.password; } public String getBuildName() { return this.buildName; } public Proxy getProxy() { return this.proxy; } @Override public String toString() { ToStringCreator creator = new ToStringCreator(this).append("uri", this.uri).append("buildName", this.buildName); if (this.proxy != null) { creator.append("proxy", this.proxy); } return creator.toString(); } }
3e0cf99e2449a3616fe6c91f9e4139c75adc64e1
3,701
java
Java
admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/server/service/artifact/image/effects/chain/filter/BaseFilter.java
nanthakumarm/BroadleafCommerce
3f74d1e9a840e6bce0208fa48d8111cc9663b25f
[ "Apache-2.0" ]
1
2020-04-03T20:49:40.000Z
2020-04-03T20:49:40.000Z
admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/server/service/artifact/image/effects/chain/filter/BaseFilter.java
nanthakumarm/BroadleafCommerce
3f74d1e9a840e6bce0208fa48d8111cc9663b25f
[ "Apache-2.0" ]
11
2020-06-15T21:05:08.000Z
2022-02-01T01:01:29.000Z
admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/server/service/artifact/image/effects/chain/filter/BaseFilter.java
trombka/blc-tmp
d0d12902509c872cb20d00771eebb03caea49bf1
[ "Apache-2.0" ]
2
2016-03-09T18:25:52.000Z
2020-04-03T20:49:44.000Z
33.044643
125
0.637395
5,511
/* * #%L * BroadleafCommerce Open Admin Platform * %% * Copyright (C) 2009 - 2013 Broadleaf Commerce * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.broadleafcommerce.openadmin.server.service.artifact.image.effects.chain.filter; import org.broadleafcommerce.openadmin.server.service.artifact.OperationBuilder; import java.awt.*; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.BufferedImageOp; import java.awt.image.ColorModel; import java.awt.image.IndexColorModel; import java.util.Map; public abstract class BaseFilter implements BufferedImageOp, OperationBuilder { protected RenderingHints hints; /* (non-Javadoc) * @see java.awt.image.BufferedImageOp#createCompatibleDestImage(java.awt.image.BufferedImage, java.awt.image.ColorModel) */ public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel destCM) { BufferedImage image; if (destCM == null) { destCM = src.getColorModel(); // Not much support for ICM if (destCM instanceof IndexColorModel) { destCM = ColorModel.getRGBdefault(); } } int w = src.getWidth(); int h = src.getHeight(); image = new BufferedImage (destCM, destCM.createCompatibleWritableRaster(w, h), destCM.isAlphaPremultiplied(), null); return image; } public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel destCM, int width, int height) { BufferedImage image; if (destCM == null) { destCM = src.getColorModel(); // Not much support for ICM if (destCM instanceof IndexColorModel) { destCM = ColorModel.getRGBdefault(); } } image = new BufferedImage (destCM, destCM.createCompatibleWritableRaster(width, height), destCM.isAlphaPremultiplied(), null); return image; } /* (non-Javadoc) * @see java.awt.image.BufferedImageOp#getBounds2D(java.awt.image.BufferedImage) */ public Rectangle2D getBounds2D(BufferedImage src) { return src.getRaster().getBounds(); } /* (non-Javadoc) * @see java.awt.image.BufferedImageOp#getPoint2D(java.awt.geom.Point2D, java.awt.geom.Point2D) */ public Point2D getPoint2D(Point2D srcPt, Point2D dstPt) { if (dstPt == null) { dstPt = new Point2D.Float(); } dstPt.setLocation(srcPt.getX(), srcPt.getY()); return dstPt; } /* (non-Javadoc) * @see java.awt.image.BufferedImageOp#getRenderingHints() */ public RenderingHints getRenderingHints() { return hints; } protected boolean containsMyFilterParams(String key, Map<String, String> parameterMap) { for (String paramKey : parameterMap.keySet()) { if (paramKey.startsWith(key)) { return true; } } return false; } }
3e0cfa84484b31834e765cab3f48321c57191497
10,440
java
Java
loadbalancer-standalone/src/test/java/com/rtbhouse/grpc/loadbalancer/standalone/LoadBalancerIntegrationTest.java
RTBHOUSE/grpclb-load-balancer
62f4a16e3f32ed92bffe44903fe3ab279dfca965
[ "Apache-2.0" ]
3
2019-11-08T22:44:57.000Z
2022-02-22T09:04:46.000Z
loadbalancer-standalone/src/test/java/com/rtbhouse/grpc/loadbalancer/standalone/LoadBalancerIntegrationTest.java
RTBHOUSE/grpclb-load-balancer
62f4a16e3f32ed92bffe44903fe3ab279dfca965
[ "Apache-2.0" ]
1
2019-03-26T20:21:22.000Z
2019-05-29T20:27:28.000Z
loadbalancer-standalone/src/test/java/com/rtbhouse/grpc/loadbalancer/standalone/LoadBalancerIntegrationTest.java
RTBHOUSE/grpclb-load-balancer
62f4a16e3f32ed92bffe44903fe3ab279dfca965
[ "Apache-2.0" ]
2
2019-08-02T09:57:22.000Z
2019-10-12T14:37:35.000Z
36.25
110
0.696456
5,512
package com.rtbhouse.grpc.loadbalancer.standalone; import com.rtbhouse.grpc.loadbalancer.LoadBalancerConnector; import com.rtbhouse.grpc.loadbalancer.tests.EchoGrpc; import com.rtbhouse.grpc.loadbalancer.tests.EchoReply; import com.rtbhouse.grpc.loadbalancer.tests.EchoRequest; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.Server; import io.grpc.ServerBuilder; import io.grpc.StatusRuntimeException; import io.grpc.stub.StreamObserver; import java.io.IOException; import java.net.InetAddress; import org.junit.After; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* There is a problem, that currently gRPC client supports resolving loadbalancer address only * from DNS SRV record. * It cannot be explicitly provided e.g. through a constructor. So, we have registered a dull * domain "hello.mimgrpc.me" which provides a proper record. We could try to mock the DNS request, * but it is difficult because it is done internally by gRPC library. */ @RunWith(MockitoJUnitRunner.class) public class LoadBalancerIntegrationTest { private static final Logger logger = LoggerFactory.getLogger(LoadBalancerIntegrationTest.class); /* LoadBalancerConnector will be able to fetch it from DNS just as client does, then it won't be * obligatory to pass it explicitly. */ private static final String[] lb_addresses = new String[] {"127.0.0.1:9090"}; /* We need to specify, what services our server serves, because one LB can serve clients that use * different services. * Every service has to be in format "dns_host_name:port", and it has to be the same name and port * that you use to create client's channel (look at SimpleEchoClient class). */ private static final String[] services = new String[] {"hello.mimgrpc.me:5000"}; private LoadBalancerServer loadbalancer; @BeforeClass public static void enableGrpclb() { /* When you have "normal" command-line program, you can enable grpclb through command-line * argument: -Dio.grpc.internal.DnsNameResolverProvider.enable_grpclb=true*/ System.setProperty("io.grpc.internal.DnsNameResolverProvider.enable_grpclb", "true"); } public void startLoadbalancer() throws IOException { loadbalancer = new LoadBalancerServer(9090, 3000, 4000); loadbalancer.start(); logger.info( "Started loadbalancer server at port 9090. LB will reqeust heartbeats from backend servers every 3s, " + "and will evict a server when no heartbeat is sent for 4s."); } @After public void stopLoadbalancer() { logger.info("Shutting down loadbalancer"); loadbalancer.stop(); logger.info("Loadbalancer down"); } @Test public void failingBackendsTest() throws IOException, InterruptedException { startLoadbalancer(); Server s1 = ServerBuilder.forPort(1111).addService(new EchoService("1")).build(); LoadBalancerConnector s1_connector = new LoadBalancerConnector( 1111, // our server port InetAddress.getLoopbackAddress(), // our server address lb_addresses, services); /* Typically, when you would have your custom server class (not gRPC's default), * you would have the connector inside the server class. */ s1.start(); logger.info("Started 1st backend server at port 1111 and weight 100."); s1_connector.start(); logger.info( "Backend server(1111) registered in load balancer and started sending heartbeats to the LB"); Server s2 = ServerBuilder.forPort(2222).addService(new EchoService("2")).build(); LoadBalancerConnector s2_connector = new LoadBalancerConnector(2222, InetAddress.getLoopbackAddress(), lb_addresses, services); s2.start(); logger.info("Started 2nd backend server at port 2222 and weight 100."); s2_connector.start(); logger.info( "Backend server(2222) registered in load balancer and started sending heartbeats to the LB"); logger.info("Wait 3s..."); Thread.sleep(3000); logger.info("Starting client, making requests every 0,1s for 10 seconds"); SimpleEchoClient client = new SimpleEchoClient(100); client.start(); Thread.sleep(3000); logger.info("Shutting down 1111 server"); s1_connector.stop(); s1.shutdown(); s1.awaitTermination(); logger.info("Server 1111 down"); Thread.sleep(3000); logger.info("Starting 1111 server again"); s1 = ServerBuilder.forPort(1111).addService(new EchoService("1")).build(); s1.start(); s1_connector.start(); logger.info("Server 1111 started"); Thread.sleep(3000); logger.info("Shutting down 2222 server"); s2_connector.stop(); s2.shutdown(); s2.awaitTermination(); logger.info("Server 2222 down"); Thread.sleep(3000); client.join(); logger.info("Shutting down 1111 server"); s1_connector.stop(); s1.shutdown(); s1.awaitTermination(); logger.info("Server 1111 down"); Assert.assertEquals(100, client.s1_response_count + client.s2_response_count); } @Test public void differentWeightsTest() throws IOException, InterruptedException { startLoadbalancer(); Server s1 = ServerBuilder.forPort(1111).addService(new EchoService("1")).build(); LoadBalancerConnector s1_connector = new LoadBalancerConnector( 1111, // our server port InetAddress.getLoopbackAddress(), // our server address lb_addresses, services, AvailableServerList.BackendServer.DEFAULT_WEIGHT); /* Typically, you would use a custom server class instead of gRPC's default implementation * and the LoadBalancerConnector object would be hidden inside of that class. */ s1.start(); logger.info("Started 1st backend server at port 1111 and weight 100."); s1_connector.start(); logger.info( "Backend server(1111) registered in load balancer and started sending heartbeats to the LB"); Server s2 = ServerBuilder.forPort(2222).addService(new EchoService("2")).build(); LoadBalancerConnector s2_connector = new LoadBalancerConnector( 2222, InetAddress.getLoopbackAddress(), lb_addresses, services, 3 * AvailableServerList.BackendServer.DEFAULT_WEIGHT); s2.start(); logger.info("Started 2nd backend server at port 2222 and weight 300."); s2_connector.start(); logger.info( "Backend server(2222) registered in load balancer and started sending heartbeats to the LB"); logger.info("Wait 3s..."); Thread.sleep(3000); logger.info("Starting client, making requests every 0,1s for 10 seconds (total 100 requests)"); SimpleEchoClient client = new SimpleEchoClient(100); client.start(); client.join(); logger.info("Shutting down 1111 server"); s1_connector.stop(); s1.shutdown(); s1.awaitTermination(); logger.info("Server 1111 down"); logger.info("Shutting down 2222 server"); s2_connector.stop(); s2.shutdown(); s2.awaitTermination(); logger.info("Server 2222 down"); Thread.sleep(3000); Assert.assertEquals(100, client.s1_response_count + client.s2_response_count); Assert.assertTrue(Math.abs(3 * client.s1_response_count - client.s2_response_count) < 25); } @Test public void dissappearingLoadBalancer() throws IOException, InterruptedException { Server s1 = ServerBuilder.forPort(1111).addService(new EchoService("1")).build(); LoadBalancerConnector s1_connector = new LoadBalancerConnector( 1111, // our server port InetAddress.getLoopbackAddress(), // our server address lb_addresses, services); s1.start(); logger.info("Started backend server at port 1111 and weight 100."); s1_connector.start(); logger.info("Connector started, will do a few pause/resume..."); s1_connector.pause(); s1_connector.resume(); s1_connector.pause(); Thread.sleep(100); s1_connector.resume(); Thread.sleep(100); Thread.sleep(5000); logger.info("Starting loadbalancer..."); startLoadbalancer(); SimpleEchoClient client = new SimpleEchoClient(5); logger.info("Starting client, making 5 requests..."); client.start(); client.join(); s1.shutdownNow(); s1_connector.stop(); Assert.assertEquals(5, client.s1_response_count); } private class EchoService extends EchoGrpc.EchoImplBase { private final String num; public EchoService(String num) { this.num = num; } @Override public void sayHello(EchoRequest req, StreamObserver<EchoReply> responseObserver) { EchoReply reply = EchoReply.newBuilder().setMessage(req.getMessage()).setServerNum(num).build(); responseObserver.onNext(reply); responseObserver.onCompleted(); } } private class SimpleEchoClient extends Thread { private final Logger logger = LoggerFactory.getLogger(LoadBalancerIntegrationTest.SimpleEchoClient.class); private int no_requests; private int s1_response_count; private int s2_response_count; public SimpleEchoClient(int no_requests) { this.no_requests = no_requests; } public void run() { ManagedChannel channel = ManagedChannelBuilder.forAddress("hello.mimgrpc.me", 5000).usePlaintext().build(); EchoGrpc.EchoBlockingStub stub = EchoGrpc.newBlockingStub(channel); for (int i = 0; i < no_requests; i++) { try { EchoReply response = stub.sayHello(EchoRequest.newBuilder().setMessage("Hello!").build()); logger.info("Got response from " + response.getServerNum()); if (response.getServerNum().equals("1")) s1_response_count++; else if (response.getServerNum().equals("2")) s2_response_count++; Thread.sleep(100); } catch (InterruptedException e) { logger.warn("Client interrupted: ", e); } catch (StatusRuntimeException e) { logger.warn("Client: ", e); i--; } } logger.info( "Client summary: responses from s1: {}, from s2: {}", s1_response_count, s2_response_count); channel.shutdownNow(); logger.info("Client exits"); } } }
3e0cfb245a7cc10ff1bedf1d1348772f429f2e8b
1,183
java
Java
src/ro/nextreports/server/web/analysis/feature/filter/FilterObjectDataProvider.java
bireports/nextreports-server
b5d2e10dec8563c6573812e8d5baa63393ce6c3f
[ "Apache-2.0" ]
27
2015-03-10T20:15:37.000Z
2021-04-19T03:29:37.000Z
src/ro/nextreports/server/web/analysis/feature/filter/FilterObjectDataProvider.java
bireports/nextreports-server
b5d2e10dec8563c6573812e8d5baa63393ce6c3f
[ "Apache-2.0" ]
9
2015-03-09T13:19:55.000Z
2020-08-26T11:52:35.000Z
src/ro/nextreports/server/web/analysis/feature/filter/FilterObjectDataProvider.java
bireports/nextreports-server
b5d2e10dec8563c6573812e8d5baa63393ce6c3f
[ "Apache-2.0" ]
20
2015-03-22T15:32:03.000Z
2022-03-11T17:58:23.000Z
28.166667
99
0.775993
5,513
package ro.nextreports.server.web.analysis.feature.filter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; import org.apache.wicket.injection.Injector; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import ro.nextreports.server.domain.AnalysisFilter; public class FilterObjectDataProvider extends SortableDataProvider<AnalysisFilter, String> { private ArrayList<AnalysisFilter> filters; public FilterObjectDataProvider(IModel<ArrayList<AnalysisFilter>> filterModel) { Injector.get().inject(this); this.filters = filterModel.getObject(); } @Override public Iterator<? extends AnalysisFilter> iterator(long first, long count) { return getFilterObjects().subList((int)first, (int)(first + Math.min(count, size()))).iterator(); } @Override public IModel<AnalysisFilter> model(AnalysisFilter filterObject) { return new Model<AnalysisFilter>(filterObject); } @Override public long size() { return getFilterObjects().size(); } private List<AnalysisFilter> getFilterObjects() { return filters; } }
3e0cfc9891d885571acc1b179c4e36f9220503be
5,673
java
Java
bot/java/src/main/java/com/antgroup/antchain/openapi/bot/models/Device.java
alipay/antchain-openapi-prod-sdk
f78549e5135d91756093bd88d191ca260b28e083
[ "MIT" ]
6
2020-06-28T06:40:50.000Z
2022-02-25T11:02:18.000Z
bot/java/src/main/java/com/antgroup/antchain/openapi/bot/models/Device.java
alipay/antchain-openapi-prod-sdk
f78549e5135d91756093bd88d191ca260b28e083
[ "MIT" ]
null
null
null
bot/java/src/main/java/com/antgroup/antchain/openapi/bot/models/Device.java
alipay/antchain-openapi-prod-sdk
f78549e5135d91756093bd88d191ca260b28e083
[ "MIT" ]
6
2020-06-30T09:29:03.000Z
2022-01-07T10:42:22.000Z
23.442149
142
0.603913
5,514
// This file is auto-generated, don't edit it. Thanks. package com.antgroup.antchain.openapi.bot.models; import com.aliyun.tea.*; public class Device extends TeaModel { // 设备实体唯一Id @NameInMap("device_id") @Validation(required = true) public String deviceId; // 数据模型Id @NameInMap("device_data_model_id") @Validation(required = true) public String deviceDataModelId; // 场景码 @NameInMap("scene") @Validation(required = true) public String scene; // imei号 @NameInMap("device_imei") @Validation(required = true) public String deviceImei; // 设备名称 @NameInMap("device_name") public String deviceName; // 设备厂商名称 @NameInMap("corp_name") public String corpName; // 设备ICCID // // @NameInMap("device_iccid") public String deviceIccid; // 设备扩展信息 @NameInMap("extra_info") public String extraInfo; // 设备链上Id @NameInMap("chain_device_id") @Validation(required = true) public String chainDeviceId; // 上链哈希 @NameInMap("tx_hash") @Validation(required = true) public String txHash; // 上链时间 @NameInMap("tx_time") @Validation(required = true) public Long txTime; // 设备类型编码,必填,对应资管平台中的设备类型 // // 枚举值: // // 车辆 1000 // 车辆 四轮车 1001 // 车辆 四轮车 纯电四轮车 1002 // 车辆 四轮车 混动四轮车 1003 // 车辆 四轮车 燃油四轮车 1004 // 车辆 两轮车 1011 // 车辆 两轮车 两轮单车 1012 // 车辆 两轮车 两轮助力车 1013 // // 换电柜 2000 // 换电柜 二轮车换电柜 2001 // // 电池 3000 // 电池 磷酸铁电池 3001 // 电池 三元锂电池 3002 // // 回收设备 4000 // // 垃圾分类回收 4001 // // 洗车机 5000 @NameInMap("device_type_code") @Validation(required = true) public Long deviceTypeCode; // 单价 @NameInMap("initial_price") @Validation(required = true) public Long initialPrice; // 投放时间 @NameInMap("release_time") @Validation(required = true, pattern = "\\d{4}[-]\\d{1,2}[-]\\d{1,2}[T]\\d{2}:\\d{2}:\\d{2}([Z]|([\\.]\\d{1,9})?[\\+]\\d{2}[\\:]?\\d{2})") public String releaseTime; // 出厂时间 @NameInMap("factory_time") @Validation(required = true, pattern = "\\d{4}[-]\\d{1,2}[-]\\d{1,2}[T]\\d{2}:\\d{2}:\\d{2}([Z]|([\\.]\\d{1,9})?[\\+]\\d{2}[\\:]?\\d{2})") public String factoryTime; // 设备状态,取值范围:NORMAL、OFFLINE、UNREGISTER @NameInMap("device_status") public String deviceStatus; public static Device build(java.util.Map<String, ?> map) throws Exception { Device self = new Device(); return TeaModel.build(map, self); } public Device setDeviceId(String deviceId) { this.deviceId = deviceId; return this; } public String getDeviceId() { return this.deviceId; } public Device setDeviceDataModelId(String deviceDataModelId) { this.deviceDataModelId = deviceDataModelId; return this; } public String getDeviceDataModelId() { return this.deviceDataModelId; } public Device setScene(String scene) { this.scene = scene; return this; } public String getScene() { return this.scene; } public Device setDeviceImei(String deviceImei) { this.deviceImei = deviceImei; return this; } public String getDeviceImei() { return this.deviceImei; } public Device setDeviceName(String deviceName) { this.deviceName = deviceName; return this; } public String getDeviceName() { return this.deviceName; } public Device setCorpName(String corpName) { this.corpName = corpName; return this; } public String getCorpName() { return this.corpName; } public Device setDeviceIccid(String deviceIccid) { this.deviceIccid = deviceIccid; return this; } public String getDeviceIccid() { return this.deviceIccid; } public Device setExtraInfo(String extraInfo) { this.extraInfo = extraInfo; return this; } public String getExtraInfo() { return this.extraInfo; } public Device setChainDeviceId(String chainDeviceId) { this.chainDeviceId = chainDeviceId; return this; } public String getChainDeviceId() { return this.chainDeviceId; } public Device setTxHash(String txHash) { this.txHash = txHash; return this; } public String getTxHash() { return this.txHash; } public Device setTxTime(Long txTime) { this.txTime = txTime; return this; } public Long getTxTime() { return this.txTime; } public Device setDeviceTypeCode(Long deviceTypeCode) { this.deviceTypeCode = deviceTypeCode; return this; } public Long getDeviceTypeCode() { return this.deviceTypeCode; } public Device setInitialPrice(Long initialPrice) { this.initialPrice = initialPrice; return this; } public Long getInitialPrice() { return this.initialPrice; } public Device setReleaseTime(String releaseTime) { this.releaseTime = releaseTime; return this; } public String getReleaseTime() { return this.releaseTime; } public Device setFactoryTime(String factoryTime) { this.factoryTime = factoryTime; return this; } public String getFactoryTime() { return this.factoryTime; } public Device setDeviceStatus(String deviceStatus) { this.deviceStatus = deviceStatus; return this; } public String getDeviceStatus() { return this.deviceStatus; } }
3e0cfce45400dbfbd2e497b845864e1569c59ed7
1,541
java
Java
subprojects/site/src/test/java/com/ksoichiro/task/converter/TaskStatusToStringConverterJaTests.java
ksoichiro/task
c84b46466888511a83071abbcad648b392de3200
[ "Apache-2.0" ]
null
null
null
subprojects/site/src/test/java/com/ksoichiro/task/converter/TaskStatusToStringConverterJaTests.java
ksoichiro/task
c84b46466888511a83071abbcad648b392de3200
[ "Apache-2.0" ]
null
null
null
subprojects/site/src/test/java/com/ksoichiro/task/converter/TaskStatusToStringConverterJaTests.java
ksoichiro/task
c84b46466888511a83071abbcad648b392de3200
[ "Apache-2.0" ]
null
null
null
32.104167
82
0.75146
5,515
package com.ksoichiro.task.converter; import com.ksoichiro.task.App; import com.ksoichiro.task.constant.TaskStatusEnum; import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.rules.SpringClassRule; import org.springframework.test.context.junit4.rules.SpringMethodRule; import java.util.Locale; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; @SpringBootTest(classes = App.class) public class TaskStatusToStringConverterJaTests { @ClassRule public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule(); @Rule public final SpringMethodRule springMethodRule = new SpringMethodRule(); private static Locale defaultLocale = Locale.getDefault(); @Autowired private TaskStatusToStringConverter converter; @BeforeClass public static void setUpClass() { Locale.setDefault(Locale.JAPANESE); } @AfterClass public static void tearDownClass() { Locale.setDefault(defaultLocale); } @Test public void convert() { assertThat(converter.convert(TaskStatusEnum.NOT_YET), is("未着手")); assertThat(converter.convert(TaskStatusEnum.DOING), is("作業中")); assertThat(converter.convert(TaskStatusEnum.CANCELLED), is("中止")); assertThat(converter.convert(TaskStatusEnum.HOLD), is("保留")); assertThat(converter.convert(TaskStatusEnum.DONE), is("完了")); } }
3e0cfd771a67f4fd48a5c0e1251f536c06e78b88
9,095
java
Java
counter/src/main/java/org/infinispan/counter/impl/manager/EmbeddedCounterManager.java
dukefirehawk/infinispan
c8e3df8784f8b9d6d9c6351a10716130d2103d37
[ "Apache-2.0" ]
null
null
null
counter/src/main/java/org/infinispan/counter/impl/manager/EmbeddedCounterManager.java
dukefirehawk/infinispan
c8e3df8784f8b9d6d9c6351a10716130d2103d37
[ "Apache-2.0" ]
null
null
null
counter/src/main/java/org/infinispan/counter/impl/manager/EmbeddedCounterManager.java
dukefirehawk/infinispan
c8e3df8784f8b9d6d9c6351a10716130d2103d37
[ "Apache-2.0" ]
null
null
null
37.582645
144
0.716548
5,516
package org.infinispan.counter.impl.manager; import static org.infinispan.commons.util.concurrent.CompletableFutures.completedExceptionFuture; import static org.infinispan.commons.util.concurrent.CompletableFutures.completedNull; import static org.infinispan.commons.util.concurrent.CompletableFutures.toNullFunction; import static org.infinispan.counter.impl.Util.awaitCounterOperation; import static org.infinispan.counter.logging.Log.CONTAINER; import java.util.Collection; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentHashMap; import org.infinispan.commons.logging.LogFactory; import org.infinispan.counter.api.CounterConfiguration; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterType; import org.infinispan.counter.api.PropertyFormatter; import org.infinispan.counter.api.StrongCounter; import org.infinispan.counter.api.WeakCounter; import org.infinispan.counter.impl.factory.StrongCounterFactory; import org.infinispan.counter.impl.factory.WeakCounterFactory; import org.infinispan.counter.impl.listener.CounterManagerNotificationManager; import org.infinispan.counter.logging.Log; import org.infinispan.factories.annotations.Inject; import org.infinispan.factories.annotations.Start; import org.infinispan.factories.annotations.Stop; import org.infinispan.factories.scopes.Scope; import org.infinispan.factories.scopes.Scopes; import org.infinispan.jmx.annotations.MBean; import org.infinispan.jmx.annotations.ManagedOperation; import org.infinispan.util.concurrent.CompletionStages; /** * A {@link CounterManager} implementation for embedded cache manager. * * @author Pedro Ruivo * @since 9.0 */ @Scope(Scopes.GLOBAL) @MBean(objectName = EmbeddedCounterManager.OBJECT_NAME, description = "Component to manage counters") public class EmbeddedCounterManager implements CounterManager { public static final String OBJECT_NAME = "CounterManager"; private static final Log log = LogFactory.getLog(EmbeddedCounterManager.class, Log.class); private final Map<String, CompletableFuture<InternalCounterAdmin>> counters; private volatile boolean stopped = true; @Inject CounterConfigurationManager configurationManager; @Inject CounterManagerNotificationManager notificationManager; @Inject StrongCounterFactory strongCounterFactory; @Inject WeakCounterFactory weakCounterFactory; public EmbeddedCounterManager() { counters = new ConcurrentHashMap<>(32); } @Start public void start() { if (log.isTraceEnabled()) { log.trace("Starting EmbeddedCounterManager"); } stopped = false; } @Stop(priority = 9) //lower than default priority to avoid creating the counters cache. public void stop() { if (log.isTraceEnabled()) { log.trace("Stopping EmbeddedCounterManager"); } stopped = true; } @ManagedOperation( description = "Removes the counter's value from the cluster. The counter will be re-created when access next time.", displayName = "Remove Counter", name = "remove" ) @Override public void remove(String counterName) { awaitCounterOperation(removeAsync(counterName, true)); } public CompletionStage<Void> removeAsync(String counterName, boolean keepConfig) { CompletionStage<Void> removeStage = getConfigurationAsync(counterName) .thenCompose(config -> { // check if the counter is defined if (config == null) { return completedNull(); } CompletionStage<InternalCounterAdmin> existingCounter = counters.remove(counterName); // if counter instance exists, invoke destroy() if (existingCounter != null) { return existingCounter.thenCompose(InternalCounterAdmin::destroy); } if (config.type() == CounterType.WEAK) { return weakCounterFactory.removeWeakCounter(counterName, config); } else { return strongCounterFactory.removeStrongCounter(counterName); } }); if (keepConfig) { return removeStage; } return removeStage.thenCompose(unused -> configurationManager.removeConfiguration(counterName)) .thenApply(toNullFunction()); } @Override public void undefineCounter(String counterName) { awaitCounterOperation(removeAsync(counterName, false)); } @Override public StrongCounter getStrongCounter(String name) { return awaitCounterOperation(getStrongCounterAsync(name)); } public CompletionStage<StrongCounter> getStrongCounterAsync(String counterName) { return getOrCreateAsync(counterName).thenApply(InternalCounterAdmin::asStrongCounter); } @Override public WeakCounter getWeakCounter(String name) { return awaitCounterOperation(getWeakCounterAsync(name)); } public CompletionStage<WeakCounter> getWeakCounterAsync(String counterName) { return getOrCreateAsync(counterName).thenApply(InternalCounterAdmin::asWeakCounter); } public CompletionStage<InternalCounterAdmin> getOrCreateAsync(String counterName) { if (stopped) { return completedExceptionFuture(CONTAINER.counterManagerNotStarted()); } CompletableFuture<InternalCounterAdmin> stage = counters.computeIfAbsent(counterName, this::createCounter); if (CompletionStages.isCompletedSuccessfully(stage)) { // avoid invoking "exceptionally()" every time return stage; } // remove if it fails stage.exceptionally(throwable -> { counters.remove(counterName, stage); return null; }); return stage; } @ManagedOperation( description = "Returns a collection of defined counter's name.", displayName = "Get Defined Counters", name = "counters") @Override public Collection<String> getCounterNames() { return configurationManager.getCounterNames(); } public CompletableFuture<Boolean> defineCounterAsync(String name, CounterConfiguration configuration) { return configurationManager.defineConfiguration(name, configuration); } @Override public boolean defineCounter(String name, CounterConfiguration configuration) { return awaitCounterOperation(defineCounterAsync(name, configuration)); } @Override public boolean isDefined(String name) { return awaitCounterOperation(isDefinedAsync(name)); } @Override public CounterConfiguration getConfiguration(String counterName) { return awaitCounterOperation(getConfigurationAsync(counterName)); } public CompletableFuture<CounterConfiguration> getConfigurationAsync(String name) { return configurationManager.getConfiguration(name); } @ManagedOperation( description = "Returns the current counter's value", displayName = "Get Counter' Value", name = "value" ) public long getValue(String counterName) { return awaitCounterOperation(getOrCreateAsync(counterName).thenCompose(InternalCounterAdmin::value)); } @ManagedOperation( description = "Resets the counter's value", displayName = "Reset Counter", name = "reset" ) public void reset(String counterName) { awaitCounterOperation(getOrCreateAsync(counterName).thenCompose(InternalCounterAdmin::reset)); } @ManagedOperation( description = "Returns the counter's configuration", displayName = "Counter Configuration", name = "configuration" ) public Properties getCounterConfiguration(String counterName) { CounterConfiguration configuration = getConfiguration(counterName); if (configuration == null) { throw CONTAINER.undefinedCounter(counterName); } return PropertyFormatter.getInstance().format(configuration); } public CompletableFuture<Boolean> isDefinedAsync(String name) { return getConfigurationAsync(name).thenApply(Objects::nonNull); } private CompletableFuture<InternalCounterAdmin> createCounter(String counterName) { return getConfigurationAsync(counterName) .thenCompose(config -> { if (config == null) { return completedExceptionFuture(CONTAINER.undefinedCounter(counterName)); } switch (config.type()) { case WEAK: return weakCounterFactory.createWeakCounter(counterName, config); case BOUNDED_STRONG: case UNBOUNDED_STRONG: return strongCounterFactory.createStrongCounter(counterName, config); default: return completedExceptionFuture(new IllegalStateException("[should never happen] unknown counter type: " + config.type())); } }); } }
3e0cfd8357a6bb1fe9e809dd9edbfacce3201654
933
java
Java
spring-boot-data-aggregator-core/src/main/java/io/github/lvyahui8/spring/aggregate2/AggregateServiceV2.java
lvyahui8/spring-boot-data-aggregate
3db0e50ffac5250c24c64be3292c077b0ccc0c39
[ "Apache-2.0" ]
null
null
null
spring-boot-data-aggregator-core/src/main/java/io/github/lvyahui8/spring/aggregate2/AggregateServiceV2.java
lvyahui8/spring-boot-data-aggregate
3db0e50ffac5250c24c64be3292c077b0ccc0c39
[ "Apache-2.0" ]
null
null
null
spring-boot-data-aggregator-core/src/main/java/io/github/lvyahui8/spring/aggregate2/AggregateServiceV2.java
lvyahui8/spring-boot-data-aggregate
3db0e50ffac5250c24c64be3292c077b0ccc0c39
[ "Apache-2.0" ]
null
null
null
35.923077
188
0.766595
5,517
package io.github.lvyahui8.spring.aggregate2; import io.github.lvyahui8.spring.aggregate.model.DataProvideDefinition; import io.github.lvyahui8.spring.aggregate.service.DataBeanAggregateService; import java.lang.reflect.InvocationTargetException; import java.util.Map; /** * @author feego ychag@example.com * @date 2022/4/2 */ public class AggregateServiceV2 implements DataBeanAggregateService { @Override public <T> T get(String id, Map<String, Object> invokeParams, Class<T> resultType) throws InterruptedException, InvocationTargetException, IllegalAccessException { final Context context = new Context(); context.paramMap = invokeParams; return null; } @Override public <T> T get(DataProvideDefinition provider, Map<String, Object> invokeParams, Class<T> resultType) throws InterruptedException, InvocationTargetException, IllegalAccessException { return null; } }
3e0cfd9e6050425aa3efef47a3d50e57f95e67e4
605
java
Java
jadaptive-api/src/main/java/com/jadaptive/api/repository/AssignableUUIDEntity.java
ludup/jadaptive-builder
4d3f4f9a860ee3a4298b4b1aca01b7ae7ee2c293
[ "Apache-2.0" ]
2
2020-11-08T00:41:02.000Z
2021-08-21T02:40:53.000Z
jadaptive-api/src/main/java/com/jadaptive/api/repository/AssignableUUIDEntity.java
ludup/jadaptive-app-builder
4d3f4f9a860ee3a4298b4b1aca01b7ae7ee2c293
[ "Apache-2.0" ]
null
null
null
jadaptive-api/src/main/java/com/jadaptive/api/repository/AssignableUUIDEntity.java
ludup/jadaptive-app-builder
4d3f4f9a860ee3a4298b4b1aca01b7ae7ee2c293
[ "Apache-2.0" ]
null
null
null
21.607143
71
0.742149
5,518
package com.jadaptive.api.repository; import java.util.Collection; import java.util.HashSet; public abstract class AssignableUUIDEntity extends AbstractUUIDEntity { private static final long serialVersionUID = -5734236381558890213L; Collection<String> roles = new HashSet<>(); Collection<String> users = new HashSet<>(); public Collection<String> getRoles() { return roles; } public void setRoles(Collection<String> roles) { this.roles = roles; } public Collection<String> getUsers() { return users; } public void setUsers(Collection<String> users) { this.users = users; } }
3e0cfdb02fc825d79f1d61dc02a20e04865f799b
791
java
Java
LACCPlus/Hadoop/3033_1.java
sgholamian/log-aware-clone-detection
9993cb081c420413c231d1807bfff342c39aa69a
[ "MIT" ]
null
null
null
LACCPlus/Hadoop/3033_1.java
sgholamian/log-aware-clone-detection
9993cb081c420413c231d1807bfff342c39aa69a
[ "MIT" ]
null
null
null
LACCPlus/Hadoop/3033_1.java
sgholamian/log-aware-clone-detection
9993cb081c420413c231d1807bfff342c39aa69a
[ "MIT" ]
null
null
null
34.391304
79
0.656131
5,519
//,temp,Resources.java,514,531,temp,Resources.java,382,395 //,3 public class xxx { public static Resource componentwiseMin(Resource lhs, Resource rhs) { Resource ret = createResource(0); int maxLength = ResourceUtils.getNumberOfKnownResourceTypes(); for (int i = 0; i < maxLength; i++) { try { ResourceInformation rhsValue = rhs.getResourceInformation(i); ResourceInformation lhsValue = lhs.getResourceInformation(i); ResourceInformation outInfo = lhsValue.getValue() < rhsValue.getValue() ? lhsValue : rhsValue; ret.setResourceInformation(i, outInfo); } catch (ResourceNotFoundException ye) { LOG.warn("Resource is missing:" + ye.getMessage()); continue; } } return ret; } };
3e0cfe1957946055c60905dbd2b2902527bd24ca
7,009
java
Java
modules/composer-ffmpeg/src/test/java/org/opencastproject/composer/impl/EncodingProfileTest.java
LinqLover/opencast
f803d6fa3cd805619c934a6d35b1306b1a9b3c4b
[ "ECL-2.0" ]
300
2017-06-19T09:49:57.000Z
2022-03-15T09:23:32.000Z
modules/composer-ffmpeg/src/test/java/org/opencastproject/composer/impl/EncodingProfileTest.java
LinqLover/opencast
f803d6fa3cd805619c934a6d35b1306b1a9b3c4b
[ "ECL-2.0" ]
1,907
2017-06-22T13:16:39.000Z
2022-03-31T22:34:24.000Z
modules/composer-ffmpeg/src/test/java/org/opencastproject/composer/impl/EncodingProfileTest.java
LinqLover/opencast
f803d6fa3cd805619c934a6d35b1306b1a9b3c4b
[ "ECL-2.0" ]
228
2017-06-19T12:57:09.000Z
2022-03-29T11:29:17.000Z
32.151376
113
0.728492
5,520
/** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * * The Apereo Foundation licenses this file to you under the Educational * Community License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License * at: * * http://opensource.org/licenses/ecl2.txt * * 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.opencastproject.composer.impl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.opencastproject.composer.api.EncodingProfile; import org.opencastproject.composer.api.EncodingProfile.MediaType; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.net.URL; import java.util.Collections; import java.util.Map; /** * Tests for encoding format handling. */ public class EncodingProfileTest { /** Map with encoding profiles */ private Map<String, EncodingProfile> profiles = null; /** Name of the h264 profile */ private String h264ProfileId = "h264-medium.http"; /** Name of the cover ui profile */ private String coverProfileId = "cover-ui.http"; @Rule public TemporaryFolder tmp = new TemporaryFolder(); /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { URL url = EncodingProfileTest.class.getResource("/encodingtestprofiles.properties"); EncodingProfileScanner mgr = new EncodingProfileScanner(); profiles = mgr.loadFromProperties(new File(url.toURI())); } /** * Test (un)installing profiles */ @Test public void testInstall() throws Exception { URL url = EncodingProfileTest.class.getResource("/encodingtestprofiles.properties"); File file = new File(url.toURI()); EncodingProfileScanner mgr = new EncodingProfileScanner(); mgr.install(file); int profileCount = mgr.getProfiles().size(); assertTrue(profileCount > 0); mgr.update(file); assertEquals(mgr.getProfiles().size(), profileCount); mgr.uninstall(file); assertEquals(0, mgr.getProfiles().size()); } /** * Test method for {@link org.opencastproject.composer.api.EncodingProfileImpl}. */ @Test public void testMediaTypes() { assertNotNull(EncodingProfile.MediaType.parseString("audio")); assertNotNull(EncodingProfile.MediaType.parseString("visual")); assertNotNull(EncodingProfile.MediaType.parseString("audiovisual")); assertNotNull(EncodingProfile.MediaType.parseString("enhancedaudio")); assertNotNull(EncodingProfile.MediaType.parseString("image")); assertNotNull(EncodingProfile.MediaType.parseString("imagesequence")); assertNotNull(EncodingProfile.MediaType.parseString("cover")); try { EncodingProfile.MediaType.parseString("foo"); fail("Test should have failed for media type 'foo'"); } catch (IllegalArgumentException e) { // Expected } } /** * Test method for {@link org.opencastproject.composer.api.EncodingProfileImpl}. */ @Test public void testInitializationFromProperties() { assertNotNull(profiles); assertEquals(12, profiles.size()); } /** * Test method for {@link org.opencastproject.composer.api.EncodingProfileImpl#getIdentifier()}. */ @Test public void testGetIdentifier() { EncodingProfile profile = profiles.get(h264ProfileId); assertEquals(h264ProfileId, profile.getIdentifier()); } /** * Test method for {@link org.opencastproject.composer.api.EncodingProfileImpl#getName()}. */ @Test public void testGetName() { EncodingProfile profile = profiles.get(h264ProfileId); assertEquals("h.264 download medium quality", profile.getName()); } /** * Test method for {@link org.opencastproject.composer.api.EncodingProfileImpl#getOutputType()}. */ @Test public void testGetType() { EncodingProfile profile = profiles.get(h264ProfileId); assertEquals(MediaType.Visual, profile.getOutputType()); } /** * Test method for {@link org.opencastproject.composer.api.EncodingProfileImpl#getSuffix()}. */ @Test public void testGetSuffix() { EncodingProfile profile = profiles.get(h264ProfileId); assertEquals("-dm.m4v", profile.getSuffix()); } /** * Test method for {@link org.opencastproject.composer.api.EncodingProfileImpl#getApplicableMediaTypes()}. */ @Test public void testGetApplicableMediaTypes() { EncodingProfile profile = profiles.get(h264ProfileId); MediaType type = profile.getApplicableMediaType(); assertNotNull(type); assertEquals(MediaType.Visual, type); } /** * Test method for {@link org.opencastproject.composer.api.EncodingProfileImpl#getApplicableMediaTypes()}. */ @Test public void testApplicableTo() { EncodingProfile profile = profiles.get(h264ProfileId); assertTrue(profile.isApplicableTo(MediaType.Visual)); assertFalse(profile.isApplicableTo(MediaType.Audio)); } /** * Test method for {@link org.opencastproject.composer.api.EncodingProfileImpl#getExtension(java.lang.String)}. */ @Test public void testGetExtension() { EncodingProfile profile = profiles.get(h264ProfileId); assertNull(profile.getExtension("test")); // Test profile with existing extension profile = profiles.get(coverProfileId); String commandline = "-i #{in.path} -y -r 1 -t 1 -f image2 -s 160x120 #{out.dir}/#{in.name}#{out.suffix}"; assertEquals(commandline, profile.getExtension("ffmpeg.command")); } /** * Test method for {@link org.opencastproject.composer.api.EncodingProfileImpl#getExtensions()}. */ @Test public void testGetExtensions() { EncodingProfile profile = profiles.get(h264ProfileId); profile.isApplicableTo(MediaType.Visual); assertEquals(Collections.emptyMap(), profile.getExtensions()); // Test profile with existing extension profile = profiles.get(coverProfileId); assertEquals(1, profile.getExtensions().size()); } /** * Test method for {@link org.opencastproject.composer.api.EncodingProfileImpl#hasExtensions()}. */ @Test public void testHasExtensions() { EncodingProfile profile = profiles.get(h264ProfileId); assertFalse(profile.hasExtensions()); // Test profile with existing extension profile = profiles.get(coverProfileId); assertTrue(profile.hasExtensions()); } }
3e0cfef6b02895a6cde875f334c4dfaa5caf8744
4,613
java
Java
main/plugins/org.talend.designer.components.libs/libs_src/bonitaclient/src/main/java/org/talend/bonita/Client.java
bgunics-talend/tdi-studio-se
3f54f55acb4d214f2d02532667bae98420068170
[ "Apache-2.0" ]
114
2015-03-05T15:34:59.000Z
2022-02-22T03:48:44.000Z
main/plugins/org.talend.designer.components.libs/libs_src/bonitaclient/src/main/java/org/talend/bonita/Client.java
bgunics-talend/tdi-studio-se
3f54f55acb4d214f2d02532667bae98420068170
[ "Apache-2.0" ]
1,137
2015-03-04T01:35:42.000Z
2022-03-29T06:03:17.000Z
main/plugins/org.talend.designer.components.libs/libs_src/bonitaclient/src/main/java/org/talend/bonita/Client.java
bgunics-talend/tdi-studio-se
3f54f55acb4d214f2d02532667bae98420068170
[ "Apache-2.0" ]
219
2015-01-21T10:42:18.000Z
2022-02-17T07:57:20.000Z
43.11215
155
0.701713
5,521
package org.talend.bonita; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import org.bonitasoft.engine.api.LoginAPI; import org.bonitasoft.engine.api.ProcessAPI; import org.bonitasoft.engine.api.TenantAPIAccessor; import org.bonitasoft.engine.bpm.bar.BusinessArchive; import org.bonitasoft.engine.bpm.bar.BusinessArchiveFactory; import org.bonitasoft.engine.bpm.process.ProcessDefinition; import org.bonitasoft.engine.bpm.process.ProcessInstance; import org.bonitasoft.engine.exception.BonitaException; import org.bonitasoft.engine.session.APISession; public class Client { private static final String BONITA_HOME_KEY = "bonita.home"; private APISession session; private ProcessAPI processAPI; private LoginAPI loginAPI; public Client(String bonitaHome) throws BonitaException { System.setProperty(BONITA_HOME_KEY,bonitaHome); loginAPI = TenantAPIAccessor.getLoginAPI(); } public static void main(String[] args) throws Exception { Client client = new Client("C:/BonitaBPMCommunity-6.5.2/workspace/bonita"); client.login("walter.bates", "bpm"); // deploy a process String processDefinitionId = client.deployProcess("C:/Users/Talend/Desktop/login--1.0.bar"); // start a process Map<String,Object> vars = new HashMap<String,Object>(); vars.put("id",1); vars.put("name","wangwei"); vars.put("date","2015"); client.startProcess(processDefinitionId,vars); client.startProcess("login","1.0",vars); client.startProcess("login","1.0",vars); client.logout(); } public String deployProcess(String file) throws BonitaException, IOException { BusinessArchive businessArchive = BusinessArchiveFactory.readBusinessArchive(new File(file)); ProcessDefinition processDefinition = processAPI.deploy(businessArchive); processAPI.enableProcess(processDefinition.getId()); return String.valueOf(processDefinition.getId()); } public String startProcess(String processDefinitionId,Map<String, Object> processVariables) throws BonitaException { Map<String, Serializable> listVariablesSerializable = new HashMap<String, Serializable>(); for (String variableName : processVariables.keySet()) { if (processVariables.get(variableName) == null || (!(processVariables.get(variableName) instanceof Serializable))) { continue; } Object value = processVariables.get(variableName); Serializable valueSerializable = (Serializable) value; variableName = variableName.toLowerCase(); listVariablesSerializable.put(variableName, valueSerializable); } ProcessInstance processInstance = processAPI.startProcess(Long.parseLong(processDefinitionId),listVariablesSerializable); return String.valueOf(processInstance.getId()); } public String startProcess(String processDefinitionName,String processDefinitionVersion,Map<String, Object> processVariables) throws BonitaException { long processDefinitionId = processAPI.getProcessDefinitionId(processDefinitionName, processDefinitionVersion); ProcessDefinition processDefinition = processAPI.getProcessDefinition(processDefinitionId); Map<String, Serializable> listVariablesSerializable = new HashMap<String, Serializable>(); for (String variableName : processVariables.keySet()) { if (processVariables.get(variableName) == null || (!(processVariables.get(variableName) instanceof Serializable))) continue; Object value = processVariables.get(variableName); Serializable valueSerializable = (Serializable) value; variableName = variableName.toLowerCase(); listVariablesSerializable.put(variableName, valueSerializable); } ProcessInstance processInstance = processAPI.startProcess(processDefinition.getId(),listVariablesSerializable); return String.valueOf(processInstance.getId()); } public void login(String username, String password) throws BonitaException { this.session = loginAPI.login(username, password); processAPI = TenantAPIAccessor.getProcessAPI(session); } public void logout() throws BonitaException { loginAPI.logout(session); session = null; } }
3e0cffa6aedba0fae3fd44777be787cd5d859c91
575
java
Java
src/test/java/com/angkorteam/fintech/pages/TaxDashboardPageUITest.java
PkayJava/fintech
84131d2fdf1d9e8dd55f5d22c65da45009b11859
[ "Apache-2.0" ]
1
2020-06-22T15:03:08.000Z
2020-06-22T15:03:08.000Z
src/test/java/com/angkorteam/fintech/pages/TaxDashboardPageUITest.java
PkayJava/fintech
84131d2fdf1d9e8dd55f5d22c65da45009b11859
[ "Apache-2.0" ]
3
2017-11-14T14:06:41.000Z
2017-11-17T17:53:55.000Z
src/test/java/com/angkorteam/fintech/pages/TaxDashboardPageUITest.java
PkayJava/fintech
84131d2fdf1d9e8dd55f5d22c65da45009b11859
[ "Apache-2.0" ]
null
null
null
20.535714
78
0.713043
5,522
package com.angkorteam.fintech.pages; import org.junit.Before; import org.junit.Test; import com.angkorteam.fintech.junit.JUnit; import com.angkorteam.fintech.junit.JUnitWicketTester; public class TaxDashboardPageUITest { private JUnitWicketTester wicket; @Before public void before() { this.wicket = JUnit.getWicket(); } @Test public void visitPage() { this.wicket.login(); TaxDashboardPage page = this.wicket.startPage(TaxDashboardPage.class); this.wicket.assertRenderedPage(TaxDashboardPage.class); } }
3e0d01081b04ac3bba14eb6b9a8e6a6122521560
341
java
Java
MyPets/app/src/main/java/com/example/mypets/DBConnection.java
David100459/Moviles-6A-2020
3755ebe592923818fc398b53271e04f03e44ef91
[ "MIT" ]
null
null
null
MyPets/app/src/main/java/com/example/mypets/DBConnection.java
David100459/Moviles-6A-2020
3755ebe592923818fc398b53271e04f03e44ef91
[ "MIT" ]
null
null
null
MyPets/app/src/main/java/com/example/mypets/DBConnection.java
David100459/Moviles-6A-2020
3755ebe592923818fc398b53271e04f03e44ef91
[ "MIT" ]
null
null
null
24.357143
57
0.768328
5,523
package com.example.mypets; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class DBConnection extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_d_b_connection); } }
3e0d01c0683580d58d1a2b3cb8832aeda630ed1e
4,053
java
Java
structr-ui/src/main/java/org/structr/web/resource/LoginResource.java
dlaske/structr
e829a57d42c1b82774ef4d61b816fef6f1950846
[ "IJG", "ADSL" ]
null
null
null
structr-ui/src/main/java/org/structr/web/resource/LoginResource.java
dlaske/structr
e829a57d42c1b82774ef4d61b816fef6f1950846
[ "IJG", "ADSL" ]
null
null
null
structr-ui/src/main/java/org/structr/web/resource/LoginResource.java
dlaske/structr
e829a57d42c1b82774ef4d61b816fef6f1950846
[ "IJG", "ADSL" ]
null
null
null
25.490566
134
0.710091
5,524
/** * Copyright (C) 2010-2015 Morgner UG (haftungsbeschränkt) * * This file is part of Structr <http://structr.org>. * * Structr is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Structr is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Structr. If not, see <http://www.gnu.org/licenses/>. */ package org.structr.web.resource; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.structr.common.SecurityContext; import org.structr.common.error.FrameworkException; import org.structr.core.Result; import org.structr.core.entity.Principal; import org.structr.core.property.PropertyKey; import org.structr.core.property.PropertyMap; import org.structr.rest.RestMethodResult; import org.structr.rest.exception.NotAllowedException; import org.structr.rest.resource.Resource; import org.structr.web.entity.User; //~--- classes ---------------------------------------------------------------- /** * Resource that handles user logins * * @author Axel Morgner */ public class LoginResource extends Resource { private static final Logger logger = Logger.getLogger(LoginResource.class.getName()); //~--- methods -------------------------------------------------------- @Override public boolean checkAndConfigure(String part, SecurityContext securityContext, HttpServletRequest request) { this.securityContext = securityContext; if (getUriPart().equals(part)) { return true; } return false; } @Override public RestMethodResult doPost(Map<String, Object> propertySet) throws FrameworkException { PropertyMap properties = PropertyMap.inputTypeToJavaType(securityContext, User.class, propertySet); String name = properties.get(User.name); String email = properties.get(User.eMail); String password = properties.get(User.password); String emailOrUsername = StringUtils.isNotEmpty(email) ? email : name; if (StringUtils.isNotEmpty(emailOrUsername) && StringUtils.isNotEmpty(password)) { Principal user = (Principal) securityContext.getAuthenticator().doLogin(securityContext.getRequest(), emailOrUsername, password); if (user != null) { logger.log(Level.INFO, "Login successful: {0}", new Object[]{ user }); RestMethodResult methodResult = new RestMethodResult(200); methodResult.addContent(user); return methodResult; } } logger.log(Level.INFO, "Invalid credentials (name, email, password): {0}, {1}, {2}", new Object[]{ name, email, password }); return new RestMethodResult(401); } @Override public Result doGet(PropertyKey sortKey, boolean sortDescending, int pageSize, int page, String offsetId) throws FrameworkException { throw new NotAllowedException(); } @Override public RestMethodResult doPut(Map<String, Object> propertySet) throws FrameworkException { throw new NotAllowedException(); } @Override public RestMethodResult doDelete() throws FrameworkException { throw new NotAllowedException(); } @Override public Resource tryCombineWith(Resource next) throws FrameworkException { return null; } // ----- private methods ----- //~--- get methods ---------------------------------------------------- @Override public Class getEntityClass() { return null; } @Override public String getUriPart() { return "login"; } @Override public String getResourceSignature() { return "_login"; } @Override public boolean isCollectionResource() { return false; } }