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
3e1f1d500dc40471fca9aefc06be40a9833e445e
1,662
java
Java
Mage.Sets/src/mage/cards/d/Disembowel.java
jgalrito/mage
94aa52f4af754ea8ace4ab5d0f4f5b64fda6454d
[ "MIT" ]
1
2018-09-11T23:42:18.000Z
2018-09-11T23:42:18.000Z
Mage.Sets/src/mage/cards/d/Disembowel.java
jgalrito/mage
94aa52f4af754ea8ace4ab5d0f4f5b64fda6454d
[ "MIT" ]
null
null
null
Mage.Sets/src/mage/cards/d/Disembowel.java
jgalrito/mage
94aa52f4af754ea8ace4ab5d0f4f5b64fda6454d
[ "MIT" ]
null
null
null
32.588235
138
0.726233
13,153
package mage.cards.d; import java.util.UUID; import mage.abilities.Ability; import mage.abilities.SpellAbility; import mage.abilities.effects.common.DestroyTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.ComparisonType; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.mageobject.ConvertedManaCostPredicate; import mage.game.Game; import mage.target.common.TargetCreaturePermanent; /** * * @author LoneFox */ public final class Disembowel extends CardImpl { public Disembowel(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{X}{B}"); // Destroy target creature with converted mana cost X. this.getSpellAbility().addEffect(new DestroyTargetEffect()); this.getSpellAbility().addTarget(new TargetCreaturePermanent(new FilterCreaturePermanent("creature with converted mana cost X"))); } @Override public void adjustTargets(Ability ability, Game game) { if(ability instanceof SpellAbility) { ability.getTargets().clear(); int xValue = ability.getManaCostsToPay().getX(); FilterCreaturePermanent filter = new FilterCreaturePermanent("creature with converted mana cost X"); filter.add(new ConvertedManaCostPredicate(ComparisonType.EQUAL_TO, xValue)); ability.addTarget(new TargetCreaturePermanent(filter)); } } public Disembowel(final Disembowel card) { super(card); } @Override public Disembowel copy() { return new Disembowel(this); } }
3e1f1d760802fcb257e2e28193ad8e6c533ea1df
145
java
Java
hub/src/main/java/com/codecademy/eventhub/base/Schema.java
NunoEdgarGFlowHub/EventHub
e0f33dc554fa1f2493982bdf3bc5d7b4825ff9c8
[ "MIT" ]
450
2015-01-04T01:55:29.000Z
2022-03-15T12:34:19.000Z
hub/src/main/java/com/codecademy/eventhub/base/Schema.java
varver/EventHub
27467497ddf36d1cfde03eb4b7d72026ec550890
[ "MIT" ]
2
2015-01-08T09:00:30.000Z
2021-03-19T18:10:19.000Z
hub/src/main/java/com/codecademy/eventhub/base/Schema.java
varver/EventHub
27467497ddf36d1cfde03eb4b7d72026ec550890
[ "MIT" ]
104
2015-01-07T15:53:14.000Z
2021-12-02T07:39:21.000Z
18.125
37
0.703448
13,154
package com.codecademy.eventhub.base; public interface Schema<T> { int getObjectSize(); byte[] toBytes(T t); T fromBytes(byte[] bytes); }
3e1f1da23a8177e145492980334b79aff33ded25
419
java
Java
Task/Queue-Usage/Java/queue-usage-2.java
mullikine/RosettaCodeData
4f0027c6ce83daa36118ee8b67915a13cd23ab67
[ "Info-ZIP" ]
1
2018-11-09T22:08:38.000Z
2018-11-09T22:08:38.000Z
Task/Queue-Usage/Java/queue-usage-2.java
mullikine/RosettaCodeData
4f0027c6ce83daa36118ee8b67915a13cd23ab67
[ "Info-ZIP" ]
null
null
null
Task/Queue-Usage/Java/queue-usage-2.java
mullikine/RosettaCodeData
4f0027c6ce83daa36118ee8b67915a13cd23ab67
[ "Info-ZIP" ]
1
2018-11-09T22:08:40.000Z
2018-11-09T22:08:40.000Z
34.916667
62
0.627685
13,155
import java.util.LinkedList; ... LinkedList queue = new LinkedList(); System.out.println(queue.isEmpty()); // empty test - true queue.add(new Integer(1)); queue.add(new Integer(2)); queue.add(new Integer(3)); System.out.println(queue); // [1, 2, 3] System.out.println(queue.removeFirst()); // 1 System.out.println(queue); // [2, 3] System.out.println(queue.isEmpty()); // false
3e1f1dc2f78750ddcd4bcc5873d7813bd04994c7
5,037
java
Java
xmppserver/src/main/java/org/jivesoftware/openfire/spi/LegacyConnectionAcceptor.java
wwjiang007/Openfire
e1d6b670424d3db9714781c6bfd18cc1c7219542
[ "Apache-2.0" ]
2,496
2015-01-02T16:13:08.000Z
2022-03-31T08:05:23.000Z
xmppserver/src/main/java/org/jivesoftware/openfire/spi/LegacyConnectionAcceptor.java
wwjiang007/Openfire
e1d6b670424d3db9714781c6bfd18cc1c7219542
[ "Apache-2.0" ]
993
2015-01-10T10:15:39.000Z
2022-03-31T08:33:30.000Z
xmppserver/src/main/java/org/jivesoftware/openfire/spi/LegacyConnectionAcceptor.java
wwjiang007/Openfire
e1d6b670424d3db9714781c6bfd18cc1c7219542
[ "Apache-2.0" ]
1,539
2015-01-04T13:11:28.000Z
2022-03-31T07:35:27.000Z
37.385185
178
0.631266
13,156
package org.jivesoftware.openfire.spi; import org.jivesoftware.openfire.Connection; import org.jivesoftware.openfire.net.SocketAcceptThread; import org.jivesoftware.util.SystemProperty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.BindException; import java.time.Duration; import java.time.temporal.ChronoUnit; /** * A connection acceptor that employs the legacy, pre-MINA/NIO socket implementation of Openfire. * * @author Guus der Kinderen, nnheo@example.com * @deprecated Used only for S2S, which should be be ported to NIO. */ @Deprecated public class LegacyConnectionAcceptor extends ConnectionAcceptor { private final Logger Log = LoggerFactory.getLogger( LegacyConnectionAcceptor.class ); public static final SystemProperty<Duration> STARTUP_RETRY_DELAY = SystemProperty.Builder.ofType(Duration.class) .setKey("xmpp.server.startup.retry.delay") .setDefaultValue(Duration.ofMillis(2000)) .setMinValue(Duration.ofMillis(-1)) .setChronoUnit(ChronoUnit.MILLIS) .setDynamic(Boolean.TRUE) .build(); private SocketAcceptThread socketAcceptThread; /** * Constructs a new instance which will accept new connections based on the provided configuration. * <p> * The provided configuration is expected to be immutable. ConnectionAcceptor instances are not expected to handle * changes in configuration. When such changes are to be applied, an instance is expected to be replaced. * <p> * Newly instantiated ConnectionAcceptors will not accept any connections before {@link #start()} is invoked. * * @param configuration The configuration for connections to be accepted (cannot be null). */ public LegacyConnectionAcceptor( ConnectionConfiguration configuration ) { super( configuration ); } /** * Starts this acceptor by binding the socket acceptor. When the acceptor is already started, a warning will be * logged and the method invocation is otherwise ignored. */ @Override public synchronized void start() { if ( socketAcceptThread != null ) { Log.warn( "Unable to start acceptor (it is already started!)" ); return; } if ( configuration.getMaxThreadPoolSize() > 1 ) { Log.warn( "Configuration allows for up to " + configuration.getMaxThreadPoolSize() + " threads, although implementation is limited to exactly one." ); } doStart(true); } private synchronized void doStart(boolean allowRetry) { try { socketAcceptThread = new SocketAcceptThread(configuration.getPort(), configuration.getBindAddress(), configuration.getTlsPolicy() == Connection.TLSPolicy.legacyMode); socketAcceptThread.setDaemon(true); socketAcceptThread.setPriority(Thread.MAX_PRIORITY); socketAcceptThread.start(); } catch (Exception e) { System.err.println("Error starting " + configuration.getPort() + ": " + e.getMessage()); Log.error("Error starting: " + configuration.getPort(), e); // Reset for future use. if (socketAcceptThread != null) { try { socketAcceptThread.shutdown(); } finally { socketAcceptThread = null; } } if (allowRetry && e instanceof BindException) { // OF-1956: Retry a failed bind after a short delay, to work around restart race conditions. final Duration delay = STARTUP_RETRY_DELAY.getValue(); if (delay != null && !delay.isNegative()) { System.err.println("Retrying to start " + configuration.getPort() + " after a delay of " + delay); Log.error("Retrying to start " + configuration.getPort() + " after a delay of " + delay); try { Thread.sleep( delay.toMillis()); doStart(false); } catch (InterruptedException ex) { Log.error("Restart interrupted.", ex); } } } } } /** * Stops this acceptor by unbinding the socket acceptor. Does nothing when the instance is not started. */ @Override public synchronized void stop() { if ( socketAcceptThread != null ) { try { socketAcceptThread.shutdown(); } finally { socketAcceptThread = null; } } } @Override public synchronized boolean isIdle() { return socketAcceptThread != null; // We're not tracking actual sessions. This is a best effort response. } @Override public synchronized void reconfigure( ConnectionConfiguration configuration ) { this.configuration = configuration; // nothing can be reloaded in this implementation. } }
3e1f1f4073bab35c26294f70fbd1c0ca6b35aca3
2,334
java
Java
src/main/java/com/jsoniter/benchmark/with_long_string/SerThrift.java
wl21st/java-benchmark
cb09458395954e7ee6b93a1d4cb3f8d06720a95c
[ "MIT" ]
14
2017-02-09T05:00:30.000Z
2021-05-10T07:00:46.000Z
src/main/java/com/jsoniter/benchmark/with_long_string/SerThrift.java
wl21st/java-benchmark
cb09458395954e7ee6b93a1d4cb3f8d06720a95c
[ "MIT" ]
5
2017-12-10T09:53:52.000Z
2021-12-09T20:20:32.000Z
src/main/java/com/jsoniter/benchmark/with_long_string/SerThrift.java
wl21st/java-benchmark
cb09458395954e7ee6b93a1d4cb3f8d06720a95c
[ "MIT" ]
10
2017-02-28T02:23:50.000Z
2021-09-03T08:35:29.000Z
34.835821
193
0.714225
13,157
package com.jsoniter.benchmark.with_long_string; import com.jsoniter.benchmark.All; import org.apache.thrift.TException; import org.apache.thrift.TSerializer; import org.apache.thrift.protocol.TCompactProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TIOStreamTransport; import org.junit.Test; import org.openjdk.jmh.Main; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.runner.RunnerException; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.concurrent.TimeUnit; /* Benchmark Mode Cnt Score Error Units SerThrift.ser avgt 5 252140.935 ± 5993.905 ns/op */ @State(Scope.Thread) public class SerThrift { private ThriftTestObject testObject; private ByteArrayOutputStream byteArrayOutputStream; private TProtocol protocol; @Setup(Level.Trial) public void benchSetup(BenchmarkParams params) throws TException { testObject = new ThriftTestObject(); testObject.setField1("0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"); byteArrayOutputStream = new ByteArrayOutputStream(); TCompactProtocol.Factory protocolFactory = new TCompactProtocol.Factory(); protocol = protocolFactory.getProtocol(new TIOStreamTransport(byteArrayOutputStream)); } @Test public void test() throws TException { byte[] output = new TSerializer(new TCompactProtocol.Factory()).serialize(testObject); System.out.println(output.length); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void ser(Blackhole bh) throws TException { for (int i = 0; i < 1000; i++) { byteArrayOutputStream.reset(); testObject.write(protocol); bh.consume(byteArrayOutputStream); } } public static void main(String[] args) throws IOException, RunnerException { All.loadJMH(); Main.main(new String[]{ "with_long_string.SerThrift", "-i", "5", "-wi", "5", "-f", "1", }); } }
3e1f1ff3a0690c5004900746819b83f2ba02a9de
2,411
java
Java
sm-catalog/src/main/java/com/salesmanager/catalog/presentation/tag/ManufacturerImageUrlTag.java
buschmais/adr-starter
6c4f302e3445bd8ccee8a7f0f880c8b3564b013f
[ "Apache-2.0" ]
3
2020-09-16T13:28:33.000Z
2021-11-15T12:27:20.000Z
sm-catalog/src/main/java/com/salesmanager/catalog/presentation/tag/ManufacturerImageUrlTag.java
buschmais/adr-starter
6c4f302e3445bd8ccee8a7f0f880c8b3564b013f
[ "Apache-2.0" ]
null
null
null
sm-catalog/src/main/java/com/salesmanager/catalog/presentation/tag/ManufacturerImageUrlTag.java
buschmais/adr-starter
6c4f302e3445bd8ccee8a7f0f880c8b3564b013f
[ "Apache-2.0" ]
1
2022-01-31T10:42:55.000Z
2022-01-31T10:42:55.000Z
25.378947
98
0.790543
13,158
package com.salesmanager.catalog.presentation.tag; import com.salesmanager.catalog.business.integration.core.service.MerchantStoreInfoService; import com.salesmanager.catalog.model.integration.core.MerchantStoreInfo; import com.salesmanager.catalog.presentation.model.manufacturer.Manufacturer; import com.salesmanager.catalog.presentation.util.UriUtils; import com.salesmanager.core.integration.merchant.MerchantStoreDTO; import com.salesmanager.common.presentation.constants.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.tags.RequestContextAwareTag; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspException; public class ManufacturerImageUrlTag extends RequestContextAwareTag { /** * */ private static final long serialVersionUID = 6319855234657139862L; private static final Logger LOGGER = LoggerFactory.getLogger(ManufacturerImageUrlTag.class); private String imageName; private String imageType; private Manufacturer manufacturer; @Autowired private MerchantStoreInfoService merchantStoreInfoService; @Autowired private UriUtils uriUtils; public int doStartTagInternal() throws JspException { try { HttpServletRequest request = (HttpServletRequest) pageContext .getRequest(); MerchantStoreDTO storeDTO = (MerchantStoreDTO) request.getAttribute(Constants.ADMIN_STORE_DTO); MerchantStoreInfo merchantStore = this.merchantStoreInfoService.findbyCode(storeDTO.getCode()); StringBuilder imagePath = new StringBuilder(); String baseUrl = uriUtils.getStoreUri(merchantStore, request.getContextPath()); imagePath.append(baseUrl); pageContext.getOut().print(imagePath.toString()); } catch (Exception ex) { LOGGER.error("Error while getting content url", ex); } return SKIP_BODY; } public int doEndTag() { return EVAL_PAGE; } public void setImageName(String imageName) { this.imageName = imageName; } public String getImageName() { return imageName; } public void setImageType(String imageType) { this.imageType = imageType; } public String getImageType() { return imageType; } public Manufacturer getManufacturer() { return manufacturer; } public void setManufacturer(Manufacturer manufacturer) { this.manufacturer = manufacturer; } }
3e1f20a048faf3e04a2a40134f430271c5e5b9c1
5,824
java
Java
marvellib/src/main/java/com/ywqln/marvellib/net/util/HttpsUtil.java
2249692487/Marvel
e55152e71ae147b1c9273ad6208e973185be3983
[ "MIT" ]
1
2019-02-17T06:30:48.000Z
2019-02-17T06:30:48.000Z
marvellib/src/main/java/com/ywqln/marvellib/net/util/HttpsUtil.java
2249692487/Marvel
e55152e71ae147b1c9273ad6208e973185be3983
[ "MIT" ]
null
null
null
marvellib/src/main/java/com/ywqln/marvellib/net/util/HttpsUtil.java
2249692487/Marvel
e55152e71ae147b1c9273ad6208e973185be3983
[ "MIT" ]
null
null
null
33.090909
99
0.596154
13,159
package com.ywqln.marvellib.net.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.ArrayList; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; /** * 描述:Https SSL信任及相关工具. * <p> * * @author yanwenqiang. * @date 2019/1/23 */ public class HttpsUtil { private final static String DEFAULT_PASS = "123456"; private File mBksFile; private File[] mCerFile; private String mPass; private InputStream mBks; private InputStream[] mCers; private X509TrustManager x509; public HttpsUtil(File... files) { this(null, files); } public HttpsUtil(File bksFile, File... cerFile) { this(DEFAULT_PASS, bksFile, cerFile); } public HttpsUtil(String pass, File bksFile, File... cerFile) { mBksFile = bksFile; mCerFile = cerFile; mPass = pass; initBksAndCer(); } private void initBksAndCer() { try { mPass = mPass == null ? DEFAULT_PASS : mPass; if (mBksFile != null) { mBks = new FileInputStream(mBksFile); } ArrayList<InputStream> cers = new ArrayList<>(); for (File file : mCerFile) { cers.add(new FileInputStream(file)); } if (!cers.isEmpty()) { mCers = cers.toArray(new InputStream[]{}); } } catch (FileNotFoundException e) { e.printStackTrace(); } } //获取SSLSocketFactory public SSLSocketFactory getSSLSocketFactory() { try { SSLContext tls = SSLContext.getInstance("TLS"); tls.init(mBks == null ? null : getKeyManager(), getTrustManager(), new SecureRandom()); return tls.getSocketFactory(); } catch (NoSuchAlgorithmException | KeyManagementException e) { e.printStackTrace(); } return null; } private KeyManager[] getKeyManager() { try { KeyStore keyStore = KeyStore.getInstance("BKS"); keyStore.load(mBks, mPass.toCharArray()); KeyManagerFactory keyManager = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm()); keyManager.init(keyStore, mPass.toCharArray()); mBks.close(); return keyManager.getKeyManagers(); } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | IOException | CertificateException e) { e.printStackTrace(); } return null; } //获取TrustManager public TrustManager[] getTrustManager() { try { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); int alias = 0; if (mCers != null) { for (InputStream is : mCers) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate certificate = cf.generateCertificate(is); keyStore.setCertificateEntry(Integer.toString(alias++), certificate); is.close(); } TrustManagerFactory tmf = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); tmf.init(keyStore); chooseX509(tmf); return tmf.getTrustManagers(); } else { TrustManager[] trustManagers = {new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[]{}; } }}; x509 = (X509TrustManager) trustManagers[0]; return trustManagers; } } catch (NoSuchAlgorithmException | KeyStoreException | IOException | CertificateException e) { e.printStackTrace(); } return null; } private void chooseX509(TrustManagerFactory tmf) { for (TrustManager trustManager : tmf.getTrustManagers()) { if (trustManager instanceof X509TrustManager) { x509 = (X509TrustManager) trustManager; break; } } } public X509TrustManager getX509() { return x509; } public HostnameVerifier hostNameVerifier() { return new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; } }
3e1f20a17424f95f667e25e69db3d0fdaf00f84d
7,800
java
Java
chrome/android/junit/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuCoordinatorTest.java
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/android/junit/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuCoordinatorTest.java
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/android/junit/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuCoordinatorTest.java
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
48.75
98
0.736538
13,160
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.contextmenu; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.when; import android.app.Activity; import android.util.Pair; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.robolectric.Robolectric; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.base.test.util.JniMocker; import org.chromium.blink_public.common.ContextMenuDataMediaType; import org.chromium.chrome.R; import org.chromium.chrome.browser.contextmenu.ChromeContextMenuItem.Item; import org.chromium.chrome.browser.contextmenu.ChromeContextMenuPopulator.ContextMenuGroup; import org.chromium.chrome.browser.contextmenu.RevampedContextMenuCoordinator.ListItemType; import org.chromium.chrome.browser.performance_hints.PerformanceHintsObserver; import org.chromium.chrome.browser.performance_hints.PerformanceHintsObserverJni; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.test.util.browser.Features; import org.chromium.components.embedder_support.contextmenu.ContextMenuParams; import org.chromium.ui.base.ActivityWindowAndroid; import org.chromium.ui.base.WindowAndroid; import org.chromium.ui.modelutil.MVCListAdapter.ModelList; import java.util.ArrayList; import java.util.List; /** * Unit tests for the Revamped context menu. */ @RunWith(BaseRobolectricTestRunner.class) public class RevampedContextMenuCoordinatorTest { @Rule public TestRule mProcessor = new Features.JUnitProcessor(); @Rule public JniMocker mocker = new JniMocker(); @Mock PerformanceHintsObserver.Natives mNativeMock; private RevampedContextMenuCoordinator mCoordinator; private Activity mActivity; private WindowAndroid mWindow; private final Profile mProfile = Mockito.mock(Profile.class); @Before public void setUpTest() { mActivity = Robolectric.setupActivity(Activity.class); mWindow = new ActivityWindowAndroid(mActivity, false); mCoordinator = new RevampedContextMenuCoordinator(0, null); MockitoAnnotations.initMocks(this); mocker.mock(PerformanceHintsObserverJni.TEST_HOOKS, mNativeMock); when(mNativeMock.isContextMenuPerformanceInfoEnabled()).thenReturn(false); } @After public void tearDownTest() { mWindow.destroy(); } @Test public void testGetItemListWithImageLink() { final ContextMenuParams params = new ContextMenuParams( 0, ContextMenuDataMediaType.IMAGE, "", "", "", "", "", "", null, false, 0, 0, 0); List<Pair<Integer, List<ContextMenuItem>>> rawItems = new ArrayList<>(); // Link items List<ContextMenuItem> groupOne = new ArrayList<>(); groupOne.add(new ChromeContextMenuItem(Item.OPEN_IN_NEW_TAB)); groupOne.add(new ChromeContextMenuItem(Item.OPEN_IN_INCOGNITO_TAB)); groupOne.add(new ChromeContextMenuItem(Item.SAVE_LINK_AS)); groupOne.add(new ShareContextMenuItem(R.string.contextmenu_share_link, org.chromium.chrome.R.id.contextmenu_share_link, true)); rawItems.add(new Pair<>(ContextMenuGroup.LINK, groupOne)); // Image Items List<ContextMenuItem> groupTwo = new ArrayList<>(); groupTwo.add(new ChromeContextMenuItem(Item.OPEN_IMAGE_IN_NEW_TAB)); groupTwo.add(new ChromeContextMenuItem(Item.SAVE_IMAGE)); groupTwo.add(new ShareContextMenuItem(R.string.contextmenu_share_image, org.chromium.chrome.R.id.contextmenu_share_image, false)); rawItems.add(new Pair<>(ContextMenuGroup.IMAGE, groupTwo)); mCoordinator.initializeHeaderCoordinatorForTesting(mActivity, params, mProfile); ModelList itemList = mCoordinator.getItemList(mWindow, rawItems, params); assertThat(itemList.get(0).type, equalTo(ListItemType.HEADER)); assertThat(itemList.get(1).type, equalTo(ListItemType.DIVIDER)); assertThat(itemList.get(2).type, equalTo(ListItemType.CONTEXT_MENU_ITEM)); assertThat(itemList.get(3).type, equalTo(ListItemType.CONTEXT_MENU_ITEM)); assertThat(itemList.get(4).type, equalTo(ListItemType.CONTEXT_MENU_ITEM)); assertThat(itemList.get(5).type, equalTo(ListItemType.CONTEXT_MENU_SHARE_ITEM)); assertThat(itemList.get(6).type, equalTo(ListItemType.DIVIDER)); assertThat(itemList.get(7).type, equalTo(ListItemType.CONTEXT_MENU_ITEM)); assertThat(itemList.get(8).type, equalTo(ListItemType.CONTEXT_MENU_ITEM)); assertThat(itemList.get(9).type, equalTo(ListItemType.CONTEXT_MENU_SHARE_ITEM)); } @Test public void testGetItemListWithLink() { // We're testing it for a link, but the mediaType in params is image. That's because if it // isn't image or video, the header mediator tries to get a favicon for us and calls // Profile.getLastUsedRegularProfile(), which throws an exception because native isn't // initialized. mediaType here doesn't have any effect on what we're testing. final ContextMenuParams params = new ContextMenuParams( 0, ContextMenuDataMediaType.IMAGE, "", "", "", "", "", "", null, false, 0, 0, 0); List<Pair<Integer, List<ContextMenuItem>>> rawItems = new ArrayList<>(); // Link items List<ContextMenuItem> groupOne = new ArrayList<>(); groupOne.add(new ChromeContextMenuItem(Item.OPEN_IN_NEW_TAB)); groupOne.add(new ChromeContextMenuItem(Item.OPEN_IN_INCOGNITO_TAB)); groupOne.add(new ChromeContextMenuItem(Item.SAVE_LINK_AS)); groupOne.add(new ShareContextMenuItem(R.string.contextmenu_share_link, org.chromium.chrome.R.id.contextmenu_share_link, true)); rawItems.add(new Pair<>(ContextMenuGroup.LINK, groupOne)); mCoordinator.initializeHeaderCoordinatorForTesting(mActivity, params, mProfile); ModelList itemList = mCoordinator.getItemList(mWindow, rawItems, params); assertThat(itemList.get(0).type, equalTo(ListItemType.HEADER)); assertThat(itemList.get(1).type, equalTo(ListItemType.DIVIDER)); assertThat(itemList.get(2).type, equalTo(ListItemType.CONTEXT_MENU_ITEM)); assertThat(itemList.get(3).type, equalTo(ListItemType.CONTEXT_MENU_ITEM)); assertThat(itemList.get(4).type, equalTo(ListItemType.CONTEXT_MENU_ITEM)); assertThat(itemList.get(5).type, equalTo(ListItemType.CONTEXT_MENU_SHARE_ITEM)); } @Test public void testGetItemListWithVideo() { final ContextMenuParams params = new ContextMenuParams( 0, ContextMenuDataMediaType.VIDEO, "", "", "", "", "", "", null, false, 0, 0, 0); List<Pair<Integer, List<ContextMenuItem>>> rawItems = new ArrayList<>(); // Video items List<ContextMenuItem> groupOne = new ArrayList<>(); groupOne.add(new ChromeContextMenuItem(Item.SAVE_VIDEO)); rawItems.add(new Pair<>(ContextMenuGroup.LINK, groupOne)); mCoordinator.initializeHeaderCoordinatorForTesting(mActivity, params, mProfile); ModelList itemList = mCoordinator.getItemList(mWindow, rawItems, params); assertThat(itemList.get(0).type, equalTo(ListItemType.HEADER)); assertThat(itemList.get(1).type, equalTo(ListItemType.DIVIDER)); assertThat(itemList.get(2).type, equalTo(ListItemType.CONTEXT_MENU_ITEM)); } }
3e1f20d1d58eb184d0528f2fd706f2d8dddda357
1,888
java
Java
yshop-tools/src/main/java/co/yixiang/tools/service/AlipayConfigurationService.java
yaoshengyi/serviceplatform
b03d560650ed9127ed0b1fb8f5ac68c045b256a9
[ "Apache-2.0" ]
null
null
null
yshop-tools/src/main/java/co/yixiang/tools/service/AlipayConfigurationService.java
yaoshengyi/serviceplatform
b03d560650ed9127ed0b1fb8f5ac68c045b256a9
[ "Apache-2.0" ]
null
null
null
yshop-tools/src/main/java/co/yixiang/tools/service/AlipayConfigurationService.java
yaoshengyi/serviceplatform
b03d560650ed9127ed0b1fb8f5ac68c045b256a9
[ "Apache-2.0" ]
null
null
null
29.968254
142
0.764831
13,161
/** * Copyright (C) 2018-2020 * All rights reserved, Designed By www.yixiang.co * 注意: * 本软件为www.yixiang.co开发研制,未经购买不得使用 * 购买后可获得全部源代码(禁止转卖、分享、上传到码云、github等开源平台) * 一经发现盗用、分享等行为,将追究法律责任,后果自负 */ package co.yixiang.tools.service; import co.yixiang.common.service.BaseService; import co.yixiang.tools.domain.AlipayConfiguration; import co.yixiang.tools.service.dto.AlipayConfigurationDto; import co.yixiang.tools.service.dto.AlipayConfigurationQueryCriteria; import org.springframework.data.domain.Pageable; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; import java.util.Map; /** * @author zhoujinlai * @date 2021-09-01 */ public interface AlipayConfigurationService extends BaseService<AlipayConfiguration>{ /** * 查询数据分页 * @param criteria 条件 * @param pageable 分页参数 * @return Map<String,Object> */ Map<String,Object> queryAll(AlipayConfigurationQueryCriteria criteria, Pageable pageable); /** * 查询所有数据不分页 * @param criteria 条件参数 * @return List<AlipayConfigurationDto> */ List<AlipayConfiguration> queryAll(AlipayConfigurationQueryCriteria criteria); /** * 导出数据 * @param all 待导出的数据 * @param response / * @throws IOException / */ void download(List<AlipayConfigurationDto> all, HttpServletResponse response) throws IOException; Boolean saveAlipayConfiguration(AlipayConfiguration resources); Boolean updateAlipayConfiguration(AlipayConfiguration resources); void deleteById(Integer id); String alipayH5Pay(String body, String subject, String outTradeNo, String timeoutExpress, String totalAmount,String appId,String orderId); String alipayTradeAppPay(String subject, String userid, String outTradeNo, String timeoutExpress, String totalAmount,String appId); String refundOrder(String tradeNo, String refundAmount, String appId); }
3e1f233f58939a40ce6750e2c3ccfdd67afb2134
1,439
java
Java
components/org.wso2.carbon.identity.idp.metadata.saml2/src/main/java/org/wso2/carbon/identity/idp/metadata/saml2/ConfigElements.java
Wathsara/identity-metadata-saml2
51d6584c44d87294ade929802520fa916f4aa98c
[ "Apache-2.0" ]
null
null
null
components/org.wso2.carbon.identity.idp.metadata.saml2/src/main/java/org/wso2/carbon/identity/idp/metadata/saml2/ConfigElements.java
Wathsara/identity-metadata-saml2
51d6584c44d87294ade929802520fa916f4aa98c
[ "Apache-2.0" ]
null
null
null
components/org.wso2.carbon.identity.idp.metadata.saml2/src/main/java/org/wso2/carbon/identity/idp/metadata/saml2/ConfigElements.java
Wathsara/identity-metadata-saml2
51d6584c44d87294ade929802520fa916f4aa98c
[ "Apache-2.0" ]
null
null
null
41.114286
91
0.753301
13,162
/* * 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.identity.idp.metadata.saml2; /** * Defines SAML specific String constants */ public class ConfigElements { public static final String ENTITY_DESCRIPTOR = "EntityDescriptor"; public static final String IDPSSO_DESCRIPTOR = "IDPSSODescriptor"; public static final String SSOSERVICE_DESCRIPTOR = "SingleSignOnService"; public static final String NAMEID_FORMAT = "NameIDFormat"; public static final String SLOSERVICE_DESCRIPTOR = "SingleLogoutService"; public static final String XMLSIGNATURE_NS = "http://www.w3.org/2000/09/xmldsig#"; public static final String FED_METADATA_NS = "urn:oasis:names:tc:SAML:2.0:metadata"; public static final String ARTIFACTRESSERVICE_DESCRIPTOR = "ArtifactResolutionService"; }
3e1f240a8704b05804c42d5766d8a46f6057a284
5,778
java
Java
src/main/java/org/mitre/schemastore/porters/mappingImporters/M3MappingImporter.java
TomMD/AIPlatform
57455477b51a25bfaef0362b6efc048623ee32d7
[ "Apache-2.0" ]
1
2020-09-15T11:46:13.000Z
2020-09-15T11:46:13.000Z
src/main/java/org/mitre/schemastore/porters/mappingImporters/M3MappingImporter.java
TomMD/AIPlatform
57455477b51a25bfaef0362b6efc048623ee32d7
[ "Apache-2.0" ]
8
2020-03-20T23:37:27.000Z
2020-09-15T11:50:22.000Z
src/main/java/org/mitre/schemastore/porters/mappingImporters/M3MappingImporter.java
TomMD/AIPlatform
57455477b51a25bfaef0362b6efc048623ee32d7
[ "Apache-2.0" ]
2
2020-09-23T19:37:16.000Z
2020-11-04T03:21:54.000Z
36.1125
142
0.733645
13,163
// Copyright 2008 The MITRE Corporation. ALL RIGHTS RESERVED. package org.mitre.schemastore.porters.mappingImporters; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.zip.ZipInputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.mitre.schemastore.model.Function; import org.mitre.schemastore.model.FunctionImp; import org.mitre.schemastore.model.MappingCell; import org.mitre.schemastore.model.ProjectSchema; import org.mitre.schemastore.model.schemaInfo.HierarchicalSchemaInfo; import org.mitre.schemastore.porters.ImporterException; import org.mitre.schemastore.porters.ImporterException.ImporterExceptionType; import org.mitre.schemastore.porters.URIType; import org.mitre.schemastore.porters.xml.ConvertFromXML; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** Importer for copying mappings from other repositories */ public class M3MappingImporter extends MappingImporter { /** Stores the M3 document to be imported */ private Element element; /** Returns the importer name */ public String getName() { return "M3 Mapping Importer"; } /** Returns the importer description */ public String getDescription() { return "This importer can be used to download a mapping in the M3 format"; } /** Returns the importer URI type */ public URIType getURIType() { return URIType.FILE; } /** Returns the importer URI file types */ public ArrayList<String> getFileTypes() { ArrayList<String> fileTypes = new ArrayList<String>(); fileTypes.add(".m3m"); return fileTypes; } /** Initializes the importer for the specified Document */ final public void initialize(Document document) throws ImporterException { element = document.getDocumentElement(); } /** Initialize the importer */ protected void initialize() throws ImporterException { try { // Uncompresses the file ZipInputStream zipIn = new ZipInputStream(new FileInputStream(new File(uri))); File tempFile = File.createTempFile("M3M", ".xml"); FileOutputStream out = new FileOutputStream(tempFile); zipIn.getNextEntry(); byte data[] = new byte[100000]; int count; while((count = zipIn.read(data)) > 0) out.write(data, 0, count); zipIn.close(); out.close(); // Retrieve the XML document element DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(tempFile); element = document.getDocumentElement(); tempFile.delete(); } catch(Exception e) { throw new ImporterException(ImporterExceptionType.IMPORT_FAILURE, e.getMessage()); } } /** Returns the source schema in the mapping */ public ProjectSchema getSourceSchema() throws ImporterException { try { return ConvertFromXML.getSourceSchema(element); } catch(Exception e) { throw new ImporterException(ImporterExceptionType.IMPORT_FAILURE, e.getMessage()); } } /** Returns the target schema in the mapping */ public ProjectSchema getTargetSchema() throws ImporterException { try { return ConvertFromXML.getTargetSchema(element); } catch(Exception e) { throw new ImporterException(ImporterExceptionType.IMPORT_FAILURE, e.getMessage()); } } /** Retrieves the elements with the specified label */ private ArrayList<Element> getElements(String label) { ArrayList<Element> elements = new ArrayList<Element>(); NodeList elementList = element.getElementsByTagName(label); if (elementList != null) { for (int i = 0; i < elementList.getLength(); i++) { Node node = elementList.item(i); if (node instanceof Element) elements.add((Element)node); } } return elements; } /** Returns the imported functions */ public HashMap<Function,ArrayList<FunctionImp>> getFunctions() throws ImporterException { try { HashMap<Function,ArrayList<FunctionImp>> functions = new HashMap<Function,ArrayList<FunctionImp>>(); for (Element element : getElements("Function")) { Function function = ConvertFromXML.getFunction(element); ArrayList<FunctionImp> functionImps = ConvertFromXML.getFunctionImps(element); functions.put(function, functionImps); } return functions; } catch(Exception e) { throw new ImporterException(ImporterExceptionType.IMPORT_FAILURE, e.getMessage()); } } /** Returns the imported mapping cells */ public ArrayList<MappingCell> getMappingCells() throws ImporterException { // Clear out the unidentified mapping cells unidentifiedMappingCellPaths.clear(); try { // Get the source and target info HierarchicalSchemaInfo sourceInfo = new HierarchicalSchemaInfo(client.getSchemaInfo(source.getId()), getSourceSchema().geetSchemaModel()); HierarchicalSchemaInfo targetInfo = new HierarchicalSchemaInfo(client.getSchemaInfo(target.getId()), getTargetSchema().geetSchemaModel()); // Generate the list of mapping cells ArrayList<MappingCell> mappingCells = new ArrayList<MappingCell>(); for (Element element : getElements("MappingCell")) { // Gets the imported mapping cell MappingCell mappingCell = ConvertFromXML.getMappingCell(element, sourceInfo, targetInfo); if (mappingCell==null) unidentifiedMappingCellPaths.add(ConvertFromXML.getMappingCellPaths(element)); else mappingCells.add(mappingCell); } return mappingCells; } catch(Exception e) { throw new ImporterException(ImporterExceptionType.IMPORT_FAILURE, e.getMessage()); } } }
3e1f2589e0f7eebfe68aefab41d9e76cf3259350
982
java
Java
src/main/java/dev/gigaherz/eyes/InitiateJumpscarePacket.java
Kasualix/EyesInTheDarkness
2df7b0415908d46fc16b7b0b94294f8be974114e
[ "BSD-3-Clause" ]
null
null
null
src/main/java/dev/gigaherz/eyes/InitiateJumpscarePacket.java
Kasualix/EyesInTheDarkness
2df7b0415908d46fc16b7b0b94294f8be974114e
[ "BSD-3-Clause" ]
null
null
null
src/main/java/dev/gigaherz/eyes/InitiateJumpscarePacket.java
Kasualix/EyesInTheDarkness
2df7b0415908d46fc16b7b0b94294f8be974114e
[ "BSD-3-Clause" ]
null
null
null
23.380952
92
0.662933
13,164
package dev.gigaherz.eyes; import dev.gigaherz.eyes.client.ClientMessageHandler; import net.minecraft.network.FriendlyByteBuf; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class InitiateJumpscarePacket { public double px; public double py; public double pz; public InitiateJumpscarePacket(double px, double py, double pz) { this.px = px; this.py = py; this.pz = pz; } public InitiateJumpscarePacket(FriendlyByteBuf buf) { this.px = buf.readDouble(); this.py = buf.readDouble(); this.pz = buf.readDouble(); } public void encode(FriendlyByteBuf buf) { buf.writeDouble(px); buf.writeDouble(py); buf.writeDouble(pz); } public boolean handle(Supplier<NetworkEvent.Context> context) { context.get().enqueueWork(() -> ClientMessageHandler.handleInitiateJumpscare(this)); return true; } }
3e1f262d6154c10bd8ea68308955d9f25ff902fe
5,576
java
Java
src/main/java/com/github/fujiyamakazan/zabuton/tool/AbstractWebContainerStarter.java
fujiyamakazan/zabuton
eade17a85956705777493b261ef816245c7190e1
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/fujiyamakazan/zabuton/tool/AbstractWebContainerStarter.java
fujiyamakazan/zabuton
eade17a85956705777493b261ef816245c7190e1
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/fujiyamakazan/zabuton/tool/AbstractWebContainerStarter.java
fujiyamakazan/zabuton
eade17a85956705777493b261ef816245c7190e1
[ "Apache-2.0" ]
null
null
null
25.577982
97
0.585545
13,165
package com.github.fujiyamakazan.zabuton.tool; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Writer; import java.net.HttpURLConnection; import java.net.URL; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.fujiyamakazan.zabuton.util.jframe.JFrameUtils; /** * Webコンテナを起動します。 * 既にポートが利用されていないかをチェックします。 * ポートが利用されていても、同一アプリケーションでなければ、 * 空きポートでリトライします。 * * @author fujiyama */ public abstract class AbstractWebContainerStarter { private static final Logger log = LoggerFactory.getLogger(AbstractWebContainerStarter.class); /** アプリケーションクラスの名前を確認できる画面のURL。 */ private static final String APP_INFO = "/app-info"; private static final int DEFAULT_PORT = 8080; private final Class<?> appClass; private boolean running = false; public boolean isRunning() { return running; } private int port; private String subParams; public AbstractWebContainerStarter(Class<?> appClass) { this.appClass = appClass; this.port = getPortStart(); } public AbstractWebContainerStarter(Class<?> appClass, String subParams) { this.appClass = appClass; this.subParams = subParams; this.port = getPortStart(); } protected int getPortStart() { return DEFAULT_PORT; } /** * ポートをチェックして、Webコンテナを開始します。 */ public void start() { int retryCount = 0; while (this.running == false) { try { /* 起動を試みる */ tryStartServer(retryCount); log.info("起動成功"); this.running = true; return; } catch (ApplicationAlreadyException e) { JFrameUtils.showErrorDialog("アプリケーションは起動中です。"); System.exit(0); } catch (PortAlreadyException e) { /* スキャン続行 */ port = port + 1; } /* リトライ制限回数を超えていれば終了する */ if (retryCount++ > 10) { JFrameUtils.showErrorDialog("利用できるポートが見つかりませんでした。"); System.exit(0); } } } private void tryStartServer(int retryCount) throws ApplicationAlreadyException, PortAlreadyException { /* * ポートの使用状況を確認する */ String classNameOnHtml = ""; boolean portNoUsed = false; HttpURLConnection con = null; try { URL url = new URL(getUrlRoot() + APP_INFO); con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.connect(); try (InputStream is = con.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is))) { StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } classNameOnHtml = sb.toString(); } } catch (Exception e) { log.info("port=" + port + "に既存のアプリケーションは起動していません。"); portNoUsed = true; } finally { if (con != null) { con.disconnect(); } } if (portNoUsed == false) { if (StringUtils.equals(classNameOnHtml, appClass.getName())) { log.warn("port=" + port + "に同じアプリケーションが起動しています。"); throw new ApplicationAlreadyException(); } else { log.info("port=" + port + "に異なるアプリが起動しています。>スキャン続行"); throw new PortAlreadyException(); } } /* アプリケーションを特定するためのサーブレット */ AppInfoServlet appInfoServlet = new AppInfoServlet(appClass); /* サーバーを起動する */ startServer(port, appInfoServlet, APP_INFO, appClass); } protected abstract void startServer( int port, AppInfoServlet appInfoServlet, String appInfoUrl, Class<?> appClass) throws PortAlreadyException; /** * ブラウザで開くURLを返す。 * @return URL */ public String getUrl() { if (StringUtils.isNotEmpty(subParams)) { return getUrlRoot() + subParams; } return getUrlRoot(); } private String getUrlRoot() { return "http://localhost:" + port + "/"; } protected static final class AppInfoServlet extends HttpServlet { private final Class<?> appClass; private static final long serialVersionUID = 1L; public AppInfoServlet(Class<?> appClass) { this.appClass = appClass; } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Writer w = resp.getWriter(); w.write(appClass.getName()); w.flush(); } } /** * portが使用済みの時にthrowする例外です。 */ public class PortAlreadyException extends Exception { private static final long serialVersionUID = 1L; } /** * アプリケーションが起動済みの時にthrowする例外です。 */ public class ApplicationAlreadyException extends Exception { private static final long serialVersionUID = 1L; } }
3e1f26801f2eeedc7387924bc456adc98743bf78
1,054
java
Java
javafx-d3-demo/src/test/java/org/treez/javafxd3/d3/color/RgbColorTest.java
saschapojot/javafx-d3
db31187e92ea12f74fe43cb18e5314ec4fc4763d
[ "BSD-3-Clause" ]
104
2015-11-17T17:44:14.000Z
2022-03-25T06:26:22.000Z
javafx-d3-demo/src/test/java/org/treez/javafxd3/d3/color/RgbColorTest.java
saschapojot/javafx-d3
db31187e92ea12f74fe43cb18e5314ec4fc4763d
[ "BSD-3-Clause" ]
12
2015-10-15T17:42:50.000Z
2019-07-12T07:38:02.000Z
javafx-d3-demo/src/test/java/org/treez/javafxd3/d3/color/RgbColorTest.java
saschapojot/javafx-d3
db31187e92ea12f74fe43cb18e5314ec4fc4763d
[ "BSD-3-Clause" ]
32
2015-11-30T15:42:44.000Z
2021-05-31T16:17:17.000Z
22.913043
52
0.680266
13,166
package org.treez.javafxd3.d3.color; import org.treez.javafxd3.d3.color.Colors; import org.treez.javafxd3.d3.color.HSLColor; import org.treez.javafxd3.d3.color.RGBColor; import org.treez.javafxd3.d3.AbstractTestCase; /** * Tests the class RgbColor */ public class RgbColorTest extends AbstractTestCase { @Override public void doTest() { Colors colors = new Colors(engine); RGBColor rgb = colors.rgb("#ff0000"); assertEquals(255, rgb.r()); assertEquals(0, rgb.g()); assertEquals(0, rgb.b()); rgb = rgb.darker(); assertTrue(rgb.r() < 255); rgb = rgb.brighter().brighter(); assertEquals(255, rgb.r()); HSLColor hsl = rgb.hsl(); System.out.println(hsl.h()); System.out.println(hsl.s()); System.out.println(hsl.l()); RGBColor rgb2 = colors.rgb(0, 0, 255); assertEquals(0, rgb2.r()); assertEquals(0, rgb2.g()); assertEquals(255, rgb2.b()); System.out.println(rgb2.toHexaString()); RGBColor rgb3 = colors.rgb(hsl); assertEquals(255, rgb3.r()); assertEquals(0, rgb3.g()); assertEquals(0, rgb3.b()); } }
3e1f275350b5eb6fda3d4991cea8e6bbd76e14ed
689
java
Java
src/test/java/org/bitsofinfo/hazelcast/discovery/consul/ManualRunner.java
Verdoso/hazelcast-consul-discovery-spi
024da5ae0e373ac5338b96bc115805d2957d9785
[ "Apache-2.0" ]
53
2015-11-26T20:23:57.000Z
2020-10-08T08:47:11.000Z
src/test/java/org/bitsofinfo/hazelcast/discovery/consul/ManualRunner.java
Verdoso/hazelcast-consul-discovery-spi
024da5ae0e373ac5338b96bc115805d2957d9785
[ "Apache-2.0" ]
31
2016-01-20T20:50:32.000Z
2021-03-02T18:42:03.000Z
src/test/java/org/bitsofinfo/hazelcast/discovery/consul/ManualRunner.java
Verdoso/hazelcast-consul-discovery-spi
024da5ae0e373ac5338b96bc115805d2957d9785
[ "Apache-2.0" ]
25
2016-01-06T19:35:20.000Z
2022-02-09T17:26:34.000Z
24.607143
84
0.773585
13,167
package org.bitsofinfo.hazelcast.discovery.consul; import com.hazelcast.config.ClasspathXmlConfig; import com.hazelcast.config.Config; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; /** * Simple class for manually spawning hz instances and watching what happens * as they discover one another * * @author bitsofinfo * */ public class ManualRunner { public static void main(String[] args) throws Exception { Config conf =new ClasspathXmlConfig("hazelcast-consul-discovery-spi-example.xml"); HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(conf); Thread.currentThread().sleep(300000); System.exit(0); } }
3e1f280e2acf6da7fcde98a8ad06df18b6b6aa3f
787
java
Java
Introduction_to_Java_Programming/src/chapter02/check_point/CheckPoint02_13.java
emaphis/Introduction_to_Java_Programming
616b285e88c185c60751d12d40d3d07e9dd3dc22
[ "MIT" ]
null
null
null
Introduction_to_Java_Programming/src/chapter02/check_point/CheckPoint02_13.java
emaphis/Introduction_to_Java_Programming
616b285e88c185c60751d12d40d3d07e9dd3dc22
[ "MIT" ]
null
null
null
Introduction_to_Java_Programming/src/chapter02/check_point/CheckPoint02_13.java
emaphis/Introduction_to_Java_Programming
616b285e88c185c60751d12d40d3d07e9dd3dc22
[ "MIT" ]
null
null
null
24.59375
84
0.634053
13,168
/* * Check Point. */ package chapter02.check_point; /** * * @author emaph */ public class CheckPoint02_13 { // 2.13.1 How do you obtain the current second, minute, and hour? public static void main(String[] args) { long totalMilliseconds = System.currentTimeMillis(); // Compute the current second long totalSeconds = totalMilliseconds / 1000; long currentSecond = totalSeconds % 60; // Compute the current minute long totalMinutes = totalSeconds / 60; long currentMinute = totalMinutes % 60; // Compute the current hour long totalHours = totalMinutes / 60; long currentHour = totalHours % 24; System.out.println(currentHour + ":" + currentMinute + ":" + currentSecond); } }
3e1f29a402a1d8ac4e08ecc1059fc830be605f3e
546
java
Java
src/main/java/cn/hmxz/modules/wx/enums/ArticleTypeEnum.java
MrRabblt/wx-api
6baf86451fced59933f9b897025b8962858b6dec
[ "Apache-2.0" ]
null
null
null
src/main/java/cn/hmxz/modules/wx/enums/ArticleTypeEnum.java
MrRabblt/wx-api
6baf86451fced59933f9b897025b8962858b6dec
[ "Apache-2.0" ]
null
null
null
src/main/java/cn/hmxz/modules/wx/enums/ArticleTypeEnum.java
MrRabblt/wx-api
6baf86451fced59933f9b897025b8962858b6dec
[ "Apache-2.0" ]
null
null
null
15.166667
51
0.496337
13,169
package cn.hmxz.modules.wx.enums; /** * 定义文章类型 */ public enum ArticleTypeEnum { /** * 普通文章 */ COMMON(1), /** * 帮助中心文章 */ QUESTION(5); /** * 数据库属性值 */ private int value; ArticleTypeEnum(int type) { this.value = type; } public int getValue() { return this.value; } public static ArticleTypeEnum of(String name) { try { return ArticleTypeEnum.valueOf(name); } catch (Exception e) { return null; } } }
3e1f29cd29197dece989257613d7a7c78fe64ada
568
java
Java
src/main/java/com/zhihei/basicknowledge/javabasic/thread/StringBufferWithoutSync.java
zkydrx/mypractices
894d3d61b3e4a4e5e13ca3f8338d0ac0c4818f07
[ "Apache-2.0" ]
null
null
null
src/main/java/com/zhihei/basicknowledge/javabasic/thread/StringBufferWithoutSync.java
zkydrx/mypractices
894d3d61b3e4a4e5e13ca3f8338d0ac0c4818f07
[ "Apache-2.0" ]
1
2020-06-15T20:06:08.000Z
2020-06-15T20:06:08.000Z
src/main/java/com/zhihei/basicknowledge/javabasic/thread/StringBufferWithoutSync.java
zkydrx/mypractices
894d3d61b3e4a4e5e13ca3f8338d0ac0c4818f07
[ "Apache-2.0" ]
null
null
null
24.695652
76
0.630282
13,170
package com.zhihei.basicknowledge.javabasic.thread; public class StringBufferWithoutSync { public void add(String str1, String str2) { //StringBuffer是线程安全,由于sb只会在append方法中使用,不可能被其他线程引用 //因此sb属于不可能共享的资源,JVM会自动消除内部的锁 StringBuffer sb = new StringBuffer(); sb.append(str1).append(str2); } public static void main(String[] args) { StringBufferWithoutSync withoutSync = new StringBufferWithoutSync(); for (int i = 0; i < 1000; i++) { withoutSync.add("aaa", "bbb"); } } }
3e1f2ac66aca757b64237a9bab832383b6b06905
7,992
java
Java
ssemi/src/home/beans/dao/QnaDao.java
SOL-hub/semi
72e2ee2a4ac486729e0e6bea578347bc18415a2b
[ "MIT" ]
1
2020-07-06T04:29:28.000Z
2020-07-06T04:29:28.000Z
ssemi/src/home/beans/dao/QnaDao.java
SOL-hub/semi
72e2ee2a4ac486729e0e6bea578347bc18415a2b
[ "MIT" ]
9
2020-07-08T01:45:23.000Z
2020-07-20T00:38:44.000Z
ssemi/src/home/beans/dao/QnaDao.java
SOL-hub/semi
72e2ee2a4ac486729e0e6bea578347bc18415a2b
[ "MIT" ]
null
null
null
30.62069
321
0.660786
13,171
package home.beans.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Types; import java.util.ArrayList; import java.util.List; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import home.beans.dto.MemberDto; import home.beans.dto.QnaDto; import home.beans.dto.QnaWithMemberDto; import home.beans.dto.QnaDto; public class QnaDao { private static DataSource src;// 리모컨 선언 static { try { Context ctx = new InitialContext();// 탐색 도구 Context env = (Context) ctx.lookup("java:/comp/env");// Context 설정 탐색 src = (DataSource) env.lookup("jdbc/oracle"); } catch (NamingException e) { e.printStackTrace(); } } // 연결 메소드 public Connection getConnection() throws Exception { return src.getConnection(); } // 목록 메소드 public List<QnaWithMemberDto> getList(int start, int finish) throws Exception{ Connection con = getConnection(); String sql = "SELECT * FROM(" + "SELECT ROWNUM rn, T.* FROM(" + "SELECT q.*, m.MEMBER_NO, m.MEMBER_ID " + "FROM qna q INNER JOIN MEMBER m ON q.QNA_WRITER = m.MEMBER_no and q.QNA_TITLE = '상품문의' CONNECT BY PRIOR qna_no=super_no " + "START WITH super_no IS NULL ORDER SIBLINGS BY group_no DESC, qna_no ASC" + ")T" + " ) WHERE rn BETWEEN ? and ?"; PreparedStatement ps = con.prepareStatement(sql); ps.setInt(1, start); ps.setInt(2, finish); ResultSet rs = ps.executeQuery(); List<QnaWithMemberDto> list = new ArrayList<>(); while(rs.next()) { QnaWithMemberDto qmdto = new QnaWithMemberDto(rs); list.add(qmdto); } con.close(); return list; } // 목록 메소드 public List<QnaWithMemberDto> getList2(int start, int finish) throws Exception{ Connection con = getConnection(); String sql = "SELECT * FROM(SELECT ROWNUM rn, T.* FROM(SELECT q.*, m.MEMBER_NO, m.MEMBER_ID " + "FROM qna q INNER JOIN MEMBER m ON q.QNA_WRITER = m.MEMBER_no and q.QNA_TITLE ='공지사항' CONNECT BY PRIOR qna_no=super_no " + "START WITH super_no IS NULL ORDER SIBLINGS BY group_no DESC, qna_no ASC)T ) WHERE rn BETWEEN ? and ?"; PreparedStatement ps = con.prepareStatement(sql); ps.setInt(1, start); ps.setInt(2, finish); ResultSet rs = ps.executeQuery(); List<QnaWithMemberDto> list = new ArrayList<>(); while(rs.next()) { QnaWithMemberDto qmdto = new QnaWithMemberDto(rs); list.add(qmdto); } con.close(); return list; } // 검색 메소드 public List<QnaWithMemberDto> search(String type, String keyword, int start, int finish) throws Exception{ Connection con = getConnection(); String sql = "SELECT * FROM(SELECT ROWNUM rn, T.* FROM(SELECT q.*, m.MEMBER_NO, m.MEMBER_ID FROM qna q INNER JOIN MEMBER m ON q.QNA_WRITER = m.MEMBER_no WHERE Instr(m.member_id,?)>0 CONNECT BY PRIOR qna_no=super_no START WITH super_no IS NULL ORDER SIBLINGS BY group_no DESC, qna_no ASC)T ) WHERE rn BETWEEN ? and ?"; sql = sql.replace("#1", type); PreparedStatement ps = con.prepareStatement(sql); ps.setString(1, keyword); ps.setInt(2, start); ps.setInt(3, finish); ResultSet rs = ps.executeQuery(); List<QnaWithMemberDto> list = new ArrayList<>(); while(rs.next()) { QnaWithMemberDto qmdto = new QnaWithMemberDto(rs); list.add(qmdto); } con.close(); return list; } // public List<QnaWithMemberDto> getList() throws Exception { // Connection con = getConnection(); // String sql = "SELECT*FROM qna ORDER BY qna_no DESC "; // PreparedStatement ps = con.prepareStatement(sql); // ResultSet rs = ps.executeQuery(); // // List<QnaWithMemberDto> list = new ArrayList<>(); // while (rs.next()) { // QnaWithMemberDto qmdto = new QnaWithMemberDto(rs); // list.add(qmdto); // } // con.close(); // return list; // } // 개수 조회 메소드 public int getCount() throws Exception { Connection con = getConnection(); String sql = "SELECT count(*) FROM qna"; PreparedStatement ps = con.prepareStatement(sql); ResultSet rs = ps.executeQuery(); rs.next(); // 데이터는 무조건 1개가 나오므로 이동 int count = rs.getInt(1); // 또는 rs.getInt("count(*)"); con.close(); return count; } public int getCount(String type, String keyword) throws Exception { Connection con = getConnection(); String sql = "SELECT count(*) FROM qna WHERE instr(#1,?)>0"; sql = sql.replace("#1", type); PreparedStatement ps = con.prepareStatement(sql); ps.setString(1, keyword); ResultSet rs = ps.executeQuery(); rs.next(); // 데이터는 무조건 1개가 나오므로 이동 int count = rs.getInt(1); // 또는 rs.getInt("count(*)"); con.close(); return count; } // 시퀀스 생성 // - dual 테이블은 오라클이 제공하는 임시 테이블 public int getSequence() throws Exception { Connection con = getConnection(); String sql = "SELECT qna_seq.nextval FROM dual"; PreparedStatement ps = con.prepareStatement(sql); ResultSet rs = ps.executeQuery(); rs.next(); int seq = rs.getInt(1);// rs.getInt("NEXTVAL"); con.close(); return seq; } // 단일조회 (Qna_content.jsp) public QnaDto get(int qna_no) throws Exception { Connection con = getConnection(); String sql = "SELECT*FROM qna WHERE qna_no=?"; PreparedStatement ps = con.prepareStatement(sql); ps.setInt(1, qna_no); ResultSet rs = ps.executeQuery(); QnaDto qdto = rs.next() ? new QnaDto(rs) : null; // 3항 연산자 con.close(); return qdto; } // 단일조회2 (Qna_content.jsp) public QnaDto get_id(int qna_writer) throws Exception { Connection con = getConnection(); String sql = "SELECT*FROM qna WHERE qna_writer=?"; PreparedStatement ps = con.prepareStatement(sql); ps.setInt(1, qna_writer); ResultSet rs = ps.executeQuery(); QnaDto qdto = rs.next() ? new QnaDto(rs) : null; // 3항 연산자 con.close(); return qdto; } // 아이디 단일조회 (member_no 대신 아이디 불러오기) public String getWriter(int member_no) throws Exception { Connection con = getConnection(); String sql = "SELECT member.member_id FROM member inner join qna on member.member_no=qna.qna_writer WHERE member_no=?"; PreparedStatement ps = con.prepareStatement(sql); ps.setInt(1, member_no); ResultSet rs = ps.executeQuery(); rs.next(); String member_id = rs.getString(1); con.close(); return member_id; } // 게시글 등록 메소드 public void write(QnaDto qdto) throws Exception { if (qdto.getSuper_no() == 0) { qdto.setGroup_no(qdto.getQna_no()); } else { QnaDto find = this.get(qdto.getSuper_no()); qdto.setGroup_no(find.getGroup_no()); qdto.setDepth(find.getDepth() + 1); } Connection con = getConnection(); String sql = "INSERT INTO qna(qna_no, qna_writer, qna_title, qna_content, group_no, depth, super_no) VALUES(?, ?, ?, ?, ?, ?, ?) "; PreparedStatement ps = con.prepareStatement(sql); ps.setInt(1, qdto.getQna_no()); ps.setInt(2, qdto.getQna_writer()); ps.setString(3, qdto.getQna_title()); ps.setString(4, qdto.getQna_content()); ps.setInt(5, qdto.getGroup_no()); ps.setInt(6, qdto.getDepth()); if (qdto.getSuper_no() == 0) { // 새글이면 ps.setNull(7, Types.NULL); } else { // 답글이면 ps.setInt(7, qdto.getSuper_no()); } ps.execute(); con.close(); } // 수정 메소드 public void edit(QnaDto qdto) throws Exception { Connection con = getConnection(); String sql = "UPDATE qna SET qna_title=?, qna_content=? WHERE qna_no=?"; PreparedStatement ps = con.prepareStatement(sql); ps.setString(1, qdto.getQna_title()); ps.setString(2, qdto.getQna_content()); ps.setInt(3, qdto.getQna_no()); ps.execute(); con.close(); } // 게시글 삭제 public void delete(int qna_no) throws Exception { Connection con = getConnection(); String sql = "DELETE FROM qna WHERE qna_no=?"; PreparedStatement ps = con.prepareStatement(sql); ps.setInt(1, qna_no); ps.execute(); con.close(); } }
3e1f2ad118faa4cfe4b5b23d062b81e6975c1124
3,718
java
Java
src/contrib/fairscheduler/src/java/org/apache/hadoop/mapred/TaskSelector.java
moyue/hadoop
947640284fd9b7cfa967b82fa08f755416f42db5
[ "Apache-2.0" ]
194
2015-01-07T11:12:52.000Z
2022-03-14T09:19:24.000Z
src/contrib/fairscheduler/src/java/org/apache/hadoop/mapred/TaskSelector.java
moyue/hadoop
947640284fd9b7cfa967b82fa08f755416f42db5
[ "Apache-2.0" ]
1
2017-10-19T16:57:05.000Z
2017-10-19T16:57:05.000Z
src/contrib/fairscheduler/src/java/org/apache/hadoop/mapred/TaskSelector.java
moyue/hadoop
947640284fd9b7cfa967b82fa08f755416f42db5
[ "Apache-2.0" ]
172
2015-01-14T19:25:48.000Z
2022-02-24T02:42:02.000Z
36.45098
80
0.72808
13,172
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapred; import java.io.IOException; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; /** * A pluggable object for selecting tasks to run from a {@link JobInProgress} on * a given {@link TaskTracker}, for use by the {@link TaskScheduler}. The * <code>TaskSelector</code> is in charge of managing both locality and * speculative execution. For the latter purpose, it must also provide counts of * how many tasks each speculative job needs to launch, so that the scheduler * can take this into account in its calculations. */ public abstract class TaskSelector implements Configurable { protected Configuration conf; protected TaskTrackerManager taskTrackerManager; public Configuration getConf() { return conf; } public void setConf(Configuration conf) { this.conf = conf; } public synchronized void setTaskTrackerManager( TaskTrackerManager taskTrackerManager) { this.taskTrackerManager = taskTrackerManager; } /** * Lifecycle method to allow the TaskSelector to start any work in separate * threads. */ public void start() throws IOException { // do nothing } /** * Lifecycle method to allow the TaskSelector to stop any work it is doing. */ public void terminate() throws IOException { // do nothing } /** * How many speculative map tasks does the given job want to launch? * @param job The job to count speculative maps for * @return Number of speculative maps that can be launched for job */ public abstract int neededSpeculativeMaps(JobInProgress job); /** * How many speculative reduce tasks does the given job want to launch? * @param job The job to count speculative reduces for * @return Number of speculative reduces that can be launched for job */ public abstract int neededSpeculativeReduces(JobInProgress job); /** * Choose a map task to run from the given job on the given TaskTracker. * @param taskTracker {@link TaskTrackerStatus} of machine to run on * @param job Job to select a task for * @return A {@link Task} to run on the machine, or <code>null</code> if * no map should be launched from this job on the task tracker. * @throws IOException */ public abstract Task obtainNewMapTask(TaskTrackerStatus taskTracker, JobInProgress job) throws IOException; /** * Choose a reduce task to run from the given job on the given TaskTracker. * @param taskTracker {@link TaskTrackerStatus} of machine to run on * @param job Job to select a task for * @return A {@link Task} to run on the machine, or <code>null</code> if * no reduce should be launched from this job on the task tracker. * @throws IOException */ public abstract Task obtainNewReduceTask(TaskTrackerStatus taskTracker, JobInProgress job) throws IOException; }
3e1f2c9bc2c74b196b8eebac3b21060d68ba1330
1,599
java
Java
src/main/java/com/ccc/oa/model/Notice.java
fantongkw/oa
d615d8723b2e2fe9b16fb0de073e3a014ed77aeb
[ "Apache-2.0" ]
3
2019-05-07T08:34:04.000Z
2021-02-19T07:51:13.000Z
src/main/java/com/ccc/oa/model/Notice.java
fantongkw/SSM
d615d8723b2e2fe9b16fb0de073e3a014ed77aeb
[ "Apache-2.0" ]
1
2022-03-21T08:19:12.000Z
2022-03-21T08:19:12.000Z
src/main/java/com/ccc/oa/model/Notice.java
fantongkw/SSM
d615d8723b2e2fe9b16fb0de073e3a014ed77aeb
[ "Apache-2.0" ]
1
2019-09-25T07:23:47.000Z
2019-09-25T07:23:47.000Z
20.766234
88
0.541588
13,173
package com.ccc.oa.model; import java.io.Serializable; import java.util.Calendar; public class Notice implements Serializable { private static final long serialVersionUID = 4942784013793429744L; private String id; private String type; private String username; private String title; private Long created; public Notice() { } public Notice(String id, String type, String username, String title, Long created) { this.id = id; this.type = type; this.username = username; this.title = title; this.created = created; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Long getCreated() { return created; } public void setCreated(Long created) { this.created = created; } @Override public String toString() { return "Notice{" + "id='" + id + '\'' + ", type='" + type + '\'' + ", username='" + username + '\'' + ", title='" + title + '\'' + ", created=" + created + '}'; } }
3e1f2cc0381c9b55a614841ba213e4dbc4bee8b5
1,648
java
Java
ripple-core/src/main/java/org/rippleosi/patient/appointments/search/NotConfiguredAppointmentSearch.java
shanemuk/EHR4NI
7c5918b06dbac0ed3ce2a1fc62e22fa4ce91b209
[ "Apache-2.0" ]
1
2018-05-14T08:56:16.000Z
2018-05-14T08:56:16.000Z
ripple-core/src/main/java/org/rippleosi/patient/appointments/search/NotConfiguredAppointmentSearch.java
shanemuk/EHR4NI
7c5918b06dbac0ed3ce2a1fc62e22fa4ce91b209
[ "Apache-2.0" ]
null
null
null
ripple-core/src/main/java/org/rippleosi/patient/appointments/search/NotConfiguredAppointmentSearch.java
shanemuk/EHR4NI
7c5918b06dbac0ed3ce2a1fc62e22fa4ce91b209
[ "Apache-2.0" ]
null
null
null
32.96
87
0.75182
13,174
/* * Copyright 2015 Ripple OSI * * 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.rippleosi.patient.appointments.search; import java.util.List; import org.rippleosi.common.exception.ConfigurationException; import org.rippleosi.common.types.RepoSourceType; import org.rippleosi.common.types.RepoSourceTypes; import org.rippleosi.patient.appointments.model.AppointmentDetails; import org.rippleosi.patient.appointments.model.AppointmentSummary; /** */ public class NotConfiguredAppointmentSearch implements AppointmentSearch { @Override public RepoSourceType getSource() { return RepoSourceTypes.NONE; } @Override public int getPriority() { return Integer.MAX_VALUE; } @Override public List<AppointmentSummary> findAllAppointments(String patientId) { throw ConfigurationException.unimplementedTransaction(AppointmentSearch.class); } @Override public AppointmentDetails findAppointment(String patientId, String appointmentId) { throw ConfigurationException.unimplementedTransaction(AppointmentSearch.class); } }
3e1f2cca5929408c903800344886c8336c6f44cd
1,443
java
Java
mybatis-generator-core/src/main/java/org/mybatis/generator/config/JDBCConnectionConfiguration.java
yangfancoming/mybatis-generator
00298bf16cfc9d9ad84aa8cebbed2dbaf2631c6d
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
mybatis-generator-core/src/main/java/org/mybatis/generator/config/JDBCConnectionConfiguration.java
yangfancoming/mybatis-generator
00298bf16cfc9d9ad84aa8cebbed2dbaf2631c6d
[ "ECL-2.0", "Apache-2.0" ]
3
2021-02-03T19:33:39.000Z
2021-12-14T20:44:04.000Z
mybatis-generator-core/src/main/java/org/mybatis/generator/config/JDBCConnectionConfiguration.java
yangfancoming/mybatis-generator
00298bf16cfc9d9ad84aa8cebbed2dbaf2631c6d
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
22.2
79
0.659044
13,175
package org.mybatis.generator.config; import static org.mybatis.generator.internal.util.StringUtility.stringHasValue; import static org.mybatis.generator.internal.util.messages.Messages.getString; import java.util.List; public class JDBCConnectionConfiguration extends PropertyHolder { private String driverClass; private String connectionURL; private String userId; private String password; public JDBCConnectionConfiguration() { super(); } public String getConnectionURL() { return connectionURL; } public void setConnectionURL(String connectionURL) { this.connectionURL = connectionURL; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getDriverClass() { return driverClass; } public void setDriverClass(String driverClass) { this.driverClass = driverClass; } public void validate(List<String> errors) { if (!stringHasValue(driverClass)) { errors.add(getString("ValidationError.4")); //$NON-NLS-1$ } if (!stringHasValue(connectionURL)) { errors.add(getString("ValidationError.5")); //$NON-NLS-1$ } } }
3e1f2cf00ccd69d18c1c505f3444ea2dd9556c2a
2,989
java
Java
src/main/java/szewek/flux/recipe/AbstractMachineRecipe.java
szeweq/Flux
4ff51a4d8ef65eee7a76e26e4ebb31cb17748ca4
[ "MIT" ]
1
2020-02-08T23:20:29.000Z
2020-02-08T23:20:29.000Z
src/main/java/szewek/flux/recipe/AbstractMachineRecipe.java
Szewek/Flux
4ff51a4d8ef65eee7a76e26e4ebb31cb17748ca4
[ "MIT" ]
73
2020-01-19T14:57:02.000Z
2021-07-13T23:02:23.000Z
src/main/java/szewek/flux/recipe/AbstractMachineRecipe.java
szeweq/Flux
4ff51a4d8ef65eee7a76e26e4ebb31cb17748ca4
[ "MIT" ]
2
2020-06-23T14:13:58.000Z
2021-03-13T06:28:03.000Z
25.991304
117
0.744062
13,176
package szewek.flux.recipe; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.item.crafting.IRecipeSerializer; import net.minecraft.item.crafting.IRecipeType; import net.minecraft.item.crafting.Ingredient; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.common.util.RecipeMatcher; import szewek.fl.network.FluxAnalytics; import szewek.fl.recipe.CountedIngredient; import szewek.fl.type.FluxRecipeType; import szewek.flux.util.inventory.IInventoryIO; import java.util.ArrayList; import java.util.function.Consumer; public abstract class AbstractMachineRecipe implements IRecipe<IInventoryIO>, Consumer<Iterable<ItemStack>> { public final NonNullList<Ingredient> ingredients; public final ItemStack result; public final float experience; public final int processTime; private final FluxRecipeType<?> type; private final ResourceLocation id; private final String group; public AbstractMachineRecipe(FluxRecipeType<?> type, ResourceLocation id, MachineRecipeSerializer.Builder builder) { this.type = type; this.id = id; group = builder.group; ingredients = builder.buildIngredients(); result = builder.result; experience = builder.experience; processTime = builder.process; } @Override public IRecipeType<?> getType() { return type; } @Override public ResourceLocation getId() { return id; } @Override public String getGroup() { return group; } @Override public ItemStack getResultItem() { return result; } @Override public NonNullList<Ingredient> getIngredients() { return ingredients; } @Override public IRecipeSerializer<?> getSerializer() { return type.serializer; } @Override public boolean matches(IInventoryIO inv, World worldIn) { ArrayList<ItemStack> filledInputs = new ArrayList<>(); int inputSize = inv.getIOSize().in; for (int i = 0; i < inputSize; i++) { ItemStack stack = inv.getItem(i); if (!stack.isEmpty()) { filledInputs.add(stack); } } int[] match = RecipeMatcher.findMatches(filledInputs, ingredients); return match != null; } @Override public ItemStack assemble(IInventoryIO inv) { return result.copy(); } @Override public boolean canCraftInDimensions(int width, int height) { return ingredients.size() <= width * height; } @Override public final void accept(Iterable<ItemStack> stacks) { ArrayList<ItemStack> filledInputs = new ArrayList<>(ingredients.size()); for (ItemStack stack : stacks) { if (!stack.isEmpty()) { filledInputs.add(stack); } } int[] match = RecipeMatcher.findMatches(filledInputs, ingredients); if (match != null) { for(int i = 0; i < match.length; ++i) { Ingredient ingredient = ingredients.get(match[i]); int count = ingredient instanceof CountedIngredient ? ((CountedIngredient) ingredient).getCount() : 1; filledInputs.get(i).grow(-count); } } } }
3e1f2d6cd9c68cbb5d362d6afc06964cbedd4e60
6,350
java
Java
CoreFeatures/FeatureLoadingSystem/FilesystemTracker/src/test/java/info/smart_tools/smartactors/feature_loading_system/filesystem_tracker/ListenerTaskTest.java
asatuchin/smartactors-core
35d6cae61144305e80b22db04264c14be8405c3f
[ "Apache-2.0" ]
21
2017-09-29T09:45:37.000Z
2021-09-21T14:12:54.000Z
CoreFeatures/FeatureLoadingSystem/FilesystemTracker/src/test/java/info/smart_tools/smartactors/feature_loading_system/filesystem_tracker/ListenerTaskTest.java
asatuchin/smartactors-core
35d6cae61144305e80b22db04264c14be8405c3f
[ "Apache-2.0" ]
310
2019-04-11T16:42:11.000Z
2021-05-23T08:14:16.000Z
CoreFeatures/FeatureLoadingSystem/FilesystemTracker/src/test/java/info/smart_tools/smartactors/feature_loading_system/filesystem_tracker/ListenerTaskTest.java
asatuchin/smartactors-core
35d6cae61144305e80b22db04264c14be8405c3f
[ "Apache-2.0" ]
12
2017-09-29T09:50:30.000Z
2022-02-09T08:08:29.000Z
43.493151
111
0.713858
13,177
package info.smart_tools.smartactors.feature_loading_system.filesystem_tracker; import info.smart_tools.smartactors.base.interfaces.iaction.IAction; import info.smart_tools.smartactors.base.interfaces.iaction.exception.ActionExecuteException; import info.smart_tools.smartactors.base.interfaces.ipath.IPath; import org.junit.Before; import org.junit.Test; import java.nio.file.*; import java.nio.file.spi.FileSystemProvider; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class ListenerTaskTest { private IAction<IPath> actionMock; private IPath directoryMock; private FileSystem fileSystemMock; private FileSystemProvider fileSystemProviderMock; private WatchService watchServiceMock; private WatchKey watchKeyMock; private WatchEvent event1Mock, event2Mock; private java.nio.file.Path directoryPathMock; @Before public void setUp() throws Exception { actionMock = mock(IAction.class); directoryMock = mock(IPath.class); directoryPathMock = mock(java.nio.file.Path.class); fileSystemMock = mock(FileSystem.class); fileSystemProviderMock = mock(FileSystemProvider.class); watchServiceMock = mock(WatchService.class); watchKeyMock = mock(WatchKey.class); event1Mock = mock(WatchEvent.class); event2Mock = mock(WatchEvent.class); when(directoryMock.getPath()).thenReturn("dir"); when(directoryPathMock.getFileSystem()).thenReturn(fileSystemMock); when(fileSystemMock.getPath("dir")).thenReturn(directoryPathMock); when(fileSystemMock.provider()).thenReturn(fileSystemProviderMock); when(fileSystemMock.newWatchService()).thenReturn(watchServiceMock); } @Test public void Should_setupWatchServiceOnCreation() throws Exception { ListenerTask task = new ListenerTask(directoryMock, actionMock, fileSystemMock); verify(directoryPathMock).register(same(watchServiceMock), same(StandardWatchEventKinds.ENTRY_CREATE)); } @Test public void Should_queryListOfExistFilesAndPollWatchServiceEvents() throws Exception { DirectoryStream directoryStreamMock = mock(DirectoryStream.class); Iterator directoryStreamIteratorMock = mock(Iterator.class); java.nio.file.Path[] filesMock = new java.nio.file.Path[] { mock(java.nio.file.Path.class), mock(java.nio.file.Path.class) }; when(filesMock[0].toString()).thenReturn("dir/one"); when(filesMock[1].toString()).thenReturn("dir/two"); when(directoryStreamIteratorMock.hasNext()).thenReturn(true, true, false); when(directoryStreamIteratorMock.next()).thenReturn(filesMock[0], filesMock[1]); when(directoryStreamMock.iterator()).thenReturn(directoryStreamIteratorMock); when(fileSystemProviderMock.newDirectoryStream(any(), any())).thenReturn(directoryStreamMock); java.nio.file.Path newFileEventPathMock = mock(java.nio.file.Path.class); when(newFileEventPathMock.toString()).thenReturn("new"); java.nio.file.Path newFileActualPathMock = mock(java.nio.file.Path.class); when(newFileActualPathMock.toString()).thenReturn("dir/new"); when(directoryPathMock.resolve(newFileEventPathMock)).thenReturn(newFileActualPathMock); when(event1Mock.kind()).thenReturn((WatchEvent.Kind)StandardWatchEventKinds.ENTRY_CREATE); when(event1Mock.context()).thenReturn(newFileEventPathMock); when(event2Mock.kind()).thenReturn((WatchEvent.Kind)StandardWatchEventKinds.ENTRY_DELETE); when(watchKeyMock.pollEvents()) .thenReturn(Arrays.asList(event1Mock, event2Mock)) .thenReturn(Collections.emptyList()); when(watchServiceMock.take()).thenReturn(watchKeyMock); when(watchKeyMock.reset()).thenReturn(true).thenReturn(false); ListenerTask task = new ListenerTask(directoryMock, actionMock, fileSystemMock); task.run(); verify(actionMock, times(1)).execute(eq(new info.smart_tools.smartactors.base.path.Path("dir/one"))); verify(actionMock, times(1)).execute(eq(new info.smart_tools.smartactors.base.path.Path("dir/two"))); verify(actionMock, times(1)).execute(eq(new info.smart_tools.smartactors.base.path.Path("dir/new"))); verify(actionMock, times(3)).execute(any()); } @Test public void Should_handleThreadInterruption() throws Exception { DirectoryStream directoryStreamMock = mock(DirectoryStream.class); Iterator directoryStreamIteratorMock = mock(Iterator.class); when(directoryStreamIteratorMock.hasNext()).thenReturn(false); when(directoryStreamMock.iterator()).thenReturn(directoryStreamIteratorMock); when(fileSystemProviderMock.newDirectoryStream(any(), any())).thenReturn(directoryStreamMock); when(watchServiceMock.take()).thenThrow(new InterruptedException()); ListenerTask task = new ListenerTask(directoryMock, actionMock, fileSystemMock); task.run(); assertTrue(Thread.interrupted()); } @Test public void Should_wrapActionExceptionsIntoRuntimeExceptions() throws Exception { DirectoryStream directoryStreamMock = mock(DirectoryStream.class); Iterator directoryStreamIteratorMock = mock(Iterator.class); java.nio.file.Path[] filesMock = new java.nio.file.Path[] { mock(java.nio.file.Path.class) }; when(directoryStreamIteratorMock.hasNext()).thenReturn(true, false); when(directoryStreamIteratorMock.next()).thenReturn(filesMock[0]); when(directoryStreamMock.iterator()).thenReturn(directoryStreamIteratorMock); when(fileSystemProviderMock.newDirectoryStream(any(), any())).thenReturn(directoryStreamMock); ListenerTask task = new ListenerTask(directoryMock, actionMock, fileSystemMock); doThrow(new ActionExecuteException("")).when(actionMock).execute(any(IPath.class)); try { task.run(); fail(); } catch (RuntimeException e) { assertTrue(e.getCause() instanceof ActionExecuteException); } } }
3e1f2e623a58b59896007335430bbe29e3dc4835
17,356
java
Java
opensrp-web/src/main/java/org/opensrp/web/controller/FormSubmissionController.java
SoftmedTanzania/EGPF_backend
8cc5010c28c5b341706202c06131cdbd92ddf642
[ "Apache-2.0" ]
null
null
null
opensrp-web/src/main/java/org/opensrp/web/controller/FormSubmissionController.java
SoftmedTanzania/EGPF_backend
8cc5010c28c5b341706202c06131cdbd92ddf642
[ "Apache-2.0" ]
null
null
null
opensrp-web/src/main/java/org/opensrp/web/controller/FormSubmissionController.java
SoftmedTanzania/EGPF_backend
8cc5010c28c5b341706202c06131cdbd92ddf642
[ "Apache-2.0" ]
null
null
null
46.406417
328
0.727587
13,178
package org.opensrp.web.controller; import ch.lambdaj.function.convert.Converter; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.google.i18n.phonenumbers.NumberParseException; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.Phonenumber; import org.joda.time.DateTime; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.opensrp.common.AllConstants; import org.opensrp.connector.openmrs.constants.OpenmrsHouseHold; import org.opensrp.connector.openmrs.service.EncounterService; import org.opensrp.connector.openmrs.service.HouseholdService; import org.opensrp.connector.openmrs.service.PatientService; import org.opensrp.domain.*; import org.opensrp.dto.PatientReferralsDTO; import org.opensrp.dto.PatientsDTO; import org.opensrp.dto.ReferralsDTO; import org.opensrp.dto.form.FormSubmissionDTO; import org.opensrp.dto.form.MultimediaDTO; import org.opensrp.form.domain.FormSubmission; import org.opensrp.form.service.FormAttributeParser; import org.opensrp.form.service.FormSubmissionConverter; import org.opensrp.form.service.FormSubmissionMap; import org.opensrp.form.service.FormSubmissionService; import org.opensrp.repository.*; import org.opensrp.scheduler.SystemEvent; import org.opensrp.scheduler.TaskSchedulerService; import org.opensrp.service.*; import org.opensrp.service.formSubmission.FormEntityConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPathExpressionException; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.Map; import static ch.lambdaj.collection.LambdaCollections.with; import static java.text.MessageFormat.format; import static org.springframework.http.HttpStatus.*; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static org.springframework.web.bind.annotation.RequestMethod.POST; @Controller public class FormSubmissionController { private static Logger logger = LoggerFactory.getLogger(FormSubmissionController.class.toString()); private FormSubmissionService formSubmissionService; private GoogleFCMService googleFCMService; private TaskSchedulerService scheduler; private EncounterService encounterService; private FormEntityConverter formEntityConverter; private PatientService patientService; private ReferralPatientsService referralPatientService; private HouseholdService householdService; private ErrorTraceService errorTraceService; private MultimediaService multimediaService; private MultimediaRepository multimediaRepository; private HealthFacilitiesPatientsRepository healthFacilitiesPatientsRepository; private PatientReferralRepository patientReferralRepository; private PatientReferralIndicatorRepository patientReferralIndicatorRepository; private GooglePushNotificationsUsersRepository googlePushNotificationsUsersRepository; private RapidProServiceImpl rapidProService; ; @Autowired public FormSubmissionController(FormSubmissionService formSubmissionService, TaskSchedulerService scheduler, EncounterService encounterService, FormEntityConverter formEntityConverter, PatientService patientService, HouseholdService householdService,MultimediaService multimediaService, MultimediaRepository multimediaRepository, ErrorTraceService errorTraceService,HealthFacilitiesPatientsRepository healthFacilitiesPatientsRepository,PatientReferralRepository patientReferralRepository, GooglePushNotificationsUsersRepository googlePushNotificationsUsersRepository,GoogleFCMService googleFCMService, PatientReferralIndicatorRepository patientReferralIndicatorRepository, ReferralPatientsService referralPatientService,RapidProServiceImpl rapidProService) { this.formSubmissionService = formSubmissionService; this.scheduler = scheduler; this.errorTraceService=errorTraceService; this.encounterService = encounterService; this.formEntityConverter = formEntityConverter; this.patientService = patientService; this.householdService = householdService; this.multimediaService = multimediaService; this.multimediaRepository = multimediaRepository; this.healthFacilitiesPatientsRepository = healthFacilitiesPatientsRepository; this.patientReferralRepository = patientReferralRepository; this.googlePushNotificationsUsersRepository = googlePushNotificationsUsersRepository; this.googleFCMService =googleFCMService; this.patientReferralIndicatorRepository = patientReferralIndicatorRepository; this.referralPatientService = referralPatientService; this.rapidProService=rapidProService; } @RequestMapping(method = GET, value = "/form-submissions") @ResponseBody private List<FormSubmissionDTO> getNewSubmissionsForANM(@RequestParam("anm-id") String anmIdentifier, @RequestParam("timestamp") Long timeStamp, @RequestParam(value = "batch-size", required = false) Integer batchSize) { List<FormSubmission> newSubmissionsForANM = formSubmissionService .getNewSubmissionsForANM(anmIdentifier, timeStamp, batchSize); return with(newSubmissionsForANM).convert(new Converter<FormSubmission, FormSubmissionDTO>() { @Override public FormSubmissionDTO convert(FormSubmission submission) { return FormSubmissionConverter.from(submission); } }); } @RequestMapping(method = GET, value="/all-form-submissions") @ResponseBody private List<FormSubmissionDTO> getAllFormSubmissions(@RequestParam("timestamp") Long timeStamp, @RequestParam(value = "batch-size", required = false) Integer batchSize) { List<FormSubmission> allSubmissions = formSubmissionService .getAllSubmissions(timeStamp, batchSize); return with(allSubmissions).convert(new Converter<FormSubmission, FormSubmissionDTO>() { @Override public FormSubmissionDTO convert(FormSubmission submission) { return FormSubmissionConverter.from(submission); } }); } @RequestMapping(headers = {"Accept=application/json"}, method = POST, value = "/form-submissions") public ResponseEntity<HttpStatus> submitForms(@RequestBody List<FormSubmissionDTO> formSubmissionsDTO) { try { if (formSubmissionsDTO.isEmpty()) { return new ResponseEntity<>(BAD_REQUEST); } System.out.println("\n"); System.out.println("DrTest received formsubmission: "+formSubmissionsDTO.toString()); try { System.out.println("DrTest saving to couchdb formsubmission: "+formSubmissionsDTO.toString()); scheduler.notifyEvent(new SystemEvent<>(AllConstants.OpenSRPEvent.FORM_SUBMISSION, formSubmissionsDTO)); }catch (Exception e){ System.out.println("Error saving to couchdb : "+formSubmissionsDTO.toString()); e.printStackTrace(); } System.out.println("DrTest received saving data "); try{ String json = new Gson().toJson(formSubmissionsDTO); List<FormSubmissionDTO> formSubmissions = new Gson().fromJson(json, new TypeToken<List<FormSubmissionDTO>>() { }.getType()); List<FormSubmission> fsl = with(formSubmissions).convert(new Converter<FormSubmissionDTO, FormSubmission>() { @Override public FormSubmission convert(FormSubmissionDTO submission) { return FormSubmissionConverter.toFormSubmission(submission); } }); for (FormSubmission formSubmission : fsl) { try{ System.out.println("DrTest received saving data to openSRP "); saveFormToOpenSRP(formSubmission); System.out.println("DrTest received saving data to openMRS "); addFormToOpenMRS(formSubmission); } catch(Exception e){ e.printStackTrace(); ErrorTrace errorTrace=new ErrorTrace(new DateTime(), "Parse Exception", "", e.getStackTrace().toString(), "Unsolved", formSubmission.formName()); errorTrace.setRecordId(formSubmission.instanceId()); errorTraceService.addError(errorTrace); } } } catch(Exception e){ e.printStackTrace(); } logger.debug(format("Added Form submissions to queue.\nSubmissions: {0}", formSubmissionsDTO)); } catch (Exception e) { logger.error(format("Form submissions processing failed with exception {0}.\nSubmissions: {1}", e, formSubmissionsDTO)); return new ResponseEntity<>(INTERNAL_SERVER_ERROR); } return new ResponseEntity<>(CREATED); } private void addFormToOpenMRS(FormSubmission formSubmission) throws ParseException, IllegalStateException, JSONException{ FormSubmissionMap formSubmissionMap = null; try { formSubmissionMap = formSubmissionService.formAttributeParser.createFormSubmissionMap(formSubmission); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } if(formEntityConverter.isOpenmrsForm(formSubmissionMap)){ Client c = formEntityConverter.getClientFromFormSubmission(formSubmission); Event e = formEntityConverter.getEventFromFormSubmission(formSubmission); Map<String, Map<String, Object>> dep = formEntityConverter.getDependentClientsFromFormSubmission(formSubmission); // TODO temporary because not necessarily we register inner entity for Household only if(formSubmission.formName().toLowerCase().contains("household") || formSubmission.formName().toLowerCase().contains("census") ){ OpenmrsHouseHold hh = new OpenmrsHouseHold(c, e); for (Map<String, Object> cm : dep.values()) { hh.addHHMember((Client)cm.get("client"), (Event)cm.get("event")); } householdService.saveHH(hh, true); } else { JSONObject p = patientService.getPatientByIdentifier(c.getBaseEntityId()); if(p == null){ System.out.println(patientService.createPatient(c)); } System.out.println(encounterService.createEncounter(e)); for (Map<String, Object> cm : dep.values()) { Client cin = (Client)cm.get("client"); Event evin = (Event)cm.get("event"); JSONObject pin = patientService.getPatientByIdentifier(cin.getBaseEntityId()); if(pin == null){ System.out.println(patientService.createPatient(cin)); } System.out.println(encounterService.createEncounter(evin)); } } } } private void saveFormToOpenSRP(FormSubmission formSubmission) throws ParseException, IllegalStateException, JSONException{ logger.info("saveFormToOpenSRP : saving patient into OpenSRP"); Patients patient = formEntityConverter.getPatientFromFormSubmission(formSubmission); PatientReferral patientReferral = formEntityConverter.getPatientReferralFromFormSubmission(formSubmission); try { long healthfacilityPatientId = referralPatientService.savePatient(patient, patientReferral.getFacilityId(), patientReferral.getCtcNumber()); List<HealthFacilitiesPatients> healthFacilitiesPatients = healthFacilitiesPatientsRepository.getHealthFacilityPatients("SELECT * FROM "+HealthFacilitiesPatients.tbName+" WHERE "+HealthFacilitiesPatients.COL_HEALTH_FACILITY_PATIENT_ID+" = "+healthfacilityPatientId,null); patient.setPatientId(healthFacilitiesPatients.get(0).getPatient().getPatientId()); patientReferral.setPatient(patient); //TODO Coze remove hardcoding of these values. This is a temporally patch to be removed later on patientReferral.setReferralSource(0); patientReferral.setReferralStatus(0); patientReferral.setReferralType(1); logger.info("saveFormToOpenSRP : saving referral Data"); long id = patientReferralRepository.save(patientReferral); patientReferral.setId(id); JSONArray indicatorIds = formEntityConverter.getReferralIndicatorsFromFormSubmission(formSubmission); int size = indicatorIds.length(); List<Long> referralIndicatorIds = new ArrayList<>(); for(int i=0;i<size;i++){ PatientReferralIndicators referralIndicators = new PatientReferralIndicators(); referralIndicators.setActive(true); referralIndicators.setReferralId(id); referralIndicators.setReferralServiceIndicatorId(indicatorIds.getLong(i)); long patientReferralIndicatorId = patientReferralIndicatorRepository.save(referralIndicators); referralIndicatorIds.add(indicatorIds.getLong(i)); } String phoneNumber = patient.getPhoneNumber(); phoneNumber = reformatPhoneNumber(phoneNumber); List<String> urns; urns = new ArrayList<String>(); urns.add("tel:"+phoneNumber); try { //TODO RAPIDPRO, fix the message sent String response = rapidProService.sendMessage(urns,null,null, "Successful registration",null); logger.info("Received rapidpro response : "+response); }catch (Exception e){ e.printStackTrace(); } Object[] facilityParams = new Object[]{patientReferral.getFacilityId(),1}; List<GooglePushNotificationsUsers> googlePushNotificationsUsers = googlePushNotificationsUsersRepository.getGooglePushNotificationsUsers("SELECT * FROM "+GooglePushNotificationsUsers.tbName+" WHERE "+GooglePushNotificationsUsers.COL_FACILITY_UIID+" = ? AND "+GooglePushNotificationsUsers.COL_USER_TYPE+" = ?",facilityParams); JSONArray tokens = new JSONArray(); for(GooglePushNotificationsUsers googlePushNotificationsUsers1:googlePushNotificationsUsers){ tokens.put(googlePushNotificationsUsers1.getGooglePushNotificationToken()); } PatientReferralsDTO patientReferralsDTO = new PatientReferralsDTO(); PatientsDTO patientsDTO = PatientsConverter.toPatientsDTO(patient); patientsDTO.setCtcNumber(patientReferral.getCtcNumber()); patientReferralsDTO.setPatientsDTO(patientsDTO); List<ReferralsDTO> referralsDTOS = new ArrayList<>(); ReferralsDTO referralsDTO = PatientsConverter.toPatientDTO(patientReferral); referralsDTO.setServiceIndicatorIds(referralIndicatorIds); referralsDTOS.add(referralsDTO); patientReferralsDTO.setPatientReferralsList(referralsDTOS); JSONObject body = new JSONObject(); String json = new Gson().toJson(patientReferralsDTO); logger.info("saveFormToOpenSRP: FCM msg = "+json); JSONObject msg = new JSONObject(json); msg.put("type","PatientReferral"); googleFCMService.SendPushNotification(msg,tokens,true); } catch (Exception e) { e.printStackTrace(); logger.error(format("Patient Form submissions processing failed with exception {0}.\nSubmissions: {1}", e, formSubmission)); } } @RequestMapping(headers = {"Accept=application/json"}, method = GET, value = "/multimedia-file") @ResponseBody public List<MultimediaDTO> getFiles(@RequestParam("anm-id") String providerId) { List<Multimedia> allMultimedias = multimediaService.getMultimediaFiles(providerId); return with(allMultimedias).convert(new Converter<Multimedia, MultimediaDTO>() { @Override public MultimediaDTO convert(Multimedia md) { return new MultimediaDTO(md.getCaseId(), md.getProviderId(), md.getContentType(), md.getFilePath(), md.getFileCategory()); } }); } public String reformatPhoneNumber(String phoneNumber){ PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); try { logger.info("ReformatPhoneNumber: registered phone number = "+phoneNumber); Phonenumber.PhoneNumber tzPhoneNumber = phoneUtil.parse(phoneNumber, "TZ"); phoneNumber = phoneUtil.format(tzPhoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164); return phoneNumber; } catch (NumberParseException e) { e.printStackTrace(); return ""; } } }
3e1f2e8d8c9a1d9e88e3fe1525721acd1f01cc99
1,707
java
Java
springcloud-alibaba/shop-order/src/main/java/com/config/ExceptionHandlerPage.java
code1990/phonebook
148a15e603aef31d2251deba0d0a46297f6f4e30
[ "MIT" ]
1
2021-11-02T03:40:48.000Z
2021-11-02T03:40:48.000Z
springcloud-alibaba/shop-order/src/main/java/com/config/ExceptionHandlerPage.java
code1990/phonebook
148a15e603aef31d2251deba0d0a46297f6f4e30
[ "MIT" ]
4
2021-03-10T09:21:46.000Z
2022-02-27T00:22:18.000Z
springcloud-alibaba/shop-order/src/main/java/com/config/ExceptionHandlerPage.java
code1990/phonebook
148a15e603aef31d2251deba0d0a46297f6f4e30
[ "MIT" ]
null
null
null
31.611111
77
0.729936
13,179
package com.config; import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException; import com.alibaba.csp.sentinel.slots.block.flow.FlowException; import com.alibaba.fastjson.JSON; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @program: springcloud-alibaba * @Date: 2020-06-14 16:01 * @Author: code1990 * @Description: */ //异常处理页面 @Component public class ExceptionHandlerPage implements UrlBlockHandler { //BlockException 异常接口,包含Sentinel的五个异常 // FlowException 限流异常 // DegradeException 降级异常 // ParamFlowException 参数限流异常 // AuthorityException 授权异常 // SystemBlockException 系统负载异常 @Override public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException { httpServletResponse.setContentType("application/json;charset=utf-8"); ResponseData data = null; if (e instanceof FlowException) { data = new ResponseData(-1, "接口被限流了..."); } else if (e instanceof DegradeException) { data = new ResponseData(-2, "接口被降级了..."); } httpServletResponse.getWriter().write(JSON.toJSONString(data)); } } @Data @AllArgsConstructor//全参构造 @NoArgsConstructor //无参构造 class ResponseData { private int code; private String message; }
3e1f2e95f3011f1b5d619acb9d3a1b060e234a23
4,132
java
Java
src/main/java/io/ovh/tsl/LOADSOURCERAW.java
aurrelhebert/TSL-Adaptor
a282612cf8503ff4aee886adaec6147088aeeec3
[ "BSD-3-Clause" ]
3
2019-12-18T18:39:53.000Z
2019-12-19T04:18:18.000Z
src/main/java/io/ovh/tsl/LOADSOURCERAW.java
aurrelhebert/TSL-Adaptor
a282612cf8503ff4aee886adaec6147088aeeec3
[ "BSD-3-Clause" ]
null
null
null
src/main/java/io/ovh/tsl/LOADSOURCERAW.java
aurrelhebert/TSL-Adaptor
a282612cf8503ff4aee886adaec6147088aeeec3
[ "BSD-3-Clause" ]
1
2019-12-18T22:04:35.000Z
2019-12-18T22:04:35.000Z
38.259259
137
0.635528
13,180
package io.ovh.tsl; import io.warp10.continuum.gts.GeoTimeSerie; import io.warp10.script.NamedWarpScriptFunction; import io.warp10.script.WarpScriptException; import io.warp10.script.WarpScriptStack; import io.warp10.script.WarpScriptStackFunction; import java.util.HashMap; import java.util.List; import java.util.Map; import static io.warp10.script.unary.TOTIMESTAMP.parseTimestamp; public abstract class LOADSOURCERAW extends NamedWarpScriptFunction implements WarpScriptStackFunction { private Boolean isFind; public LOADSOURCERAW(String name, Boolean isFind) { super(name); this.isFind = isFind; } @Override public Object apply(WarpScriptStack stack) throws WarpScriptException { Object top = stack.pop(); // Pop and parse native FETCH list parameter if (!(top instanceof List)) { throw new WarpScriptException(getName() + " expects a LIST on top of the stack."); } List<Object> params = (List) top; if (!(params.get(0) instanceof String)) { throw new WarpScriptException(getName() + " expects Influx basic auth"); } String token = (String) params.get(0); if (!(params.get(1) instanceof String)) { throw new WarpScriptException(getName() + " expects Influx basic auth"); } String selector = (String) params.get(1); if (!(params.get(2) instanceof Map)) { throw new WarpScriptException(getName() + " expects a labels map"); } Map labels = (Map) params.get(2); Map<String, String> stringLabels = new HashMap<String, String>(); for (Object key: labels.keySet()) { stringLabels.put(key.toString(), labels.get(key).toString()); } // Case of a FIND statement if (this.isFind) { List<GeoTimeSerie> allSeries = this.FindGTS(token, selector, stringLabels); stack.push(allSeries); return stack; } Object startObject = params.get(3); Long start = -1L; if (!(startObject instanceof String) && !(startObject instanceof java.util.Date) && !(startObject instanceof Long)) { throw new WarpScriptException(getName() + " expects an ISO8601 timestamp, a Date instance or a long tick as 3rd parameter."); } else if (startObject instanceof java.util.Date) { start = ((java.util.Date) startObject).getTime() * TimeConstants.TIME_UNITS_PER_MS; } else if (startObject instanceof String) { start = parseTimestamp(startObject.toString()); } else if (startObject instanceof Long) { start = (Long) startObject; } Object endObject = params.get(4); Long end = -1L; if (!(endObject instanceof String) && !(endObject instanceof java.util.Date) && !(endObject instanceof Long)) { throw new WarpScriptException(getName() + " expects an ISO8601 timestamp, a Date instance or a long tick as 3rd parameter."); } else if (endObject instanceof java.util.Date) { end = ((java.util.Date) endObject).getTime() * TimeConstants.TIME_UNITS_PER_MS; } else if (endObject instanceof String) { end = parseTimestamp(endObject.toString()); } else if (endObject instanceof Long) { end = (Long) endObject; } if (start > end ) { Long tmp = start; start = end; end = tmp; } if (startObject instanceof Long && endObject instanceof Long) { start = end - start; } // Call custom data source native FETCH List<GeoTimeSerie> allSeries = this.FetchGTS(token, selector, stringLabels, start, end); stack.push(allSeries); return stack; } abstract public List<GeoTimeSerie> FetchGTS(String token, String selector, Map<String, String> labels, Long start, Long end) throws WarpScriptException; abstract public List<GeoTimeSerie> FindGTS(String token, String selector, Map<String, String> labels) throws WarpScriptException; }
3e1f2fa6a0d0eb5a43344f26447501884b38675e
3,167
java
Java
taurus-agent/src/main/java/com/dp/bigdata/taurus/agent/sheduler/KillTaskThread.java
fjfd/taurus
3426e8759d68b8893d0370bf346d7b5b6799aa28
[ "Apache-2.0" ]
9
2015-01-03T02:26:42.000Z
2022-01-07T19:38:17.000Z
taurus-agent/src/main/java/com/dp/bigdata/taurus/agent/sheduler/KillTaskThread.java
andyyin/taurus
3426e8759d68b8893d0370bf346d7b5b6799aa28
[ "Apache-2.0" ]
null
null
null
taurus-agent/src/main/java/com/dp/bigdata/taurus/agent/sheduler/KillTaskThread.java
andyyin/taurus
3426e8759d68b8893d0370bf346d7b5b6799aa28
[ "Apache-2.0" ]
18
2015-01-06T09:41:36.000Z
2022-01-20T00:59:08.000Z
28.531532
98
0.721819
13,181
/** * Project: taurus-agent * * File Created at 2013-5-21 * $Id$ * * Copyright 2013 dianping.com. * All rights reserved. * * This software is the confidential and proprietary information of * Dianping Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with dianping.com. */ package com.dp.bigdata.taurus.agent.sheduler; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.concurrent.locks.Lock; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.dp.bigdata.taurus.agent.common.BaseEnvManager; import com.dp.bigdata.taurus.agent.exec.Executor; import com.dp.bigdata.taurus.agent.utils.LockHelper; import com.dp.bigdata.taurus.zookeeper.common.infochannel.bean.ScheduleConf; import com.dp.bigdata.taurus.zookeeper.common.infochannel.bean.ScheduleStatus; import com.dp.bigdata.taurus.zookeeper.common.infochannel.interfaces.ScheduleInfoChannel; /** * TODO Comment of KillThread * * @author renyuan.sun * */ public class KillTaskThread extends BaseEnvManager { private static final Log LOGGER = LogFactory.getLog(KillTaskThread.class); private static final String KILL_COMMAND = "%s %s %s"; Executor executor; String localIp; ScheduleInfoChannel cs; String jobInstanceId; KillTaskThread(Executor executor, String localIp, ScheduleInfoChannel cs, String jobInstanceId) { this.executor = executor; this.localIp = localIp; this.cs = cs; this.jobInstanceId = jobInstanceId; } @Override public void run() { Lock lock = LockHelper.getLock(jobInstanceId); try { lock.lock(); ScheduleConf conf = (ScheduleConf) cs.getConf(localIp, jobInstanceId); ScheduleStatus status = (ScheduleStatus) cs.getStatus(localIp, jobInstanceId); killTask(localIp, conf, status); } catch (Exception e) { LOGGER.error(e, e); } finally { lock.unlock(); } } private void killTask(String ip, ScheduleConf conf, ScheduleStatus status) { String attemptID = conf.getAttemptID(); int returnCode = 1; try { if (ON_WINDOWS) { returnCode = executor.kill(attemptID); } else { String fileName = running + FILE_SEPRATOR + '.' + attemptID; BufferedReader br = new BufferedReader(new FileReader((new File(fileName)))); String pid = br.readLine(); br.close(); LOGGER.debug("Ready to kill " + attemptID + ", pid is " + pid); String kill = String.format(KILL_COMMAND, killJob, pid, "9"); returnCode = executor.execute("kill", System.out, System.err, kill); try { new File(fileName).delete(); } catch (Exception e) { LOGGER.error("Fail to delete file for " + attemptID); } } } catch (FileNotFoundException e) { LOGGER.debug(attemptID + " is over when been killed."); returnCode = 0; } catch (Exception e) { LOGGER.error(e, e); returnCode = 1; } if (returnCode == 0) { cs.removeRunningJob(localIp, jobInstanceId); status.setStatus(ScheduleStatus.DELETE_SUCCESS); } } }
3e1f2fbe72eadc823ed050f18bf1a349b2db7075
4,310
java
Java
Universal-G-Code-Sender/ugs-core/src/com/willwinder/universalgcodesender/uielements/helpers/LoaderDialogHelper.java
thomascoreapps/tinkering
37a49312b606ea0866c9bf0dc6b798446f5c0740
[ "MIT" ]
2
2020-04-21T20:32:25.000Z
2021-07-24T18:20:04.000Z
Universal-G-Code-Sender/ugs-core/src/com/willwinder/universalgcodesender/uielements/helpers/LoaderDialogHelper.java
thomascoreapps/tinkering
37a49312b606ea0866c9bf0dc6b798446f5c0740
[ "MIT" ]
2
2020-09-02T04:47:16.000Z
2022-03-25T19:21:20.000Z
Universal-G-Code-Sender/ugs-core/src/com/willwinder/universalgcodesender/uielements/helpers/LoaderDialogHelper.java
thomascoreapps/tinkering
37a49312b606ea0866c9bf0dc6b798446f5c0740
[ "MIT" ]
null
null
null
37.155172
104
0.67587
13,182
/* Copyright 2020 Will Winder This file is part of Universal Gcode Sender (UGS). UGS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. UGS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with UGS. If not, see <http://www.gnu.org/licenses/>. */ package com.willwinder.universalgcodesender.uielements.helpers; import com.willwinder.universalgcodesender.utils.ThreadHelper; import net.miginfocom.swing.MigLayout; import javax.swing.ImageIcon; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; import java.awt.Component; import java.awt.Dialog.ModalityType; import java.awt.Window; import java.net.URL; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledFuture; /** * A helper class for displaying a modal loader dialog with a spinner icon and a title. * * @author Joacim Breiler */ public class LoaderDialogHelper { private static final String LAYOUT_CONSTRAINTS = "fill, wrap 2, inset 24, gap 6, wmin 120, hmin 64"; private static JDialog dialog; private static long startTime; private static long minimumTimeToShow; private LoaderDialogHelper() { } /** * Shows a modal loader dialog with the given component as the parent. * To close the dialog, use {@link LoaderDialogHelper#closeDialog()}. If closing * the window occurs before the given parameter minimumTimeToShow it will still * be visible until that time has passed. The intention is to make sure the user * is given time to read the title of the dialog. * * @param title the title to display in the dialog * @param minimumTimeToShow the minimum time to show the dialog before the * loader dialog is closed * @param parent the parent component for finding the root window */ public static void showDialog(String title, long minimumTimeToShow, Component parent) { LoaderDialogHelper.minimumTimeToShow = minimumTimeToShow; if (dialog != null) { dialog.dispose(); dialog = null; } startTime = System.currentTimeMillis(); Window window = SwingUtilities.getWindowAncestor(parent); dialog = new JDialog(window, title, ModalityType.APPLICATION_MODAL); dialog.setUndecorated(true); URL loaderUrl = LoaderDialogHelper.class.getResource("/resources/icons/loader.gif"); JPanel panel = new JPanel(new MigLayout(LAYOUT_CONSTRAINTS)); panel.add(new JLabel(new ImageIcon(loaderUrl)), "shrink"); panel.add(new JLabel(title), "grow"); dialog.add(panel); dialog.pack(); dialog.setLocationRelativeTo(window); ThreadHelper.invokeLater(() -> dialog.setVisible(true)); } /** * Closes the dialog if open. If closing the dialog occurs before * minimumTimeToShow the dialog will still be visible until that time has passed. * <p> * Make sure not calling this method in EventQueue thread as it will block until * the closing of the dialog is complete. */ public static void closeDialog() { long timeToShowDialog = startTime + minimumTimeToShow - System.currentTimeMillis(); if (timeToShowDialog < 0 || startTime == 0) { timeToShowDialog = 0; } // Closes the ScheduledFuture<?> scheduledFuture = ThreadHelper.invokeLater(() -> { if (dialog != null) { dialog.setVisible(false); dialog = null; startTime = 0; } }, timeToShowDialog); // Wait for the dialog to close try { scheduledFuture.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } }
3e1f3015c247eef765cb1e1df295be57bd003964
1,412
java
Java
rabbitmq-test/src/test/java/org/sky/rabbitmq/ProducerTest.java
roc-wong/sky-framework
8b08cea4d9841ce989b04bc80453c9ff0205dfc7
[ "Apache-2.0" ]
null
null
null
rabbitmq-test/src/test/java/org/sky/rabbitmq/ProducerTest.java
roc-wong/sky-framework
8b08cea4d9841ce989b04bc80453c9ff0205dfc7
[ "Apache-2.0" ]
4
2021-01-20T23:17:49.000Z
2022-01-21T23:19:06.000Z
rabbitmq-test/src/test/java/org/sky/rabbitmq/ProducerTest.java
roc-wong/sky-framework
8b08cea4d9841ce989b04bc80453c9ff0205dfc7
[ "Apache-2.0" ]
null
null
null
29.416667
90
0.613314
13,183
package org.sky.rabbitmq; import com.google.gson.Gson; import com.rabbitmq.client.Address; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import java.io.IOException; import java.util.Scanner; public class ProducerTest { public static void main(String[] args) throws IOException { ConnectionFactory factory = new ConnectionFactory(); factory.setUsername("guest"); factory.setPassword("guest"); Address address = new Address("10.0.29.29", 5672); Connection connection = factory.newConnection(new Address[]{address}); Channel channel = connection.createChannel(); String exchange = "rate_limter_exchange_test"; channel.exchangeDeclare(exchange, "fanout", false); Gson gson = new Gson(); while (true) { System.out.println("请输入生产的消息数量"); Scanner scan = new Scanner(System.in); int messageNum = scan.nextInt(); if(messageNum <=0){ break; } for (int i = 1; i < messageNum; i++) { Message message = new Message(); message.setContent("hello world, " + i); channel.basicPublish(exchange, "", null, gson.toJson(message).getBytes()); } } channel.close(); connection.close(); } }
3e1f302164b511eb1b3780e95e4120bd0fe94690
9,704
java
Java
lytest/src/main/java/com/lingyi/autiovideo/test/widget/popup/MyCallLayout.java
yangkun19921001/T01_AV_SDKDEMO
2052610f3bf5b84f1da3d0a13e7903070c3da3d2
[ "Apache-2.0" ]
4
2019-05-28T01:04:55.000Z
2020-04-24T07:21:47.000Z
lytest/src/main/java/com/lingyi/autiovideo/test/widget/popup/MyCallLayout.java
yangkun19921001/T01_AV_SDKDEMO
2052610f3bf5b84f1da3d0a13e7903070c3da3d2
[ "Apache-2.0" ]
null
null
null
lytest/src/main/java/com/lingyi/autiovideo/test/widget/popup/MyCallLayout.java
yangkun19921001/T01_AV_SDKDEMO
2052610f3bf5b84f1da3d0a13e7903070c3da3d2
[ "Apache-2.0" ]
4
2020-08-19T02:42:11.000Z
2022-01-30T17:53:43.000Z
33.811847
96
0.585944
13,184
package com.lingyi.autiovideo.test.widget.popup; import android.content.Context; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.blankj.utilcode.util.ScreenUtils; import com.blankj.utilcode.util.ToastUtils; import com.bnc.activity.T01Helper; import com.bnc.activity.utils.ViewType; import com.bnc.activity.widget.call.CallLayout; import com.lingyi.autiovideo.test.R; import org.doubango.ngn.sip.NgnInviteSession; /** * Created by yangk on 2018/12/10. */ public class MyCallLayout extends CallLayout implements View.OnClickListener { private NgnInviteSession.InviteState mAVState; private TextView mTvInfo; private TextView tvRemoteNumber; private TextView tryingRemoteName; public MyCallLayout(Context context) { super(context); initCall(); } public MyCallLayout(Context context, AttributeSet attrs) { super(context, attrs); initCall(); } public MyCallLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initCall(); } @Override public void onDestroy() { super.onDestroy(); onCallDestory(); } /** * 找到布局 */ private void initCall() { addCallLayoutListener(new ICallLayoutCallBack() { @Override public void findById(View view, LayoutState type) { switch (type) { case DEF_LAYOUT: handleDef(view); break; case AUDIO_LAYOUT: handleAudio(view); break; case VIDEO_LAYOUT: handleVideo(view); break; case TERMINATED: handleTerminated(view); break; } } @Override public void onError(String meg) { ToastUtils.showShort(meg); } }); } /** * 处理结束中的业务 * @param view */ private void handleTerminated(View view) { mTvInfo = (TextView) view .findViewById(R.id.tryingPhoneAttribution); mTvInfo.setText(getContext().getString(R.string.string_call_terminated) ); if (mCurrentView == ViewType.ViewTermwait) { return; } final TextView tvRemote = (TextView) view .findViewById(R.id.tryingRemoteNumber); tryingRemoteName = (TextView) view .findViewById(R.id.tryingRemoteName); view.findViewById(R.id.tryAnswer).setVisibility(View.GONE); view.findViewById(R.id.tryHangup).setVisibility(View.GONE); // 显示号码 if (mRemotePartyDisplayName != null && tvRemoteNumber != null) { Log.e(TAG, "xianshi" + mRemotePartyDisplayName); tvRemoteNumber.setText("(" + mRemotePartyDisplayName + ")"); } // 显示名称 if (!TextUtils.isEmpty(mUserName.getUserName())) { tryingRemoteName.setText(mUserName.getUserName()); } else { tryingRemoteName.setText(mUserName.getUserId()); } tvRemote.setText("(" + mRemotePartyDisplayName + ")"); } /** * 处理视频通话的业务 * @param view */ private void handleVideo(View view) { //解决 硬编花屏问题 if (T01Helper.getInstance().getSetEngine().getCurVideoQuality().equals("高清") || T01Helper.getInstance().getSetEngine().getCurVideoQuality().equals("超清")) { ScreenUtils.setLandscape(mContext.get()); } view.findViewById(R.id.video_call_mute_btn).setOnClickListener(MyCallLayout.this); view.findViewById(R.id.video_call_handsfree_btn).setOnClickListener(MyCallLayout.this); view.findViewById(R.id.video_call_local_btn).setOnClickListener(MyCallLayout.this); view.findViewById(R.id.video_call_change_btn).setOnClickListener(MyCallLayout.this); view.findViewById(R.id.video_call_hangup).setOnClickListener(MyCallLayout.this); final TextView tvRemote = (TextView) view .findViewById(R.id.video_call_number); if (!TextUtils.isEmpty(mUserName.getUserName())) { tvRemote.setText(mUserName.getUserName()); } else { tvRemote.setText(mUserName.getUserId()); } } /** * 处理音频通话的业务 * @param view */ private void handleAudio(View view) { view.findViewById(R.id.audio_call_hangup).setOnClickListener(MyCallLayout.this); view.findViewById(R.id.audio_call_mute_btn).setOnClickListener(MyCallLayout.this); view.findViewById(R.id.audio_call_handsfree_btn).setOnClickListener(MyCallLayout.this); final TextView tvRemote = (TextView) view .findViewById(R.id.audio_call_number); final Button btHang = (Button) view .findViewById(R.id.audio_call_hangup); if (!TextUtils.isEmpty(mUserName.getUserName())) { tvRemote.setText(mUserName.getUserName()); } else { tvRemote.setText(mUserName.getUserId()); } } /** * 处理默认通话的布局中的业务 * @param view */ private void handleDef(View view) { view.findViewById(R.id.tryAnswer).setOnClickListener(MyCallLayout.this); view.findViewById(R.id.tryHangup).setOnClickListener(MyCallLayout.this); mTvInfo = (TextView) view.findViewById(R.id.tryingPhoneAttribution); tvRemoteNumber = (TextView) view.findViewById(R.id.tryingRemoteNumber); tryingRemoteName = (TextView) view.findViewById(R.id.tryingRemoteName); final Button btAnswer = (Button) view.findViewById(R.id.tryAnswer); final Button btHang = (Button) view.findViewById(R.id.tryHangup); final ImageView ivAvatar = (ImageView) view.findViewById(R.id.tryingContachPhone); switch (mAVState) { case INCOMING: mTvInfo.setText(getContext().getString(R.string.string_call_incoming)); break; case INPROGRESS: mTvInfo.setText(getContext().getString(R.string.string_call_inprogress)); btAnswer.setVisibility(View.GONE); break; case INCALL: mTvInfo.setText(getContext().getString(R.string.string_call_outgoing)); break; case REMOTE_RINGING: case EARLY_MEDIA: default: mTvInfo.setText(getContext().getString(R.string.string_call_inprogress)); break; } if (mRemotePartyDisplayName != null && tvRemoteNumber != null) // 显示号码 tvRemoteNumber.setText("(" + mRemotePartyDisplayName + ")"); // 显示名称 // 显示名称 if (!TextUtils.isEmpty(mUserName.getUserName())) { tryingRemoteName.setText(mUserName.getUserName()); } else { tryingRemoteName.setText(mUserName.getUserId()); } if ((mSessionType & getTypeVideo()) == getTypeAudio()) { ivAvatar.setBackgroundResource(R.drawable.re_audio_center_bg_focus); } else if ((mSessionType & TYPE_VIDEO) == TYPE_VIDEO) { ivAvatar.setBackgroundResource(R.drawable.re_video_incoming); } } /** * 加载通话结束的布局 * * @return */ @Override protected int loadCallDestoryLayout() { return R.layout.activity_trying; } /** * 加载当前进入的默认布局 * * @param state 当前的通话状态 * @return */ @Override public int loadDefCurrentLayout(NgnInviteSession.InviteState state) { mAVState = state; return R.layout.activity_trying; } /** * 音频通话的布局 * * @param state * @return */ @Override public int loadAudioLayout(NgnInviteSession.InviteState state) { return R.layout.activity_audio_call; } /** * 加载视频通话功能的布局 * * @param state * @return */ @Override protected int loadVideoFunctionLayout(NgnInviteSession.InviteState state) { return R.layout.layout_video_funchtion; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tryAnswer: T01Helper.getInstance().getCallEngine().acceptCall(); break; case R.id.video_call_handsfree_btn: case R.id.audio_call_handsfree_btn: T01Helper.getInstance().getCallEngine().isHandsfree(); break; case R.id.video_call_local_btn: T01Helper.getInstance().getCallEngine().stopLocalVideo(); break; case R.id.video_call_mute_btn: case R.id.audio_call_mute_btn: T01Helper.getInstance().getCallEngine().isMute(); break; case R.id.video_call_change_btn: T01Helper.getInstance().getCallEngine().changeCamera(); break; case R.id.tryHangup: case R.id.audio_call_hangup: case R.id.video_call_hangup: T01Helper.getInstance().getCallEngine().hangUpCall(); break; } } }
3e1f3076e170886952a04266035f8c8981179fa2
465
java
Java
src/main/java/com/keuin/blame/adapter/handler/AttackEntityHandler.java
hit-mc/Blame-Fabric
6d62d680e0cff107cfdf2b47d2ae225f1171b2c4
[ "MIT" ]
null
null
null
src/main/java/com/keuin/blame/adapter/handler/AttackEntityHandler.java
hit-mc/Blame-Fabric
6d62d680e0cff107cfdf2b47d2ae225f1171b2c4
[ "MIT" ]
null
null
null
src/main/java/com/keuin/blame/adapter/handler/AttackEntityHandler.java
hit-mc/Blame-Fabric
6d62d680e0cff107cfdf2b47d2ae225f1171b2c4
[ "MIT" ]
null
null
null
35.769231
139
0.832258
13,185
package com.keuin.blame.adapter.handler; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.Hand; import net.minecraft.util.hit.EntityHitResult; import net.minecraft.world.World; import org.jetbrains.annotations.Nullable; public interface AttackEntityHandler { void onPlayerAttackEntity(PlayerEntity playerEntity, World world, Hand hand, Entity entity, @Nullable EntityHitResult entityHitResult); }
3e1f30de5eb6073c9686457be4fba9635f4f2759
24,448
java
Java
src/som/mod/som/form/SFormSeasonProducer.java
swaplicado/som10
ce20090021bd95a4c8208bbfb81ea692fefd0239
[ "MIT" ]
null
null
null
src/som/mod/som/form/SFormSeasonProducer.java
swaplicado/som10
ce20090021bd95a4c8208bbfb81ea692fefd0239
[ "MIT" ]
null
null
null
src/som/mod/som/form/SFormSeasonProducer.java
swaplicado/som10
ce20090021bd95a4c8208bbfb81ea692fefd0239
[ "MIT" ]
null
null
null
40.210526
195
0.683123
13,186
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package som.mod.som.form; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.sql.SQLException; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import sa.lib.SLibConsts; import sa.lib.SLibUtils; import sa.lib.db.SDbRegistry; import sa.lib.gui.SGuiClient; import sa.lib.gui.SGuiConsts; import sa.lib.gui.SGuiFieldKeyGroup; import sa.lib.gui.SGuiUtils; import sa.lib.gui.SGuiValidation; import sa.lib.gui.bean.SBeanFieldRadio; import som.gui.SGuiClientSessionCustom; import som.mod.SModConsts; import som.mod.som.db.SDbProducer; import som.mod.som.db.SDbSeasonProducer; import som.mod.som.db.SDbSeasonRegion; /** * * @author Juan Barajas, Sergio Flores */ public class SFormSeasonProducer extends sa.lib.gui.bean.SBeanForm implements ItemListener, ChangeListener, ActionListener { private SDbSeasonProducer moRegistry; private SGuiFieldKeyGroup moFieldKeyGroup; private SDbProducer moProducer; private double mdAuxPricePerTon; private double mdAuxPriceFreight; /** * Creates new form SFormSeasonProducer */ public SFormSeasonProducer(SGuiClient client, String title) { setFormSettings(client, SGuiConsts.BEAN_FORM_EDIT, SModConsts.SU_SEAS_PROD, SLibConsts.UNDEFINED, title); initComponents(); initComponentsCustom(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel3 = new javax.swing.JPanel(); moUpdateTickets = new javax.swing.ButtonGroup(); jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jPanel6 = new javax.swing.JPanel(); jlSeason = new javax.swing.JLabel(); moKeySeason = new sa.lib.gui.bean.SBeanFieldKey(); jPanel11 = new javax.swing.JPanel(); jlRegion = new javax.swing.JLabel(); moKeyRegion = new sa.lib.gui.bean.SBeanFieldKey(); jPanel7 = new javax.swing.JPanel(); jlItem = new javax.swing.JLabel(); moKeyItem = new sa.lib.gui.bean.SBeanFieldKey(); jPanel15 = new javax.swing.JPanel(); jlProducer = new javax.swing.JLabel(); moKeyProducer = new sa.lib.gui.bean.SBeanFieldKey(); moBoolFreight = new sa.lib.gui.bean.SBeanFieldBoolean(); jPanel9 = new javax.swing.JPanel(); moBoolPrcTon = new sa.lib.gui.bean.SBeanFieldBoolean(); jPanel17 = new javax.swing.JPanel(); jlPricePerTonReg = new javax.swing.JLabel(); moDecPricePerTonReg = new sa.lib.gui.bean.SBeanFieldDecimal(); moTextCurrencyCodePrcTonReg = new sa.lib.gui.bean.SBeanFieldText(); jPanel16 = new javax.swing.JPanel(); jlPricePerTon = new javax.swing.JLabel(); moDecPricePerTon = new sa.lib.gui.bean.SBeanFieldDecimal(); moTextCurrencyCodePrcTon = new sa.lib.gui.bean.SBeanFieldText(); jbEditPrice = new javax.swing.JButton(); jPanel14 = new javax.swing.JPanel(); jlPriceFreight = new javax.swing.JLabel(); moDecPriceFreight = new sa.lib.gui.bean.SBeanFieldDecimal(); moTextCurrencyCodeFreight = new sa.lib.gui.bean.SBeanFieldText(); jPanel10 = new javax.swing.JPanel(); jPanel12 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); moRadUpdateTicketsNone = new sa.lib.gui.bean.SBeanFieldRadio(); jPanel5 = new javax.swing.JPanel(); moRadUpdateTicketsAsOfDate = new sa.lib.gui.bean.SBeanFieldRadio(); moDateDate = new sa.lib.gui.bean.SBeanFieldDate(); jPanel8 = new javax.swing.JPanel(); moRadUpdateTicketsAll = new sa.lib.gui.bean.SBeanFieldRadio(); jPanel1.setLayout(new java.awt.BorderLayout()); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del registro:")); jPanel2.setLayout(new java.awt.GridLayout(8, 1, 0, 5)); jPanel6.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlSeason.setForeground(new java.awt.Color(0, 0, 255)); jlSeason.setText("Temporada:*"); jlSeason.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel6.add(jlSeason); moKeySeason.setPreferredSize(new java.awt.Dimension(300, 23)); jPanel6.add(moKeySeason); jPanel2.add(jPanel6); jPanel11.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlRegion.setForeground(new java.awt.Color(0, 0, 255)); jlRegion.setText("Región:*"); jlRegion.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel11.add(jlRegion); moKeyRegion.setPreferredSize(new java.awt.Dimension(300, 23)); jPanel11.add(moKeyRegion); jPanel2.add(jPanel11); jPanel7.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlItem.setForeground(new java.awt.Color(0, 0, 255)); jlItem.setText("Ítem:*"); jlItem.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel7.add(jlItem); moKeyItem.setPreferredSize(new java.awt.Dimension(300, 23)); jPanel7.add(moKeyItem); jPanel2.add(jPanel7); jPanel15.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlProducer.setForeground(new java.awt.Color(0, 0, 255)); jlProducer.setText("Proveedor:*"); jlProducer.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel15.add(jlProducer); moKeyProducer.setPreferredSize(new java.awt.Dimension(300, 23)); jPanel15.add(moKeyProducer); moBoolFreight.setText("Se paga flete al proveedor"); moBoolFreight.setEditable(false); moBoolFreight.setPreferredSize(new java.awt.Dimension(175, 23)); jPanel15.add(moBoolFreight); jPanel2.add(jPanel15); jPanel9.setEnabled(false); jPanel9.setFocusable(false); jPanel9.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); moBoolPrcTon.setText("Aplica precio ton para el proveedor"); moBoolPrcTon.setPreferredSize(new java.awt.Dimension(225, 23)); jPanel9.add(moBoolPrcTon); jPanel2.add(jPanel9); jPanel17.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlPricePerTonReg.setText("Precio ton región:"); jlPricePerTonReg.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel17.add(jlPricePerTonReg); moDecPricePerTonReg.setEditable(false); jPanel17.add(moDecPricePerTonReg); moTextCurrencyCodePrcTonReg.setEditable(false); moTextCurrencyCodePrcTonReg.setText("sBeanFieldText1"); moTextCurrencyCodePrcTonReg.setPreferredSize(new java.awt.Dimension(50, 23)); jPanel17.add(moTextCurrencyCodePrcTonReg); jPanel2.add(jPanel17); jPanel16.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlPricePerTon.setText("Precio ton:*"); jlPricePerTon.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel16.add(jlPricePerTon); jPanel16.add(moDecPricePerTon); moTextCurrencyCodePrcTon.setEditable(false); moTextCurrencyCodePrcTon.setText("sBeanFieldText1"); moTextCurrencyCodePrcTon.setPreferredSize(new java.awt.Dimension(50, 23)); jPanel16.add(moTextCurrencyCodePrcTon); jbEditPrice.setText("<"); jbEditPrice.setToolTipText("Modificar precios"); jbEditPrice.setMargin(new java.awt.Insets(0, 0, 0, 0)); jbEditPrice.setPreferredSize(new java.awt.Dimension(23, 23)); jPanel16.add(jbEditPrice); jPanel2.add(jPanel16); jPanel14.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlPriceFreight.setText("Precio flete:*"); jlPriceFreight.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel14.add(jlPriceFreight); jPanel14.add(moDecPriceFreight); moTextCurrencyCodeFreight.setEditable(false); moTextCurrencyCodeFreight.setText("sBeanFieldText1"); moTextCurrencyCodeFreight.setPreferredSize(new java.awt.Dimension(50, 23)); jPanel14.add(moTextCurrencyCodeFreight); jPanel2.add(jPanel14); jPanel1.add(jPanel2, java.awt.BorderLayout.NORTH); jPanel10.setBorder(javax.swing.BorderFactory.createTitledBorder("Actualización por cambio en precio:")); jPanel10.setLayout(new java.awt.BorderLayout()); jPanel12.setLayout(new java.awt.GridLayout(3, 0, 0, 5)); jPanel4.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); moUpdateTickets.add(moRadUpdateTicketsNone); moRadUpdateTicketsNone.setSelected(true); moRadUpdateTicketsNone.setText("No actualizar boletos"); moRadUpdateTicketsNone.setPreferredSize(new java.awt.Dimension(175, 23)); jPanel4.add(moRadUpdateTicketsNone); jPanel12.add(jPanel4); jPanel5.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); moUpdateTickets.add(moRadUpdateTicketsAsOfDate); moRadUpdateTicketsAsOfDate.setText("Actualizar boletos a partir del"); moRadUpdateTicketsAsOfDate.setPreferredSize(new java.awt.Dimension(170, 23)); jPanel5.add(moRadUpdateTicketsAsOfDate); jPanel5.add(moDateDate); jPanel12.add(jPanel5); jPanel8.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); moUpdateTickets.add(moRadUpdateTicketsAll); moRadUpdateTicketsAll.setText("Actualizar todos los boletos"); moRadUpdateTicketsAll.setPreferredSize(new java.awt.Dimension(175, 23)); jPanel8.add(moRadUpdateTicketsAll); jPanel12.add(jPanel8); jPanel10.add(jPanel12, java.awt.BorderLayout.NORTH); jPanel1.add(jPanel10, java.awt.BorderLayout.CENTER); getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel10; private javax.swing.JPanel jPanel11; private javax.swing.JPanel jPanel12; private javax.swing.JPanel jPanel14; private javax.swing.JPanel jPanel15; private javax.swing.JPanel jPanel16; private javax.swing.JPanel jPanel17; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JPanel jPanel8; private javax.swing.JPanel jPanel9; private javax.swing.JButton jbEditPrice; private javax.swing.JLabel jlItem; private javax.swing.JLabel jlPriceFreight; private javax.swing.JLabel jlPricePerTon; private javax.swing.JLabel jlPricePerTonReg; private javax.swing.JLabel jlProducer; private javax.swing.JLabel jlRegion; private javax.swing.JLabel jlSeason; private sa.lib.gui.bean.SBeanFieldBoolean moBoolFreight; private sa.lib.gui.bean.SBeanFieldBoolean moBoolPrcTon; private sa.lib.gui.bean.SBeanFieldDate moDateDate; private sa.lib.gui.bean.SBeanFieldDecimal moDecPriceFreight; private sa.lib.gui.bean.SBeanFieldDecimal moDecPricePerTon; private sa.lib.gui.bean.SBeanFieldDecimal moDecPricePerTonReg; private sa.lib.gui.bean.SBeanFieldKey moKeyItem; private sa.lib.gui.bean.SBeanFieldKey moKeyProducer; private sa.lib.gui.bean.SBeanFieldKey moKeyRegion; private sa.lib.gui.bean.SBeanFieldKey moKeySeason; private sa.lib.gui.bean.SBeanFieldRadio moRadUpdateTicketsAll; private sa.lib.gui.bean.SBeanFieldRadio moRadUpdateTicketsAsOfDate; private sa.lib.gui.bean.SBeanFieldRadio moRadUpdateTicketsNone; private sa.lib.gui.bean.SBeanFieldText moTextCurrencyCodeFreight; private sa.lib.gui.bean.SBeanFieldText moTextCurrencyCodePrcTon; private sa.lib.gui.bean.SBeanFieldText moTextCurrencyCodePrcTonReg; private javax.swing.ButtonGroup moUpdateTickets; // End of variables declaration//GEN-END:variables private void initComponentsCustom() { SGuiUtils.setWindowBounds(this, 720, 450); moFieldKeyGroup = new SGuiFieldKeyGroup(miClient); moKeySeason.setKeySettings(miClient, SGuiUtils.getLabelName(jlSeason.getText()), true); moKeyRegion.setKeySettings(miClient, SGuiUtils.getLabelName(jlRegion.getText()), true); moKeyItem.setKeySettings(miClient, SGuiUtils.getLabelName(jlItem.getText()), true); moKeyProducer.setKeySettings(miClient, SGuiUtils.getLabelName(jlProducer.getText()), true); moBoolFreight.setBooleanSettings(SGuiUtils.getLabelName(moBoolFreight.getText()), false); moBoolPrcTon.setBooleanSettings(SGuiUtils.getLabelName(moBoolPrcTon.getText()), false); moDecPricePerTonReg.setDecimalSettings(SGuiUtils.getLabelName(jlPricePerTonReg.getText()), SGuiConsts.GUI_TYPE_DEC_AMT, false); moTextCurrencyCodePrcTonReg.setTextSettings(SGuiUtils.getLabelName(jlPricePerTonReg.getText()), 3); moDecPricePerTon.setDecimalSettings(SGuiUtils.getLabelName(jlPricePerTon.getText()), SGuiConsts.GUI_TYPE_DEC_AMT, true); moTextCurrencyCodePrcTon.setTextSettings(SGuiUtils.getLabelName(jlPricePerTon.getText()), 3); moDecPriceFreight.setDecimalSettings(SGuiUtils.getLabelName(jlPriceFreight.getText()), SGuiConsts.GUI_TYPE_DEC_AMT, true); moTextCurrencyCodeFreight.setTextSettings(SGuiUtils.getLabelName(jlPriceFreight.getText()), 3); moRadUpdateTicketsNone.setBooleanSettings(SGuiUtils.getLabelName(moRadUpdateTicketsNone.getText()), true); moRadUpdateTicketsAsOfDate.setBooleanSettings(SGuiUtils.getLabelName(moRadUpdateTicketsAsOfDate.getText()), false); moDateDate.setDateSettings(miClient, SGuiUtils.getLabelName(moRadUpdateTicketsAsOfDate.getText()), true); moRadUpdateTicketsAll.setBooleanSettings(SGuiUtils.getLabelName(moRadUpdateTicketsAll.getText()), false); moFields.addField(moKeySeason); moFields.addField(moKeyRegion); moFields.addField(moKeyItem); moFields.addField(moKeyProducer); moFields.addField(moBoolFreight); moFields.addField(moBoolPrcTon); //moFields.addField(moDecPricePerTonReg); moFields.addField(moDecPricePerTon); moFields.addField(moDecPriceFreight); moFields.addField(moRadUpdateTicketsNone); moFields.addField(moRadUpdateTicketsAsOfDate); moFields.addField(moDateDate); moFields.addField(moRadUpdateTicketsAll); moFields.setFormButton(jbSave); } private void setPriceTonRegion() { double priceRegion = 0; SDbSeasonRegion region = null; try { if (moKeySeason.getSelectedIndex() > 0 && moKeyRegion.getSelectedIndex() > 0 && moKeyItem.getSelectedIndex() > 0) { region = (SDbSeasonRegion) miClient.getSession().readRegistry(SModConsts.SU_SEAS_REG, new int[] { moKeySeason.getValue()[0], moKeyRegion.getValue()[1], moKeyItem.getValue()[2] }); priceRegion = region.getPricePerTon(); } moDecPricePerTonReg.setValue(priceRegion); } catch (Exception e) { SLibUtils.printException(this, e); } } private void actionItemEditPrice(boolean enable) { moBoolPrcTon.setEnabled(enable); moDecPriceFreight.setEditable(enable && (moProducer != null && moProducer.isFreightPayment())); jbEditPrice.setEnabled(!enable); itemStatePriceTon(); } private void actionUpdateTicket() { if (moRadUpdateTicketsAsOfDate.isSelected() && !moDateDate.isEditable()) { moDateDate.setValue(miClient.getSession().getWorkingDate()); } moDateDate.setEditable(moRadUpdateTicketsAsOfDate.isSelected()); } private void itemStatePriceTon() { moDecPricePerTon.setEditable(moBoolPrcTon.getValue() && moBoolPrcTon.isEnabled()); if (moDecPricePerTon.isEditable()) { moDecPricePerTon.requestFocus(); } if (!moBoolPrcTon.getValue()) { moDecPricePerTon.setValue(0d); } } private void itemStateFreight() { moDecPriceFreight.setEditable(moBoolFreight.getValue() && moBoolPrcTon.isEnabled()); } private void itemStateKeyProducer() { boolean enable = false; if (moKeyProducer.getSelectedIndex() > 0) { moProducer = new SDbProducer(); try { moProducer.read(miClient.getSession(), moKeyProducer.getValue()); } catch (SQLException e) { SLibUtils.showException(this, e); } catch (Exception e) { SLibUtils.showException(this, e); } enable = moProducer.isFreightPayment(); } moBoolFreight.setValue(enable); itemStateFreight(); } @Override public void addAllListeners() { moBoolFreight.addItemListener(this); moBoolPrcTon.addItemListener(this); moKeyItem.addItemListener(this); moKeyProducer.addItemListener(this); jbEditPrice.addActionListener(this); moRadUpdateTicketsNone.addChangeListener(this); moRadUpdateTicketsAsOfDate.addChangeListener(this); moRadUpdateTicketsAll.addChangeListener(this); } @Override public void removeAllListeners() { moBoolFreight.removeItemListener(this); moBoolPrcTon.removeItemListener(this); moKeyItem.removeItemListener(this); moKeyProducer.removeItemListener(this); jbEditPrice.removeActionListener(this); moRadUpdateTicketsNone.removeChangeListener(this); moRadUpdateTicketsAsOfDate.removeChangeListener(this); moRadUpdateTicketsAll.removeChangeListener(this); } @Override public void reloadCatalogues() { moFieldKeyGroup.initGroup(); moFieldKeyGroup.addFieldKey(moKeySeason, SModConsts.SX_PROD_SEAS, SLibConsts.UNDEFINED, null); moFieldKeyGroup.addFieldKey(moKeyRegion, SModConsts.SX_PROD_REG, SLibConsts.UNDEFINED, null); moFieldKeyGroup.addFieldKey(moKeyItem, SModConsts.SX_PROD_ITEM, SLibConsts.UNDEFINED, null); moFieldKeyGroup.populateCatalogues(); miClient.getSession().populateCatalogue(moKeyProducer, SModConsts.SU_PROD, SLibConsts.UNDEFINED, null); } @Override public void setRegistry(SDbRegistry registry) throws Exception { int[] key = null; moRegistry = (SDbSeasonProducer) registry; mnFormResult = SLibConsts.UNDEFINED; mbFirstActivation = true; removeAllListeners(); reloadCatalogues(); key = moRegistry.getPrimaryKey(); if (moRegistry.isRegistryNew()) { moRegistry.initPrimaryKey(); jtfRegistryKey.setText(""); } else { jtfRegistryKey.setText(SLibUtils.textKey(moRegistry.getPrimaryKey())); } moKeySeason.setValue(new int[] { key[0] }); moKeyRegion.setValue(new int[] { key[0], key[1] }); moKeyItem.setValue(new int[] { key[0], key[1], key[2] }); moKeyProducer.setValue(new int[] { key[3] }); moDecPriceFreight.setValue(mdAuxPriceFreight = moRegistry.getPriceFreight()); moTextCurrencyCodeFreight.setValue(((SGuiClientSessionCustom) miClient.getSession().getSessionCustom()).getLocalCurrencyCode()); moDecPricePerTon.setValue(mdAuxPricePerTon = moRegistry.getPricePerTon()); moTextCurrencyCodePrcTon.setValue(((SGuiClientSessionCustom) miClient.getSession().getSessionCustom()).getLocalCurrencyCode()); moTextCurrencyCodePrcTonReg.setValue(((SGuiClientSessionCustom) miClient.getSession().getSessionCustom()).getLocalCurrencyCode()); moBoolFreight.setValue(moRegistry.isFreightPayment()); moBoolPrcTon.setValue(moRegistry.isPricePerTon()); setFormEditable(true); moBoolFreight.setEnabled(false); moDecPriceFreight.setEditable(false); moDecPricePerTon.setEditable(moRegistry.isPricePerTon()); actionItemEditPrice(moRegistry.isRegistryNew()); itemStateFreight(); itemStatePriceTon(); itemStateKeyProducer(); setPriceTonRegion(); if (moRegistry.isRegistryNew()) { if (key == null) { moFieldKeyGroup.resetGroup(); } } else { moKeySeason.setEnabled(false); moKeyRegion.setEnabled(false); moKeyItem.setEnabled(false); moKeyProducer.setEnabled(false); } moDateDate.setValue(miClient.getSession().getWorkingDate()); moDecPricePerTonReg.setEditable(false); moRadUpdateTicketsNone.setSelected(true); addAllListeners(); actionUpdateTicket(); } @Override public SDbRegistry getRegistry() throws Exception { SDbSeasonProducer registry = moRegistry.clone(); if (registry.isRegistryNew()) { registry.setPkSeasonId(moKeyItem.getValue()[0]); registry.setPkRegionId(moKeyItem.getValue()[1]); registry.setPkItemId(moKeyItem.getValue()[2]); registry.setPkProducerId(moKeyProducer.getValue()[0]); } if (moBoolFreight.getValue()) { registry.setPriceFreight(moDecPriceFreight.getValue()); } else { registry.setPriceFreight(0d); } if (moBoolPrcTon.getValue()) { registry.setPricePerTon(moDecPricePerTon.getValue()); } else { registry.setPricePerTon(0d); } registry.setPricePerTon(moBoolPrcTon.getValue()); registry.setFreightPayment(moBoolFreight.getValue()); if (moRadUpdateTicketsAsOfDate.isSelected() || moRadUpdateTicketsAll.isSelected()) { registry.setAuxUpdatePriceTonTickets(true); registry.setAuxUpdatePriceFreightTickets(true); registry.setAuxUpdateTicketDateStart(moRadUpdateTicketsAsOfDate.isSelected() ? moDateDate.getValue() : null); } return registry; } @Override public SGuiValidation validateForm() { SGuiValidation validation = moFields.validateFields(); return validation; } @Override public void itemStateChanged(ItemEvent e) { if (e.getSource() instanceof JCheckBox) { JCheckBox checkBox = (JCheckBox) e.getSource(); if (checkBox == moBoolFreight) { itemStateFreight(); } else if (checkBox == moBoolPrcTon) { itemStatePriceTon(); } } else if (e.getSource() instanceof JComboBox) { JComboBox comboBox = (JComboBox) e.getSource(); if (comboBox == moKeyProducer) { itemStateKeyProducer(); } else if (comboBox == moKeyItem) { setPriceTonRegion(); } } } @Override public void stateChanged(ChangeEvent e) { if (e.getSource() instanceof SBeanFieldRadio) { if ((SBeanFieldRadio) e.getSource() == moRadUpdateTicketsNone || (SBeanFieldRadio) e.getSource() == moRadUpdateTicketsAsOfDate || (SBeanFieldRadio) e.getSource() == moRadUpdateTicketsAll) { actionUpdateTicket(); } } } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof JButton) { JButton button = (JButton) e.getSource(); if (button == jbEditPrice) { actionItemEditPrice(true); } } } }
3e1f312e79c19d8f37adb6ac31af34798dda0eb2
592
java
Java
src/main/java/com/github/antonioazambuja/noxus/api/LeagueV4.java
antonioazambuja/noxus
b18c335640980a2797fbe698822e2a79101a8be1
[ "Apache-2.0" ]
1
2020-09-12T19:10:19.000Z
2020-09-12T19:10:19.000Z
src/main/java/com/github/antonioazambuja/noxus/api/LeagueV4.java
antonioazambuja/noxus
b18c335640980a2797fbe698822e2a79101a8be1
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/antonioazambuja/noxus/api/LeagueV4.java
antonioazambuja/noxus
b18c335640980a2797fbe698822e2a79101a8be1
[ "Apache-2.0" ]
null
null
null
42.285714
92
0.858108
13,187
package com.github.antonioazambuja.noxus.api; import com.github.antonioazambuja.noxus.resources.LeagueEntryDTO; import com.github.antonioazambuja.noxus.resources.LeagueListDTO; public interface LeagueV4 { LeagueListDTO getChallengerLeaguesByQueue(String queueName); LeagueEntryDTO[] getEntriesBySummoner(String encryptedSummonerId); LeagueEntryDTO[] getEntriesByQueueTierDivision(String queue, String tier, String division); LeagueListDTO getGrandmasterLeaguesByQueue(String queue); LeagueListDTO getLeagueById(String leagueId); LeagueListDTO getMasterLeaguesByQueue(String queue); }
3e1f315d84bacef125714c358f8170f6d7eb42ed
1,104
java
Java
bootleaf/src/main/java/com/example/bootleaf/Userss.java
cgl-dong/SSM
dccf4b13ecae2d095a0846e1ab0ce5cb59b041b6
[ "Apache-2.0" ]
1
2019-08-21T12:21:51.000Z
2019-08-21T12:21:51.000Z
bootleaf/src/main/java/com/example/bootleaf/Userss.java
cgl-dong/SSM
dccf4b13ecae2d095a0846e1ab0ce5cb59b041b6
[ "Apache-2.0" ]
10
2020-03-04T22:09:34.000Z
2021-12-09T21:17:07.000Z
bootleaf/src/main/java/com/example/bootleaf/Userss.java
cgl-dong/SSM
dccf4b13ecae2d095a0846e1ab0ce5cb59b041b6
[ "Apache-2.0" ]
null
null
null
19.034483
69
0.480072
13,188
package com.example.bootleaf; public class Userss { private String name; private String age; private String sex; private String work; @Override public String toString() { return "Userss{" + "name='" + name + '\'' + ", age='" + age + '\'' + ", sex='" + sex + '\'' + ", work='" + work + '\'' + '}'; } public Userss(String name, String age, String sex, String work) { this.name = name; this.age = age; this.sex = sex; this.work = work; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getWork() { return work; } public void setWork(String work) { this.work = work; } }
3e1f31b01232d99504dc014b6b2105bd32ffbe06
2,120
java
Java
toolbardrawerlayoutdemo/src/main/java/com/baurine/toolbardrawerlayoutdemo/MainActivity.java
baurine/android-practice
ae4816083f793fb00b17d2b72096c25b16f935d6
[ "MIT" ]
1
2015-07-07T11:31:20.000Z
2015-07-07T11:31:20.000Z
toolbardrawerlayoutdemo/src/main/java/com/baurine/toolbardrawerlayoutdemo/MainActivity.java
baurine/android-practice
ae4816083f793fb00b17d2b72096c25b16f935d6
[ "MIT" ]
null
null
null
toolbardrawerlayoutdemo/src/main/java/com/baurine/toolbardrawerlayoutdemo/MainActivity.java
baurine/android-practice
ae4816083f793fb00b17d2b72096c25b16f935d6
[ "MIT" ]
null
null
null
29.444444
88
0.671698
13,189
package com.baurine.toolbardrawerlayoutdemo; import android.graphics.Color; import android.os.Bundle; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.widget.ArrayAdapter; import android.widget.ListView; import butterknife.ButterKnife; import butterknife.InjectView; /* 教程来源:http://chenqichao.me/2014/12/08/108-Android-Toolbar-DrawerLayout-01/ */ public class MainActivity extends AppCompatActivity { @InjectView(R.id.tl_custom) Toolbar mToolbar; @InjectView(R.id.dl_custom) DrawerLayout mDrawerLayout; @InjectView(R.id.lv_drawer_menu) ListView mLvDrawerMenu; private static final String[] mMenuItems = { "List Item 01", "List Item 02", "List Item 03", "List Item 04", }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.inject(this); setupToolbar(); setupDrawerLayout(); setupDrawerMenu(); } private void setupToolbar() { mToolbar.setTitle("Toolbar"); mToolbar.setTitleTextColor(Color.parseColor("#ffffff")); setSupportActionBar(mToolbar); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } private void setupDrawerLayout() { ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.drawer_open, R.string.drawer_close); drawerToggle.syncState(); mDrawerLayout.setDrawerListener(drawerToggle); } private void setupDrawerMenu() { ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, mMenuItems); mLvDrawerMenu.setAdapter(arrayAdapter); } }
3e1f31dc3b073ddc22919c7e8b385619bf934429
3,091
java
Java
java/classes3/com/ziroom/ziroomcustomer/model/HouseRoommate.java
gaoht/house
b9e63db1a4975b614c422fed3b5b33ee57ea23fd
[ "Apache-2.0" ]
1
2020-05-08T05:35:32.000Z
2020-05-08T05:35:32.000Z
java/classes3/com/ziroom/ziroomcustomer/model/HouseRoommate.java
gaoht/house
b9e63db1a4975b614c422fed3b5b33ee57ea23fd
[ "Apache-2.0" ]
null
null
null
java/classes3/com/ziroom/ziroomcustomer/model/HouseRoommate.java
gaoht/house
b9e63db1a4975b614c422fed3b5b33ee57ea23fd
[ "Apache-2.0" ]
3
2018-09-07T08:15:08.000Z
2020-05-22T03:59:12.000Z
19.080247
128
0.688127
13,190
package com.ziroom.ziroomcustomer.model; import java.io.Serializable; public class HouseRoommate implements Serializable, Comparable { private String gender; private String header_image; private String house_code; private String house_company; private String house_dzz; private String house_type; private String room_code; private String room_photos; private String room_price; private String show_type; private String sublet_attestation; private String xingzuo; public int compareTo(Object paramObject) { paramObject = (HouseRoommate)paramObject; try { int i = Integer.parseInt(this.house_code); int j = Integer.parseInt(((HouseRoommate)paramObject).getHouse_code()); return i - j; } catch (NumberFormatException paramObject) { ((NumberFormatException)paramObject).printStackTrace(); } return 0; } public String getGender() { return this.gender; } public String getHeader_image() { return this.header_image; } public String getHouse_code() { return this.house_code; } public String getHouse_company() { return this.house_company; } public String getHouse_dzz() { return this.house_dzz; } public String getHouse_type() { return this.house_type; } public String getRoom_code() { return this.room_code; } public String getRoom_photos() { return this.room_photos; } public String getRoom_price() { return this.room_price; } public String getShow_type() { return this.show_type; } public String getSublet_attestation() { return this.sublet_attestation; } public String getXingzuo() { return this.xingzuo; } public void setGender(String paramString) { this.gender = paramString; } public void setHeader_image(String paramString) { this.header_image = paramString; } public void setHouse_code(String paramString) { this.house_code = paramString; } public void setHouse_company(String paramString) { this.house_company = paramString; } public void setHouse_dzz(String paramString) { this.house_dzz = paramString; } public void setHouse_type(String paramString) { this.house_type = paramString; } public void setRoom_code(String paramString) { this.room_code = paramString; } public void setRoom_photos(String paramString) { this.room_photos = paramString; } public void setRoom_price(String paramString) { this.room_price = paramString; } public void setShow_type(String paramString) { this.show_type = paramString; } public void setSublet_attestation(String paramString) { this.sublet_attestation = paramString; } public void setXingzuo(String paramString) { this.xingzuo = paramString; } } /* Location: /Users/gaoht/Downloads/zirom/classes3-dex2jar.jar!/com/ziroom/ziroomcustomer/model/HouseRoommate.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
3e1f3212c32a61380f576db4e9b9269091295423
687
java
Java
src/main/java/com/petclinic/api/rest/VetServiceEndpoint.java
sg4j/springboot-ignite-consul
fbdca13658d52ced966a5ca716603a5eb3bd77f1
[ "Apache-2.0" ]
1
2019-04-07T18:45:26.000Z
2019-04-07T18:45:26.000Z
src/main/java/com/petclinic/api/rest/VetServiceEndpoint.java
sg4j/springboot-ignite-consul
fbdca13658d52ced966a5ca716603a5eb3bd77f1
[ "Apache-2.0" ]
null
null
null
src/main/java/com/petclinic/api/rest/VetServiceEndpoint.java
sg4j/springboot-ignite-consul
fbdca13658d52ced966a5ca716603a5eb3bd77f1
[ "Apache-2.0" ]
null
null
null
31.227273
80
0.79476
13,191
package com.petclinic.api.rest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.petclinic.repository.springdatajpa.postgres.SpringDataVetRepository; @RestController public class VetServiceEndpoint { @Autowired SpringDataVetRepository vetRepository; @RequestMapping("/vet/id") public String getVetById(@RequestParam(value="id") Integer id){ System.out.println("Came here in getVetById"); return vetRepository.findById(id).toString(); } }
3e1f339593ed7bc0a4f663399d921be8498810e4
1,328
java
Java
src/main/java/org/tugraz/sysds/runtime/compress/cocode/ColumnGroupPartitioner.java
Shafaq-Siddiqi/systemds
a5a8d4e0040308993d7892be11dae63c81575efd
[ "Apache-2.0" ]
42
2018-11-23T16:55:30.000Z
2021-03-15T15:01:44.000Z
src/main/java/org/tugraz/sysds/runtime/compress/cocode/ColumnGroupPartitioner.java
kev-inn/systemds
2d0f219e02af1174a97a04191590441821fbfab6
[ "Apache-2.0" ]
120
2019-02-07T22:13:40.000Z
2020-04-15T10:42:17.000Z
src/main/java/org/tugraz/sysds/runtime/compress/cocode/ColumnGroupPartitioner.java
kev-inn/systemds
2d0f219e02af1174a97a04191590441821fbfab6
[ "Apache-2.0" ]
28
2019-02-07T11:13:14.000Z
2021-12-20T10:14:25.000Z
36.888889
117
0.762048
13,192
/* * Modifications Copyright 2020 Graz University of Technology * * 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.tugraz.sysds.runtime.compress.cocode; import java.util.HashMap; import java.util.List; import org.tugraz.sysds.runtime.compress.cocode.PlanningCoCoder.GroupableColInfo; public abstract class ColumnGroupPartitioner { /** * Partitions a list of columns into a list of partitions that contains subsets of columns. Note that this call must * compute a complete and disjoint partitioning. * * @param groupCols list of columns * @param groupColsInfo list of column infos * @return list of partitions (where each partition is a list of columns) */ public abstract List<int[]> partitionColumns(List<Integer> groupCols, HashMap<Integer, GroupableColInfo> groupColsInfo); }
3e1f33cb9e8878f5c09aa8c0f64d131e8347e74a
3,383
java
Java
main/plugins/org.talend.model/src/main/java/org/talend/core/model/properties/FileItem.java
dmytro-sylaiev/tcommon-studio-se
b75fadfb9bd1a42897073fe2984f1d4fb42555bd
[ "Apache-2.0" ]
75
2015-01-29T03:23:32.000Z
2022-02-26T07:05:40.000Z
main/plugins/org.talend.model/src/main/java/org/talend/core/model/properties/FileItem.java
dmytro-sylaiev/tcommon-studio-se
b75fadfb9bd1a42897073fe2984f1d4fb42555bd
[ "Apache-2.0" ]
813
2015-01-21T09:36:31.000Z
2022-03-30T01:15:29.000Z
main/plugins/org.talend.model/src/main/java/org/talend/core/model/properties/FileItem.java
dmytro-sylaiev/tcommon-studio-se
b75fadfb9bd1a42897073fe2984f1d4fb42555bd
[ "Apache-2.0" ]
272
2015-01-08T06:47:46.000Z
2022-02-09T23:22:27.000Z
32.219048
123
0.593556
13,193
/** * <copyright> </copyright> * * $Id$ */ package org.talend.core.model.properties; /** * <!-- begin-user-doc --> A representation of the model object '<em><b>File Item</b></em>'. <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link org.talend.core.model.properties.FileItem#getName <em>Name</em>}</li> * <li>{@link org.talend.core.model.properties.FileItem#getExtension <em>Extension</em>}</li> * <li>{@link org.talend.core.model.properties.FileItem#getContent <em>Content</em>}</li> * </ul> * </p> * * @see org.talend.core.model.properties.PropertiesPackage#getFileItem() * @model abstract="true" * @generated */ public interface FileItem extends Item { /** * Returns the value of the '<em><b>Name</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Name</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Name</em>' attribute. * @see #setName(String) * @see org.talend.core.model.properties.PropertiesPackage#getFileItem_Name() * @model * @generated */ String getName(); /** * Sets the value of the '{@link org.talend.core.model.properties.FileItem#getName <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Name</em>' attribute. * @see #getName() * @generated */ void setName(String value); /** * Returns the value of the '<em><b>Extension</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Extension</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Extension</em>' attribute. * @see #setExtension(String) * @see org.talend.core.model.properties.PropertiesPackage#getFileItem_Extension() * @model * @generated */ String getExtension(); /** * Sets the value of the '{@link org.talend.core.model.properties.FileItem#getExtension <em>Extension</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Extension</em>' attribute. * @see #getExtension() * @generated */ void setExtension(String value); /** * Returns the value of the '<em><b>Content</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Content</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Content</em>' reference. * @see #setContent(ByteArray) * @see org.talend.core.model.properties.PropertiesPackage#getFileItem_Content() * @model * @generated */ ByteArray getContent(); /** * Sets the value of the '{@link org.talend.core.model.properties.FileItem#getContent <em>Content</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Content</em>' reference. * @see #getContent() * @generated */ void setContent(ByteArray value); } // FileItem
3e1f34067cba9b562f2b2df33ff6953cb36b45a9
8,742
java
Java
ask-mitigation-android/src/com/jonas/reedsolomon/Berlekamp.java
jonasrmichel/digital-voices
23fb353712aaf8214a0877a8698d27dc9228fe43
[ "MIT" ]
null
null
null
ask-mitigation-android/src/com/jonas/reedsolomon/Berlekamp.java
jonasrmichel/digital-voices
23fb353712aaf8214a0877a8698d27dc9228fe43
[ "MIT" ]
null
null
null
ask-mitigation-android/src/com/jonas/reedsolomon/Berlekamp.java
jonasrmichel/digital-voices
23fb353712aaf8214a0877a8698d27dc9228fe43
[ "MIT" ]
null
null
null
25.409884
80
0.603821
13,194
package com.jonas.reedsolomon; /** * Copyright Henry Minsky (nnheo@example.com) 1991-2009 (Ported to Java by Jonas * Michel 2012) * * This is a direct port of RSCODE by Henry Minsky * http://rscode.sourceforge.net/ * * 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. * * Commercial licensing is available under a separate license, please contact * author for details. * * Source code is available at * http://code.google.com/p/mobile-acoustic-modems-in-action/ * * * Berlekamp-Peterson and Berlekamp-Massey Algorithms for error-location * * From Cain, Clark, "Error-Correction Coding For Digital Communications", pp. * 205. * * This finds the coefficients of the error locator polynomial. * * The roots are then found by looking for the values of a^n where evaluating * the polynomial yields zero. * * Error correction is done using the error-evaluator equation on pp 207. * */ public class Berlekamp { private int parityBytes; private int maxDeg; private int[] synBytes; /* * The Error Locator Polynomial, also known as Lambda or Sigma. Lambda[0] == * 1 */ private int Lambda[]; /* The Error Evaluator Polynomial */ private int Omega[]; /* error locations found using Chien's search */ private int ErrorLocs[] = new int[256]; private int NErrors; /* erasure flags */ private int ErasureLocs[] = new int[256]; private int NErasures; public Berlekamp(int parityBytes, int[] synBytes) { this.parityBytes = parityBytes; maxDeg = parityBytes * 2; this.synBytes = synBytes; Lambda = new int[maxDeg]; Omega = new int[maxDeg]; } /* * From Cain, Clark, "Error-Correction Coding For Digital Communications", * pp. 216. */ private void Modified_Berlekamp_Massey() { int n, L, L2, k, d, i; int psi[] = new int[maxDeg], psi2[] = new int[maxDeg], D[] = new int[maxDeg]; int gamma[] = new int[maxDeg]; /* initialize Gamma, the erasure locator polynomial */ init_gamma(gamma); /* initialize to z */ copy_poly(D, gamma); mul_z_poly(D); copy_poly(psi, gamma); k = -1; L = NErasures; for (n = NErasures; n < parityBytes; n++) { d = compute_discrepancy(psi, synBytes, L, n); if (d != 0) { /* psi2 = psi - d*D */ for (i = 0; i < maxDeg; i++) psi2[i] = psi[i] ^ Galois.gmult(d, D[i]); if (L < (n - k)) { L2 = n - k; k = n - L; /* D = scale_poly(Galois.ginv(d), psi); */ for (i = 0; i < maxDeg; i++) D[i] = Galois.gmult(psi[i], Galois.ginv(d)); L = L2; } /* psi = psi2 */ for (i = 0; i < maxDeg; i++) psi[i] = psi2[i]; } mul_z_poly(D); } for (i = 0; i < maxDeg; i++) Lambda[i] = psi[i]; compute_modified_omega(); } /* * given Psi (called Lambda in Modified_Berlekamp_Massey) and RS.synBytes, * compute the combined erasure/error evaluator polynomial as Psi*S mod z^4 */ private void compute_modified_omega() { int i; int product[] = new int[maxDeg * 2]; mult_polys(product, Lambda, synBytes); zero_poly(Omega); for (i = 0; i < parityBytes; i++) Omega[i] = product[i]; } /* polynomial multiplication */ public void mult_polys(int dst[], int p1[], int p2[]) { int i, j; int tmp1[] = new int[maxDeg * 2]; for (i = 0; i < (maxDeg * 2); i++) dst[i] = 0; for (i = 0; i < maxDeg; i++) { for (j = maxDeg; j < (maxDeg * 2); j++) tmp1[j] = 0; /* scale tmp1 by p1[i] */ for (j = 0; j < maxDeg; j++) tmp1[j] = Galois.gmult(p2[j], p1[i]); /* and mult (shift) tmp1 right by i */ for (j = (maxDeg * 2) - 1; j >= i; j--) tmp1[j] = tmp1[j - i]; for (j = 0; j < i; j++) tmp1[j] = 0; /* add into partial product */ for (j = 0; j < (maxDeg * 2); j++) dst[j] ^= tmp1[j]; } } /* gamma = product (1-z*a^Ij) for erasure locs Ij */ private void init_gamma(int gamma[]) { int e; int tmp[] = new int[maxDeg]; zero_poly(gamma); zero_poly(tmp); gamma[0] = 1; for (e = 0; e < NErasures; e++) { copy_poly(tmp, gamma); scale_poly(Galois.gexp[ErasureLocs[e]], tmp); mul_z_poly(tmp); add_polys(gamma, tmp); } } private void compute_next_omega(int d, int A[], int dst[], int src[]) { int i; for (i = 0; i < maxDeg; i++) { dst[i] = src[i] ^ Galois.gmult(d, A[i]); } } private int compute_discrepancy(int lambda[], int S[], int L, int n) { int i, sum = 0; for (i = 0; i <= L; i++) sum ^= Galois.gmult(lambda[i], S[n - i]); return (sum); } /********** polynomial arithmetic *******************/ public void add_polys(int dst[], int src[]) { int i; for (i = 0; i < maxDeg; i++) dst[i] ^= src[i]; } public void copy_poly(int dst[], int src[]) { int i; for (i = 0; i < maxDeg; i++) dst[i] = src[i]; } public void scale_poly(int k, int poly[]) { int i; for (i = 0; i < maxDeg; i++) poly[i] = Galois.gmult(k, poly[i]); } public void zero_poly(int poly[]) { int i; for (i = 0; i < maxDeg; i++) poly[i] = 0; } /* multiply by z, i.e., shift right by 1 */ public void mul_z_poly(int src[]) { int i; for (i = maxDeg - 1; i > 0; i--) src[i] = src[i - 1]; src[0] = 0; } /* * Finds all the roots of an error-locator polynomial with coefficients * Lambda[j] by evaluating Lambda at successive values of alpha. * * This can be tested with the decoder's equations case. */ private void Find_Roots() { int sum, r, k; NErrors = 0; for (r = 1; r < 256; r++) { sum = 0; /* evaluate lambda at r */ for (k = 0; k < parityBytes + 1; k++) { sum ^= Galois.gmult(Galois.gexp[(k * r) % 255], Lambda[k]); } if (sum == 0) { ErrorLocs[NErrors] = (255 - r); NErrors++; if (Settings.DEBUG) System.err.println("Root found at r = " + r + ", (255-r) = " + (255 - r)); } } } /* * Combined Erasure And Error Magnitude Computation * * Pass in the codeword, its size in bytes, as well as an array of any known * erasure locations, along the number of these erasures. * * Evaluate Omega(actually Psi)/Lambda' at the roots alpha^(-i) for error * locs i. * * Returns 1 if everything ok, or 0 if an out-of-bounds error is found */ public int correct_errors_erasures(byte[] codeword, int csize, int nerasures, int erasures[]) { int r, i, j, err; /* * If you want to take advantage of erasure correction, be sure to set * NErasures and ErasureLocs[] with the locations of erasures. */ NErasures = nerasures; for (i = 0; i < NErasures; i++) ErasureLocs[i] = erasures[i]; Modified_Berlekamp_Massey(); Find_Roots(); if ((NErrors <= parityBytes) && NErrors > 0) { /* first check for illegal error locs */ for (r = 0; r < NErrors; r++) { if (ErrorLocs[r] >= csize) { if (Settings.DEBUG) System.err.println("Error loc i=" + i + " outside of codeword length " + csize); return (0); } } for (r = 0; r < NErrors; r++) { int num, denom; i = ErrorLocs[r]; /* evaluate Omega at alpha^(-i) */ num = 0; for (j = 0; j < maxDeg; j++) num ^= Galois.gmult(Omega[j], Galois.gexp[((255 - i) * j) % 255]); /* * evaluate Lambda' (derivative) at alpha^(-i) ; all odd powers * disappear */ denom = 0; for (j = 1; j < maxDeg; j += 2) { denom ^= Galois.gmult(Lambda[j], Galois.gexp[((255 - i) * (j - 1)) % 255]); } err = Galois.gmult(num, Galois.ginv(denom)); if (Settings.DEBUG) System.err.println("Error magnitude 0x" + Integer.toHexString(err) + " at loc " + (csize - i)); codeword[csize - i - 1] ^= err; } return (1); } else { if (Settings.DEBUG && NErrors > 0) System.err.println("Uncorrectable codeword"); return (0); } } }
3e1f34f4042b58cce66364eeb86f237fcc8c75d3
1,125
java
Java
aiml-jaxb/src/main/java/ai/saxatus/aiml/internal/parsing/tags/abstracts/AbstractContentEnclosingTag.java
SebastianGlass/aiml-core
c8d0ea4818a0673b9ac368021d84fa38f468f51c
[ "MIT" ]
null
null
null
aiml-jaxb/src/main/java/ai/saxatus/aiml/internal/parsing/tags/abstracts/AbstractContentEnclosingTag.java
SebastianGlass/aiml-core
c8d0ea4818a0673b9ac368021d84fa38f468f51c
[ "MIT" ]
null
null
null
aiml-jaxb/src/main/java/ai/saxatus/aiml/internal/parsing/tags/abstracts/AbstractContentEnclosingTag.java
SebastianGlass/aiml-core
c8d0ea4818a0673b9ac368021d84fa38f468f51c
[ "MIT" ]
null
null
null
25
80
0.644444
13,195
package ai.saxatus.aiml.internal.parsing.tags.abstracts; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlMixed; import ai.saxatus.aiml.api.parsing.tags.ContentEnclosingNode; public abstract class AbstractContentEnclosingTag extends AbstractAIMLContentTag implements ContentEnclosingNode<AbstractAIMLContentTag> { @XmlElementRef @XmlMixed private List<AbstractAIMLContentTag> content; @Override public List<AbstractAIMLContentTag> getContent() { return content; } @Override public void setContent(List<AbstractAIMLContentTag> content) { this.content = content; } protected String contentToString() { if (getContent() == null) { return ""; } List<?> a = new ArrayList<>(getContent()); return a.stream() .map(Object::toString) .map(String::trim) .collect(Collectors.joining(" ")); } }
3e1f3531cfdaceca5407e883ff3ffb8a2e8c6077
2,690
java
Java
Eclipse/semi-compilado/src/net/javaguides/usermanagement/web/FilaDePacienteServlet.java
lucas-leme/CovidNet
68fcc0f3faf646cd2a3fbbf414b3c52d770fcad7
[ "MIT" ]
1
2020-11-13T14:46:03.000Z
2020-11-13T14:46:03.000Z
Eclipse/semi-compilado/src/net/javaguides/usermanagement/web/FilaDePacienteServlet.java
lucas-leme/CovidNet
68fcc0f3faf646cd2a3fbbf414b3c52d770fcad7
[ "MIT" ]
6
2020-11-13T19:52:11.000Z
2020-12-03T16:19:18.000Z
Eclipse/semi-compilado/src/net/javaguides/usermanagement/web/FilaDePacienteServlet.java
lucas-leme/CovidNet
68fcc0f3faf646cd2a3fbbf414b3c52d770fcad7
[ "MIT" ]
null
null
null
30.224719
134
0.788476
13,196
package net.javaguides.usermanagement.web; import java.io.IOException; import java.sql.SQLException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.javaguides.usermanagement.dao.FilaDePacienteDAO; import net.javaguides.usermanagement.model.FilaDePaciente; import net.javaguides.usermanagement.model.Paciente; @WebServlet( urlPatterns = {"/fila_de_pacientes","/fila_de_pacientes/solicita_uti", "/fila_de_pacientes/list","/fila_de_pacientes/pega_primeiro"} ) public class FilaDePacienteServlet extends HttpServlet { private static final long serialVersionUID = 1L; private FilaDePacienteDAO filaDePacienteDAO; private static final String root = "/semi-compilado"; public void init() { filaDePacienteDAO = new FilaDePacienteDAO(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getServletPath(); try { switch (action) { case "/fila_de_pacientes/solicita_uti": solicitaUti(request, response); break; case "/fila_de_pacientes/list": mostraFila(request, response); break; case "/fila_de_pacientes/pega_primeiro": pegaPrimeiro(request, response); break; default: break; } } catch (SQLException ex) { throw new ServletException(ex); } } private void solicitaUti(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException, ServletException { int prontuario_id = Integer.parseInt(request.getParameter("prontuario_id")); filaDePacienteDAO.solicitaUti(prontuario_id); response.sendRedirect(root); } private void mostraFila(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException, ServletException { List<FilaDePaciente> lista_de_pacientes = filaDePacienteDAO.selectAllPacientesNaFila(); request.setAttribute("mostraFila", lista_de_pacientes); RequestDispatcher dispatcher = request.getRequestDispatcher("/fila_de_pacientes-list.jsp"); dispatcher.forward(request, response); } private void pegaPrimeiro(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException, ServletException { filaDePacienteDAO.selectPrimeiroPacienteDaFila(); response.sendRedirect(root); } }
3e1f37d9425b6e6dc96963eb751ef9c4a46525a0
5,535
java
Java
WS6/SoalSusah(20).java
VikriAulia/Fasilkom-SDAGasal2018
84569df4be7f44a5af1c6576ad3f484a198ae627
[ "MIT" ]
null
null
null
WS6/SoalSusah(20).java
VikriAulia/Fasilkom-SDAGasal2018
84569df4be7f44a5af1c6576ad3f484a198ae627
[ "MIT" ]
null
null
null
WS6/SoalSusah(20).java
VikriAulia/Fasilkom-SDAGasal2018
84569df4be7f44a5af1c6576ad3f484a198ae627
[ "MIT" ]
null
null
null
21.87747
92
0.626378
13,198
/** * */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.Comparator; import java.util.ArrayList; import java.util.Collections; /** * @author vikri * @author 1706124182 */ public class SoalSusah { /** * @param args */ public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String inputs[] = reader.readLine().split(" "); int N = Integer.parseInt(inputs[0]); int M = Integer.parseInt(inputs[1]); // TODO: Implement this ArrayList<CustomPriorityQueue> prioritasPerorangan = new ArrayList<CustomPriorityQueue>(); for (int i = 0; i < N; i++) { inputs = reader.readLine().split(" "); String nama = inputs[0]; int type = Integer.parseInt(inputs[1]); int minimal = Integer.parseInt(inputs[2]); prioritasPerorangan.add(i,new CustomPriorityQueue(nama, type, minimal) ); } // TODO: Implement this like this for (int i = 0; i < M; i++) { inputs = reader.readLine().split(" "); int index = Integer.parseInt(inputs[0]); int poin = Integer.parseInt(inputs[1]); int waktu = Integer.parseInt(inputs[2]); Persoalan soal = new Persoalan(poin, waktu); CustomPriorityQueue ini = prioritasPerorangan.get(index); ini.insert(soal); } // TODO: Implement this like this using ctrl + space for (int i = 0; i < N; i++) { CustomPriorityQueue current = prioritasPerorangan.get(i); // TODO: Implement this System.out.println(current.getNama()+": "+ current.countMinimalValue()); } } } class Persoalan { private int poin; private int waktu; public Persoalan(int poin, int waktu) { this.poin = poin; this.waktu = waktu; } public int getPoin() { return this.poin; } public int getWaktu() { return this.waktu; } } class SoalPoinComparator implements Comparator<Persoalan> { // TODO: Implement this // sumber algoritma dari hasil membaca soal dan // contoh penggunaan comparator dari GeeksforGeeks public int compare(Persoalan p1, Persoalan p2) { if (p1.getPoin()<p2.getPoin()) { return 1; }else if(p1.getPoin()>p2.getPoin()) { return -1; } return 0; } } class SoalWaktuComparator implements Comparator<Persoalan> { // TODO: Implement this // sumber algorima dari hasil membaca soal dan // contoh penggunaan comparator dari GeeksforGeeks public int compare(Persoalan p1, Persoalan p2) { if (p1.getWaktu()>p2.getWaktu()) { return 1; }else if(p1.getWaktu()<p2.getWaktu()) { return -1; } return 0; } } // Implementasi PQ menggunakan unsorted array method class CustomPriorityQueue { private ArrayList<Persoalan> array; private int size; private String nama; private int type; private int nilaiMinimal; public CustomPriorityQueue(String nama, int type, int nilaiMinimal) { this.array = new ArrayList<Persoalan>(); this.size = 0; this.nama = nama; this.type = type; this.nilaiMinimal = nilaiMinimal; } public boolean empty() { return size == 0; } // TODO: Implement this public void insert(Persoalan soal) { //diatur masuknya //ide algoritmanya seperti insert HeapTree , //kemudian di putar otak agar bisa sort generic type array.add(soal); size++; Collections.sort(array, this.getComparator()); } public Comparator<Persoalan> getComparator() { if (this.type == 1) { return new SoalPoinComparator(); } return new SoalWaktuComparator(); } public Persoalan remove() { if (size == 0) { return null; } int idx = 0; Persoalan result = this.array.get(0); this.array.set(0, this.array.get(size - 1)); this.array.remove(size - 1); size--; Comparator < Persoalan > comparator = this.getComparator(); while (idx < size) { int l = 2 * idx + 1; int r = 2 * idx + 2; Persoalan val = this.array.get(idx); int dest = -1; if (l < size) { if (comparator.compare(this.array.get(l), val) > 0) { val = this.array.get(l); dest = l; } } if (r < size) { if (comparator.compare(this.array.get(r), val) > 0) { val = this.array.get(r); dest = r; } } if (dest == -1) { break; } Persoalan temp = this.array.get(idx); this.array.set(idx, val); this.array.set(dest, temp); idx = dest; } return result; } // TODO: Implement this public int countMinimalValue() { // int ygdioutput = 0; int hitung = 0; // if(type==1) { // int nilai = 0; // int i = 0; // int j = size; // while (j>0&&nilai<=nilaiMinimal) { // Persoalan current = array.get(i); // nilai += current.getPoin(); // ygdioutput += current.getWaktu(); // i++; // j--; // } // if (nilai<nilaiMinimal) { // return -1; // }else { // return ygdioutput; // } // }else { // int poin = 0; // int i = 0; // int j = size; try { while (hitung < nilaiMinimal) { Persoalan current = remove(); if (type==1) { ygdioutput+=current.getWaktu(); nilaiMinimal-=current.getPoin(); }else { ygdioutput+=current.getPoin(); nilaiMinimal-=current.getWaktu(); } } return ygdioutput; }catch (NullPointerException e) { // TODO: handle exception return -1; } // while (j>0) { // while (nilai<nilaiMinimal) { // // nilai += current.getPoin(); // ygdioutput += current.getWaktu(); // i++; // j--; // } // } // return nilai; // } } public String getNama() { return this.nama; } }
3e1f37f6205fedcde42d7edabfffd1e384678e0e
1,810
java
Java
src/test/java/michapehlivan/discordbotlib/SlashCommandTest.java
MichaPehlivan/discord-bot-library
cadd92bf66530efb03eaffbe67214b5c970027f9
[ "Apache-2.0" ]
null
null
null
src/test/java/michapehlivan/discordbotlib/SlashCommandTest.java
MichaPehlivan/discord-bot-library
cadd92bf66530efb03eaffbe67214b5c970027f9
[ "Apache-2.0" ]
null
null
null
src/test/java/michapehlivan/discordbotlib/SlashCommandTest.java
MichaPehlivan/discord-bot-library
cadd92bf66530efb03eaffbe67214b5c970027f9
[ "Apache-2.0" ]
null
null
null
34.150943
86
0.70663
13,199
package michapehlivan.discordbotlib; import discord4j.core.GatewayDiscordClient; import discord4j.core.event.domain.interaction.ChatInputInteractionEvent; import discord4j.core.object.command.ApplicationCommand; import discord4j.discordjson.json.ApplicationCommandRequest; import michapehlivan.discordbotlib.interactions.applicationcommands.SlashCommand; import reactor.core.publisher.Mono; public class SlashCommandTest implements SlashCommand { @Override public String name() { return "testcommand"; } @Override public void createGlobal(GatewayDiscordClient gateway) { long applicationId = gateway.getRestClient().getApplicationId().block(); ApplicationCommandRequest commandRequest = ApplicationCommandRequest.builder() .name(name()) .description("a test command") .type(ApplicationCommand.Type.CHAT_INPUT.getValue()) .build(); gateway.getRestClient().getApplicationService() .createGlobalApplicationCommand(applicationId, commandRequest) .subscribe(); } @Override public void createGuild(GatewayDiscordClient gateway, long guildId) { long applicationId = gateway.getRestClient().getApplicationId().block(); ApplicationCommandRequest commandRequest = ApplicationCommandRequest.builder() .name(name()) .description("a test command") .type(ApplicationCommand.Type.CHAT_INPUT.getValue()) .build(); gateway.getRestClient().getApplicationService() .createGuildApplicationCommand(applicationId, guildId, commandRequest) .subscribe(); } @Override public Mono<Void> execute(ChatInputInteractionEvent event) { return event.reply("Test!!!"); } }
3e1f38a22d0a59c6e66c8207b6ace297dc785fbb
887
java
Java
src/main/java/com/clexel/dp/behavior/observer/pull/Observer.java
jonathanzhan/design-pattern
3b118a1e0769b78127ed806b95ff011db5b15be8
[ "Apache-2.0" ]
null
null
null
src/main/java/com/clexel/dp/behavior/observer/pull/Observer.java
jonathanzhan/design-pattern
3b118a1e0769b78127ed806b95ff011db5b15be8
[ "Apache-2.0" ]
null
null
null
src/main/java/com/clexel/dp/behavior/observer/pull/Observer.java
jonathanzhan/design-pattern
3b118a1e0769b78127ed806b95ff011db5b15be8
[ "Apache-2.0" ]
null
null
null
26.235294
75
0.699552
13,200
/* * Copyright 2014-2019 ychag@example.com(Jonathan) * * 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.clexel.dp.behavior.observer.pull; /** * 观察者抽象接口 * * @author Jonathan * @version 1.0.0 * @date 2019/8/12 16:52 * @since 1.0.0+ */ public interface Observer { /** * 观察者响应 * @param subject 抽象主题对象 */ void response(Subject subject); }
3e1f38d5ab7fff50193f6b20cf70ee2a695b0b33
1,183
java
Java
app/src/main/java/cn/artaris/androidknowledge/Delegate/SalesInvocationHandler.java
ArtarisCN/AndroidKnowledge
d5226b6a46b3e0df866f353afef40b2e3b6f8ff1
[ "Apache-2.0" ]
null
null
null
app/src/main/java/cn/artaris/androidknowledge/Delegate/SalesInvocationHandler.java
ArtarisCN/AndroidKnowledge
d5226b6a46b3e0df866f353afef40b2e3b6f8ff1
[ "Apache-2.0" ]
null
null
null
app/src/main/java/cn/artaris/androidknowledge/Delegate/SalesInvocationHandler.java
ArtarisCN/AndroidKnowledge
d5226b6a46b3e0df866f353afef40b2e3b6f8ff1
[ "Apache-2.0" ]
null
null
null
25.717391
119
0.655114
13,201
package cn.artaris.androidknowledge.Delegate; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * delegate * LeetCode * 2019.03.19.16:37 * * @author : artairs */ public class SalesInvocationHandler implements InvocationHandler { //代理类持有一个委托类的对象引用 private Object delegate; /** * 绑定委托对象并返回一个代理类 * * @param delegate * @return */ public Object bind(Object delegate) { this.delegate = delegate; return Proxy.newProxyInstance(delegate.getClass().getClassLoader(), delegate.getClass().getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println(proxy.getClass().getInterfaces()[0]); System.out.println("Enter method " + method.getName()); long start = System.currentTimeMillis(); Object result = method.invoke(delegate, args); long end = System.currentTimeMillis(); System.out.println("Exit method " + method.getName()); System.out.println("执行时间:" + (end - start)); return result; } }
3e1f3a1c321138608e0fd3945d774fb6d99cb8ff
1,193
java
Java
core/src/com/crashinvaders/texturepackergui/controllers/model/ScaleFactorModel.java
alexkarezin/gdx-texture-packer-gui
3fa093c078660e04c0cf3323d98a3d7bbbfab1be
[ "Apache-2.0" ]
479
2016-09-05T01:00:15.000Z
2022-03-24T09:49:23.000Z
core/src/com/crashinvaders/texturepackergui/controllers/model/ScaleFactorModel.java
alexkarezin/gdx-texture-packer-gui
3fa093c078660e04c0cf3323d98a3d7bbbfab1be
[ "Apache-2.0" ]
126
2016-09-06T21:11:08.000Z
2022-03-30T14:09:02.000Z
core/src/com/crashinvaders/texturepackergui/controllers/model/ScaleFactorModel.java
alexkarezin/gdx-texture-packer-gui
3fa093c078660e04c0cf3323d98a3d7bbbfab1be
[ "Apache-2.0" ]
82
2016-09-06T21:53:34.000Z
2022-03-12T17:33:22.000Z
29.097561
95
0.720034
13,202
package com.crashinvaders.texturepackergui.controllers.model; import com.badlogic.gdx.tools.texturepacker.TexturePacker; import com.crashinvaders.common.statehash.StateHashUtils; import com.crashinvaders.common.statehash.StateHashable; public class ScaleFactorModel implements StateHashable { private final String suffix; private final float factor; private final TexturePacker.Resampling resampling; public ScaleFactorModel(String suffix, float factor, TexturePacker.Resampling resampling) { this.suffix = suffix; this.factor = factor; this.resampling = resampling; } public ScaleFactorModel(ScaleFactorModel scaleFactorModel) { this.suffix = scaleFactorModel.getSuffix(); this.factor = scaleFactorModel.getFactor(); this.resampling = scaleFactorModel.getResampling(); } public String getSuffix() { return suffix; } public float getFactor() { return factor; } public TexturePacker.Resampling getResampling() { return resampling; } @Override public int computeStateHash() { return StateHashUtils.computeHash(suffix, factor, resampling); } }
3e1f3d390744df95216a06564aa2788c77ae3ffe
2,634
java
Java
backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/quota/QuotaDependencyTest.java
emesika/ovirt-engine
db6458e688eeb385b683a0c9c5530917cd6dfe5f
[ "Apache-2.0" ]
347
2015-01-20T14:13:21.000Z
2022-03-31T17:53:11.000Z
backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/quota/QuotaDependencyTest.java
emesika/ovirt-engine
db6458e688eeb385b683a0c9c5530917cd6dfe5f
[ "Apache-2.0" ]
128
2015-05-22T19:14:32.000Z
2022-03-31T08:11:18.000Z
backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/quota/QuotaDependencyTest.java
emesika/ovirt-engine
db6458e688eeb385b683a0c9c5530917cd6dfe5f
[ "Apache-2.0" ]
202
2015-01-04T06:20:49.000Z
2022-03-08T15:30:08.000Z
38.735294
121
0.692863
13,203
package org.ovirt.engine.core.bll.quota; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.ovirt.engine.core.bll.CommandBase; import org.ovirt.engine.core.bll.CommandsFactory; import org.ovirt.engine.core.bll.InternalCommandAttribute; import org.ovirt.engine.core.common.action.ActionType; public class QuotaDependencyTest { public static Stream<ActionType> quotaDependency() { return Arrays.stream(ActionType.values()).filter(a -> a.getQuotaDependency() != ActionType.QuotaDependency.NONE); } @ParameterizedTest @MethodSource public void quotaDependency(ActionType actionType) { Class commandClass = CommandsFactory.getCommandClass(actionType.name()); // if command is deprecated or internal - skip it if (commandClass.getAnnotation(Deprecated.class) != null || commandClass.getAnnotation(InternalCommandAttribute.class) != null) { return; } switch (actionType.getQuotaDependency()) { case CLUSTER: assertCommandIsQuotaVdsDependent(commandClass); break; case STORAGE: assertCommandIsQuotaStorageDependent(commandClass); break; case BOTH: assertCommandIsQuotaVdsDependent(commandClass); assertCommandIsQuotaStorageDependent(commandClass); break; default: break; } } private void assertCommandIsQuotaStorageDependent(Class commandClass) { assertTrue(isImplementingRecursive(commandClass, QuotaStorageDependent.class), String.format("The command %s was expected to implement QuotaStorageDependent interface", commandClass.getName())); } private void assertCommandIsQuotaVdsDependent(Class commandClass) { assertTrue(isImplementingRecursive(commandClass, QuotaVdsDependent.class), String.format("The command %s was expected to implement QuotaVdsDependent interface", commandClass.getName())); } private boolean isImplementingRecursive(Class commandClass, Class interfaceClass) { if (Arrays.asList(commandClass.getInterfaces()).contains(interfaceClass)) { return true; } else { return !commandClass.getSuperclass().equals(CommandBase.class) && isImplementingRecursive(commandClass.getSuperclass(), interfaceClass); } } }
3e1f3e420e34bfe80c566dabcd290a3acaa5d70c
2,988
java
Java
src/main/java/com/example/SpringBootSecurityDemo/jwt/JwtTokenVerifier.java
dimples-app/StudentRoster_WithSpringBootSecurity
0c6a9a3fbffabe7d72db9be7e551ee9405a1b2f2
[ "Apache-2.0" ]
1
2021-10-11T17:59:01.000Z
2021-10-11T17:59:01.000Z
src/main/java/com/example/SpringBootSecurityDemo/jwt/JwtTokenVerifier.java
dimples-app/StudentRoster_WithSpringBootSecurity
0c6a9a3fbffabe7d72db9be7e551ee9405a1b2f2
[ "Apache-2.0" ]
null
null
null
src/main/java/com/example/SpringBootSecurityDemo/jwt/JwtTokenVerifier.java
dimples-app/StudentRoster_WithSpringBootSecurity
0c6a9a3fbffabe7d72db9be7e551ee9405a1b2f2
[ "Apache-2.0" ]
1
2021-11-29T01:43:23.000Z
2021-11-29T01:43:23.000Z
36.439024
119
0.705154
13,204
package com.example.SpringBootSecurityDemo.jwt; import com.google.common.base.Strings; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import io.jsonwebtoken.JwtException; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.security.Keys; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.filter.OncePerRequestFilter; import javax.crypto.SecretKey; 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.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; public class JwtTokenVerifier extends OncePerRequestFilter { private final JwtConfig jwtConfig; private final SecretKey secretKey; public JwtTokenVerifier(JwtConfig jwtConfig, SecretKey secretKey) { this.jwtConfig = jwtConfig; this.secretKey = secretKey; } @Override protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { String authorizationHeader = httpServletRequest.getHeader(jwtConfig.getAuthorizationHeader()); if (Strings.isNullOrEmpty(authorizationHeader) || authorizationHeader.startsWith(jwtConfig.getTokenPrefix())) { filterChain.doFilter(httpServletRequest, httpServletResponse); return; } String token = authorizationHeader.replace(jwtConfig.getTokenPrefix(), ""); try { Jws<Claims> claimsJws = Jwts.parser() .setSigningKey(secretKey) .parseClaimsJws(token); Claims body = claimsJws.getBody(); String username = body.getSubject(); List<Map<String, String>> authorities = (List<Map<String, String>>) body.get("authorities"); Set<SimpleGrantedAuthority> simpleGrantedAuthorities = authorities.stream() .map(m -> new SimpleGrantedAuthority(m.get("authority"))) .collect(Collectors.toSet()); Authentication authentication = new UsernamePasswordAuthenticationToken( username, null, simpleGrantedAuthorities ); SecurityContextHolder.getContext().setAuthentication(authentication); } catch (JwtException error) { throw new IllegalStateException(String.format("Token is not Valid", token)); } filterChain.doFilter(httpServletRequest, httpServletResponse); } }
3e1f3eca263bef04907bee51a434cae96f15cf47
5,739
java
Java
core/src/main/java/org/jruby/runtime/assigner/PreManyRest0Post0Assigner.java
1587/jruby
719a009a621e4a7becba4c1ea5e41bc918614fad
[ "Ruby", "Apache-2.0" ]
3
2015-12-29T07:34:53.000Z
2020-05-30T12:29:14.000Z
core/src/main/java/org/jruby/runtime/assigner/PreManyRest0Post0Assigner.java
1587/jruby
719a009a621e4a7becba4c1ea5e41bc918614fad
[ "Ruby", "Apache-2.0" ]
null
null
null
core/src/main/java/org/jruby/runtime/assigner/PreManyRest0Post0Assigner.java
1587/jruby
719a009a621e4a7becba4c1ea5e41bc918614fad
[ "Ruby", "Apache-2.0" ]
1
2018-03-08T03:57:56.000Z
2018-03-08T03:57:56.000Z
38.75
100
0.639582
13,205
/* ***** BEGIN LICENSE BLOCK ***** * Version: EPL 1.0/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Eclipse Public * License Version 1.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.eclipse.org/legal/epl-v10.html * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * Copyright (C) 2009 Thomas E Enebo <kenaa@example.com> * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the EPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the EPL, the GPL or the LGPL. ***** END LICENSE BLOCK *****/ package org.jruby.runtime.assigner; import org.jruby.Ruby; import org.jruby.RubyArray; import org.jruby.ast.ListNode; import org.jruby.runtime.Block; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; /** * This will only be true for blocks which have a pre > 3 in length. */ public class PreManyRest0Post0Assigner extends Assigner { private int preLength; private ListNode pre; public PreManyRest0Post0Assigner(ListNode pre, int preCount) { this.pre = pre; this.preLength = preCount; } @Override public void assign(Ruby runtime, ThreadContext context, IRubyObject self, Block block) { assignNilTo(runtime, context, self, block, 0); } @Override public void assign(Ruby runtime, ThreadContext context, IRubyObject self, IRubyObject value1, Block block) { pre.get(0).assign(runtime, context, self, value1, block, false); assignNilTo(runtime, context, self, block, 1); } @Override public void assign(Ruby runtime, ThreadContext context, IRubyObject self, IRubyObject value1, IRubyObject value2, Block block) { pre.get(0).assign(runtime, context, self, value1, block, false); pre.get(1).assign(runtime, context, self, value1, block, false); assignNilTo(runtime, context, self, block, 2); } @Override public void assign(Ruby runtime, ThreadContext context, IRubyObject self, IRubyObject value1, IRubyObject value2, IRubyObject value3, Block block) { pre.get(0).assign(runtime, context, self, value1, block, false); pre.get(1).assign(runtime, context, self, value1, block, false); pre.get(2).assign(runtime, context, self, value1, block, false); assignNilTo(runtime, context, self, block, 3); } @Override public void assign(Ruby runtime, ThreadContext context, IRubyObject self, IRubyObject values[], Block block) { int valueLength = values == null ? 0 : values.length; switch (valueLength) { case 0: assign(runtime, context, self, block); return; case 1: assign(runtime, context, self, values[0], block); return; case 2: assign(runtime, context, self, values[0], values[1], block); return; } // Populate up to shorter of calling arguments or local parameters in the block for (int i = 0; i < preLength && i < valueLength; i++) { pre.get(i).assign(runtime, context, self, values[i], block, false); } // nil pad since we provided less values than block parms if (valueLength < preLength) { assignNilTo(runtime, context, self, block, valueLength); } } @Override public void assignArray(Ruby runtime, ThreadContext context, IRubyObject self, IRubyObject arg, Block block) { RubyArray values = (RubyArray) arg; int valueLength = values.getLength(); switch (valueLength) { case 0: assign(runtime, context, self, block); break; case 1: assign(runtime, context, self, values.eltInternal(0), block); break; case 2: assign(runtime, context, self, values.eltInternal(0), values.eltInternal(1), block); break; case 3: assign(runtime, context, self, values.eltInternal(0), values.eltInternal(1), values.eltInternal(2), block); break; } // Populate up to shorter of calling arguments or local parameters in the block for (int i = 0; i < preLength && i < valueLength; i++) { pre.get(i).assign(runtime, context, self, values.eltInternal(i), block, false); } } private void assignNilTo(Ruby runtime, ThreadContext context, IRubyObject self, Block block, int start) { IRubyObject nil = runtime.getNil(); for (int i = start; i < preLength; i++) { pre.get(i).assign(runtime, context, self, nil, block, false); } } }
3e1f3f68de73ff04461eab3d2cd8c78777c3864e
2,227
java
Java
server-spring/src/main/java/com/nogenem/skyapp/controller/AuthController.java
nogenem/Skyapp
e4227df4ea80cd2bfa55e9301236925197ffdc5b
[ "MIT" ]
null
null
null
server-spring/src/main/java/com/nogenem/skyapp/controller/AuthController.java
nogenem/Skyapp
e4227df4ea80cd2bfa55e9301236925197ffdc5b
[ "MIT" ]
1
2021-04-21T22:18:19.000Z
2021-04-21T22:18:19.000Z
server-spring/src/main/java/com/nogenem/skyapp/controller/AuthController.java
nogenem/Skyapp
e4227df4ea80cd2bfa55e9301236925197ffdc5b
[ "MIT" ]
null
null
null
35.349206
117
0.801527
13,206
package com.nogenem.skyapp.controller; import javax.validation.Valid; import com.nogenem.skyapp.DTO.UserDTO; import com.nogenem.skyapp.exception.EmailAlreadyTakenException; import com.nogenem.skyapp.exception.TranslatableApiException; import com.nogenem.skyapp.exception.UnableToSendConfirmationEmailException; import com.nogenem.skyapp.model.User; import com.nogenem.skyapp.requestBody.auth.SignUpRequestBody; import com.nogenem.skyapp.response.auth.SignUpResponse; import com.nogenem.skyapp.service.AuthService; import com.nogenem.skyapp.service.MailService; import com.nogenem.skyapp.service.TokenService; import com.nogenem.skyapp.utils.Utils; import org.springframework.dao.DuplicateKeyException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import lombok.AllArgsConstructor; @RestController @RequestMapping("/api/auth") @AllArgsConstructor public class AuthController { private AuthService authService; private TokenService tokenService; private MailService mailService; @PostMapping("/signup") @ResponseStatus(HttpStatus.CREATED) public SignUpResponse signup(@Valid @RequestBody SignUpRequestBody requestBody, @RequestHeader HttpHeaders headers) throws TranslatableApiException { User user = null; try { // TODO: Find a way to use transaction !? user = authService.save(requestBody); } catch (DuplicateKeyException ex) { throw new EmailAlreadyTakenException(); } try { String origin = Utils.getOriginFromHeaders(headers); mailService.sendConfirmationEmail(user.getEmail(), user.getConfirmationToken(), origin); } catch (Exception e) { e.printStackTrace(); throw new UnableToSendConfirmationEmailException(); } return new SignUpResponse(new UserDTO(user, tokenService.generateToken(user, true))); } }
3e1f3f731545f50582cbfff794923dc086fae0e8
561
java
Java
java-example/src/test/java/ru/stqa/training/selenium/TestBaseIE.java
Tan-Sid/SeleniumCourse
639acdd8fb912850aeff846119b14bde01a37bb1
[ "Apache-2.0" ]
null
null
null
java-example/src/test/java/ru/stqa/training/selenium/TestBaseIE.java
Tan-Sid/SeleniumCourse
639acdd8fb912850aeff846119b14bde01a37bb1
[ "Apache-2.0" ]
null
null
null
java-example/src/test/java/ru/stqa/training/selenium/TestBaseIE.java
Tan-Sid/SeleniumCourse
639acdd8fb912850aeff846119b14bde01a37bb1
[ "Apache-2.0" ]
null
null
null
20.777778
53
0.743316
13,207
package ru.stqa.training.selenium; import org.junit.After; import org.junit.Before; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.support.ui.WebDriverWait; public class TestBaseIE { public WebDriver driver; public WebDriverWait wait; @Before public void start() { driver = new InternetExplorerDriver(); wait = new WebDriverWait(driver,10); } @After public void stop(){ driver.quit(); driver = null; } }
3e1f3f93472ad8a90fc7cfbc48a5fad960743114
1,762
java
Java
hierarchyviewer/src/main/java/com/polidea/hierarchyviewer/internal/provider/ServerInfoProvider.java
Polidea/android-hierarchy-viewer
50675b42df87e1372983b412196d30fa3d3dac87
[ "MIT" ]
120
2015-04-23T13:00:46.000Z
2021-11-09T10:11:43.000Z
hierarchyviewer/src/main/java/com/polidea/hierarchyviewer/internal/provider/ServerInfoProvider.java
Polidea/android-hierarchy-viewer
50675b42df87e1372983b412196d30fa3d3dac87
[ "MIT" ]
2
2015-04-29T13:50:44.000Z
2017-06-19T18:44:40.000Z
hierarchyviewer/src/main/java/com/polidea/hierarchyviewer/internal/provider/ServerInfoProvider.java
Polidea/android-hierarchy-viewer
50675b42df87e1372983b412196d30fa3d3dac87
[ "MIT" ]
11
2015-05-27T02:25:58.000Z
2021-01-17T03:23:49.000Z
27.53125
106
0.562429
13,208
package com.polidea.hierarchyviewer.internal.provider; import android.content.Context; import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Collections; import java.util.List; public class ServerInfoProvider { private Context context; public ServerInfoProvider(Context context) { this.context = context; } String getIpAddress() { String ipAddress = getIpAddress(true); if (ipAddress == null) { ipAddress = getIpAddress(false); } return ipAddress; } private String getIpAddress(boolean useIPv4) { String result = null; try { List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { result = getIpAddress(intf, useIPv4); if (result != null) { break; } } } catch (Exception ignored) { } return result; } private String getIpAddress(NetworkInterface intf, boolean useIPv4) { String result = null; List<InetAddress> addrs = Collections.list(intf.getInetAddresses()); for (InetAddress addr : addrs) { if (!addr.isLoopbackAddress()) { String sAddr = addr.getHostAddress().toUpperCase(); boolean isIPv4 = addr instanceof Inet4Address; if (useIPv4 && isIPv4) { result = sAddr; break; } else if (!useIPv4 && !isIPv4) { result = sAddr; break; } } } return result; } }
3e1f3fa69d08a67a0f9c11807a390ca4d3c3adcf
6,598
java
Java
src/main/java/slimeknights/tconstruct/smeltery/tileentity/TileMultiblock.java
panoskj/TinkersConstruct
a8a133a94cf9d736fea0ff7a6278b0289eac5e47
[ "MIT" ]
1
2016-06-10T03:51:33.000Z
2016-06-10T03:51:33.000Z
src/main/java/slimeknights/tconstruct/smeltery/tileentity/TileMultiblock.java
panoskj/TinkersConstruct
a8a133a94cf9d736fea0ff7a6278b0289eac5e47
[ "MIT" ]
2
2016-06-23T11:00:35.000Z
2017-12-20T05:23:20.000Z
src/main/java/slimeknights/tconstruct/smeltery/tileentity/TileMultiblock.java
panoskj/TinkersConstruct
a8a133a94cf9d736fea0ff7a6278b0289eac5e47
[ "MIT" ]
3
2018-01-12T09:36:15.000Z
2021-01-31T03:37:38.000Z
32.825871
141
0.715368
13,209
package slimeknights.tconstruct.smeltery.tileentity; import com.google.common.collect.ImmutableList; import net.minecraft.block.state.IBlockState; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SPacketUpdateTileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import javax.annotation.Nonnull; import slimeknights.mantle.multiblock.IMasterLogic; import slimeknights.mantle.multiblock.IServantLogic; import slimeknights.mantle.tileentity.TileInventory; import slimeknights.tconstruct.library.utils.TagUtil; import slimeknights.tconstruct.smeltery.block.BlockMultiblockController; import slimeknights.tconstruct.smeltery.multiblock.MultiblockDetection; public abstract class TileMultiblock<T extends MultiblockDetection> extends TileInventory implements IMasterLogic { public static final String TAG_ACTIVE = "active"; public static final String TAG_MINPOS = "minPos"; public static final String TAG_MAXPOS = "maxPos"; protected static final int MAX_SIZE = 9; // consistancy by this point. All others do 9x9 protected boolean active; // Info about the structure/multiblock protected MultiblockDetection.MultiblockStructure info; protected T multiblock; /** smallest coordinate INSIDE the multiblock */ protected BlockPos minPos; /** biggest coordinate INSIDE the multiblock */ protected BlockPos maxPos; public TileMultiblock(String name, int inventorySize) { super(name, inventorySize); } public TileMultiblock(String name, int inventorySize, int maxStackSize) { super(name, inventorySize, maxStackSize); } /** Call in the constructor. Set the multiblock */ protected void setMultiblock(T multiblock) { this.multiblock = multiblock; } public BlockPos getMinPos() { return minPos; } public BlockPos getMaxPos() { return maxPos; } /** Called by the servants */ @Override public void notifyChange(IServantLogic servant, BlockPos pos) { checkMultiblockStructure(); } // Checks if the tank is fully built and updates status accordingly public void checkMultiblockStructure() { boolean wasActive = active; IBlockState state = this.getWorld().getBlockState(getPos()); if(!(state.getBlock() instanceof BlockMultiblockController)) { active = false; } else { EnumFacing in = state.getValue(BlockMultiblockController.FACING).getOpposite(); // we only check if the chunks we want to check are loaded. Otherwise we assume the previous state is/was correct if(info == null || multiblock.checkIfMultiblockCanBeRechecked(world, info)) { MultiblockDetection.MultiblockStructure structure = multiblock.detectMultiblock(this.getWorld(), this.getPos().offset(in), MAX_SIZE); if(structure == null) { active = false; updateStructureInfoInternal(null); } else { // we found a valid tank. booyah! active = true; MultiblockDetection.assignMultiBlock(this.getWorld(), this.getPos(), structure.blocks); updateStructureInfoInternal(structure); // we still have to update since something caused us to rebuild our stats // might be the tank size changed if(wasActive) { this.getWorld().notifyBlockUpdate(getPos(), state, state, 3); } } } } // mark the block for updating so the controller block updates its graphics if(wasActive != active) { this.getWorld().notifyBlockUpdate(getPos(), state, state, 3); this.markDirty(); } } protected final void updateStructureInfoInternal(MultiblockDetection.MultiblockStructure structure) { info = structure; if(structure == null) { structure = new MultiblockDetection.MultiblockStructure(0, 0, 0, ImmutableList.of(this.pos)); } if(info != null) { minPos = info.minPos.add(1, 1, 1); // add walls and floor maxPos = info.maxPos.add(-1, hasCeiling() ? -1 : 0, -1); // subtract walls, no ceiling } else { minPos = maxPos = this.pos; } updateStructureInfo(structure); } /** if true the maxPos will be adjusted accordingly that the structure has no ceiling */ protected boolean hasCeiling() { return true; } protected abstract void updateStructureInfo(MultiblockDetection.MultiblockStructure structure); public boolean isActive() { return active && (getWorld() == null || getWorld().isRemote || info != null); } public void setInvalid() { this.active = false; updateStructureInfoInternal(null); } @Override public void validate() { super.validate(); // on validation we set active to false so the tank checks anew if it's formed active = false; } @Nonnull @Override public NBTTagCompound writeToNBT(NBTTagCompound compound) { compound = super.writeToNBT(compound); compound.setBoolean(TAG_ACTIVE, active); compound.setTag(TAG_MINPOS, TagUtil.writePos(minPos)); compound.setTag(TAG_MAXPOS, TagUtil.writePos(maxPos)); return compound; } @Override public void readFromNBT(NBTTagCompound compound) { super.readFromNBT(compound); active = compound.getBoolean(TAG_ACTIVE); minPos = TagUtil.readPos(compound.getCompoundTag(TAG_MINPOS)); maxPos = TagUtil.readPos(compound.getCompoundTag(TAG_MAXPOS)); } @Override public SPacketUpdateTileEntity getUpdatePacket() { NBTTagCompound tag = new NBTTagCompound(); this.writeToNBT(tag); return new SPacketUpdateTileEntity(this.getPos(), this.getBlockMetadata(), tag); } @Override public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) { boolean wasActive = active; readFromNBT(pkt.getNbtCompound()); // update chunk (rendering) if the active state changed if(active != wasActive) { IBlockState state = getWorld().getBlockState(getPos()); getWorld().notifyBlockUpdate(getPos(), state, state, 3); } } @Nonnull @Override public NBTTagCompound getUpdateTag() { // new tag instead of super since default implementation calls the super of writeToNBT return writeToNBT(new NBTTagCompound()); } /** Returns true if it's a client world, false if no world or server */ public boolean isClientWorld() { return this.getWorld() != null && this.getWorld().isRemote; } /** Returns true if it's a server world, false if no world or client */ public boolean isServerWorld() { return this.getWorld() != null && !this.getWorld().isRemote; } }
3e1f4010808a03d9983b57af5b1c8276d437a06a
987
java
Java
leetcode/0021 - Merge Two Sorted Lists/Solution.java
Jianfu-She/LeetCode
c4fd7e9026a4b2ab299c02f70b3f6340148b135a
[ "Apache-2.0" ]
null
null
null
leetcode/0021 - Merge Two Sorted Lists/Solution.java
Jianfu-She/LeetCode
c4fd7e9026a4b2ab299c02f70b3f6340148b135a
[ "Apache-2.0" ]
null
null
null
leetcode/0021 - Merge Two Sorted Lists/Solution.java
Jianfu-She/LeetCode
c4fd7e9026a4b2ab299c02f70b3f6340148b135a
[ "Apache-2.0" ]
null
null
null
21.933333
94
0.464032
13,210
/** * Problem: Merge two sorted linked lists and return it as a new list. * The new list should be made by splicing together the nodes of the first two lists. * * Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4 */ /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode dummy = new ListNode(0); ListNode cur = dummy; while (l1 != null && l2 != null) { if (l1.val < l2.val) { cur.next = l1; l1 = l1.next; } else { cur.next = l2; l2 = l2.next; } cur = cur.next; } if (l1 != null) { cur.next = l1; } if (l2 != null) { cur.next = l2; } return dummy.next; } }
3e1f405f4c9ce0ca9b7609f492aeb35f289cee9b
34,576
java
Java
demo/src/main/java/utilities/CommonMethods.java
Toqeer12/AndroidImageSlider-master
0b4dd905078bb96ca4ad7e091aafcf457107e995
[ "MIT" ]
null
null
null
demo/src/main/java/utilities/CommonMethods.java
Toqeer12/AndroidImageSlider-master
0b4dd905078bb96ca4ad7e091aafcf457107e995
[ "MIT" ]
null
null
null
demo/src/main/java/utilities/CommonMethods.java
Toqeer12/AndroidImageSlider-master
0b4dd905078bb96ca4ad7e091aafcf457107e995
[ "MIT" ]
null
null
null
38.247788
133
0.54185
13,211
package utilities; import android.app.ProgressDialog; import android.content.Context; import android.content.SharedPreferences; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import com.koherent.pdlapps.cricketworldcup2015live.R; public class CommonMethods { private static ProgressDialog pgDialog; // public static void showProgressDialog(Context nContext) { // try { // pgDialog = new ProgressDialog(nContext); // pgDialog.setIndeterminate(true); // pgDialog.setCancelable(false); // pgDialog.show(); //// pgDialog.setContentView(R.layout.dialog_loading); // } catch (Exception e) { // } // } // public static void hideProgressDialog() { // try { // if (pgDialog != null) // pgDialog.dismiss(); // } catch (Exception e) { // // } // } // public static Dialog showConfirmationDialog(Context nContext, // String tittle, String message, String negativeButton, // String positiveButton) { // try { //// View view = CommonMethods.createView(nContext, //// R.layout.popup_confirmation, null); //// TextView tvTittle = (TextView) view.findViewById(R.id.tvTittle); //// tvTittle.setText(tittle); //// TextView tvMessage = (TextView) view.findViewById(R.id.tvMessage); //// tvMessage.setText(message); //// Button btnPositive = (Button) view.findViewById(R.id.btnPossitive); //// btnPossitive.setText(possitiveButton); //// Button btnNegative = (Button) view.findViewById(R.id.btnNegative); //// btnNegative.setText(negativeButton); //// Dialog nDialog = new Dialog(nContext, R.style.NewDialog); //// nDialog.setContentView(view); //// nDialog.show(); //// return nDialog; // } catch (Exception e) { // // } // return null; // } // public static boolean checkForNetworkProvider( LocationManager nLocationManager, Context nContext) { try { if (nLocationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER) || (CommonMethods.isNetworkAvailable(nContext) || CommonMethods .isWifiConnected(nContext))) { return true; } } catch (Exception e) { } return false; } public static void showProgressDialog(Context nContext) { try { pgDialog = new ProgressDialog(nContext); pgDialog.setIndeterminate(true); pgDialog.setCancelable(false); pgDialog.show(); pgDialog.setContentView(R.layout.dialoug_loading); } catch (Exception e) { } } public static void hideProgressDialog() { try { if (pgDialog != null) pgDialog.dismiss(); } catch (Exception e) { } } // public static void showToast(String message, int toastDurattion) { // try { // Toast.makeText(CommonObjects.getContext(), message, toastDurattion) // .show(); // } catch (Exception e) { // } // } // // public static String getCurrentDate() { // try { // Calendar calender = Calendar.getInstance(); // return getDateFormatted( // String.valueOf(calender.get(Calendar.MONTH) + 1), // String.valueOf(calender.get(Calendar.DAY_OF_MONTH)), // String.valueOf(calender.get(Calendar.YEAR))); // } catch (Exception e) { // return ""; // } // } // public static String getDateFormatted(String strMonth, String strDayOfMonth, // String strYear) { // try { // if (strMonth.length() == 1) // strMonth = "0" + strMonth; // if (strDayOfMonth.length() == 1) // strDayOfMonth = "0" + strDayOfMonth; // return strMonth + "/" + strDayOfMonth + "/" + strYear; // } catch (Exception e) { // return ""; // } // } // public static String getCurrentTime() { // try { // Calendar calender = Calendar.getInstance(); // return getTimeFormatted1( // String.valueOf(calender.get(Calendar.HOUR_OF_DAY)), // String.valueOf(calender.get(Calendar.MINUTE))); // } catch (Exception e) { // return ""; // } // // } // public static String getTimeFormatted1(String strHour, String strMinute) { // try { // if (strMinute.length() == 1) // strMinute = "0" + strMinute; // return getHourIn12Format(Integer.valueOf(strHour)) + ":" + strMinute + " " + getAMPM(strHour); // } catch (Exception e) { // return ""; // } // } // public static String getTimeFormatted2(String strHour, String strMinute) { // try { // if (strMinute.length() == 1) // strMinute = "0" + strMinute; // return strHour + ":" + strMinute; // } catch (Exception e) { // return ""; // } // } // // public static String getReFormattedDate(String date) { // try { // String[] dateTime = date.split("/"); // return dateTime[2] + "-" + dateTime[0] + "-" + dateTime[1]; // } catch (Exception e) { // return ""; // } // } // public static void showNotification(Context nContext, // Class<?> nActivityClass, String title, String message) { // try { //// Intent intent = new Intent(nContext, nActivityClass); //// NotificationManager notificationManager = (NotificationManager) nContext //// .getSystemService(Context.NOTIFICATION_SERVICE); //// PendingIntent pendingIntent = PendingIntent.getActivity(nContext, //// 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK); //// NotificationCompat.Builder builder = new NotificationCompat.Builder( //// nContext).setSmallIcon(R.drawable.ic_launcher) //// .setContentTitle(title).setContentText(message) //// .setContentIntent(pendingIntent).setAutoCancel(true); //// notificationManager.notify(1, builder.build()); // } catch (Exception e) { // } // } // public static void hideSoftKeyboard(View v, Context context) { // try { // InputMethodManager imm = (InputMethodManager) context // .getSystemService(Context.INPUT_METHOD_SERVICE); // imm.hideSoftInputFromWindow(v.getWindowToken(), 0); // } catch (Exception e) { // } // } // // / // // public static void callAnActivityForResult(Context newContext, // Class<?> newActivityClass, int requestCode) { // try { // Intent newIntent = new Intent(newContext, newActivityClass); // ((Activity) newContext).startActivityForResult(newIntent, requestCode); // } catch (Exception e) { // } // } // // public static void callAnActivityForResultWithParameter(Context newContext, // Class<?> newActivityClass, int requestCode, String tag, String value) { // try { // Intent newIntent = new Intent(newContext, newActivityClass); // newIntent.putExtra(tag, value); // ((Activity) newContext).startActivityForResult(newIntent, requestCode); // } catch (Exception e) { // // } // } // public static void callAnActivityWithParameter(Context newContext, // Class<?> newActivityClass, String tag, String value) { // try { // Intent newIntent = new Intent(newContext, newActivityClass); // newIntent.putExtra(tag, value); // newContext.startActivity(newIntent); // } catch (Exception e) { // // } // } // public static View createView(Context context, int layout, ViewGroup parent) { // try { // LayoutInflater newLayoutInflater = (LayoutInflater) context // .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // return newLayoutInflater.inflate(layout, parent, false); // } catch (Exception e) { // return null; // } // } // public static String getStringPreference(Context nContext, String preferenceName, String preferenceItem, String defaultValue) { try { SharedPreferences nPreferences; nPreferences = nContext.getSharedPreferences(preferenceName, Context.MODE_PRIVATE); return nPreferences.getString(preferenceItem, defaultValue); } catch (Exception e) { return ""; } } // public static int getIntPreference(Context nContext, // String preferenceName, String preferenceItem, int deafaultValue) { // try { // SharedPreferences nPreferences; // nPreferences = nContext.getSharedPreferences(preferenceName, // Context.MODE_PRIVATE); // return nPreferences.getInt(preferenceItem, deafaultValue); // } catch (Exception e) { // return deafaultValue; // } // } // public static Boolean getBooleanPreference(Context nContext, // String preferenceName, String preferenceItem, // Boolean defaultValue) { // try { // SharedPreferences nPreferences; // nPreferences = nContext.getSharedPreferences(preferenceName, // Context.MODE_PRIVATE); // return nPreferences.getBoolean(preferenceItem, defaultValue); // } catch (Exception e) { // return defaultValue; // } // } //// public static void setStringPreference(Context nContext, String preferenceName, String preferenceItem, String preferenceItemValue) { try { SharedPreferences nPreferences; nPreferences = nContext.getSharedPreferences(preferenceName, Context.MODE_PRIVATE); SharedPreferences.Editor nEditor = nPreferences.edit(); nEditor.putString(preferenceItem, preferenceItemValue); nEditor.commit(); } catch (Exception e) { } } // public static void setIntPreference(Context nContext, // String preferenceName, String preferenceItem, // int preferenceItemValue) { // try { // SharedPreferences nPreferences; // nPreferences = nContext.getSharedPreferences(preferenceName, // Context.MODE_PRIVATE); // Editor nEditor = nPreferences.edit(); // nEditor.putInt(preferenceItem, preferenceItemValue); // nEditor.commit(); // } catch (Exception e) { // } // } // public static void setBooleanPreference(Context nContext, // String preferenceName, String preferenceItem, // Boolean preferenceItemValue) { // try { // SharedPreferences nPreferences; // nPreferences = nContext.getSharedPreferences(preferenceName, // Context.MODE_PRIVATE); // Editor nEditor = nPreferences.edit(); // nEditor.putBoolean(preferenceItem, preferenceItemValue); // nEditor.commit(); // } catch (Exception e) { // } // } // public static String removeSpacing(String phoneNumber) { // try { // phoneNumber = phoneNumber.replace("-", ""); // phoneNumber = phoneNumber.replace(" ", ""); // removeNonDigits(phoneNumber); // if (phoneNumber.length() >= 11) { // phoneNumber = phoneNumber.substring(phoneNumber.length() - 11); // } // return phoneNumber; // } catch (Exception e) { // return phoneNumber; // } // } // public static String removeNonDigits(String text) { // try { // int length = text.length(); // StringBuffer buffer = new StringBuffer(length); // for (int i = 0; i < length; i++) { // char ch = text.charAt(i); // if (Character.isDigit(ch)) { // buffer.append(ch); // } // } // return buffer.toString(); // } catch (Exception e) { // return text; // } // } // // public static boolean getBoolean(int bolInt) { // try { // if (bolInt == 1) // return true; // else // return false; // } catch (Exception e) { // return false; // } // } public static boolean isNetworkAvailable(Context nContext) { try { ConnectivityManager connectivityManager = (ConnectivityManager) nContext .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager .getActiveNetworkInfo(); return activeNetworkInfo != null; } catch (Exception e) { } return false; } public static boolean isWifiConnected(Context nContext) { try { ConnectivityManager connectivityManager = (ConnectivityManager) nContext .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = null; if (connectivityManager != null) { networkInfo = connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_WIFI); } return networkInfo == null ? false : networkInfo.isConnected(); } catch (Exception e) { } return false; } // public static boolean isInternetAvailable() { // try { // InetAddress ipAddr = InetAddress.getByName("google.com"); // if (ipAddr.equals("")) { // return false; // } else { // return true; // } // } catch (Exception e) { // return false; // } // } // public static boolean isEmailValid(String email) { // try { // Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+"); // Matcher matcher = pattern.matcher(email); // return matcher.matches(); // } catch (Exception e) { // return false; // } // } // public static void callTimePicker(Context nContext, String time, // OnTimeSetListener timePickerListener, Boolean is24Hours, // FragmentManager manager) { // try { // int hour, minute; // if (time.contains("Time")) { // Calendar calendar = Calendar.getInstance(); // hour = calendar.get(Calendar.HOUR_OF_DAY); // minute = calendar.get(Calendar.MINUTE); // // } else { // time=time.replace(":", " "); // String[] nTime = time.split(" "); // hour = getHourIn24FFormat(nTime[0],nTime[2]); // minute = Integer.parseInt(nTime[1]); // } // TimePickerDialog timePickerDialog = TimePickerDialog.newInstance( // timePickerListener, hour, minute, is24Hours); // timePickerDialog.setVibrate(false); // timePickerDialog.setCloseOnSingleTapMinute(false); // timePickerDialog.show(manager, "timepicker"); // } catch (Exception e) { // } // } // private static int getHourIn24Format(String strHour, String strAM_PM) { // int hour = 0; // if (strAM_PM.equals("PM")) { // hour = Integer.parseInt(strHour) + 12; // } else { // if (Integer.parseInt(strHour) != 12) { // hour = Integer.parseInt(strHour); // } // } // return hour; // } // public static void callDatePicker(Context nContext, String date, // DatePickerDialog.OnDateSetListener datePickerListener, FragmentManager manager) { // try { // int day, month, year; // if (date.contains("")) { // Calendar calendar = Calendar.getInstance(); // day = calendar.get(Calendar.DAY_OF_MONTH); // month = calendar.get(Calendar.MONTH); // year = calendar.get(Calendar.YEAR); // } else { // String[] nDate = date.split("/"); // month = Integer.parseInt(nDate[0]) - 1; // day = Integer.parseInt(nDate[1]); // year = Integer.parseInt(nDate[2]); // } // DatePickerDialog datePickerDialog = DatePickerDialog.newInstance( // datePickerListener, year, month, day, false); // datePickerDialog.setVibrate(false); // datePickerDialog.setYearRange(1985, 2028); // datePickerDialog.setCloseOnSingleTapDay(false); // datePickerDialog.show(manager, "datepicker"); // } catch (Exception e) { // } // } // // public static String getDateFormatted(String date) { // try { // date = date.replace("-", " "); // Date d = new SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH) // .parse(date); // Calendar cal = Calendar.getInstance(); // cal.setTime(d); // int month = cal.get(Calendar.MONTH) + 1; // int day = cal.get(Calendar.DAY_OF_MONTH); // int year = cal.get(Calendar.YEAR); // return getDateFormatted("" + month, "" + day, "" + year); // } catch (Exception e) { // return ""; // } // } // // public static void setImage(ImageView nImageView, byte[] nImageBytes, Point size) { // new LoadImageTask(nImageView, nImageBytes, size).execute(); // } // public static void setImage(ImageView nImageView, byte[] nImageBytes, Point size, boolean isRoundedCorners, int pixels) { // new LoadImageTask(nImageView, nImageBytes, size, isRoundedCorners, pixels).execute(); // } // // public static void setImageFromUrl(Context context, ImageView nImageView, String url, Point size, boolean isRounded) { // new LoadImageFromUrl(context, nImageView, url, size, isRounded).execute(); // } // // private static class LoadImageTask extends AsyncTask<String, Void, Boolean> { // private ImageView nImageView; // private byte[] mCameraData; // private Bitmap nBitmap; // private Point nSize; // private boolean isRoundedCorners; // private int pixels; // // public LoadImageTask(ImageView nImageView, byte[] mCameraData, Point nSize, boolean isRoundedCorners, int pixels) { // this.nImageView = nImageView; // this.mCameraData = mCameraData; // this.nSize = nSize; // this.isRoundedCorners = isRoundedCorners; // this.pixels = pixels; // } // // public LoadImageTask(ImageView nImageView, byte[] mCameraData, Point nSize) { // this.nImageView = nImageView; // this.mCameraData = mCameraData; // this.nSize = nSize; // } // @Override // protected Boolean doInBackground(String... params) { // nBitmap = loadBitmap(mCameraData); // return true; // } // // @Override // protected void onPostExecute(Boolean result) { // super.onPostExecute(result); // if (nBitmap != null) { // nImageView.setImageBitmap(nBitmap); // } // } // // private Bitmap loadBitmap(byte[] cameraData) { // Bitmap bitmap = Bitmap.createScaledBitmap( // BitmapFactory.decodeByteArray(mCameraData, 0, mCameraData.length), nSize.x, nSize.y, true); // ByteArrayOutputStream stream = new ByteArrayOutputStream(); // bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream); // if (isRoundedCorners) { // bitmap = getRoundedCornerBitmap(bitmap, pixels); // } // Matrix nMatrix = new Matrix(); // nMatrix.postRotate(90); // bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), nMatrix, true); // return bitmap; // } // // private Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) { // Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap // .getHeight(), Bitmap.Config.ARGB_8888); // Canvas canvas = new Canvas(output); // // final int color = 0xff424242; // final Paint paint = new Paint(); // final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); // final RectF rectF = new RectF(rect); // final float roundPx = pixels; // // paint.setAntiAlias(true); // canvas.drawARGB(0, 0, 0, 0); // paint.setColor(color); // canvas.drawRoundRect(rectF, roundPx, roundPx, paint); // // paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); // canvas.drawBitmap(bitmap, rect, rect, paint); // // return output; // } // } // // private static class LoadImageFromUrl extends AsyncTask<String, Void, Boolean> { // private ImageView nImageView; // private String url; // private Bitmap nBitmap; // private Point nSize; // private boolean isRounded; // private ImageLoader imageLoader; /// // @Override // protected Boolean doInBackground(String... params) { // nBitmap = loadBitmap(imageLoader.getBitmap(url)); // return true; // } // // @Override // protected void onPostExecute(Boolean result) { // super.onPostExecute(result); // if (nBitmap != null) { // nImageView.setImageBitmap(nBitmap); // } // } // private Bitmap loadBitmap(Bitmap bitmap) { // bitmap = Bitmap.createScaledBitmap( // bitmap, nSize.x, nSize.y, true); // if (isRounded) { // bitmap = getRoundedShapeBitmap(bitmap); // } // return bitmap; // } // // private Bitmap getRoundedShapeBitmap(Bitmap bitmap) { // int targetWidth = nSize.x; // int targetHeight = nSize.y; // Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, // targetHeight, Bitmap.Config.ARGB_8888); // // Canvas canvas = new Canvas(targetBitmap); // Path path = new Path(); // path.addCircle(((float) targetWidth - 1) / 2, // ((float) targetHeight - 1) / 2, // (Math.min(((float) targetWidth), // ((float) targetHeight)) / 2), // Path.Direction.CCW); // canvas.clipPath(path); // Bitmap sourceBitmap = bitmap; // canvas.drawBitmap(sourceBitmap, // new Rect(0, 0, sourceBitmap.getWidth(), // sourceBitmap.getHeight()), // new Rect(0, 0, targetWidth, targetHeight), null); // return targetBitmap; // } // } // // public static int dpToPx(int dp, Context context) { // DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); // int px = Math.round(dp * (displayMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)); // return px; // } // public static int pxToDp(int px, Context context) { // DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); // int dp = Math.round(px / (displayMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)); // return dp; // } // public static ArrayList<ArrayList<String>> getCategoriesList() { // ArrayList<ArrayList<String>> categoriesList = new ArrayList<ArrayList<String>>(); // categoriesList.add(new ArrayList<String>() {{ // add("ic_sell"); // add("Regulated Mods"); // }}); // categoriesList.add(new ArrayList<String>() {{ // add("ic_sell"); // add("Mechanical Mods"); // }}); // categoriesList.add(new ArrayList<String>() {{ // add("ic_sell"); // add("RDA Atomizers"); // }}); // categoriesList.add(new ArrayList<String>() {{ // add("ic_sell"); // add("RBA Atomizers"); // }}); // categoriesList.add(new ArrayList<String>() {{ // add("ic_sell"); // add("Genesis Style Atomizers"); // }}); // categoriesList.add(new ArrayList<String>() {{ // add("ic_sell"); // add("E-Juice"); // }}); // categoriesList.add(new ArrayList<String>() {{ // add("ic_sell"); // add("Accessories"); // }}); // categoriesList.add(new ArrayList<String>() {{ // add("ic_sell"); // add("Other"); // }}); // return categoriesList; // } // public static ArrayList<ArrayList<String>> getColorsList() { // ArrayList<ArrayList<String>> colorsList = new ArrayList<ArrayList<String>>(); // colorsList.add(new ArrayList<String>() {{ // add("circle_color_black"); // add("Black"); // }}); // colorsList.add(new ArrayList<String>() {{ // add("circle_color_blue"); // add("Blue"); // }}); // colorsList.add(new ArrayList<String>() {{ // add("circle_color_brass"); // add("Brass"); // }}); // colorsList.add(new ArrayList<String>() {{ // add("circle_color_bronze"); // add("Bronze"); // }}); // colorsList.add(new ArrayList<String>() {{ // add("circle_color_copper"); // add("Copper"); // }}); // colorsList.add(new ArrayList<String>() {{ // add("circle_color_gold"); // add("Gold"); // }}); // colorsList.add(new ArrayList<String>() {{ // add("circle_color_green"); // add("Green"); // }}); // colorsList.add(new ArrayList<String>() {{ // add("circle_color_grey"); // add("Grey"); // }}); // colorsList.add(new ArrayList<String>() {{ // add("circle_color_pink"); // add("Pink"); // }}); // colorsList.add(new ArrayList<String>() {{ // add("circle_color_purple"); // add("Purple"); // }}); // colorsList.add(new ArrayList<String>() {{ // add("circle_color_red"); // add("Red"); // }}); // colorsList.add(new ArrayList<String>() {{ // add("circle_color_silver"); // add("Silver"); // }}); // colorsList.add(new ArrayList<String>() {{ // add("circle_color_stainless_steel"); // add("Stainless Steel"); // }}); // colorsList.add(new ArrayList<String>() {{ // add("circle_color_teal"); // add("Teal"); // }}); // colorsList.add(new ArrayList<String>() {{ // add("circle_color_white"); // add("White"); // }}); // colorsList.add(new ArrayList<String>() {{ // add("circle_color_yellow"); // add("Yellow"); // }}); // return colorsList; // } // // public static ArrayList<ArrayList<String>> getAuthentications() { // ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>(); // list.add(new ArrayList<String>() {{ // add("ic_authentic"); // add("Authentic"); // }}); // list.add(new ArrayList<String>() {{ // add("ic_clone"); // add("Clone"); // }}); // return list; // } // // public static ArrayList<Double> getPackage() { // ArrayList<Double> list = new ArrayList<Double>(); // list.add(3.29); // list.add(5.20); // list.add(11.30); // return list; // } // // public static int getIndex(Spinner spinner, String myString) { // int index = 0; // // for (int i = 0; i < spinner.getCount(); i++) { // if (spinner.getItemAtPosition(i).equals(myString)) { // index = i; // } // } // return index; // } // // public static int getDeviceWidth(Context nConext) { // DisplayMetrics metrics = new DisplayMetrics(); // ((Activity) nConext).getWindowManager().getDefaultDisplay().getMetrics(metrics); // return metrics.widthPixels; // } // // public static int getDeviceHeight(Context nConext) { // DisplayMetrics metrics = new DisplayMetrics(); // ((Activity) nConext).getWindowManager().getDefaultDisplay().getMetrics(metrics); // return metrics.heightPixels; // } // // public static void createShipment() { //// new CreateShipment().execute(); // } // private static class CreateShipment extends AsyncTask<String, Void, Boolean> { // // // public CreateShipment() { // // } // // @Override // protected Boolean doInBackground(String... params) { // EasyPost.apiKey = "cueqNZUb3ldeWTNX7MU3Mel8UXtaAMUi"; // // Map<String, Object> fromAddressMap = new HashMap<String, Object>(); // fromAddressMap.put("name", "Simpler Postage Inc"); // fromAddressMap.put("street1", "388 Townsend St"); // fromAddressMap.put("street2", "Apt 20"); // fromAddressMap.put("city", "San Francisco"); // fromAddressMap.put("state", "CA"); // fromAddressMap.put("zip", "94107"); // fromAddressMap.put("phone", "415-456-7890"); // // Map<String, Object> toAddressMap = new HashMap<String, Object>(); // toAddressMap.put("name", "Sawyer Bateman"); // toAddressMap.put("street1", "1A Larkspur Cres"); // toAddressMap.put("street2", ""); // toAddressMap.put("city", "St. Albert"); // toAddressMap.put("state", "AB"); // toAddressMap.put("zip", "T8N2M4"); // toAddressMap.put("phone", "780-483-2746"); // toAddressMap.put("country", "CA"); // // Map<String, Object> parcelMap = new HashMap<String, Object>(); // parcelMap.put("weight", 22.9); // parcelMap.put("height", 12.1); // parcelMap.put("width", 8); // parcelMap.put("length", 19.8); // // Map<String, Object> customsItem1Map = new HashMap<String, Object>(); // customsItem1Map.put("description", "EasyPost T-shirts"); // customsItem1Map.put("quantity", 2); // customsItem1Map.put("value", 23.56); // customsItem1Map.put("weight", 18.8); // customsItem1Map.put("origin_country", "us"); // customsItem1Map.put("hs_tariff_number", "123456"); // // Map<String, Object> customsItem2Map = new HashMap<String, Object>(); // customsItem2Map.put("description", "EasyPost Stickers"); // customsItem2Map.put("quantity", 11); // customsItem2Map.put("value", 8.98); // customsItem2Map.put("weight", 3.2); // customsItem2Map.put("origin_country", "us"); // customsItem2Map.put("hs_tariff_number", "654321"); // // try { // Parcel parcel = Parcel.create(parcelMap); // Address fromAddress = Address.create(fromAddressMap); // Address toAddress = Address.create(toAddressMap); // // // Address verified = to_address.verify(); // // // customs // Map<String, Object> customsInfoMap = new HashMap<String, Object>(); // customsInfoMap.put("integrated_form_type", "form_2976"); // customsInfoMap.put("customs_certify", true); // customsInfoMap.put("customs_signer", "Dr. Pepper"); // customsInfoMap.put("contents_type", "gift"); // customsInfoMap.put("eel_pfc", "NOEEI 30.37(a)"); // customsInfoMap.put("non_delivery_option", "return"); // customsInfoMap.put("restriction_type", "none"); // CustomsItem customsItem1 = CustomsItem.create(customsItem1Map); // CustomsItem customsItem2 = CustomsItem.create(customsItem2Map); // List<CustomsItem> customsItemsList = new ArrayList<CustomsItem>(); // customsItemsList.add(customsItem1); // customsItemsList.add(customsItem2); // customsInfoMap.put("customs_items", customsItemsList); // CustomsInfo customsInfo = CustomsInfo.create(customsInfoMap); // // // create shipment // Map<String, Object> shipmentMap = new HashMap<String, Object>(); // shipmentMap.put("to_address", toAddress); // shipmentMap.put("from_address", fromAddress); // shipmentMap.put("parcel", parcel); // shipmentMap.put("customs_info", customsInfo); // // Shipment shipment = Shipment.create(shipmentMap); // // // buy postage // List<String> buyCarriers = new ArrayList<String>(); // buyCarriers.add("USPS"); // List<String> buyServices = new ArrayList<String>(); // buyServices.add("PriorityMailInternational"); // // shipment = shipment.buy(shipment.lowestRate(buyCarriers, buyServices)); // // String s= shipment.prettyPrint(); // String s2=s; // } catch (EasyPostException e) { // e.printStackTrace(); // } // return true; // } // // @Override // protected void onPostExecute(Boolean result) { // super.onPostExecute(result); // // } // // // // } }
3e1f410968bbb257714ff584dc448eaf01918175
1,203
java
Java
python/src/com/jetbrains/python/testing/PythonUnitTestRunnableScriptFilter.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
2
2019-04-28T07:48:50.000Z
2020-12-11T14:18:08.000Z
python/src/com/jetbrains/python/testing/PythonUnitTestRunnableScriptFilter.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
1
2020-07-30T19:04:47.000Z
2020-07-30T19:04:47.000Z
python/src/com/jetbrains/python/testing/PythonUnitTestRunnableScriptFilter.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
1
2020-10-15T05:56:42.000Z
2020-10-15T05:56:42.000Z
32.513514
81
0.76143
13,212
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.testing; import com.intellij.execution.Location; import com.jetbrains.python.run.RunnableScriptFilter; import org.jetbrains.annotations.ApiStatus; /** * @author Ilya.Kazakevich */ public final class PythonUnitTestRunnableScriptFilter { private PythonUnitTestRunnableScriptFilter(){} /** * @deprecated Use {@link RunnableScriptFilter#isIfNameMain(Location)} instead. */ @ApiStatus.ScheduledForRemoval(inVersion = "2021.1") @Deprecated public static boolean isIfNameMain(Location location) { return RunnableScriptFilter.isIfNameMain(location); } }
3e1f412ad0261f1370d3bfc8ed29e978d9075d1a
3,362
java
Java
backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/ExportRepoImageCommandTest.java
UranusBlockStack/ovirt-engine
fe3c90ed3e74e6af9497c826c82e653382946ae1
[ "Apache-2.0" ]
null
null
null
backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/ExportRepoImageCommandTest.java
UranusBlockStack/ovirt-engine
fe3c90ed3e74e6af9497c826c82e653382946ae1
[ "Apache-2.0" ]
null
null
null
backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/ExportRepoImageCommandTest.java
UranusBlockStack/ovirt-engine
fe3c90ed3e74e6af9497c826c82e653382946ae1
[ "Apache-2.0" ]
null
null
null
34.659794
101
0.742415
13,213
package org.ovirt.engine.core.bll; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.ovirt.engine.core.common.action.ExportRepoImageParameters; import org.ovirt.engine.core.common.businessentities.StorageDomainStatus; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VMStatus; import org.ovirt.engine.core.common.businessentities.storage.ImageStatus; import org.ovirt.engine.core.common.errors.VdcBllMessages; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.dao.VmDAO; import java.util.Arrays; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; /** A test case for {@link org.ovirt.engine.core.bll.ExportRepoImageCommandTest} */ @RunWith(MockitoJUnitRunner.class) public class ExportRepoImageCommandTest extends ImportExportRepoImageCommandTest { @Mock protected VmDAO vmDao; protected ExportRepoImageCommand<ExportRepoImageParameters> cmd; protected VM vm; @Before public void setUp() { super.setUp(); vm = new VM(); vm.setStatus(VMStatus.Down); when(vmDao.getVmsListForDisk(getDiskImageId(), Boolean.FALSE)).thenReturn(Arrays.asList(vm)); ExportRepoImageParameters exportParameters = new ExportRepoImageParameters( getDiskImageGroupId(), getRepoStorageDomainId()); cmd = spy(new ExportRepoImageCommand<>(exportParameters)); doReturn(vmDao).when(cmd).getVmDAO(); doReturn(getStorageDomainDao()).when(cmd).getStorageDomainDAO(); doReturn(getStoragePoolDao()).when(cmd).getStoragePoolDAO(); doReturn(getDiskDao()).when(cmd).getDiskDao(); doReturn(getProviderProxy()).when(cmd).getProviderProxy(); } @Test public void testCanDoActionSuccess() { CanDoActionTestUtils.runAndAssertCanDoActionSuccess(cmd); } @Test public void testCanDoActionImageDoesNotExist() { when(getDiskDao().get(getDiskImageGroupId())).thenReturn(null); CanDoActionTestUtils.runAndAssertCanDoActionFailure(cmd, VdcBllMessages.ACTION_TYPE_FAILED_DISK_NOT_EXIST); } @Test public void testCanDoActionDomainInMaintenance() { getDiskStorageDomain().setStatus(StorageDomainStatus.Maintenance); CanDoActionTestUtils.runAndAssertCanDoActionFailure(cmd, VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2); } @Test public void testCanDoActionImageHasParent() { getDiskImage().setParentId(Guid.newGuid()); CanDoActionTestUtils.runAndAssertCanDoActionFailure(cmd, VdcBllMessages.ACTION_TYPE_FAILED_DISK_CONFIGURATION_NOT_SUPPORTED); } @Test public void testCanDoActionVmRunning() { vm.setStatus(VMStatus.Up); CanDoActionTestUtils.runAndAssertCanDoActionFailure(cmd, VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_RUNNING); } @Test public void testCanDoActionImageLocked() { getDiskImage().setImageStatus(ImageStatus.LOCKED); CanDoActionTestUtils.runAndAssertCanDoActionFailure(cmd, VdcBllMessages.ACTION_TYPE_FAILED_DISKS_LOCKED); } }
3e1f413527fa0967ba462652f37d5192a7e6baf3
7,869
java
Java
src/main/java/net/daw/dao/TipoproductoDao.java
yolanda83/tailorShop
2802cbc46ba22dffa73fb8c91691f98afebab141
[ "MIT" ]
null
null
null
src/main/java/net/daw/dao/TipoproductoDao.java
yolanda83/tailorShop
2802cbc46ba22dffa73fb8c91691f98afebab141
[ "MIT" ]
null
null
null
src/main/java/net/daw/dao/TipoproductoDao.java
yolanda83/tailorShop
2802cbc46ba22dffa73fb8c91691f98afebab141
[ "MIT" ]
null
null
null
33.918103
136
0.543017
13,214
package net.daw.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import net.daw.bean.TipoproductoBean; import net.daw.helper.SqlBuilder; /** * * @author Yolanda */ public class TipoproductoDao { Connection oConnection; String ob = null; /** * Constructor * * @param oConnection * @param ob */ public TipoproductoDao(Connection oConnection, String ob) { super(); this.oConnection = oConnection; this.ob = ob; } /** * Método GET * * @param id * @param expand * @return Devuelve un Bean de un Tipo Producto concreto * @throws Exception */ public TipoproductoBean get(int id, Integer expand) throws Exception { String strSQL = "SELECT * FROM " + ob + " WHERE id=?"; TipoproductoBean oTipoproductoBean; ResultSet oResultSet = null; PreparedStatement oPreparedStatement = null; try { oPreparedStatement = oConnection.prepareStatement(strSQL); oPreparedStatement.setInt(1, id); oResultSet = oPreparedStatement.executeQuery(); if (oResultSet.next()) { oTipoproductoBean = new TipoproductoBean(); oTipoproductoBean.fill(oResultSet, oConnection, expand); } else { oTipoproductoBean = null; } } catch (SQLException e) { throw new Exception("Error en Dao get de " + ob, e); } finally { if (oResultSet != null) { oResultSet.close(); } if (oPreparedStatement != null) { oPreparedStatement.close(); } } return oTipoproductoBean; } /** * Método REMOVE * * @param id * @return Borra un producto concreto. Devuelve un resultado binario: (1) * éxito (0) fallo * @throws Exception */ public int remove(int id) throws Exception { int iRes = 0; String strSQL = "DELETE FROM " + ob + " WHERE id=?"; PreparedStatement oPreparedStatement = null; try { oPreparedStatement = oConnection.prepareStatement(strSQL); oPreparedStatement.setInt(1, id); iRes = oPreparedStatement.executeUpdate(); } catch (SQLException e) { throw new Exception("Error en Dao remove de " + ob, e); } finally { if (oPreparedStatement != null) { oPreparedStatement.close(); } } return iRes; } /** * Método GET COUNT * * @return Devuelve el nº de Tipos de Productos en la BBDD * @throws Exception */ public int getcount() throws Exception { String strSQL = "SELECT COUNT(id) FROM " + ob; int res = 0; ResultSet oResultSet = null; PreparedStatement oPreparedStatement = null; try { oPreparedStatement = oConnection.prepareStatement(strSQL); oResultSet = oPreparedStatement.executeQuery(); if (oResultSet.next()) { res = oResultSet.getInt(1); } } catch (SQLException e) { throw new Exception("Error en Dao get de " + ob, e); } finally { if (oResultSet != null) { oResultSet.close(); } if (oPreparedStatement != null) { oPreparedStatement.close(); } } return res; } /** * Método CREATE * * @param oTipoproductoBean * @return Crea un Tipo Producto y lo devuelve como Bean relleno. * @throws Exception */ public TipoproductoBean create(TipoproductoBean oTipoproductoBean) throws Exception { String strSQL = "INSERT INTO " + ob + " (`id`, `desc`) VALUES (NULL, ?); "; ResultSet oResultSet = null; PreparedStatement oPreparedStatement = null; try { oPreparedStatement = oConnection.prepareStatement(strSQL); oPreparedStatement.setString(1, oTipoproductoBean.getDesc()); oPreparedStatement.executeUpdate(); oResultSet = oPreparedStatement.getGeneratedKeys(); if (oResultSet.next()) { oTipoproductoBean.setId(oResultSet.getInt(1)); } else { oTipoproductoBean.setId(0); } } catch (SQLException e) { throw new Exception("Error en Dao create de " + ob, e); } finally { if (oResultSet != null) { oResultSet.close(); } if (oPreparedStatement != null) { oPreparedStatement.close(); } } return oTipoproductoBean; } /** * Método UPDATE * * @param oTipoproductoBean * @return Actualiza un Tipo Producto. Devuelve un resultado binario: (1) * éxito (0) fallo * @throws Exception */ public int update(TipoproductoBean oTipoproductoBean) throws Exception { int iResult = 0; String strSQL = "UPDATE " + ob + " SET " + ob + ".desc = ? WHERE id = ?;"; PreparedStatement oPreparedStatement = null; try { oPreparedStatement = oConnection.prepareStatement(strSQL); oPreparedStatement.setString(1, oTipoproductoBean.getDesc()); oPreparedStatement.setInt(2, oTipoproductoBean.getId()); iResult = oPreparedStatement.executeUpdate(); } catch (SQLException e) { throw new Exception("Error en Dao update de " + ob, e); } finally { if (oPreparedStatement != null) { oPreparedStatement.close(); } } return iResult; } /** * Método GET PAGE * * @param iRpp * @param iPage * @param hmOrder * @param expand * @return Devuelve un arrayList con todos los Tipo Productos en la BBDD * @throws Exception */ public ArrayList<TipoproductoBean> getpage(int iRpp, int iPage, HashMap<String, String> hmOrder, Integer expand) throws Exception { String strSQL = "SELECT * FROM " + ob; strSQL += SqlBuilder.buildSqlOrder(hmOrder); ArrayList<TipoproductoBean> alTipoproductoBean; if (iRpp > 0 && iRpp < 100000 && iPage > 0 && iPage < 100000000) { strSQL += " LIMIT " + (iPage - 1) * iRpp + ", " + iRpp; ResultSet oResultSet = null; PreparedStatement oPreparedStatement = null; try { oPreparedStatement = oConnection.prepareStatement(strSQL); oResultSet = oPreparedStatement.executeQuery(); alTipoproductoBean = new ArrayList<TipoproductoBean>(); while (oResultSet.next()) { TipoproductoBean oTipoproductoBean = new TipoproductoBean(); oTipoproductoBean.fill(oResultSet, oConnection, expand); alTipoproductoBean.add(oTipoproductoBean); } } catch (SQLException e) { throw new Exception("Error en Dao getpage de " + ob, e); } finally { if (oResultSet != null) { oResultSet.close(); } if (oPreparedStatement != null) { oPreparedStatement.close(); } } } else { throw new Exception("Error en Dao getpage de " + ob); } return alTipoproductoBean; } }
3e1f41c69089c160fc63ce3e02e52708f4874723
4,008
java
Java
java/TestProcessor/src/main/java/com/heaven7/java/study/processor/MyProcessor.java
LightSun/tool_plugin_study
9fb8fcdd3e614d639e48b6e97ae5a094b7d36ebe
[ "Apache-2.0" ]
null
null
null
java/TestProcessor/src/main/java/com/heaven7/java/study/processor/MyProcessor.java
LightSun/tool_plugin_study
9fb8fcdd3e614d639e48b6e97ae5a094b7d36ebe
[ "Apache-2.0" ]
null
null
null
java/TestProcessor/src/main/java/com/heaven7/java/study/processor/MyProcessor.java
LightSun/tool_plugin_study
9fb8fcdd3e614d639e48b6e97ae5a094b7d36ebe
[ "Apache-2.0" ]
null
null
null
49.802469
159
0.665097
13,215
package com.heaven7.java.study.processor; import javax.annotation.processing.*; import javax.lang.model.SourceVersion; import javax.lang.model.element.*; import javax.tools.Diagnostic; import java.util.Arrays; import java.util.Set; /** * 步骤: build jar * .java 源代码生成器 github. TypeSpec */ @SupportedAnnotationTypes({"com.heaven7.java.study.processor.PrintMe", "com.heaven7.java.study.processor.ShouldProxy"}) @SupportedSourceVersion(SourceVersion.RELEASE_6) //@SupportedOptions() //supportedOptions用来表示所支持的附加选项 public class MyProcessor extends AbstractProcessor { @Override public synchronized void init(ProcessingEnvironment processingEnv) { /** * 在init()中我们获得如下引用: Elements:一个用来处理Element的工具类; Types:一个用来处理TypeMirror的工具类; Filer:正如这个名字所示,使用Filer你可以创建文件; */ super.init(processingEnv); } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) { Messager messager = processingEnv.getMessager(); for (TypeElement te : annotations) { //TypeElement 代表 注解的元素.这里有@PrintMe messager.printMessage(Diagnostic.Kind.WARNING, "TypeElement: " + te.getClass().getName()); //com.sun.tools.javac.code.Symbol$ClassSymbol messager.printMessage(Diagnostic.Kind.WARNING, "getNestingKind(): " + te.getNestingKind()); messager.printMessage(Diagnostic.Kind.WARNING, "getInterfaces(): " + te.getInterfaces()); messager.printMessage(Diagnostic.Kind.WARNING, "getSuperclass(): " + te.getSuperclass()); messager.printMessage(Diagnostic.Kind.WARNING, "getTypeParameters(): " + te.getTypeParameters()); messager.printMessage(Diagnostic.Kind.WARNING, "getQualifiedName(): " + te.getQualifiedName()); for (Element e : env.getElementsAnnotatedWith(te)) { messager.printMessage(Diagnostic.Kind.NOTE, "Element: " + e.getClass().getName()); messager.printMessage(Diagnostic.Kind.NOTE, "asType(): " + e.asType()); messager.printMessage(Diagnostic.Kind.NOTE, "getAnnotationMirrors(): " + e.getAnnotationMirrors());efpyi@example.com messager.printMessage(Diagnostic.Kind.NOTE, "getEnclosedElements(): " + e.getEnclosedElements());//得到所有的filed,method. /** * 得到使用注解的类名的前缀 * pulltorefresh.android.heaven7.com.pulltorefesh.sample.PullToRefreshTestActivity ->pulltorefresh.android.heaven7.com.pulltorefesh.sample */ messager.printMessage(Diagnostic.Kind.NOTE, "getEnclosingElement(): " + e.getEnclosingElement()); messager.printMessage(Diagnostic.Kind.NOTE, "getKind(): " + e.getKind()); //CLASS messager.printMessage(Diagnostic.Kind.NOTE, "Printing: " + e.toString());//完整的类,类,名 } } // processingEnv.getFiler().createSourceFile("heaven7", ) return true; } @Override public Iterable<? extends Completion> getCompletions(Element element, AnnotationMirror annotation, ExecutableElement member, String userText) { Messager msg = processingEnv.getMessager(); msg.printMessage(Diagnostic.Kind.NOTE, "--------------- start getCompletions() --------------------"); msg.printMessage(Diagnostic.Kind.NOTE, "Element: " + element); msg.printMessage(Diagnostic.Kind.NOTE, "annotation: " + annotation); msg.printMessage(Diagnostic.Kind.NOTE, "ExecutableElement: " + member); msg.printMessage(Diagnostic.Kind.NOTE, "userText: " + userText); msg.printMessage(Diagnostic.Kind.NOTE, "--------------- end getCompletions() --------------------"); // return super.getCompletions(element, annotation, member, userText); return Arrays.asList(Completions.of("key_test", "test message")); } @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } }
3e1f42762dedb62937658a41ce35aec8c071f012
2,245
java
Java
lucene/core/src/test/org/apache/lucene/analysis/tokenattributes/TestBytesRefAttImpl.java
keren123/lucence
1dcb64b492b33f2adc3735458eefbc80e8feb1ef
[ "BSD-2-Clause", "Apache-2.0" ]
903
2015-01-02T22:13:47.000Z
2022-03-31T13:40:42.000Z
lucene/core/src/test/org/apache/lucene/analysis/tokenattributes/TestBytesRefAttImpl.java
keren123/lucence
1dcb64b492b33f2adc3735458eefbc80e8feb1ef
[ "BSD-2-Clause", "Apache-2.0" ]
429
2021-03-10T14:47:58.000Z
2022-03-31T21:26:52.000Z
lucene/core/src/test/org/apache/lucene/analysis/tokenattributes/TestBytesRefAttImpl.java
keren123/lucence
1dcb64b492b33f2adc3735458eefbc80e8feb1ef
[ "BSD-2-Clause", "Apache-2.0" ]
480
2015-01-05T03:07:05.000Z
2022-03-31T10:35:08.000Z
40.089286
94
0.742539
13,216
/* * 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.lucene.analysis.tokenattributes; import java.util.stream.Stream; import org.apache.lucene.tests.util.LuceneTestCase; import org.apache.lucene.util.AttributeImpl; import org.apache.lucene.util.BytesRef; public class TestBytesRefAttImpl extends LuceneTestCase { public void testCopyTo() throws Exception { BytesTermAttributeImpl t = new BytesTermAttributeImpl(); BytesTermAttributeImpl copy = assertCopyIsEqual(t); // first do empty assertEquals(t.getBytesRef(), copy.getBytesRef()); assertNull(copy.getBytesRef()); // now after setting it t.setBytesRef(new BytesRef("hello")); copy = assertCopyIsEqual(t); assertEquals(t.getBytesRef(), copy.getBytesRef()); assertNotSame(t.getBytesRef(), copy.getBytesRef()); } public static <T extends AttributeImpl> T assertCopyIsEqual(T att) throws Exception { @SuppressWarnings("unchecked") T copy = (T) att.getClass().getConstructor().newInstance(); att.copyTo(copy); assertEquals("Copied instance must be equal", att, copy); assertEquals("Copied instance's hashcode must be equal", att.hashCode(), copy.hashCode()); return copy; } public void testLucene9856() { assertTrue( "BytesTermAttributeImpl must explicitly declare to implement TermToBytesRefAttribute", Stream.of(BytesTermAttributeImpl.class.getInterfaces()) .anyMatch(TermToBytesRefAttribute.class::equals)); } }
3e1f4319011e498e673723605dce8d506d78c31d
9,364
java
Java
spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestParamMethodArgumentResolverTests.java
JiaMingLiu93/Spring
31a277503eb36eadc12ca5036842591cad56a650
[ "Apache-2.0" ]
1
2021-03-12T03:01:56.000Z
2021-03-12T03:01:56.000Z
spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestParamMethodArgumentResolverTests.java
JiaMingLiu93/Spring
31a277503eb36eadc12ca5036842591cad56a650
[ "Apache-2.0" ]
null
null
null
spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestParamMethodArgumentResolverTests.java
JiaMingLiu93/Spring
31a277503eb36eadc12ca5036842591cad56a650
[ "Apache-2.0" ]
1
2017-01-04T19:28:28.000Z
2017-01-04T19:28:28.000Z
39.016667
100
0.80094
13,217
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.reactive.result.method.annotation; import java.lang.reflect.Method; import java.net.URISyntaxException; import java.util.Map; import java.util.Optional; import org.junit.Before; import org.junit.Test; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import org.springframework.core.LocalVariableTableParameterNameDiscoverer; import org.springframework.core.MethodParameter; import org.springframework.core.ParameterNameDiscoverer; import org.springframework.core.annotation.SynthesizingMethodParameter; import org.springframework.format.support.DefaultFormattingConversionService; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest; import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse; import org.springframework.util.MultiValueMap; import org.springframework.util.ReflectionUtils; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.support.ConfigurableWebBindingInitializer; import org.springframework.web.reactive.BindingContext; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebInputException; import org.springframework.web.server.adapter.DefaultServerWebExchange; import org.springframework.web.server.session.MockWebSessionManager; import org.springframework.web.server.session.WebSessionManager; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.springframework.web.util.UriComponentsBuilder.fromPath; /** * Unit tests for {@link RequestParamMethodArgumentResolver}. * * @author Rossen Stoyanchev */ public class RequestParamMethodArgumentResolverTests { private RequestParamMethodArgumentResolver resolver; private MethodParameter paramNamedDefaultValueString; private MethodParameter paramNamedStringArray; private MethodParameter paramNamedMap; private MethodParameter paramMap; private MethodParameter paramStringNotAnnot; private MethodParameter paramRequired; private MethodParameter paramNotRequired; private MethodParameter paramOptional; private BindingContext bindContext; @Before @SuppressWarnings("ConfusingArgumentToVarargsMethod") public void setUp() throws Exception { this.resolver = new RequestParamMethodArgumentResolver(null, true); ParameterNameDiscoverer paramNameDiscoverer = new LocalVariableTableParameterNameDiscoverer(); Method method = ReflectionUtils.findMethod(getClass(), "handle", (Class<?>[]) null); this.paramNamedDefaultValueString = new SynthesizingMethodParameter(method, 0); this.paramNamedStringArray = new SynthesizingMethodParameter(method, 1); this.paramNamedMap = new SynthesizingMethodParameter(method, 2); this.paramMap = new SynthesizingMethodParameter(method, 3); this.paramStringNotAnnot = new SynthesizingMethodParameter(method, 4); this.paramStringNotAnnot.initParameterNameDiscovery(paramNameDiscoverer); this.paramRequired = new SynthesizingMethodParameter(method, 5); this.paramNotRequired = new SynthesizingMethodParameter(method, 6); this.paramOptional = new SynthesizingMethodParameter(method, 7); ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer(); initializer.setConversionService(new DefaultFormattingConversionService()); this.bindContext = new BindingContext(initializer); } @Test public void supportsParameter() { this.resolver = new RequestParamMethodArgumentResolver(null, true); assertTrue(this.resolver.supportsParameter(this.paramNamedDefaultValueString)); assertTrue(this.resolver.supportsParameter(this.paramNamedStringArray)); assertTrue(this.resolver.supportsParameter(this.paramNamedMap)); assertFalse(this.resolver.supportsParameter(this.paramMap)); assertTrue(this.resolver.supportsParameter(this.paramStringNotAnnot)); assertTrue(this.resolver.supportsParameter(this.paramRequired)); assertTrue(this.resolver.supportsParameter(this.paramNotRequired)); assertTrue(this.resolver.supportsParameter(this.paramOptional)); this.resolver = new RequestParamMethodArgumentResolver(null, false); assertFalse(this.resolver.supportsParameter(this.paramStringNotAnnot)); } @Test public void resolveWithQueryString() throws Exception { assertEquals("foo", resolve(this.paramNamedDefaultValueString, exchangeWithQuery("name=foo"))); } @Test public void resolveWithFormData() throws Exception { assertEquals("foo", resolve(this.paramNamedDefaultValueString, exchangeWithFormData("name=foo"))); } @Test public void resolveStringArray() throws Exception { Object result = resolve(this.paramNamedStringArray, exchangeWithQuery("name=foo&name=bar")); assertTrue(result instanceof String[]); assertArrayEquals(new String[] {"foo", "bar"}, (String[]) result); } @Test public void resolveDefaultValue() throws Exception { Object result = resolve(this.paramNamedDefaultValueString, exchange()); assertEquals("bar", result); } @Test public void missingRequestParam() throws Exception { Mono<Object> mono = this.resolver.resolveArgument( this.paramNamedStringArray, this.bindContext, exchange()); StepVerifier.create(mono) .expectNextCount(0) .expectError(ServerWebInputException.class) .verify(); } @Test public void resolveSimpleTypeParam() throws Exception { ServerWebExchange exchange = exchangeWithQuery("stringNotAnnot=plainValue"); Object result = resolve(this.paramStringNotAnnot, exchange); assertEquals("plainValue", result); } @Test // SPR-8561 public void resolveSimpleTypeParamToNull() throws Exception { assertNull(resolve(this.paramStringNotAnnot, exchange())); } @Test // SPR-10180 public void resolveEmptyValueToDefault() throws Exception { ServerWebExchange exchange = exchangeWithQuery("name="); Object result = resolve(this.paramNamedDefaultValueString, exchange); assertEquals("bar", result); } @Test public void resolveEmptyValueWithoutDefault() throws Exception { assertEquals("", resolve(this.paramStringNotAnnot, exchangeWithQuery("stringNotAnnot="))); } @Test public void resolveEmptyValueRequiredWithoutDefault() throws Exception { assertEquals("", resolve(this.paramRequired, exchangeWithQuery("name="))); } @Test public void resolveOptionalParamValue() throws Exception { ServerWebExchange exchange = exchange(); Object result = resolve(this.paramOptional, exchange); assertEquals(Optional.empty(), result); exchange = exchangeWithQuery("name=123"); result = resolve(this.paramOptional, exchange); assertEquals(Optional.class, result.getClass()); Optional<?> value = (Optional<?>) result; assertTrue(value.isPresent()); assertEquals(123, value.get()); } private ServerWebExchange exchangeWithQuery(String query) throws URISyntaxException { MockServerHttpRequest request = new MockServerHttpRequest(HttpMethod.GET, "/"); MultiValueMap<String, String> params = fromPath("/").query(query).build().getQueryParams(); request.getQueryParams().putAll(params); return exchange(request); } private ServerWebExchange exchangeWithFormData(String formData) throws URISyntaxException { MockServerHttpRequest request = new MockServerHttpRequest(HttpMethod.GET, "/"); request.getHeaders().setContentType(MediaType.APPLICATION_FORM_URLENCODED); request.setBody(formData); return exchange(request); } private ServerWebExchange exchange() { return exchange(new MockServerHttpRequest(HttpMethod.GET, "/")); } private ServerWebExchange exchange(ServerHttpRequest request) { MockServerHttpResponse response = new MockServerHttpResponse(); WebSessionManager manager = new MockWebSessionManager(); return new DefaultServerWebExchange(request, response, manager); } private Object resolve(MethodParameter parameter, ServerWebExchange exchange) { return this.resolver.resolveArgument(parameter, this.bindContext, exchange).blockMillis(0); } @SuppressWarnings({"unused", "OptionalUsedAsFieldOrParameterType"}) public void handle( @RequestParam(name = "name", defaultValue = "bar") String param1, @RequestParam("name") String[] param2, @RequestParam("name") Map<?, ?> param3, @RequestParam Map<?, ?> param4, String stringNotAnnot, @RequestParam("name") String paramRequired, @RequestParam(name = "name", required = false) String paramNotRequired, @RequestParam("name") Optional<Integer> paramOptional) { } }
3e1f43ab9baca4ed74fef663bd2c0cbc08219e3b
495
java
Java
Week1/Examples/ExtraExamples/junit/AllTests.java
Dreadcyc/Training
e339bd2e8ddcfa8f8bf2a0e5706eab12d2c08107
[ "MIT" ]
1
2020-11-09T21:34:07.000Z
2020-11-09T21:34:07.000Z
Week1/Examples/ExtraExamples/junit/AllTests.java
Dreadcyc/Training
e339bd2e8ddcfa8f8bf2a0e5706eab12d2c08107
[ "MIT" ]
null
null
null
Week1/Examples/ExtraExamples/junit/AllTests.java
Dreadcyc/Training
e339bd2e8ddcfa8f8bf2a0e5706eab12d2c08107
[ "MIT" ]
9
2020-11-10T15:53:05.000Z
2021-02-11T04:17:25.000Z
30.9375
81
0.787879
13,218
package com.revature.junit; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; //A test suite is a grouping of test cases //A test case is a grouping of test steps for testing a particular feature @RunWith(Suite.class)//denotes that we are going to use a test suite @SuiteClasses({ Annotations.class, ArithmeticTest.class, ArithmeticTest2.class }) //this denotes which tests are part of this testing suite public class AllTests { }
3e1f43ebcd6f2aa59570a521d311ced4ba5ae6ad
2,793
java
Java
zk-customer-service/src/main/java/geektime/spring/zk/CustomerRunner.java
monsterhxw/Spring-Learning-Practice
1a4e549a83339957bab62ac81cd11dec5ae27316
[ "MIT" ]
null
null
null
zk-customer-service/src/main/java/geektime/spring/zk/CustomerRunner.java
monsterhxw/Spring-Learning-Practice
1a4e549a83339957bab62ac81cd11dec5ae27316
[ "MIT" ]
null
null
null
zk-customer-service/src/main/java/geektime/spring/zk/CustomerRunner.java
monsterhxw/Spring-Learning-Practice
1a4e549a83339957bab62ac81cd11dec5ae27316
[ "MIT" ]
null
null
null
37.743243
106
0.696384
13,219
package geektime.spring.zk; import geektime.spring.zk.model.Coffee; import geektime.spring.zk.model.CoffeeOrder; import geektime.spring.zk.model.NewOrderRequest; import java.util.Arrays; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpMethod; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; @Component @Slf4j public class CustomerRunner implements ApplicationRunner { @Autowired private RestTemplate restTemplate; @Autowired private DiscoveryClient discoveryClient; @Override public void run(ApplicationArguments args) throws Exception { showServiceInstances(); readMenu(); Long id = orderCoffee(); queryOrder(id); } private void showServiceInstances() { log.info("DiscoveryClient: {}", discoveryClient.getClass().getName()); discoveryClient.getInstances("springbucks-service").forEach(s -> { log.info("Host: {}, Port: {}", s.getHost(), s.getPort()); }); } private void readMenu() { ParameterizedTypeReference<List<Coffee>> ptr = new ParameterizedTypeReference<List<Coffee>>() { }; ResponseEntity<List<Coffee>> list = restTemplate .exchange("http://springbucks-service/coffee/", HttpMethod.GET, null, ptr); list.getBody().forEach(c -> log.info("Coffee: {}", c)); } private Long orderCoffee() { NewOrderRequest orderRequest = NewOrderRequest.builder() .customer("Li Lei") .items(Arrays.asList("capuccino")) .build(); RequestEntity<NewOrderRequest> request = RequestEntity .post(UriComponentsBuilder.fromUriString("http://springbucks-service/order/").build().toUri()) .body(orderRequest); ResponseEntity<CoffeeOrder> response = restTemplate.exchange(request, CoffeeOrder.class); log.info("Order Request Status Code: {}", response.getStatusCode()); Long id = response.getBody().getId(); log.info("Order ID: {}", id); return id; } private void queryOrder(Long id) { CoffeeOrder order = restTemplate .getForObject("http://springbucks-service/order/{id}", CoffeeOrder.class, id); log.info("Order: {}", order); } }
3e1f44a1b38fce3f9f761cd46c6308693a562b39
7,241
java
Java
d2/src/test/java/com/linkedin/d2/balancer/properties/UriPropertiesSerializerTest.java
radai-rosenblatt/rest.li
08c5c3c4b951eb134ba192a323c72833ec9541d8
[ "Apache-2.0" ]
1,682
2015-01-07T03:29:42.000Z
2022-03-30T22:50:53.000Z
d2/src/test/java/com/linkedin/d2/balancer/properties/UriPropertiesSerializerTest.java
radai-rosenblatt/rest.li
08c5c3c4b951eb134ba192a323c72833ec9541d8
[ "Apache-2.0" ]
312
2015-01-26T18:27:08.000Z
2022-03-28T16:23:12.000Z
d2/src/test/java/com/linkedin/d2/balancer/properties/UriPropertiesSerializerTest.java
radai-rosenblatt/rest.li
08c5c3c4b951eb134ba192a323c72833ec9541d8
[ "Apache-2.0" ]
441
2015-01-07T09:17:41.000Z
2022-03-26T23:14:12.000Z
41.614943
183
0.730148
13,220
/* Copyright (c) 2012 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.linkedin.d2.balancer.properties; import com.linkedin.d2.balancer.util.JacksonUtil; import com.linkedin.d2.balancer.util.partitions.DefaultPartitionAccessor; import com.linkedin.d2.discovery.PropertySerializationException; import java.net.URI; import java.net.URISyntaxException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; public class UriPropertiesSerializerTest { // the old way of constructing uri properties; ideally we would like to keep it as a constructor // However, it has the same signature as the new one after type erasure if it is still a constructor public static UriProperties getInstanceWithOldArguments(String clusterName, Map<URI, Double> weights) { Map<URI, Map<Integer, PartitionData>> partitionData = new HashMap<>(); for (URI uri : weights.keySet()) { Map<Integer, PartitionData> partitionWeight = new HashMap<>(); partitionWeight.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(weights.get(uri))); partitionData.put(uri,partitionWeight); } return new UriProperties(clusterName, partitionData); } @Test(groups = { "small", "back-end" }) public void testUriPropertiesSerializer() throws URISyntaxException, PropertySerializationException { UriPropertiesJsonSerializer jsonSerializer = new UriPropertiesJsonSerializer(); Map<URI, Double> uriWeights = new HashMap<>(); UriProperties property = getInstanceWithOldArguments("test", uriWeights); assertEquals(jsonSerializer.fromBytes(jsonSerializer.toBytes(property)), property); uriWeights.put(URI.create("http://www.google.com"), 1d); UriProperties property1 = getInstanceWithOldArguments("test", uriWeights); assertEquals(jsonSerializer.fromBytes(jsonSerializer.toBytes(property1)), property1); uriWeights.put(URI.create("http://www.imdb.com"), 2d); UriProperties property2 = getInstanceWithOldArguments("test2", uriWeights); assertEquals(jsonSerializer.fromBytes(jsonSerializer.toBytes(property2)), property2); // test new way of constructing uri property final Map<URI, Map<Integer, PartitionData>> partitionDesc = new HashMap<>(); property = new UriProperties("test 3", partitionDesc); assertEquals(jsonSerializer.fromBytes(jsonSerializer.toBytes(property)), property); final Map<Integer, PartitionData> partitions = new HashMap<>(); partitions.put(0, new PartitionData(0.3d)); partitions.put(700, new PartitionData(0.3d)); partitions.put(1200, new PartitionData(0.4d)); partitionDesc.put(URI.create("http://www.google.com"), partitions); partitionDesc.put(URI.create("http://www.imdb.com"), partitions); property = new UriProperties("test 3", partitionDesc); assertEquals(jsonSerializer.fromBytes(jsonSerializer.toBytes(property)), property); // test compatibility with old UriProperties bytes: client can understand uris published by old servers String oldUriJson = "{\"clusterName\": \"test4\", \"weights\":{\"http://www.google.com\": 1.0, \"http://www.imdb.com\": 2.0}}"; UriProperties fromOldBytes = jsonSerializer.fromBytes(oldUriJson.getBytes()); UriProperties createdNew = getInstanceWithOldArguments("test4", uriWeights); assertEquals(fromOldBytes, createdNew); // test the we include old uri format in the serialization result for unpartitioned services // servers publish uris that can be understood by old clients (if it is unpartitioned services) byte[] bytesIncludingWeights = jsonSerializer.toBytes(createdNew); UriProperties result = fromOldFormatBytes(bytesIncludingWeights); assertEquals(createdNew, result); } public UriProperties fromOldFormatBytes(byte[] bytes) throws PropertySerializationException { try { @SuppressWarnings("unchecked") Map<String, Object> untyped = JacksonUtil.getObjectMapper().readValue(new String(bytes, "UTF-8"), HashMap.class); return fromOldFormatMap(untyped); } catch (Exception e) { throw new PropertySerializationException(e); } } // this method only uses the weights map // if this method succeeds, old clients would have no problem processing the weights map @SuppressWarnings("unchecked") public UriProperties fromOldFormatMap(Map<String, Object> map) { String clusterName = (String)map.get("clusterName"); Map<URI, Map<Integer, PartitionData>> partitionDesc = new HashMap<>(); Map<String, Double> weights = (Map<String, Double>) map.get("weights"); if (weights != null) { for(Map.Entry<String, Double> weight: weights.entrySet()) { URI uri = URI.create(weight.getKey()); Map<Integer, PartitionData> partitionDataMap = new HashMap<>(); partitionDataMap.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(weight.getValue())); partitionDesc.put(uri, partitionDataMap); } } return new UriProperties(clusterName, partitionDesc); } @Test public void testWithApplicationProperties() throws PropertySerializationException { UriPropertiesJsonSerializer jsonSerializer = new UriPropertiesJsonSerializer(); URI uri = URI.create("https://www.linkedin.com"); // new constructor Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put("foo", "fooValue"); applicationProperties.put("bar", "barValue"); applicationProperties.put("baz", 1); Map<URI, Map<Integer, PartitionData>> partitionDesc = new HashMap<>(); Map<Integer, PartitionData> partitions = new HashMap<>(); partitions.put(0, new PartitionData(0.3d)); partitions.put(1000, new PartitionData(0.3d)); partitionDesc.put(uri, partitions); UriProperties properties = new UriProperties("test", partitionDesc, Collections.singletonMap(uri, applicationProperties)); UriProperties stored = jsonSerializer.fromBytes(jsonSerializer.toBytes(properties)); assertEquals(stored, properties); // from bytes that were stored using an old constructor partitionDesc = new HashMap<>(); partitions = new HashMap<>(); partitions.put(0, new PartitionData(0.3d)); partitions.put(1000, new PartitionData(0.3d)); partitionDesc.put(uri, partitions); properties = new UriProperties("test", partitionDesc); assertEquals(jsonSerializer.fromBytes("{\"clusterName\":\"test\",\"partitionDesc\":{\"https://www.linkedin.com\":{\"0\":{\"weight\":0.3},\"1000\":{\"weight\":0.3}}}}".getBytes()), properties); } }
3e1f44b025cdf4c857f4992a0cc576f244f68712
1,849
java
Java
examples/components-api-archetypes/bd-component-archetype/src/main/resources/archetype-resources/__componentNameLowerCase__-definition/src/main/java/definition/__componentNameClass__ComponentFamilyDefinition.java
wwang-talend/components
273af8f4ec300684c65b8afef23b96107680f8d9
[ "Apache-2.0" ]
53
2016-03-06T10:52:48.000Z
2020-12-09T15:11:21.000Z
examples/components-api-archetypes/bd-component-archetype/src/main/resources/archetype-resources/__componentNameLowerCase__-definition/src/main/java/definition/__componentNameClass__ComponentFamilyDefinition.java
wwang-talend/components
273af8f4ec300684c65b8afef23b96107680f8d9
[ "Apache-2.0" ]
1,727
2016-01-28T09:05:53.000Z
2022-03-29T05:59:55.000Z
examples/components-api-archetypes/bd-component-archetype/src/main/resources/archetype-resources/__componentNameLowerCase__-definition/src/main/java/definition/__componentNameClass__ComponentFamilyDefinition.java
pontus-vision/talend-components
3377a1491b3c800dda52f37d9fc7ea6f40f11015
[ "Apache-2.0" ]
112
2016-01-28T03:27:24.000Z
2021-10-13T02:58:54.000Z
42.022727
157
0.710114
13,221
// ============================================================================ // // Copyright (C) 2006-2017 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package ${package}.definition; import com.google.auto.service.AutoService; import ${packageTalend}.api.AbstractComponentFamilyDefinition; import ${packageTalend}.api.ComponentInstaller; import ${packageTalend}.api.Constants; import ${package}.definition.input.${componentNameClass}InputDefinition; import ${package}.definition.output.${componentNameClass}OutputDefinition; import org.osgi.service.component.annotations.Component; /** * Install all of the definitions provided for the ${componentName} family of components. */ @AutoService(ComponentInstaller.class) @Component(name = Constants.COMPONENT_INSTALLER_PREFIX + ${componentNameClass}ComponentFamilyDefinition.NAME, service = ComponentInstaller.class) public class ${componentNameClass}ComponentFamilyDefinition extends AbstractComponentFamilyDefinition implements ComponentInstaller { public static final String NAME = "${componentName}"; public ${componentNameClass}ComponentFamilyDefinition() { super(NAME, new ${componentNameClass}DatastoreDefinition(), new ${componentNameClass}DatasetDefinition(), new ${componentNameClass}InputDefinition(), new ${componentNameClass}OutputDefinition()); } public void install(ComponentFrameworkContext ctx) { ctx.registerComponentFamilyDefinition(this); } }
3e1f453db9d943a9104f7fd512f82940f2e96818
4,552
java
Java
benchmarks/luindex/Index.java
dshung1997/Original_VerifiedFT
f530f3fcd397014d4365cab32a84ff400ed5e042
[ "BSD-3-Clause" ]
49
2015-01-16T09:00:28.000Z
2022-03-13T17:13:16.000Z
benchmarks/luindex/Index.java
dshung1997/Original_VerifiedFT
f530f3fcd397014d4365cab32a84ff400ed5e042
[ "BSD-3-Clause" ]
1
2019-04-29T16:47:18.000Z
2019-04-29T16:47:18.000Z
benchmarks/luindex/Index.java
dshung1997/Original_VerifiedFT
f530f3fcd397014d4365cab32a84ff400ed5e042
[ "BSD-3-Clause" ]
32
2015-01-16T04:49:18.000Z
2022-03-15T15:28:29.000Z
35.015385
137
0.696178
13,222
/****************************************************************************** Copyright (c) 2016, Cormac Flanagan (University of California, Santa Cruz) and Stephen Freund (Williams College) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of the University of California, Santa Cruz and Williams College 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. ******************************************************************************/ /* * Based on code: * * 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. */ import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.demo.FileDocument; public class Index { private final File scratch; public Index(File scratch) { this.scratch = scratch; } /** * Index all text files under a directory. */ public void main(final File INDEX_DIR, final String[] args) throws Exception { IndexWriter writer = new IndexWriter(INDEX_DIR, new StandardAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); for (int arg = 0; arg < args.length; arg++) { final File docDir = new File(scratch, args[arg]); if (!docDir.exists() || !docDir.canRead()) { System.out.println("Document directory '" + docDir.getAbsolutePath() + "' does not exist or is not readable, please check the path"); throw new RuntimeException("Cannot read from document directory"); } indexDocs(writer, docDir); System.out.println("Optimizing..."); writer.optimize(); } writer.close(); } /** * Index either a file or a directory tree. * * @param writer * @param file * @throws IOException */ void indexDocs(IndexWriter writer, File file) throws IOException { /* Strip the absolute part of the path name from file name output */ int scratchP = scratch.getPath().length() + 1; /* do not try to index files that cannot be read */ if (file.canRead()) { if (file.isDirectory()) { String[] files = file.list(); // an IO error could occur if (files != null) { Arrays.sort(files); for (int i = 0; i < files.length; i++) { indexDocs(writer, new File(file, files[i])); } } } else { System.out.println("adding " + file.getPath().substring(scratchP)); try { writer.addDocument(FileDocument.Document(file)); } // at least on windows, some temporary files raise this exception with // an "access denied" message // checking if the file can be read doesn't help catch (FileNotFoundException fnfe) { ; } } } } }
3e1f45e941c466e61b634c5aedef2627176b0dd6
2,735
java
Java
Java-Concurrent-Programming-Beauty/src/main/java/com/beauty/thread/chapter1/NotifyTest.java
dongzl/Java_Multi_Thread
39200a1096475557c749db68993e3a3ccc0547b5
[ "Apache-2.0" ]
1
2018-12-04T02:11:38.000Z
2018-12-04T02:11:38.000Z
Java-Concurrent-Programming-Beauty/src/main/java/com/beauty/thread/chapter1/NotifyTest.java
dongzl/Java_Multi_Thread
39200a1096475557c749db68993e3a3ccc0547b5
[ "Apache-2.0" ]
null
null
null
Java-Concurrent-Programming-Beauty/src/main/java/com/beauty/thread/chapter1/NotifyTest.java
dongzl/Java_Multi_Thread
39200a1096475557c749db68993e3a3ccc0547b5
[ "Apache-2.0" ]
null
null
null
33.353659
81
0.403656
13,223
package com.beauty.thread.chapter1; /** * @author dongzonglei * @description * @date 2019-03-09 09:49 */ public class NotifyTest { private static volatile Object resourceA = new Object(); public static void main(String args[]) throws Exception { Thread threadA = new Thread(new Runnable() { @Override public void run() { synchronized (resourceA) { System.out.println("threadA get resourceA lock"); try {Thread threadB = new Thread(new Runnable() { @Override public void run() { synchronized (resourceA) { System.out.println("threadB get resourceA lock"); try { System.out.println("threadB begin wait"); resourceA.wait(); System.out.println("rhreadB end wait"); } catch (Exception e) { e.printStackTrace(); } } } }); System.out.println("threadA begin wait"); resourceA.wait(); System.out.println("rhreadA end wait"); } catch (Exception e) { e.printStackTrace(); } } } }); Thread threadB = new Thread(new Runnable() { @Override public void run() { synchronized (resourceA) { System.out.println("threadB get resourceA lock"); try { System.out.println("threadB begin wait"); resourceA.wait(); System.out.println("rhreadB end wait"); } catch (Exception e) { e.printStackTrace(); } } } }); Thread threadC = new Thread(new Runnable() { @Override public void run() { synchronized (resourceA) { System.out.println("threadC begin notify"); //resourceA.notifyAll(); resourceA.notify(); } } }); threadA.start(); threadB.start(); Thread.sleep(1000); threadC.start(); threadA.join(); threadB.join(); threadC.join(); System.out.println("main over"); } }
3e1f45f38da474d8405d3e73e9d007b07ebdf541
1,679
java
Java
src/util/GpxLoader.java
niedral/gpx2cruiser
5d4cf37dafced785b5e1846e3eb622e4994eb622
[ "MIT" ]
null
null
null
src/util/GpxLoader.java
niedral/gpx2cruiser
5d4cf37dafced785b5e1846e3eb622e4994eb622
[ "MIT" ]
null
null
null
src/util/GpxLoader.java
niedral/gpx2cruiser
5d4cf37dafced785b5e1846e3eb622e4994eb622
[ "MIT" ]
null
null
null
25.059701
101
0.628946
13,224
package util; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Element; import model.Waypoint; public class GpxLoader { public static final List<Waypoint> loadWaypoints(File gpxFile) { List<Waypoint> list = null; try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(gpxFile); doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("rtept"); System.out.println("----------------------------"); for (int pos = 0; pos < nList.getLength(); pos++) { if (list == null) { list = new ArrayList<Waypoint>(); } Node nNode = nList.item(pos); System.out.println("\nCurrent Element :" + nNode.getNodeName()); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println("Lat : " + eElement.getAttribute("lat")); System.out.println("Lon : " + eElement.getAttribute("lon")); Waypoint waypoint = new Waypoint(eElement.getAttribute("lat"), eElement.getAttribute("lon")); list.add(waypoint); } } } catch (Exception e) { e.printStackTrace(); return null; } return list; } }
3e1f463e6a0ff1935d9b06e533ada910523e5cc5
3,295
java
Java
src/on_tool/io/LeitorXML.java
renanrcrr/ontology-tool
ad728417d749124f26282e74cb818598b7afadd3
[ "MIT" ]
1
2019-12-27T08:42:07.000Z
2019-12-27T08:42:07.000Z
src/on_tool/io/LeitorXML.java
renanrcrr/ontology-tool
ad728417d749124f26282e74cb818598b7afadd3
[ "MIT" ]
null
null
null
src/on_tool/io/LeitorXML.java
renanrcrr/ontology-tool
ad728417d749124f26282e74cb818598b7afadd3
[ "MIT" ]
null
null
null
26.572581
69
0.669499
13,225
package on_tool.io; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Vector; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; import on_tool.desenho.AreaDesenho; import on_tool.desenho.elemento.Vertice; import org.jgraph.graph.DefaultEdge; import org.xml.sax.SAXException; public class LeitorXML { private static boolean analisar(File f, ManipuladorXML h) { boolean retorno = true; try { SAXParserFactory.newInstance().newSAXParser().parse(f, h); } catch (SAXException e) { retorno = false; e.printStackTrace(); } catch (IOException e) { retorno = false; e.printStackTrace(); } catch (ParserConfigurationException e) { retorno = false; e.printStackTrace(); } catch (FactoryConfigurationError e) { retorno = false; e.printStackTrace(); } return retorno; } private static String criarArquivoTemporario(File f) { try { BufferedReader entrada = new BufferedReader(new InputStreamReader( new FileInputStream(f), "UTF-8")); String stream = ""; String linha = entrada.readLine(); while (linha != null) { if (linha.startsWith("<!DOCTYPE")) { String temp = ""; for (int i = 0; i < linha.length(); i++) { if (linha.charAt(i) == '#') temp += System.getProperty("file.separator"); else temp += linha.charAt(i); } stream += temp + "\n"; } else stream += linha + "\n"; linha = entrada.readLine(); } entrada.close(); File arquivo = new File("temp.xml"); BufferedWriter saida = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(arquivo), "UTF-8")); for (int i = 0; i < stream.length(); i++) { if (stream.charAt(i) == '\n') saida.newLine(); else saida.write(stream.charAt(i)); } saida.flush(); saida.close(); } catch (IOException exc) { exc.printStackTrace(); } return "temp.xml"; } public static boolean lerMapa(File f, AreaDesenho area) { ManipuladorXML h = new ManipuladorXML(); boolean retorno = true; File temp = new File(criarArquivoTemporario(f)); if (analisar(temp, h)) { area.getGraphLayoutCache().insert( h.ontologia.vertices.toArray()); for (int i = 0; i < h.ontologia.ligacoesArcos.size(); i++) { Vector ligacao = (Vector)h.ontologia.ligacoesArcos.get(i); ((DefaultEdge)h.ontologia.arcos.get(i)).setSource( ((Vertice)h.ontologia.vertices.get(((Integer) ligacao.get(0)).intValue())).pegaPortPadrao()); ((DefaultEdge)h.ontologia.arcos.get(i)).setTarget( ((Vertice)h.ontologia.vertices.get(((Integer) ligacao.get(1)).intValue())).pegaPortPadrao()); } area.getGraphLayoutCache().insert( h.ontologia.arcos.toArray()); area.setSelectionCells(new Object[] {}); try { area.mudaCaminhoArquivo(f.getCanonicalPath()); } catch (IOException exc) { exc.printStackTrace(); } area.mudaNomeArquivo(f.getName()); } else retorno = false; temp.delete(); return retorno; } }
3e1f468691c64b0686eae6426ff4ce070489c8c5
30,396
java
Java
controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentContext.java
homerredroc/vespa
0a66f8f17eba82f9c0cbfbbbe37c2fcdefe93063
[ "Apache-2.0" ]
null
null
null
controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentContext.java
homerredroc/vespa
0a66f8f17eba82f9c0cbfbbbe37c2fcdefe93063
[ "Apache-2.0" ]
null
null
null
controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentContext.java
homerredroc/vespa
0a66f8f17eba82f9c0cbfbbbe37c2fcdefe93063
[ "Apache-2.0" ]
null
null
null
47.867717
183
0.625148
13,226
// Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.deployment; import com.yahoo.component.Version; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.AthenzDomain; import com.yahoo.config.provision.AthenzService; import com.yahoo.config.provision.ClusterSpec; import com.yahoo.config.provision.Environment; import com.yahoo.config.provision.HostName; import com.yahoo.config.provision.zone.RoutingMethod; import com.yahoo.config.provision.zone.ZoneId; import com.yahoo.security.KeyAlgorithm; import com.yahoo.security.KeyUtils; import com.yahoo.security.SignatureAlgorithm; import com.yahoo.security.X509CertificateBuilder; import com.yahoo.vespa.hosted.controller.Application; import com.yahoo.vespa.hosted.controller.ControllerTester; import com.yahoo.vespa.hosted.controller.Instance; import com.yahoo.vespa.hosted.controller.api.identifiers.DeploymentId; import com.yahoo.vespa.hosted.controller.api.integration.configserver.ConfigServerException; import com.yahoo.vespa.hosted.controller.api.integration.configserver.LoadBalancer; import com.yahoo.vespa.hosted.controller.api.integration.deployment.ApplicationVersion; import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobId; import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobType; import com.yahoo.vespa.hosted.controller.api.integration.deployment.RunId; import com.yahoo.vespa.hosted.controller.api.integration.deployment.SourceRevision; import com.yahoo.vespa.hosted.controller.api.integration.deployment.TesterCloud; import com.yahoo.vespa.hosted.controller.api.integration.deployment.TesterId; import com.yahoo.vespa.hosted.controller.api.integration.routing.RoutingEndpoint; import com.yahoo.vespa.hosted.controller.api.integration.routing.RoutingGeneratorMock; import com.yahoo.vespa.hosted.controller.application.ApplicationPackage; import com.yahoo.vespa.hosted.controller.application.Deployment; import com.yahoo.vespa.hosted.controller.application.EndpointId; import com.yahoo.vespa.hosted.controller.application.TenantAndApplicationId; import com.yahoo.vespa.hosted.controller.integration.ConfigServerMock; import com.yahoo.vespa.hosted.controller.maintenance.JobControl; import com.yahoo.vespa.hosted.controller.maintenance.JobRunner; import com.yahoo.vespa.hosted.controller.maintenance.NameServiceDispatcher; import com.yahoo.vespa.hosted.controller.routing.GlobalRouting; import com.yahoo.vespa.hosted.controller.routing.RoutingPolicy; import com.yahoo.vespa.hosted.controller.routing.RoutingPolicyId; import com.yahoo.vespa.hosted.controller.routing.Status; import javax.security.auth.x500.X500Principal; import java.math.BigInteger; import java.net.URI; import java.security.KeyPair; import java.security.cert.X509Certificate; import java.time.Duration; import java.time.Instant; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.succeeded; import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.unfinished; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; /** * A deployment context for an application. This allows fine-grained control of the deployment of an application's * instances. * * References to this should be acquired through {@link DeploymentTester#newDeploymentContext}. * * Tester code that is not specific to a single application's deployment context should be added to either * {@link ControllerTester} or {@link DeploymentTester} instead of this class. * * @author mpolden * @author jonmv */ public class DeploymentContext { public static final ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .athenzIdentity(AthenzDomain.from("domain"), AthenzService.from("service")) .upgradePolicy("default") .region("us-central-1") .parallel("us-west-1", "us-east-3") .emailRole("author") .emailAddress("b@a") .build(); public static final ApplicationPackage publicCdApplicationPackage = new ApplicationPackageBuilder() .athenzIdentity(AthenzDomain.from("domain"), AthenzService.from("service")) .upgradePolicy("default") .region("aws-us-east-1c") .emailRole("author") .emailAddress("b@a") .trust(generateCertificate()) .build(); public static final SourceRevision defaultSourceRevision = new SourceRevision("repository1", "master", "commit1"); private final TenantAndApplicationId applicationId; private final ApplicationId instanceId; private final TesterId testerId; private final JobController jobs; private final RoutingGeneratorMock routing; private final JobRunner runner; private final DeploymentTester tester; private final Set<Environment> deferLoadBalancerProvisioning = new HashSet<>(); private ApplicationVersion lastSubmission = null; private boolean deferDnsUpdates = false; public DeploymentContext(ApplicationId instanceId, DeploymentTester tester) { this.applicationId = TenantAndApplicationId.from(instanceId); this.instanceId = instanceId; this.testerId = TesterId.of(instanceId); this.jobs = tester.controller().jobController(); this.runner = tester.runner(); this.tester = tester; this.routing = tester.controllerTester().serviceRegistry().routingGeneratorMock(); createTenantAndApplication(); } private void createTenantAndApplication() { try { var tenant = tester.controllerTester().createTenant(instanceId.tenant().value()); tester.controllerTester().createApplication(tenant.value(), instanceId.application().value(), instanceId.instance().value()); } catch (IllegalArgumentException ignored) { } // Tenant and or application may already exist with custom setup. } public Application application() { return tester.controller().applications().requireApplication(applicationId); } public Instance instance() { return tester.controller().applications().requireInstance(instanceId); } public DeploymentStatus deploymentStatus() { return tester.controller().jobController().deploymentStatus(application()); } public Map<JobType, JobStatus> instanceJobs() { return deploymentStatus().instanceJobs(instanceId.instance()); } public Deployment deployment(ZoneId zone) { return instance().deployments().get(zone); } public ApplicationId instanceId() { return instanceId; } public TesterId testerId() { return testerId; } public DeploymentId deploymentIdIn(ZoneId zone) { return new DeploymentId(instanceId, zone); } /** Completely deploy the latest change */ public DeploymentContext deploy() { assertTrue("Application package submitted", application().latestVersion().isPresent()); assertFalse("Submission is not already deployed", application().instances().values().stream() .anyMatch(instance -> instance.deployments().values().stream() .anyMatch(deployment -> deployment.applicationVersion().equals(lastSubmission)))); assertEquals(application().latestVersion(), instance().change().application()); completeRollout(); assertFalse(instance().change().hasTargets()); return this; } /** Upgrade platform of this to given version */ public DeploymentContext deployPlatform(Version version) { assertEquals(instance().change().platform().get(), version); assertFalse(application().instances().values().stream() .anyMatch(instance -> instance.deployments().values().stream() .anyMatch(deployment -> deployment.version().equals(version)))); assertEquals(version, instance().change().platform().get()); assertFalse(instance().change().application().isPresent()); completeRollout(); assertTrue(application().productionDeployments().values().stream() .allMatch(deployments -> deployments.stream() .allMatch(deployment -> deployment.version().equals(version)))); for (var spec : application().deploymentSpec().instances()) for (JobType type : new DeploymentSteps(spec, tester.controller()::system).productionJobs()) assertTrue(tester.configServer().nodeRepository() .list(type.zone(tester.controller().system()), applicationId.defaultInstance()).stream() // TODO jonmv: support more .allMatch(node -> node.currentVersion().equals(version))); assertFalse(instance().change().hasTargets()); return this; } /** * Defer provisioning of load balancers in zones in given environment. Default behaviour is to automatically * provision load balancers in all zones that support direct routing. */ public DeploymentContext deferLoadBalancerProvisioningIn(Environment... environment) { deferLoadBalancerProvisioning.addAll(List.of(environment)); return this; } /** Defer DNS updates */ public DeploymentContext deferDnsUpdates() { deferDnsUpdates = true; return this; } /** Flush all pending DNS updates */ public DeploymentContext flushDnsUpdates() { flushDnsUpdates(Integer.MAX_VALUE); assertTrue("All name service requests dispatched", tester.controller().curator().readNameServiceQueue().requests().isEmpty()); return this; } /** Flush count pending DNS updates */ public DeploymentContext flushDnsUpdates(int count) { var dispatcher = new NameServiceDispatcher(tester.controller(), Duration.ofDays(1), new JobControl(tester.controller().curator()), count); dispatcher.run(); return this; } /** Add a routing policy for this in given zone, with status set to active */ public DeploymentContext addRoutingPolicy(ZoneId zone, boolean active) { return addRoutingPolicy(instanceId, zone, active); } /** Add a routing policy for tester instance of this in given zone, with status set to active */ public DeploymentContext addTesterRoutingPolicy(ZoneId zone, boolean active) { return addRoutingPolicy(testerId.id(), zone, active); } private DeploymentContext addRoutingPolicy(ApplicationId instance, ZoneId zone, boolean active) { var clusterId = "default" + (!active ? "-inactive" : ""); var id = new RoutingPolicyId(instance, ClusterSpec.Id.from(clusterId), zone); var policies = new LinkedHashMap<>(tester.controller().curator().readRoutingPolicies(instance)); policies.put(id, new RoutingPolicy(id, HostName.from("lb-host"), Optional.empty(), Set.of(EndpointId.of("c0")), new Status(active, GlobalRouting.DEFAULT_STATUS))); tester.controller().curator().writeRoutingPolicies(instance, policies); return this; } /** Submit given application package for deployment */ public DeploymentContext submit(ApplicationPackage applicationPackage) { return submit(applicationPackage, Optional.of(defaultSourceRevision)); } /** Submit given application package for deployment */ public DeploymentContext submit(ApplicationPackage applicationPackage, Optional<SourceRevision> sourceRevision) { var projectId = tester.controller().applications() .requireApplication(applicationId) .projectId() .orElse(1000); // These are really set through submission, so just pick one if it hasn't been set. lastSubmission = jobs.submit(applicationId, sourceRevision, Optional.of("a@b"), Optional.empty(), Optional.empty(), projectId, applicationPackage, new byte[0]); return this; } /** Submit the default application package for deployment */ public DeploymentContext submit() { return submit(tester.controller().system().isPublic() ? publicCdApplicationPackage : applicationPackage); } /** Trigger all outstanding jobs, if any */ public DeploymentContext triggerJobs() { while (tester.controller().applications().deploymentTrigger().triggerReadyJobs() > 0); return this; } /** Fail current deployment in given job */ public DeploymentContext outOfCapacity(JobType type) { return failDeployment(type, new ConfigServerException(URI.create("https://config.server"), "Failed to deploy application", "Out of capacity", ConfigServerException.ErrorCode.OUT_OF_CAPACITY, new RuntimeException("Out of capacity from test code"))); } /** Fail current deployment in given job */ public DeploymentContext failDeployment(JobType type) { return failDeployment(type, new IllegalArgumentException("Exception from test code")); } /** Fail current deployment in given job */ private DeploymentContext failDeployment(JobType type, RuntimeException exception) { triggerJobs(); var job = jobId(type); RunId id = currentRun(job).id(); configServer().throwOnNextPrepare(exception); runner.advance(currentRun(job)); assertTrue(jobs.run(id).get().hasFailed()); assertTrue(jobs.run(id).get().hasEnded()); doTeardown(job); return this; } /** Returns the last submitted application version */ public Optional<ApplicationVersion> lastSubmission() { return Optional.ofNullable(lastSubmission); } /** Runs and returns all remaining jobs for the application, at most once, and asserts the current change is rolled out. */ public DeploymentContext completeRollout() { triggerJobs(); Set<JobType> jobs = new HashSet<>(); List<Run> activeRuns; while ( ! (activeRuns = this.jobs.active(applicationId)).isEmpty()) for (Run run : activeRuns) if (jobs.add(run.id().type())) { runJob(run.id().type()); triggerJobs(); } else throw new AssertionError("Job '" + run.id() + "' was run twice"); assertFalse("Change should have no targets, but was " + instance().change(), instance().change().hasTargets()); if (!deferDnsUpdates) { flushDnsUpdates(); } return this; } /** Runs a deployment of the given package to the given dev/perf job, on the given version. */ public DeploymentContext runJob(JobType type, ApplicationPackage applicationPackage, Version vespaVersion) { jobs.deploy(instanceId, type, Optional.ofNullable(vespaVersion), applicationPackage); return runJob(type); } /** Runs a deployment of the given package to the given dev/perf job. */ public DeploymentContext runJob(JobType type, ApplicationPackage applicationPackage) { return runJob(type, applicationPackage, null); } /** Pulls the ready job trigger, and then runs the whole of the given job, successfully. */ public DeploymentContext runJob(JobType type) { var job = jobId(type); triggerJobs(); doDeploy(job); if (job.type().isDeployment()) { doUpgrade(job); doConverge(job); if (job.type().environment().isManuallyDeployed()) return this; } if (job.type().isTest()) doTests(job); doTeardown(job); return this; } /** Abort the running job of the given type and. */ public DeploymentContext abortJob(JobType type) { var job = jobId(type); assertNotSame(RunStatus.aborted, currentRun(job).status()); jobs.abort(currentRun(job).id()); jobAborted(type); return this; } /** Finish an already aborted run of the given type. */ public DeploymentContext jobAborted(JobType type) { Run run = jobs.last(instanceId, type).get(); assertSame(RunStatus.aborted, run.status()); assertFalse(run.hasEnded()); runner.advance(run); assertTrue(jobs.run(run.id()).get().hasEnded()); return this; } /** Simulate upgrade time out in given job */ public DeploymentContext timeOutUpgrade(JobType type) { var job = jobId(type); triggerJobs(); RunId id = currentRun(job).id(); doDeploy(job); tester.clock().advance(InternalStepRunner.installationTimeout.plusSeconds(1)); runner.advance(currentRun(job)); assertTrue(jobs.run(id).get().hasFailed()); assertTrue(jobs.run(id).get().hasEnded()); doTeardown(job); return this; } /** Simulate convergence time out in given job */ public DeploymentContext timeOutConvergence(JobType type) { var job = jobId(type); triggerJobs(); RunId id = currentRun(job).id(); doDeploy(job); doUpgrade(job); tester.clock().advance(InternalStepRunner.installationTimeout.plusSeconds(1)); runner.advance(currentRun(job)); assertTrue(jobs.run(id).get().hasFailed()); assertTrue(jobs.run(id).get().hasEnded()); doTeardown(job); return this; } /** Deploy default application package, start a run for that change and return its ID */ public RunId newRun(JobType type) { submit(); tester.readyJobsTrigger().maintain(); if (type.isProduction()) { runJob(JobType.systemTest); runJob(JobType.stagingTest); tester.readyJobsTrigger().maintain(); } Run run = jobs.active().stream() .filter(r -> r.id().type() == type) .findAny() .orElseThrow(() -> new AssertionError(type + " is not among the active: " + jobs.active())); return run.id(); } /** Start tests in system test stage */ public RunId startSystemTestTests() { RunId id = newRun(JobType.systemTest); runner.run(); configServer().convergeServices(instanceId, JobType.systemTest.zone(tester.controller().system())); configServer().convergeServices(testerId.id(), JobType.systemTest.zone(tester.controller().system())); setEndpoints(JobType.systemTest.zone(tester.controller().system())); runner.run(); assertEquals(unfinished, jobs.run(id).get().stepStatuses().get(Step.endTests)); assertTrue(jobs.run(id).get().steps().get(Step.endTests).startTime().isPresent()); return id; } public void assertRunning(JobType type) { assertTrue(jobId(type) + " should be among the active: " + jobs.active(), jobs.active().stream().anyMatch(run -> run.id().application().equals(instanceId) && run.id().type() == type)); } public void assertNotRunning(JobType type) { assertFalse(jobId(type) + " should not be among the active: " + jobs.active(), jobs.active().stream().anyMatch(run -> run.id().application().equals(instanceId) && run.id().type() == type)); } /** Deploys tester and real app, and completes tester and initial staging installation first if needed. */ private void doDeploy(JobId job) { RunId id = currentRun(job).id(); ZoneId zone = zone(job); DeploymentId deployment = new DeploymentId(job.application(), zone); // Provision load balancers in directly routed zones, unless explicitly deferred if (provisionLoadBalancerIn(zone)) { configServer().putLoadBalancers(zone, List.of(new LoadBalancer(deployment.toString(), deployment.applicationId(), ClusterSpec.Id.from("default"), HostName.from("lb-0--" + instanceId.serializedForm() + "--" + zone.toString()), LoadBalancer.State.active, Optional.of("dns-zone-1")))); } // First step is always a deployment. runner.advance(currentRun(job)); if (job.type().isTest()) doInstallTester(job); if (job.type() == JobType.stagingTest) { // Do the initial deployment and installation of the real application. assertEquals(unfinished, jobs.run(id).get().stepStatuses().get(Step.installInitialReal)); Versions versions = currentRun(job).versions(); tester.configServer().nodeRepository().doUpgrade(deployment, Optional.empty(), versions.sourcePlatform().orElse(versions.targetPlatform())); configServer().convergeServices(id.application(), zone); setEndpoints(zone); runner.advance(currentRun(job)); assertEquals(Step.Status.succeeded, jobs.run(id).get().stepStatuses().get(Step.installInitialReal)); // All installation is complete and endpoints are ready, so setup may begin. assertEquals(Step.Status.succeeded, jobs.run(id).get().stepStatuses().get(Step.installInitialReal)); assertEquals(Step.Status.succeeded, jobs.run(id).get().stepStatuses().get(Step.installTester)); assertEquals(Step.Status.succeeded, jobs.run(id).get().stepStatuses().get(Step.startStagingSetup)); assertEquals(unfinished, jobs.run(id).get().stepStatuses().get(Step.endStagingSetup)); tester.cloud().set(TesterCloud.Status.SUCCESS); runner.advance(currentRun(job)); assertEquals(succeeded, jobs.run(id).get().stepStatuses().get(Step.endStagingSetup)); } } /** Upgrades nodes to target version. */ private void doUpgrade(JobId job) { RunId id = currentRun(job).id(); ZoneId zone = zone(job); DeploymentId deployment = new DeploymentId(job.application(), zone); assertEquals(unfinished, jobs.run(id).get().stepStatuses().get(Step.installReal)); configServer().nodeRepository().doUpgrade(deployment, Optional.empty(), currentRun(job).versions().targetPlatform()); runner.advance(currentRun(job)); } /** Returns the current run for the given job type, and verifies it is still running normally. */ private Run currentRun(JobId job) { Run run = jobs.last(job) .filter(r -> r.id().type() == job.type()) .orElseThrow(() -> new AssertionError(job.type() + " is not among the active: " + jobs.active())); assertFalse(run.id() + " should not have failed yet", run.hasFailed()); assertFalse(run.id() + " should not have ended yet", run.hasEnded()); return run; } /** Sets a single endpoint in the routing layer */ DeploymentContext setEndpoints(ZoneId zone) { if (!supportsRoutingMethod(RoutingMethod.shared, zone)) return this; var id = instanceId; routing.putEndpoints(new DeploymentId(id, zone), Collections.singletonList(new RoutingEndpoint(String.format("https://%s--%s--%s.%s.%s.vespa:43", id.instance().value(), id.application().value(), id.tenant().value(), zone.region().value(), zone.environment().value()), "host1", true, String.format("cluster1.%s.%s.%s.%s", id.application().value(), id.tenant().value(), zone.region().value(), zone.environment().value())))); return this; } /** Lets nodes converge on new application version. */ private void doConverge(JobId job) { RunId id = currentRun(job).id(); ZoneId zone = zone(job); assertEquals(unfinished, jobs.run(id).get().stepStatuses().get(Step.installReal)); configServer().convergeServices(id.application(), zone); setEndpoints(zone); runner.advance(currentRun(job)); if (job.type().environment().isManuallyDeployed()) { assertEquals(Step.Status.succeeded, jobs.run(id).get().stepStatuses().get(Step.installReal)); assertTrue(jobs.run(id).get().hasEnded()); return; } assertEquals(Step.Status.succeeded, jobs.run(id).get().stepStatuses().get(Step.installReal)); } /** Installs tester and starts tests. */ private void doInstallTester(JobId job) { RunId id = currentRun(job).id(); ZoneId zone = zone(job); assertEquals(unfinished, jobs.run(id).get().stepStatuses().get(Step.installTester)); configServer().nodeRepository().doUpgrade(new DeploymentId(TesterId.of(job.application()).id(), zone), Optional.empty(), tester.controller().systemVersion()); runner.advance(currentRun(job)); assertEquals(unfinished, jobs.run(id).get().stepStatuses().get(Step.installTester)); configServer().convergeServices(TesterId.of(id.application()).id(), zone); runner.advance(currentRun(job)); assertEquals(succeeded, jobs.run(id).get().stepStatuses().get(Step.installTester)); runner.advance(currentRun(job)); } /** Completes tests with success. */ private void doTests(JobId job) { RunId id = currentRun(job).id(); ZoneId zone = zone(job); // All installation is complete and endpoints are ready, so tests may begin. if (job.type().isDeployment()) assertEquals(Step.Status.succeeded, jobs.run(id).get().stepStatuses().get(Step.installReal)); assertEquals(Step.Status.succeeded, jobs.run(id).get().stepStatuses().get(Step.installTester)); assertEquals(Step.Status.succeeded, jobs.run(id).get().stepStatuses().get(Step.startTests)); assertEquals(unfinished, jobs.run(id).get().stepStatuses().get(Step.endTests)); tester.cloud().set(TesterCloud.Status.SUCCESS); runner.advance(currentRun(job)); assertTrue(jobs.run(id).get().hasEnded()); assertFalse(jobs.run(id).get().hasFailed()); assertEquals(job.type().isProduction(), instance().deployments().containsKey(zone)); assertTrue(configServer().nodeRepository().list(zone, TesterId.of(id.application()).id()).isEmpty()); } /** Removes endpoints from routing layer — always call this. */ private void doTeardown(JobId job) { ZoneId zone = zone(job); DeploymentId deployment = new DeploymentId(job.application(), zone); if ( ! instance().deployments().containsKey(zone)) routing.removeEndpoints(deployment); routing.removeEndpoints(new DeploymentId(TesterId.of(job.application()).id(), zone)); } /** Returns whether a load balancer is expected to be provisioned in given zone */ private boolean provisionLoadBalancerIn(ZoneId zone) { return !deferLoadBalancerProvisioning.contains(zone.environment()) && supportsRoutingMethod(RoutingMethod.exclusive, zone); } private boolean supportsRoutingMethod(RoutingMethod method, ZoneId zone) { return tester.controller().zoneRegistry().zones().routingMethod(method).ids().contains(zone); } private JobId jobId(JobType type) { return new JobId(instanceId, type); } private ZoneId zone(JobId job) { return job.type().zone(tester.controller().system()); } private ConfigServerMock configServer() { return tester.configServer(); } private static X509Certificate generateCertificate() { KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256); X500Principal subject = new X500Principal("CN=subject"); return X509CertificateBuilder.fromKeypair(keyPair, subject, Instant.now(), Instant.now().plusSeconds(1), SignatureAlgorithm.SHA512_WITH_ECDSA, BigInteger.valueOf(1)) .build(); } }
3e1f46c02562a32fa2d79f636e41c1d15c27c7fe
32,029
java
Java
grumpy-core/src/test/java/com/github/davidmoten/grumpy/core/PositionTest.java
d3athwarrior/grumpy
8e5f5b2449dd6dc24902766c90a4251dc1055791
[ "Apache-2.0" ]
24
2015-04-20T20:25:03.000Z
2022-03-15T11:58:45.000Z
grumpy-core/src/test/java/com/github/davidmoten/grumpy/core/PositionTest.java
d3athwarrior/grumpy
8e5f5b2449dd6dc24902766c90a4251dc1055791
[ "Apache-2.0" ]
33
2019-01-20T00:41:36.000Z
2022-03-21T06:23:05.000Z
grumpy-core/src/test/java/com/github/davidmoten/grumpy/core/PositionTest.java
d3athwarrior/grumpy
8e5f5b2449dd6dc24902766c90a4251dc1055791
[ "Apache-2.0" ]
12
2016-02-20T12:42:35.000Z
2022-01-06T07:05:02.000Z
37.243023
142
0.629648
13,227
package com.github.davidmoten.grumpy.core; import static com.github.davidmoten.grumpy.core.Position.longitudeDiff; import static com.github.davidmoten.grumpy.core.Position.to180; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.slf4j.LoggerFactory; import com.github.davidmoten.grumpy.core.Position.LongitudePair; /** * @author sxo * */ public class PositionTest { private static final int ACCEPTABLE_DISTANCE_PRECISION = 3; private static final double PRECISION = 0.00001; private static final double MIN_DISTANCE_KM = 200; private static org.slf4j.Logger log = LoggerFactory.getLogger(PositionTest.class); List<Position> squareRegion; @Before public void init() { squareRegion = new ArrayList<Position>(); squareRegion.add(new Position(20, 20)); squareRegion.add(new Position(40, 20)); squareRegion.add(new Position(40, 40)); squareRegion.add(new Position(20, 40)); } @Test public final void testPredict() { Position p = new Position(53, 3); Position p2 = p.predict(100, 30); Assert.assertEquals(53.77644258276322, p2.getLat(), 0.01); Assert.assertEquals(3.7609191005595877, p2.getLon(), 0.01); // large distance tests around the equator double meanCircumferenceKm = 40041.47; // start on equator, just East of Greenwich p = new Position(0, 3); // quarter circumference, Still in Eastern hemisphere p2 = p.predict(meanCircumferenceKm / 4.0, 90); Assert.assertEquals(p.getLat(), p2.getLat(), 0.001); Assert.assertEquals(93.0, p2.getLon(), 0.1); // half circumference, Now in Western hemisphere, // just East of the International date line p2 = p.predict(meanCircumferenceKm / 2.0, 90); Assert.assertEquals(p.getLat(), p2.getLat(), 0.001); Assert.assertEquals(-177.0, p2.getLon(), 0.1); // three quarters circumference, Now in Western hemisphere, p2 = p.predict(3.0 * meanCircumferenceKm / 4.0, 90); Assert.assertEquals(p.getLat(), p2.getLat(), 0.001); Assert.assertEquals(-87.0, p2.getLon(), 0.1); // full circumference, back to start // relax Longitude tolerance slightly p2 = p.predict(meanCircumferenceKm, 90); Assert.assertEquals(p.getLat(), p2.getLat(), 0.001); Assert.assertEquals(p.getLon(), p2.getLon(), 0.2); // same thing but backwards (heading west) // quarter circumference, Still in western hemisphere p2 = p.predict(meanCircumferenceKm / 4.0, 270); Assert.assertEquals(p.getLat(), p2.getLat(), 0.001); Assert.assertEquals(-87.0, p2.getLon(), 0.1); // half circumference, Now in Western hemisphere, // just East of the International date line p2 = p.predict(meanCircumferenceKm / 2.0, 270); Assert.assertEquals(p.getLat(), p2.getLat(), 0.001); Assert.assertEquals(-177.0, p2.getLon(), 0.1); // three quarters circumference, Now in eastern hemisphere, p2 = p.predict(3.0 * meanCircumferenceKm / 4.0, 270); Assert.assertEquals(p.getLat(), p2.getLat(), 0.001); Assert.assertEquals(93.0, p2.getLon(), 0.1); // full circumference, back to start // relax Longitude tolerance slightly p2 = p.predict(meanCircumferenceKm, 90); Assert.assertEquals(p.getLat(), p2.getLat(), 0.001); Assert.assertEquals(p.getLon(), p2.getLon(), 0.2); // OVER THE South POLE // =================== // quarter circumference, should be at south pole p2 = p.predict(meanCircumferenceKm / 4.0, 180); Assert.assertEquals(-90.0, p2.getLat(), 0.1); // this next assertion is by no means confident // expecting 3 but getting it's reciprocal. // Strange things happen at the pole!! Assert.assertEquals(-177, p2.getLon(), 0.00001); // half circumference, should be at the equator // but in the Western hemisphere p2 = p.predict(meanCircumferenceKm / 2.0, 180); Assert.assertEquals(p.getLat(), p2.getLat(), 0.1); Assert.assertEquals(-177, p2.getLon(), 0.00001); // 3/4 circumference, should be at the north Pole // but in the Western hemisphere p2 = p.predict(3.0 * meanCircumferenceKm / 4.0, 180); Assert.assertEquals(90.0, p2.getLat(), 0.1); Assert.assertEquals(p.getLon(), p2.getLon(), 0.00001); // full circumference, back to start // relax latitude tolerance slightly p2 = p.predict(meanCircumferenceKm, 270); Assert.assertEquals(p.getLat(), p2.getLat(), 0.1); Assert.assertEquals(p.getLon(), p2.getLon(), 0.2); } /** * worked example from http://en.wikipedia.org/wiki/Great-circle_distance# * Radius_for_spherical_Earth used for test below */ @Test public final void testDistance() { Position p1 = new Position(36.12, -86.67); Position p2 = new Position(33.94, -118.4); Assert.assertEquals(2886.45, p1.getDistanceToKm(p2), 0.01); } @Test public final void testBearing() { // test case taken from Geoscience Australia implementation of // Vincenty formula. // http://www.ga.gov.au/bin/gda_vincenty.cgi?inverse=0&lat_degrees1=-37&lat_minutes1=57&lat_seconds1=03.72030&NamePoint1=Flinders+Peak // &lon_degrees1=144&lon_minutes1=25&lon_seconds1=29.52440&forward_azimuth_deg=306&forward_azimuth_min=52&forward_azimuth_sec=05.37 // &NamePoint2=Buninyong&ellipsoidal_dist=54972.217&lat_deg1=-37+deg&lat_min1=57+min&lat_sec1=3.7203+sec&lon_deg1=144+deg // &lon_min1=25+min&lon_sec1=29.5244+sec&f_az_deg=306+deg&f_az_min=52+min&f_az_sec=5.37+sec&Submit=Submit+Data // Note that we are not using Vincenty formula but we are close to the // answer (within 0.2 degrees). That's sufficient! Position p1 = new Position(-(37 + 57.0 / 60 + 3.72030 / 3600), 144 + 25.0 / 60 + 29.52440 / 3600); Position p2 = new Position(-(37 + 39.0 / 60 + 10.15718 / 3600), 143 + 55.0 / 60 + 35.38564 / 3600); Assert.assertEquals(Position.toDegrees(306, 52, 5.37), p1.getBearingDegrees(p2), 0.2); } @Test public final void testBearingToSelfReturnsZero() { Position p = Position.create(-10, 120); assertEquals(0, p.getBearingDegrees(p), PRECISION); } @Test public final void testBearingToSameLonReturns180() { Position p = Position.create(-10, 120); Position p2 = Position.create(-15, 120); assertEquals(180, p.getBearingDegrees(p2), PRECISION); } // @Test // public final void // testBearingWithSmallDeltaIsCorrectForTinyChangeInLatitude() { // double delta = 0.00000000000000001; // Position p = Position.create(-10, 120); // Position p2 = Position.create(-10 - delta, 120); // assertEquals(270, p.getBearingDegrees(p2), PRECISION); // } // // @Test // public final void // testBearingWithSmallDeltaIsCorrectForTinyChangeInLongitude() { // double delta = 0.00000000000000001; // Position p = Position.create(-10, 120); // Position p2 = Position.create(-10, 120 + delta); // assertEquals(90, p.getBearingDegrees(p2), PRECISION); // } @Test public final void testBearingDifference() { double precision = 0.00001; Assert.assertEquals(15.0, Position.getBearingDifferenceDegrees(20, 5), precision); Assert.assertEquals(15.0, Position.getBearingDifferenceDegrees(20, 365), precision); Assert.assertEquals(15.0, Position.getBearingDifferenceDegrees(20, 5), precision); Assert.assertEquals(15.0, Position.getBearingDifferenceDegrees(380, 5), precision); Assert.assertEquals(-25, Position.getBearingDifferenceDegrees(-20, 5), precision); Assert.assertEquals(5, Position.getBearingDifferenceDegrees(-20, -25), precision); } @Test public final void testLatLonPresentation() { char d = 0x00B0; char m = '\''; Assert.assertEquals("25" + d + "30.00" + m + "S", Position.toDegreesMinutesDecimalMinutesLatitude(-25.5)); Assert.assertEquals("0" + d + "00.00" + m + "N", Position.toDegreesMinutesDecimalMinutesLatitude(0)); Assert.assertEquals("0" + d + "30.00" + m + "S", Position.toDegreesMinutesDecimalMinutesLatitude(-0.5)); Assert.assertEquals("0" + d + "30.00" + m + "N", Position.toDegreesMinutesDecimalMinutesLatitude(0.5)); Assert.assertEquals("1" + d + "30.00" + m + "N", Position.toDegreesMinutesDecimalMinutesLatitude(1.5)); Assert.assertEquals("1" + d + "00.00" + m + "N", Position.toDegreesMinutesDecimalMinutesLatitude(1.0)); Assert.assertEquals("1" + d + "00.00" + m + "E", Position.toDegreesMinutesDecimalMinutesLongitude(1.0)); Assert.assertEquals("1" + d + "00.00" + m + "W", Position.toDegreesMinutesDecimalMinutesLongitude(-1.0)); } @Test public final void testGetPositionAlongPath() { // Create new position objects Position p1 = new Position(36.12, -86.67); Position p2 = new Position(33.94, -118.4); { double distanceKm = p1.getDistanceToKm(p2); double bearingDegrees = p1.getBearingDegrees(p2); Position p3 = p1.predict(distanceKm * 0.7, bearingDegrees); // Expected position Position actual = p1.getPositionAlongPath(p2, 0.7); // Test expected Lat return position Assert.assertEquals(p3.getLat(), actual.getLat(), 0.01); // Test expected Lon return position Assert.assertEquals(p3.getLon(), actual.getLon(), 0.01); // Test expected Lat return position Assert.assertEquals(35.47, actual.getLat(), 0.01); // Test expected Lon return position Assert.assertEquals(-109.11, actual.getLon(), 0.01); } { // If start point equals end point then a proportion // along the path should equal the start point. Position actual = p1.getPositionAlongPath(p1, 0.7); // Test expected Lat return position Assert.assertEquals(p1.getLat(), actual.getLat(), 0.01); // Test expected Lon return position Assert.assertEquals(p1.getLon(), actual.getLon(), 0.01); } { // If proportion is 0.0 then should return start point Position actual = p1.getPositionAlongPath(p2, 0.0); // Test expected Lat return position Assert.assertEquals(p1.getLat(), actual.getLat(), 0.01); // Test expected Lon return position Assert.assertEquals(p1.getLon(), actual.getLon(), 0.01); } { // If proportion is 1.0 then should return end point Position actual = p1.getPositionAlongPath(p2, 1.0); // Test expected Lat return position Assert.assertEquals(p2.getLat(), actual.getLat(), 0.01); // Test expected Lon return position Assert.assertEquals(p2.getLon(), actual.getLon(), 0.01); } } @Test(expected = RuntimeException.class) public final void testGetPositionAlongPathExceptionsGreater() { // Create new position objects Position p1 = new Position(36.12, -86.67); Position p2 = new Position(33.94, -118.4); p1.getPositionAlongPath(p2, 1.1); } @Test(expected = RuntimeException.class) public final void testGetPositionAlongPathExceptionsLess() { // Create new position objects Position p1 = new Position(36.12, -86.67); Position p2 = new Position(33.94, -118.4); p1.getPositionAlongPath(p2, -0.1); } @Test(expected = NullPointerException.class) public final void testGetPositionAlongPathExceptionsNull() { // Create new position objects Position p1 = new Position(36.12, -86.67); p1.getPositionAlongPath(null, 0.7); } @Test public final void testEnsureContinuous() { { Position a = new Position(-35, 179); Position b = new Position(-35, -178); Position c = b.ensureContinuous(a); Assert.assertEquals(182, c.getLon(), 0.0001); Assert.assertEquals(b.getLat(), c.getLat(), 0.0001); } { Position a = new Position(-35, -2); Position b = new Position(-35, 360); Position c = b.ensureContinuous(a); Assert.assertEquals(0, c.getLon(), 0.0001); } } @Test public final void testIsWithin() { final List<Position> testRegion; // square polygon with v cut out shape testRegion = new ArrayList<Position>(); testRegion.add(new Position(-20, 130)); testRegion.add(new Position(-20, 140)); testRegion.add(new Position(-30, 140)); testRegion.add(new Position(-25, 135)); testRegion.add(new Position(-30, 130)); Position bothLatAndLongInsideRegion = new Position(-24, 135); Position bothLatAndLongOutsideRegion = new Position(-35, 145); Position latInAndLongOutRegion = new Position(-25, 145); Position latOutAndLongInRegion = new Position(-35, 135); Position latInAndLongInVRegion = new Position(-28, 138); Position latOutAndLongOutVRegion = new Position(-26, 135); Position bothLatAndLongOnBorder = new Position(-20, 135); Position bothLatAndLongOnOutsideCorner = new Position(-20, 130); Position bothLatAndLongOnInsideCorner = new Position(-25, 135); Assert.assertTrue(bothLatAndLongInsideRegion.isWithin(testRegion)); Assert.assertTrue(latInAndLongInVRegion.isWithin(testRegion)); Assert.assertTrue(bothLatAndLongOnInsideCorner.isWithin(testRegion)); Assert.assertFalse(bothLatAndLongOutsideRegion.isWithin(testRegion)); Assert.assertFalse(latInAndLongOutRegion.isWithin(testRegion)); Assert.assertFalse(latOutAndLongInRegion.isWithin(testRegion)); Assert.assertFalse(latOutAndLongOutVRegion.isWithin(testRegion)); Assert.assertFalse(bothLatAndLongOnBorder.isWithin(testRegion)); Assert.assertFalse(bothLatAndLongOnOutsideCorner.isWithin(testRegion)); } /** * Returned intersection occurs in the centre of the segment and the segment * latitude is constant. */ @Test public void testGetClosestIntersectionWithSegment1() { Position p = new Position(-30, 120); Position r = p.getClosestIntersectionWithSegment(new Position(-20, 110), new Position(-20, 130)); log.info(r.getLon() + ""); log.info(r.getLat() + ""); assertEquals(-20.0, r.getLat(), 1); assertEquals(120.0, r.getLon(), 1); } /** * Returned intersection doesn't occur in the centre of the segment and the * segment latitude is constant. */ @Test public void testGetClosestIntersectionWithSegment2() { Position p = new Position(-30, 110); Position r = p.getClosestIntersectionWithSegment(new Position(-20, 100), new Position(-20, 130)); log.info(r.getLon() + ""); log.info(r.getLat() + ""); assertEquals(-20.58106, r.getLat(), PRECISION); assertEquals(110.218334, r.getLon(), PRECISION); } /** * Returned intersection occurs in the centre of the segment and the segment * longitude is constant. */ @Test public void testGetClosestIntersectionWithSegment3() { Position p = new Position(-30, 120); Position r = p.getClosestIntersectionWithSegment(new Position(-20, 110), new Position(-20, 130)); log.info(r.getLon() + ""); log.info(r.getLat() + ""); assertEquals(-20.28353, r.getLat(), PRECISION); assertEquals(119.90349, r.getLon(), PRECISION); } /** * Returned intersection doesn't occur in the centre of the segment and the * segment longitude is constant. */ @Test public void testGetClosestIntersectionWithSegment4() { Position p = new Position(-30, 110); Position r = p.getClosestIntersectionWithSegment(new Position(-20, 100), new Position(-20, 130)); // log.info(r.getLon()); // log.info(r.getLat()); assertEquals(-20.58106, r.getLat(), PRECISION); assertEquals(110.218334, r.getLon(), PRECISION); } /** * The test position should return the closest distance to the segment when * it's perpendicular to the segment. */ @Test public void testGetDistanceToSegmentKm1() { Position p = new Position(-30, 110); Position sp1 = new Position(-20, 100); Position sp2 = new Position(-20, 130); double r = p.getDistanceToSegmentKm(sp1, sp2); // log.info(r); Position intersection = p.getClosestIntersectionWithSegment(sp1, sp2); log.info("Position of intersection, used to manually calculate the distance via http://www.nhc.noaa.gov/gccalc.shtml : " + intersection); // 1047 according to http://www.nhc.noaa.gov/gccalc.shtml assertEquals(1047, r, ACCEPTABLE_DISTANCE_PRECISION); } /** * The test position should return the distance to the closest segment end * when the intersection falls out of the given segment. In this test the * position is closest to the <b>first</b> point of the segment. */ public void testGetDistanceToSegmentKm2() { Position p = new Position(-10, 115); // Segment made of two points Position sp1 = new Position(-30, 140); Position sp2 = new Position(-30, 140); Position r1 = p.getClosestIntersectionWithSegment(sp1, sp2); // log.info(r1.getLat()); // log.info(r1.getLon()); assertEquals(sp1.getLat(), r1.getLat(), PRECISION); assertEquals(sp1.getLon(), r1.getLon(), PRECISION); } /** * The test position should return the distance to the closest segment end * when the intersection falls out of the given segment. In this test the * position is closest to the <b>second</b> point of the segment. */ public void testGetDistanceToSegmentKm3() { Position p = new Position(-10, 150); // Segment made of two points Position sp1 = new Position(-20, 120); Position sp2 = new Position(-30, 140); Position r = p.getClosestIntersectionWithSegment(sp1, sp2); // log.info(r.getLat()); // log.info(r.getLon()); assertEquals(sp2.getLat(), r.getLat(), PRECISION); assertEquals(sp2.getLon(), r.getLon(), PRECISION); } /** * Test the position when the segment's start and end points are identical. * In this test the position is closest to the both the start and end * points. */ @Test public void testGetDistanceToSegmentKm4() { Position p = new Position(-10, 150); // Segment made of two points Position sp1 = new Position(-20, 120); Position sp2 = new Position(-20, 120); double r = p.getDistanceToSegmentKm(sp1, sp2); log.info(r + ""); // log.info(r.getLon()); // 3399.0 according to http://www.nhc.noaa.gov/gccalc.shtml assertEquals(3399.0, r, ACCEPTABLE_DISTANCE_PRECISION); } /** * Test the position when the it lies on segment. In this test the position * should return 0 since it lies on the line. */ @Test public void testGetDistanceToSegmentKm5() { // Segment made of two points Position sp1 = new Position(-10, 120); Position p = sp1.getPositionAlongPath(sp1, 0.4); Position sp2 = new Position(-10, 150); double r = p.getDistanceToSegmentKm(sp1, sp2); assertEquals(0, r, PRECISION); } /** * Test the position when it lies outside of the segment but in line(great * cirle path) with the two segment points. In this test the position is * closest to the <b>second</b> segment point. */ @Test public void testGetDistanceToSegmentKm6() { // Segment made of two points Position sp1 = new Position(-10, 120); Position p = new Position(-10, 150); Position sp2 = sp1.getPositionAlongPath(p, 0.5); log.info(sp2 + ""); double r = p.getDistanceToSegmentKm(sp1, sp2); // 1641 according to http://www.nhc.noaa.gov/gccalc.shtml assertEquals(1641.00, r, ACCEPTABLE_DISTANCE_PRECISION); log.info(r + ""); } /** * The test position should return the closest distance to either a segment * point or segment intersection on the path. The path constitutes several * valid {@link Position}'s. In this test the point is closest to the * <b>first segment</b>. */ @Test public void testGetDistanceToPathKm1() { // positions to test Position p = new Position(-10, 115); // segment positions constituting a path Position sp1 = new Position(-30, 100); Position sp2 = new Position(-20, 120); Position sp3 = new Position(-30, 140); // path with two segments List<Position> path = new ArrayList<Position>(); path.add(sp1); path.add(sp2); path.add(sp3); // expect that the closes point will be sp2 itself since the test // position can't be perpendicular to the segment and sp2 is the closest // point. double r = p.getDistanceToPathKm(path); log.info(r + ""); Position intersection = p.getClosestIntersectionWithSegment(sp1, sp2); log.info("Position of intersection, used to manually calculate the distance via http://www.nhc.noaa.gov/gccalc.shtml : " + intersection); // 1234 according to http://www.nhc.noaa.gov/gccalc.shtml assertEquals(1234, r, ACCEPTABLE_DISTANCE_PRECISION); } /** * The test position should return the closest distance to either a segment * point or segment intersection on the path. The path constitutes several * valid {@link Position}'s. In this test the point is closest to the * <b>first segment start position</b> . */ @Test public void testGetDistanceToPathKm2() { // positions to test Position p = new Position(-10, 80); // segment positions constituting a path Position sp1 = new Position(-30, 100); Position sp2 = new Position(-20, 120); Position sp3 = new Position(-30, 140); // path with two segments List<Position> path = new ArrayList<Position>(); path.add(sp1); path.add(sp2); path.add(sp3); // expect that the closes point will be sp2 itself since the test // position can't be perpendicular to the segment and sp2 is the closest // point. double r = p.getDistanceToPathKm(path); log.info(r + ""); // 3039 accroding to http://www.nhc.noaa.gov/gccalc.shtml assertEquals(3039, r, ACCEPTABLE_DISTANCE_PRECISION); } /** * The test position should return the closest distance to either a segment * point or segment intersection on the path. The path constitutes several * valid {@link Position}'s. In this test the point is closest to the * <b>second segment</b>. */ @Test public void testGetDistanceToPathKm3() { // positions to test Position p = new Position(-10, 115); // segment positions constituting a path Position sp1 = new Position(-30, 100); Position sp2 = new Position(-20, 120); Position sp3 = new Position(-30, 140); // path with two segments List<Position> path = new ArrayList<Position>(); path.add(sp1); path.add(sp2); path.add(sp3); // expect that the closes point will be sp2 itself since the test // position can't be perpendicular to the segment and sp2 is the closest // point. double r = p.getDistanceToPathKm(path); log.info(r + ""); Position intersection = p.getClosestIntersectionWithSegment(sp1, sp2); log.info("Position of intersection, used to manually calculate the distance via http://www.nhc.noaa.gov/gccalc.shtml : " + intersection); // 1234 according to http://www.nhc.noaa.gov/gccalc.shtml assertEquals(1234, r, ACCEPTABLE_DISTANCE_PRECISION); } /** * The test position should return the closest distance to either a segment * point or segment intersection on the path. The path constitutes several * valid {@link Position}'s. In this test the point is closest to the * <b>second segment end position</b>. */ @Test public void testGetDistanceToPathKm4() { // positions to test Position p = new Position(-10, 150); // segment positions constituting a path Position sp1 = new Position(-30, 100); Position sp2 = new Position(-20, 120); Position sp3 = new Position(-30, 140); // path with two segments List<Position> path = new ArrayList<Position>(); path.add(sp1); path.add(sp2); path.add(sp3); // expect that the closes point will be sp2 itself since the test // position can't be perpendicular to the segment and sp2 is the closest // point. double r = p.getDistanceToPathKm(path); log.info(r + ""); // 2452 according http://www.nhc.noaa.gov/gccalc.shtml assertEquals(2452, r, ACCEPTABLE_DISTANCE_PRECISION); } /** * Test when a position is given an empty path. */ @Test(expected = RuntimeException.class) public void testGetDistanceToPathKm5() { // empty initialized list List<Position> path = new ArrayList<Position>(); // positions to test Position p = new Position(-10, 150); p.getDistanceToPathKm(path); } /** * Test when a position is given a null path. */ @Test(expected = NullPointerException.class) public void testGetDistanceToPathKm6() { // empty initialized list List<Position> path = null; // positions to test Position p = new Position(-10, 150); p.getDistanceToPathKm(path); } /** * Test when a position is given a path with only one position in it. */ @Test public void testGetDistanceToPathKm7() { // empty initialized list List<Position> path = new ArrayList<Position>(); path.add(new Position(-30, 100)); // positions to test Position p = new Position(-30, 120); double r = p.getDistanceToPathKm(path); // 1922 according to http://www.nhc.noaa.gov/gccalc.shtml assertEquals(1922, r, ACCEPTABLE_DISTANCE_PRECISION); } /** * Test when a position is outside a given region consisting of several * joining points. In this test the region is a roughly square region * consisting of four segments or eight {@link Position}s. The test position * is outside the region but within minimum distance in km. */ @Test public void testIsOutside1() { Position p = new Position(30, 19.99); assertFalse(p.isOutside(squareRegion, MIN_DISTANCE_KM)); } /** * Test when a position is outside a given region consisting of several * joining points. In this test the region is a roughly square region * consisting of four segments or eight {@link Position}s. The test position * is outside both the region and the minimum distance in km. */ @Test public void testIsOutside2() { Position p = new Position(-10, 110); assertTrue(p.isOutside(squareRegion, MIN_DISTANCE_KM)); } /** * Test when a position is outside a given region consisting of several * joining points. In this test the region is a roughly square region * consisting of four segments or eight {@link Position}s. The test position * is on the region path. */ @Test public void testIsOutside3() { Position p = new Position(20.07030897931526, 24.999999999999996); assertFalse(p.isOutside(squareRegion, MIN_DISTANCE_KM)); } /** * Test when a position is outside a given region consisting of several * joining points. In this test the region is a roughly square region * consisting of four segments or eight {@link Position}s. The test position * is within the region path. */ @Test public void testIsOutside4() { Position p = new Position(30, 30); assertFalse(p.isOutside(squareRegion, MIN_DISTANCE_KM)); } @Test public void testTo180() { assertEquals(0, to180(0), PRECISION); assertEquals(10, to180(10), PRECISION); assertEquals(-10, to180(-10), PRECISION); assertEquals(180, to180(180), PRECISION); assertEquals(-180, to180(-180), PRECISION); assertEquals(-170, to180(190), PRECISION); assertEquals(170, to180(-190), PRECISION); assertEquals(-170, to180(190 + 360), PRECISION); } @Test public void testLongitudeDiff() { assertEquals(10, longitudeDiff(15, 5), PRECISION); assertEquals(10, longitudeDiff(-175, 175), PRECISION); assertEquals(10, longitudeDiff(175, -175), PRECISION); assertEquals(5, longitudeDiff(149, 154), PRECISION); } @Test public void testGetLatitudeOnGreatCircleSameLatitudeHalfwayToSouthPole() { Position a = Position.create(-45, 20); Position b = Position.create(-45, 30); System.out.println(a.getBearingDegrees(b)); Double halfwayLat = a.getLatitudeOnGreatCircle(b, 25); assertEquals(-45, halfwayLat, 1.0); } @Test public void testGetLatitudeOnGreatCircleBothPointsOnEquator() { Position a = Position.create(0, 20); Position b = Position.create(0, 30); System.out.println(a.getBearingDegrees(b)); Double halfwayLat = a.getLatitudeOnGreatCircle(b, 25); assertEquals(0, halfwayLat, 0.1); } @Test public void testGetLatitudeOnGreatCircleFromLaxToJfk() { Position a = Position.create(33 + 57 / 60.0, -118 - 24 / 60.0); Position b = Position.create(40 + 38 / 60.0, -73 - 47 / 60.0); System.out.println(a.getBearingDegrees(b)); Double halfwayLat = a.getLatitudeOnGreatCircle(b, -111); assertEquals(36 + 24 / 60.0, halfwayLat, 0.1); } @Test public void testGetLatitudeOnGreatCircleForSmallSegment() { Position a = Position.create(-40, 100); Position b = Position.create(-40, 100.016); System.out.println(a.getBearingDegrees(b)); Double halfwayLat = a.getLatitudeOnGreatCircle(b, 100.008); assertEquals(-40, halfwayLat, 0.001); } @Test public void testGetLongitudeOnGreatCircleFromLaxToJfk() { Position a = Position.create(33 + 57 / 60.0, -118 - 24 / 60.0); Position b = Position.create(40 + 38 / 60.0, -73 - 47 / 60.0); System.out.println(a.getBearingDegrees(b)); LongitudePair candidates = a.getLongitudeOnGreatCircle(b, 36 + 23.65967428 / 60.0); System.out.println(candidates); assertEquals(-111, candidates.getLon1(), PRECISION); assertEquals(-48.391565812643, candidates.getLon2(), PRECISION); } }
3e1f473b3c0cb90616bd5c55a7bfe4f0087c37c9
359
java
Java
flexmark/src/main/java/com/vladsch/flexmark/html/CustomNodeRenderer.java
jvdvegt/flexmark-java
d4d18057f068fc522935c110a7dfc216ca4f52fc
[ "BSD-2-Clause" ]
null
null
null
flexmark/src/main/java/com/vladsch/flexmark/html/CustomNodeRenderer.java
jvdvegt/flexmark-java
d4d18057f068fc522935c110a7dfc216ca4f52fc
[ "BSD-2-Clause" ]
1
2019-03-01T11:10:33.000Z
2019-03-04T08:19:08.000Z
flexmark/src/main/java/com/vladsch/flexmark/html/CustomNodeRenderer.java
jvdvegt/flexmark-java
d4d18057f068fc522935c110a7dfc216ca4f52fc
[ "BSD-2-Clause" ]
null
null
null
35.9
84
0.824513
13,228
package com.vladsch.flexmark.html; import com.vladsch.flexmark.util.ast.Node; import com.vladsch.flexmark.util.ast.NodeAdaptingVisitor; import com.vladsch.flexmark.html.renderer.NodeRendererContext; public interface CustomNodeRenderer<N extends Node> extends NodeAdaptingVisitor<N> { void render(N node, NodeRendererContext context, HtmlWriter html); }
3e1f47f0691fd75b8abe61478aa37fb43ca3e37c
1,222
java
Java
src/main/java/core/command/MoveCommand.java
chickenalfredo/Agent-Bunny
f395cd7826a831db02951fa5349e6528ce70ef7b
[ "MIT" ]
1
2019-02-20T02:36:25.000Z
2019-02-20T02:36:25.000Z
src/main/java/core/command/MoveCommand.java
chickenalfredo/Animation-Game
f395cd7826a831db02951fa5349e6528ce70ef7b
[ "MIT" ]
34
2019-02-20T02:25:23.000Z
2019-02-26T06:51:39.000Z
src/main/java/core/command/MoveCommand.java
chickenalfredo/Agent-Bunny
f395cd7826a831db02951fa5349e6528ce70ef7b
[ "MIT" ]
1
2019-02-19T22:51:28.000Z
2019-02-19T22:51:28.000Z
29.804878
116
0.696399
13,229
package core.command; import core.entity.Entity; import core.game.World; import core.system.systems.MovementSystem; /** * This Command will execute a move command. Execution of this object will * send an update request the MovementSystem. */ public class MoveCommand implements Command { private String key; private boolean isKeyPressedEvent; /** * Constructs a Move Command with the key that was pressed and whether or not * the event was a key pressed event * * @param key * @param isKeyPressed */ public MoveCommand(String key, boolean isKeyPressedEvent) { this.key = key; this.isKeyPressedEvent = isKeyPressedEvent; } /** * Executes the Move Command by request an update to the Movement System * * @param actor * @param world */ @Override public void execute(Entity actor, World world) { world.getManager().getSystemManager().getSystem(MovementSystem.class).requestUpdate(actor); world.getManager().getSystemManager().getSystem(MovementSystem.class).setKey(key); world.getManager().getSystemManager().getSystem(MovementSystem.class).setKeyPressedEvent(isKeyPressedEvent); } }
3e1f48a9709fbfb9d662a4e99f81ed86fa174d06
235
java
Java
src/main/java/com/utils/releaseshelper/model/properties/GitMergeProperty.java
Simone3/SoftwareReleasesHelper
3fb69c9d2da1970e4245230e7b7b2adbb6fd64f2
[ "MIT" ]
null
null
null
src/main/java/com/utils/releaseshelper/model/properties/GitMergeProperty.java
Simone3/SoftwareReleasesHelper
3fb69c9d2da1970e4245230e7b7b2adbb6fd64f2
[ "MIT" ]
null
null
null
src/main/java/com/utils/releaseshelper/model/properties/GitMergeProperty.java
Simone3/SoftwareReleasesHelper
3fb69c9d2da1970e4245230e7b7b2adbb6fd64f2
[ "MIT" ]
null
null
null
15.666667
50
0.765957
13,230
package com.utils.releaseshelper.model.properties; import lombok.Data; /** * A property for a Git merge */ @Data public class GitMergeProperty { private Boolean pull; private String sourceBranch; private String targetBranch; }
3e1f491ab9196af05ab504f828e5d367f00247cb
17,977
java
Java
cli/src/test/org/apache/hadoop/hive/cli/TestCliDriverMethods.java
swalker-lixl/project-panthera-ase
b7f2b5b7237f2232bc2c0d505d47d4ea72eb17b7
[ "Apache-2.0" ]
14
2020-06-20T14:08:02.000Z
2022-01-22T14:26:00.000Z
cli/src/test/org/apache/hadoop/hive/cli/TestCliDriverMethods.java
shuhuai007/hive
12e3872aae80db5b824892700650f40e7daf675b
[ "Apache-2.0" ]
2
2021-04-27T01:40:24.000Z
2021-06-04T02:42:18.000Z
cli/src/test/org/apache/hadoop/hive/cli/TestCliDriverMethods.java
shuhuai007/hive
12e3872aae80db5b824892700650f40e7daf675b
[ "Apache-2.0" ]
13
2020-06-20T14:58:34.000Z
2021-11-09T13:25:32.000Z
32.332734
112
0.68571
13,231
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.cli; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.Field; import java.security.Permission; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import jline.ArgumentCompletor; import jline.Completor; import jline.ConsoleReader; import junit.framework.TestCase; import org.apache.commons.io.FileUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.conf.HiveConf.ConfVars; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.metastore.api.Schema; import org.apache.hadoop.hive.ql.CommandNeedRetryException; import org.apache.hadoop.hive.ql.Driver; import org.apache.hadoop.hive.ql.processors.CommandProcessorResponse; import org.apache.hadoop.hive.service.HiveClient; import org.apache.hadoop.hive.service.HiveServerException; import org.apache.thrift.TException; // Cannot call class TestCliDriver since that's the name of the generated // code for the script-based testing public class TestCliDriverMethods extends TestCase { // If the command has an associated schema, make sure it gets printed to use public void testThatCliDriverPrintsHeaderForCommandsWithSchema() throws CommandNeedRetryException { Schema mockSchema = mock(Schema.class); List<FieldSchema> fieldSchemas = new ArrayList<FieldSchema>(); String fieldName = "FlightOfTheConchords"; fieldSchemas.add(new FieldSchema(fieldName, "type", "comment")); when(mockSchema.getFieldSchemas()).thenReturn(fieldSchemas); PrintStream mockOut = headerPrintingTestDriver(mockSchema); // Should have printed out the header for the field schema verify(mockOut, times(1)).print(fieldName); } // If the command has no schema, make sure nothing is printed public void testThatCliDriverPrintsNoHeaderForCommandsWithNoSchema() throws CommandNeedRetryException { Schema mockSchema = mock(Schema.class); when(mockSchema.getFieldSchemas()).thenReturn(null); PrintStream mockOut = headerPrintingTestDriver(mockSchema); // Should not have tried to print any thing. verify(mockOut, never()).print(anyString()); } /** * Do the actual testing against a mocked CliDriver based on what type of schema * * @param mockSchema * Schema to throw against test * @return Output that would have been sent to the user * @throws CommandNeedRetryException * won't actually be thrown */ private PrintStream headerPrintingTestDriver(Schema mockSchema) throws CommandNeedRetryException { CliDriver cliDriver = new CliDriver(); // We want the driver to try to print the header... Configuration conf = mock(Configuration.class); when(conf.getBoolean(eq(ConfVars.HIVE_CLI_PRINT_HEADER.varname), anyBoolean())) .thenReturn(true); cliDriver.setConf(conf); Driver proc = mock(Driver.class); CommandProcessorResponse cpr = mock(CommandProcessorResponse.class); when(cpr.getResponseCode()).thenReturn(0); when(proc.run(anyString())).thenReturn(cpr); // and then see what happens based on the provided schema when(proc.getSchema()).thenReturn(mockSchema); CliSessionState mockSS = mock(CliSessionState.class); PrintStream mockOut = mock(PrintStream.class); mockSS.out = mockOut; cliDriver.processLocalCmd("use default;", proc, mockSS); return mockOut; } public void testGetCommandCompletor() { Completor[] completors = CliDriver.getCommandCompletor(); assertEquals(2, completors.length); assertTrue(completors[0] instanceof ArgumentCompletor); assertTrue(completors[1] instanceof Completor); //comletor add space after last delimeter List<String>testList=new ArrayList<String>(Arrays.asList(new String[]{")"})); completors[1].complete("fdsdfsdf", 0, testList); assertEquals(") ", testList.get(0)); testList=new ArrayList<String>(); completors[1].complete("len", 0, testList); assertTrue(testList.get(0).endsWith("length(")); testList=new ArrayList<String>(); completors[0].complete("set f", 0, testList); assertEquals("set", testList.get(0)); } public void testRun() throws Exception { // clean history String historyDirectory = System.getProperty("user.home"); if ((new File(historyDirectory)).exists()) { File historyFile = new File(historyDirectory + File.separator + ".hivehistory"); historyFile.delete(); } HiveConf configuration = new HiveConf(); CliSessionState ss = new CliSessionState(configuration); CliSessionState.start(ss); String[] args = {}; PrintStream oldOut = System.out; ByteArrayOutputStream dataOut = new ByteArrayOutputStream(); System.setOut(new PrintStream(dataOut)); PrintStream oldErr = System.err; ByteArrayOutputStream dataErr = new ByteArrayOutputStream(); System.setErr(new PrintStream(dataErr)); try { new FakeCliDriver().run(args); assertTrue(dataOut.toString().contains("test message")); assertTrue(dataErr.toString().contains("Hive history file=")); assertTrue(dataErr.toString().contains("File: fakeFile is not a file.")); dataOut.reset(); dataErr.reset(); } finally { System.setOut(oldOut); System.setErr(oldErr); } } /** * Test commands exit and quit */ public void testQuit() throws Exception { CliSessionState ss = new CliSessionState(new HiveConf()); ss.err = System.err; ss.out = System.out; NoExitSecurityManager newSecurityManager = new NoExitSecurityManager(); try { CliSessionState.start(ss); CliDriver cliDriver = new CliDriver(); cliDriver.processCmd("quit"); fail("should be exit"); } catch (ExitException e) { assertEquals(0, e.getStatus()); } catch (Exception e) { newSecurityManager.resetSecurityManager(); throw e; } try { CliSessionState.start(ss); CliDriver cliDriver = new CliDriver(); cliDriver.processCmd("exit"); fail("should be exit"); } catch (ExitException e) { assertEquals(0, e.getStatus()); } finally { newSecurityManager.resetSecurityManager(); } } /** * test remote execCommand */ public void testRemoteCall() throws Exception { MyCliSessionState ss = new MyCliSessionState(new HiveConf(), org.apache.hadoop.hive.cli.TestCliDriverMethods.MyCliSessionState.ClientResult.RETURN_OK); ss.err = System.err; ByteArrayOutputStream data = new ByteArrayOutputStream(); ss.out = new PrintStream(data); MyCliSessionState.start(ss); CliDriver cliDriver = new CliDriver(); cliDriver.processCmd("remote command"); assertTrue(data.toString().contains("test result")); } /** * test remote Exception */ public void testServerException() throws Exception { MyCliSessionState ss = new MyCliSessionState( new HiveConf(), org.apache.hadoop.hive.cli.TestCliDriverMethods.MyCliSessionState.ClientResult.RETURN_SERVER_EXCEPTION); ByteArrayOutputStream data = new ByteArrayOutputStream(); ss.err = new PrintStream(data); ss.out = System.out; MyCliSessionState.start(ss); CliDriver cliDriver = new CliDriver(); cliDriver.processCmd("remote command"); assertTrue(data.toString().contains("[Hive Error]: test HiveServerException")); data.reset(); } /** * test remote Exception */ public void testServerTException() throws Exception { MyCliSessionState ss = new MyCliSessionState( new HiveConf(), org.apache.hadoop.hive.cli.TestCliDriverMethods.MyCliSessionState.ClientResult.RETURN_T_EXCEPTION); ByteArrayOutputStream data = new ByteArrayOutputStream(); ss.err = new PrintStream(data); ss.out = System.out; MyCliSessionState.start(ss); CliDriver cliDriver = new CliDriver(); cliDriver.processCmd("remote command"); assertTrue(data.toString().contains("[Thrift Error]: test TException")); assertTrue(data.toString().contains( "[Thrift Error]: Hive server is not cleaned due to thrift exception: test TException")); } /** * test remote Exception */ public void testProcessSelectDatabase() throws Exception { CliSessionState sessinState = new CliSessionState(new HiveConf()); CliSessionState.start(sessinState); ByteArrayOutputStream data = new ByteArrayOutputStream(); sessinState.err = new PrintStream(data); sessinState.database = "database"; CliDriver driver = new CliDriver(); NoExitSecurityManager securityManager = new NoExitSecurityManager(); try { driver.processSelectDatabase(sessinState); fail("shuld be exit"); } catch (ExitException e) { e.printStackTrace(); assertEquals(40000, e.getStatus()); } finally { securityManager.resetSecurityManager(); } assertTrue(data.toString().contains( "FAILED: ParseException line 1:4 cannot recognize input near 'database'")); } public void testprocessInitFiles() throws Exception { String oldHiveHome = System.getenv("HIVE_HOME"); String oldHiveConfDir = System.getenv("HIVE_CONF_DIR"); File homeFile = File.createTempFile("test", "hive"); String tmpDir = homeFile.getParentFile().getAbsoluteFile() + File.separator + "TestCliDriverMethods"; homeFile.delete(); FileUtils.deleteDirectory(new File(tmpDir)); homeFile = new File(tmpDir + File.separator + "bin" + File.separator + CliDriver.HIVERCFILE); homeFile.getParentFile().mkdirs(); homeFile.createNewFile(); FileUtils.write(homeFile, "-- init hive file for test "); setEnv("HIVE_HOME", homeFile.getParentFile().getParentFile().getAbsolutePath()); setEnv("HIVE_CONF_DIR", homeFile.getParentFile().getAbsolutePath()); CliSessionState sessionState = new CliSessionState(new HiveConf()); ByteArrayOutputStream data = new ByteArrayOutputStream(); NoExitSecurityManager securityManager = new NoExitSecurityManager(); sessionState.err = new PrintStream(data); sessionState.out = System.out; try { CliSessionState.start(sessionState); CliDriver cliDriver = new CliDriver(); cliDriver.processInitFiles(sessionState); assertTrue(data.toString().contains( "Putting the global hiverc in $HIVE_HOME/bin/.hiverc is deprecated. " + "Please use $HIVE_CONF_DIR/.hiverc instead.")); FileUtils.write(homeFile, "bla bla bla"); // if init file contains incorrect row try { cliDriver.processInitFiles(sessionState); fail("should be exit"); } catch (ExitException e) { assertEquals(40000, e.getStatus()); } setEnv("HIVE_HOME", null); try { cliDriver.processInitFiles(sessionState); fail("should be exit"); } catch (ExitException e) { assertEquals(40000, e.getStatus()); } } finally { // restore data setEnv("HIVE_HOME", oldHiveHome); setEnv("HIVE_CONF_DIR", oldHiveConfDir); FileUtils.deleteDirectory(new File(tmpDir)); } File f = File.createTempFile("hive", "test"); FileUtils.write(f, "bla bla bla"); try { sessionState.initFiles = Arrays.asList(new String[] {f.getAbsolutePath()}); CliDriver cliDriver = new CliDriver(); cliDriver.processInitFiles(sessionState); fail("should be exit"); } catch (ExitException e) { assertEquals(40000, e.getStatus()); assertTrue(data.toString().contains("cannot recognize input near 'bla' 'bla' 'bla'")); } finally { securityManager.resetSecurityManager(); } } private static void setEnv(String key, String value) throws Exception { Class[] classes = Collections.class.getDeclaredClasses(); Map<String, String> env = (Map<String, String>) System.getenv(); for (Class cl : classes) { if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) { Field field = cl.getDeclaredField("m"); field.setAccessible(true); Object obj = field.get(env); Map<String, String> map = (Map<String, String>) obj; if (value == null) { map.remove(key); } else { map.put(key, value); } } } } private static class FakeCliDriver extends CliDriver { @Override protected ConsoleReader getConsoleReader() throws IOException { ConsoleReader reslt = new FakeConsoleReader(); return reslt; } } private static class FakeConsoleReader extends ConsoleReader { private int counter = 0; File temp = null; public FakeConsoleReader() throws IOException { super(); } @Override public String readLine(String prompt) throws IOException { FileWriter writer; switch (counter++) { case 0: return "!echo test message;"; case 1: temp = File.createTempFile("hive", "test"); temp.deleteOnExit(); return "source " + temp.getAbsolutePath() + ";"; case 2: temp = File.createTempFile("hive", "test"); temp.deleteOnExit(); writer = new FileWriter(temp); writer.write("bla bla bla"); writer.close(); return "list file file://" + temp.getAbsolutePath() + ";"; case 3: return "!echo "; case 4: return "test message;"; case 5: return "source fakeFile;"; case 6: temp = File.createTempFile("hive", "test"); temp.deleteOnExit(); writer = new FileWriter(temp); writer.write("source fakeFile;"); writer.close(); return "list file file://" + temp.getAbsolutePath() + ";"; // drop table over10k; default: return null; } } } private static class NoExitSecurityManager extends SecurityManager { public SecurityManager parentSecurityManager; public NoExitSecurityManager() { super(); parentSecurityManager = System.getSecurityManager(); System.setSecurityManager(this); } @Override public void checkPermission(Permission perm, Object context) { if (parentSecurityManager != null) { parentSecurityManager.checkPermission(perm, context); } } @Override public void checkPermission(Permission perm) { if (parentSecurityManager != null) { parentSecurityManager.checkPermission(perm); } } @Override public void checkExit(int status) { throw new ExitException(status); } public void resetSecurityManager() { System.setSecurityManager(parentSecurityManager); } } private static class ExitException extends RuntimeException { int status; public ExitException(int status) { this.status = status; } public int getStatus() { return status; } } private static class MyCliSessionState extends CliSessionState { public enum ClientResult { RETURN_OK, RETURN_SERVER_EXCEPTION, RETURN_T_EXCEPTION }; private final ClientResult result; public MyCliSessionState(HiveConf conf, ClientResult result) { super(conf); this.result = result; } @Override public boolean isRemoteMode() { return true; } @Override public HiveClient getClient() { HiveClient result = mock(HiveClient.class); if (ClientResult.RETURN_OK.equals(this.result)) { List<String> fetchResult = new ArrayList<String>(1); fetchResult.add("test result"); try { when(result.fetchN(anyInt())).thenReturn(fetchResult); } catch (HiveServerException e) { } catch (Exception e) { } } else if (ClientResult.RETURN_SERVER_EXCEPTION.equals(this.result)) { HiveServerException exception = new HiveServerException("test HiveServerException", 10, "sql state"); try { when(result.fetchN(anyInt())).thenThrow(exception); when(result.fetchN(anyInt())).thenThrow(exception); } catch (TException e) { ; } return result; } else if (ClientResult.RETURN_T_EXCEPTION.equals(this.result)) { TException exception = new TException("test TException"); try { // org.mockito.Mockito. doThrow(exception).when(result).clean(); when(result.fetchN(anyInt())).thenThrow(exception); } catch (TException e) { e.printStackTrace(); } return result; } return result; } } }
3e1f49576b1f957ec870cbea8536365fdd586158
572
java
Java
src/test/java/com/ilamstone/publicfortests/testmodel/SelfCallClass1.java
ilamstone/publicfortests
69062c177f5c509377ce30b5a277f0525df02daf
[ "MIT" ]
null
null
null
src/test/java/com/ilamstone/publicfortests/testmodel/SelfCallClass1.java
ilamstone/publicfortests
69062c177f5c509377ce30b5a277f0525df02daf
[ "MIT" ]
null
null
null
src/test/java/com/ilamstone/publicfortests/testmodel/SelfCallClass1.java
ilamstone/publicfortests
69062c177f5c509377ce30b5a277f0525df02daf
[ "MIT" ]
null
null
null
26
73
0.767483
13,232
package com.ilamstone.publicfortests.testmodel; import com.ilamstone.publicfortests.PublicForTests; public class SelfCallClass1 { public static final String PUBLIC_EXPECTATION = "Hello from Public"; public static final String PRIVATE_EXPECTATION = "Hello from Private"; @PublicForTests("com.ilamstone.publicfortests.testmodel.Class1Testing") private String somePrivateMethod() { return PRIVATE_EXPECTATION; } private String selfCalled() { return PUBLIC_EXPECTATION; } public String somePublicMethod() { return this.selfCalled(); } }
3e1f496a3906cd989f61bd5c0cfdb1c03535b55c
9,257
java
Java
server/src/main/java/org/elasticsearch/indices/recovery/RecoverySettings.java
engrmostafijur/crate
fe8bd52d6bc4e7a989f775f9cd0f89fe43c6b38a
[ "Apache-2.0" ]
1
2020-05-15T16:06:55.000Z
2020-05-15T16:06:55.000Z
server/src/main/java/org/elasticsearch/indices/recovery/RecoverySettings.java
engrmostafijur/crate
fe8bd52d6bc4e7a989f775f9cd0f89fe43c6b38a
[ "Apache-2.0" ]
null
null
null
server/src/main/java/org/elasticsearch/indices/recovery/RecoverySettings.java
engrmostafijur/crate
fe8bd52d6bc4e7a989f775f9cd0f89fe43c6b38a
[ "Apache-2.0" ]
null
null
null
44.719807
141
0.756509
13,233
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.indices.recovery; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.lucene.store.RateLimiter; import org.apache.lucene.store.RateLimiter.SimpleRateLimiter; import org.elasticsearch.common.settings.ClusterSettings; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Setting.Property; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import io.crate.common.unit.TimeValue; public class RecoverySettings { private static final Logger LOGGER = LogManager.getLogger(RecoverySettings.class); public static final Setting<ByteSizeValue> INDICES_RECOVERY_MAX_BYTES_PER_SEC_SETTING = Setting.byteSizeSetting("indices.recovery.max_bytes_per_sec", new ByteSizeValue(40, ByteSizeUnit.MB), Property.Dynamic, Property.NodeScope); /** * Controls the maximum number of file chunk requests that can be sent concurrently from the source node to the target node. */ public static final Setting<Integer> INDICES_RECOVERY_MAX_CONCURRENT_FILE_CHUNKS_SETTING = Setting.intSetting("indices.recovery.max_concurrent_file_chunks", 2, 1, 5, Property.Dynamic, Property.NodeScope); /** * how long to wait before retrying after issues cause by cluster state syncing between nodes * i.e., local node is not yet known on remote node, remote shard not yet started etc. */ public static final Setting<TimeValue> INDICES_RECOVERY_RETRY_DELAY_STATE_SYNC_SETTING = Setting.positiveTimeSetting("indices.recovery.retry_delay_state_sync", TimeValue.timeValueMillis(500), Property.Dynamic, Property.NodeScope); /** how long to wait before retrying after network related issues */ public static final Setting<TimeValue> INDICES_RECOVERY_RETRY_DELAY_NETWORK_SETTING = Setting.positiveTimeSetting("indices.recovery.retry_delay_network", TimeValue.timeValueSeconds(5), Property.Dynamic, Property.NodeScope); /** timeout value to use for requests made as part of the recovery process */ public static final Setting<TimeValue> INDICES_RECOVERY_INTERNAL_ACTION_TIMEOUT_SETTING = Setting.positiveTimeSetting("indices.recovery.internal_action_timeout", TimeValue.timeValueMinutes(15), Property.Dynamic, Property.NodeScope); /** * timeout value to use for requests made as part of the recovery process that are expected to take long time. * defaults to twice `indices.recovery.internal_action_timeout`. */ public static final Setting<TimeValue> INDICES_RECOVERY_INTERNAL_LONG_ACTION_TIMEOUT_SETTING = Setting.timeSetting( "indices.recovery.internal_action_long_timeout", (s) -> TimeValue.timeValueMillis(INDICES_RECOVERY_INTERNAL_ACTION_TIMEOUT_SETTING.get(s).millis() * 2), TimeValue.timeValueSeconds(0), Property.Dynamic, Property.NodeScope ); /** * recoveries that don't show any activity for more then this interval will be failed. * defaults to `indices.recovery.internal_action_long_timeout` */ public static final Setting<TimeValue> INDICES_RECOVERY_ACTIVITY_TIMEOUT_SETTING = Setting.timeSetting("indices.recovery.recovery_activity_timeout", INDICES_RECOVERY_INTERNAL_LONG_ACTION_TIMEOUT_SETTING::get, TimeValue.timeValueSeconds(0), Property.Dynamic, Property.NodeScope); public static final ByteSizeValue DEFAULT_CHUNK_SIZE = new ByteSizeValue(512, ByteSizeUnit.KB); private volatile ByteSizeValue maxBytesPerSec; private volatile int maxConcurrentFileChunks; private volatile SimpleRateLimiter rateLimiter; private volatile TimeValue retryDelayStateSync; private volatile TimeValue retryDelayNetwork; private volatile TimeValue activityTimeout; private volatile TimeValue internalActionTimeout; private volatile TimeValue internalActionLongTimeout; private volatile ByteSizeValue chunkSize = DEFAULT_CHUNK_SIZE; public RecoverySettings(Settings settings, ClusterSettings clusterSettings) { this.retryDelayStateSync = INDICES_RECOVERY_RETRY_DELAY_STATE_SYNC_SETTING.get(settings); // doesn't have to be fast as nodes are reconnected every 10s by default (see InternalClusterService.ReconnectToNodes) // and we want to give the master time to remove a faulty node this.maxConcurrentFileChunks = INDICES_RECOVERY_MAX_CONCURRENT_FILE_CHUNKS_SETTING.get(settings); this.retryDelayNetwork = INDICES_RECOVERY_RETRY_DELAY_NETWORK_SETTING.get(settings); this.internalActionTimeout = INDICES_RECOVERY_INTERNAL_ACTION_TIMEOUT_SETTING.get(settings); this.internalActionLongTimeout = INDICES_RECOVERY_INTERNAL_LONG_ACTION_TIMEOUT_SETTING.get(settings); this.activityTimeout = INDICES_RECOVERY_ACTIVITY_TIMEOUT_SETTING.get(settings); this.maxBytesPerSec = INDICES_RECOVERY_MAX_BYTES_PER_SEC_SETTING.get(settings); if (maxBytesPerSec.getBytes() <= 0) { rateLimiter = null; } else { rateLimiter = new SimpleRateLimiter(maxBytesPerSec.getMbFrac()); } LOGGER.debug("using max_bytes_per_sec[{}]", maxBytesPerSec); clusterSettings.addSettingsUpdateConsumer(INDICES_RECOVERY_MAX_BYTES_PER_SEC_SETTING, this::setMaxBytesPerSec); clusterSettings.addSettingsUpdateConsumer(INDICES_RECOVERY_MAX_CONCURRENT_FILE_CHUNKS_SETTING, this::setMaxConcurrentFileChunks); clusterSettings.addSettingsUpdateConsumer(INDICES_RECOVERY_RETRY_DELAY_STATE_SYNC_SETTING, this::setRetryDelayStateSync); clusterSettings.addSettingsUpdateConsumer(INDICES_RECOVERY_RETRY_DELAY_NETWORK_SETTING, this::setRetryDelayNetwork); clusterSettings.addSettingsUpdateConsumer(INDICES_RECOVERY_INTERNAL_ACTION_TIMEOUT_SETTING, this::setInternalActionTimeout); clusterSettings.addSettingsUpdateConsumer(INDICES_RECOVERY_INTERNAL_LONG_ACTION_TIMEOUT_SETTING, this::setInternalActionLongTimeout); clusterSettings.addSettingsUpdateConsumer(INDICES_RECOVERY_ACTIVITY_TIMEOUT_SETTING, this::setActivityTimeout); } public RateLimiter rateLimiter() { return rateLimiter; } public TimeValue retryDelayNetwork() { return retryDelayNetwork; } public TimeValue retryDelayStateSync() { return retryDelayStateSync; } public TimeValue activityTimeout() { return activityTimeout; } public TimeValue internalActionTimeout() { return internalActionTimeout; } public TimeValue internalActionLongTimeout() { return internalActionLongTimeout; } public ByteSizeValue getChunkSize() { return chunkSize; } public void setChunkSize(ByteSizeValue chunkSize) { // only settable for tests if (chunkSize.bytesAsInt() <= 0) { throw new IllegalArgumentException("chunkSize must be > 0"); } this.chunkSize = chunkSize; } public void setRetryDelayStateSync(TimeValue retryDelayStateSync) { this.retryDelayStateSync = retryDelayStateSync; } public void setRetryDelayNetwork(TimeValue retryDelayNetwork) { this.retryDelayNetwork = retryDelayNetwork; } public void setActivityTimeout(TimeValue activityTimeout) { this.activityTimeout = activityTimeout; } public void setInternalActionTimeout(TimeValue internalActionTimeout) { this.internalActionTimeout = internalActionTimeout; } public void setInternalActionLongTimeout(TimeValue internalActionLongTimeout) { this.internalActionLongTimeout = internalActionLongTimeout; } private void setMaxBytesPerSec(ByteSizeValue maxBytesPerSec) { this.maxBytesPerSec = maxBytesPerSec; if (maxBytesPerSec.getBytes() <= 0) { rateLimiter = null; } else if (rateLimiter != null) { rateLimiter.setMBPerSec(maxBytesPerSec.getMbFrac()); } else { rateLimiter = new SimpleRateLimiter(maxBytesPerSec.getMbFrac()); } } public int getMaxConcurrentFileChunks() { return maxConcurrentFileChunks; } private void setMaxConcurrentFileChunks(int maxConcurrentFileChunks) { this.maxConcurrentFileChunks = maxConcurrentFileChunks; } }
3e1f4a6bac26f48e2cca949c89c0e82995bc3afd
4,986
java
Java
common/common-core/src/main/java/com/zte/mao/common/filter/SessionFilter.java
zc806zc/zStudio
7c03ced7b51747d6a4e4fd82797f76546192c7a8
[ "MIT" ]
2
2021-01-03T16:49:33.000Z
2022-02-19T07:33:28.000Z
common/common-core/src/main/java/com/zte/mao/common/filter/SessionFilter.java
zc806zc/zStudio
7c03ced7b51747d6a4e4fd82797f76546192c7a8
[ "MIT" ]
null
null
null
common/common-core/src/main/java/com/zte/mao/common/filter/SessionFilter.java
zc806zc/zStudio
7c03ced7b51747d6a4e4fd82797f76546192c7a8
[ "MIT" ]
2
2018-02-06T04:18:40.000Z
2020-12-02T12:43:43.000Z
38.353846
173
0.62856
13,234
package com.zte.mao.common.filter; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import com.zte.mao.common.config.ConfigManage; import com.zte.mao.common.entity.CommonConst; import com.zte.mao.common.entity.UserSimpleEntity; import com.zte.mao.common.exception.MaoCommonException; import com.zte.mao.common.util.MaoCommonUtil; public class SessionFilter extends AbstractFilter { private static Logger logger = Logger.getLogger(SessionFilter.class.getName()); private String[] excludedPageArray = new String[0]; private String[] ignoreTypesArray = new String[0]; @Override public void init(FilterConfig filterConfig) throws ServletException { String excludedPages = filterConfig.getInitParameter("excludedPages"); if (StringUtils.isNotBlank(excludedPages)) { excludedPageArray = excludedPages.toLowerCase().split(","); } String ignoreTypes = filterConfig.getInitParameter("ignoreTypes"); if (StringUtils.isNotBlank(ignoreTypes)) { ignoreTypesArray = ignoreTypes.toLowerCase().split(","); } } @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; String servletPath = httpRequest.getServletPath().toLowerCase(); if (servletPath.startsWith("/")) { servletPath = servletPath.substring(1); } if (isExcludeRequest(servletPath)) { chain.doFilter(request, response); } else { boolean isLogin = true; setSpringObj(request); boolean isAuth = true; try { String requestURI = httpRequest.getRequestURI(); UserSimpleEntity user = sessionManager.checkSignin((HttpServletRequest) request); // 当重新开启tab页时会导致获取的session内容中没有保存租户信息的情况,这里统一从sessionManager中获取session String loginName = user.getLoginName(); Long tenantId = user.getTenantId(); if (!"admin".equals(loginName.split("@")[0])) { isAuth = seessionAuthAccessManager.isAuthOperatorRes(loginName, tenantId, requestURI); } } catch (Exception e) { logger.error(e.getMessage()); isLogin = false; } if (isLogin && isAuth) { chain.doFilter(request, response); } else { redirectPage(httpRequest, response, isLogin, isAuth); } } } /** * 不需要鉴权请求的判断 * @param servletPath * @return */ private boolean isExcludeRequest(String servletPath) { if (servletPath.startsWith("mao/uap/") || servletPath.startsWith("mao/sso/") || servletPath.startsWith("orm/") || servletPath.startsWith("mao/common/login/check") || servletPath.startsWith("upload/design/application/zip") || servletPath.startsWith("import/design/application/package")) { return true; } if (ArrayUtils.indexOf(excludedPageArray, servletPath) > -1) { return true; } for (String type : ignoreTypesArray) { if (servletPath.endsWith("." + type)) { return true; } } return false; } private void redirectPage(HttpServletRequest httpRequest, ServletResponse response, boolean isLogin, boolean isAuth) throws IOException { String userNginxUrl = httpRequestUtils.getLocalPath(); String loginPageName = "/user-page.html?page=log"; if (!isLogin) { if(CommonConst.PLATFORM_TYPE_MOCK.equals(ConfigManage.getInstance().getPlatformType())){ try { ((HttpServletResponse) response).sendRedirect("http://" + MaoCommonUtil.getLocalIP() + ":" + CommonConst.DESIGNER_ADDRESS_PORT + "/workbench/user-page.html?page=log"); } catch (MaoCommonException e) { logger.error(e.getMessage()); } }else{ ((HttpServletResponse) response).sendRedirect(userNginxUrl + httpRequest.getContextPath() + loginPageName); } } if (!isAuth) { // 转向到无权限页面 ((HttpServletResponse) response).sendRedirect(userNginxUrl + httpRequest.getContextPath() + "/dispermission.html"); } } }
3e1f4acf3ff553d5000367fe4fe96f7a0634780a
3,823
java
Java
java/src/main/java/com/cloudera/api/ApiRootResource.java
zcjtom/cm_api
985b28a28d90bff8f5c97681dc7f6de7483ac07f
[ "Apache-2.0" ]
329
2015-01-06T15:41:14.000Z
2022-03-12T15:28:20.000Z
java/src/main/java/com/cloudera/api/ApiRootResource.java
zcjtom/cm_api
985b28a28d90bff8f5c97681dc7f6de7483ac07f
[ "Apache-2.0" ]
58
2015-02-10T11:43:42.000Z
2021-01-20T23:05:55.000Z
java/src/main/java/com/cloudera/api/ApiRootResource.java
zcjtom/cm_api
985b28a28d90bff8f5c97681dc7f6de7483ac07f
[ "Apache-2.0" ]
257
2015-01-15T10:57:20.000Z
2022-03-09T12:13:57.000Z
23.169697
75
0.682971
13,235
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, 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 com.cloudera.api; import com.cloudera.api.v1.RootResourceV1; import com.cloudera.api.v10.RootResourceV10; import com.cloudera.api.v11.RootResourceV11; import com.cloudera.api.v12.RootResourceV12; import com.cloudera.api.v13.RootResourceV13; import com.cloudera.api.v14.RootResourceV14; import com.cloudera.api.v15.RootResourceV15; import com.cloudera.api.v16.RootResourceV16; import com.cloudera.api.v2.RootResourceV2; import com.cloudera.api.v3.RootResourceV3; import com.cloudera.api.v4.RootResourceV4; import com.cloudera.api.v5.RootResourceV5; import com.cloudera.api.v6.RootResourceV6; import com.cloudera.api.v7.RootResourceV7; import com.cloudera.api.v8.RootResourceV8; import com.cloudera.api.v9.RootResourceV9; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; /** * Root resource for the API. Provides access to the version-specific * resources. */ @Path("/") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public interface ApiRootResource { /** * @return The v1 root resource. */ @Path("/v1") RootResourceV1 getRootV1(); /** * @return The v2 root resource. */ @Path("/v2") RootResourceV2 getRootV2(); /** * @return The v3 root resource. */ @Path("/v3") RootResourceV3 getRootV3(); /** * @return The v4 root resource. */ @Path("/v4") RootResourceV4 getRootV4(); /** * @return The v5 root resource. */ @Path("/v5") RootResourceV5 getRootV5(); /** * @return The v6 root resource. */ @Path("/v6") RootResourceV6 getRootV6(); /** * @return The v7 root resource. */ @Path("/v7") RootResourceV7 getRootV7(); /** * @return The v8 root resource. */ @Path("/v8") RootResourceV8 getRootV8(); /** * @return The v9 root resource. */ @Path("/v9") RootResourceV9 getRootV9(); /** * @return The v10 root resource. */ @Path("/v10") RootResourceV10 getRootV10(); /** * @return The v11 root resource. */ @Path("/v11") RootResourceV11 getRootV11(); /** * @return The v12 root resource. */ @Path("/v12") RootResourceV12 getRootV12(); /** * @return The v13 root resource. */ @Path("/v13") RootResourceV13 getRootV13(); /** * @return The v14 root resource. */ @Path("/v14") RootResourceV14 getRootV14(); /** * @return The v15 root resource. */ @Path("/v15") RootResourceV15 getRootV15(); /** * @return The v15 root resource. */ @Path("/v16") RootResourceV16 getRootV16(); /** * Important: Update {@link ApiRootResourceExternal} interface as well * on adding new CM API version. */ /** * Fetch the current API version supported by the server. * <p> * Available since API v2. * * @return The current API version (e.g., "v2"). */ @GET @Path("/version") @Consumes() @Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN }) String getCurrentVersion(); }
3e1f4afef69da4a08fc0162c1942f2c40d5b0511
856
java
Java
minecraft/info/spicyclient/modules/memes/LSD.java
kjonaas/SpicyClient
e6b78a891db05b9fd3fbeeb644173ce1dba416be
[ "MIT" ]
207
2020-10-12T20:10:45.000Z
2021-11-12T11:27:58.000Z
minecraft/info/spicyclient/modules/memes/LSD.java
SkypetheDeveloper/SpicyClient
746fbc9509a2942e284cc8ea00ccf2777bc707b2
[ "MIT" ]
18
2020-09-22T05:58:40.000Z
2021-04-18T02:10:57.000Z
minecraft/info/spicyclient/modules/memes/LSD.java
SkypetheDeveloper/SpicyClient
746fbc9509a2942e284cc8ea00ccf2777bc707b2
[ "MIT" ]
30
2020-10-28T17:06:40.000Z
2022-03-17T00:27:49.000Z
25.176471
124
0.73014
13,236
package info.spicyclient.modules.memes; import java.awt.Color; import org.lwjgl.input.Keyboard; import info.spicyclient.events.Event; import info.spicyclient.events.listeners.EventRenderGUI; import info.spicyclient.events.listeners.EventUpdate; import info.spicyclient.modules.Module; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.ScaledResolution; public class LSD extends Module { public LSD() { super("LSD", Keyboard.KEY_NONE, Category.MEMES); } @Override public void onEvent(Event e) { if (e instanceof EventRenderGUI && e.isPre()) { float hue = System.currentTimeMillis() % (int)(4 * 1000) / (float)(4 * 1000); int primColor = Color.HSBtoRGB(hue, 1, 1); Gui.drawRect(0, 0, new ScaledResolution(mc).getScaledWidth(), new ScaledResolution(mc).getScaledHeight(), 0x6600ff00); } } }
3e1f4c853c5bb0cc85f365f76ae84ae43b5e3e77
1,264
java
Java
ksqldb-engine/src/main/java/io/confluent/ksql/services/SandboxedAdminClient.java
aculver28/ksql
42cffe268a61dbbf0e86a1d3c1b478058c89f812
[ "Apache-2.0" ]
1
2019-05-03T19:31:00.000Z
2019-05-03T19:31:00.000Z
ksqldb-engine/src/main/java/io/confluent/ksql/services/SandboxedAdminClient.java
aculver28/ksql
42cffe268a61dbbf0e86a1d3c1b478058c89f812
[ "Apache-2.0" ]
null
null
null
ksqldb-engine/src/main/java/io/confluent/ksql/services/SandboxedAdminClient.java
aculver28/ksql
42cffe268a61dbbf0e86a1d3c1b478058c89f812
[ "Apache-2.0" ]
null
null
null
30.095238
96
0.74288
13,237
/* * Copyright 2018 Confluent Inc. * * Licensed under the Confluent Community License (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.confluent.io/confluent-community-license * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package io.confluent.ksql.services; import static io.confluent.ksql.util.LimitedProxyBuilder.anyParams; import io.confluent.ksql.util.LimitedProxyBuilder; import org.apache.kafka.clients.admin.Admin; /** * An admin client to use while trying out operations. * * <p>The client will not make changes to the remote Kafka cluster. * * <p>Most operations result in a {@code UnsupportedOperationException} being thrown as they are * not called. */ final class SandboxedAdminClient { static Admin createProxy() { return LimitedProxyBuilder.forClass(Admin.class) .swallow("close", anyParams()) .build(); } private SandboxedAdminClient() { } }
3e1f4ca20afafb44ed28da50dd138f64b1d478d3
1,109
java
Java
api/src/main/java/io/bdeploy/api/deploy/v1/InstanceDeploymentInformationApi.java
krajna/bdeploy
d1b71cd7040ad7aaa292bdc73aac9fae1bbca9f3
[ "Apache-2.0" ]
17
2019-06-30T09:09:53.000Z
2022-01-17T13:14:55.000Z
api/src/main/java/io/bdeploy/api/deploy/v1/InstanceDeploymentInformationApi.java
krajna/bdeploy
d1b71cd7040ad7aaa292bdc73aac9fae1bbca9f3
[ "Apache-2.0" ]
2
2020-06-06T18:05:57.000Z
2021-11-12T12:21:45.000Z
api/src/main/java/io/bdeploy/api/deploy/v1/InstanceDeploymentInformationApi.java
krajna/bdeploy
d1b71cd7040ad7aaa292bdc73aac9fae1bbca9f3
[ "Apache-2.0" ]
3
2021-11-12T11:08:29.000Z
2022-03-08T14:46:45.000Z
35.774194
130
0.741208
13,238
package io.bdeploy.api.deploy.v1; import io.bdeploy.api.remote.v1.dto.InstanceConfigurationApi; /** * Describes a deployments current state. This object is persisted to a file. To retrieve the path to the file in an app-info.yaml * use the <code>{{I:DEPLOYMENT_INFO_FILE}}</code> expansion. * <p> * The file containing this object is updated whenever BDeploy updates the deployment of this instance. Thus it can be consumed by * applications to detect changes to the current deployment states. * <p> * This file is available for server applications only. The client launcher does not provide this file. */ public class InstanceDeploymentInformationApi { public static final String FILE_NAME = "deployment-info.json"; /** * The currently active instance version. */ public String activeInstanceVersion; /** * The instance this information refers to. The information refers to the currently active instance version. * <p> * Note that the description field is currently always empty in this scenario. */ public InstanceConfigurationApi instance; }
3e1f4cd7d91814d84a75a41f2d0268bf24498d89
20,841
java
Java
src/com.mentor.nucleus.bp.core.test/src/com/mentor/nucleus/bp/core/test/synchronization/SynchronizationTestUtils.java
hjjohny/editor
c85d3329f00327f2fd9010ab617c70e031ed5e00
[ "Apache-2.0" ]
1
2018-01-24T16:28:01.000Z
2018-01-24T16:28:01.000Z
src/com.mentor.nucleus.bp.core.test/src/com/mentor/nucleus/bp/core/test/synchronization/SynchronizationTestUtils.java
NDGuthrie/bposs
2c47abf74a3e6fadb174b08e57aa66a209400606
[ "Apache-2.0" ]
1
2015-09-11T07:14:45.000Z
2015-09-11T07:14:45.000Z
src/com.mentor.nucleus.bp.core.test/src/com/mentor/nucleus/bp/core/test/synchronization/SynchronizationTestUtils.java
NDGuthrie/bposs
2c47abf74a3e6fadb174b08e57aa66a209400606
[ "Apache-2.0" ]
null
null
null
36.952128
116
0.713162
13,239
//======================================================================== // //File: $RCSfile: SynchronizationTestUtils.java,v $ //Version: $Revision: 1.3 $ //Modified: $Date: 2013/01/10 22:49:12 $ // //Copyright 2005-2014 Mentor Graphics Corporation. All rights reserved. // //======================================================================== // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. //======================================================================== // package com.mentor.nucleus.bp.core.test.synchronization; import java.util.ArrayList; import java.util.List; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; import junit.framework.Assert; import junit.framework.TestCase; import com.mentor.nucleus.bp.core.ComponentPackage_c; import com.mentor.nucleus.bp.core.ComponentReference_c; import com.mentor.nucleus.bp.core.Component_c; import com.mentor.nucleus.bp.core.ExecutableProperty_c; import com.mentor.nucleus.bp.core.Gd_c; import com.mentor.nucleus.bp.core.InterfaceOperation_c; import com.mentor.nucleus.bp.core.InterfacePackage_c; import com.mentor.nucleus.bp.core.InterfaceReference_c; import com.mentor.nucleus.bp.core.InterfaceSignal_c; import com.mentor.nucleus.bp.core.Interface_c; import com.mentor.nucleus.bp.core.Package_c; import com.mentor.nucleus.bp.core.PackageableElement_c; import com.mentor.nucleus.bp.core.Port_c; import com.mentor.nucleus.bp.core.ProvidedExecutableProperty_c; import com.mentor.nucleus.bp.core.ProvidedOperation_c; import com.mentor.nucleus.bp.core.ProvidedSignal_c; import com.mentor.nucleus.bp.core.Provision_c; import com.mentor.nucleus.bp.core.RequiredExecutableProperty_c; import com.mentor.nucleus.bp.core.RequiredOperation_c; import com.mentor.nucleus.bp.core.RequiredSignal_c; import com.mentor.nucleus.bp.core.Requirement_c; import com.mentor.nucleus.bp.core.SystemModel_c; import com.mentor.nucleus.bp.core.common.NonRootModelElement; import com.mentor.nucleus.bp.core.ui.actions.PublishSynchronizationChanges; import com.mentor.nucleus.bp.core.ui.actions.PullSynchronizationChanges; import com.mentor.nucleus.bp.core.ui.dialogs.ScrolledTextDialog; import com.mentor.nucleus.bp.test.TestUtil; public class SynchronizationTestUtils { public static void deleteExecutableProperty(ExecutableProperty_c ep) { ep.getPersistableComponent(); ep.Dispose(); } public static Component_c createComponent(NonRootModelElement pkg, String name) { if(pkg instanceof Package_c) { Package_c cPkg = (Package_c) pkg; cPkg.Newcomponent(); Component_c[] comps = Component_c .getManyC_CsOnR8001(PackageableElement_c .getManyPE_PEsOnR8000(cPkg)); Component_c comp = comps[comps.length - 1]; comp.setName(name); return comp; } else if(pkg instanceof ComponentPackage_c) { ComponentPackage_c cPkg = (ComponentPackage_c) pkg; cPkg.Newcomponent(); Component_c[] comps = Component_c.getManyC_CsOnR4604(cPkg); Component_c comp = comps[comps.length - 1]; comp.setName(name); return comp; } return null; } public static boolean requirementContainsOperation(Requirement_c requirement, InterfaceOperation_c operation) { return referenceContainsOperation(InterfaceReference_c .getOneC_IROnR4009(requirement), operation, false); } public static boolean requirementContainsSignal(Requirement_c requirement, InterfaceSignal_c signal) { return referenceContainsSignal(InterfaceReference_c .getOneC_IROnR4009(requirement), signal, false); } public static boolean provisionContainsOperation(Provision_c provision, InterfaceOperation_c operation) { return referenceContainsOperation(InterfaceReference_c .getOneC_IROnR4009(provision), operation, true); } public static boolean provisionContainsSignal(Provision_c provision, InterfaceSignal_c signal) { return referenceContainsSignal(InterfaceReference_c .getOneC_IROnR4009(provision), signal, true); } public static boolean referenceContainsOperation( InterfaceReference_c reference, final InterfaceOperation_c operation, final boolean provided) { ProvidedExecutableProperty_c[] peps = ProvidedExecutableProperty_c .getManySPR_PEPsOnR4501(Provision_c .getManyC_PsOnR4009(reference)); RequiredExecutableProperty_c[] reps = RequiredExecutableProperty_c .getManySPR_REPsOnR4500(Requirement_c .getManyC_RsOnR4009(reference)); if (provided) { for(int i = 0; i < peps.length; i++) { ExecutableProperty_c epProxy = ExecutableProperty_c .getOneC_EPOnR4501(peps[i]); if(epProxy.Getcachedname().equals(operation.getName())) { return true; } } } else { for(int i = 0; i < reps.length; i++) { ExecutableProperty_c epProxy = ExecutableProperty_c .getOneC_EPOnR4500(reps[i]); if(epProxy.Getcachedname().equals(operation.getName())) { return true; } } } return false; } public static boolean referenceContainsSignal(InterfaceReference_c reference, final InterfaceSignal_c signal, boolean provided) { ProvidedExecutableProperty_c[] peps = ProvidedExecutableProperty_c .getManySPR_PEPsOnR4501(Provision_c .getManyC_PsOnR4009(reference)); RequiredExecutableProperty_c[] reps = RequiredExecutableProperty_c .getManySPR_REPsOnR4500(Requirement_c .getManyC_RsOnR4009(reference)); if (provided) { for (int i = 0; i < peps.length; i++) { ExecutableProperty_c epProxy = ExecutableProperty_c .getOneC_EPOnR4501(peps[i]); if (epProxy.Getcachedname().equals(signal.getName())) { return true; } } } else { for (int i = 0; i < reps.length; i++) { ExecutableProperty_c epProxy = ExecutableProperty_c .getOneC_EPOnR4500(reps[i]); if (epProxy.Getcachedname().equals(signal.getName())) { return true; } } } return false; } public static InterfaceOperation_c createInterfaceOperation(Interface_c iface, String name) { iface.Newexecutableproperty(false); ExecutableProperty_c[] eps = ExecutableProperty_c .getManyC_EPsOnR4003(iface); ExecutableProperty_c newEp = eps[eps.length - 1]; newEp.getPersistableComponent(); InterfaceOperation_c operation = InterfaceOperation_c.getOneC_IOOnR4004(newEp); operation.setName(name); // there is no persistence occurring, which means the cached // name is never configured, simulate that here newEp.getName(); return operation; } public static InterfaceSignal_c createInterfaceSignal(Interface_c iface, String name) { iface.Newexecutableproperty(true); ExecutableProperty_c[] eps = ExecutableProperty_c .getManyC_EPsOnR4003(iface); ExecutableProperty_c newEp = eps[eps.length - 1]; newEp.getPersistableComponent(); InterfaceSignal_c signal = InterfaceSignal_c.getOneC_ASOnR4004(newEp); signal.setName(name); // there is no persistence occurring, which means the cached // name is never configured, simulate that here newEp.getName(); return signal; } public static Requirement_c createAndFormalizeNewRequirement( Component_c component, Interface_c iface) { boolean created = component.Newrequirement(component.getId(), false, Gd_c.Null_unique_id(), false); TestCase.assertTrue("Test requirement was not created.", created); Requirement_c[] requirements = Requirement_c .getManyC_RsOnR4009(InterfaceReference_c .getManyC_IRsOnR4016(Port_c .getManyC_POsOnR4010(component))); Requirement_c requirement = requirements[requirements.length - 1]; requirement.Formalize(iface.getId(), false); // make sure C_IR has component set InterfaceReference_c ir = InterfaceReference_c.getOneC_IROnR4009(requirement); ir.getPersistableComponent(); return requirement; } public static Provision_c createAndFormalizeNewProvision(Component_c component, Interface_c iface) { boolean created = component.Newprovision(component.getId(), false, Gd_c.Null_unique_id(), false); TestCase.assertTrue("Test provision was not created.", created); Provision_c[] provisions = Provision_c .getManyC_PsOnR4009(InterfaceReference_c .getManyC_IRsOnR4016(Port_c .getManyC_POsOnR4010(component))); Provision_c provision = provisions[provisions.length - 1]; provision.Formalize(iface.getId(), false); // make sure C_IR has component set InterfaceReference_c ir = InterfaceReference_c.getOneC_IROnR4009(provision); ir.getPersistableComponent(); return provision; } public static Provision_c createNewProvision(Component_c component) { boolean created = component.Newprovision(component.getId(), false, Gd_c.Null_unique_id(), false); TestCase.assertTrue("Test provision was not created.", created); Provision_c[] provisions = Provision_c .getManyC_PsOnR4009(InterfaceReference_c .getManyC_IRsOnR4016(Port_c .getManyC_POsOnR4010(component))); Provision_c provision = provisions[provisions.length - 1]; // make sure C_IR has component set InterfaceReference_c ir = InterfaceReference_c.getOneC_IROnR4009(provision); ir.getPersistableComponent(); return provision; } public static Requirement_c createNewRequirement(Component_c component) { boolean created = component.Newrequirement(component.getId(), false, Gd_c.Null_unique_id(), false); TestCase.assertTrue("Test requirement was not created.", created); Requirement_c[] requirements = Requirement_c .getManyC_RsOnR4009(InterfaceReference_c .getManyC_IRsOnR4016(Port_c .getManyC_POsOnR4010(component))); Requirement_c requirement = requirements[requirements.length - 1]; // make sure C_IR has component set InterfaceReference_c ir = InterfaceReference_c.getOneC_IROnR4009(requirement); ir.getPersistableComponent(); return requirement; } public static Interface_c createInterface(NonRootModelElement pkg, String name, String[] operationNames, String[] signalNames) { if(pkg instanceof Package_c) { Package_c iPkg = (Package_c) pkg; iPkg.Newinterface(); Interface_c[] ifaces = Interface_c.getManyC_IsOnR8001(PackageableElement_c.getManyPE_PEsOnR8000(iPkg)); Interface_c iface = ifaces[ifaces.length - 1]; for(String operationName : operationNames) { createInterfaceOperation(iface, operationName); } for(String signalName : signalNames) { createInterfaceSignal(iface, signalName); } iface.setName(name); return iface; } else if(pkg instanceof InterfacePackage_c) { InterfacePackage_c iPkg = (InterfacePackage_c) pkg; iPkg.Newinterface(); Interface_c[] ifaces = Interface_c.getManyC_IsOnR4303(iPkg); Interface_c iface = ifaces[ifaces.length - 1]; for(String operationName : operationNames) { createInterfaceOperation(iface, operationName); } for(String signalName : signalNames) { createInterfaceSignal(iface, signalName); } iface.setName(name); return iface; } return null; } public static Package_c createContainer(String name, SystemModel_c parent) { parent.Newpackage(); Package_c[] pkgs = Package_c.getManyEP_PKGsOnR1405(parent); Package_c pkg = pkgs[pkgs.length - 1]; pkg.setName(name); return pkg; } public static void synchronizeByPushing(SystemModel_c[] systems) { PublishSynchronizationChanges action = new PublishSynchronizationChanges(); action.selectionChanged(null, new StructuredSelection(systems)); action.run(null); } public static void synchronizeByPulling(SystemModel_c[] systems) { PullSynchronizationChanges action = new PullSynchronizationChanges(); action.selectionChanged(null, new StructuredSelection(systems)); action.run(null); } public static InterfacePackage_c createSpecializedInterfacePackage(String name, SystemModel_c system) { system.Newinterfacepackage(); InterfacePackage_c[] pkgs = InterfacePackage_c .getManyIP_IPsOnR4302(system); InterfacePackage_c pkg = pkgs[pkgs.length - 1]; pkg.setName(name); return pkg; } public static ComponentPackage_c createSpecializedComponentPackage( String name, SystemModel_c system) { system.Newcomponentpackage(); ComponentPackage_c[] pkgs = ComponentPackage_c.getManyCP_CPsOnR4602(system); ComponentPackage_c pkg = pkgs[pkgs.length - 1]; pkg.setName(name); return pkg; } protected static List<String> dialogContents = new ArrayList<String>(); public static void noToSynchronizationDialog() { PlatformUI.getWorkbench().getDisplay().timerExec(500, new Runnable() { @Override public void run() { Shell[] shells = PlatformUI.getWorkbench().getDisplay().getShells(); ScrolledTextDialog dialog = null; for(int i = 0; i < shells.length; i++) { if(shells[i].getData() instanceof ScrolledTextDialog) { dialog = (ScrolledTextDialog) shells[i].getData(); } } if(dialog != null) { Control[] children = dialog.getShell().getChildren(); Text textField = null; for(int i = 0; i < children.length; i++) { textField = getTextFromControl(children[i]); if(textField != null) { break; } } if(textField != null) { dialogContents.add(textField.getText()); } Button no = TestUtil.findButton(dialog.getShell(), "Cancel"); no.notifyListeners(SWT.Selection, new Event()); } } }); } protected static Text getTextFromControl(Control control) { if(control instanceof Text) { return (Text) control; } if(control instanceof Composite) { Composite composite = (Composite) control; Control[] children = composite.getChildren(); for(int i = 0; i < children.length; i++) { Text text = getTextFromControl(children[i]); if(text != null) { return text; } } } return null; } public static String getSynchronizationDialogText() { return dialogContents.remove(0); } public static void okToSynchronizationDialog() { PlatformUI.getWorkbench().getDisplay().timerExec(500, new Runnable() { @Override public void run() { Shell[] shells = PlatformUI.getWorkbench().getDisplay().getShells(); ScrolledTextDialog dialog = null; for(int i = 0; i < shells.length; i++) { if(shells[i].getData() instanceof ScrolledTextDialog) { dialog = (ScrolledTextDialog) shells[i].getData(); } } if(dialog != null) { Control[] children = dialog.getShell().getChildren(); Text textField = null; for(int i = 0; i < children.length; i++) { textField = getTextFromControl(children[i]); if(textField != null) { break; } } if(textField != null) { dialogContents.add(textField.getText()); } Button okButton = TestUtil.findButton(dialog.getShell(), "OK"); okButton.notifyListeners(SWT.Selection, new Event()); } } }); } private static int attempts = 0; public static void okWithDoNotShowCheckedToSynchronizationDialog(final String doNotShowLabel, final int timeout) { attempts = 0; PlatformUI.getWorkbench().getDisplay().timerExec(timeout, new Runnable() { @Override public void run() { Shell[] shells = PlatformUI.getWorkbench().getDisplay().getShells(); ScrolledTextDialog dialog = null; for(int i = 0; i < shells.length; i++) { if(shells[i].getData() instanceof ScrolledTextDialog) { dialog = (ScrolledTextDialog) shells[i].getData(); break; } } if(dialog != null) { Control[] children = dialog.getShell().getChildren(); Text textField = null; for(int i = 0; i < children.length; i++) { textField = getTextFromControl(children[i]); if(textField != null) { break; } } if(textField != null) { dialogContents.add(textField.getText()); } Button doNotShow = TestUtil.findButton(dialog.getShell(), doNotShowLabel); doNotShow.setSelection(true); Button okButton = TestUtil.findButton(dialog.getShell(), "OK"); okButton.notifyListeners(SWT.Selection, new Event()); } else { if(attempts < 5) { attempts++; okWithDoNotShowCheckedToSynchronizationDialog(doNotShowLabel, timeout); } } } }); } public static void addOALToProvision(Provision_c provision) { ProvidedOperation_c po = ProvidedOperation_c .getOneSPR_POOnR4503(ProvidedExecutableProperty_c .getManySPR_PEPsOnR4501(provision)); if(po != null) { po.setAction_semantics_internal("// test OAL"); } ProvidedSignal_c ps = ProvidedSignal_c .getOneSPR_PSOnR4503(ProvidedExecutableProperty_c .getManySPR_PEPsOnR4501(provision)); if(ps != null) { ps.setAction_semantics_internal("// test OAL"); } } public static void addOALToRequirement(Requirement_c requirement) { RequiredOperation_c ro = RequiredOperation_c .getOneSPR_ROOnR4502(RequiredExecutableProperty_c .getManySPR_REPsOnR4500(requirement)); if(ro != null) { ro.setAction_semantics_internal("// test OAL"); } RequiredSignal_c rs = RequiredSignal_c .getOneSPR_RSOnR4502(RequiredExecutableProperty_c .getManySPR_REPsOnR4500(requirement)); if(rs != null) { rs.setAction_semantics_internal("// test OAL"); } } public static void validateOALInProvision(Provision_c provision) { ProvidedOperation_c po = ProvidedOperation_c .getOneSPR_POOnR4503(ProvidedExecutableProperty_c .getManySPR_PEPsOnR4501(provision)); if (po != null) { Assert.assertTrue("OAL did not remain unchanged.", po .getAction_semantics_internal().equals("// test OAL")); } else { Assert.fail("Could not locate provided operation."); } ProvidedSignal_c ps = ProvidedSignal_c .getOneSPR_PSOnR4503(ProvidedExecutableProperty_c .getManySPR_PEPsOnR4501(provision)); if (ps != null) { Assert.assertTrue("OAL did not remain unchanged.", ps .getAction_semantics_internal().equals("// test OAL")); } else { Assert.fail("Could not locate provided signal."); } } public static void validateOALInRequirement(Requirement_c requirement) { RequiredOperation_c ro = RequiredOperation_c .getOneSPR_ROOnR4502(RequiredExecutableProperty_c .getManySPR_REPsOnR4500(requirement)); if (ro != null) { Assert.assertTrue("OAL did not remain unchanged.", ro .getAction_semantics_internal().equals("// test OAL")); } else { Assert.fail("Could not locate required operation."); } RequiredSignal_c rs = RequiredSignal_c .getOneSPR_RSOnR4502(RequiredExecutableProperty_c .getManySPR_REPsOnR4500(requirement)); if (rs != null) { Assert.assertTrue("OAL did not remain unchanged.", rs .getAction_semantics_internal().equals("// test OAL")); } else { Assert.fail("Could not locate required signal."); } } public static ComponentReference_c createComponentReferenceAndAssignToComponent(NonRootModelElement container, Component_c component) { if(container instanceof Package_c) { Package_c pkg = (Package_c) container; pkg.Newimportedcomponent(); ComponentReference_c[] references = ComponentReference_c .getManyCL_ICsOnR8001(PackageableElement_c .getManyPE_PEsOnR8000(pkg)); ComponentReference_c ref = references[references.length - 1]; ref.Assigntocomp(component.getId()); return ref; } else { ComponentPackage_c pkg = (ComponentPackage_c) container; pkg.Newimportedcomponent(); ComponentReference_c[] references = ComponentReference_c .getManyCL_ICsOnR4605(pkg); ComponentReference_c ref = references[references.length - 1]; ref.Assigntocomp(component.getId()); return ref; } } public static void deleteComponent(Component_c component) { component.Dispose(); } }
3e1f4de309bb5a44ec68e5aaabe36327774060fa
9,945
java
Java
wamp2spring-core/src/test/java/ch/rasc/wamp2spring/WampPublisherTest.java
ralscha/wamp2spring
5c9865d94861d288bddc92680070b532a1e1925b
[ "Apache-2.0" ]
24
2017-08-17T13:44:31.000Z
2021-08-05T02:17:36.000Z
wamp2spring-core/src/test/java/ch/rasc/wamp2spring/WampPublisherTest.java
ralscha/wamp2spring
5c9865d94861d288bddc92680070b532a1e1925b
[ "Apache-2.0" ]
12
2017-12-27T11:32:14.000Z
2022-03-17T03:39:10.000Z
wamp2spring-core/src/test/java/ch/rasc/wamp2spring/WampPublisherTest.java
ralscha/wamp2spring
5c9865d94861d288bddc92680070b532a1e1925b
[ "Apache-2.0" ]
9
2017-08-17T13:44:33.000Z
2021-07-10T20:49:45.000Z
35.391459
84
0.752941
13,240
/** * Copyright 2017-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.rasc.wamp2spring; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatchers; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.messaging.SubscribableChannel; import ch.rasc.wamp2spring.message.PublishMessage; import ch.rasc.wamp2spring.message.WampMessage; public class WampPublisherTest { @Mock private SubscribableChannel clientOutboundChannel; private WampPublisher wampPublisher; @Captor ArgumentCaptor<PublishMessage> messageCaptor; @BeforeEach public void setup() { MockitoAnnotations.openMocks(this); Mockito.when( this.clientOutboundChannel.send(ArgumentMatchers.any(WampMessage.class))) .thenReturn(true); this.wampPublisher = new WampPublisher(this.clientOutboundChannel); } @Test public void testPublishToAll() { this.wampPublisher.publishToAll("topic", 1); Mockito.verify(this.clientOutboundChannel, Mockito.times(1)) .send(this.messageCaptor.capture()); PublishMessage publishMessage = this.messageCaptor.getValue(); assertPublishMessage(publishMessage, "topic", Collections.singletonList(1), null, null); } @Test public void testPublishToAllList() { List<String> value = Arrays.asList("a", "b", "c"); this.wampPublisher.publishToAll("topic2", value); Mockito.verify(this.clientOutboundChannel, Mockito.times(1)) .send(this.messageCaptor.capture()); PublishMessage publishMessage = this.messageCaptor.getValue(); assertPublishMessage(publishMessage, "topic2", value, null, null); } @Test public void testPublishToAllMap() { Map<String, Integer> mapValue = new HashMap<>(); mapValue.put("one", 1); mapValue.put("two", 2); mapValue.put("three", 3); this.wampPublisher.publishToAll("topic3", mapValue); Mockito.verify(this.clientOutboundChannel, Mockito.times(1)) .send(this.messageCaptor.capture()); PublishMessage publishMessage = this.messageCaptor.getValue(); assertPublishMessage(publishMessage, "topic3", mapValue, null, null); } @Test public void testPublishTo() { this.wampPublisher.publishTo(Collections.singleton(123L), "topic", 1); Mockito.verify(this.clientOutboundChannel, Mockito.times(1)) .send(this.messageCaptor.capture()); PublishMessage publishMessage = this.messageCaptor.getValue(); assertPublishMessage(publishMessage, "topic", Collections.singletonList(1), Collections.singleton(123L), null); } @Test public void testPublishToOneCollection() { this.wampPublisher.publishTo(124L, "topic1", Arrays.asList(1, 2, 3, 4)); Mockito.verify(this.clientOutboundChannel, Mockito.times(1)) .send(this.messageCaptor.capture()); PublishMessage publishMessage = this.messageCaptor.getValue(); assertPublishMessage(publishMessage, "topic1", Arrays.asList(1, 2, 3, 4), Collections.singleton(124L), null); } @Test public void testPublishToOneMap() { Map<String, Object> data = new HashMap<>(); data.put("one", 1); data.put("two", 2); this.wampPublisher.publishTo(125L, "topic2", data); Mockito.verify(this.clientOutboundChannel, Mockito.times(1)) .send(this.messageCaptor.capture()); PublishMessage publishMessage = this.messageCaptor.getValue(); assertPublishMessage(publishMessage, "topic2", data, Collections.singleton(125L), null); } @Test public void testPublishToList() { List<String> value = Arrays.asList("a", "b", "c"); this.wampPublisher.publishTo(Collections.singleton(123L), "topic2", value); Mockito.verify(this.clientOutboundChannel, Mockito.times(1)) .send(this.messageCaptor.capture()); PublishMessage publishMessage = this.messageCaptor.getValue(); assertPublishMessage(publishMessage, "topic2", value, Collections.singleton(123L), null); } @Test public void testPublishToMap() { Map<String, Integer> mapValue = new HashMap<>(); mapValue.put("one", 1); mapValue.put("two", 2); mapValue.put("three", 3); this.wampPublisher.publishTo(Collections.singleton(123L), "topic3", mapValue); Mockito.verify(this.clientOutboundChannel, Mockito.times(1)) .send(this.messageCaptor.capture()); PublishMessage publishMessage = this.messageCaptor.getValue(); assertPublishMessage(publishMessage, "topic3", mapValue, Collections.singleton(123L), null); } @Test public void testPublishToAllExcept() { this.wampPublisher.publishToAllExcept(Collections.singleton(123L), "topic", 1); Mockito.verify(this.clientOutboundChannel, Mockito.times(1)) .send(this.messageCaptor.capture()); PublishMessage publishMessage = this.messageCaptor.getValue(); assertPublishMessage(publishMessage, "topic", Collections.singletonList(1), null, Collections.singleton(123L)); } @Test public void testPublishToAllExceptOne() { this.wampPublisher.publishToAllExcept(124, "topic1", 2); Mockito.verify(this.clientOutboundChannel, Mockito.times(1)) .send(this.messageCaptor.capture()); PublishMessage publishMessage = this.messageCaptor.getValue(); assertPublishMessage(publishMessage, "topic1", Collections.singletonList(2), null, Collections.singleton(124L)); } @Test public void testPublishToAllExceptOneCollection() { this.wampPublisher.publishToAllExcept(125, "topic2", Arrays.asList(1, 2, 3)); Mockito.verify(this.clientOutboundChannel, Mockito.times(1)) .send(this.messageCaptor.capture()); PublishMessage publishMessage = this.messageCaptor.getValue(); assertPublishMessage(publishMessage, "topic2", Arrays.asList(1, 2, 3), null, Collections.singleton(125L)); } @Test public void testPublishToAllExceptOneMap() { Map<String, Integer> mapValue = new HashMap<>(); mapValue.put("one", 1); mapValue.put("two", 2); mapValue.put("three", 3); this.wampPublisher.publishToAllExcept(126, "topic3", mapValue); Mockito.verify(this.clientOutboundChannel, Mockito.times(1)) .send(this.messageCaptor.capture()); PublishMessage publishMessage = this.messageCaptor.getValue(); assertPublishMessage(publishMessage, "topic3", mapValue, null, Collections.singleton(126L)); } @Test public void testPublishToAllExceptList() { List<String> value = Arrays.asList("a", "b", "c"); this.wampPublisher.publishToAllExcept(Collections.singleton(123L), "topic2", value); Mockito.verify(this.clientOutboundChannel, Mockito.times(1)) .send(this.messageCaptor.capture()); PublishMessage publishMessage = this.messageCaptor.getValue(); assertPublishMessage(publishMessage, "topic2", value, null, Collections.singleton(123L)); } @Test public void testPublishToAllExceptMap() { Map<String, Integer> mapValue = new HashMap<>(); mapValue.put("one", 1); mapValue.put("two", 2); mapValue.put("three", 3); this.wampPublisher.publishToAllExcept(Collections.singleton(123L), "topic3", mapValue); Mockito.verify(this.clientOutboundChannel, Mockito.times(1)) .send(this.messageCaptor.capture()); PublishMessage publishMessage = this.messageCaptor.getValue(); assertPublishMessage(publishMessage, "topic3", mapValue, null, Collections.singleton(123L)); } private static <T> void assertPublishMessage(PublishMessage publishMessage, String topic, Map<String, T> value, Set<Long> eligible, Set<Long> exclude) { assertThat(publishMessage.getCode()).isEqualTo(16); assertThat(publishMessage.getRequestId()).isGreaterThan(0); assertThat(publishMessage.getTopic()).isEqualTo(topic); if (eligible == null) { assertThat(publishMessage.getEligible()).isNull(); } else { assertThat(publishMessage.getEligible()).containsOnlyElementsOf(eligible); } if (exclude == null) { assertThat(publishMessage.getExclude()).isNull(); } else { assertThat(publishMessage.getExclude()).containsOnlyElementsOf(exclude); } assertThat(publishMessage.isAcknowledge()).isFalse(); assertThat(publishMessage.isDiscloseMe()).isFalse(); assertThat(publishMessage.isExcludeMe()).isTrue(); assertThat(publishMessage.getArguments()).isNull(); assertThat(publishMessage.getArgumentsKw()).containsAllEntriesOf(value); } private static <T> void assertPublishMessage(PublishMessage publishMessage, String topic, List<T> values, Set<Long> eligible, Set<Long> exclude) { assertThat(publishMessage.getCode()).isEqualTo(16); assertThat(publishMessage.getRequestId()).isGreaterThan(0); assertThat(publishMessage.getTopic()).isEqualTo(topic); if (eligible == null) { assertThat(publishMessage.getEligible()).isNull(); } else { assertThat(publishMessage.getEligible()).containsOnlyElementsOf(eligible); } if (exclude == null) { assertThat(publishMessage.getExclude()).isNull(); } else { assertThat(publishMessage.getExclude()).containsOnlyElementsOf(exclude); } assertThat(publishMessage.isAcknowledge()).isFalse(); assertThat(publishMessage.isDiscloseMe()).isFalse(); assertThat(publishMessage.isExcludeMe()).isTrue(); assertThat(publishMessage.getArguments()).containsExactlyElementsOf(values); assertThat(publishMessage.getArgumentsKw()).isNull(); } }
3e1f4df95986fd3d290541236257f16527dec1f5
3,378
java
Java
deprecated/UltimateAndroidGradle/demoofui/src/main/java/com/marshalchen/common/demoofui/sampleModules/CustomPullToRefreshActivity.java
maysusan/UltimateAndroid
5abd6794e1bbc885e83600df532436b83a21b6e3
[ "Apache-2.0" ]
1,781
2015-01-01T08:11:19.000Z
2022-03-23T08:06:48.000Z
deprecated/UltimateAndroidGradle/demoofui/src/main/java/com/marshalchen/common/demoofui/sampleModules/CustomPullToRefreshActivity.java
maysusan/UltimateAndroid
5abd6794e1bbc885e83600df532436b83a21b6e3
[ "Apache-2.0" ]
21
2015-05-13T09:25:38.000Z
2022-03-15T02:32:31.000Z
deprecated/UltimateAndroidGradle/demoofui/src/main/java/com/marshalchen/common/demoofui/sampleModules/CustomPullToRefreshActivity.java
maysusan/UltimateAndroid
5abd6794e1bbc885e83600df532436b83a21b6e3
[ "Apache-2.0" ]
695
2015-01-04T08:12:11.000Z
2022-03-07T20:49:23.000Z
30.432432
115
0.635287
13,241
package com.marshalchen.common.demoofui.sampleModules; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.marshalchen.common.demoofui.R; import com.marshalchen.common.uimodule.widget.PullRefreshLayout; public class CustomPullToRefreshActivity extends Activity { PullRefreshLayout layout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.custom_pull_to_refresh_activity_demo); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); String[] array = new String[50]; for (int i = 0; i < array.length; i++) { array[i] = "string " + i; } recyclerView.setAdapter(new ArrayAdapter(this, array)); layout = (PullRefreshLayout) findViewById(R.id.swipeRefreshLayout); layout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { layout.postDelayed(new Runnable() { @Override public void run() { layout.setRefreshing(false); } }, 4000); } }); } static class ArrayAdapter extends RecyclerView.Adapter<ViewHolder> { private String[] mArray; private Context mContext; public ArrayAdapter(Context context, String[] array) { mContext = context; mArray = array; } @Override public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { return new ViewHolder(View.inflate(viewGroup.getContext(), android.R.layout.simple_list_item_1, null)); } @Override public void onBindViewHolder(ViewHolder viewHolder, int i) { viewHolder.mTextView.setText(mArray[i]); } @Override public int getItemCount() { return mArray.length; } } static class ViewHolder extends RecyclerView.ViewHolder { public TextView mTextView; public ViewHolder(View itemView) { super(itemView); mTextView = (TextView) itemView; } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.custom_pull_to_refresh, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.action_circles: layout.setRefreshStyle(PullRefreshLayout.STYLE_CIRCLES); return true; case R.id.action_water_drop: layout.setRefreshStyle(PullRefreshLayout.STYLE_WATER_DROP); return true; case R.id.action_ring: layout.setRefreshStyle(PullRefreshLayout.STYLE_RING); return true; } return super.onOptionsItemSelected(item); } }
3e1f4e996fbca2a97e2ca5c0525342e9b609220c
1,637
java
Java
src/com/oui/pojo/TbShow.java
katsukichan/OuiSystem
2a76a9ab983da07834aef8baa83f663fe09a2120
[ "MIT" ]
null
null
null
src/com/oui/pojo/TbShow.java
katsukichan/OuiSystem
2a76a9ab983da07834aef8baa83f663fe09a2120
[ "MIT" ]
null
null
null
src/com/oui/pojo/TbShow.java
katsukichan/OuiSystem
2a76a9ab983da07834aef8baa83f663fe09a2120
[ "MIT" ]
null
null
null
17.989011
57
0.690898
13,242
package com.oui.pojo; import java.io.Serializable; public class TbShow implements Serializable{ private static final long serialVersionUID = 1L; /*演出编号*/ private Long id; /*演出图片路径*/ private String img; /*演出标题*/ private String title; /*演出场馆*/ private String place; /*演出时间*/ private String time; /*演出价格*/ private String price; /*演出城市*/ private String city; /*演出分类*/ private String category; /*演出上下架状态*/ private String status; /*第一场场次日期*/ private String first_play_date; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getPlace() { return place; } public void setPlace(String place) { this.place = place; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getFirst_play_date() { return first_play_date; } public void setFirst_play_date(String first_play_date) { this.first_play_date = first_play_date; } }
3e1f4f586b52aef34f82efedf7c79b431b39152d
1,560
java
Java
jdk_11_gradle/cs/graphql/patio-api/src/main/java/patio/security/graphql/ChangePasswordInput.java
EMResearch/EMB
5f81fa65daf463cb7aec43a7b22ccafdf653479b
[ "Apache-2.0" ]
11
2017-06-11T14:13:30.000Z
2022-02-21T13:45:34.000Z
jdk_11_gradle/cs/graphql/patio-api/src/main/java/patio/security/graphql/ChangePasswordInput.java
EMResearch/EMB
5f81fa65daf463cb7aec43a7b22ccafdf653479b
[ "Apache-2.0" ]
9
2018-12-20T10:45:45.000Z
2022-03-08T12:12:56.000Z
jdk_11_gradle/cs/graphql/patio-api/src/main/java/patio/security/graphql/ChangePasswordInput.java
EMResearch/EMB
5f81fa65daf463cb7aec43a7b22ccafdf653479b
[ "Apache-2.0" ]
6
2018-08-16T15:11:20.000Z
2022-03-31T06:53:00.000Z
26
71
0.696795
13,243
/* * Copyright (C) 2019 Kaleidos Open Source SL * * This file is part of PATIO. * PATIO is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PATIO is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PATIO. If not, see <https://www.gnu.org/licenses/> */ package patio.security.graphql; /** * Input to change the password for a user * * @since 0.1.0 */ public class ChangePasswordInput { private final String otpCode; private final String password; /** * Creates an input instance with the required dependencies * * @param otpCode the OTP code to change the password * @param password the new password */ public ChangePasswordInput(String otpCode, String password) { this.otpCode = otpCode; this.password = password; } /** * Returns the input's password * * @return input password * @since 0.1.0 */ public String getPassword() { return password; } /** * Returns the otp code used for changing the password * * @return the otp code used for changing the password */ public String getOtpCode() { return otpCode; } }
3e1f50dcd7903d1c8c6efac0d10863493e826355
1,671
java
Java
databus-util-cmdline/databus-util-cmdline-impl/src/main/java/com/linkedin/databus/util/AvroPrimitiveTypes.java
xiangyuf/databus
a089fed09706ddfeca06c409f899d65ffb1be77b
[ "Apache-2.0" ]
2,989
2015-01-06T01:58:48.000Z
2022-03-31T11:57:55.000Z
databus-util-cmdline/databus-util-cmdline-impl/src/main/java/com/linkedin/databus/util/AvroPrimitiveTypes.java
xiangyuf/databus
a089fed09706ddfeca06c409f899d65ffb1be77b
[ "Apache-2.0" ]
85
2015-01-02T13:47:10.000Z
2022-03-22T07:18:34.000Z
databus-util-cmdline/databus-util-cmdline-impl/src/main/java/com/linkedin/databus/util/AvroPrimitiveTypes.java
xiangyuf/databus
a089fed09706ddfeca06c409f899d65ffb1be77b
[ "Apache-2.0" ]
671
2015-01-06T12:59:27.000Z
2022-03-23T02:50:07.000Z
22.972603
70
0.678593
13,244
/* * $Id: AvroPrimitiveTypes.java 151262 2010-11-17 23:00:29Z jwesterm $ */ package com.linkedin.databus.util; /* * * Copyright 2013 LinkedIn Corp. 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. * */ /** * @author Jemiah Westerman<anpch@example.com> * @version $Revision: 151262 $ */ public enum AvroPrimitiveTypes { INTEGER("long"), INTEGER_UNSIGNED("long"), LONG("long"), RAW("bytes"), FLOAT("float"), DECIMAL("double"), DOUBLE("double"), CLOB("string"), VARCHAR("string"), VARCHAR2("string"), NVARCHAR("string"), NVARCHAR2("string"), TIMESTAMP("long"), DATETIME("long"), CHAR("string"), DATE("long"), BLOB("bytes"), ARRAY("array"), TABLE("record"), XMLTYPE("string"), TINYINT("int"), TINYINT_UNSIGNED("int"), SMALLINT("int"), SMALLINT_UNSIGNED("int"), MEDIUMINT("int"), MEDIUMINT_UNSIGNED("int"), INT("long"), INT_UNSIGNED("long"), BIGINT("long"), BIGINT_UNSIGNED("long"), YEAR("int"); private final String _avroType; private AvroPrimitiveTypes(String avroType) { _avroType = avroType; } public String getAvroType() { return _avroType; } }
3e1f510c48c587e32c0ae16dc20a63310392b31d
4,123
java
Java
modules/MarchCommand/src/main/java/com/marchnetworks/command/spring/security/SessionAuthenticationFilter.java
TheAmeliaDeWitt/YAHoneyPot
569c2578b876f776e629ba7d7d2952c535f33357
[ "MIT" ]
null
null
null
modules/MarchCommand/src/main/java/com/marchnetworks/command/spring/security/SessionAuthenticationFilter.java
TheAmeliaDeWitt/YAHoneyPot
569c2578b876f776e629ba7d7d2952c535f33357
[ "MIT" ]
null
null
null
modules/MarchCommand/src/main/java/com/marchnetworks/command/spring/security/SessionAuthenticationFilter.java
TheAmeliaDeWitt/YAHoneyPot
569c2578b876f776e629ba7d7d2952c535f33357
[ "MIT" ]
null
null
null
34.358333
166
0.803784
13,245
package com.marchnetworks.command.spring.security; import org.springframework.security.authentication.AuthenticationDetailsSource; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.util.Assert; import org.springframework.web.filter.GenericFilterBean; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class SessionAuthenticationFilter extends GenericFilterBean { private AuthenticationManager authenticationManager; protected AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> authenticationDetailsSource = new WebAuthenticationDetailsSource(); private static final String SESSIONIDHEADER = "x-sessionId"; private static final String SESSIONIDPARAM = "sessionId"; public void afterPropertiesSet() { Assert.notNull( authenticationManager, "An AuthenticationManager is required" ); } public void doFilter( ServletRequest req, ServletResponse res, FilterChain chain ) throws IOException, ServletException { HttpServletRequest request = ( HttpServletRequest ) req; HttpServletResponse response = ( HttpServletResponse ) res; Authentication authResult; if ( !requiresAuthentication( request, response ) ) { chain.doFilter( request, response ); return; } try { authResult = attemptAuthentication( request, response ); if ( authResult == null ) return; } catch ( AuthenticationException failed ) { SecurityContextHolder.getContext().setAuthentication( null ); response.sendError( 401, failed.getMessage() ); return; } SecurityContextHolder.getContext().setAuthentication( authResult ); chain.doFilter( request, response ); } protected boolean requiresAuthentication( HttpServletRequest request, HttpServletResponse response ) { String sessionIdheader = request.getHeader( "x-sessionId" ); String sessionIdparam = request.getParameter( "sessionId" ); if ( ( sessionIdheader == null ) && ( sessionIdparam == null ) ) { return false; } return true; } public Authentication attemptAuthentication( HttpServletRequest request, HttpServletResponse response ) throws AuthenticationException, IOException, ServletException { String sessionId = null; if ( request.isSecure() ) { sessionId = request.getHeader( "x-sessionId" ); if ( sessionId == null ) { sessionId = request.getParameter( "sessionId" ); } } if ( sessionId == null ) { throw new AuthenticationServiceException( "Session does not exist" ); } SessionAuthenticationToken authRequest = new SessionAuthenticationToken( sessionId ); authRequest.setDetails( authenticationDetailsSource.buildDetails( request ) ); return getAuthenticationManager().authenticate( authRequest ); } protected AuthenticationManager getAuthenticationManager() { return authenticationManager; } public void setAuthenticationManager( AuthenticationManager authenticationManager ) { this.authenticationManager = authenticationManager; } public void setAuthenticationDetailsSource( AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> authenticationDetailsSource ) { Assert.notNull( authenticationDetailsSource, "AuthenticationDetailsSource required" ); this.authenticationDetailsSource = authenticationDetailsSource; } public AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> getAuthenticationDetailsSource() { return authenticationDetailsSource; } }
3e1f5373ab763589ea4705a2cc49562b44d9640a
456
java
Java
src/util/Utils.java
edmilson-fnk/ProjectEuler
b69ef17a5ce75133820df5bf3eb1e1ba72df9bab
[ "MIT" ]
null
null
null
src/util/Utils.java
edmilson-fnk/ProjectEuler
b69ef17a5ce75133820df5bf3eb1e1ba72df9bab
[ "MIT" ]
null
null
null
src/util/Utils.java
edmilson-fnk/ProjectEuler
b69ef17a5ce75133820df5bf3eb1e1ba72df9bab
[ "MIT" ]
null
null
null
19
69
0.677632
13,246
package util; import java.util.Arrays; public class Utils { public static void show(Object[] array) { System.out.println(arrayToString(array)); } public static void show(Object[][] array) { Arrays.stream(array).forEach(it -> show(it)); } private static String arrayToString(Object[] array) { StringBuilder sb = new StringBuilder(); Arrays.stream(array).forEach(it -> sb.append(it.toString() + " ")); return sb.toString(); } }
3e1f53ffb941cc3f19e37d0a2c576b997de8f9a2
170
java
Java
AgoraLive-Android/app/src/main/java/io/agora/vlive/protocol/model/response/Response.java
Lhh1206/AgoraLive
3a94dc93ef2017f161e343bae711631d74e8d255
[ "MIT" ]
457
2020-04-01T01:35:59.000Z
2022-03-31T07:22:43.000Z
AgoraLive-Android/app/src/main/java/io/agora/vlive/protocol/model/response/Response.java
Lhh1206/AgoraLive
3a94dc93ef2017f161e343bae711631d74e8d255
[ "MIT" ]
27
2020-07-13T03:33:15.000Z
2022-03-21T12:46:07.000Z
AgoraLive-Android/app/src/main/java/io/agora/vlive/protocol/model/response/Response.java
Lhh1206/AgoraLive
3a94dc93ef2017f161e343bae711631d74e8d255
[ "MIT" ]
149
2020-07-16T06:53:45.000Z
2022-03-22T04:16:07.000Z
18.888889
47
0.723529
13,247
package io.agora.vlive.protocol.model.response; public abstract class Response { public static final int SUCCESS = 0; public int code; public String msg; }
3e1f5572dd6885affd052bed4eda0e5349c378b8
580
java
Java
persistence/src/main/java/io/reflectoring/jiraalerts/device/DeviceType.java
pDiller/JiraAlerts
12d4d9506e1a858955e4a2abd583882399a1a008
[ "MIT" ]
6
2017-06-05T07:09:41.000Z
2019-10-29T16:57:10.000Z
persistence/src/main/java/io/reflectoring/jiraalerts/device/DeviceType.java
pDiller/JiraAlerts
12d4d9506e1a858955e4a2abd583882399a1a008
[ "MIT" ]
18
2017-06-10T10:53:20.000Z
2017-08-11T18:34:17.000Z
persistence/src/main/java/io/reflectoring/jiraalerts/device/DeviceType.java
pDiller/JiraAlerts
12d4d9506e1a858955e4a2abd583882399a1a008
[ "MIT" ]
2
2017-06-07T15:17:52.000Z
2017-06-07T17:40:02.000Z
17.575758
80
0.715517
13,248
package io.reflectoring.jiraalerts.device; import java.util.ResourceBundle; import io.reflectoring.jiraalerts.common.EnumWithId; import io.reflectoring.jiraalerts.common.LocalizedEnum; /** * The type of a device. */ public enum DeviceType implements EnumWithId, LocalizedEnum { RAITO4RPI(0), // PHILIPS_HUE(1); private final int id; DeviceType(int id) { this.id = id; } @Override public int getId() { return id; } @Override public String toLocalizedString() { return ResourceBundle.getBundle(getClass().getName()).getString(name()); } }
3e1f55891771fb01788736a849dfe135b23a89b2
3,327
java
Java
entitybroker/api/src/java/org/sakaiproject/entitybroker/access/EntityViewAccessProvider.java
cboyd10/sakai
7741f00a5dc9b52944968844f403462255a568a6
[ "ECL-2.0" ]
13
2016-05-25T16:12:49.000Z
2021-04-09T01:49:24.000Z
entitybroker/api/src/java/org/sakaiproject/entitybroker/access/EntityViewAccessProvider.java
Bobmaintain/sakai
eff276d940e373469ff93e8062ae40b95689068f
[ "ECL-2.0" ]
265
2015-10-19T02:40:55.000Z
2022-03-28T07:24:49.000Z
entitybroker/api/src/java/org/sakaiproject/entitybroker/access/EntityViewAccessProvider.java
Bobmaintain/sakai
eff276d940e373469ff93e8062ae40b95689068f
[ "ECL-2.0" ]
7
2016-02-08T11:41:40.000Z
2021-06-08T18:18:02.000Z
48.985294
107
0.739117
13,249
/** * $Id$ * $URL$ * ViewAccessProvider.java - entity-broker - Apr 11, 2008 11:37:48 AM - azeckoski ************************************************************************** * Copyright (c) 2008 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sakaiproject.entitybroker.access; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.sakaiproject.entitybroker.EntityView; import org.sakaiproject.entitybroker.exception.EntityException; import org.sakaiproject.entitybroker.exception.FormatUnsupportedException; /** * Represents a bean which is capable of handling access for an {@link EntityView}, * this replaces the {@link HttpServletAccessProvider} as all entity URLs are now being parsed * so more information can be provided through the {@link EntityView}<br/> * <br/> * This interface would be typically implemented from a tool (webapp) context, and registered with * the {@link EntityViewAccessProviderManager} in a context loader listener<br/> * <br/> * If the implementation throws a {@link SecurityException} during the course of this method, the * access will be directed to a login page or authentication method before being redirected back to * the implementation method<br/> * If you want to control the requests which make it through to this by format type you can * optionally implement {@link AccessFormats} * * @author Aaron Zeckoski (upchh@example.com) */ public interface EntityViewAccessProvider { /** * Make and return the data responses for this type of data provider for a specific entity view * and entity reference (contained within the entity view), * use the request to get any additional sent in information you may need or want * and use the response to hold the output you generate<br/> * <br/> * <b>NOTE:</b> If you decide that you cannot handle this access request for any reason * you can either throw an {@link EntityException} to specify why OR throw a general {@link Exception}, * both will kill the request entirely but the general exception will pass through the system * while the {@link EntityException} will produce a handled result * * @param view an entity view, should contain all the information related to the incoming entity URL * @param req the servlet request (available in case you need to get anything out of it) * @param res the servlet response, put the correct data response into the outputstream * @throws FormatUnsupportedException if the format requested in the view is not supported * @throws EntityException if there is a request processing/handling failure */ public void handleAccess(EntityView view, HttpServletRequest req, HttpServletResponse res); }
3e1f56a98f77e8f166962f296974e125c3ce323f
2,824
java
Java
src/main/java/com/chao/cloud/admin/vue/controller/MenuController.java
chaojunzi/chao-cloud-admin-vue
15c2c7b075cfb6ed56933298a394a5ce8265d535
[ "ECL-2.0", "Apache-2.0" ]
1
2019-09-20T06:43:38.000Z
2019-09-20T06:43:38.000Z
src/main/java/com/chao/cloud/admin/vue/controller/MenuController.java
chaojunzi/chao-cloud-admin-vue
15c2c7b075cfb6ed56933298a394a5ce8265d535
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/main/java/com/chao/cloud/admin/vue/controller/MenuController.java
chaojunzi/chao-cloud-admin-vue
15c2c7b075cfb6ed56933298a394a5ce8265d535
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
24.556522
70
0.712465
13,250
package com.chao.cloud.admin.vue.controller; import java.util.List; import javax.validation.constraints.NotNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.baomidou.mybatisplus.extension.api.R; import com.chao.cloud.admin.vue.dal.entity.SysMenu; import com.chao.cloud.admin.vue.service.SysMenuService; import com.chao.cloud.common.entity.Response; import com.chao.cloud.common.exception.BusinessException; /** * * @功能: * @author: 薛超 * @时间:2019年5月8日 * @version 2.0 */ @RequestMapping("/sys/menu") @Controller @Validated public class MenuController extends BaseController { String prefix = "sys/menu"; @Autowired private SysMenuService sysMenuService; @RequestMapping("/list") @ResponseBody R<List<SysMenu>> list() { return R.ok(sysMenuService.list()); } /** * 菜单选择 * @return */ @RequestMapping("/choose") @ResponseBody public R<List<SysMenu>> choose() { // 获取当前角色的权限 // UserDTO user = getUser(); // Set<String> perms = getUser().getPerms(); List<SysMenu> list = sysMenuService.list(); // list.stream().filter(l -> // perms.contains(l.getPerms())).collect(Collectors.toList()); return R.ok(list); } @RequestMapping("/add/{pId}") String add(Model model, @PathVariable("pId") Long pId) { model.addAttribute("pId", pId); if (pId == 0) { model.addAttribute("pName", "根目录"); } else { model.addAttribute("pName", sysMenuService.getById(pId).getName()); } return prefix + "/add"; } @RequestMapping("/edit/{id}") String edit(Model model, @PathVariable("id") Integer id) { SysMenu mdo = sysMenuService.getById(id); Integer pId = mdo.getParentId(); model.addAttribute("pId", pId); if (pId == 0) { model.addAttribute("pName", "根目录"); } else { model.addAttribute("pName", sysMenuService.getById(pId).getName()); } model.addAttribute("menu", mdo); return prefix + "/edit"; } @RequestMapping("/save") @ResponseBody Response<String> save(SysMenu menu) { if (sysMenuService.save(menu)) { return Response.ok(); } throw new BusinessException("保存失败"); } @RequestMapping("/update") @ResponseBody Response<String> update(SysMenu menu) { if (sysMenuService.updateById(menu)) { return Response.ok(); } throw new BusinessException("更新失败"); } @RequestMapping("/remove") @ResponseBody Response<String> remove(@NotNull Integer id) { // 递归删除 if (sysMenuService.recursionRemove(id)) { return Response.ok(); } throw new BusinessException("删除失败"); } }
3e1f57f5a19a79e322fbfebb1cc896b9526d6e0c
6,759
java
Java
src/test/java/com/github/dperezcabrera/ge/st/StateMachineInstanceTests.java
dperezcabrera/game-engine
1edc08d403fe7b5e06dd14f1b2d1e983f05c60ff
[ "Apache-2.0" ]
null
null
null
src/test/java/com/github/dperezcabrera/ge/st/StateMachineInstanceTests.java
dperezcabrera/game-engine
1edc08d403fe7b5e06dd14f1b2d1e983f05c60ff
[ "Apache-2.0" ]
null
null
null
src/test/java/com/github/dperezcabrera/ge/st/StateMachineInstanceTests.java
dperezcabrera/game-engine
1edc08d403fe7b5e06dd14f1b2d1e983f05c60ff
[ "Apache-2.0" ]
null
null
null
38.254237
120
0.671983
13,251
/* * Copyright 2020 David Pérez Cabrera <anpch@example.com>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.dperezcabrera.ge.st; import com.github.dperezcabrera.ge.GameContext; import com.github.dperezcabrera.ge.annotations.Timeout; import java.util.Properties; import java.util.concurrent.Executors; import org.junit.jupiter.api.Test; import static org.assertj.core.api.BDDAssertions.then; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; /** * * @author David Pérez Cabrera <anpch@example.com> */ public class StateMachineInstanceTests { StateMachineInstance instance; StateMachineDefinition<State, Model> stateMachine; Model modelMock = mock(Model.class); StateTrigger<Model> trigger0Mock = mock(StateTrigger.class); StateTrigger<Model> trigger1Mock = mock(StateTrigger.class); StateTrigger<Model> trigger2Mock = mock(StateTrigger.class); PlayerStrategy player0Mock = mock(PlayerStrategy.class); PlayerStrategy player1Mock = mock(PlayerStrategy.class); PlayerStrategy player2Mock = mock(PlayerStrategy.class); Properties propertiesMock = mock(Properties.class); @Test public void testIsFinish() { stateMachine = StateMachineDefinitionBuilder.<State, Model> create(State.A) .add(state(State.A).trigger(trigger0Mock).transition(State.B)) .add(state(State.B).transition(State.D, c -> c.getScores() != null).transition(State.C)) .add(state(State.C).trigger(trigger2Mock).transition(State.D)).build(); given(propertiesMock.getProperty("timeout.getRandom")).willReturn("1000"); given(propertiesMock.containsKey("timeout.getRandom")).willReturn(true); given(player0Mock.getRandom(0L, 0)).willReturn(0); given(player1Mock.getRandom(0L, 1)).willThrow(RuntimeException.class); given(player2Mock.getRandom(0L, 2)).willAnswer((m) -> { synchronized (m) { m.wait(500); } return 1; }); instance = stateMachine.startInstance(modelMock); then(instance.isFinish()).isFalse(); } public static StateMachineDefinitionBuilder.StateTriggerBuilder<State, Model> state(State state) { return StateMachineDefinitionBuilder.StateTriggerBuilder.<State, Model> state(state); } @Timeout("timeout.getRandom") public interface PlayerStrategy { public Integer getRandom(Long seed, Integer size); } public static class Model extends GameContext<PlayerStrategy> { } public enum State { A, B, C, D } /** * Test of execute method, of class StateMachineInstance. * * @throws java.lang.InterruptedException */ @Test public void testExecuteAlreadyRunning() throws InterruptedException { final Object mutex = new Object(); trigger2Mock = c -> { try { synchronized (mutex) { mutex.notify(); } synchronized (c) { c.wait(); } } catch (InterruptedException ex) { } }; stateMachine = StateMachineDefinitionBuilder.<State, Model> create(State.A) .add(state(State.A).trigger(trigger0Mock).transition(State.B)).add(state(State.B).transition(State.C)) .add(state(State.C).trigger(trigger2Mock).transition(State.D)).build(); given(player0Mock.getRandom(0L, 0)).willReturn(0); given(player1Mock.getRandom(0L, 1)).willReturn(0); given(player2Mock.getRandom(0L, 2)).willReturn(0); instance = stateMachine.startInstance(modelMock); Executors.newFixedThreadPool(1).submit(() -> instance.execute()); synchronized (mutex) { mutex.wait(); } assertThrows(StateMachineException.class, () -> instance.execute(), "This instance is already running"); } @Test public void testExecuteFinished() { StateMachineDefinition<State, Model> stateMachine = StateMachineDefinitionBuilder.<State, Model> create(State.A) .add(state(State.A).trigger(trigger0Mock).transition(State.B)) .add(state(State.B).transition(State.D, c -> c.getScores() != null).transition(State.C)) .add(state(State.C).trigger(trigger2Mock).transition(State.D)).build(); given(player0Mock.getRandom(0L, 0)).willReturn(0); given(player1Mock.getRandom(0L, 1)).willReturn(1); given(player2Mock.getRandom(0L, 2)).willReturn(2); StateMachineInstance instance = stateMachine.startInstance(modelMock); instance.execute(); assertThrows(StateMachineException.class, () -> instance.execute(), "This instance has been executed"); } @Test public void testExecuteException() { StateMachineDefinition<State, Model> stateMachine = StateMachineDefinitionBuilder.<State, Model> create(State.A) .add(state(State.A).trigger(trigger0Mock).transition(State.B)) .add(state(State.B).transition(State.D, c -> c.getScores() != null).transition(State.C)) .add(state(State.C).trigger(trigger2Mock).transition(State.D)).build(); willThrow(new RuntimeException("Unexpected Error")).given(trigger0Mock).execute(any(Model.class)); given(player0Mock.getRandom(0L, 0)).willReturn(0); given(player1Mock.getRandom(0L, 1)).willReturn(1); given(player2Mock.getRandom(0L, 2)).willReturn(2); assertThrows(StateMachineException.class, () -> stateMachine.startInstance(modelMock).execute(), "There is an error"); } /** * Test of getContext method, of class StateMachineInstance. */ @Test public void testGetContext() { StateMachineDefinition<State, Model> stateMachineMock = mock(StateMachineDefinition.class); Model result = new StateMachineInstance<>(modelMock, stateMachineMock, State.A).getContext(); then(result).isEqualTo(modelMock); } }
3e1f580a915c56ae47067476d517ee745c7ce117
2,139
java
Java
jmix-ui/ui/src/main/java/io/jmix/ui/widget/listselect/JmixAbstractListSelect.java
pierresj/jmix
df2da30df1e0bb7a10ffba3a98e16e9dc4d31318
[ "Apache-2.0" ]
30
2019-02-26T07:42:11.000Z
2022-03-31T16:46:03.000Z
jmix-ui/ui/src/main/java/io/jmix/ui/widget/listselect/JmixAbstractListSelect.java
pierresj/jmix
df2da30df1e0bb7a10ffba3a98e16e9dc4d31318
[ "Apache-2.0" ]
909
2019-02-26T08:29:19.000Z
2022-03-31T16:56:18.000Z
jmix-ui/ui/src/main/java/io/jmix/ui/widget/listselect/JmixAbstractListSelect.java
pierresj/jmix
df2da30df1e0bb7a10ffba3a98e16e9dc4d31318
[ "Apache-2.0" ]
15
2019-05-08T19:17:03.000Z
2022-03-31T06:24:22.000Z
32.409091
91
0.635344
13,252
/* * Copyright 2020 Haulmont. * * 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.jmix.ui.widget.listselect; import com.vaadin.data.provider.ListDataProvider; import com.vaadin.data.provider.Query; import com.vaadin.ui.ListSelect; import io.jmix.ui.widget.client.listselect.JmixListSelectServerRpc; import java.util.function.Consumer; /** * @param <V> item type */ public abstract class JmixAbstractListSelect<V> extends ListSelect<V> { protected Consumer<V> doubleClickHandler; protected JmixListSelectServerRpc listSelectServerRpc = new JmixListSelectServerRpc() { @SuppressWarnings("unchecked") @Override public void onDoubleClick(Integer itemIndex) { if (doubleClickHandler != null && itemIndex >= 0) { ListDataProvider<V> container = (ListDataProvider<V>) getDataProvider(); if (container != null && itemIndex < container.size(new Query<>())) { int count = 0; for (V item : container.getItems()) { if (count == itemIndex) { doubleClickHandler.accept(item); break; } count++; } } } } }; public JmixAbstractListSelect() { registerRpc(listSelectServerRpc); } public Consumer<V> getDoubleClickHandler() { return doubleClickHandler; } public void setDoubleClickHandler(Consumer<V> doubleClickHandler) { this.doubleClickHandler = doubleClickHandler; } }
3e1f59b3acc38b515091c84dfcddabe53b6f4bb4
728
java
Java
Exam/src/hang/Hang.java
SJY0000/JAVA-STDUY
2a68d97ae8a02706fcfcbee4155a42794b710196
[ "MIT" ]
null
null
null
Exam/src/hang/Hang.java
SJY0000/JAVA-STDUY
2a68d97ae8a02706fcfcbee4155a42794b710196
[ "MIT" ]
null
null
null
Exam/src/hang/Hang.java
SJY0000/JAVA-STDUY
2a68d97ae8a02706fcfcbee4155a42794b710196
[ "MIT" ]
null
null
null
16.930233
48
0.653846
13,253
package hang; import java.util.Scanner; public class Hang { private boolean running = true; RandomWord word = new RandomWord(); Scanner scanner = new Scanner(System.in); public void run() { do { displayWord(); getInUserinput(); checkUserInput(); } while (running); } private void displayWord() { System.out.println(word.toString()); } private void getInUserinput() { System.out.print("하나의 문자 입력 : "); String guess = scanner.nextLine(); word.addGuess(guess.charAt(0)); } private void checkUserInput() { if (word.isCompleted()) { System.out.println("잘 맞췄어요!"); System.out.println("정답은 " + word.toString()); running = false; } } public void close() { scanner.close(); } }