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
923d140dcf3fa7461fb0995b1bb4a47030c6d0e1
956
java
Java
core/src/main/java/com/alibaba/alink/params/dl/HasUserFiles.java
zhangjun0x01/Alink
c1cd3380bed29a4be4eb058a7462213869c02387
[ "Apache-2.0" ]
3,301
2018-10-01T16:30:44.000Z
2022-03-30T08:07:16.000Z
core/src/main/java/com/alibaba/alink/params/dl/HasUserFiles.java
zhangjun0x01/Alink
c1cd3380bed29a4be4eb058a7462213869c02387
[ "Apache-2.0" ]
206
2019-11-27T14:04:42.000Z
2022-03-28T08:02:05.000Z
core/src/main/java/com/alibaba/alink/params/dl/HasUserFiles.java
zhangjun0x01/Alink
c1cd3380bed29a4be4eb058a7462213869c02387
[ "Apache-2.0" ]
765
2018-10-09T02:02:19.000Z
2022-03-31T12:06:21.000Z
29.875
82
0.773013
1,000,167
package com.alibaba.alink.params.dl; import org.apache.flink.ml.api.misc.param.ParamInfo; import org.apache.flink.ml.api.misc.param.ParamInfoFactory; import org.apache.flink.ml.api.misc.param.WithParams; import com.alibaba.alink.common.dl.ExternalFilesConfig; public interface HasUserFiles<T> extends WithParams <T> { ParamInfo <String> USER_FILES = ParamInfoFactory .createParamInfo("userFiles", String.class) .setAlias(new String[] {"userFile", "scriptFiles"}) .setDescription("userFiles") .build(); default ExternalFilesConfig getUserFiles() { return ExternalFilesConfig.fromJson(get(USER_FILES)); } default T setUserFiles(String value) { return set(USER_FILES, value); } default T setUserFiles(String[] values) { return set(USER_FILES, new ExternalFilesConfig().addFilePaths(values).toJson()); } default T setUserFiles(ExternalFilesConfig externalFilesConfig) { return set(USER_FILES, externalFilesConfig.toJson()); } }
923d1445523994541ee504e9376aa464f0bc912e
1,333
java
Java
dataset/tmp/prototype/src/main/java/com/ramesh/gof/prototype/HeroFactory.java
jpduque/cerbero
9650c2f9056240ce79561abe2e4e29b0e946b4f5
[ "MIT" ]
null
null
null
dataset/tmp/prototype/src/main/java/com/ramesh/gof/prototype/HeroFactory.java
jpduque/cerbero
9650c2f9056240ce79561abe2e4e29b0e946b4f5
[ "MIT" ]
null
null
null
dataset/tmp/prototype/src/main/java/com/ramesh/gof/prototype/HeroFactory.java
jpduque/cerbero
9650c2f9056240ce79561abe2e4e29b0e946b4f5
[ "MIT" ]
null
null
null
34.179487
80
0.747187
1,000,168
/** * The MIT License * Copyright (c) 2014 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.ramesh.gof.prototype; /** * * Interface for the factory class. * */ public interface HeroFactory { Mage createMage(); Warlord createWarlord(); Beast createBeast(); }
923d15103e237ee4f8ea751ebf49f11fa5ed793f
7,791
java
Java
sources/p026rx/p390c/p393c/C14780c.java
tusharchoudhary0003/Custom-Football-Game
47283462b2066ad5c53b3c901182e7ae62a34fc8
[ "MIT" ]
1
2019-10-01T11:34:10.000Z
2019-10-01T11:34:10.000Z
sources/p026rx/p390c/p393c/C14780c.java
tusharchoudhary0003/Custom-Football-Game
47283462b2066ad5c53b3c901182e7ae62a34fc8
[ "MIT" ]
null
null
null
sources/p026rx/p390c/p393c/C14780c.java
tusharchoudhary0003/Custom-Football-Game
47283462b2066ad5c53b3c901182e7ae62a34fc8
[ "MIT" ]
1
2020-05-26T05:10:33.000Z
2020-05-26T05:10:33.000Z
30.433594
112
0.554358
1,000,169
package p026rx.p390c.p393c; import java.util.Iterator; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import p026rx.C0126V; import p026rx.C0126V.C0127a; import p026rx.C0137ja; import p026rx.p027b.C0128a; import p026rx.p029i.C0136c; import p026rx.p029i.C14978f; import p026rx.p390c.p395e.C14882j; /* renamed from: rx.c.c.c */ /* compiled from: CachedThreadScheduler */ public final class C14780c extends C0126V implements C14809t { /* renamed from: a */ private static final long f43970a = ((long) Integer.getInteger("rx.io-scheduler.keepalive", 60).intValue()); /* renamed from: b */ private static final TimeUnit f43971b = TimeUnit.SECONDS; /* renamed from: c */ static final C14783c f43972c = new C14783c(C14882j.f44169a); /* renamed from: d */ static final C14781a f43973d = new C14781a(null, 0, null); /* renamed from: e */ final ThreadFactory f43974e; /* renamed from: f */ final AtomicReference<C14781a> f43975f = new AtomicReference<>(f43973d); /* renamed from: rx.c.c.c$a */ /* compiled from: CachedThreadScheduler */ static final class C14781a { /* renamed from: a */ private final ThreadFactory f43976a; /* renamed from: b */ private final long f43977b; /* renamed from: c */ private final ConcurrentLinkedQueue<C14783c> f43978c; /* renamed from: d */ private final C0136c f43979d; /* renamed from: e */ private final ScheduledExecutorService f43980e; /* renamed from: f */ private final Future<?> f43981f; C14781a(ThreadFactory threadFactory, long keepAliveTime, TimeUnit unit) { this.f43976a = threadFactory; this.f43977b = unit != null ? unit.toNanos(keepAliveTime) : 0; this.f43978c = new ConcurrentLinkedQueue<>(); this.f43979d = new C0136c(); ScheduledExecutorService evictor = null; Future<?> task = null; if (unit != null) { evictor = Executors.newScheduledThreadPool(1, new C14778a(this, threadFactory)); C14801p.m46461c(evictor); C14779b bVar = new C14779b(this); long j = this.f43977b; task = evictor.scheduleWithFixedDelay(bVar, j, j, TimeUnit.NANOSECONDS); } this.f43980e = evictor; this.f43981f = task; } /* access modifiers changed from: 0000 */ /* renamed from: b */ public C14783c mo45925b() { if (this.f43979d.isUnsubscribed()) { return C14780c.f43972c; } while (!this.f43978c.isEmpty()) { C14783c threadWorker = (C14783c) this.f43978c.poll(); if (threadWorker != null) { return threadWorker; } } C14783c w = new C14783c(this.f43976a); this.f43979d.mo3713a((C0137ja) w); return w; } /* access modifiers changed from: 0000 */ /* renamed from: a */ public void mo45924a(C14783c threadWorker) { threadWorker.mo45928a(mo45926c() + this.f43977b); this.f43978c.offer(threadWorker); } /* access modifiers changed from: 0000 */ /* renamed from: a */ public void mo45923a() { if (!this.f43978c.isEmpty()) { long currentTimestamp = mo45926c(); Iterator i$ = this.f43978c.iterator(); while (i$.hasNext()) { C14783c threadWorker = (C14783c) i$.next(); if (threadWorker.mo45929d() > currentTimestamp) { return; } if (this.f43978c.remove(threadWorker)) { this.f43979d.mo3714b(threadWorker); } } } } /* access modifiers changed from: 0000 */ /* renamed from: c */ public long mo45926c() { return System.nanoTime(); } /* access modifiers changed from: 0000 */ /* renamed from: d */ public void mo45927d() { try { if (this.f43981f != null) { this.f43981f.cancel(true); } if (this.f43980e != null) { this.f43980e.shutdownNow(); } } finally { this.f43979d.unsubscribe(); } } } /* renamed from: rx.c.c.c$b */ /* compiled from: CachedThreadScheduler */ static final class C14782b extends C0127a implements C0128a { /* renamed from: a */ private final C0136c f43982a = new C0136c(); /* renamed from: b */ private final C14781a f43983b; /* renamed from: c */ private final C14783c f43984c; /* renamed from: d */ final AtomicBoolean f43985d; C14782b(C14781a pool) { this.f43983b = pool; this.f43985d = new AtomicBoolean(); this.f43984c = pool.mo45925b(); } public void unsubscribe() { if (this.f43985d.compareAndSet(false, true)) { this.f43984c.mo3707a((C0128a) this); } this.f43982a.unsubscribe(); } public void call() { this.f43983b.mo45924a(this.f43984c); } public boolean isUnsubscribed() { return this.f43982a.isUnsubscribed(); } /* renamed from: a */ public C0137ja mo3707a(C0128a action) { return mo3709a(action, 0, null); } /* renamed from: a */ public C0137ja mo3709a(C0128a action, long delayTime, TimeUnit unit) { if (this.f43982a.isUnsubscribed()) { return C14978f.m46782b(); } C14805s s = this.f43984c.mo45937b(new C14784d(this, action), delayTime, unit); this.f43982a.mo3713a((C0137ja) s); s.mo45941a(this.f43982a); return s; } } /* renamed from: rx.c.c.c$c */ /* compiled from: CachedThreadScheduler */ static final class C14783c extends C14801p { /* renamed from: i */ private long f43986i = 0; C14783c(ThreadFactory threadFactory) { super(threadFactory); } /* renamed from: d */ public long mo45929d() { return this.f43986i; } /* renamed from: a */ public void mo45928a(long expirationTime) { this.f43986i = expirationTime; } } static { f43972c.unsubscribe(); f43973d.mo45927d(); } public C14780c(ThreadFactory threadFactory) { this.f43974e = threadFactory; start(); } public void start() { C14781a update = new C14781a(this.f43974e, f43970a, f43971b); if (!this.f43975f.compareAndSet(f43973d, update)) { update.mo45927d(); } } public void shutdown() { C14781a curr; C14781a aVar; do { curr = (C14781a) this.f43975f.get(); aVar = f43973d; if (curr == aVar) { return; } } while (!this.f43975f.compareAndSet(curr, aVar)); curr.mo45927d(); } public C0127a createWorker() { return new C14782b((C14781a) this.f43975f.get()); } }
923d1619282d23451d5d21e8f2473b32197acd90
1,427
java
Java
chrome/android/java/src/org/chromium/chrome/browser/services/gcm/GCMBackgroundServiceImpl.java
sunlongbo/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/android/java/src/org/chromium/chrome/browser/services/gcm/GCMBackgroundServiceImpl.java
sunlongbo/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/android/java/src/org/chromium/chrome/browser/services/gcm/GCMBackgroundServiceImpl.java
sunlongbo/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
36.589744
98
0.747722
1,000,170
// 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.services.gcm; import android.annotation.TargetApi; import android.content.Intent; import android.os.Build; import android.os.Bundle; import org.chromium.base.Log; import org.chromium.base.task.PostTask; import org.chromium.components.gcm_driver.GCMMessage; import org.chromium.content_public.browser.UiThreadTaskTraits; /** * Service that dispatches a GCM message in the background. Launched from ChromeGcmListenerService * if we received a high priority push message, as that should allow us to start a background * service even if Chrome is not running. */ @TargetApi(Build.VERSION_CODES.N) public class GCMBackgroundServiceImpl extends GCMBackgroundService.Impl { private static final String TAG = "GCMBackgroundService"; @Override protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras(); GCMMessage message = GCMMessage.createFromBundle(extras); if (message == null) { Log.e(TAG, "The received bundle containing message data could not be validated."); return; } PostTask.runSynchronously(UiThreadTaskTraits.DEFAULT, () -> ChromeGcmListenerServiceImpl.dispatchMessageToDriver(message)); } }
923d1638d4c6823aa37cab48525a64007496552b
1,567
java
Java
server/src/main/java/com/blocklang/marketplace/service/impl/GitRepoPublishTaskServiceImpl.java
blocklang/blocklang.com
939074c9df037c0780e01e9a73ee724b3dcc1dc0
[ "MIT" ]
38
2019-01-28T10:32:24.000Z
2022-03-14T15:17:35.000Z
server/src/main/java/com/blocklang/marketplace/service/impl/GitRepoPublishTaskServiceImpl.java
blocklang/blocklang-release
939074c9df037c0780e01e9a73ee724b3dcc1dc0
[ "MIT" ]
515
2019-02-08T14:26:27.000Z
2022-01-15T01:23:22.000Z
server/src/main/java/com/blocklang/marketplace/service/impl/GitRepoPublishTaskServiceImpl.java
blocklang/blocklang-release
939074c9df037c0780e01e9a73ee724b3dcc1dc0
[ "MIT" ]
16
2019-04-08T08:07:08.000Z
2022-03-10T07:03:26.000Z
33.340426
122
0.799617
1,000,171
package com.blocklang.marketplace.service.impl; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.blocklang.core.service.UserService; import com.blocklang.marketplace.dao.GitRepoPublishTaskDao; import com.blocklang.marketplace.model.GitRepoPublishTask; import com.blocklang.marketplace.service.GitRepoPublishTaskService; import com.blocklang.release.constant.ReleaseResult; @Service public class GitRepoPublishTaskServiceImpl implements GitRepoPublishTaskService{ @Autowired private GitRepoPublishTaskDao gitRepoPublishTaskDao; @Autowired private UserService userService; @Override public GitRepoPublishTask save(GitRepoPublishTask task) { Integer maxSeq = gitRepoPublishTaskDao .findFirstByGitUrlAndCreateUserIdOrderBySeqDesc(task.getGitUrl(), task.getCreateUserId()) .map(GitRepoPublishTask::getSeq) .orElse(0); task.setSeq(maxSeq + 1); return gitRepoPublishTaskDao.save(task); } @Override public List<GitRepoPublishTask> findUserPublishingTasks(Integer userId) { return gitRepoPublishTaskDao.findAllByCreateUserIdAndPublishResultOrderByCreateTimeDesc(userId, ReleaseResult.STARTED); } @Override public Optional<GitRepoPublishTask> findById(Integer taskId) { return gitRepoPublishTaskDao.findById(taskId).map(task ->{ userService.findById(task.getCreateUserId()).ifPresent(user -> task.setCreateUserName(user.getLoginName())); return task; }); } }
923d176a412ba6346918fbc5d30efb80687196d9
2,460
java
Java
src/test/java/com/github/ingogriebsch/sample/spring/boot/graphql/repository/ContinentRepositoryTest.java
ingogriebsch/sample-spring-boot-graphql
e93b6a1ce7e9308454b12f050d0e1ccbb1a8a8ac
[ "Apache-2.0" ]
1
2021-03-17T02:34:40.000Z
2021-03-17T02:34:40.000Z
src/test/java/com/github/ingogriebsch/sample/spring/boot/graphql/repository/ContinentRepositoryTest.java
ingogriebsch/sample-spring-boot-graphql
e93b6a1ce7e9308454b12f050d0e1ccbb1a8a8ac
[ "Apache-2.0" ]
6
2019-02-04T20:02:43.000Z
2019-02-04T20:02:56.000Z
src/test/java/com/github/ingogriebsch/sample/spring/boot/graphql/repository/ContinentRepositoryTest.java
ingogriebsch/sample-spring-boot-graphql
e93b6a1ce7e9308454b12f050d0e1ccbb1a8a8ac
[ "Apache-2.0" ]
1
2021-03-17T02:34:42.000Z
2021-03-17T02:34:42.000Z
39.677419
129
0.769106
1,000,172
/* * Copyright 2019 Ingo Griebsch * 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.ingogriebsch.sample.spring.boot.graphql.repository; import static org.assertj.core.api.Assertions.assertThat; import java.util.Optional; import com.github.ingogriebsch.sample.spring.boot.graphql.model.Continent; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner; @DataJpaTest @RunWith(SpringRunner.class) public class ContinentRepositoryTest { @Autowired private ContinentRepository continentRepository; @Autowired private TestEntityManager testEntityManager; @Test public void findByName_should_return_empty_optional_if_called_with_null() throws Exception { Optional<Continent> continent = continentRepository.findByName(null); assertThat(continent).isNotNull(); assertThat(continent.isPresent()).isFalse(); } @Test public void findByName_should_return_matching_continent_if_available() throws Exception { Continent continent = testEntityManager.persistAndFlush(new Continent("Continent")); Optional<Continent> found = continentRepository.findByName(continent.getName()); assertThat(found).isNotNull(); assertThat(found.isPresent()).isTrue(); assertThat(found.get()).isEqualTo(continent); } @Test public void findByName_should_return_empty_optional_if_not_available() throws Exception { testEntityManager.persistAndFlush(new Continent("Continent")); Optional<Continent> found = continentRepository.findByName("Some completely different continent"); assertThat(found).isNotNull(); assertThat(found.isPresent()).isFalse(); } }
923d17b0f67486f9d99d0b0a56b28d190af88e05
2,394
java
Java
src/main/java/controller/SearchController.java
UNIZAR-30226-PROYS/Backend-1
6e43d9465025689f3c3afbf3df2a082a39d175f3
[ "MIT" ]
null
null
null
src/main/java/controller/SearchController.java
UNIZAR-30226-PROYS/Backend-1
6e43d9465025689f3c3afbf3df2a082a39d175f3
[ "MIT" ]
null
null
null
src/main/java/controller/SearchController.java
UNIZAR-30226-PROYS/Backend-1
6e43d9465025689f3c3afbf3df2a082a39d175f3
[ "MIT" ]
2
2018-04-29T16:14:32.000Z
2019-03-09T10:05:29.000Z
39.9
122
0.662907
1,000,173
package main.java.controller; import main.java.model.Cancion; import main.java.model.Listarep; import main.java.model.Usuario; 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 javax.servlet.http.HttpSession; import java.io.IOException; import java.util.List; @WebServlet(name = "SearchController", urlPatterns = "/search") public class SearchController extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String search = request.getParameter("search_input"); String UA = request.getHeader("User-Agent"); HttpSession session = request.getSession(true); Usuario username = (Usuario) session.getAttribute("username"); username.setConexion(); // Actualiza estado de conexion del usuario username.saveUser(); RequestDispatcher rd; List<Listarep> listas = null; List<Cancion> canciones = null; List<Usuario> usuarios = null; if (!search.equals("")) { System.out.println("Cadena no vacia"); listas = Listarep.searchList(search); canciones = Cancion.searchSong(search); usuarios = Usuario.searchUser(search); request.setAttribute("listas", listas); request.setAttribute("usuarios", usuarios); request.setAttribute("canciones", canciones); request.setAttribute("consulta", search); if (UA.contains("Mobile")) { rd = request.getRequestDispatcher("/movil/resultados.jsp"); } else { rd = request.getRequestDispatcher("/escritorio/resultados.jsp"); } rd.forward(request, response); } else { System.out.println("Cadena vacia"); if (UA.contains("Mobile")) { response.sendRedirect("/movil/explorar.jsp"); } else { response.sendRedirect("/escritorio/explorar.jsp"); } } } }
923d1919eb5a96f80bd3d152ef69e661ac148077
742
java
Java
com/raytracer/filter/color/BlendColorFilter.java
MitchellJAllen/ImageFilterRayTracer
e8b84a0940062c92be96d9735963e2cbf5521fb5
[ "MIT" ]
null
null
null
com/raytracer/filter/color/BlendColorFilter.java
MitchellJAllen/ImageFilterRayTracer
e8b84a0940062c92be96d9735963e2cbf5521fb5
[ "MIT" ]
null
null
null
com/raytracer/filter/color/BlendColorFilter.java
MitchellJAllen/ImageFilterRayTracer
e8b84a0940062c92be96d9735963e2cbf5521fb5
[ "MIT" ]
null
null
null
21.823529
84
0.762803
1,000,174
package com.raytracer.filter.color; import com.raytracer.math.vector.Vector4; public class BlendColorFilter extends ColorFilter { private Vector4 blendColor; private float intensity; public BlendColorFilter(Vector4 blendColor, float intensity) { this.blendColor = blendColor; this.intensity = intensity; } public Vector4 getBlendColor() { return this.blendColor; } public void setBlendColor(Vector4 blendColor) { this.blendColor = blendColor; } public float getIntensity() { return this.intensity; } public void setIntensity(float intensity) { this.intensity = intensity; } public Vector4 processColor(Vector4 color) { return this.blendColor.scale(this.intensity).add(color.scale(1 - this.intensity)); } }
923d1a18a0d748a8d34b8349bb66f1c67cf4e126
4,846
java
Java
build/tmp/expandedArchives/forge-1.18.1-39.0.0_mapped_official_1.18.1-sources.jar_f6a4a89164f1bd9335800eaab8a74a09/net/minecraft/world/entity/vehicle/MinecartCommandBlock.java
AlgorithmLX/IndustrialLevel
727d90a9404c2967ec2d3ba8dadbd1276b1ad81f
[ "MIT" ]
null
null
null
build/tmp/expandedArchives/forge-1.18.1-39.0.0_mapped_official_1.18.1-sources.jar_f6a4a89164f1bd9335800eaab8a74a09/net/minecraft/world/entity/vehicle/MinecartCommandBlock.java
AlgorithmLX/IndustrialLevel
727d90a9404c2967ec2d3ba8dadbd1276b1ad81f
[ "MIT" ]
1
2022-02-23T20:43:13.000Z
2022-02-23T21:04:55.000Z
build/tmp/expandedArchives/forge-1.18.1-39.0.0_mapped_official_1.18.1-sources.jar_f6a4a89164f1bd9335800eaab8a74a09/net/minecraft/world/entity/vehicle/MinecartCommandBlock.java
AlgorithmLX/IndustrialLevel
727d90a9404c2967ec2d3ba8dadbd1276b1ad81f
[ "MIT" ]
null
null
null
40.383333
278
0.756294
1,000,175
package net.minecraft.world.entity.vehicle; import net.minecraft.commands.CommandSourceStack; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.TextComponent; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.BaseCommandBlock; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; public class MinecartCommandBlock extends AbstractMinecart { static final EntityDataAccessor<String> DATA_ID_COMMAND_NAME = SynchedEntityData.defineId(MinecartCommandBlock.class, EntityDataSerializers.STRING); static final EntityDataAccessor<Component> DATA_ID_LAST_OUTPUT = SynchedEntityData.defineId(MinecartCommandBlock.class, EntityDataSerializers.COMPONENT); private final BaseCommandBlock commandBlock = new MinecartCommandBlock.MinecartCommandBase(); private static final int ACTIVATION_DELAY = 4; private int lastActivated; public MinecartCommandBlock(EntityType<? extends MinecartCommandBlock> p_38509_, Level p_38510_) { super(p_38509_, p_38510_); } public MinecartCommandBlock(Level p_38512_, double p_38513_, double p_38514_, double p_38515_) { super(EntityType.COMMAND_BLOCK_MINECART, p_38512_, p_38513_, p_38514_, p_38515_); } protected void defineSynchedData() { super.defineSynchedData(); this.getEntityData().define(DATA_ID_COMMAND_NAME, ""); this.getEntityData().define(DATA_ID_LAST_OUTPUT, TextComponent.EMPTY); } protected void readAdditionalSaveData(CompoundTag p_38525_) { super.readAdditionalSaveData(p_38525_); this.commandBlock.load(p_38525_); this.getEntityData().set(DATA_ID_COMMAND_NAME, this.getCommandBlock().getCommand()); this.getEntityData().set(DATA_ID_LAST_OUTPUT, this.getCommandBlock().getLastOutput()); } protected void addAdditionalSaveData(CompoundTag p_38529_) { super.addAdditionalSaveData(p_38529_); this.commandBlock.save(p_38529_); } public AbstractMinecart.Type getMinecartType() { return AbstractMinecart.Type.COMMAND_BLOCK; } public BlockState getDefaultDisplayBlockState() { return Blocks.COMMAND_BLOCK.defaultBlockState(); } public BaseCommandBlock getCommandBlock() { return this.commandBlock; } public void activateMinecart(int p_38517_, int p_38518_, int p_38519_, boolean p_38520_) { if (p_38520_ && this.tickCount - this.lastActivated >= 4) { this.getCommandBlock().performCommand(this.level); this.lastActivated = this.tickCount; } } public InteractionResult interact(Player p_38522_, InteractionHand p_38523_) { InteractionResult ret = super.interact(p_38522_, p_38523_); if (ret.consumesAction()) return ret; return this.commandBlock.usedBy(p_38522_); } public void onSyncedDataUpdated(EntityDataAccessor<?> p_38527_) { super.onSyncedDataUpdated(p_38527_); if (DATA_ID_LAST_OUTPUT.equals(p_38527_)) { try { this.commandBlock.setLastOutput(this.getEntityData().get(DATA_ID_LAST_OUTPUT)); } catch (Throwable throwable) { } } else if (DATA_ID_COMMAND_NAME.equals(p_38527_)) { this.commandBlock.setCommand(this.getEntityData().get(DATA_ID_COMMAND_NAME)); } } public boolean onlyOpCanSetNbt() { return true; } public class MinecartCommandBase extends BaseCommandBlock { public ServerLevel getLevel() { return (ServerLevel)MinecartCommandBlock.this.level; } public void onUpdated() { MinecartCommandBlock.this.getEntityData().set(MinecartCommandBlock.DATA_ID_COMMAND_NAME, this.getCommand()); MinecartCommandBlock.this.getEntityData().set(MinecartCommandBlock.DATA_ID_LAST_OUTPUT, this.getLastOutput()); } public Vec3 getPosition() { return MinecartCommandBlock.this.position(); } public MinecartCommandBlock getMinecart() { return MinecartCommandBlock.this; } public CommandSourceStack createCommandSourceStack() { return new CommandSourceStack(this, MinecartCommandBlock.this.position(), MinecartCommandBlock.this.getRotationVector(), this.getLevel(), 2, this.getName().getString(), MinecartCommandBlock.this.getDisplayName(), this.getLevel().getServer(), MinecartCommandBlock.this); } } }
923d1a9099bb481ba7efae32bc14b61f4ed5e90c
1,296
java
Java
auth-server/src/main/java/org/springframework/security/oauth/samples/configproperties/Loginform.java
hubeixiang/spring-oauth2
f48812da110605f520d1e556b598b2c868606488
[ "Apache-2.0" ]
null
null
null
auth-server/src/main/java/org/springframework/security/oauth/samples/configproperties/Loginform.java
hubeixiang/spring-oauth2
f48812da110605f520d1e556b598b2c868606488
[ "Apache-2.0" ]
null
null
null
auth-server/src/main/java/org/springframework/security/oauth/samples/configproperties/Loginform.java
hubeixiang/spring-oauth2
f48812da110605f520d1e556b598b2c868606488
[ "Apache-2.0" ]
null
null
null
23.563636
72
0.669753
1,000,176
package org.springframework.security.oauth.samples.configproperties; public class Loginform { /** * 默认的登录页面url */ private String loginPageUrl = "/"; /** * 登录错误调转页面url */ private String loginErrorPageUrl = "/"; /** * 登录成功默认调转页面url */ private String loginDefaultSucessUrl = "/"; /** * 默认登录时,提交登录信息,服务进行处理的url * 只是用户密码,或者手机号码短信登录 */ private String defaultLoginPostUrl = "/login"; public String getLoginPageUrl() { return loginPageUrl; } public void setLoginPageUrl(String loginPageUrl) { this.loginPageUrl = loginPageUrl; } public String getLoginErrorPageUrl() { return loginErrorPageUrl; } public void setLoginErrorPageUrl(String loginErrorPageUrl) { this.loginErrorPageUrl = loginErrorPageUrl; } public String getLoginDefaultSucessUrl() { return loginDefaultSucessUrl; } public void setLoginDefaultSucessUrl(String loginDefaultSucessUrl) { this.loginDefaultSucessUrl = loginDefaultSucessUrl; } public String getDefaultLoginPostUrl() { return defaultLoginPostUrl; } public void setDefaultLoginPostUrl(String defaultLoginPostUrl) { this.defaultLoginPostUrl = defaultLoginPostUrl; } }
923d1aa59de960525a7c6245f86b9d28a98f0287
2,157
java
Java
connector/connector-kafka/src/main/java/org/apache/sqoop/connector/kafka/KafkaToInitializer.java
maheshsv/sqoop-on-spark
d4072165d49196f4789014fe545e70b6914a547c
[ "Apache-2.0" ]
53
2015-06-29T11:24:49.000Z
2021-12-06T02:48:29.000Z
connector/connector-kafka/src/main/java/org/apache/sqoop/connector/kafka/KafkaToInitializer.java
maheshsv/sqoop-on-spark
d4072165d49196f4789014fe545e70b6914a547c
[ "Apache-2.0" ]
3
2015-06-22T09:43:02.000Z
2020-02-03T16:32:27.000Z
connector/connector-kafka/src/main/java/org/apache/sqoop/connector/kafka/KafkaToInitializer.java
maheshsv/sqoop-on-spark
d4072165d49196f4789014fe545e70b6914a547c
[ "Apache-2.0" ]
46
2015-06-11T18:44:22.000Z
2021-12-03T04:32:04.000Z
41.480769
127
0.780714
1,000,177
/** * 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.sqoop.connector.kafka; import org.apache.log4j.Logger; import org.apache.sqoop.connector.kafka.configuration.ToJobConfiguration; import org.apache.sqoop.connector.kafka.configuration.LinkConfiguration; import org.apache.sqoop.job.etl.Initializer; import org.apache.sqoop.job.etl.InitializerContext; import org.apache.sqoop.utils.ClassUtils; import java.util.Set; public class KafkaToInitializer extends Initializer<LinkConfiguration,ToJobConfiguration> { private static final Logger LOG = Logger.getLogger(KafkaToInitializer.class); @Override public void initialize(InitializerContext context,LinkConfiguration linkConfiguration, ToJobConfiguration jobConfiguration) { LOG.info("Running Kafka Connector initializer. This does nothing except log this message."); } @Override public Set<String> getJars(InitializerContext context, LinkConfiguration linkConfiguration, ToJobConfiguration toJobConfiguration) { Set<String> jars = super.getJars(context, linkConfiguration, toJobConfiguration); // Jars for Kafka, Scala and Yammer (required by Kafka) jars.add(ClassUtils.jarForClass("kafka.javaapi.producer.Producer")); jars.add(ClassUtils.jarForClass("scala.collection.immutable.StringLike")); jars.add(ClassUtils.jarForClass("com.yammer.metrics.Metrics")); return jars; } }
923d1af9401b56b1ef6233d853a2da7eec4a7160
9,228
java
Java
app/src/main/java/com/ruesga/android/wallpapers/photophase/effects/ToonEffect.java
jruesga/PhotoPhase
78413fb87a5edbe31ff212e04107c7d2b5b4e382
[ "Apache-2.0" ]
39
2015-01-13T07:51:33.000Z
2021-09-26T19:06:02.000Z
app/src/main/java/com/ruesga/android/wallpapers/photophase/effects/ToonEffect.java
jruesga/PhotoPhase
78413fb87a5edbe31ff212e04107c7d2b5b4e382
[ "Apache-2.0" ]
10
2017-03-12T11:20:30.000Z
2020-08-17T15:09:33.000Z
app/src/main/java/com/ruesga/android/wallpapers/photophase/effects/ToonEffect.java
jruesga/PhotoPhase
78413fb87a5edbe31ff212e04107c7d2b5b4e382
[ "Apache-2.0" ]
15
2015-08-20T02:02:18.000Z
2021-08-29T02:40:46.000Z
38.773109
111
0.373862
1,000,178
// // https://github.com/spite/Wagner/blob/master/fragment-shaders/toon-fs.glsl // package com.ruesga.android.wallpapers.photophase.effects; import android.media.effect.EffectContext; import android.opengl.GLES20; import com.ruesga.android.wallpapers.photophase.utils.GLESUtil; /** * A cartoon effect<br/> * <table> * <tr><td>Parameter name</td><td>Meaning</td><td>Valid values</td></tr> * </table> */ public class ToonEffect extends PhotoPhaseEffect { private static final String FRAGMENT_SHADER = "precision mediump float;\n" + "uniform float w;\n" + "uniform float h;\n" + "uniform sampler2D tex_sampler;\n" + "varying vec2 v_texcoord;\n" + "\n" + "#define HueLevCount 6\n" + "#define SatLevCount 7\n" + "#define ValLevCount 4\n" + "float HueLevels[HueLevCount];\n" + "float SatLevels[SatLevCount];\n" + "float ValLevels[ValLevCount];\n" + "\n" + "vec3 RGBtoHSV(float r, float g, float b) {\n" + " float minv, maxv, delta;\n" + " vec3 res;\n" + "\n" + " minv = min(min(r, g), b);\n" + " maxv = max(max(r, g), b);\n" + " res.z = maxv;\n" + "\n" + " delta = maxv - minv;\n" + "\n" + " if( maxv != 0.0 )\n" + " res.y = delta / maxv;\n" + " else {\n" + " res.y = 0.0;\n" + " res.x = -1.0;\n" + " return res;\n" + " }\n" + "\n" + " if (r == maxv)\n" + " res.x = ( g - b ) / delta;\n" + " else if (g == maxv)\n" + " res.x = 2.0 + (b - r) / delta;\n" + " else\n" + " res.x = 4.0 + (r - g) / delta;\n" + "\n" + " res.x = res.x * 60.0;\n" + " if (res.x < 0.0)\n" + " res.x = res.x + 360.0;\n" + "\n" + " return res;\n" + "}\n" + "\n" + "vec3 HSVtoRGB(float h, float s, float v) {\n" + " int i;\n" + " float f, p, q, t;\n" + " vec3 res;\n" + "\n" + " if (s == 0.0) {\n" + " // achromatic (grey)\n" + " res.x = v;\n" + " res.y = v;\n" + " res.z = v;\n" + " return res;\n" + " }\n" + "\n" + " h /= 60.0;\n" + " i = int(floor(h));\n" + " f = h - float(i);\n" + " p = v * ( 1.0 - s );\n" + " q = v * ( 1.0 - s * f );\n" + " t = v * ( 1.0 - s * ( 1.0 - f ) );\n" + "\n" + " if (i==0) {\n" + " res.x = v;\n" + " res.y = t;\n" + " res.z = p;\n" + " } else if (i==1) {\n" + " res.x = q;\n" + " res.y = v;\n" + " res.z = p;\n" + " } else if (i==2) {\n" + " res.x = p;\n" + " res.y = v;\n" + " res.z = t;\n" + " } else if (i==3) {\n" + " res.x = p;\n" + " res.y = q;\n" + " res.z = v;\n" + " } else if (i==4) {\n" + " res.x = t;\n" + " res.y = p;\n" + " res.z = v;\n" + " } else if (i==5) {\n" + " res.x = v;\n" + " res.y = p;\n" + " res.z = q;\n" + " }\n" + "\n" + " return res;\n" + "}\n" + "\n" + "float nearestLevel(float col, int mode) {\n" + " if (mode==0) {\n" + " for (int i =0; i<HueLevCount-1; i++ ) {\n" + " if (col >= HueLevels[i] && col <= HueLevels[i+1]) {\n" + " return HueLevels[i+1];\n" + " }\n" + " }\n" + " }\n" + "\n" + " if (mode==1) {\n" + " for (int i =0; i<SatLevCount-1; i++ ) {\n" + " if (col >= SatLevels[i] && col <= SatLevels[i+1]) {\n" + " return SatLevels[i+1];\n" + " }\n" + " }\n" + " }\n" + "\n" + "\n" + " if (mode==2) {\n" + " for (int i =0; i<ValLevCount-1; i++ ) {\n" + " if (col >= ValLevels[i] && col <= ValLevels[i+1]) {\n" + " return ValLevels[i+1];\n" + " }\n" + " }\n" + " }\n" + "}\n" + "\n" + "float avg_intensity(vec4 pix) {\n" + " return (pix.r + pix.g + pix.b) / 3.;\n" + "}\n" + "\n" + "vec4 get_pixel(vec2 coords, float dx, float dy) {\n" + " return texture2D(tex_sampler, coords + vec2(dx, dy));\n" + "}\n" + "\n" + "float IsEdge(in vec2 coords){\n" + " float dxtex = 1.0 / w;\n" + " float dytex = 1.0 / h;\n" + "\n" + " float pix[9];\n" + "\n" + " int k = -1;\n" + " float delta;\n" + "\n" + " // read neighboring pixel intensities\n" + " float pix0 = avg_intensity(get_pixel(coords, -1.0 * dxtex, -1.0 * dytex));\n" + " float pix1 = avg_intensity(get_pixel(coords, -1.0 * dxtex, 0.0 * dytex));\n" + " float pix2 = avg_intensity(get_pixel(coords, -1.0 * dxtex, 1.0 * dytex));\n" + " float pix3 = avg_intensity(get_pixel(coords, 0.0 * dxtex, -1.0 * dytex));\n" + " float pix4 = avg_intensity(get_pixel(coords, 0.0 * dxtex, 0.0 * dytex));\n" + " float pix5 = avg_intensity(get_pixel(coords, 0.0 * dxtex, 1.0 * dytex));\n" + " float pix6 = avg_intensity(get_pixel(coords, 1.0 * dxtex, -1.0 * dytex));\n" + " float pix7 = avg_intensity(get_pixel(coords, 1.0 * dxtex, 0.0 * dytex));\n" + " float pix8 = avg_intensity(get_pixel(coords, 1.0 * dxtex, 1.0 * dytex));\n" + " delta = (abs(pix1 - pix7) + abs(pix5 - pix3) + abs(pix0 - pix8) + abs(pix2 - pix6)) / 4.;\n" + "\n" + " return clamp(5.5*delta,0.0,1.0);\n" + "}\n" + "\n" + "void main(void)\n" + "{\n" + " HueLevels[0] = 0.0;\n" + " HueLevels[1] = 80.0;\n" + " HueLevels[2] = 160.0;\n" + " HueLevels[3] = 240.0;\n" + " HueLevels[4] = 320.0;\n" + " HueLevels[5] = 360.0;\n" + "\n" + " SatLevels[0] = 0.0;\n" + " SatLevels[1] = 0.1;\n" + " SatLevels[2] = 0.3;\n" + " SatLevels[3] = 0.5;\n" + " SatLevels[4] = 0.6;\n" + " SatLevels[5] = 0.8;\n" + " SatLevels[6] = 1.0;\n" + "\n" + " ValLevels[0] = 0.0;\n" + " ValLevels[1] = 0.3;\n" + " ValLevels[2] = 0.6;\n" + " ValLevels[3] = 1.0;\n" + "\n" + " vec4 colorOrg = texture2D(tex_sampler, v_texcoord);\n" + " vec3 vHSV = RGBtoHSV(colorOrg.r, colorOrg.g, colorOrg.b);\n" + " vHSV.x = nearestLevel(vHSV.x, 0);\n" + " vHSV.y = nearestLevel(vHSV.y, 1);\n" + " vHSV.z = nearestLevel(vHSV.z, 2);\n" + " float edg = IsEdge(v_texcoord);\n" + " vec3 vRGB = (edg >= 0.3)? vec3(0.0, 0.0, 0.0) : HSVtoRGB(vHSV.x, vHSV.y, vHSV.z);\n" + " gl_FragColor = vec4(vRGB.x, vRGB.y, vRGB.z, 1.0);\n" + "}\n"; private final int mWidthHandle; private final int mHeightHandle; /** * Constructor of <code>ToonEffect</code>. * * @param ctx The effect context * @param name The effect name */ public ToonEffect(EffectContext ctx, String name) { super(ctx, ToonEffect.class.getName()); init(VERTEX_SHADER, FRAGMENT_SHADER); // Parameters mWidthHandle = GLES20.glGetUniformLocation(mProgram[0], "w"); GLESUtil.glesCheckError("glGetUniformLocation"); mHeightHandle = GLES20.glGetUniformLocation(mProgram[0], "h"); GLESUtil.glesCheckError("glGetUniformLocation"); } /** * {@inheritDoc} */ @Override void applyParameters(int width, int height) { // Set parameters GLES20.glUniform1f(mWidthHandle, (float) width); GLESUtil.glesCheckError("glUniform1f"); GLES20.glUniform1f(mHeightHandle, (float) height); GLESUtil.glesCheckError("glUniform1f"); } }
923d1c25360fa532ee027e9a73f01557eb367d37
16,465
java
Java
src/main/java/marc/henrard/book/algorithmicdifferentiation/finance/formula/BlackFormula.java
ChinaQuants/algorithmic-differentiation-book
509208ab7fc693fb371c554917dc90ebf805e15e
[ "Apache-2.0" ]
10
2016-09-02T14:02:29.000Z
2021-11-05T03:58:22.000Z
src/main/java/marc/henrard/book/algorithmicdifferentiation/finance/formula/BlackFormula.java
JamesLTaylor/algorithmic-differentiation-book
509208ab7fc693fb371c554917dc90ebf805e15e
[ "Apache-2.0" ]
null
null
null
src/main/java/marc/henrard/book/algorithmicdifferentiation/finance/formula/BlackFormula.java
JamesLTaylor/algorithmic-differentiation-book
509208ab7fc693fb371c554917dc90ebf805e15e
[ "Apache-2.0" ]
9
2017-07-11T06:26:16.000Z
2022-02-14T02:27:04.000Z
47.449568
123
0.693228
1,000,179
/** * Copyright (C) 2014 - present by Marc Henrard */ package marc.henrard.book.algorithmicdifferentiation.finance.formula; import cern.jet.random.Normal; import marc.henrard.book.algorithmicdifferentiation.mathad.MathAad; import marc.henrard.book.algorithmicdifferentiation.mathad.MathSad; import marc.henrard.book.algorithmicdifferentiation.tape.TapeAad; import marc.henrard.book.algorithmicdifferentiation.tape.TapeEntryAad; import marc.henrard.book.algorithmicdifferentiation.type.DoubleAad; import marc.henrard.book.algorithmicdifferentiation.type.DoubleDerivatives; import marc.henrard.book.algorithmicdifferentiation.type.DoubleSad; import marc.henrard.book.algorithmicdifferentiation.type.OperationTypeAad; /** * Implementation of the Black-Scholes formula for option pricing. * <p> * Implementation of the price and different algorithmic differentiation versions. * <p> * The mathematical library underlying is <a href="https://dst.lbl.gov/ACSSoftware/colt/index.html">Colt</a> */ public class BlackFormula { /* The normal distribution implementation. */ private static final Normal NORMAL = new Normal(0.0d, 1.0d, null); /** * Returns the option price computed by the Black-Scholes formula. * @param forward The forward price/rate. * @param volatility The log-normal volatility of the model. * @param numeraire The numeraire. * @param strike The strike price/rate. * @param expiry The time to expiry. * @param isCall The call (true) / put (false) flag. * @return The price. * @throws MathException */ public static double price( double forward, double volatility, double numeraire, double strike, double expiry, boolean isCall) { double periodVolatility = volatility * Math.sqrt(expiry); double dPlus = Math.log(forward / strike) / periodVolatility + 0.5d * periodVolatility; double dMinus = dPlus - periodVolatility; double omega = isCall ? 1.0d : -1.0d; double nPlus = NORMAL.cdf(omega * dPlus); double nMinus = NORMAL.cdf(omega * dMinus); double price = numeraire * omega * (forward * nPlus - strike * nMinus); return price; } /** * Returns the option price for the Black-Scholes formula and its derivatives with respect to * [0] forward, [1] volatility, [2] numeraire, [3] strike, and [4] expiry. * The derivatives are computed by Standard Algorithmic Differentiation. * @param forward The forward price/rate. * @param volatility The log-normal volatility of the model. * @param numeraire The numeraire. * @param strike The strike price/rate. * @param expiry The time to expiry. * @param isCall The call (true) / put (false) flag. * @return The price and derivatives. */ public static DoubleDerivatives price_Sad( double forward, double volatility, double numeraire, double strike, double expiry, boolean isCall) { // Forward sweep - function double omega = isCall ? 1.0d : -1.0d; double periodVolatility = volatility * Math.sqrt(expiry); double dPlus = Math.log(forward / strike) / periodVolatility + 0.5d * periodVolatility; double dMinus = dPlus - periodVolatility; double nPlus = NORMAL.cdf(omega * dPlus); double nMinus = NORMAL.cdf(omega * dMinus); double price = numeraire * omega * (forward * nPlus - strike * nMinus); // Forward sweep - derivatives int nbInputs = 5; double[] inputDot = new double[nbInputs]; for (int loopinput = 0; loopinput < nbInputs; loopinput++) { inputDot[loopinput] = 1.0d; } double[] periodVolatilityDot = new double[nbInputs]; periodVolatilityDot[1] = Math.sqrt(expiry) * inputDot[1]; periodVolatilityDot[4] = volatility * 0.5d / Math.sqrt(expiry) * inputDot[4]; double[] dPlusDot = new double[nbInputs]; for (int loopinput = 0; loopinput < nbInputs; loopinput++) { dPlusDot[loopinput] = (Math.log(forward / strike) * -1.0d / (periodVolatility * periodVolatility) + 0.5d) * periodVolatilityDot[loopinput]; } dPlusDot[0] += 1.0d / (periodVolatility * forward) * inputDot[0]; dPlusDot[3] += -1.0d / (periodVolatility * forward) * inputDot[3]; double[] dMinusDot = new double[nbInputs]; for (int loopinput = 0; loopinput < nbInputs; loopinput++) { dMinusDot[loopinput] = dPlusDot[loopinput] - periodVolatilityDot[loopinput]; } double[] nPlusDot = new double[nbInputs]; double nPdfpPlus = NORMAL.pdf(omega * dPlus); for (int loopinput = 0; loopinput < nbInputs; loopinput++) { nPlusDot[loopinput] = nPdfpPlus * omega * dPlusDot[loopinput]; } double[] nMinusDot = new double[nbInputs]; double nPdfdMinus = NORMAL.pdf(omega * dMinus); for (int loopinput = 0; loopinput < nbInputs; loopinput++) { nMinusDot[loopinput] = nPdfdMinus * omega * dMinusDot[loopinput]; } double[] priceDot = new double[nbInputs]; for (int loopinput = 0; loopinput < nbInputs; loopinput++) { priceDot[loopinput] = numeraire * omega * forward * nPlusDot[loopinput] - numeraire * omega * strike * nMinusDot[loopinput]; } priceDot[0] += numeraire * omega * nPlus * inputDot[0]; priceDot[2] += omega * (forward * nPlus - strike * nMinus) * inputDot[2]; priceDot[3] += -numeraire * omega * nMinus * inputDot[3]; return new DoubleDerivatives(price, priceDot); } /** * Returns the option price for the Black-Scholes formula and its derivatives with respect to * [0] forward, [1] volatility, [2] numeraire, [3] strike, and [4] expiry. * The derivatives are computed by Standard Algorithmic Differentiation. * @param forward The forward price/rate. * @param volatility The log-normal volatility of the model. * @param numeraire The numeraire. * @param strike The strike price/rate. * @param expiry The time to expiry. * @param isCall The call (true) / put (false) flag. * @return The price and derivatives. */ public static DoubleSad price_Sad_Automatic( double forward, double volatility, double numeraire, double strike, double expiry, boolean isCall) { int nbInputs = 5; double[] input = new double[nbInputs]; input[0] = forward; input[1] = volatility; input[2] = numeraire; input[3] = strike; input[4] = expiry; DoubleSad[] inputSad = DoubleSad.init(input); double omega = isCall ? 1.0d : -1.0d; DoubleSad periodVolatility = MathSad.multipliedBy(inputSad[1], MathSad.sqrt(inputSad[4])); DoubleSad dPlus = MathSad.plus( MathSad.dividedBy(MathSad.log(MathSad.dividedBy(inputSad[0], inputSad[3])), periodVolatility), MathSad.multipliedBy(periodVolatility, 0.5d)); DoubleSad dMinus = MathSad.minus(dPlus, periodVolatility); DoubleSad nPlus = MathSad.normalCdf(MathSad.multipliedBy(dPlus, omega)); DoubleSad nMinus = MathSad.normalCdf(MathSad.multipliedBy(dMinus, omega)); DoubleSad price = MathSad.multipliedBy(MathSad.multipliedBy(inputSad[2], omega), MathSad.minus(MathSad.multipliedBy(inputSad[0], nPlus), MathSad.multipliedBy(inputSad[3], nMinus))); return price; } /** * Returns the option price for the Black-Scholes formula and its derivatives with respect to * [0] forward, [1] volatility, [2] numeraire, [3] strike, and [4] expiry. * The derivatives are computed by Adjoint Algorithmic Differentiation. * @param forward The forward price/rate. * @param volatility The log-normal volatility of the model. * @param numeraire The numeraire. * @param strike The strike price/rate. * @param expiry The time to expiry. * @param isCall The call (true) / put (false) flag. * @return The price and derivatives. */ public static DoubleDerivatives price_Aad( double forward, double volatility, double numeraire, double strike, double expiry, boolean isCall) { // Forward sweep - function double omega = isCall ? 1.0d : -1.0d; double periodVolatility = volatility * Math.sqrt(expiry); double dPlus = Math.log(forward / strike) / periodVolatility + 0.5d * periodVolatility; double dMinus = dPlus - periodVolatility; double nPlus = NORMAL.cdf(omega * dPlus); double nMinus = NORMAL.cdf(omega * dMinus); double price = numeraire * omega * (forward * nPlus - strike * nMinus); // Backward sweep - derivatives double priceBar = 1.0; double nMinusBar = numeraire * omega * -strike * priceBar; double nPlusBar = numeraire * omega * forward * priceBar; double dMinusBar = NORMAL.pdf(omega * dMinus) * omega * nMinusBar; double dPlusBar = 1.0d * dMinusBar + NORMAL.pdf(omega * dPlus) * omega * nPlusBar; // Note: dPlusBar is always 0; it is the optimal exercise boundary. double periodVolatilityBar = -1.0d * dMinusBar + (-Math.log(forward / strike) / (periodVolatility * periodVolatility) + 0.5d) * dPlusBar; double[] inputBar = new double[5]; // forward, volatility, numeraire, strike, expiry inputBar[4] = volatility * 0.5 / Math.sqrt(expiry) * periodVolatilityBar; inputBar[3] = -1.0d / strike / periodVolatility * dPlusBar + numeraire * omega * -nMinus * priceBar; inputBar[2] = omega * (forward * nPlus - strike * nMinus) * priceBar; inputBar[1] = Math.sqrt(expiry) * periodVolatilityBar; inputBar[0] = 1.0d / forward / periodVolatility * dPlusBar + numeraire * omega * nPlus * priceBar; return new DoubleDerivatives(price, inputBar); } /** * Returns the option price for the Black-Scholes formula and its derivatives with respect to * [0] forward, [1] volatility, [2] numeraire, [3] strike, and [4] expiry. * The derivatives are computed by Adjoint Algorithmic Differentiation. * The formula is optimized to reduce computation time by using domain specific knowledge. * @param forward The forward price/rate. * @param volatility The log-normal volatility of the model. * @param numeraire The numeraire. * @param strike The strike price/rate. * @param expiry The time to expiry. * @param isCall The call (true) / put (false) flag. * @return The price and derivatives. */ public static DoubleDerivatives price_Aad_Optimized( double forward, double volatility, double numeraire, double strike, double expiry, boolean isCall) { // Forward sweep - function double omega = isCall ? 1.0d : -1.0d; double sqrtExpiry = Math.sqrt(expiry); double periodVolatility = volatility * sqrtExpiry; double dPlus = Math.log(forward / strike) / periodVolatility + 0.5d * periodVolatility; double dMinus = dPlus - periodVolatility; double nPlus = NORMAL.cdf(omega * dPlus); double nMinus = NORMAL.cdf(omega * dMinus); double price = numeraire * omega * (forward * nPlus - strike * nMinus); // Backward sweep - derivatives double priceBar = 1.0; double nMinusBar = numeraire * omega * -strike * priceBar; double dMinusBar = NORMAL.pdf(omega * dMinus) * omega * nMinusBar; double periodVolatilityBar = -1.0d * dMinusBar; double[] inputBar = new double[5]; // forward, volatility, numeraire, strike, expiry inputBar[4] = volatility * 0.5 / sqrtExpiry * periodVolatilityBar; inputBar[3] = numeraire * omega * -nMinus * priceBar; inputBar[2] = omega * (forward * nPlus - strike * nMinus) * priceBar; inputBar[1] = sqrtExpiry * periodVolatilityBar; inputBar[0] = numeraire * omega * nPlus * priceBar; return new DoubleDerivatives(price, inputBar); } /** * Returns the option price for the Black-Scholes formula as a {@link DoubleAad}. * The method also update the tape of type {@link TapeAad} which can be use to compute derivatives * by automatic AD. * @param forward The forward price/rate. * @param volatility The log-normal volatility of the model. * @param numeraire The numeraire. * @param strike The strike price/rate. * @param expiry The time to expiry. * @param isCall The call (true) / put (false) flag. * @param tape The tape where the operations are recorded. The tape is modified by the method. * @return The price and derivatives. */ public static DoubleAad price_Aad_Automatic( DoubleAad forward, DoubleAad volatility, DoubleAad numeraire, DoubleAad strike, DoubleAad expiry, boolean isCall, TapeAad tape) { double omega = isCall ? 1.0d : -1.0d; DoubleAad periodVolatility = MathAad.multipliedBy(volatility, MathAad.sqrt(expiry, tape), tape); DoubleAad dPlus = MathAad.plus(MathAad.dividedBy(MathAad.log(MathAad.dividedBy(forward, strike, tape), tape), periodVolatility, tape), MathAad.multipliedBy(periodVolatility, 0.5d, tape), tape); DoubleAad dMinus = MathAad.minus(dPlus, periodVolatility, tape); DoubleAad nPlus = MathAad.normalCdf(MathAad.multipliedBy(dPlus, omega, tape), tape); DoubleAad nMinus = MathAad.normalCdf(MathAad.multipliedBy(dMinus, omega, tape), tape); DoubleAad price = MathAad.multipliedBy(MathAad.multipliedBy(numeraire, omega, tape), MathAad.minus(MathAad.multipliedBy(forward, nPlus, tape), MathAad.multipliedBy(strike, nMinus, tape), tape), tape); return price; } /** * Returns the option price for the Black-Scholes formula and its derivatives with respect to * [0] forward, [1] volatility, [2] numeraire, [3] strike, and [4] expiry. * The derivatives are computed by Adjoint Algorithmic Differentiation. * The formula is optimized to reduce computation time by using domain specific knowledge. * The code is written manually but the object returned is the one used in Automatic AAD. * This code demonstrate that it is possible to combine manual and automatic AD. * @param forward The forward price/rate. * @param volatility The log-normal volatility of the model. * @param numeraire The numeraire. * @param strike The strike price/rate. * @param expiry The time to expiry. * @param isCall The call (true) / put (false) flag. * @return The price and derivatives. */ public static DoubleAad price_Aad_Automatic2( DoubleAad forwardAad, DoubleAad volatilityAad, DoubleAad numeraireAad, DoubleAad strikeAad, DoubleAad expiryAad, boolean isCall, TapeAad tape) { double forward = forwardAad.value(); double volatility = volatilityAad.value(); double numeraire = numeraireAad.value(); double strike = strikeAad.value(); double expiry = expiryAad.value(); // Forward sweep - function double omega = isCall ? 1.0d : -1.0d; double sqrtExpiry = Math.sqrt(expiry); double periodVolatility = volatility * sqrtExpiry; double dPlus = Math.log(forward / strike) / periodVolatility + 0.5d * periodVolatility; double dMinus = dPlus - periodVolatility; double nPlus = NORMAL.cdf(omega * dPlus); double nMinus = NORMAL.cdf(omega * dMinus); double price = numeraire * omega * (forward * nPlus - strike * nMinus); // Backward sweep - derivatives double priceBar = 1.0; double nMinusBar = numeraire * omega * -strike * priceBar; double dMinusBar = NORMAL.pdf(omega * dMinus) * omega * nMinusBar; double periodVolatilityBar = -1.0d * dMinusBar; double[] inputBar = new double[5]; // forward, volatility, numeraire, strike, expiry inputBar[4] = volatility * 0.5 / sqrtExpiry * periodVolatilityBar; inputBar[3] = numeraire * omega * -nMinus * priceBar; inputBar[2] = omega * (forward * nPlus - strike * nMinus) * priceBar; inputBar[1] = sqrtExpiry * periodVolatilityBar; inputBar[0] = numeraire * omega * nPlus * priceBar; int indexPrice0 = tape.addEntry(new TapeEntryAad(OperationTypeAad.MANUAL, forwardAad.tapeIndex(), price, inputBar[0])); int indexPrice1 = tape.addEntry(new TapeEntryAad(OperationTypeAad.MANUAL, volatilityAad.tapeIndex(), indexPrice0, price, inputBar[1])); int indexPrice2 = tape.addEntry(new TapeEntryAad(OperationTypeAad.MANUAL, numeraireAad.tapeIndex(), indexPrice1, price, inputBar[2])); int indexPrice3 = tape.addEntry(new TapeEntryAad(OperationTypeAad.MANUAL, strikeAad.tapeIndex(), indexPrice2, price, inputBar[3])); int indexPrice4 = tape.addEntry(new TapeEntryAad(OperationTypeAad.MANUAL, expiryAad.tapeIndex(), indexPrice3, price, inputBar[4])); return new DoubleAad(price, indexPrice4); } }
923d1c7e186adab3f664944da8cbe4e7ebf372fb
5,005
java
Java
src/org/xmodel/xpath/function/custom/SumMulFunction.java
bdunnagan/XModel
720b4ec18b069493cdbcc1b7dd7ec98a6379b795
[ "Apache-2.0" ]
null
null
null
src/org/xmodel/xpath/function/custom/SumMulFunction.java
bdunnagan/XModel
720b4ec18b069493cdbcc1b7dd7ec98a6379b795
[ "Apache-2.0" ]
null
null
null
src/org/xmodel/xpath/function/custom/SumMulFunction.java
bdunnagan/XModel
720b4ec18b069493cdbcc1b7dd7ec98a6379b795
[ "Apache-2.0" ]
1
2019-04-23T03:58:04.000Z
2019-04-23T03:58:04.000Z
29.269006
126
0.61039
1,000,180
/* * JAHM - Java Advanced Hierarchical Model * * SumFunction.java * * Copyright 2009 Robert Arvin Dunnagan * * 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.xmodel.xpath.function.custom; import java.util.List; import org.xmodel.IModelObject; import org.xmodel.Xlate; import org.xmodel.xpath.expression.ExpressionException; import org.xmodel.xpath.expression.IContext; import org.xmodel.xpath.expression.IExpression; import org.xmodel.xpath.function.Function; /** * A custom XPath function, similar to the sum() function, that performs a sum of the results * of multiplying numbers. The numbers that are multiplied may be pair-wise, or a single number * multiplied by a list of numbers, depending on whether a single number, or a list of numbers * is returned by one or both arguments. */ public class SumMulFunction extends Function { /* (non-Javadoc) * @see org.xmodel.xpath.expression.IExpression#getName() */ public String getName() { return "sum-mul"; } /* (non-Javadoc) * @see org.xmodel.xpath.expression.IExpression#getType() */ public ResultType getType() { return ResultType.NUMBER; } /* (non-Javadoc) * @see org.xmodel.xpath.expression.IExpression#evaluateNumber( * org.xmodel.xpath.expression.IContext) */ public double evaluateNumber( IContext context) throws ExpressionException { assertArgs( 2, 2); double sum = 0; IExpression arg0 = getArgument( 0); IExpression arg1 = getArgument( 1); switch( arg0.getType( context)) { case NODES: { switch( arg1.getType( context)) { case NODES: { List<IModelObject> nodes0 = arg0.evaluateNodes( context); List<IModelObject> nodes1 = arg1.evaluateNodes( context); for( int i=0; i<nodes0.size(); i++) { sum += Xlate.get( nodes0.get( i), 0d) * Xlate.get( nodes1.get( i), 0d); } } break; case NUMBER: case STRING: case BOOLEAN: { List<IModelObject> nodes0 = arg0.evaluateNodes( context); double value1 = arg1.evaluateNumber( context); for( int i=0; i<nodes0.size(); i++) { sum += Xlate.get( nodes0.get( i), 0d) * value1; } } break; default: break; } } break; case NUMBER: case STRING: case BOOLEAN: { double value0 = arg0.evaluateNumber( context); switch( arg1.getType( context)) { case NODES: { List<IModelObject> nodes1 = arg1.evaluateNodes( context); for( int i=0; i<nodes1.size(); i++) { sum += value0 * Xlate.get( nodes1.get( i), 0d); } } break; case NUMBER: case STRING: case BOOLEAN: { double value1 = arg1.evaluateNumber( context); sum += value0 * value1; } break; default: break; } } break; default: break; } return sum; } /* (non-Javadoc) * @see org.xmodel.xpath.expression.Expression#notifyAdd( * org.xmodel.xpath.expression.IExpression, org.xmodel.xpath.expression.IContext, * java.util.List) */ @Override public void notifyAdd( IExpression expression, IContext context, List<IModelObject> nodes) { if ( getParent() != null) notifyChange( this, context); } /* (non-Javadoc) * @see org.xmodel.xpath.expression.Expression#notifyRemove( * org.xmodel.xpath.expression.IExpression, org.xmodel.xpath.expression.IContext, * java.util.List) */ @Override public void notifyRemove( IExpression expression, IContext context, List<IModelObject> nodes) { if ( getParent() != null) notifyChange( this, context); } /* (non-Javadoc) * @see org.xmodel.xpath.expression.Expression#notifyValue(org.xmodel.xpath.expression.IExpression, * org.xmodel.xpath.expression.IContext[], org.xmodel.IModelObject, java.lang.Object, java.lang.Object) */ @Override public void notifyValue( IExpression expression, IContext[] contexts, IModelObject object, Object newValue, Object oldValue) { if ( getParent() != null) notifyChange( this, contexts[ 0]); } }
923d1ce252e77baf1dc28b1631f42496e561420b
27,084
java
Java
java/src/main/java/terra/market/v1beta1/Market.java
Vritra4/terra.proto
977264b7c3e0f9d135120d77b48657b82f5eacf6
[ "Apache-2.0" ]
3
2021-10-02T00:27:32.000Z
2022-02-12T05:00:12.000Z
java/src/main/java/terra/market/v1beta1/Market.java
Vritra4/terra.proto
977264b7c3e0f9d135120d77b48657b82f5eacf6
[ "Apache-2.0" ]
6
2021-09-14T07:20:46.000Z
2022-02-23T04:55:14.000Z
java/src/main/java/terra/market/v1beta1/Market.java
Vritra4/terra.proto
977264b7c3e0f9d135120d77b48657b82f5eacf6
[ "Apache-2.0" ]
8
2021-09-09T09:16:38.000Z
2022-03-26T23:00:08.000Z
37.985975
218
0.667036
1,000,181
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: terra/market/v1beta1/market.proto package terra.market.v1beta1; public final class Market { private Market() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } public interface ParamsOrBuilder extends // @@protoc_insertion_point(interface_extends:terra.market.v1beta1.Params) com.google.protobuf.MessageOrBuilder { /** * <code>bytes base_pool = 1 [(.gogoproto.nullable) = false, (.gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (.gogoproto.moretags) = "yaml:&#92;"base_pool&#92;""];</code> * @return The basePool. */ com.google.protobuf.ByteString getBasePool(); /** * <code>uint64 pool_recovery_period = 2 [(.gogoproto.moretags) = "yaml:&#92;"pool_recovery_period&#92;""];</code> * @return The poolRecoveryPeriod. */ long getPoolRecoveryPeriod(); /** * <code>bytes min_stability_spread = 3 [(.gogoproto.nullable) = false, (.gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (.gogoproto.moretags) = "yaml:&#92;"min_stability_spread&#92;""];</code> * @return The minStabilitySpread. */ com.google.protobuf.ByteString getMinStabilitySpread(); } /** * <pre> * Params defines the parameters for the market module. * </pre> * * Protobuf type {@code terra.market.v1beta1.Params} */ public static final class Params extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:terra.market.v1beta1.Params) ParamsOrBuilder { private static final long serialVersionUID = 0L; // Use Params.newBuilder() to construct. private Params(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Params() { basePool_ = com.google.protobuf.ByteString.EMPTY; minStabilitySpread_ = com.google.protobuf.ByteString.EMPTY; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new Params(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Params( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { basePool_ = input.readBytes(); break; } case 16: { poolRecoveryPeriod_ = input.readUInt64(); break; } case 26: { minStabilitySpread_ = input.readBytes(); break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return terra.market.v1beta1.Market.internal_static_terra_market_v1beta1_Params_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return terra.market.v1beta1.Market.internal_static_terra_market_v1beta1_Params_fieldAccessorTable .ensureFieldAccessorsInitialized( terra.market.v1beta1.Market.Params.class, terra.market.v1beta1.Market.Params.Builder.class); } public static final int BASE_POOL_FIELD_NUMBER = 1; private com.google.protobuf.ByteString basePool_; /** * <code>bytes base_pool = 1 [(.gogoproto.nullable) = false, (.gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (.gogoproto.moretags) = "yaml:&#92;"base_pool&#92;""];</code> * @return The basePool. */ @java.lang.Override public com.google.protobuf.ByteString getBasePool() { return basePool_; } public static final int POOL_RECOVERY_PERIOD_FIELD_NUMBER = 2; private long poolRecoveryPeriod_; /** * <code>uint64 pool_recovery_period = 2 [(.gogoproto.moretags) = "yaml:&#92;"pool_recovery_period&#92;""];</code> * @return The poolRecoveryPeriod. */ @java.lang.Override public long getPoolRecoveryPeriod() { return poolRecoveryPeriod_; } public static final int MIN_STABILITY_SPREAD_FIELD_NUMBER = 3; private com.google.protobuf.ByteString minStabilitySpread_; /** * <code>bytes min_stability_spread = 3 [(.gogoproto.nullable) = false, (.gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (.gogoproto.moretags) = "yaml:&#92;"min_stability_spread&#92;""];</code> * @return The minStabilitySpread. */ @java.lang.Override public com.google.protobuf.ByteString getMinStabilitySpread() { return minStabilitySpread_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!basePool_.isEmpty()) { output.writeBytes(1, basePool_); } if (poolRecoveryPeriod_ != 0L) { output.writeUInt64(2, poolRecoveryPeriod_); } if (!minStabilitySpread_.isEmpty()) { output.writeBytes(3, minStabilitySpread_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!basePool_.isEmpty()) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(1, basePool_); } if (poolRecoveryPeriod_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(2, poolRecoveryPeriod_); } if (!minStabilitySpread_.isEmpty()) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(3, minStabilitySpread_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof terra.market.v1beta1.Market.Params)) { return super.equals(obj); } terra.market.v1beta1.Market.Params other = (terra.market.v1beta1.Market.Params) obj; if (!getBasePool() .equals(other.getBasePool())) return false; if (getPoolRecoveryPeriod() != other.getPoolRecoveryPeriod()) return false; if (!getMinStabilitySpread() .equals(other.getMinStabilitySpread())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + BASE_POOL_FIELD_NUMBER; hash = (53 * hash) + getBasePool().hashCode(); hash = (37 * hash) + POOL_RECOVERY_PERIOD_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getPoolRecoveryPeriod()); hash = (37 * hash) + MIN_STABILITY_SPREAD_FIELD_NUMBER; hash = (53 * hash) + getMinStabilitySpread().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static terra.market.v1beta1.Market.Params parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static terra.market.v1beta1.Market.Params parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static terra.market.v1beta1.Market.Params parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static terra.market.v1beta1.Market.Params parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static terra.market.v1beta1.Market.Params parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static terra.market.v1beta1.Market.Params parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static terra.market.v1beta1.Market.Params parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static terra.market.v1beta1.Market.Params parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static terra.market.v1beta1.Market.Params parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static terra.market.v1beta1.Market.Params parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static terra.market.v1beta1.Market.Params parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static terra.market.v1beta1.Market.Params parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(terra.market.v1beta1.Market.Params prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Params defines the parameters for the market module. * </pre> * * Protobuf type {@code terra.market.v1beta1.Params} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:terra.market.v1beta1.Params) terra.market.v1beta1.Market.ParamsOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return terra.market.v1beta1.Market.internal_static_terra_market_v1beta1_Params_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return terra.market.v1beta1.Market.internal_static_terra_market_v1beta1_Params_fieldAccessorTable .ensureFieldAccessorsInitialized( terra.market.v1beta1.Market.Params.class, terra.market.v1beta1.Market.Params.Builder.class); } // Construct using terra.market.v1beta1.Market.Params.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); basePool_ = com.google.protobuf.ByteString.EMPTY; poolRecoveryPeriod_ = 0L; minStabilitySpread_ = com.google.protobuf.ByteString.EMPTY; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return terra.market.v1beta1.Market.internal_static_terra_market_v1beta1_Params_descriptor; } @java.lang.Override public terra.market.v1beta1.Market.Params getDefaultInstanceForType() { return terra.market.v1beta1.Market.Params.getDefaultInstance(); } @java.lang.Override public terra.market.v1beta1.Market.Params build() { terra.market.v1beta1.Market.Params result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public terra.market.v1beta1.Market.Params buildPartial() { terra.market.v1beta1.Market.Params result = new terra.market.v1beta1.Market.Params(this); result.basePool_ = basePool_; result.poolRecoveryPeriod_ = poolRecoveryPeriod_; result.minStabilitySpread_ = minStabilitySpread_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof terra.market.v1beta1.Market.Params) { return mergeFrom((terra.market.v1beta1.Market.Params)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(terra.market.v1beta1.Market.Params other) { if (other == terra.market.v1beta1.Market.Params.getDefaultInstance()) return this; if (other.getBasePool() != com.google.protobuf.ByteString.EMPTY) { setBasePool(other.getBasePool()); } if (other.getPoolRecoveryPeriod() != 0L) { setPoolRecoveryPeriod(other.getPoolRecoveryPeriod()); } if (other.getMinStabilitySpread() != com.google.protobuf.ByteString.EMPTY) { setMinStabilitySpread(other.getMinStabilitySpread()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { terra.market.v1beta1.Market.Params parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (terra.market.v1beta1.Market.Params) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private com.google.protobuf.ByteString basePool_ = com.google.protobuf.ByteString.EMPTY; /** * <code>bytes base_pool = 1 [(.gogoproto.nullable) = false, (.gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (.gogoproto.moretags) = "yaml:&#92;"base_pool&#92;""];</code> * @return The basePool. */ @java.lang.Override public com.google.protobuf.ByteString getBasePool() { return basePool_; } /** * <code>bytes base_pool = 1 [(.gogoproto.nullable) = false, (.gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (.gogoproto.moretags) = "yaml:&#92;"base_pool&#92;""];</code> * @param value The basePool to set. * @return This builder for chaining. */ public Builder setBasePool(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } basePool_ = value; onChanged(); return this; } /** * <code>bytes base_pool = 1 [(.gogoproto.nullable) = false, (.gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (.gogoproto.moretags) = "yaml:&#92;"base_pool&#92;""];</code> * @return This builder for chaining. */ public Builder clearBasePool() { basePool_ = getDefaultInstance().getBasePool(); onChanged(); return this; } private long poolRecoveryPeriod_ ; /** * <code>uint64 pool_recovery_period = 2 [(.gogoproto.moretags) = "yaml:&#92;"pool_recovery_period&#92;""];</code> * @return The poolRecoveryPeriod. */ @java.lang.Override public long getPoolRecoveryPeriod() { return poolRecoveryPeriod_; } /** * <code>uint64 pool_recovery_period = 2 [(.gogoproto.moretags) = "yaml:&#92;"pool_recovery_period&#92;""];</code> * @param value The poolRecoveryPeriod to set. * @return This builder for chaining. */ public Builder setPoolRecoveryPeriod(long value) { poolRecoveryPeriod_ = value; onChanged(); return this; } /** * <code>uint64 pool_recovery_period = 2 [(.gogoproto.moretags) = "yaml:&#92;"pool_recovery_period&#92;""];</code> * @return This builder for chaining. */ public Builder clearPoolRecoveryPeriod() { poolRecoveryPeriod_ = 0L; onChanged(); return this; } private com.google.protobuf.ByteString minStabilitySpread_ = com.google.protobuf.ByteString.EMPTY; /** * <code>bytes min_stability_spread = 3 [(.gogoproto.nullable) = false, (.gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (.gogoproto.moretags) = "yaml:&#92;"min_stability_spread&#92;""];</code> * @return The minStabilitySpread. */ @java.lang.Override public com.google.protobuf.ByteString getMinStabilitySpread() { return minStabilitySpread_; } /** * <code>bytes min_stability_spread = 3 [(.gogoproto.nullable) = false, (.gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (.gogoproto.moretags) = "yaml:&#92;"min_stability_spread&#92;""];</code> * @param value The minStabilitySpread to set. * @return This builder for chaining. */ public Builder setMinStabilitySpread(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } minStabilitySpread_ = value; onChanged(); return this; } /** * <code>bytes min_stability_spread = 3 [(.gogoproto.nullable) = false, (.gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (.gogoproto.moretags) = "yaml:&#92;"min_stability_spread&#92;""];</code> * @return This builder for chaining. */ public Builder clearMinStabilitySpread() { minStabilitySpread_ = getDefaultInstance().getMinStabilitySpread(); onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:terra.market.v1beta1.Params) } // @@protoc_insertion_point(class_scope:terra.market.v1beta1.Params) private static final terra.market.v1beta1.Market.Params DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new terra.market.v1beta1.Market.Params(); } public static terra.market.v1beta1.Market.Params getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Params> PARSER = new com.google.protobuf.AbstractParser<Params>() { @java.lang.Override public Params parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Params(input, extensionRegistry); } }; public static com.google.protobuf.Parser<Params> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Params> getParserForType() { return PARSER; } @java.lang.Override public terra.market.v1beta1.Market.Params getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_terra_market_v1beta1_Params_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_terra_market_v1beta1_Params_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n!terra/market/v1beta1/market.proto\022\024ter" + "ra.market.v1beta1\032\024gogoproto/gogo.proto\"" + "\225\002\n\006Params\022U\n\tbase_pool\030\001 \001(\014BB\362\336\037\020yaml:" + "\"base_pool\"\332\336\037&github.com/cosmos/cosmos-" + "sdk/types.Dec\310\336\037\000\022=\n\024pool_recovery_perio" + "d\030\002 \001(\004B\037\362\336\037\033yaml:\"pool_recovery_period\"" + "\022k\n\024min_stability_spread\030\003 \001(\014BM\362\336\037\033yaml" + ":\"min_stability_spread\"\332\336\037&github.com/co" + "smos/cosmos-sdk/types.Dec\310\336\037\000:\010\350\240\037\001\230\240\037\000B" + ",Z*github.com/terra-money/core/x/market/" + "typesb\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.protobuf.GoGoProtos.getDescriptor(), }); internal_static_terra_market_v1beta1_Params_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_terra_market_v1beta1_Params_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_terra_market_v1beta1_Params_descriptor, new java.lang.String[] { "BasePool", "PoolRecoveryPeriod", "MinStabilitySpread", }); com.google.protobuf.ExtensionRegistry registry = com.google.protobuf.ExtensionRegistry.newInstance(); registry.add(com.google.protobuf.GoGoProtos.customtype); registry.add(com.google.protobuf.GoGoProtos.equal); registry.add(com.google.protobuf.GoGoProtos.goprotoStringer); registry.add(com.google.protobuf.GoGoProtos.moretags); registry.add(com.google.protobuf.GoGoProtos.nullable); com.google.protobuf.Descriptors.FileDescriptor .internalUpdateFileDescriptor(descriptor, registry); com.google.protobuf.GoGoProtos.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
923d1d8aaa92f082cb03a5a9fbd9926bd9be847c
7,656
java
Java
library/src/androidTest/java/com/google/android/exoplayer2/util/UtilTest.java
hide8213/ExoPlayer
047234ed50f4e94e2502abc8bb6bf9591a99dc34
[ "Apache-2.0" ]
37
2016-08-15T07:11:25.000Z
2018-05-24T09:05:46.000Z
library/core/src/androidTest/java/com/google/android/exoplayer2/util/UtilTest.java
AmrMohammed89/exoplayer2.4.0_speedup
fcceb1bd5737b8682605d0d4182b68b4e353a356
[ "Apache-2.0" ]
null
null
null
library/core/src/androidTest/java/com/google/android/exoplayer2/util/UtilTest.java
AmrMohammed89/exoplayer2.4.0_speedup
fcceb1bd5737b8682605d0d4182b68b4e353a356
[ "Apache-2.0" ]
18
2016-09-11T07:31:02.000Z
2019-10-22T21:45:55.000Z
42.77095
93
0.718521
1,000,182
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.util; import com.google.android.exoplayer2.testutil.TestUtil; import java.util.ArrayList; import java.util.List; import java.util.Random; import junit.framework.TestCase; /** * Unit tests for {@link Util}. */ public class UtilTest extends TestCase { public void testArrayBinarySearchFloor() { long[] values = new long[0]; assertEquals(-1, Util.binarySearchFloor(values, 0, false, false)); assertEquals(0, Util.binarySearchFloor(values, 0, false, true)); values = new long[] {1, 3, 5}; assertEquals(-1, Util.binarySearchFloor(values, 0, false, false)); assertEquals(-1, Util.binarySearchFloor(values, 0, true, false)); assertEquals(0, Util.binarySearchFloor(values, 0, false, true)); assertEquals(0, Util.binarySearchFloor(values, 0, true, true)); assertEquals(-1, Util.binarySearchFloor(values, 1, false, false)); assertEquals(0, Util.binarySearchFloor(values, 1, true, false)); assertEquals(0, Util.binarySearchFloor(values, 1, false, true)); assertEquals(0, Util.binarySearchFloor(values, 1, true, true)); assertEquals(1, Util.binarySearchFloor(values, 4, false, false)); assertEquals(1, Util.binarySearchFloor(values, 4, true, false)); assertEquals(1, Util.binarySearchFloor(values, 5, false, false)); assertEquals(2, Util.binarySearchFloor(values, 5, true, false)); assertEquals(2, Util.binarySearchFloor(values, 6, false, false)); assertEquals(2, Util.binarySearchFloor(values, 6, true, false)); } public void testListBinarySearchFloor() { List<Integer> values = new ArrayList<>(); assertEquals(-1, Util.binarySearchFloor(values, 0, false, false)); assertEquals(0, Util.binarySearchFloor(values, 0, false, true)); values.add(1); values.add(3); values.add(5); assertEquals(-1, Util.binarySearchFloor(values, 0, false, false)); assertEquals(-1, Util.binarySearchFloor(values, 0, true, false)); assertEquals(0, Util.binarySearchFloor(values, 0, false, true)); assertEquals(0, Util.binarySearchFloor(values, 0, true, true)); assertEquals(-1, Util.binarySearchFloor(values, 1, false, false)); assertEquals(0, Util.binarySearchFloor(values, 1, true, false)); assertEquals(0, Util.binarySearchFloor(values, 1, false, true)); assertEquals(0, Util.binarySearchFloor(values, 1, true, true)); assertEquals(1, Util.binarySearchFloor(values, 4, false, false)); assertEquals(1, Util.binarySearchFloor(values, 4, true, false)); assertEquals(1, Util.binarySearchFloor(values, 5, false, false)); assertEquals(2, Util.binarySearchFloor(values, 5, true, false)); assertEquals(2, Util.binarySearchFloor(values, 6, false, false)); assertEquals(2, Util.binarySearchFloor(values, 6, true, false)); } public void testArrayBinarySearchCeil() { long[] values = new long[0]; assertEquals(0, Util.binarySearchCeil(values, 0, false, false)); assertEquals(-1, Util.binarySearchCeil(values, 0, false, true)); values = new long[] {1, 3, 5}; assertEquals(0, Util.binarySearchCeil(values, 0, false, false)); assertEquals(0, Util.binarySearchCeil(values, 0, true, false)); assertEquals(1, Util.binarySearchCeil(values, 1, false, false)); assertEquals(0, Util.binarySearchCeil(values, 1, true, false)); assertEquals(1, Util.binarySearchCeil(values, 2, false, false)); assertEquals(1, Util.binarySearchCeil(values, 2, true, false)); assertEquals(3, Util.binarySearchCeil(values, 5, false, false)); assertEquals(2, Util.binarySearchCeil(values, 5, true, false)); assertEquals(2, Util.binarySearchCeil(values, 5, false, true)); assertEquals(2, Util.binarySearchCeil(values, 5, true, true)); assertEquals(3, Util.binarySearchCeil(values, 6, false, false)); assertEquals(3, Util.binarySearchCeil(values, 6, true, false)); assertEquals(2, Util.binarySearchCeil(values, 6, false, true)); assertEquals(2, Util.binarySearchCeil(values, 6, true, true)); } public void testListBinarySearchCeil() { List<Integer> values = new ArrayList<>(); assertEquals(0, Util.binarySearchCeil(values, 0, false, false)); assertEquals(-1, Util.binarySearchCeil(values, 0, false, true)); values.add(1); values.add(3); values.add(5); assertEquals(0, Util.binarySearchCeil(values, 0, false, false)); assertEquals(0, Util.binarySearchCeil(values, 0, true, false)); assertEquals(1, Util.binarySearchCeil(values, 1, false, false)); assertEquals(0, Util.binarySearchCeil(values, 1, true, false)); assertEquals(1, Util.binarySearchCeil(values, 2, false, false)); assertEquals(1, Util.binarySearchCeil(values, 2, true, false)); assertEquals(3, Util.binarySearchCeil(values, 5, false, false)); assertEquals(2, Util.binarySearchCeil(values, 5, true, false)); assertEquals(2, Util.binarySearchCeil(values, 5, false, true)); assertEquals(2, Util.binarySearchCeil(values, 5, true, true)); assertEquals(3, Util.binarySearchCeil(values, 6, false, false)); assertEquals(3, Util.binarySearchCeil(values, 6, true, false)); assertEquals(2, Util.binarySearchCeil(values, 6, false, true)); assertEquals(2, Util.binarySearchCeil(values, 6, true, true)); } public void testParseXsDuration() { assertEquals(150279L, Util.parseXsDuration("PT150.279S")); assertEquals(1500L, Util.parseXsDuration("PT1.500S")); } public void testParseXsDateTime() throws Exception { assertEquals(1403219262000L, Util.parseXsDateTime("2014-06-19T23:07:42")); assertEquals(1407322800000L, Util.parseXsDateTime("2014-08-06T11:00:00Z")); assertEquals(1407322800000L, Util.parseXsDateTime("2014-08-06T11:00:00,000Z")); assertEquals(1411161535000L, Util.parseXsDateTime("2014-09-19T13:18:55-08:00")); assertEquals(1411161535000L, Util.parseXsDateTime("2014-09-19T13:18:55-0800")); assertEquals(1411161535000L, Util.parseXsDateTime("2014-09-19T13:18:55.000-0800")); } public void testUnescapeInvalidFileName() { assertNull(Util.unescapeFileName("%a")); assertNull(Util.unescapeFileName("%xyz")); } public void testEscapeUnescapeFileName() { assertEscapeUnescapeFileName("just+a regular+fileName", "just+a regular+fileName"); assertEscapeUnescapeFileName("key:value", "key%3avalue"); assertEscapeUnescapeFileName("<>:\"/\\|?*%", "%3c%3e%3a%22%2f%5c%7c%3f%2a%25"); Random random = new Random(0); for (int i = 0; i < 1000; i++) { String string = TestUtil.buildTestString(1000, random); assertEscapeUnescapeFileName(string); } } private static void assertEscapeUnescapeFileName(String fileName, String escapedFileName) { assertEquals(escapedFileName, Util.escapeFileName(fileName)); assertEquals(fileName, Util.unescapeFileName(escapedFileName)); } private static void assertEscapeUnescapeFileName(String fileName) { String escapedFileName = Util.escapeFileName(fileName); assertEquals(fileName, Util.unescapeFileName(escapedFileName)); } }
923d1fd8c71fd70858971c86d909c53237fcb5ad
1,448
java
Java
app/src/main/java/com/joinacf/acf/modelclasses/DashboardCategories.java
BhanuCheguri/ACFBackup-Latest-master-master
25f8209e7e65cfd10f124371de66b1f95c03a2f5
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/joinacf/acf/modelclasses/DashboardCategories.java
BhanuCheguri/ACFBackup-Latest-master-master
25f8209e7e65cfd10f124371de66b1f95c03a2f5
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/joinacf/acf/modelclasses/DashboardCategories.java
BhanuCheguri/ACFBackup-Latest-master-master
25f8209e7e65cfd10f124371de66b1f95c03a2f5
[ "Apache-2.0" ]
null
null
null
20.685714
54
0.607735
1,000,183
package com.joinacf.acf.modelclasses; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; public class DashboardCategories { @SerializedName("status") @Expose private String status; @SerializedName("message") @Expose private String message; @SerializedName("result") @Expose private ArrayList<Result> result = null; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public ArrayList<Result> getResult() { return result; } public void setResult(ArrayList<Result> result) { this.result = result; } public class Result { @SerializedName("CategoryID") @Expose private String categoryID; @SerializedName("Name") @Expose private String name; public String getCategoryID() { return categoryID; } public void setCategoryID(String categoryID) { this.categoryID = categoryID; } public String getName() { return name; } public void setName(String name) { this.name = name; } } }
923d20b8cc3003b6b2d85ab1618a2021bd6d1443
2,346
java
Java
core/src/main/java/org/mapfish/print/map/style/ParserPluginUtils.java
moove-it/mapfish-print
09307058a756c3504724fad56304733f59e1c8fc
[ "BSD-2-Clause" ]
null
null
null
core/src/main/java/org/mapfish/print/map/style/ParserPluginUtils.java
moove-it/mapfish-print
09307058a756c3504724fad56304733f59e1c8fc
[ "BSD-2-Clause" ]
null
null
null
core/src/main/java/org/mapfish/print/map/style/ParserPluginUtils.java
moove-it/mapfish-print
09307058a756c3504724fad56304733f59e1c8fc
[ "BSD-2-Clause" ]
1
2015-10-15T16:03:41.000Z
2015-10-15T16:03:41.000Z
35.014925
132
0.671782
1,000,184
package org.mapfish.print.map.style; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.io.ByteStreams; import com.google.common.io.Closer; import org.geotools.styling.Style; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpResponse; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; /** * Utilities for creating parser plugins. */ public final class ParserPluginUtils { private ParserPluginUtils() { // utility class } /** * Load data using {@link org.mapfish.print.config.Configuration#loadFile(String)} and using http. If data is able to be loaded * it will be passed to the loadFunction to be turned into a style. * * @param clientHttpRequestFactory the factory to use for http requests * @param styleRef the uri/file/else for attempting to load a style * @param loadFunction the function to call when data has been loaded. */ public static Optional<Style> loadStyleAsURI( final ClientHttpRequestFactory clientHttpRequestFactory, final String styleRef, final Function<byte[], Optional<Style>> loadFunction) throws IOException { HttpStatus statusCode; final byte[] input; Closer closer = Closer.create(); try { URI uri; try { uri = new URI(styleRef); } catch (URISyntaxException e) { uri = new File(styleRef).toURI(); } final ClientHttpRequest request = clientHttpRequestFactory.createRequest(uri, HttpMethod.GET); final ClientHttpResponse response = closer.register(request.execute()); statusCode = response.getStatusCode(); input = ByteStreams.toByteArray(response.getBody()); } catch (Exception e) { return Optional.absent(); } finally { closer.close(); } if (statusCode == HttpStatus.OK) { return loadFunction.apply(input); } else { return Optional.absent(); } } }
923d20d1797c0652120f14a69901aa197c87f344
4,850
java
Java
feign-ribbon/src/main/java/feign/ribbon/LBClient.java
PlayBoyFly/open-feign
fb2f9d5858ed2f34738a1505847be2a93b2ca147
[ "Apache-2.0" ]
null
null
null
feign-ribbon/src/main/java/feign/ribbon/LBClient.java
PlayBoyFly/open-feign
fb2f9d5858ed2f34738a1505847be2a93b2ca147
[ "Apache-2.0" ]
null
null
null
feign-ribbon/src/main/java/feign/ribbon/LBClient.java
PlayBoyFly/open-feign
fb2f9d5858ed2f34738a1505847be2a93b2ca147
[ "Apache-2.0" ]
null
null
null
31.493506
106
0.743299
1,000,185
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package feign.ribbon; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.ListMultimap; import com.netflix.client.AbstractLoadBalancerAwareClient; import com.netflix.client.ClientException; import com.netflix.client.ClientRequest; import com.netflix.client.IResponse; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.util.Pair; import java.io.IOException; import java.net.URI; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import javax.ws.rs.core.MultivaluedMap; import feign.Client; import feign.Request; import feign.RequestTemplate; import feign.Response; import feign.RetryableException; import static com.netflix.client.config.CommonClientConfigKey.ConnectTimeout; import static com.netflix.client.config.CommonClientConfigKey.ReadTimeout; class LBClient extends AbstractLoadBalancerAwareClient<LBClient.RibbonRequest, LBClient.RibbonResponse> { private final Client delegate; private final int connectTimeout; private final int readTimeout; LBClient(Client delegate, ILoadBalancer lb, IClientConfig clientConfig) { this.delegate = delegate; this.connectTimeout = Integer.valueOf(clientConfig.getProperty(ConnectTimeout).toString()); this.readTimeout = Integer.valueOf(clientConfig.getProperty(ReadTimeout).toString()); setLoadBalancer(lb); initWithNiwsConfig(clientConfig); } @Override public RibbonResponse execute(RibbonRequest request) throws IOException { int connectTimeout = config(request, ConnectTimeout, this.connectTimeout); int readTimeout = config(request, ReadTimeout, this.readTimeout); Request.Options options = new Request.Options(connectTimeout, readTimeout); Response response = delegate.execute(request.toRequest(), options); return new RibbonResponse(request.getUri(), response); } @Override protected boolean isCircuitBreakerException(Exception e) { return e instanceof IOException; } @Override protected boolean isRetriableException(Exception e) { return e instanceof RetryableException; } @Override protected Pair<String, Integer> deriveSchemeAndPortFromPartialUri(RibbonRequest task) { return new Pair<String, Integer>(URI.create(task.request.url()).getScheme(), task.getUri().getPort()); } @Override protected int getDefaultPort() { return 443; } static class RibbonRequest extends ClientRequest implements Cloneable { private final Request request; RibbonRequest(Request request, URI uri) { this.request = request; setUri(uri); } Request toRequest() { return new RequestTemplate() .method(request.method()) .append(getUri().toASCIIString()) .headers(request.headers()) .body(request.body().orNull()).request(); } public Object clone() { return new RibbonRequest(request, getUri()); } } static class RibbonResponse implements IResponse { private final URI uri; private final Response response; RibbonResponse(URI uri, Response response) { this.uri = uri; this.response = response; } @Override public Object getPayload() throws ClientException { return response.body().orNull(); } @Override public boolean hasPayload() { return response.body().isPresent(); } @Override public boolean isSuccess() { return response.status() == 200; } @Override public URI getRequestedURI() { return uri; } @Override public Map<String, Collection<String>> getHeaders() { return response.headers().asMap(); } Response toResponse() { return response; } } static int config(RibbonRequest request, CommonClientConfigKey key, int defaultValue) { if (request.getOverrideConfig() != null && request.getOverrideConfig().containsProperty(key)) return Integer.valueOf(request.getOverrideConfig().getProperty(key).toString()); return defaultValue; } }
923d20e421fb525314d15ce0be1257e493f7795d
1,412
java
Java
1.2.java
eminsaygi/JavaAlgoritmaSorulari
730b8bdd7c9f577eb79cbc326fe4860bb70321d4
[ "Apache-2.0" ]
4
2021-06-19T19:31:39.000Z
2021-09-16T17:15:43.000Z
1.2.java
eminsaygi/JavaAlgoritmaSorulari
730b8bdd7c9f577eb79cbc326fe4860bb70321d4
[ "Apache-2.0" ]
null
null
null
1.2.java
eminsaygi/JavaAlgoritmaSorulari
730b8bdd7c9f577eb79cbc326fe4860bb70321d4
[ "Apache-2.0" ]
null
null
null
23.932203
69
0.375354
1,000,186
package soru9; public class Soru9 { public static void main(String[] args) { int sayac =1,sayi=2; String sonuc =""; while (sayac<100) { if (Asal(sayi) && Palindromik(sayi) && AsalTersi(sayi)) { if(sayac%10==0){ sonuc += " "+sayi+"\n"; }else{ sonuc += " "+sayi; } sayac++; } sayi++; } System.out.print(sonuc); } static boolean Palindromik(int a){ int sonuc = 10; int numara = a; while(a!=0){ int sondeger= a%10; sonuc = sonuc*10+sondeger; a /=10; } return numara!=sonuc; } static boolean Asal (int a){ for (int bolen = 2; bolen <= a/2; bolen++) { if (a%bolen==0) { return false; } } return true; } static boolean AsalTersi(int a){ int sonuc = 0; int numara = a; while(a!=0){ int sondeger= a%10; sonuc = sonuc*10+sondeger; a /=10; } for (int bolen = 2; bolen <= sonuc/2; bolen++) { if (sonuc%bolen==0) { return false; } } return true; } }
923d216c183cf8e7059b85143ce41659237ad5c2
695
java
Java
src/main/java/org/xson/common/validate/rule/StringLengthIntervalChecker.java
xsonorg/validate
58b7f8908fb10eed574f43c1d06e930d2fbb4296
[ "Apache-2.0" ]
null
null
null
src/main/java/org/xson/common/validate/rule/StringLengthIntervalChecker.java
xsonorg/validate
58b7f8908fb10eed574f43c1d06e930d2fbb4296
[ "Apache-2.0" ]
null
null
null
src/main/java/org/xson/common/validate/rule/StringLengthIntervalChecker.java
xsonorg/validate
58b7f8908fb10eed574f43c1d06e930d2fbb4296
[ "Apache-2.0" ]
null
null
null
25.740741
65
0.661871
1,000,187
package org.xson.common.validate.rule; import org.xson.common.object.XCO; import org.xson.common.validate.Checker; /** * 字符串长度校验 */ public class StringLengthIntervalChecker implements Checker { @Override public boolean check(XCO xco, String fieldName, Object value) { String strVal = xco.getStringValue(fieldName); int val = strVal.length(); int[] result = (int[]) value; return val >= result[0] && val <= result[1]; } public static Object parseValue(String value) { String[] array = value.split(","); int[] result = { 0, 0 }; result[0] = Integer.parseInt(array[0].trim()); result[1] = Integer.parseInt(array[1].trim()); return result; } }
923d21967c097db341eb7f437b1c62e7e89641cf
10,238
java
Java
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/TestChecksumFileSystem.java
routarddev/hadoop
e4fc609d5d3739b7809057954c5233cfd1d1117b
[ "Apache-2.0" ]
4
2017-05-17T15:40:06.000Z
2020-05-06T05:46:51.000Z
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/TestChecksumFileSystem.java
routarddev/hadoop
e4fc609d5d3739b7809057954c5233cfd1d1117b
[ "Apache-2.0" ]
1
2018-08-20T08:37:35.000Z
2018-08-21T01:59:34.000Z
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/TestChecksumFileSystem.java
routarddev/hadoop
e4fc609d5d3739b7809057954c5233cfd1d1117b
[ "Apache-2.0" ]
1
2019-11-28T02:51:15.000Z
2019-11-28T02:51:15.000Z
36.049296
87
0.709807
1,000,188
/** * 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.fs; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FSDataOutputStream; import static org.apache.hadoop.fs.FileSystemTestHelper.*; import org.apache.hadoop.conf.Configuration; import org.junit.*; import static org.junit.Assert.*; public class TestChecksumFileSystem { static final String TEST_ROOT_DIR = System.getProperty("test.build.data","build/test/data/work-dir/localfs"); static LocalFileSystem localFs; @Before public void resetLocalFs() throws Exception { localFs = FileSystem.getLocal(new Configuration()); localFs.setVerifyChecksum(true); } @Test public void testgetChecksumLength() throws Exception { assertEquals(8, ChecksumFileSystem.getChecksumLength(0L, 512)); assertEquals(12, ChecksumFileSystem.getChecksumLength(1L, 512)); assertEquals(12, ChecksumFileSystem.getChecksumLength(512L, 512)); assertEquals(16, ChecksumFileSystem.getChecksumLength(513L, 512)); assertEquals(16, ChecksumFileSystem.getChecksumLength(1023L, 512)); assertEquals(16, ChecksumFileSystem.getChecksumLength(1024L, 512)); assertEquals(408, ChecksumFileSystem.getChecksumLength(100L, 1)); assertEquals(4000000000008L, ChecksumFileSystem.getChecksumLength(10000000000000L, 10)); } @Test public void testVerifyChecksum() throws Exception { Path testPath = new Path(TEST_ROOT_DIR, "testPath"); Path testPath11 = new Path(TEST_ROOT_DIR, "testPath11"); FSDataOutputStream fout = localFs.create(testPath); fout.write("testing".getBytes()); fout.close(); fout = localFs.create(testPath11); fout.write("testing you".getBytes()); fout.close(); // Exercise some boundary cases - a divisor of the chunk size // the chunk size, 2x chunk size, and +/-1 around these. readFile(localFs, testPath, 128); readFile(localFs, testPath, 511); readFile(localFs, testPath, 512); readFile(localFs, testPath, 513); readFile(localFs, testPath, 1023); readFile(localFs, testPath, 1024); readFile(localFs, testPath, 1025); localFs.delete(localFs.getChecksumFile(testPath), true); assertTrue("checksum deleted", !localFs.exists(localFs.getChecksumFile(testPath))); //copying the wrong checksum file FileUtil.copy(localFs, localFs.getChecksumFile(testPath11), localFs, localFs.getChecksumFile(testPath),false,true,localFs.getConf()); assertTrue("checksum exists", localFs.exists(localFs.getChecksumFile(testPath))); boolean errorRead = false; try { readFile(localFs, testPath, 1024); }catch(ChecksumException ie) { errorRead = true; } assertTrue("error reading", errorRead); //now setting verify false, the read should succeed localFs.setVerifyChecksum(false); String str = readFile(localFs, testPath, 1024).toString(); assertTrue("read", "testing".equals(str)); } @Test public void testMultiChunkFile() throws Exception { Path testPath = new Path(TEST_ROOT_DIR, "testMultiChunk"); FSDataOutputStream fout = localFs.create(testPath); for (int i = 0; i < 1000; i++) { fout.write(("testing" + i).getBytes()); } fout.close(); // Exercise some boundary cases - a divisor of the chunk size // the chunk size, 2x chunk size, and +/-1 around these. readFile(localFs, testPath, 128); readFile(localFs, testPath, 511); readFile(localFs, testPath, 512); readFile(localFs, testPath, 513); readFile(localFs, testPath, 1023); readFile(localFs, testPath, 1024); readFile(localFs, testPath, 1025); } /** * Test to ensure that if the checksum file is truncated, a * ChecksumException is thrown */ @Test public void testTruncatedChecksum() throws Exception { Path testPath = new Path(TEST_ROOT_DIR, "testtruncatedcrc"); FSDataOutputStream fout = localFs.create(testPath); fout.write("testing truncation".getBytes()); fout.close(); // Read in the checksum Path checksumFile = localFs.getChecksumFile(testPath); FileSystem rawFs = localFs.getRawFileSystem(); FSDataInputStream checksumStream = rawFs.open(checksumFile); byte buf[] = new byte[8192]; int read = checksumStream.read(buf, 0, buf.length); checksumStream.close(); // Now rewrite the checksum file with the last byte missing FSDataOutputStream replaceStream = rawFs.create(checksumFile); replaceStream.write(buf, 0, read - 1); replaceStream.close(); // Now reading the file should fail with a ChecksumException try { readFile(localFs, testPath, 1024); fail("Did not throw a ChecksumException when reading truncated " + "crc file"); } catch(ChecksumException ie) { } // telling it not to verify checksums, should avoid issue. localFs.setVerifyChecksum(false); String str = readFile(localFs, testPath, 1024).toString(); assertTrue("read", "testing truncation".equals(str)); } @Test public void testStreamType() throws Exception { Path testPath = new Path(TEST_ROOT_DIR, "testStreamType"); localFs.create(testPath).close(); FSDataInputStream in = null; localFs.setVerifyChecksum(true); in = localFs.open(testPath); assertTrue("stream is input checker", in.getWrappedStream() instanceof FSInputChecker); localFs.setVerifyChecksum(false); in = localFs.open(testPath); assertFalse("stream is not input checker", in.getWrappedStream() instanceof FSInputChecker); } @Test public void testCorruptedChecksum() throws Exception { Path testPath = new Path(TEST_ROOT_DIR, "testCorruptChecksum"); Path checksumPath = localFs.getChecksumFile(testPath); // write a file to generate checksum FSDataOutputStream out = localFs.create(testPath, true); out.write("testing 1 2 3".getBytes()); out.close(); assertTrue(localFs.exists(checksumPath)); FileStatus stat = localFs.getFileStatus(checksumPath); // alter file directly so checksum is invalid out = localFs.getRawFileSystem().create(testPath, true); out.write("testing stale checksum".getBytes()); out.close(); assertTrue(localFs.exists(checksumPath)); // checksum didn't change on disk assertEquals(stat, localFs.getFileStatus(checksumPath)); Exception e = null; try { localFs.setVerifyChecksum(true); readFile(localFs, testPath, 1024); } catch (ChecksumException ce) { e = ce; } finally { assertNotNull("got checksum error", e); } localFs.setVerifyChecksum(false); String str = readFile(localFs, testPath, 1024); assertEquals("testing stale checksum", str); } @Test public void testRenameFileToFile() throws Exception { Path srcPath = new Path(TEST_ROOT_DIR, "testRenameSrc"); Path dstPath = new Path(TEST_ROOT_DIR, "testRenameDst"); verifyRename(srcPath, dstPath, false); } @Test public void testRenameFileIntoDir() throws Exception { Path srcPath = new Path(TEST_ROOT_DIR, "testRenameSrc"); Path dstPath = new Path(TEST_ROOT_DIR, "testRenameDir"); localFs.mkdirs(dstPath); verifyRename(srcPath, dstPath, true); } @Test public void testRenameFileIntoDirFile() throws Exception { Path srcPath = new Path(TEST_ROOT_DIR, "testRenameSrc"); Path dstPath = new Path(TEST_ROOT_DIR, "testRenameDir/testRenameDst"); assertTrue(localFs.mkdirs(dstPath)); verifyRename(srcPath, dstPath, false); } @Test public void testSetConf() { Configuration conf = new Configuration(); conf.setInt(LocalFileSystemConfigKeys.LOCAL_FS_BYTES_PER_CHECKSUM_KEY, 0); try { localFs.setConf(conf); fail("Should have failed because zero bytes per checksum is invalid"); } catch (IllegalStateException ignored) { } conf.setInt(LocalFileSystemConfigKeys.LOCAL_FS_BYTES_PER_CHECKSUM_KEY, -1); try { localFs.setConf(conf); fail("Should have failed because negative bytes per checksum is invalid"); } catch (IllegalStateException ignored) { } conf.setInt(LocalFileSystemConfigKeys.LOCAL_FS_BYTES_PER_CHECKSUM_KEY, 512); localFs.setConf(conf); } void verifyRename(Path srcPath, Path dstPath, boolean dstIsDir) throws Exception { localFs.delete(srcPath,true); localFs.delete(dstPath,true); Path realDstPath = dstPath; if (dstIsDir) { localFs.mkdirs(dstPath); realDstPath = new Path(dstPath, srcPath.getName()); } // ensure file + checksum are moved writeFile(localFs, srcPath, 1); assertTrue(localFs.exists(localFs.getChecksumFile(srcPath))); assertTrue(localFs.rename(srcPath, dstPath)); assertTrue(localFs.exists(localFs.getChecksumFile(realDstPath))); // create a file with no checksum, rename, ensure dst checksum is removed writeFile(localFs.getRawFileSystem(), srcPath, 1); assertFalse(localFs.exists(localFs.getChecksumFile(srcPath))); assertTrue(localFs.rename(srcPath, dstPath)); assertFalse(localFs.exists(localFs.getChecksumFile(realDstPath))); // create file with checksum, rename over prior dst with no checksum writeFile(localFs, srcPath, 1); assertTrue(localFs.exists(localFs.getChecksumFile(srcPath))); assertTrue(localFs.rename(srcPath, dstPath)); assertTrue(localFs.exists(localFs.getChecksumFile(realDstPath))); } }
923d223923798411b81eeb81fd5a3729d95a67a0
838
java
Java
redis/redis-proxy/src/main/java/com/ctrip/xpipe/redis/proxy/tunnel/state/FrontendClosed.java
minluzhou/test1
100c39192a6ca6e749cb2857ece59239fa3d0a43
[ "Apache-2.0" ]
null
null
null
redis/redis-proxy/src/main/java/com/ctrip/xpipe/redis/proxy/tunnel/state/FrontendClosed.java
minluzhou/test1
100c39192a6ca6e749cb2857ece59239fa3d0a43
[ "Apache-2.0" ]
null
null
null
redis/redis-proxy/src/main/java/com/ctrip/xpipe/redis/proxy/tunnel/state/FrontendClosed.java
minluzhou/test1
100c39192a6ca6e749cb2857ece59239fa3d0a43
[ "Apache-2.0" ]
null
null
null
19.952381
57
0.657518
1,000,189
package com.ctrip.xpipe.redis.proxy.tunnel.state; import com.ctrip.xpipe.redis.proxy.tunnel.DefaultTunnel; import com.ctrip.xpipe.redis.proxy.tunnel.TunnelState; /** * @author chen.zhu * <p> * May 12, 2018 */ public class FrontendClosed extends AbstractTunnelState { public FrontendClosed(DefaultTunnel tunnel) { super(tunnel); } @Override public String name() { return "Frontend-Closed"; } @Override protected TunnelState doNextAfterSuccess() { return new TunnelClosing(tunnel); } @Override protected TunnelState doNextAfterFail() { return new TunnelClosing(tunnel); } @Override public boolean equals(Object obj) { return super.equals(obj); } @Override public String toString() { return super.toString(); } }
923d246da32f26fb3a8bb7de978827a870b0120d
1,093
java
Java
spring-pcf-fortune-service-oauth2/src/main/java/com/thinkenterprise/FortuneController.java
Thinkenterprise/spring-synchrone-microservices-pattern-workshop
ab2626b400eec4cbbb82eda65c98e2fce6409389
[ "Apache-2.0" ]
null
null
null
spring-pcf-fortune-service-oauth2/src/main/java/com/thinkenterprise/FortuneController.java
Thinkenterprise/spring-synchrone-microservices-pattern-workshop
ab2626b400eec4cbbb82eda65c98e2fce6409389
[ "Apache-2.0" ]
null
null
null
spring-pcf-fortune-service-oauth2/src/main/java/com/thinkenterprise/FortuneController.java
Thinkenterprise/spring-synchrone-microservices-pattern-workshop
ab2626b400eec4cbbb82eda65c98e2fce6409389
[ "Apache-2.0" ]
null
null
null
31.228571
110
0.764867
1,000,190
package com.thinkenterprise; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class FortuneController { Logger logger = LoggerFactory.getLogger(FortuneController.class); @Value("${cf.instance.index}") private String indexName; @Autowired FortuneRepository fortuneRepository; @PreAuthorize("#oauth2.hasScope('random')") @RequestMapping("/random") public Fortune fortune() { logger.info("FortuneController:fortune called ..."); //Fortune fortune = new Fortune(1L, "Application index : " + indexName + " FortuneController Random Fake"); Iterable<Fortune> result = fortuneRepository.randomFortunes(); return result.iterator().next(); } }
923d2514497c7bb2fc2ddc329657ae32c203730f
3,874
java
Java
src/test/java/seedu/address/model/transaction/CustomerContainsKeywordPredicateTest.java
aliciatxl/main
eb089ce527997bd3c582b21147b40498f371b95c
[ "MIT" ]
1
2020-03-14T08:17:53.000Z
2020-03-14T08:17:53.000Z
src/test/java/seedu/address/model/transaction/CustomerContainsKeywordPredicateTest.java
aliciatxl/main
eb089ce527997bd3c582b21147b40498f371b95c
[ "MIT" ]
118
2020-02-19T16:29:16.000Z
2020-04-15T17:06:16.000Z
src/test/java/seedu/address/model/transaction/CustomerContainsKeywordPredicateTest.java
aliciatxl/main
eb089ce527997bd3c582b21147b40498f371b95c
[ "MIT" ]
2
2020-02-19T07:54:38.000Z
2020-02-26T06:32:40.000Z
43.52809
119
0.728704
1,000,191
package seedu.address.model.transaction; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.address.testutil.customer.TypicalCustomers.ALICE; import static seedu.address.testutil.transaction.TypicalTransactions.ALICE_BUY_ONE_BAG_MARCH_FIRST; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import seedu.address.model.customer.Customer; import seedu.address.testutil.customer.CustomerBuilder; import seedu.address.testutil.transaction.TransactionBuilder; public class CustomerContainsKeywordPredicateTest { @Test public void equals() { List<String> firstPredicateKeywordList = Collections.singletonList("Alice"); List<String> secondPredicateKeywordList = Arrays.asList("Alice", "Bob"); CustomerContainsKeywordPredicate firstPredicate = new CustomerContainsKeywordPredicate(firstPredicateKeywordList); CustomerContainsKeywordPredicate secondPredicate = new CustomerContainsKeywordPredicate(secondPredicateKeywordList); // same object -> returns true assertTrue(firstPredicate.equals(firstPredicate)); // same values -> returns true CustomerContainsKeywordPredicate firstPredicateCopy = new CustomerContainsKeywordPredicate(firstPredicateKeywordList); assertTrue(firstPredicate.equals(firstPredicateCopy)); // different types -> returns false assertFalse(firstPredicate.equals(1)); // null -> returns false assertFalse(firstPredicate.equals(null)); // different keywords -> returns false assertFalse(firstPredicate.equals(secondPredicate)); } @Test public void test_customerContainsKeyword_returnsTrue() { //one keyword CustomerContainsKeywordPredicate predicate = new CustomerContainsKeywordPredicate(Collections.singletonList("Alice")); assertTrue(predicate.test(ALICE_BUY_ONE_BAG_MARCH_FIRST)); //multiple keyword predicate = new CustomerContainsKeywordPredicate(Arrays.asList("Alice", "Bob")); Customer editedAlice = new CustomerBuilder(ALICE).withName("Alice Bob").build(); assertTrue(predicate.test(new TransactionBuilder(ALICE_BUY_ONE_BAG_MARCH_FIRST) .withCustomer(editedAlice).build())); //only one matching keyword predicate = new CustomerContainsKeywordPredicate(Arrays.asList("Alice", "Andreas")); assertTrue(predicate.test(new TransactionBuilder(ALICE_BUY_ONE_BAG_MARCH_FIRST) .withCustomer(editedAlice).build())); //mixed case keywords predicate = new CustomerContainsKeywordPredicate(Arrays.asList("aLicE", "bOb")); assertTrue(predicate.test(new TransactionBuilder(ALICE_BUY_ONE_BAG_MARCH_FIRST) .withCustomer(editedAlice).build())); } @Test public void test_customerContainsKeyword_returnsFalse() { // no keyword CustomerContainsKeywordPredicate predicate = new CustomerContainsKeywordPredicate(Collections.emptyList()); assertFalse(predicate.test(ALICE_BUY_ONE_BAG_MARCH_FIRST)); //no matching keyword predicate = new CustomerContainsKeywordPredicate(Arrays.asList("random", "string")); assertFalse(predicate.test(ALICE_BUY_ONE_BAG_MARCH_FIRST)); //keywords matching other attributes rather than customer name. predicate = new CustomerContainsKeywordPredicate(Arrays.asList("1", "2020-03-01", "10:00", "20", "promotion")); assertFalse(predicate.test(new TransactionBuilder(ALICE_BUY_ONE_BAG_MARCH_FIRST) .withQuantity(1).withDateTime("2020-03-01 10:00").withMoney(20).withDescription("promotion").build())); } }
923d2567da1057cd374487544375547d035a1db1
1,223
java
Java
build-Ins_Nordlicht_blicken-Android_f_r_armeabi_v7a_GCC_4_9_Qt_5_5_1-Debug/android-build/gen/de/mda/generalmine/deutschbuch/R.java
GeneralMine/Ins-Nordlicht-Blicken-Categories-Notepad
23207cc5563b81a56dc1dfaf4f2f53421735c3d0
[ "MIT" ]
null
null
null
build-Ins_Nordlicht_blicken-Android_f_r_armeabi_v7a_GCC_4_9_Qt_5_5_1-Debug/android-build/gen/de/mda/generalmine/deutschbuch/R.java
GeneralMine/Ins-Nordlicht-Blicken-Categories-Notepad
23207cc5563b81a56dc1dfaf4f2f53421735c3d0
[ "MIT" ]
null
null
null
build-Ins_Nordlicht_blicken-Android_f_r_armeabi_v7a_GCC_4_9_Qt_5_5_1-Debug/android-build/gen/de/mda/generalmine/deutschbuch/R.java
GeneralMine/Ins-Nordlicht-Blicken-Categories-Notepad
23207cc5563b81a56dc1dfaf4f2f53421735c3d0
[ "MIT" ]
null
null
null
33.054054
85
0.6852
1,000,192
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package de.mda.generalmine.deutschbuch; public final class R { public static final class array { public static final int bundled_in_assets=0x7f040004; public static final int bundled_in_lib=0x7f040003; /** The following is handled automatically by the deployment tool. It should not be edited manually. */ public static final int bundled_libs=0x7f040001; public static final int qt_libs=0x7f040002; public static final int qt_sources=0x7f040000; } public static final class attr { } public static final class drawable { public static final int icon=0x7f020000; } public static final class layout { public static final int splash=0x7f030000; } public static final class string { public static final int fatal_error_msg=0x7f050002; public static final int ministro_needed_msg=0x7f050001; /** %%INSERT_STRINGS */ public static final int ministro_not_found_msg=0x7f050000; } }
923d26583163cb065518af865d1cbc1ffd8008f2
8,080
java
Java
src/main/java/ru/doublebyte/mathquizbot/bot/QuizBot.java
n-at/math-quiz-bot
2c2c1ebf809c44b3c9eed33641f61ae6d47c9d3a
[ "BSD-3-Clause" ]
1
2016-10-12T20:28:27.000Z
2016-10-12T20:28:27.000Z
src/main/java/ru/doublebyte/mathquizbot/bot/QuizBot.java
n-at/math-quiz-bot
2c2c1ebf809c44b3c9eed33641f61ae6d47c9d3a
[ "BSD-3-Clause" ]
null
null
null
src/main/java/ru/doublebyte/mathquizbot/bot/QuizBot.java
n-at/math-quiz-bot
2c2c1ebf809c44b3c9eed33641f61ae6d47c9d3a
[ "BSD-3-Clause" ]
1
2018-12-04T01:19:29.000Z
2018-12-04T01:19:29.000Z
31.811024
112
0.581436
1,000,193
package ru.doublebyte.mathquizbot.bot; import com.vdurmont.emoji.EmojiManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.doublebyte.mathquizbot.QuizService; import ru.doublebyte.mathquizbot.bot.types.*; import ru.doublebyte.mathquizbot.bot.types.mediaentity.Chat; import ru.doublebyte.mathquizbot.bot.types.util.EditMessageTextParams; import ru.doublebyte.mathquizbot.bot.types.util.SendMessageParams; import ru.doublebyte.mathquizbot.quiz.Level; import ru.doublebyte.mathquizbot.quiz.Quiz; import ru.doublebyte.mathquizbot.quiz.QuizVariant; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; /** * Math quiz bot */ public class QuizBot extends Bot { private static final Logger logger = LoggerFactory.getLogger(QuizBot.class); private QuizService quizService; public QuizBot(String apiUrl, String token, QuizService quizService) { super(apiUrl, token); this.quizService = quizService; } /** * Process bot update * @param update Update object */ @Override protected void processUpdate(Update update) { //text message from user with command if(update.getMessage() != null) { Message messageObj = update.getMessage(); Chat chat = messageObj.getChat(); Long messageId = messageObj.getId(); String message = messageObj.getText().trim(); switch(message) { case "/start": case "/help": sendMessage(chat.getId().toString(), helpMessage()); break; case "/simple": case "/medium": case "/hard": newQuiz(chat.getId(), message.substring(1)); break; default: sendMessage(chat.getId().toString(), wrongCommandMessage()); } } //answer to callback query with user's answer if(update.getCallbackQuery() != null) { CallbackQuery callbackQuery = update.getCallbackQuery(); processAnswer(callbackQuery.getMessage(), callbackQuery.getData()); } } /** * Start new quiz * @param chatId Id of chat * @param levelName Name of difficulty level */ protected void newQuiz(Long chatId, String levelName) { Level level; switch (levelName) { case "simple": level = Level.Simple; break; case "medium": level = Level.Medium; break; case "hard": level = Level.Hard; break; default: logger.warn("Unknown level: {}", levelName); level = Level.Simple; } //create quiz Quiz quiz = new Quiz(level); UUID quizId = UUID.randomUUID(); quizService.save(quizId, quiz); logger.info("New quiz {}. Difficulty: {}, Quiz: {}", quizId.toString(), level.toString(), quiz.getQuizString()); //build keyboard List<List<InlineKeyboardButton>> keyboard = new ArrayList<>(); List<InlineKeyboardButton> keyboardRow = quiz.getQuizVariants() .stream() .map(variant -> { InlineKeyboardButton button = new InlineKeyboardButton(); button.setText(variant.getName()); button.setCallbackData(quizId.toString() + ":" + variant.getName()); return button; }) .collect(Collectors.toList()); keyboard.add(keyboardRow); //send message SendMessageParams messageParams = new SendMessageParams(); messageParams.setChatId(chatId.toString()); messageParams.setText(buildMessageText(quiz, false)); messageParams.setReplyMarkup(new InlineKeyboardMarkup(keyboard)); sendMessage(messageParams); } /** * Process answer from user * @param originalMessage Message with quiz * @param answer User answer data */ protected void processAnswer(Message originalMessage, String answer) { if(originalMessage == null) { logger.warn("Empty original message"); return; } if(answer == null) { logger.warn("Empty answer"); return; } Long messageId = originalMessage.getId(); Long chatId = originalMessage.getChat().getId(); String[] parts = answer.split(":"); if(parts.length != 2) { logger.warn("Malformed answer: {}, chatId: {}, messageId: {}", answer, chatId, messageId); return; } UUID quizId; String variant; try { quizId = UUID.fromString(parts[0]); variant = parts[1]; } catch(Exception e) { logger.warn("Cannot parse answer ({}): {}, chatId: {}, messageId: {}", e.getMessage(), answer, chatId, messageId); return; } EditMessageTextParams editParams = new EditMessageTextParams(); editParams.setChatId(chatId.toString()); editParams.setMessageId(messageId); editParams.setReplyMarkup(InlineKeyboardMarkup.emptyKeyboardMarkup()); Quiz quiz = quizService.getById(quizId); if(quiz != null) { editParams.setText(buildMessageText(quiz, true) + (quiz.isCorrect(variant) ? correctAnswerMessage() : incorrectAnswerMessage())); } else { editParams.setText(quizNotFoundMessage()); logger.warn("Quiz not found: {}", quizId); } editMessageText(editParams); } /** * Build message text for quiz * Mark correct variant when markCorrect flag os set * * @param quiz Quiz * @return Text */ protected String buildMessageText(Quiz quiz, boolean markCorrect) { StringBuilder message = new StringBuilder(); message.append(quiz.getQuizString()); message.append("\n"); for(QuizVariant variant : quiz.getQuizVariants()) { message.append(variant.toString()); if(markCorrect && variant.getValue() == quiz.getAnswer()) { message.append(correctVariantMessage()); } message.append("\n"); } return message.toString(); } /** * Bot help message * @return Message text */ public String helpMessage() { return "This is math quiz bot. Test your math skills!\n" + "Type commands and solve random math problems:\n" + "/simple - two small numbers (10 - 100)\n" + "/medium - three medium numbers (100 - 1000)\n" + "/hard - three big numbers (1000 - 10000)"; } /** * Bot wrong command message * @return Message text */ public String wrongCommandMessage() { return "Type quiz command or /help for list of commands."; } /** * Message when user answers on a quiz that not found * @return Message text */ public String quizNotFoundMessage() { return "This problem is no longer available " + EmojiManager.getForAlias(":disappointed:").getUnicode(); } /** * Message for correct answer * @return Message text */ public String correctAnswerMessage() { return EmojiManager.getForAlias(":smiley:").getUnicode() + EmojiManager.getForAlias(":+1:").getUnicode(); } /** * Message for incorrect answer * @return Message text */ public String incorrectAnswerMessage() { return EmojiManager.getForAlias(":disappointed:").getUnicode(); } /** * Message for correct variant * @return Message text */ public String correctVariantMessage() { return " " + EmojiManager.getForAlias(":heavy_check_mark:").getUnicode(); } }
923d26b68095c32553aac4757c57b649deb49ab5
2,349
java
Java
kafka-manager-task/src/main/java/com/xiaojukeji/kafka/manager/task/listener/sink/db/SinkBrokerMetrics2DB.java
passliang/LogiKM
3336de457ac6ec1758552101a2e361e17ada3389
[ "Apache-2.0" ]
1,113
2021-07-09T03:11:56.000Z
2022-03-31T11:56:09.000Z
kafka-manager-task/src/main/java/com/xiaojukeji/kafka/manager/task/listener/sink/db/SinkBrokerMetrics2DB.java
ijihang/LogiKM
b4c60eb9109aed72a6f1b9365512dba5dd8d22af
[ "Apache-2.0" ]
120
2021-07-14T00:54:14.000Z
2022-03-25T10:50:21.000Z
kafka-manager-task/src/main/java/com/xiaojukeji/kafka/manager/task/listener/sink/db/SinkBrokerMetrics2DB.java
ijihang/LogiKM
b4c60eb9109aed72a6f1b9365512dba5dd8d22af
[ "Apache-2.0" ]
242
2021-07-09T05:13:01.000Z
2022-03-31T06:48:43.000Z
42.709091
143
0.746275
1,000,194
package com.xiaojukeji.kafka.manager.task.listener.sink.db; import com.xiaojukeji.kafka.manager.common.constant.Constant; import com.xiaojukeji.kafka.manager.common.entity.metrics.BrokerMetrics; import com.xiaojukeji.kafka.manager.common.entity.pojo.BrokerMetricsDO; import com.xiaojukeji.kafka.manager.common.events.metrics.BatchBrokerMetricsCollectedEvent; import com.xiaojukeji.kafka.manager.common.utils.ValidateUtils; import com.xiaojukeji.kafka.manager.dao.BrokerMetricsDao; import com.xiaojukeji.kafka.manager.service.utils.MetricsConvertUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; import java.util.List; /** * @author zengqiao * @date 22/01/17 */ @Component @ConditionalOnProperty(prefix = "task.metrics.sink.broker-metrics", name = "sink-db-enabled", havingValue = "true", matchIfMissing = true) public class SinkBrokerMetrics2DB implements ApplicationListener<BatchBrokerMetricsCollectedEvent> { private static final Logger logger = LoggerFactory.getLogger(SinkBrokerMetrics2DB.class); @Autowired private BrokerMetricsDao metricsDao; @Override public void onApplicationEvent(BatchBrokerMetricsCollectedEvent event) { logger.debug("sink broker-metrics to db start, event:{}.", event); List<BrokerMetrics> metricsList = event.getMetricsList(); if (ValidateUtils.isEmptyList(metricsList)) { logger.warn("sink broker-metrics to db finished, without need sink, event:{}.", event); return; } List<BrokerMetricsDO> doList = MetricsConvertUtils.convertAndUpdateCreateTime2BrokerMetricsDOList(event.getCollectTime(), metricsList); int i = 0; while (i < doList.size()) { List<BrokerMetricsDO> subDOList = doList.subList(i, Math.min(i + Constant.BATCH_INSERT_SIZE, doList.size())); if (ValidateUtils.isEmptyList(subDOList)) { break; } metricsDao.batchAdd(subDOList); i += Constant.BATCH_INSERT_SIZE; } logger.debug("sink broker-metrics to db finished, event:{}.", event); } }
923d26ba4c7412946f6c89c8fa9923f1bb71d6da
4,524
java
Java
src/main/java/com/ycao/mysite/controller/admin/AuthController.java
AlexandreSuperCC/mysite_backend_public
a4876438dcaa22af5923516cf0c0eef8499eaee1
[ "MIT" ]
null
null
null
src/main/java/com/ycao/mysite/controller/admin/AuthController.java
AlexandreSuperCC/mysite_backend_public
a4876438dcaa22af5923516cf0c0eef8499eaee1
[ "MIT" ]
null
null
null
src/main/java/com/ycao/mysite/controller/admin/AuthController.java
AlexandreSuperCC/mysite_backend_public
a4876438dcaa22af5923516cf0c0eef8499eaee1
[ "MIT" ]
null
null
null
42.280374
116
0.670645
1,000,195
package com.ycao.mysite.controller.admin; /** * login controller * where we get connected with vue * Created by ycao on 8/24 */ import com.ycao.mysite.constant.WebConst; import com.ycao.mysite.controller.BaseController; import com.ycao.mysite.model.LoginUser; import com.ycao.mysite.exception.BusinessException; import com.ycao.mysite.model.UserDomain; import com.ycao.mysite.service.user.UserService; import com.ycao.mysite.utils.APILoginResponse; import com.ycao.mysite.utils.APIResponse; import com.ycao.mysite.utils.IPKit; import com.ycao.mysite.utils.security.JwtUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Api("login related interface") @Controller @RequestMapping(value = "/") public class AuthController { private static final Logger LOGGER = LogManager.getLogger(AuthController.class); @Autowired private UserService userService; @Autowired private JwtUtil jwtUtil; @ApiOperation("login") @ApiImplicitParam(name = "form", value = "user login form", required = true, dataType = "LoginUser") @PostMapping(value = "/login") @ResponseBody public APILoginResponse toLogin( HttpServletRequest request, HttpServletResponse response, @RequestBody LoginUser loginUser//should be an object // @ApiParam(name="username",value = "user's name",required = true) // @RequestParam(name="username",required = true) // String username, // @ApiParam(name="password",value = "user's password",required = true) // @RequestParam(name="password",required = true) // String password, // @ApiParam(name="remember_me",value = "remember_me",required = false) // @RequestParam(name="remember_me",required = false) // String remember_me ){ String ip = IPKit.getIpAddrByRequest(request);//gei ip and solve the bug of filtering the cache when logging String token = null; try{ String username=loginUser.getUsername(); String password=loginUser.getPassword(); LOGGER.info("user: ["+username+"] pwd: ["+password+"] arrives"); UserDomain userInfo = userService.login(username,password); //no exception so succeed=> // depreciated, replace with token, but used again to save the user //delete by ycao 20222028 session消失bug 域名问题……调试的时候一个是127.0.0.1一个是localhost // request.getSession().setAttribute(WebConst.LOGIN_SESSION_KEY,userInfo.getUid()); // request.getSession().setMaxInactiveInterval(60*60);//session 60m expired token = JwtUtil.sign(userInfo.getUsername(),userInfo.getUid().toString()); if(token!=null){ if(userInfo.getUid()==null){ return APILoginResponse.successLogin(token,""); } return APILoginResponse.successLogin(token,String.valueOf(userInfo.getUid())); } }catch (Exception e){ String msg = "login fails"; if(e instanceof BusinessException){ String errMes = e.getMessage()!=null?e.getMessage():((BusinessException) e).getErrorCode(); LOGGER.error(ip+" : "+errMes); msg = ((BusinessException) e).getErrorCode(); }else{ LOGGER.error(msg,e); } return APILoginResponse.failLogin(msg); } return APILoginResponse.failLogin("make token error"); } @GetMapping(value = "/logout") @ResponseBody public APIResponse toLogout(HttpServletRequest request){ //delete by ycao 20222028 session消失bug 域名问题……调试的时候一个是127.0.0.1一个是localhost // LOGGER.info("userid: ["+request.getSession().getAttribute(WebConst.LOGIN_SESSION_KEY)+"] logs out"); // if(request.getSession().getAttribute(WebConst.LOGIN_SESSION_KEY)==null){ // return APIResponse.fail("no session required"); // } // request.getSession().removeAttribute(WebConst.LOGIN_SESSION_KEY); return APIResponse.success("logout success"); } }
923d26d99fce02f7d50854fa82c428c5ca92b779
4,375
java
Java
day9_lab/src/utils/CollectionUtils.java
elpidaguy/CDAC-CoreJava
65bdd41ae6acd1ed9a20efe7edcfb6840a86e18e
[ "MIT" ]
1
2020-11-10T12:48:34.000Z
2020-11-10T12:48:34.000Z
day9_lab/src/utils/CollectionUtils.java
elpidaguy/CDAC-CoreJava
65bdd41ae6acd1ed9a20efe7edcfb6840a86e18e
[ "MIT" ]
null
null
null
day9_lab/src/utils/CollectionUtils.java
elpidaguy/CDAC-CoreJava
65bdd41ae6acd1ed9a20efe7edcfb6840a86e18e
[ "MIT" ]
null
null
null
23.578378
135
0.678359
1,000,196
package utils; import static utils.ValidationRules.sdf; import static utils.ValidationRules.validateCourse; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import com.app.core.CourseTypes; import com.app.core.Student; import cust_excs.StudentHandlingException; public class CollectionUtils { public static ArrayList<Student> populateStudents() { // HashMap<String, Student> colgMap = new HashMap<>(); ArrayList<Student> colg = new ArrayList<Student>(); try { colg.add(new Student("dac-001", "Kaustubh", "kenaa@example.com", "45", validateCourse("DAC"), sdf.parse("11-06-2010"))); colg.add(new Student("dac-002", "Gurdeeep", "kenaa@example.com", "56", validateCourse("DAC"), sdf.parse("13-07-2010"))); colg.add(new Student("dac-003", "Ram", "efpyi@example.com", "98", validateCourse("DAC"), sdf.parse("09-08-2010"))); colg.add(new Student("dac-004", "Jason", "nnheo@example.com", "87", validateCourse("DAC"), sdf.parse("11-06-2010"))); } catch (Exception e) { e.printStackTrace(); } return colg; } public static void Display(ArrayList<Student> colgList) { for (Student s : colgList) System.out.println(s); } public static void getStudentDetails(String prn, ArrayList<Student> colgList) throws StudentHandlingException { for(Student stud: colgList) { if(stud != null && stud.getPrn().equals(prn)) { System.out.println(stud); } } } public static void updateMarks(String prn,String newMarks, ArrayList<Student> colgList) throws StudentHandlingException { for(Student stud: colgList) { if(stud != null && stud.getPrn().equals(prn)) { stud.setMarks(newMarks); System.out.println("Updated: "+stud); } } } public static void cancelAdmission(String prn, ArrayList<Student> colgList) throws StudentHandlingException { for(Student stud: colgList) { if(stud != null && stud.getPrn().equals(prn)) { if(colgList.remove(stud)) System.out.println("Cancelled Admission of: "+prn); } } } public static void addStudent(Student s, ArrayList<Student> colgList) throws StudentHandlingException { for(Student stud: colgList) { if(stud != null && stud.equals(s)) { throw new StudentHandlingException("PRN ALREADY EXISTS"); } } colgList.add(s); } public static void DisplayCourseWise(CourseTypes course,ArrayList<Student> colgList) throws StudentHandlingException { ArrayList<Student> courseWise = new ArrayList<Student>(); for(Student s : colgList) { if(s.getCourse() == course) { courseWise.add(s); } } if(courseWise.size() == 0) { throw new StudentHandlingException("No Student in course"+ course +"found"); } for(Student s2 : courseWise) { System.out.println(s2); } } public static void DisplayDateCourseWise(Date date, CourseTypes course, ArrayList<Student> colgList) throws StudentHandlingException { ArrayList<Student> newStudentList = new ArrayList<>(); for(Student s : colgList) { if( s.getDate().after(date) && s.getCourse() == course) { newStudentList.add(s); } } if(newStudentList.size() == 0) { throw new StudentHandlingException("No Student found"); } for(Student s2 : newStudentList) { System.out.println(s2); } } public static void sortByPRN(ArrayList<Student> colgList) throws StudentHandlingException { Collections.sort(colgList); for(Student s : colgList) { System.out.println(s); } } public static void sortByDOBMarks(ArrayList<Student> colgList) throws StudentHandlingException { Collections.sort(colgList, new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { int ret = o1.getDate().compareTo(o2.getDate()); if(ret != 0) { return ret; } return ((String) o2.getMarks()).compareTo(o1.getMarks()); } }); for(Student s : colgList) { System.out.println(s); } } public static void showTopper(ArrayList<Student> colgList) throws StudentHandlingException { System.out.println(Collections.max(colgList, new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o1.getMarks().compareTo(o2.getMarks()); } })); // for(Student s : newStudentList) // { // System.out.println(s); // } } }
923d26e25fdd1cb2dda0bdcc1c0ead8b9a25657a
1,028
java
Java
src/main/java/egovframework/com/uss/ion/lsi/service/LoginScrinImageVO.java
dasomel/egovframe-common-components
ebde09a06cbd5b762e8e37976a4fe25062d4e06e
[ "Apache-2.0" ]
9
2021-03-17T09:03:44.000Z
2021-12-10T02:08:34.000Z
src/main/java/egovframework/com/uss/ion/lsi/service/LoginScrinImageVO.java
dasomel/egovframe-common-components
ebde09a06cbd5b762e8e37976a4fe25062d4e06e
[ "Apache-2.0" ]
31
2020-11-12T01:31:07.000Z
2022-03-02T09:13:20.000Z
src/main/java/egovframework/com/uss/ion/lsi/service/LoginScrinImageVO.java
dasomel/egovframe-common-components
ebde09a06cbd5b762e8e37976a4fe25062d4e06e
[ "Apache-2.0" ]
52
2021-01-14T00:25:31.000Z
2022-03-30T03:56:10.000Z
18.035088
82
0.673152
1,000,197
/** * 개요 * - 로그인화면이미지에 대한 Vo 클래스를 정의한다. * * 상세내용 * - 로그인화면이미지의 목록 항목을 관리한다. * @author 이문준 * @version 1.0 * @created 03-8-2009 오후 2:08:56 */ package egovframework.com.uss.ion.lsi.service; import java.util.List; public class LoginScrinImageVO extends LoginScrinImage { /** * serialVersionUID */ private static final long serialVersionUID = 1L; /** * 로그인화면이미지 목록 */ List<LoginScrinImageVO> loginScrinImageList; /** * 삭제대상 목록 */ String[] delYn; /** * @return the loginScrinImageList */ public List<LoginScrinImageVO> getLoginScrinImageList() { return loginScrinImageList; } /** * @param loginScrinImageList the loginScrinImageList to set */ public void setLoginScrinImageList(List<LoginScrinImageVO> loginScrinImageList) { this.loginScrinImageList = loginScrinImageList; } /** * @return the delYn */ public String[] getDelYn() { return delYn; } /** * @param delYn the delYn to set */ public void setDelYn(String[] delYn) { this.delYn = delYn; } }
923d276190d98c1a852cfdc6d76e293e872f8bad
28,823
java
Java
aws-java-sdk-proton/src/main/java/com/amazonaws/services/proton/model/CreateEnvironmentRequest.java
hakyhanif/aws-sdk-java
676b8c88f588e9eef8102ce436f4cf94db16cb10
[ "Apache-2.0" ]
3,372
2015-01-03T00:35:43.000Z
2022-03-31T15:56:24.000Z
aws-java-sdk-proton/src/main/java/com/amazonaws/services/proton/model/CreateEnvironmentRequest.java
hakyhanif/aws-sdk-java
676b8c88f588e9eef8102ce436f4cf94db16cb10
[ "Apache-2.0" ]
2,391
2015-01-01T12:55:24.000Z
2022-03-31T08:01:50.000Z
aws-java-sdk-proton/src/main/java/com/amazonaws/services/proton/model/CreateEnvironmentRequest.java
hakyhanif/aws-sdk-java
676b8c88f588e9eef8102ce436f4cf94db16cb10
[ "Apache-2.0" ]
2,876
2015-01-01T14:38:37.000Z
2022-03-29T19:53:10.000Z
42.016035
139
0.648961
1,000,198
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.proton.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/proton-2020-07-20/CreateEnvironment" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateEnvironmentRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * A description of the environment that's being created and deployed. * </p> */ private String description; /** * <p> * The ID of the environment account connection that you provide if you're provisioning your environment * infrastructure resources to an environment account. You must include either the * <code>environmentAccountConnectionId</code> or <code>protonServiceRoleArn</code> parameter and value. For more * information, see <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/ag-env-account-connections.html">Environment account * connections</a> in the <i>AWS Proton Administrator guide</i>. * </p> */ private String environmentAccountConnectionId; /** * <p> * The name of the environment. * </p> */ private String name; /** * <p> * The Amazon Resource Name (ARN) of the AWS Proton service role that allows AWS Proton to make calls to other * services on your behalf. You must include either the <code>environmentAccountConnectionId</code> or * <code>protonServiceRoleArn</code> parameter and value. * </p> */ private String protonServiceRoleArn; /** * <p> * A link to a YAML formatted spec file that provides inputs as defined in the environment template bundle schema * file. For more information, see <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/ag-environments.html">Environments</a> in the <i>AWS * Proton Administrator Guide</i>. * </p> */ private String spec; /** * <p> * Create tags for your environment. For more information, see <i>AWS Proton resources and tagging</i> in the <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/resources.html">AWS Proton Administrator Guide</a> or * <a href="https://docs.aws.amazon.com/proton/latest/userguide/resources.html">AWS Proton User Guide</a>. * </p> */ private java.util.List<Tag> tags; /** * <p> * The ID of the major version of the environment template. * </p> */ private String templateMajorVersion; /** * <p> * The ID of the minor version of the environment template. * </p> */ private String templateMinorVersion; /** * <p> * The name of the environment template. For more information, see <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/ag-templates.html">Environment Templates</a> in the * <i>AWS Proton Administrator Guide</i>. * </p> */ private String templateName; /** * <p> * A description of the environment that's being created and deployed. * </p> * * @param description * A description of the environment that's being created and deployed. */ public void setDescription(String description) { this.description = description; } /** * <p> * A description of the environment that's being created and deployed. * </p> * * @return A description of the environment that's being created and deployed. */ public String getDescription() { return this.description; } /** * <p> * A description of the environment that's being created and deployed. * </p> * * @param description * A description of the environment that's being created and deployed. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateEnvironmentRequest withDescription(String description) { setDescription(description); return this; } /** * <p> * The ID of the environment account connection that you provide if you're provisioning your environment * infrastructure resources to an environment account. You must include either the * <code>environmentAccountConnectionId</code> or <code>protonServiceRoleArn</code> parameter and value. For more * information, see <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/ag-env-account-connections.html">Environment account * connections</a> in the <i>AWS Proton Administrator guide</i>. * </p> * * @param environmentAccountConnectionId * The ID of the environment account connection that you provide if you're provisioning your environment * infrastructure resources to an environment account. You must include either the * <code>environmentAccountConnectionId</code> or <code>protonServiceRoleArn</code> parameter and value. For * more information, see <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/ag-env-account-connections.html">Environment * account connections</a> in the <i>AWS Proton Administrator guide</i>. */ public void setEnvironmentAccountConnectionId(String environmentAccountConnectionId) { this.environmentAccountConnectionId = environmentAccountConnectionId; } /** * <p> * The ID of the environment account connection that you provide if you're provisioning your environment * infrastructure resources to an environment account. You must include either the * <code>environmentAccountConnectionId</code> or <code>protonServiceRoleArn</code> parameter and value. For more * information, see <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/ag-env-account-connections.html">Environment account * connections</a> in the <i>AWS Proton Administrator guide</i>. * </p> * * @return The ID of the environment account connection that you provide if you're provisioning your environment * infrastructure resources to an environment account. You must include either the * <code>environmentAccountConnectionId</code> or <code>protonServiceRoleArn</code> parameter and value. For * more information, see <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/ag-env-account-connections.html">Environment * account connections</a> in the <i>AWS Proton Administrator guide</i>. */ public String getEnvironmentAccountConnectionId() { return this.environmentAccountConnectionId; } /** * <p> * The ID of the environment account connection that you provide if you're provisioning your environment * infrastructure resources to an environment account. You must include either the * <code>environmentAccountConnectionId</code> or <code>protonServiceRoleArn</code> parameter and value. For more * information, see <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/ag-env-account-connections.html">Environment account * connections</a> in the <i>AWS Proton Administrator guide</i>. * </p> * * @param environmentAccountConnectionId * The ID of the environment account connection that you provide if you're provisioning your environment * infrastructure resources to an environment account. You must include either the * <code>environmentAccountConnectionId</code> or <code>protonServiceRoleArn</code> parameter and value. For * more information, see <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/ag-env-account-connections.html">Environment * account connections</a> in the <i>AWS Proton Administrator guide</i>. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateEnvironmentRequest withEnvironmentAccountConnectionId(String environmentAccountConnectionId) { setEnvironmentAccountConnectionId(environmentAccountConnectionId); return this; } /** * <p> * The name of the environment. * </p> * * @param name * The name of the environment. */ public void setName(String name) { this.name = name; } /** * <p> * The name of the environment. * </p> * * @return The name of the environment. */ public String getName() { return this.name; } /** * <p> * The name of the environment. * </p> * * @param name * The name of the environment. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateEnvironmentRequest withName(String name) { setName(name); return this; } /** * <p> * The Amazon Resource Name (ARN) of the AWS Proton service role that allows AWS Proton to make calls to other * services on your behalf. You must include either the <code>environmentAccountConnectionId</code> or * <code>protonServiceRoleArn</code> parameter and value. * </p> * * @param protonServiceRoleArn * The Amazon Resource Name (ARN) of the AWS Proton service role that allows AWS Proton to make calls to * other services on your behalf. You must include either the <code>environmentAccountConnectionId</code> or * <code>protonServiceRoleArn</code> parameter and value. */ public void setProtonServiceRoleArn(String protonServiceRoleArn) { this.protonServiceRoleArn = protonServiceRoleArn; } /** * <p> * The Amazon Resource Name (ARN) of the AWS Proton service role that allows AWS Proton to make calls to other * services on your behalf. You must include either the <code>environmentAccountConnectionId</code> or * <code>protonServiceRoleArn</code> parameter and value. * </p> * * @return The Amazon Resource Name (ARN) of the AWS Proton service role that allows AWS Proton to make calls to * other services on your behalf. You must include either the <code>environmentAccountConnectionId</code> or * <code>protonServiceRoleArn</code> parameter and value. */ public String getProtonServiceRoleArn() { return this.protonServiceRoleArn; } /** * <p> * The Amazon Resource Name (ARN) of the AWS Proton service role that allows AWS Proton to make calls to other * services on your behalf. You must include either the <code>environmentAccountConnectionId</code> or * <code>protonServiceRoleArn</code> parameter and value. * </p> * * @param protonServiceRoleArn * The Amazon Resource Name (ARN) of the AWS Proton service role that allows AWS Proton to make calls to * other services on your behalf. You must include either the <code>environmentAccountConnectionId</code> or * <code>protonServiceRoleArn</code> parameter and value. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateEnvironmentRequest withProtonServiceRoleArn(String protonServiceRoleArn) { setProtonServiceRoleArn(protonServiceRoleArn); return this; } /** * <p> * A link to a YAML formatted spec file that provides inputs as defined in the environment template bundle schema * file. For more information, see <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/ag-environments.html">Environments</a> in the <i>AWS * Proton Administrator Guide</i>. * </p> * * @param spec * A link to a YAML formatted spec file that provides inputs as defined in the environment template bundle * schema file. For more information, see <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/ag-environments.html">Environments</a> in the * <i>AWS Proton Administrator Guide</i>. */ public void setSpec(String spec) { this.spec = spec; } /** * <p> * A link to a YAML formatted spec file that provides inputs as defined in the environment template bundle schema * file. For more information, see <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/ag-environments.html">Environments</a> in the <i>AWS * Proton Administrator Guide</i>. * </p> * * @return A link to a YAML formatted spec file that provides inputs as defined in the environment template bundle * schema file. For more information, see <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/ag-environments.html">Environments</a> in the * <i>AWS Proton Administrator Guide</i>. */ public String getSpec() { return this.spec; } /** * <p> * A link to a YAML formatted spec file that provides inputs as defined in the environment template bundle schema * file. For more information, see <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/ag-environments.html">Environments</a> in the <i>AWS * Proton Administrator Guide</i>. * </p> * * @param spec * A link to a YAML formatted spec file that provides inputs as defined in the environment template bundle * schema file. For more information, see <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/ag-environments.html">Environments</a> in the * <i>AWS Proton Administrator Guide</i>. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateEnvironmentRequest withSpec(String spec) { setSpec(spec); return this; } /** * <p> * Create tags for your environment. For more information, see <i>AWS Proton resources and tagging</i> in the <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/resources.html">AWS Proton Administrator Guide</a> or * <a href="https://docs.aws.amazon.com/proton/latest/userguide/resources.html">AWS Proton User Guide</a>. * </p> * * @return Create tags for your environment. For more information, see <i>AWS Proton resources and tagging</i> in * the <a href="https://docs.aws.amazon.com/proton/latest/adminguide/resources.html">AWS Proton * Administrator Guide</a> or <a * href="https://docs.aws.amazon.com/proton/latest/userguide/resources.html">AWS Proton User Guide</a>. */ public java.util.List<Tag> getTags() { return tags; } /** * <p> * Create tags for your environment. For more information, see <i>AWS Proton resources and tagging</i> in the <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/resources.html">AWS Proton Administrator Guide</a> or * <a href="https://docs.aws.amazon.com/proton/latest/userguide/resources.html">AWS Proton User Guide</a>. * </p> * * @param tags * Create tags for your environment. For more information, see <i>AWS Proton resources and tagging</i> in the * <a href="https://docs.aws.amazon.com/proton/latest/adminguide/resources.html">AWS Proton Administrator * Guide</a> or <a href="https://docs.aws.amazon.com/proton/latest/userguide/resources.html">AWS Proton User * Guide</a>. */ public void setTags(java.util.Collection<Tag> tags) { if (tags == null) { this.tags = null; return; } this.tags = new java.util.ArrayList<Tag>(tags); } /** * <p> * Create tags for your environment. For more information, see <i>AWS Proton resources and tagging</i> in the <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/resources.html">AWS Proton Administrator Guide</a> or * <a href="https://docs.aws.amazon.com/proton/latest/userguide/resources.html">AWS Proton User Guide</a>. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setTags(java.util.Collection)} or {@link #withTags(java.util.Collection)} if you want to override the * existing values. * </p> * * @param tags * Create tags for your environment. For more information, see <i>AWS Proton resources and tagging</i> in the * <a href="https://docs.aws.amazon.com/proton/latest/adminguide/resources.html">AWS Proton Administrator * Guide</a> or <a href="https://docs.aws.amazon.com/proton/latest/userguide/resources.html">AWS Proton User * Guide</a>. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateEnvironmentRequest withTags(Tag... tags) { if (this.tags == null) { setTags(new java.util.ArrayList<Tag>(tags.length)); } for (Tag ele : tags) { this.tags.add(ele); } return this; } /** * <p> * Create tags for your environment. For more information, see <i>AWS Proton resources and tagging</i> in the <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/resources.html">AWS Proton Administrator Guide</a> or * <a href="https://docs.aws.amazon.com/proton/latest/userguide/resources.html">AWS Proton User Guide</a>. * </p> * * @param tags * Create tags for your environment. For more information, see <i>AWS Proton resources and tagging</i> in the * <a href="https://docs.aws.amazon.com/proton/latest/adminguide/resources.html">AWS Proton Administrator * Guide</a> or <a href="https://docs.aws.amazon.com/proton/latest/userguide/resources.html">AWS Proton User * Guide</a>. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateEnvironmentRequest withTags(java.util.Collection<Tag> tags) { setTags(tags); return this; } /** * <p> * The ID of the major version of the environment template. * </p> * * @param templateMajorVersion * The ID of the major version of the environment template. */ public void setTemplateMajorVersion(String templateMajorVersion) { this.templateMajorVersion = templateMajorVersion; } /** * <p> * The ID of the major version of the environment template. * </p> * * @return The ID of the major version of the environment template. */ public String getTemplateMajorVersion() { return this.templateMajorVersion; } /** * <p> * The ID of the major version of the environment template. * </p> * * @param templateMajorVersion * The ID of the major version of the environment template. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateEnvironmentRequest withTemplateMajorVersion(String templateMajorVersion) { setTemplateMajorVersion(templateMajorVersion); return this; } /** * <p> * The ID of the minor version of the environment template. * </p> * * @param templateMinorVersion * The ID of the minor version of the environment template. */ public void setTemplateMinorVersion(String templateMinorVersion) { this.templateMinorVersion = templateMinorVersion; } /** * <p> * The ID of the minor version of the environment template. * </p> * * @return The ID of the minor version of the environment template. */ public String getTemplateMinorVersion() { return this.templateMinorVersion; } /** * <p> * The ID of the minor version of the environment template. * </p> * * @param templateMinorVersion * The ID of the minor version of the environment template. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateEnvironmentRequest withTemplateMinorVersion(String templateMinorVersion) { setTemplateMinorVersion(templateMinorVersion); return this; } /** * <p> * The name of the environment template. For more information, see <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/ag-templates.html">Environment Templates</a> in the * <i>AWS Proton Administrator Guide</i>. * </p> * * @param templateName * The name of the environment template. For more information, see <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/ag-templates.html">Environment Templates</a> in * the <i>AWS Proton Administrator Guide</i>. */ public void setTemplateName(String templateName) { this.templateName = templateName; } /** * <p> * The name of the environment template. For more information, see <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/ag-templates.html">Environment Templates</a> in the * <i>AWS Proton Administrator Guide</i>. * </p> * * @return The name of the environment template. For more information, see <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/ag-templates.html">Environment Templates</a> * in the <i>AWS Proton Administrator Guide</i>. */ public String getTemplateName() { return this.templateName; } /** * <p> * The name of the environment template. For more information, see <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/ag-templates.html">Environment Templates</a> in the * <i>AWS Proton Administrator Guide</i>. * </p> * * @param templateName * The name of the environment template. For more information, see <a * href="https://docs.aws.amazon.com/proton/latest/adminguide/ag-templates.html">Environment Templates</a> in * the <i>AWS Proton Administrator Guide</i>. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateEnvironmentRequest withTemplateName(String templateName) { setTemplateName(templateName); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getDescription() != null) sb.append("Description: ").append("***Sensitive Data Redacted***").append(","); if (getEnvironmentAccountConnectionId() != null) sb.append("EnvironmentAccountConnectionId: ").append(getEnvironmentAccountConnectionId()).append(","); if (getName() != null) sb.append("Name: ").append(getName()).append(","); if (getProtonServiceRoleArn() != null) sb.append("ProtonServiceRoleArn: ").append(getProtonServiceRoleArn()).append(","); if (getSpec() != null) sb.append("Spec: ").append("***Sensitive Data Redacted***").append(","); if (getTags() != null) sb.append("Tags: ").append(getTags()).append(","); if (getTemplateMajorVersion() != null) sb.append("TemplateMajorVersion: ").append(getTemplateMajorVersion()).append(","); if (getTemplateMinorVersion() != null) sb.append("TemplateMinorVersion: ").append(getTemplateMinorVersion()).append(","); if (getTemplateName() != null) sb.append("TemplateName: ").append(getTemplateName()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CreateEnvironmentRequest == false) return false; CreateEnvironmentRequest other = (CreateEnvironmentRequest) obj; if (other.getDescription() == null ^ this.getDescription() == null) return false; if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false; if (other.getEnvironmentAccountConnectionId() == null ^ this.getEnvironmentAccountConnectionId() == null) return false; if (other.getEnvironmentAccountConnectionId() != null && other.getEnvironmentAccountConnectionId().equals(this.getEnvironmentAccountConnectionId()) == false) return false; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getProtonServiceRoleArn() == null ^ this.getProtonServiceRoleArn() == null) return false; if (other.getProtonServiceRoleArn() != null && other.getProtonServiceRoleArn().equals(this.getProtonServiceRoleArn()) == false) return false; if (other.getSpec() == null ^ this.getSpec() == null) return false; if (other.getSpec() != null && other.getSpec().equals(this.getSpec()) == false) return false; if (other.getTags() == null ^ this.getTags() == null) return false; if (other.getTags() != null && other.getTags().equals(this.getTags()) == false) return false; if (other.getTemplateMajorVersion() == null ^ this.getTemplateMajorVersion() == null) return false; if (other.getTemplateMajorVersion() != null && other.getTemplateMajorVersion().equals(this.getTemplateMajorVersion()) == false) return false; if (other.getTemplateMinorVersion() == null ^ this.getTemplateMinorVersion() == null) return false; if (other.getTemplateMinorVersion() != null && other.getTemplateMinorVersion().equals(this.getTemplateMinorVersion()) == false) return false; if (other.getTemplateName() == null ^ this.getTemplateName() == null) return false; if (other.getTemplateName() != null && other.getTemplateName().equals(this.getTemplateName()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode()); hashCode = prime * hashCode + ((getEnvironmentAccountConnectionId() == null) ? 0 : getEnvironmentAccountConnectionId().hashCode()); hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getProtonServiceRoleArn() == null) ? 0 : getProtonServiceRoleArn().hashCode()); hashCode = prime * hashCode + ((getSpec() == null) ? 0 : getSpec().hashCode()); hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode()); hashCode = prime * hashCode + ((getTemplateMajorVersion() == null) ? 0 : getTemplateMajorVersion().hashCode()); hashCode = prime * hashCode + ((getTemplateMinorVersion() == null) ? 0 : getTemplateMinorVersion().hashCode()); hashCode = prime * hashCode + ((getTemplateName() == null) ? 0 : getTemplateName().hashCode()); return hashCode; } @Override public CreateEnvironmentRequest clone() { return (CreateEnvironmentRequest) super.clone(); } }
923d27853492810cb2d528a229341d2969ff5530
216
java
Java
design-facade/src/main/java/alex/study/facade/Rectangle.java
ekko1994/Design-Patterns
b56b378d94eab707be7d9f8e73807d2f85435963
[ "Apache-2.0" ]
3
2021-02-26T07:23:52.000Z
2021-02-26T07:26:36.000Z
design-facade/src/main/java/alex/study/facade/Rectangle.java
ekko1994/Design-Patterns
b56b378d94eab707be7d9f8e73807d2f85435963
[ "Apache-2.0" ]
null
null
null
design-facade/src/main/java/alex/study/facade/Rectangle.java
ekko1994/Design-Patterns
b56b378d94eab707be7d9f8e73807d2f85435963
[ "Apache-2.0" ]
null
null
null
16.615385
45
0.638889
1,000,199
package alex.study.facade; /** * @author zhanghao * @date 2020/11/10 11:10 */ public class Rectangle implements Shape{ @Override public void draw() { System.out.println("draw rectangle"); } }
923d27f0095c16adc575c871bea92ca44a39e986
1,187
java
Java
gunit-commons/src/main/java/edu/chl/gunit/commons/api/ApiUserBadge.java
davidarnarsson/GUnit
93384351d70dbfe4984057e295ddd547652d9881
[ "MIT" ]
1
2015-04-01T07:49:00.000Z
2015-04-01T07:49:00.000Z
gunit-commons/src/main/java/edu/chl/gunit/commons/api/ApiUserBadge.java
davidarnarsson/GUnit
93384351d70dbfe4984057e295ddd547652d9881
[ "MIT" ]
null
null
null
gunit-commons/src/main/java/edu/chl/gunit/commons/api/ApiUserBadge.java
davidarnarsson/GUnit
93384351d70dbfe4984057e295ddd547652d9881
[ "MIT" ]
null
null
null
17.716418
53
0.635215
1,000,200
package edu.chl.gunit.commons.api; import com.fasterxml.jackson.annotation.JsonProperty; import java.sql.Timestamp; /** * Created by davida on 4.3.2015. */ public class ApiUserBadge { @JsonProperty public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } private int userId; private ApiBadge badge; private Timestamp earnedDate; private ApiRule fromRule; @JsonProperty public ApiBadge getBadge() { return badge; } public void setBadge(ApiBadge badge) { this.badge = badge; } @JsonProperty public Timestamp getEarnedDate() { return earnedDate; } public void setEarnedDate(Timestamp earnedDate) { this.earnedDate = earnedDate; } @JsonProperty public ApiRule getFromRule() { return fromRule; } public void setFromRule(ApiRule fromRule) { this.fromRule = fromRule; } @JsonProperty public int getSessionId() { return sessionId; } public void setSessionId(int sessionId) { this.sessionId = sessionId; } private int sessionId; }
923d2894575f8449e5d5ed8636ddbbe92c5d0a65
4,911
java
Java
app/src/main/java/connect/ui/activity/contact/adapter/RecommendAdapter.java
connectim/Android
ea5cf66f04b58c33732c04814e1cb3635031f892
[ "MIT" ]
23
2017-05-09T03:11:07.000Z
2022-03-21T17:02:17.000Z
app/src/main/java/connect/ui/activity/contact/adapter/RecommendAdapter.java
connectim/Android
ea5cf66f04b58c33732c04814e1cb3635031f892
[ "MIT" ]
6
2017-05-09T07:18:59.000Z
2018-11-12T14:47:23.000Z
app/src/main/java/connect/ui/activity/contact/adapter/RecommendAdapter.java
connectim/Android
ea5cf66f04b58c33732c04814e1cb3635031f892
[ "MIT" ]
23
2017-05-09T03:12:10.000Z
2022-03-21T17:02:20.000Z
29.763636
123
0.656485
1,000,201
package connect.ui.activity.contact.adapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import connect.db.green.bean.RecommandFriendEntity; import connect.ui.activity.R; import connect.utils.system.SystemDataUtil; import connect.utils.system.SystemUtil; import connect.utils.glide.GlideUtil; import connect.view.SideScrollView; import connect.view.roundedimageview.RoundedImageView; /** * Created by Administrator on 2017/1/21. */ public class RecommendAdapter extends BaseAdapter { private ArrayList<RecommandFriendEntity> mList = new ArrayList<>(); private OnAddListence onAddListence; @Override public int getCount() { return mList.size(); } @Override public Object getItem(int position) { return mList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_contact_recommend, parent, false); viewHolder = new ViewHolder(convertView); viewHolder.contentLayout.getLayoutParams().width = SystemDataUtil.getScreenWidth(); viewHolder.sideScrollView.setSideScrollListener(sideScrollListener); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } final RecommandFriendEntity recommendEntity = mList.get(position); GlideUtil.loadAvater(viewHolder.avatarRimg,recommendEntity.getAvatar() + "?size=80"); viewHolder.nicknameTv.setText(recommendEntity.getUsername()); viewHolder.statusBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onAddListence.add(position,recommendEntity); } }); viewHolder.contentLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onAddListence.itemClick(position,recommendEntity); } }); viewHolder.deleteTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onAddListence.deleteItem(position,recommendEntity); } }); return convertView; } public void setDataNotify(List list,boolean isClear) { if(isClear) mList.clear(); mList.addAll(list); notifyDataSetChanged(); } public ArrayList<RecommandFriendEntity> getData(){ return mList; } static class ViewHolder { @Bind(R.id.delete_tv) ImageView deleteTv; @Bind(R.id.bottom_layout) RelativeLayout bottomLayout; @Bind(R.id.avatar_rimg) RoundedImageView avatarRimg; @Bind(R.id.nickname_tv) TextView nicknameTv; @Bind(R.id.status_btn) Button statusBtn; @Bind(R.id.content_layout) RelativeLayout contentLayout; @Bind(R.id.side_scroll_view) SideScrollView sideScrollView; @Bind(R.id.content_rela) LinearLayout contentRela; ViewHolder(View view) { ButterKnife.bind(this, view); } } public void closeMenu() { if (sideScrollView != null) { sideScrollView.closeMenu(); sideScrollView = null; } } public Boolean menuIsOpen() { return sideScrollView != null; } private SideScrollView sideScrollView; private SideScrollView.SideScrollListener sideScrollListener = new SideScrollView.SideScrollListener() { @Override public void onMenuIsOpen(View view) { sideScrollView = (SideScrollView) view; } @Override public void onDownOrMove(SideScrollView slidingButtonView) { if (menuIsOpen()) { if (sideScrollView != slidingButtonView) { closeMenu(); } } } }; public void setOnAddListence(OnAddListence onAddListence) { this.onAddListence = onAddListence; } public interface OnAddListence { void add(int position, RecommandFriendEntity entity); void itemClick(int position, RecommandFriendEntity entity); void deleteItem(int position, RecommandFriendEntity entity); } }
923d2c029d9cb8d6256bcaa452f2f0eb77f4076b
855
java
Java
backend/monolith/mono-sender-service/src/main/java/dev/alexengrig/myim/mono/sender/payload/condition/SearchResponse.java
alexengrig/myim
ea21e6336fc46752f4108c5c840ee9a02872e8e6
[ "Apache-2.0" ]
null
null
null
backend/monolith/mono-sender-service/src/main/java/dev/alexengrig/myim/mono/sender/payload/condition/SearchResponse.java
alexengrig/myim
ea21e6336fc46752f4108c5c840ee9a02872e8e6
[ "Apache-2.0" ]
16
2022-01-21T21:29:47.000Z
2022-03-29T21:27:22.000Z
backend/monolith/mono-sender-service/src/main/java/dev/alexengrig/myim/mono/sender/payload/condition/SearchResponse.java
alexengrig/myim
ea21e6336fc46752f4108c5c840ee9a02872e8e6
[ "Apache-2.0" ]
null
null
null
26.71875
75
0.746199
1,000,202
/* * Copyright 2022 Alexengrig Dev. * * 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 dev.alexengrig.myim.mono.sender.payload.condition; import lombok.Data; import lombok.experimental.SuperBuilder; import java.util.List; @Data @SuperBuilder public class SearchResponse<T> { private List<T> values; private long total; }
923d2c4381f2c17b943cf85f97433b69a2ea88d9
25,610
java
Java
corpus/class/eclipse.jdt.core/844.java
masud-technope/ACER-Replication-Package-ASE2017
cb7318a729eb1403004d451a164c851af2d81f7a
[ "MIT" ]
15
2018-07-10T09:38:31.000Z
2021-11-29T08:28:07.000Z
corpus/class/eclipse.jdt.core/844.java
masud-technope/ACER-Replication-Package-ASE2017
cb7318a729eb1403004d451a164c851af2d81f7a
[ "MIT" ]
3
2018-11-16T02:58:59.000Z
2021-01-20T16:03:51.000Z
corpus/class/eclipse.jdt.core/844.java
masud-technope/ACER-Replication-Package-ASE2017
cb7318a729eb1403004d451a164c851af2d81f7a
[ "MIT" ]
6
2018-06-27T20:19:00.000Z
2022-02-19T02:29:53.000Z
40.458136
251
0.585553
1,000,203
/******************************************************************************* * Copyright (c) 2000, 2016 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.core.dom.rewrite; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.eclipse.core.runtime.Assert; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.Annotation; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.BodyDeclaration; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.Statement; import org.eclipse.jdt.core.formatter.CodeFormatter; import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; import org.eclipse.jdt.core.formatter.IndentManipulation; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.DefaultPositionUpdater; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.Position; import org.eclipse.text.edits.DeleteEdit; import org.eclipse.text.edits.InsertEdit; import org.eclipse.text.edits.MultiTextEdit; import org.eclipse.text.edits.ReplaceEdit; import org.eclipse.text.edits.TextEdit; @SuppressWarnings({ "rawtypes", "unchecked" }) public final class ASTRewriteFormatter { public static class NodeMarker extends Position { public Object data; } private class ExtendedFlattener extends ASTRewriteFlattener { private ArrayList positions; public ExtendedFlattener(RewriteEventStore store) { super(store); this.positions = new ArrayList(); } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#preVisit(ASTNode) */ public void preVisit(ASTNode node) { Object trackData = getEventStore().getTrackedNodeData(node); if (trackData != null) { addMarker(trackData, this.result.length(), 0); } Object placeholderData = getPlaceholders().getPlaceholderData(node); if (placeholderData != null) { addMarker(placeholderData, this.result.length(), 0); } } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#postVisit(ASTNode) */ public void postVisit(ASTNode node) { Object placeholderData = getPlaceholders().getPlaceholderData(node); if (placeholderData != null) { fixupLength(placeholderData, this.result.length()); } Object trackData = getEventStore().getTrackedNodeData(node); if (trackData != null) { fixupLength(trackData, this.result.length()); } } /* (non-Javadoc) * @see org.eclipse.jdt.internal.corext.dom.ASTRewriteFlattener#visit(org.eclipse.jdt.core.dom.Block) */ public boolean visit(Block node) { if (getPlaceholders().isCollapsed(node)) { visitList(node, Block.STATEMENTS_PROPERTY, null); return false; } return super.visit(node); } private NodeMarker addMarker(Object annotation, int startOffset, int length) { NodeMarker marker = new NodeMarker(); marker.offset = startOffset; marker.length = length; marker.data = annotation; this.positions.add(marker); return marker; } private void fixupLength(Object data, int endOffset) { for (int i = this.positions.size() - 1; i >= 0; i--) { NodeMarker marker = (NodeMarker) this.positions.get(i); if (marker.data == data) { marker.length = endOffset - marker.offset; return; } } } public NodeMarker[] getMarkers() { return (NodeMarker[]) this.positions.toArray(new NodeMarker[this.positions.size()]); } } private final String lineDelimiter; private final int tabWidth; private final int indentWidth; private final NodeInfoStore placeholders; private final RewriteEventStore eventStore; private final Map options; public ASTRewriteFormatter(NodeInfoStore placeholders, RewriteEventStore eventStore, Map options, String lineDelimiter) { this.placeholders = placeholders; this.eventStore = eventStore; this.options = options == null ? JavaCore.getOptions() : (Map) new HashMap(options); this.options.put(DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_RESOURCES_IN_TRY, DefaultCodeFormatterConstants.createAlignmentValue(true, DefaultCodeFormatterConstants.WRAP_NEXT_PER_LINE, DefaultCodeFormatterConstants.INDENT_DEFAULT)); this.lineDelimiter = lineDelimiter; this.tabWidth = IndentManipulation.getTabWidth(options); this.indentWidth = IndentManipulation.getIndentWidth(options); } public NodeInfoStore getPlaceholders() { return this.placeholders; } public RewriteEventStore getEventStore() { return this.eventStore; } public int getTabWidth() { return this.tabWidth; } public int getIndentWidth() { return this.indentWidth; } public String getLineDelimiter() { return this.lineDelimiter; } /** * Returns the string accumulated in the visit formatted using the default formatter. * Updates the existing node's positions. * * @param node The node to flatten. * @param initialIndentationLevel The initial indentation level. * @param resultingMarkers Resulting the updated NodeMarkers. * @return Returns the serialized and formatted code. */ public String getFormattedResult(ASTNode node, int initialIndentationLevel, Collection resultingMarkers) { ExtendedFlattener flattener = new ExtendedFlattener(this.eventStore); node.accept(flattener); NodeMarker[] markers = flattener.getMarkers(); for (int i = 0; i < markers.length; i++) { // add to result resultingMarkers.add(markers[i]); } String unformatted = flattener.getResult(); TextEdit edit = formatNode(node, unformatted, initialIndentationLevel); if (edit == null) { if (initialIndentationLevel > 0) { // at least correct the indent String indentString = createIndentString(initialIndentationLevel); ReplaceEdit[] edits = IndentManipulation.getChangeIndentEdits(unformatted, 0, this.tabWidth, this.indentWidth, indentString); edit = new MultiTextEdit(); edit.addChild(new InsertEdit(0, indentString)); edit.addChildren(edits); } else { return unformatted; } } return evaluateFormatterEdit(unformatted, edit, markers); } public String createIndentString(int indentationUnits) { return ToolFactory.createCodeFormatter(this.options).createIndentationString(indentationUnits); } public String getIndentString(String currentLine) { return IndentManipulation.extractIndentString(currentLine, this.tabWidth, this.indentWidth); } public String changeIndent(String code, int codeIndentLevel, String newIndent) { return IndentManipulation.changeIndent(code, codeIndentLevel, this.tabWidth, this.indentWidth, newIndent, this.lineDelimiter); } public int computeIndentUnits(String line) { return IndentManipulation.measureIndentUnits(line, this.tabWidth, this.indentWidth); } /** * Evaluates the edit on the given string. * @param string The string to format * @param edit The edit resulted from the code formatter * @param positions Positions to update or <code>null</code>. * @return The formatted string * @throws IllegalArgumentException If the positions are not inside the string, a * IllegalArgumentException is thrown. */ public static String evaluateFormatterEdit(String string, TextEdit edit, Position[] positions) { try { Document doc = createDocument(string, positions); edit.apply(doc, 0); if (positions != null) { for (int i = 0; i < positions.length; i++) { Assert.isTrue(!positions[i].isDeleted, "Position got deleted"); } } return doc.get(); } catch (BadLocationException e) { Assert.isTrue(false, "Fromatter created edits with wrong positions: " + e.getMessage()); } return null; } public TextEdit formatString(int kind, String string, int offset, int length, int indentationLevel) { return ToolFactory.createCodeFormatter(this.options).format(kind, string, offset, length, indentationLevel, this.lineDelimiter); } /** * Creates edits that describe how to format the given string. Returns <code>null</code> if the code could not be formatted for the given kind. * @param node Node describing the type of the string * @param str The unformatted string * @param indentationLevel * @return Returns the edit representing the result of the formatter * @throws IllegalArgumentException If the offset and length are not inside the string, a * IllegalArgumentException is thrown. */ private TextEdit formatNode(ASTNode node, String str, int indentationLevel) { int code; //$NON-NLS-1$ String prefix = ""; //$NON-NLS-1$ String suffix = ""; if (node instanceof Statement) { code = CodeFormatter.K_STATEMENTS; if (node.getNodeType() == ASTNode.SWITCH_CASE) { //$NON-NLS-1$ prefix = //$NON-NLS-1$ "switch(1) {"; //$NON-NLS-1$ suffix = "}"; code = CodeFormatter.K_STATEMENTS; } } else if (node instanceof Expression && node.getNodeType() != ASTNode.VARIABLE_DECLARATION_EXPRESSION) { if (node instanceof Annotation) { suffix = "\nclass A {}"; code = CodeFormatter.K_COMPILATION_UNIT; } else { code = CodeFormatter.K_EXPRESSION; } } else if (node instanceof BodyDeclaration) { code = CodeFormatter.K_CLASS_BODY_DECLARATIONS; } else { switch(node.getNodeType()) { case ASTNode.ARRAY_TYPE: case ASTNode.PARAMETERIZED_TYPE: case ASTNode.PRIMITIVE_TYPE: case ASTNode.QUALIFIED_TYPE: case ASTNode.SIMPLE_TYPE: //$NON-NLS-1$ prefix = //$NON-NLS-1$ "void m(final "; //$NON-NLS-1$ suffix = " x);"; code = CodeFormatter.K_CLASS_BODY_DECLARATIONS; break; case ASTNode.WILDCARD_TYPE: //$NON-NLS-1$ prefix = "A<"; //$NON-NLS-1$ suffix = "> x;"; code = CodeFormatter.K_CLASS_BODY_DECLARATIONS; break; case ASTNode.COMPILATION_UNIT: code = CodeFormatter.K_COMPILATION_UNIT; break; case ASTNode.VARIABLE_DECLARATION_EXPRESSION: //$NON-NLS-1$ suffix = ";"; code = CodeFormatter.K_STATEMENTS; break; case ASTNode.SINGLE_VARIABLE_DECLARATION: //$NON-NLS-1$ prefix = "void m("; //$NON-NLS-1$ suffix = ");"; code = CodeFormatter.K_CLASS_BODY_DECLARATIONS; break; case ASTNode.VARIABLE_DECLARATION_FRAGMENT: //$NON-NLS-1$ prefix = "A "; //$NON-NLS-1$ suffix = ";"; code = CodeFormatter.K_STATEMENTS; break; case ASTNode.PACKAGE_DECLARATION: case ASTNode.IMPORT_DECLARATION: //$NON-NLS-1$ suffix = //$NON-NLS-1$ "\nclass A {}"; code = CodeFormatter.K_COMPILATION_UNIT; break; case ASTNode.JAVADOC: //$NON-NLS-1$ suffix = //$NON-NLS-1$ "\nclass A {}"; code = CodeFormatter.K_COMPILATION_UNIT; break; case ASTNode.CATCH_CLAUSE: //$NON-NLS-1$ prefix = "try {}"; code = CodeFormatter.K_STATEMENTS; break; case ASTNode.ANONYMOUS_CLASS_DECLARATION: //$NON-NLS-1$ prefix = "new A()"; //$NON-NLS-1$ suffix = ";"; code = CodeFormatter.K_STATEMENTS; break; case ASTNode.MEMBER_VALUE_PAIR: //$NON-NLS-1$ prefix = //$NON-NLS-1$ "@Author("; //$NON-NLS-1$ suffix = //$NON-NLS-1$ ") class x {}"; code = CodeFormatter.K_COMPILATION_UNIT; break; case ASTNode.MODIFIER: //$NON-NLS-1$ suffix = //$NON-NLS-1$ " class x {}"; code = CodeFormatter.K_COMPILATION_UNIT; break; case ASTNode.TYPE_PARAMETER: //$NON-NLS-1$ prefix = //$NON-NLS-1$ "class X<"; //$NON-NLS-1$ suffix = "> {}"; code = CodeFormatter.K_COMPILATION_UNIT; break; case ASTNode.MEMBER_REF: case ASTNode.METHOD_REF: case ASTNode.METHOD_REF_PARAMETER: case ASTNode.TAG_ELEMENT: case ASTNode.TEXT_ELEMENT: // javadoc formatting disabled due to bug 93644 return null; // break; default: //Assert.isTrue(false, "Node type not covered: " + node.getClass().getName()); return null; } } String concatStr = prefix + str + suffix; TextEdit edit = formatString(code, concatStr, prefix.length(), str.length(), indentationLevel); if (prefix.length() > 0) { edit = shifEdit(edit, prefix.length()); } return edit; } private static TextEdit shifEdit(TextEdit oldEdit, int diff) { TextEdit newEdit; if (oldEdit instanceof ReplaceEdit) { ReplaceEdit edit = (ReplaceEdit) oldEdit; newEdit = new ReplaceEdit(edit.getOffset() - diff, edit.getLength(), edit.getText()); } else if (oldEdit instanceof InsertEdit) { InsertEdit edit = (InsertEdit) oldEdit; newEdit = new InsertEdit(edit.getOffset() - diff, edit.getText()); } else if (oldEdit instanceof DeleteEdit) { DeleteEdit edit = (DeleteEdit) oldEdit; newEdit = new DeleteEdit(edit.getOffset() - diff, edit.getLength()); } else if (oldEdit instanceof MultiTextEdit) { newEdit = new MultiTextEdit(); } else { // not supported return null; } TextEdit[] children = oldEdit.getChildren(); for (int i = 0; i < children.length; i++) { TextEdit shifted = shifEdit(children[i], diff); if (shifted != null) { newEdit.addChild(shifted); } } return newEdit; } private static Document createDocument(String string, Position[] positions) throws IllegalArgumentException { Document doc = new Document(string); try { if (positions != null) { final String //$NON-NLS-1$ POS_CATEGORY = //$NON-NLS-1$ "myCategory"; doc.addPositionCategory(POS_CATEGORY); doc.addPositionUpdater(new DefaultPositionUpdater(POS_CATEGORY) { protected boolean notDeleted() { int start = this.fOffset; int end = start + this.fLength; if (start < this.fPosition.offset && (this.fPosition.offset + this.fPosition.length < end)) { // deleted positions: set to end of remove this.fPosition.offset = end; return false; } return true; } }); for (int i = 0; i < positions.length; i++) { try { doc.addPosition(POS_CATEGORY, positions[i]); } catch (BadLocationException e) { throw new IllegalArgumentException("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + string.length()); } } } } catch (BadPositionCategoryException cannotHappen) { } return doc; } public static interface Prefix { String getPrefix(int indent); } public static interface BlockContext { String[] getPrefixAndSuffix(int indent, ASTNode node, RewriteEventStore events); } public static class ConstPrefix implements Prefix { private String prefix; public ConstPrefix(String prefix) { this.prefix = prefix; } public String getPrefix(int indent) { return this.prefix; } } private class FormattingPrefix implements Prefix { private int kind; private String string; private int start; private int length; public FormattingPrefix(String string, String sub, int kind) { this.start = string.indexOf(sub); this.length = sub.length(); this.string = string; this.kind = kind; } public String getPrefix(int indent) { Position pos = new Position(this.start, this.length); String str = this.string; TextEdit res = formatString(this.kind, str, 0, str.length(), indent); if (res != null) { str = evaluateFormatterEdit(str, res, new Position[] { pos }); } return str.substring(pos.offset + 1, pos.offset + pos.length - 1); } } private class BlockFormattingPrefix implements BlockContext { private String prefix; private int start; public BlockFormattingPrefix(String prefix, int start) { this.start = start; this.prefix = prefix; } public String[] getPrefixAndSuffix(int indent, ASTNode node, RewriteEventStore events) { String nodeString = ASTRewriteFlattener.asString(node, events); String str = this.prefix + nodeString; Position pos = new Position(this.start, this.prefix.length() + 1 - this.start); TextEdit res = formatString(CodeFormatter.K_STATEMENTS, str, 0, str.length(), indent); if (res != null) { str = evaluateFormatterEdit(str, res, new Position[] { pos }); } //$NON-NLS-1$ return new String[] { str.substring(pos.offset + 1, pos.offset + pos.length - 1), "" }; } } private class BlockFormattingPrefixSuffix implements BlockContext { private String prefix; private String suffix; private int start; public BlockFormattingPrefixSuffix(String prefix, String suffix, int start) { this.start = start; this.suffix = suffix; this.prefix = prefix; } public String[] getPrefixAndSuffix(int indent, ASTNode node, RewriteEventStore events) { String nodeString = ASTRewriteFlattener.asString(node, events); int nodeStart = this.prefix.length(); int nodeEnd = nodeStart + nodeString.length() - 1; String str = this.prefix + nodeString + this.suffix; Position pos1 = new Position(this.start, nodeStart + 1 - this.start); Position pos2 = new Position(nodeEnd, 2); TextEdit res = formatString(CodeFormatter.K_STATEMENTS, str, 0, str.length(), indent); if (res != null) { str = evaluateFormatterEdit(str, res, new Position[] { pos1, pos2 }); } return new String[] { str.substring(pos1.offset + 1, pos1.offset + pos1.length - 1), str.substring(pos2.offset + 1, pos2.offset + pos2.length - 1) }; } } //$NON-NLS-1$ public static final Prefix NONE = new ConstPrefix(""); //$NON-NLS-1$ public static final Prefix SPACE = new ConstPrefix(" "); //$NON-NLS-1$ public static final Prefix ASSERT_COMMENT = new ConstPrefix(" : "); //$NON-NLS-1$ //$NON-NLS-2$ public final Prefix VAR_INITIALIZER = new FormattingPrefix("A a={};", "a={", CodeFormatter.K_STATEMENTS); //$NON-NLS-1$ //$NON-NLS-2$ public final Prefix METHOD_BODY = new FormattingPrefix("void a() {}", ") {", CodeFormatter.K_CLASS_BODY_DECLARATIONS); //$NON-NLS-1$ //$NON-NLS-2$ public final Prefix FINALLY_BLOCK = new FormattingPrefix("try {} finally {}", "} finally {", CodeFormatter.K_STATEMENTS); //$NON-NLS-1$ //$NON-NLS-2$ public final Prefix CATCH_BLOCK = new FormattingPrefix("try {} catch(Exception e) {}", "} c", CodeFormatter.K_STATEMENTS); //$NON-NLS-1$ //$NON-NLS-2$ public final Prefix ANNOT_MEMBER_DEFAULT = new FormattingPrefix("String value() default 1;", ") default 1", CodeFormatter.K_CLASS_BODY_DECLARATIONS); //$NON-NLS-1$ //$NON-NLS-2$ public final Prefix ENUM_BODY_START = new FormattingPrefix("enum E { A(){void foo(){}} }", "){v", CodeFormatter.K_COMPILATION_UNIT); //$NON-NLS-1$ //$NON-NLS-2$ public final Prefix ENUM_BODY_END = new FormattingPrefix("enum E { A(){void foo(){ }}, B}", "}},", CodeFormatter.K_COMPILATION_UNIT); //$NON-NLS-1$ //$NON-NLS-2$ public final Prefix WILDCARD_EXTENDS = new FormattingPrefix("A<? extends B> a;", "? extends B", CodeFormatter.K_CLASS_BODY_DECLARATIONS); //$NON-NLS-1$ //$NON-NLS-2$ public final Prefix WILDCARD_SUPER = new FormattingPrefix("A<? super B> a;", "? super B", CodeFormatter.K_CLASS_BODY_DECLARATIONS); //$NON-NLS-1$ //$NON-NLS-2$ public final Prefix FIRST_ENUM_CONST = new FormattingPrefix("enum E { X;}", "{ X", CodeFormatter.K_COMPILATION_UNIT); //$NON-NLS-1$ //$NON-NLS-2$ public final Prefix ANNOTATION_SEPARATION = new FormattingPrefix("@A @B class C {}", "A @", CodeFormatter.K_COMPILATION_UNIT); //$NON-NLS-1$ //$NON-NLS-2$ public final Prefix PARAM_ANNOTATION_SEPARATION = new FormattingPrefix("void foo(@A @B C p) { }", "A @", CodeFormatter.K_CLASS_BODY_DECLARATIONS); //$NON-NLS-1$ //$NON-NLS-2$ public final Prefix LOCAL_ANNOTATION_SEPARATION = new FormattingPrefix("@A @B C p;", "A @", CodeFormatter.K_STATEMENTS); //$NON-NLS-1$ //$NON-NLS-2$ public final Prefix TYPE_ANNOTATION_SEPARATION = new FormattingPrefix("C<@A @B D> l;", "A @", CodeFormatter.K_STATEMENTS); //$NON-NLS-1$ //$NON-NLS-2$ public final Prefix VARARGS = new FormattingPrefix("void foo(A ... a) { }", "A .", CodeFormatter.K_CLASS_BODY_DECLARATIONS); //$NON-NLS-1$ //$NON-NLS-2$ public final Prefix TRY_RESOURCES = new FormattingPrefix("try (A a = new A(); B b = new B()) {}", "; B", CodeFormatter.K_STATEMENTS); //$NON-NLS-1$ //$NON-NLS-2$ public final Prefix TRY_RESOURCES_PAREN = new FormattingPrefix("try (A a = new A(); B b = new B()) {}", "y (", CodeFormatter.K_STATEMENTS); //$NON-NLS-1$ //$NON-NLS-2$ public final BlockContext IF_BLOCK_WITH_ELSE = new BlockFormattingPrefixSuffix("if (true)", "else{}", 8); //$NON-NLS-1$ public final BlockContext IF_BLOCK_NO_ELSE = new BlockFormattingPrefix("if (true)", 8); //$NON-NLS-1$ public final BlockContext ELSE_AFTER_STATEMENT = new BlockFormattingPrefix("if (true) foo();else ", 15); //$NON-NLS-1$ public final BlockContext ELSE_AFTER_BLOCK = new BlockFormattingPrefix("if (true) {}else ", 11); //$NON-NLS-1$ public final BlockContext FOR_BLOCK = new BlockFormattingPrefix("for (;;) ", 7); //$NON-NLS-1$ public final BlockContext WHILE_BLOCK = new BlockFormattingPrefix("while (true)", 11); //$NON-NLS-1$ //$NON-NLS-2$ public final BlockContext DO_BLOCK = new BlockFormattingPrefixSuffix("do ", "while (true);", 1); }
923d2c87a64e2121f7b573bed08ca85c91db8155
2,299
java
Java
peppe/app/src/main/java/com/peppe/amanbhardwaj/peppe/bizobj/Reservations.java
aman2/project_peppe
be300d671dd04dc3a15eef8012502a48fe215f6c
[ "Apache-2.0" ]
null
null
null
peppe/app/src/main/java/com/peppe/amanbhardwaj/peppe/bizobj/Reservations.java
aman2/project_peppe
be300d671dd04dc3a15eef8012502a48fe215f6c
[ "Apache-2.0" ]
null
null
null
peppe/app/src/main/java/com/peppe/amanbhardwaj/peppe/bizobj/Reservations.java
aman2/project_peppe
be300d671dd04dc3a15eef8012502a48fe215f6c
[ "Apache-2.0" ]
null
null
null
22.539216
63
0.646803
1,000,204
package com.peppe.amanbhardwaj.peppe.bizobj; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Created by Nshthbhardwaj on 24/08/17. */ public class Reservations implements BizObj { private int entityID; private int userID; private int petID; private Date checkin_Date; private Date checkout_Date; private boolean isAccepted; private Double payments; private String paymentType; public int getEntityID() { return entityID; } public void setEntityID(int entityID) { this.entityID = entityID; } public int getUserID() { return userID; } public void setUserID(int userID) { this.userID = userID; } public int getPetID() { return petID; } public void setPetID(int petID) { this.petID = petID; } public Date getCheckin_Date() { return checkin_Date; } public void setCheckin_Date(Date checkin_Date) { this.checkin_Date = checkin_Date; } public Date getCheckout_Date() { return checkout_Date; } public void setCheckout_Date(Date checkout_Date) { this.checkout_Date = checkout_Date; } public boolean isAccepted() { return isAccepted; } public void setAccepted(boolean accepted) { isAccepted = accepted; } public Double getPayments() { return payments; } public void setPayments(Double payments) { this.payments = payments; } public String isPaymentType() { return paymentType; } public void setPaymentType(String paymentType) { this.paymentType = paymentType; } @Override public Map<String, Object> toMap() { Map<String,Object> reservationMap = new HashMap<>(); reservationMap.put("entityID",this.entityID); reservationMap.put("userID",this.userID); reservationMap.put("petID",this.petID); reservationMap.put("checkin_Date",this.checkin_Date); reservationMap.put("checkout_Date",this.checkout_Date); reservationMap.put("isAccepted",this.isAccepted); reservationMap.put("payments",this.payments); reservationMap.put("paymentType",this.paymentType); return reservationMap; } }
923d2cc76133b87d4c5987add36d698daf40f473
15,702
java
Java
java-server/VerifyStorageConformity/src/main/java/com/tracability/main/MainApp.java
marky7/Projet-CNAM-I2
5373e7d9f3f035eac93a50131874cf4cc17fb338
[ "MIT" ]
null
null
null
java-server/VerifyStorageConformity/src/main/java/com/tracability/main/MainApp.java
marky7/Projet-CNAM-I2
5373e7d9f3f035eac93a50131874cf4cc17fb338
[ "MIT" ]
null
null
null
java-server/VerifyStorageConformity/src/main/java/com/tracability/main/MainApp.java
marky7/Projet-CNAM-I2
5373e7d9f3f035eac93a50131874cf4cc17fb338
[ "MIT" ]
1
2018-08-13T17:26:22.000Z
2018-08-13T17:26:22.000Z
48.462963
260
0.540632
1,000,205
package com.tracability.main; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.drools.template.ObjectDataCompiler; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.kie.api.KieServices; import org.kie.api.builder.KieFileSystem; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.StatelessKieSession; import com.tracability.model.*; import com.tracability.model.Package; import com.tracability.rule.Rule; import com.rabbitmq.client.*; import java.io.IOException; public class MainApp { private final static String QUEUE_NAME = "file3"; public static void main(String[] args) throws Exception { /*Toutes les minutes on éxécute le code ci-dessous*/ // Création de la connexion try { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("172.17.0.2"); factory.setPort(5672); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); JSONParser parser = new JSONParser(); try{ Object receptedValue = parser.parse(message); JSONArray arrayOfValuesJsonAcquisition = new JSONArray(); arrayOfValuesJsonAcquisition.add(receptedValue); JSONObject level1Pars = (JSONObject) arrayOfValuesJsonAcquisition.get(0); /*Object Creation : storage area*/ JSONObject parsedStorageArea = (JSONObject) level1Pars.get("storageArea"); Boolean isMobile = Boolean.parseBoolean((String) parsedStorageArea.get("isMobile")); StorageArea CurrentstorageArea = new StorageArea((String) parsedStorageArea.get("address"), isMobile, null ); /*Object Creation : measures*/ JSONArray parsedMeasures = (JSONArray) level1Pars.get("measures"); String aqkDate="2018-10-12T18:17:39.993Z"; String measures_add = "["; int i; List<Measures> currentMeasures = new ArrayList<Measures>(); JSONObject tempMeasures; double gasValue, temperaturesValue, humidityValue; for(i=0; i< parsedMeasures.size(); i++) { tempMeasures = (JSONObject) parsedMeasures.get(i); if(tempMeasures.get("name") != null){ try { measures_add +="{"; gasValue = Double.parseDouble( tempMeasures.get("value").toString()); measures_add += "\"$class\": \"org.example.mynetwork.Gas\","; Date bis = new Date(); measures_add += "\"measureId\": \""+"Measure" + bis.getHours() + bis.getMinutes() + bis.getSeconds()+"\","; measures_add += "\"type\": \"Gas\","; measures_add += "\"creationDate\": \""+ tempMeasures.get("creationDate").toString() +"\","; measures_add += "\"name\": \"" + tempMeasures.get("name").toString()+ "\","; measures_add += "\"description\": \"" +tempMeasures.get("description").toString() + "\","; measures_add += "\"value\": \"" +String.valueOf( gasValue) + "\","; measures_add += "\"unit\": \""+ tempMeasures.get("unit").toString()+"\""; currentMeasures.add(new Gas(tempMeasures.get("creationDate").toString(),"Gas", null, gasValue,tempMeasures.get("name").toString(),tempMeasures.get("description").toString(),tempMeasures.get("unit").toString())); if(i== parsedMeasures.size()-1) measures_add +="}"; else measures_add +="},"; }catch(Exception e) { System.out.println("Erreur de conversion en double "); } // currentMeasures.add(new Gas(new Date(),"Gas", null, gasValue, (String) tempMeasures.get("name"),(String) tempMeasures.get("description"),(String) tempMeasures.get("unit"))); }else if(tempMeasures.get("temperatureUnit") != null) { try { measures_add +="{"; measures_add += "\"$class\": \"org.example.mynetwork.TemperatureHumidity\","; Date bis = new Date(); measures_add += "\"measureId\": \""+"Measure" + bis.getHours() + bis.getMinutes() + bis.getSeconds()+"\","; measures_add += "\"type\": \"temperatureHumidity\","; measures_add += "\"creationDate\": \""+ tempMeasures.get("creationDate").toString() +"\","; humidityValue = Double.parseDouble(tempMeasures.get("humidity").toString()); temperaturesValue = Double.parseDouble(tempMeasures.get("temperature").toString()); measures_add += "\"\"temperature\": \"" + String.valueOf(temperaturesValue ) + "\","; measures_add += "\"\"temperatureUnit\": \"" + tempMeasures.get("temperatureUnit").toString() + "\","; measures_add += "\"humidity\": \""+ String.valueOf(humidityValue) +"\","; measures_add += "\"humidityUnit\": \""+ tempMeasures.get("humidityUnit").toString() +"\""; currentMeasures.add(new TemperaturesHumidity(tempMeasures.get("creationDate").toString(),"temperature", null,temperaturesValue,tempMeasures.get("temperatureUnit").toString(),humidityValue,tempMeasures.get("humidityUnit").toString())); if(i!= parsedMeasures.size()-1) measures_add +="},"; else measures_add +="}"; }catch(Exception e) { System.out.println("parse to double error" + e); } } aqkDate = tempMeasures.get("creationDate").toString(); } /*Object Creation : tags*/ String tag_add = "["; List<Tag> currentTags = new ArrayList<Tag>(); JSONArray parsedTags = (JSONArray) level1Pars.get("tags"); JSONObject tag; for(i=0; i< parsedTags.size(); i++) { tag_add += "{\"creationDate\":\""+aqkDate+"\","; tag = (JSONObject) parsedTags.get(i); tag_add += "{\"value\":\""+ tag.get("value").toString()+"\","; tag_add += "{\"tagId\":\""+tag.get("tagId").toString()+"\""; currentTags.add(new Tag(tag.get("tagId").toString(), tag.get("value").toString(),new Date())); if(i !=parsedTags.size()-1) tag_add += "},"; else tag_add += "}"; } /*Ajout en base..*/ List<String> aquisitionId = new ArrayList<String>(); List<String> aquisitionValues = new ArrayList<String>(); //Ajout Id Aquisition aquisitionId.add("acquisitionId"); Date d = new Date(); aquisitionValues.add("Acquisition" + d.getHours() + d.getMinutes() + d.getSeconds()); aquisitionId.add("creationDate"); aquisitionValues.add(aqkDate); aquisitionId.add("tags"); aquisitionValues.add(tag_add); tag_add +="]"; aquisitionId.add("measures"); measures_add +="]"; aquisitionValues.add(measures_add); Communication.post("http://localhost:3000/api/createAcquisition", aquisitionId, aquisitionValues); //Get package from rest api List<Package> presentPackages = new ArrayList<Package>(); Tag tagInfo; i=0; while(i<currentTags.size()) { tagInfo = currentTags.get(i); Package pack=null; try { pack = getPackageFromTag(tagInfo); presentPackages.add(pack); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } presentPackages.add(pack); i++; } int nbpacks = presentPackages.size(); int j=0; while(j<nbpacks) { Package pack =presentPackages.get(j); List<Product> products = pack.getProducts(); int nbproducts = products.size(); int k = 0; while(k<nbproducts) { Product product = products.get(k); //Vérifier que les régles de transport sont réspectées List<ProductProfile> profil_product = product.getProductProfil(); int l=0; while(l<profil_product.size()) { ProductProfile pprofil= profil_product.get(l); System.out.println("Profil associée :" + pprofil.getLabel()); List<Standart> productStandart =pprofil.getStandarts(); int m=0; while(m < productStandart.size()) { Standart pstandart = productStandart.get(m); System.out.println("Standart :" + pstandart.toString()); List<Rule> pRules= pstandart.getRules();; int n=0; while(n < pRules.size()) { Rule pRule = pRules.get(n); System.out.println("Rule :" + pRule.toString()); int o; for(o=0; o<currentMeasures.size();o++) { if (pRule.getType().equals( currentMeasures.get(o).getType())) { String drl = null; try { drl = applyRuleTemplate(currentMeasures.get(o),pRule); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } AlertDecision alertDecision = null; try { alertDecision = evaluate(drl, currentMeasures.get(o)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } TemperaturesHumidity tes = (TemperaturesHumidity) currentMeasures.get(o); if (alertDecision.getDoAlert()) { List<String> keys = new ArrayList<String>(); List<String> valuesKeys = new ArrayList<String>(); keys.add("alertId"); String valId = "alert" + pRule.toString() + new Date(); valId.replaceAll("\\s+",""); valuesKeys.add(valId); keys.add("description"); valuesKeys.add("Alert on : " + pprofil.getLabel() + ". No respect of rule : " + pRule.toString()); keys.add("type"); valuesKeys.add(pprofil.getLabel()+"Error"); keys.add("status"); valuesKeys.add("NoRescpectStandartPackage"); //notification Communication.post("http://localhost:3000/api/Alert", keys, valuesKeys); System.out.println("Detection d'anomalies!!"); } } } n++; } m++; } l++; } k++; } j++; } }catch(ParseException pe){ System.out.println("position: " + pe.getPosition()); System.out.println(pe); } } }; channel.basicConsume(QUEUE_NAME, true, consumer); }catch (Exception e) { System.out.println(" Serveur de message non connecté"); } } private static Package getPackageFromTag(Tag tag) throws Exception { String JSONPackage = Communication.get("http://localhost:3000/api/queries/selectPackage?tagid=resource%3Aorg.example.mynetwork.Tag%23" + tag.getValue()); JSONParser parser = new JSONParser(); Object receptedValue = parser.parse(JSONPackage); JSONArray arrayOfValuesJsonPackage = (JSONArray) receptedValue; JSONObject level1Pars = (JSONObject) arrayOfValuesJsonPackage.get(0); String providerID = (level1Pars.get("provider").toString().split("#"))[1]; Provider provider = Provider.getProviderFromId(providerID); String customerID = (level1Pars.get("customer").toString().split("#"))[1]; Customer customer = Customer.getCustomerFromID(customerID); String deleveryDate = level1Pars.get("deliveryDate").toString(); String creationDate = level1Pars.get("creationDate").toString(); JSONArray productID = (JSONArray) level1Pars.get("products"); List<Product> products = new ArrayList<Product>(); int i; Product p; for(i=0; i<productID.size();i++) { p = Product.getProductFromID((productID.get(i).toString().split("#"))[1]); products.add(p); } List<Attachment> attachments = new ArrayList<Attachment>(); Package pack = new Package(0, "Test Package",provider, customer, products,deleveryDate, attachments , tag, creationDate); return pack; } static private AlertDecision evaluate(String drl, Measures measures) throws Exception { KieServices kieServices = KieServices.Factory.get(); KieFileSystem kieFileSystem = kieServices.newKieFileSystem(); kieFileSystem.write("src/main/resources/rule.drl", drl); kieServices.newKieBuilder(kieFileSystem).buildAll(); KieContainer kieContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId()); StatelessKieSession statelessKieSession = kieContainer.getKieBase().newStatelessKieSession(); AlertDecision alertDecision = new AlertDecision(); statelessKieSession.getGlobals().set("alertDecision", alertDecision); statelessKieSession.execute(measures); return alertDecision; } /*Génération des règles*/ static private String applyRuleTemplate(Measures measures, Rule rule) throws Exception { Map<String, Object> data = new HashMap<String, Object>(); ObjectDataCompiler objectDataCompiler = new ObjectDataCompiler(); data.put("rule", rule); data.put("measure", measures.getClass().getName()); return objectDataCompiler.compile(Arrays.asList(data), Thread.currentThread().getContextClassLoader().getResourceAsStream("rule-template.drl")); } }
923d2ec49a07f44b04b198a86ce53daaed4702f4
827
java
Java
src/main/java/org/rpgrunner/j2me/MidletCommands.java
carlsonsantana/rpg_runner_j2me
58d67d62b000940a339acb1d21df9a27f93d10e4
[ "MIT" ]
null
null
null
src/main/java/org/rpgrunner/j2me/MidletCommands.java
carlsonsantana/rpg_runner_j2me
58d67d62b000940a339acb1d21df9a27f93d10e4
[ "MIT" ]
null
null
null
src/main/java/org/rpgrunner/j2me/MidletCommands.java
carlsonsantana/rpg_runner_j2me
58d67d62b000940a339acb1d21df9a27f93d10e4
[ "MIT" ]
null
null
null
26.677419
59
0.690447
1,000,206
package org.rpgrunner.j2me; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Displayable; import javax.microedition.midlet.MIDlet; public class MidletCommands implements CommandListener { private final MIDlet midlet; private final Command exitCommand; public MidletCommands( final MIDlet gameMidlet, final GameRunner gameRunner ) { midlet = gameMidlet; exitCommand = new Command("Exit", Command.EXIT, 0); gameRunner.addCommand(exitCommand); gameRunner.setCommandListener(this); } public void commandAction( final Command command, final Displayable displayable ) { if (command == exitCommand) { midlet.notifyDestroyed(); } } }
923d2f9fd11bc5ca9331a02f9ae1d511bae7c2c4
499
java
Java
docuwiki/documentationWiki/src/main/java/org/forwoods/docuwiki/documentationWiki/core/SquadDirFileLoader.java
tomforwood/documentationWiki
e620c74dd13dac418fd097651bee43fe96ff429c
[ "MIT" ]
null
null
null
docuwiki/documentationWiki/src/main/java/org/forwoods/docuwiki/documentationWiki/core/SquadDirFileLoader.java
tomforwood/documentationWiki
e620c74dd13dac418fd097651bee43fe96ff429c
[ "MIT" ]
null
null
null
docuwiki/documentationWiki/src/main/java/org/forwoods/docuwiki/documentationWiki/core/SquadDirFileLoader.java
tomforwood/documentationWiki
e620c74dd13dac418fd097651bee43fe96ff429c
[ "MIT" ]
null
null
null
21.695652
66
0.791583
1,000,207
package org.forwoods.docuwiki.documentationWiki.core; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class SquadDirFileLoader implements SquadFileLoader { public File squadDirectory; public SquadDirFileLoader(File squadDir) { squadDirectory = squadDir; } @Override public InputStream readFile(String filename) throws IOException { File f = new File(squadDirectory, filename); return new FileInputStream(f); } }
923d2ff569037233e4108969e3a7729cf79aff11
488
java
Java
dicom-dimse-common/src/main/java/org/alvearie/imaging/ingestion/service/dimse/ReflectionConfiguration.java
devhliu/imaging-ingestion
cd76c992a8fcc025dc8df9059dd59066305b7c77
[ "Apache-2.0" ]
13
2021-06-03T18:23:01.000Z
2022-03-26T18:41:57.000Z
dicom-dimse-common/src/main/java/org/alvearie/imaging/ingestion/service/dimse/ReflectionConfiguration.java
devhliu/imaging-ingestion
cd76c992a8fcc025dc8df9059dd59066305b7c77
[ "Apache-2.0" ]
6
2021-04-07T15:36:29.000Z
2022-03-28T20:57:04.000Z
dicom-dimse-common/src/main/java/org/alvearie/imaging/ingestion/service/dimse/ReflectionConfiguration.java
devhliu/imaging-ingestion
cd76c992a8fcc025dc8df9059dd59066305b7c77
[ "Apache-2.0" ]
2
2021-11-19T01:43:04.000Z
2022-01-05T07:35:32.000Z
24.4
88
0.77459
1,000,208
/* * (C) Copyright IBM Corp. 2021 * * SPDX-License-Identifier: Apache-2.0 */ package org.alvearie.imaging.ingestion.service.dimse; import java.util.ArrayList; import org.dcm4che3.data.Attributes; import io.nats.client.impl.SocketDataPort; import io.quarkus.runtime.annotations.RegisterForReflection; @RegisterForReflection(targets = { SocketDataPort.class, Attributes.class, String.class, ArrayList.class }, serialization = true) public class ReflectionConfiguration { }
923d319743e63ae2fcef7d501e8bd89fe6216474
6,041
java
Java
appEducacionalVaadin/src/main/java/com/app/utility/FechaUtils.java
david-romero/tfg-vaadin
f22563673bacfdeb279152b2eea9b71e41afd85d
[ "Apache-2.0" ]
null
null
null
appEducacionalVaadin/src/main/java/com/app/utility/FechaUtils.java
david-romero/tfg-vaadin
f22563673bacfdeb279152b2eea9b71e41afd85d
[ "Apache-2.0" ]
8
2015-03-26T15:32:04.000Z
2015-03-31T15:58:12.000Z
appEducacionalVaadin/src/main/java/com/app/utility/FechaUtils.java
david-romero/tfg-vaadin
f22563673bacfdeb279152b2eea9b71e41afd85d
[ "Apache-2.0" ]
null
null
null
36.391566
73
0.64774
1,000,209
/** * FechaUtils.java * appEducacional * 20/01/2014 19:25:50 * Copyright David Romero Alcaide * com.app.utility */ package com.app.utility; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.log4j.Logger; import com.google.common.collect.Lists; /** * @author David Romero Alcaide * */ public class FechaUtils { private static final Logger LOGGER = Logger.getLogger(FechaUtils.class); public static int[] getFecha(Date fechaDate) { int[] fecha = new int[3]; Calendar cal = Calendar.getInstance(); cal.setTime(fechaDate); fecha[0] = cal.get(Calendar.DAY_OF_MONTH); // Los meses empiezan por 0 fecha[1] = cal.get(Calendar.MONTH) + 1; fecha[2] = cal.get(Calendar.YEAR); return fecha; } public static List<Date> getDiasFestivos() { List<Date> festivos = Lists.newArrayList(); DateFormat df = new SimpleDateFormat("dd-MM-yyyy"); int anioActual = getFecha(new Date(System.currentTimeMillis()))[2]; try { String fecha = "01-01-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "02-01-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "03-01-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "04-01-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "05-01-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "06-01-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "28-02-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "29-02-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "30-02-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "31-02-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "31-04-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "01-05-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "31-06-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "31-09-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "12-10-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "01-11-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "31-11-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "06-12-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "08-12-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "23-12-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "24-12-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "25-12-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "26-12-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "27-12-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "28-12-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "29-12-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "30-12-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); fecha = "31-12-"; festivos.add(df.parse(fecha + anioActual)); festivos.add(df.parse(fecha + (anioActual - 1))); festivos.add(df.parse(fecha + (anioActual + 1))); } catch (ParseException e) { LOGGER.error(e); } return festivos; } }
923d31f7d070d91594b89e9f313d1206371da06f
56,228
java
Java
sdk/billing/azure-resourcemanager-billing/src/main/java/com/azure/resourcemanager/billing/implementation/BillingPermissionsClientImpl.java
Manny27nyc/azure-sdk-for-java
d8d70f14cfd509bca10aaf042f45b2f23b62cdc9
[ "MIT" ]
1,350
2015-01-17T05:22:05.000Z
2022-03-29T21:00:37.000Z
sdk/billing/azure-resourcemanager-billing/src/main/java/com/azure/resourcemanager/billing/implementation/BillingPermissionsClientImpl.java
Manny27nyc/azure-sdk-for-java
d8d70f14cfd509bca10aaf042f45b2f23b62cdc9
[ "MIT" ]
16,834
2015-01-07T02:19:09.000Z
2022-03-31T23:29:10.000Z
sdk/billing/azure-resourcemanager-billing/src/main/java/com/azure/resourcemanager/billing/implementation/BillingPermissionsClientImpl.java
Manny27nyc/azure-sdk-for-java
d8d70f14cfd509bca10aaf042f45b2f23b62cdc9
[ "MIT" ]
1,586
2015-01-02T01:50:28.000Z
2022-03-31T11:25:34.000Z
50.473968
119
0.6535
1,000,210
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.billing.implementation; import com.azure.core.annotation.ExpectedResponses; import com.azure.core.annotation.Get; import com.azure.core.annotation.HeaderParam; import com.azure.core.annotation.Headers; import com.azure.core.annotation.Host; import com.azure.core.annotation.HostParam; import com.azure.core.annotation.PathParam; import com.azure.core.annotation.QueryParam; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceInterface; import com.azure.core.annotation.ServiceMethod; import com.azure.core.annotation.UnexpectedResponseExceptionType; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.PagedResponse; import com.azure.core.http.rest.PagedResponseBase; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; import com.azure.core.management.exception.ManagementException; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.billing.fluent.BillingPermissionsClient; import com.azure.resourcemanager.billing.fluent.models.BillingPermissionsPropertiesInner; import com.azure.resourcemanager.billing.models.BillingPermissionsListResult; import reactor.core.publisher.Mono; /** An instance of this class provides access to all the operations defined in BillingPermissionsClient. */ public final class BillingPermissionsClientImpl implements BillingPermissionsClient { private final ClientLogger logger = new ClientLogger(BillingPermissionsClientImpl.class); /** The proxy service used to perform REST calls. */ private final BillingPermissionsService service; /** The service client containing this operation class. */ private final BillingManagementClientImpl client; /** * Initializes an instance of BillingPermissionsClientImpl. * * @param client the instance of the service client containing this operation class. */ BillingPermissionsClientImpl(BillingManagementClientImpl client) { this.service = RestProxy.create(BillingPermissionsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); this.client = client; } /** * The interface defining all the services for BillingManagementClientBillingPermissions to be used by the proxy * service to perform REST calls. */ @Host("{$host}") @ServiceInterface(name = "BillingManagementCli") private interface BillingPermissionsService { @Headers({"Content-Type: application/json"}) @Get( "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}" + "/billingPermissions") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<BillingPermissionsListResult>> listByCustomer( @HostParam("$host") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam("billingAccountName") String billingAccountName, @PathParam("customerName") String customerName, @HeaderParam("Accept") String accept, Context context); @Headers({"Content-Type: application/json"}) @Get("/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingPermissions") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<BillingPermissionsListResult>> listByBillingAccount( @HostParam("$host") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam("billingAccountName") String billingAccountName, @HeaderParam("Accept") String accept, Context context); @Headers({"Content-Type: application/json"}) @Get( "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}" + "/invoiceSections/{invoiceSectionName}/billingPermissions") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<BillingPermissionsListResult>> listByInvoiceSections( @HostParam("$host") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam("billingAccountName") String billingAccountName, @PathParam("billingProfileName") String billingProfileName, @PathParam("invoiceSectionName") String invoiceSectionName, @HeaderParam("Accept") String accept, Context context); @Headers({"Content-Type: application/json"}) @Get( "/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}" + "/billingPermissions") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<BillingPermissionsListResult>> listByBillingProfile( @HostParam("$host") String endpoint, @QueryParam("api-version") String apiVersion, @PathParam("billingAccountName") String billingAccountName, @PathParam("billingProfileName") String billingProfileName, @HeaderParam("Accept") String accept, Context context); @Headers({"Content-Type: application/json"}) @Get("{nextLink}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<BillingPermissionsListResult>> listByCustomerNext( @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, @HeaderParam("Accept") String accept, Context context); @Headers({"Content-Type: application/json"}) @Get("{nextLink}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<BillingPermissionsListResult>> listByBillingAccountNext( @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, @HeaderParam("Accept") String accept, Context context); @Headers({"Content-Type: application/json"}) @Get("{nextLink}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<BillingPermissionsListResult>> listByInvoiceSectionsNext( @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, @HeaderParam("Accept") String accept, Context context); @Headers({"Content-Type: application/json"}) @Get("{nextLink}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<BillingPermissionsListResult>> listByBillingProfileNext( @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("$host") String endpoint, @HeaderParam("Accept") String accept, Context context); } /** * Lists the billing permissions the caller has for a customer. * * @param billingAccountName The ID that uniquely identifies a billing account. * @param customerName The ID that uniquely identifies a customer. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<BillingPermissionsPropertiesInner>> listByCustomerSinglePageAsync( String billingAccountName, String customerName) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (billingAccountName == null) { return Mono .error(new IllegalArgumentException("Parameter billingAccountName is required and cannot be null.")); } if (customerName == null) { return Mono.error(new IllegalArgumentException("Parameter customerName is required and cannot be null.")); } final String apiVersion = "2020-05-01"; final String accept = "application/json"; return FluxUtil .withContext( context -> service .listByCustomer( this.client.getEndpoint(), apiVersion, billingAccountName, customerName, accept, context)) .<PagedResponse<BillingPermissionsPropertiesInner>>map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Lists the billing permissions the caller has for a customer. * * @param billingAccountName The ID that uniquely identifies a billing account. * @param customerName The ID that uniquely identifies a customer. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<BillingPermissionsPropertiesInner>> listByCustomerSinglePageAsync( String billingAccountName, String customerName, Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (billingAccountName == null) { return Mono .error(new IllegalArgumentException("Parameter billingAccountName is required and cannot be null.")); } if (customerName == null) { return Mono.error(new IllegalArgumentException("Parameter customerName is required and cannot be null.")); } final String apiVersion = "2020-05-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service .listByCustomer(this.client.getEndpoint(), apiVersion, billingAccountName, customerName, accept, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } /** * Lists the billing permissions the caller has for a customer. * * @param billingAccountName The ID that uniquely identifies a billing account. * @param customerName The ID that uniquely identifies a customer. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedFlux<BillingPermissionsPropertiesInner> listByCustomerAsync( String billingAccountName, String customerName) { return new PagedFlux<>( () -> listByCustomerSinglePageAsync(billingAccountName, customerName), nextLink -> listByCustomerNextSinglePageAsync(nextLink)); } /** * Lists the billing permissions the caller has for a customer. * * @param billingAccountName The ID that uniquely identifies a billing account. * @param customerName The ID that uniquely identifies a customer. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedFlux<BillingPermissionsPropertiesInner> listByCustomerAsync( String billingAccountName, String customerName, Context context) { return new PagedFlux<>( () -> listByCustomerSinglePageAsync(billingAccountName, customerName, context), nextLink -> listByCustomerNextSinglePageAsync(nextLink, context)); } /** * Lists the billing permissions the caller has for a customer. * * @param billingAccountName The ID that uniquely identifies a billing account. * @param customerName The ID that uniquely identifies a customer. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<BillingPermissionsPropertiesInner> listByCustomer( String billingAccountName, String customerName) { return new PagedIterable<>(listByCustomerAsync(billingAccountName, customerName)); } /** * Lists the billing permissions the caller has for a customer. * * @param billingAccountName The ID that uniquely identifies a billing account. * @param customerName The ID that uniquely identifies a customer. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<BillingPermissionsPropertiesInner> listByCustomer( String billingAccountName, String customerName, Context context) { return new PagedIterable<>(listByCustomerAsync(billingAccountName, customerName, context)); } /** * Lists the billing permissions the caller has on a billing account. * * @param billingAccountName The ID that uniquely identifies a billing account. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<BillingPermissionsPropertiesInner>> listByBillingAccountSinglePageAsync( String billingAccountName) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (billingAccountName == null) { return Mono .error(new IllegalArgumentException("Parameter billingAccountName is required and cannot be null.")); } final String apiVersion = "2020-05-01"; final String accept = "application/json"; return FluxUtil .withContext( context -> service .listByBillingAccount( this.client.getEndpoint(), apiVersion, billingAccountName, accept, context)) .<PagedResponse<BillingPermissionsPropertiesInner>>map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Lists the billing permissions the caller has on a billing account. * * @param billingAccountName The ID that uniquely identifies a billing account. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<BillingPermissionsPropertiesInner>> listByBillingAccountSinglePageAsync( String billingAccountName, Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (billingAccountName == null) { return Mono .error(new IllegalArgumentException("Parameter billingAccountName is required and cannot be null.")); } final String apiVersion = "2020-05-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service .listByBillingAccount(this.client.getEndpoint(), apiVersion, billingAccountName, accept, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } /** * Lists the billing permissions the caller has on a billing account. * * @param billingAccountName The ID that uniquely identifies a billing account. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedFlux<BillingPermissionsPropertiesInner> listByBillingAccountAsync(String billingAccountName) { return new PagedFlux<>( () -> listByBillingAccountSinglePageAsync(billingAccountName), nextLink -> listByBillingAccountNextSinglePageAsync(nextLink)); } /** * Lists the billing permissions the caller has on a billing account. * * @param billingAccountName The ID that uniquely identifies a billing account. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedFlux<BillingPermissionsPropertiesInner> listByBillingAccountAsync( String billingAccountName, Context context) { return new PagedFlux<>( () -> listByBillingAccountSinglePageAsync(billingAccountName, context), nextLink -> listByBillingAccountNextSinglePageAsync(nextLink, context)); } /** * Lists the billing permissions the caller has on a billing account. * * @param billingAccountName The ID that uniquely identifies a billing account. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<BillingPermissionsPropertiesInner> listByBillingAccount(String billingAccountName) { return new PagedIterable<>(listByBillingAccountAsync(billingAccountName)); } /** * Lists the billing permissions the caller has on a billing account. * * @param billingAccountName The ID that uniquely identifies a billing account. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<BillingPermissionsPropertiesInner> listByBillingAccount( String billingAccountName, Context context) { return new PagedIterable<>(listByBillingAccountAsync(billingAccountName, context)); } /** * Lists the billing permissions the caller has on an invoice section. * * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<BillingPermissionsPropertiesInner>> listByInvoiceSectionsSinglePageAsync( String billingAccountName, String billingProfileName, String invoiceSectionName) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (billingAccountName == null) { return Mono .error(new IllegalArgumentException("Parameter billingAccountName is required and cannot be null.")); } if (billingProfileName == null) { return Mono .error(new IllegalArgumentException("Parameter billingProfileName is required and cannot be null.")); } if (invoiceSectionName == null) { return Mono .error(new IllegalArgumentException("Parameter invoiceSectionName is required and cannot be null.")); } final String apiVersion = "2020-05-01"; final String accept = "application/json"; return FluxUtil .withContext( context -> service .listByInvoiceSections( this.client.getEndpoint(), apiVersion, billingAccountName, billingProfileName, invoiceSectionName, accept, context)) .<PagedResponse<BillingPermissionsPropertiesInner>>map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Lists the billing permissions the caller has on an invoice section. * * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<BillingPermissionsPropertiesInner>> listByInvoiceSectionsSinglePageAsync( String billingAccountName, String billingProfileName, String invoiceSectionName, Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (billingAccountName == null) { return Mono .error(new IllegalArgumentException("Parameter billingAccountName is required and cannot be null.")); } if (billingProfileName == null) { return Mono .error(new IllegalArgumentException("Parameter billingProfileName is required and cannot be null.")); } if (invoiceSectionName == null) { return Mono .error(new IllegalArgumentException("Parameter invoiceSectionName is required and cannot be null.")); } final String apiVersion = "2020-05-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service .listByInvoiceSections( this.client.getEndpoint(), apiVersion, billingAccountName, billingProfileName, invoiceSectionName, accept, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } /** * Lists the billing permissions the caller has on an invoice section. * * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedFlux<BillingPermissionsPropertiesInner> listByInvoiceSectionsAsync( String billingAccountName, String billingProfileName, String invoiceSectionName) { return new PagedFlux<>( () -> listByInvoiceSectionsSinglePageAsync(billingAccountName, billingProfileName, invoiceSectionName), nextLink -> listByInvoiceSectionsNextSinglePageAsync(nextLink)); } /** * Lists the billing permissions the caller has on an invoice section. * * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedFlux<BillingPermissionsPropertiesInner> listByInvoiceSectionsAsync( String billingAccountName, String billingProfileName, String invoiceSectionName, Context context) { return new PagedFlux<>( () -> listByInvoiceSectionsSinglePageAsync( billingAccountName, billingProfileName, invoiceSectionName, context), nextLink -> listByInvoiceSectionsNextSinglePageAsync(nextLink, context)); } /** * Lists the billing permissions the caller has on an invoice section. * * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<BillingPermissionsPropertiesInner> listByInvoiceSections( String billingAccountName, String billingProfileName, String invoiceSectionName) { return new PagedIterable<>( listByInvoiceSectionsAsync(billingAccountName, billingProfileName, invoiceSectionName)); } /** * Lists the billing permissions the caller has on an invoice section. * * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<BillingPermissionsPropertiesInner> listByInvoiceSections( String billingAccountName, String billingProfileName, String invoiceSectionName, Context context) { return new PagedIterable<>( listByInvoiceSectionsAsync(billingAccountName, billingProfileName, invoiceSectionName, context)); } /** * Lists the billing permissions the caller has on a billing profile. * * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<BillingPermissionsPropertiesInner>> listByBillingProfileSinglePageAsync( String billingAccountName, String billingProfileName) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (billingAccountName == null) { return Mono .error(new IllegalArgumentException("Parameter billingAccountName is required and cannot be null.")); } if (billingProfileName == null) { return Mono .error(new IllegalArgumentException("Parameter billingProfileName is required and cannot be null.")); } final String apiVersion = "2020-05-01"; final String accept = "application/json"; return FluxUtil .withContext( context -> service .listByBillingProfile( this.client.getEndpoint(), apiVersion, billingAccountName, billingProfileName, accept, context)) .<PagedResponse<BillingPermissionsPropertiesInner>>map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Lists the billing permissions the caller has on a billing profile. * * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<BillingPermissionsPropertiesInner>> listByBillingProfileSinglePageAsync( String billingAccountName, String billingProfileName, Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (billingAccountName == null) { return Mono .error(new IllegalArgumentException("Parameter billingAccountName is required and cannot be null.")); } if (billingProfileName == null) { return Mono .error(new IllegalArgumentException("Parameter billingProfileName is required and cannot be null.")); } final String apiVersion = "2020-05-01"; final String accept = "application/json"; context = this.client.mergeContext(context); return service .listByBillingProfile( this.client.getEndpoint(), apiVersion, billingAccountName, billingProfileName, accept, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } /** * Lists the billing permissions the caller has on a billing profile. * * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedFlux<BillingPermissionsPropertiesInner> listByBillingProfileAsync( String billingAccountName, String billingProfileName) { return new PagedFlux<>( () -> listByBillingProfileSinglePageAsync(billingAccountName, billingProfileName), nextLink -> listByBillingProfileNextSinglePageAsync(nextLink)); } /** * Lists the billing permissions the caller has on a billing profile. * * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedFlux<BillingPermissionsPropertiesInner> listByBillingProfileAsync( String billingAccountName, String billingProfileName, Context context) { return new PagedFlux<>( () -> listByBillingProfileSinglePageAsync(billingAccountName, billingProfileName, context), nextLink -> listByBillingProfileNextSinglePageAsync(nextLink, context)); } /** * Lists the billing permissions the caller has on a billing profile. * * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<BillingPermissionsPropertiesInner> listByBillingProfile( String billingAccountName, String billingProfileName) { return new PagedIterable<>(listByBillingProfileAsync(billingAccountName, billingProfileName)); } /** * Lists the billing permissions the caller has on a billing profile. * * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<BillingPermissionsPropertiesInner> listByBillingProfile( String billingAccountName, String billingProfileName, Context context) { return new PagedIterable<>(listByBillingProfileAsync(billingAccountName, billingProfileName, context)); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<BillingPermissionsPropertiesInner>> listByCustomerNextSinglePageAsync(String nextLink) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; return FluxUtil .withContext(context -> service.listByCustomerNext(nextLink, this.client.getEndpoint(), accept, context)) .<PagedResponse<BillingPermissionsPropertiesInner>>map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<BillingPermissionsPropertiesInner>> listByCustomerNextSinglePageAsync( String nextLink, Context context) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; context = this.client.mergeContext(context); return service .listByCustomerNext(nextLink, this.client.getEndpoint(), accept, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<BillingPermissionsPropertiesInner>> listByBillingAccountNextSinglePageAsync( String nextLink) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; return FluxUtil .withContext( context -> service.listByBillingAccountNext(nextLink, this.client.getEndpoint(), accept, context)) .<PagedResponse<BillingPermissionsPropertiesInner>>map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<BillingPermissionsPropertiesInner>> listByBillingAccountNextSinglePageAsync( String nextLink, Context context) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; context = this.client.mergeContext(context); return service .listByBillingAccountNext(nextLink, this.client.getEndpoint(), accept, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<BillingPermissionsPropertiesInner>> listByInvoiceSectionsNextSinglePageAsync( String nextLink) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; return FluxUtil .withContext( context -> service.listByInvoiceSectionsNext(nextLink, this.client.getEndpoint(), accept, context)) .<PagedResponse<BillingPermissionsPropertiesInner>>map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<BillingPermissionsPropertiesInner>> listByInvoiceSectionsNextSinglePageAsync( String nextLink, Context context) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; context = this.client.mergeContext(context); return service .listByInvoiceSectionsNext(nextLink, this.client.getEndpoint(), accept, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<BillingPermissionsPropertiesInner>> listByBillingProfileNextSinglePageAsync( String nextLink) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; return FluxUtil .withContext( context -> service.listByBillingProfileNext(nextLink, this.client.getEndpoint(), accept, context)) .<PagedResponse<BillingPermissionsPropertiesInner>>map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return result of list billingPermissions a caller has on a billing account. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<BillingPermissionsPropertiesInner>> listByBillingProfileNextSinglePageAsync( String nextLink, Context context) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } final String accept = "application/json"; context = this.client.mergeContext(context); return service .listByBillingProfileNext(nextLink, this.client.getEndpoint(), accept, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } }
923d3246399a5e263e0648b453f5bd35531c9d61
572
java
Java
server/src/main/java/io/github/yxr1024/chinesechess/chat/ChannelType.java
baijianruoliorz/chinese-chess-server
ce627d6ff5ea5fff32048e00b5f4c78a1b9b3e3d
[ "MIT" ]
1
2021-03-08T02:08:27.000Z
2021-03-08T02:08:27.000Z
server/src/main/java/io/github/yxr1024/chinesechess/chat/ChannelType.java
baijianruoliorz/chinese-chess-server
ce627d6ff5ea5fff32048e00b5f4c78a1b9b3e3d
[ "MIT" ]
null
null
null
server/src/main/java/io/github/yxr1024/chinesechess/chat/ChannelType.java
baijianruoliorz/chinese-chess-server
ce627d6ff5ea5fff32048e00b5f4c78a1b9b3e3d
[ "MIT" ]
null
null
null
13.95122
55
0.463287
1,000,211
package io.github.yxr1024.chinesechess.chat; import lombok.Data; public enum ChannelType { /** * 公开 */ PUBLIC(1), /** * 房间 */ ROOM(2), /** * 私信 */ PM(3); int code; ChannelType(int code) { this.code = code; } public int getCode() { return code; } public static ChannelType from(int code) { for (ChannelType type : ChannelType.values()) { if (code == type.getCode()) { return type; } } return null; } }
923d32643787e1f55ecfbd18a4e7194268946d04
378
java
Java
core/src/main/java/org/iton/messenger/core/TLStringVector.java
ITON-Solutions/messenger-server
2dd14a37413540fe297903a7dc08190e72a09055
[ "MIT" ]
1
2018-06-25T00:07:19.000Z
2018-06-25T00:07:19.000Z
core/src/main/java/org/iton/messenger/core/TLStringVector.java
ITON-Solutions/messenger-server
2dd14a37413540fe297903a7dc08190e72a09055
[ "MIT" ]
null
null
null
core/src/main/java/org/iton/messenger/core/TLStringVector.java
ITON-Solutions/messenger-server
2dd14a37413540fe297903a7dc08190e72a09055
[ "MIT" ]
null
null
null
20.777778
61
0.665775
1,000,212
package org.iton.messenger.core; /** * TL Vector of strings. @see org.telegram.server.tl.TLVector * * @author Korshakov Stepan <hzdkv@example.com> */ public class TLStringVector extends TLVector<String> { public TLStringVector() { setDestClass(String.class); } @Override public String toString() { return "vector<string>#1cb5c415"; } }
923d32c4d42764c97885f5b671a28e255f37db1c
898
java
Java
spring-cloud/consumers-ribbon/src/main/java/com/fns/consumers/entity/User.java
CembZy/java-bable
5642fd6511e19c21b78be2c8e09a3698fff67498
[ "AFL-3.0" ]
1
2021-03-06T14:22:02.000Z
2021-03-06T14:22:02.000Z
spring-cloud/consumers/src/main/java/com/fns/consumers/entity/User.java
CembZy/java-bable
5642fd6511e19c21b78be2c8e09a3698fff67498
[ "AFL-3.0" ]
null
null
null
spring-cloud/consumers/src/main/java/com/fns/consumers/entity/User.java
CembZy/java-bable
5642fd6511e19c21b78be2c8e09a3698fff67498
[ "AFL-3.0" ]
1
2021-03-06T14:21:54.000Z
2021-03-06T14:21:54.000Z
15.754386
48
0.582405
1,000,213
package com.fns.consumers.entity; import java.math.BigDecimal; public class User { private Long id; private String username; private String name; private short age; private BigDecimal balance; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public short getAge() { return age; } public void setAge(short age) { this.age = age; } public BigDecimal getBalance() { return balance; } public void setBalance(BigDecimal balance) { this.balance = balance; } }
923d333e9217e534b02bcab2900d243991bc32b7
14,849
java
Java
src/main/java/net/canarymod/api/factory/EntityFactory.java
FlintPowered/FlintLib
26bd0a36f4c02148e1c8525d02d5af0b5438e564
[ "Unlicense" ]
19
2015-01-10T02:15:26.000Z
2020-10-06T18:45:08.000Z
src/main/java/net/canarymod/api/factory/EntityFactory.java
FlintPowered/FlintLib
26bd0a36f4c02148e1c8525d02d5af0b5438e564
[ "Unlicense" ]
58
2015-01-02T13:00:53.000Z
2017-12-23T14:37:24.000Z
src/main/java/net/canarymod/api/factory/EntityFactory.java
FlintPowered/FlintLib
26bd0a36f4c02148e1c8525d02d5af0b5438e564
[ "Unlicense" ]
31
2015-01-25T09:59:30.000Z
2021-07-04T02:07:56.000Z
33.595023
106
0.642737
1,000,214
package net.canarymod.api.factory; import net.canarymod.api.entity.Entity; import net.canarymod.api.entity.EntityType; import net.canarymod.api.entity.living.EntityLiving; import net.canarymod.api.entity.living.animal.EntityAnimal; import net.canarymod.api.entity.living.humanoid.NonPlayableCharacter; import net.canarymod.api.entity.living.monster.EntityMob; import net.canarymod.api.entity.throwable.EntityThrowable; import net.canarymod.api.entity.vehicle.Vehicle; import net.canarymod.api.world.World; import net.canarymod.api.world.position.Location; /** * Entity Manufacturing Factory<br> * NOTE: Entities created are not spawned. * * @author Jason (darkdiplomat) */ public interface EntityFactory { /** * Creates a new Entity of the specified name initialized in the default World * * @param name * the name of the Entity to create * * @return the new Entity if of a valid EnityType; {@code null} otherwise */ Entity newEntity(String name); /** * Creates a new Entity of the specified name and initialized in the specified World * * @param name * the name of the Entity to create * @param world * the World to initialize the Entity in * * @return the new Entity if of a valid EnityType; {@code null} otherwise */ Entity newEntity(String name, World world); /** * Creates a new Entity of the specified name and initialized at the specified Location * * @param name * the name of the Entity to create * @param location * the location to initialize the Entity * * @return the new Entity if of a valid EnityType; {@code null} otherwise */ Entity newEntity(String name, Location location); /** * Creates a new Entity of the specified type initialized in the default World * * @param type * the type of the Entity to create * * @return the new Entity */ Entity newEntity(EntityType type); /** * Creates a new Entity of the specified type and initialized in the specified World * * @param type * the type of the Entity to create * @param world * the World to initialize the Entity in * * @return the new Entity */ Entity newEntity(EntityType type, World world); /** * Creates a new Entity of the specified name and initialized at the specified Location * * @param type * the type of the Entity to create * @param location * the location to initialize the Entity * * @return the new Entity */ Entity newEntity(EntityType type, Location location); /** * Creates a new EntityThrowable of the specified name initialized in the default World * * @param name * the name of the EntityThrowable to create * * @return the new EntityThrowable if is a valid EntityThrowable; {@code null} otherwise */ EntityThrowable newThrowable(String name); /** * Creates a new EntityThrowable of the specified name and initialized in the specified World * * @param name * the name of the EntityThrowable to create * @param world * the World to initialize the EntityThrowable in * * @return the new EntityThrowable if is a valid EntityThrowable; {@code null} otherwise */ EntityThrowable newThrowable(String name, World world); /** * Creates a new EntityThrowable of the specified name and initialized at the specified Location * * @param name * the name of the EntityThrowable to create * @param location * the location to initialize the EntityThrowable * * @return the new EntityThrowable if is a valid EntityThrowable; {@code null} otherwise */ EntityThrowable newThrowable(String name, Location location); /** * Creates a new EntityThrowable of the specified type initialized in the default World * * @param type * the type of the EntityThrowable to create * * @return the new EntityThrowable if is a valid EntityThrowable; {@code null} otherwise */ EntityThrowable newThrowable(EntityType type); /** * Creates a new EntityThrowable of the specified type and initialized in the specified World * * @param type * the type of the EntityThrowable to create * @param world * the World to initialize the EntityThrowable in * * @return the new EntityThrowable if is a valid EntityThrowable; {@code null} otherwise */ EntityThrowable newThrowable(EntityType type, World world); /** * Creates a new EntityThrowable of the specified name and initialized at the specified Location * * @param type * the type of the EntityThrowable to create * @param location * the location to initialize the EntityThrowable * * @return the new EntityThrowable if is a valid EntityThrowable; {@code null} otherwise */ EntityThrowable newThrowable(EntityType type, Location location); /** * Creates a new Vehicle of the specified name initialized in the default World * * @param name * the name of the Vehicle to create * * @return the new Vehicle if is a valid Vehicle; {@code null} otherwise */ Vehicle newVehicle(String name); /** * Creates a new Vehicle of the specified name and initialized in the specified World * * @param name * the name of the Vehicle to create * @param world * the World to initialize the Vehicle in * * @return the new Vehicle if is a valid Vehicle; {@code null} otherwise */ Vehicle newVehicle(String name, World world); /** * Creates a new Vehicle of the specified name and initialized at the specified Location * * @param name * the name of the Vehicle to create * @param location * the location to initialize the Vehicle * * @return the new Vehicle if is a valid Vehicle; {@code null} otherwise */ Vehicle newVehicle(String name, Location location); /** * Creates a new Vehicle of the specified type initialized in the default World * * @param type * the type of the Vehicle to create * * @return the new Vehicle if is a valid Vehicle; {@code null} otherwise */ Vehicle newVehicle(EntityType type); /** * Creates a new Vehicle of the specified type and initialized in the specified World * * @param type * the type of the Vehicle to create * @param world * the World to initialize the Vehicle in * * @return the new Vehicle if is a valid Vehicle; {@code null} otherwise */ Vehicle newVehicle(EntityType type, World world); /** * Creates a new Vehicle of the specified name and initialized at the specified Location * * @param type * the type of the Vehicle to create * @param location * the location to initialize the Vehicle * * @return the new Vehicle if is a valid Vehicle; {@code null} otherwise */ Vehicle newVehicle(EntityType type, Location location); /** * Creates a new EntityLiving of the specified name initialized in the default World * * @param name * the name of the EntityLiving to create * * @return the new EntityLiving if is a valid EntityLiving; {@code null} otherwise */ EntityLiving newEntityLiving(String name); /** * Creates a new EntityLiving of the specified name and initialized in the specified World * * @param name * the name of the EntityLiving to create * @param world * the World to initialize the EntityLiving in * * @return the new EntityLiving if is a valid EntityLiving; {@code null} otherwise */ EntityLiving newEntityLiving(String name, World world); /** * Creates a new EntityLiving of the specified name and initialized at the specified Location * * @param name * the name of the EntityLiving to create * @param location * the location to initialize the EntityLiving * * @return the new EntityLiving if is a valid EntityLiving; {@code null} otherwise */ EntityLiving newEntityLiving(String name, Location location); /** * Creates a new EntityLiving of the specified type initialized in the default World * * @param type * the type of the EntityLiving to create * * @return the new EntityLiving if is a valid EntityLiving; {@code null} otherwise */ EntityLiving newEntityLiving(EntityType type); /** * Creates a new EntityLiving of the specified type and initialized in the specified World * * @param type * the type of the EntityLiving to create * @param world * the World to initialize the EntityLiving in * * @return the new EntityLiving if is a valid EntityLiving; {@code null} otherwise */ EntityLiving newEntityLiving(EntityType type, World world); /** * Creates a new EntityLiving of the specified name and initialized at the specified Location * * @param type * the type of the EntityLiving to create * @param location * the location to initialize the EntityLiving * * @return the new EntityLiving if is a valid EntityLiving; {@code null} otherwise */ EntityLiving newEntityLiving(EntityType type, Location location); /** * Creates a new EntityAnimal of the specified name initialized in the default World * * @param name * the name of the EntityAnimal to create * * @return the new EntityAnimal if is a valid EntityAnimal; {@code null} otherwise */ EntityAnimal newEntityAnimal(String name); /** * Creates a new EntityAnimal of the specified name and initialized in the specified World * * @param name * the name of the EntityAnimal to create * @param world * the World to initialize the EntityAnimal in * * @return the new EntityAnimal if is a valid EntityAnimal; {@code null} otherwise */ EntityAnimal newEntityAnimal(String name, World world); /** * Creates a new EntityAnimal of the specified name and initialized at the specified Location * * @param name * the name of the EntityAnimal to create * @param location * the location to initialize the EntityAnimal * * @return the new EntityAnimal if is a valid EntityAnimal; {@code null} otherwise */ EntityAnimal newEntityAnimal(String name, Location location); /** * Creates a new EntityAnimal of the specified type initialized in the default World * * @param type * the type of the EntityAnimal to create * * @return the new EntityAnimal if is a valid EntityAnimal; {@code null} otherwise */ EntityAnimal newEntityAnimal(EntityType type); /** * Creates a new EntityAnimal of the specified type and initialized in the specified World * * @param type * the type of the EntityAnimal to create * @param world * the World to initialize the EntityAnimal in * * @return the new EntityAnimal if is a valid EntityAnimal; {@code null} otherwise */ EntityAnimal newEntityAnimal(EntityType type, World world); /** * Creates a new EntityAnimal of the specified name and initialized at the specified Location * * @param type * the type of the EntityAnimal to create * @param location * the location to initialize the EntityAnimal * * @return the new EntityAnimal if is a valid EntityAnimal; {@code null} otherwise */ EntityAnimal newEntityAnimal(EntityType type, Location location); /** * Creates a new EntityMob of the specified name initialized in the default World * * @param name * the name of the EntityMob to create * * @return the new EntityMob if is a valid EntityMob; {@code null} otherwise */ EntityMob newEntityMob(String name); /** * Creates a new EntityMob of the specified name and initialized in the specified World * * @param name * the name of the EntityMob to create * @param world * the World to initialize the EntityMob in * * @return the new EntityMob if is a valid EntityMob; {@code null} otherwise */ EntityMob newEntityMob(String name, World world); /** * Creates a new EntityMob of the specified name and initialized at the specified Location * * @param name * the name of the EntityMob to create * @param location * the location to initialize the EntityMob * * @return the new EntityMob if is a valid EntityMob; {@code null} otherwise */ EntityMob newEntityMob(String name, Location location); /** * Creates a new EntityMob of the specified type initialized in the default World * * @param type * the type of the EntityMob to create * * @return the new EntityMob if is a valid EntityMob; {@code null} otherwise */ EntityMob newEntityMob(EntityType type); /** * Creates a new EntityMob of the specified type and initialized in the specified World * * @param type * the type of the EntityMob to create * @param world * the World to initialize the EntityMob in * * @return the new EntityMob if is a valid EntityMob; {@code null} otherwise */ EntityMob newEntityMob(EntityType type, World world); /** * Creates a new EntityMob of the specified name and initialized at the specified Location * * @param type * the type of the EntityMob to create * @param location * the location to initialize the EntityMob * * @return the new EntityMob if is a valid EntityMob; {@code null} otherwise */ EntityMob newEntityMob(EntityType type, Location location); /** * Creates a new NonPlayableCharacter * * @param name * the name of the NonPlayableCharacter * @param location * the location for the NonPlayableCharacter * * @return the new NonPlayableCharacter if all arguments are valid; {@code null} if an argument is not */ NonPlayableCharacter newNPC(String name, Location location); }
923d33934871722f9321f179553176839666198f
92,928
java
Java
proto-google-cloud-tasks-v2beta2/src/main/java/com/google/cloud/tasks/v2beta2/Task.java
vam-google/java-tasks
216e70a745142c3153612d2b9b758e4558ddf2cb
[ "Apache-2.0" ]
null
null
null
proto-google-cloud-tasks-v2beta2/src/main/java/com/google/cloud/tasks/v2beta2/Task.java
vam-google/java-tasks
216e70a745142c3153612d2b9b758e4558ddf2cb
[ "Apache-2.0" ]
null
null
null
proto-google-cloud-tasks-v2beta2/src/main/java/com/google/cloud/tasks/v2beta2/Task.java
vam-google/java-tasks
216e70a745142c3153612d2b9b758e4558ddf2cb
[ "Apache-2.0" ]
null
null
null
34.064516
121
0.635126
1,000,215
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/tasks/v2beta2/task.proto package com.google.cloud.tasks.v2beta2; /** * * * <pre> * A unit of scheduled work. * </pre> * * Protobuf type {@code google.cloud.tasks.v2beta2.Task} */ public final class Task extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.tasks.v2beta2.Task) TaskOrBuilder { private static final long serialVersionUID = 0L; // Use Task.newBuilder() to construct. private Task(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Task() { name_ = ""; view_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new Task(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Task( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); name_ = s; break; } case 26: { com.google.cloud.tasks.v2beta2.AppEngineHttpRequest.Builder subBuilder = null; if (payloadTypeCase_ == 3) { subBuilder = ((com.google.cloud.tasks.v2beta2.AppEngineHttpRequest) payloadType_) .toBuilder(); } payloadType_ = input.readMessage( com.google.cloud.tasks.v2beta2.AppEngineHttpRequest.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom( (com.google.cloud.tasks.v2beta2.AppEngineHttpRequest) payloadType_); payloadType_ = subBuilder.buildPartial(); } payloadTypeCase_ = 3; break; } case 34: { com.google.cloud.tasks.v2beta2.PullMessage.Builder subBuilder = null; if (payloadTypeCase_ == 4) { subBuilder = ((com.google.cloud.tasks.v2beta2.PullMessage) payloadType_).toBuilder(); } payloadType_ = input.readMessage( com.google.cloud.tasks.v2beta2.PullMessage.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((com.google.cloud.tasks.v2beta2.PullMessage) payloadType_); payloadType_ = subBuilder.buildPartial(); } payloadTypeCase_ = 4; break; } case 42: { com.google.protobuf.Timestamp.Builder subBuilder = null; if (scheduleTime_ != null) { subBuilder = scheduleTime_.toBuilder(); } scheduleTime_ = input.readMessage(com.google.protobuf.Timestamp.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(scheduleTime_); scheduleTime_ = subBuilder.buildPartial(); } break; } case 50: { com.google.protobuf.Timestamp.Builder subBuilder = null; if (createTime_ != null) { subBuilder = createTime_.toBuilder(); } createTime_ = input.readMessage(com.google.protobuf.Timestamp.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(createTime_); createTime_ = subBuilder.buildPartial(); } break; } case 58: { com.google.cloud.tasks.v2beta2.TaskStatus.Builder subBuilder = null; if (status_ != null) { subBuilder = status_.toBuilder(); } status_ = input.readMessage( com.google.cloud.tasks.v2beta2.TaskStatus.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(status_); status_ = subBuilder.buildPartial(); } break; } case 64: { int rawValue = input.readEnum(); view_ = rawValue; break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.tasks.v2beta2.TaskProto .internal_static_google_cloud_tasks_v2beta2_Task_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.tasks.v2beta2.TaskProto .internal_static_google_cloud_tasks_v2beta2_Task_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.tasks.v2beta2.Task.class, com.google.cloud.tasks.v2beta2.Task.Builder.class); } /** * * * <pre> * The view specifies a subset of [Task][google.cloud.tasks.v2beta2.Task] data. * When a task is returned in a response, not all * information is retrieved by default because some data, such as * payloads, might be desirable to return only when needed because * of its large size or because of the sensitivity of data that it * contains. * </pre> * * Protobuf enum {@code google.cloud.tasks.v2beta2.Task.View} */ public enum View implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * Unspecified. Defaults to BASIC. * </pre> * * <code>VIEW_UNSPECIFIED = 0;</code> */ VIEW_UNSPECIFIED(0), /** * * * <pre> * The basic view omits fields which can be large or can contain * sensitive data. * This view does not include the * ([payload in AppEngineHttpRequest][google.cloud.tasks.v2beta2.AppEngineHttpRequest] and * [payload in PullMessage][google.cloud.tasks.v2beta2.PullMessage.payload]). These payloads are * desirable to return only when needed, because they can be large * and because of the sensitivity of the data that you choose to * store in it. * </pre> * * <code>BASIC = 1;</code> */ BASIC(1), /** * * * <pre> * All information is returned. * Authorization for [FULL][google.cloud.tasks.v2beta2.Task.View.FULL] requires * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) * permission on the [Queue][google.cloud.tasks.v2beta2.Queue] resource. * </pre> * * <code>FULL = 2;</code> */ FULL(2), UNRECOGNIZED(-1), ; /** * * * <pre> * Unspecified. Defaults to BASIC. * </pre> * * <code>VIEW_UNSPECIFIED = 0;</code> */ public static final int VIEW_UNSPECIFIED_VALUE = 0; /** * * * <pre> * The basic view omits fields which can be large or can contain * sensitive data. * This view does not include the * ([payload in AppEngineHttpRequest][google.cloud.tasks.v2beta2.AppEngineHttpRequest] and * [payload in PullMessage][google.cloud.tasks.v2beta2.PullMessage.payload]). These payloads are * desirable to return only when needed, because they can be large * and because of the sensitivity of the data that you choose to * store in it. * </pre> * * <code>BASIC = 1;</code> */ public static final int BASIC_VALUE = 1; /** * * * <pre> * All information is returned. * Authorization for [FULL][google.cloud.tasks.v2beta2.Task.View.FULL] requires * `cloudtasks.tasks.fullView` [Google IAM](https://cloud.google.com/iam/) * permission on the [Queue][google.cloud.tasks.v2beta2.Queue] resource. * </pre> * * <code>FULL = 2;</code> */ public static final int FULL_VALUE = 2; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static View valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static View forNumber(int value) { switch (value) { case 0: return VIEW_UNSPECIFIED; case 1: return BASIC; case 2: return FULL; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<View> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<View> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<View>() { public View findValueByNumber(int number) { return View.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.cloud.tasks.v2beta2.Task.getDescriptor().getEnumTypes().get(0); } private static final View[] VALUES = values(); public static View valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private View(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.cloud.tasks.v2beta2.Task.View) } private int payloadTypeCase_ = 0; private java.lang.Object payloadType_; public enum PayloadTypeCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { APP_ENGINE_HTTP_REQUEST(3), PULL_MESSAGE(4), PAYLOADTYPE_NOT_SET(0); private final int value; private PayloadTypeCase(int value) { this.value = value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static PayloadTypeCase valueOf(int value) { return forNumber(value); } public static PayloadTypeCase forNumber(int value) { switch (value) { case 3: return APP_ENGINE_HTTP_REQUEST; case 4: return PULL_MESSAGE; case 0: return PAYLOADTYPE_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public PayloadTypeCase getPayloadTypeCase() { return PayloadTypeCase.forNumber(payloadTypeCase_); } public static final int NAME_FIELD_NUMBER = 1; private volatile java.lang.Object name_; /** * * * <pre> * Optionally caller-specified in [CreateTask][google.cloud.tasks.v2beta2.CloudTasks.CreateTask]. * The task name. * The task name must have the following format: * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` * * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), * hyphens (-), colons (:), or periods (.). * For more information, see * [Identifying * projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) * * `LOCATION_ID` is the canonical ID for the task's location. * The list of available locations can be obtained by calling * [ListLocations][google.cloud.location.Locations.ListLocations]. * For more information, see https://cloud.google.com/about/locations/. * * `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or * hyphens (-). The maximum length is 100 characters. * * `TASK_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), * hyphens (-), or underscores (_). The maximum length is 500 characters. * </pre> * * <code>string name = 1;</code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * * * <pre> * Optionally caller-specified in [CreateTask][google.cloud.tasks.v2beta2.CloudTasks.CreateTask]. * The task name. * The task name must have the following format: * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` * * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), * hyphens (-), colons (:), or periods (.). * For more information, see * [Identifying * projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) * * `LOCATION_ID` is the canonical ID for the task's location. * The list of available locations can be obtained by calling * [ListLocations][google.cloud.location.Locations.ListLocations]. * For more information, see https://cloud.google.com/about/locations/. * * `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or * hyphens (-). The maximum length is 100 characters. * * `TASK_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), * hyphens (-), or underscores (_). The maximum length is 500 characters. * </pre> * * <code>string name = 1;</code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int APP_ENGINE_HTTP_REQUEST_FIELD_NUMBER = 3; /** * * * <pre> * App Engine HTTP request that is sent to the task's target. Can * be set only if * [app_engine_http_target][google.cloud.tasks.v2beta2.Queue.app_engine_http_target] is set * on the queue. * An App Engine task is a task that has [AppEngineHttpRequest][google.cloud.tasks.v2beta2.AppEngineHttpRequest] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.AppEngineHttpRequest app_engine_http_request = 3;</code> * * @return Whether the appEngineHttpRequest field is set. */ public boolean hasAppEngineHttpRequest() { return payloadTypeCase_ == 3; } /** * * * <pre> * App Engine HTTP request that is sent to the task's target. Can * be set only if * [app_engine_http_target][google.cloud.tasks.v2beta2.Queue.app_engine_http_target] is set * on the queue. * An App Engine task is a task that has [AppEngineHttpRequest][google.cloud.tasks.v2beta2.AppEngineHttpRequest] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.AppEngineHttpRequest app_engine_http_request = 3;</code> * * @return The appEngineHttpRequest. */ public com.google.cloud.tasks.v2beta2.AppEngineHttpRequest getAppEngineHttpRequest() { if (payloadTypeCase_ == 3) { return (com.google.cloud.tasks.v2beta2.AppEngineHttpRequest) payloadType_; } return com.google.cloud.tasks.v2beta2.AppEngineHttpRequest.getDefaultInstance(); } /** * * * <pre> * App Engine HTTP request that is sent to the task's target. Can * be set only if * [app_engine_http_target][google.cloud.tasks.v2beta2.Queue.app_engine_http_target] is set * on the queue. * An App Engine task is a task that has [AppEngineHttpRequest][google.cloud.tasks.v2beta2.AppEngineHttpRequest] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.AppEngineHttpRequest app_engine_http_request = 3;</code> */ public com.google.cloud.tasks.v2beta2.AppEngineHttpRequestOrBuilder getAppEngineHttpRequestOrBuilder() { if (payloadTypeCase_ == 3) { return (com.google.cloud.tasks.v2beta2.AppEngineHttpRequest) payloadType_; } return com.google.cloud.tasks.v2beta2.AppEngineHttpRequest.getDefaultInstance(); } public static final int PULL_MESSAGE_FIELD_NUMBER = 4; /** * * * <pre> * [LeaseTasks][google.cloud.tasks.v2beta2.CloudTasks.LeaseTasks] to process the task. Can be * set only if [pull_target][google.cloud.tasks.v2beta2.Queue.pull_target] is set on the queue. * A pull task is a task that has [PullMessage][google.cloud.tasks.v2beta2.PullMessage] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.PullMessage pull_message = 4;</code> * * @return Whether the pullMessage field is set. */ public boolean hasPullMessage() { return payloadTypeCase_ == 4; } /** * * * <pre> * [LeaseTasks][google.cloud.tasks.v2beta2.CloudTasks.LeaseTasks] to process the task. Can be * set only if [pull_target][google.cloud.tasks.v2beta2.Queue.pull_target] is set on the queue. * A pull task is a task that has [PullMessage][google.cloud.tasks.v2beta2.PullMessage] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.PullMessage pull_message = 4;</code> * * @return The pullMessage. */ public com.google.cloud.tasks.v2beta2.PullMessage getPullMessage() { if (payloadTypeCase_ == 4) { return (com.google.cloud.tasks.v2beta2.PullMessage) payloadType_; } return com.google.cloud.tasks.v2beta2.PullMessage.getDefaultInstance(); } /** * * * <pre> * [LeaseTasks][google.cloud.tasks.v2beta2.CloudTasks.LeaseTasks] to process the task. Can be * set only if [pull_target][google.cloud.tasks.v2beta2.Queue.pull_target] is set on the queue. * A pull task is a task that has [PullMessage][google.cloud.tasks.v2beta2.PullMessage] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.PullMessage pull_message = 4;</code> */ public com.google.cloud.tasks.v2beta2.PullMessageOrBuilder getPullMessageOrBuilder() { if (payloadTypeCase_ == 4) { return (com.google.cloud.tasks.v2beta2.PullMessage) payloadType_; } return com.google.cloud.tasks.v2beta2.PullMessage.getDefaultInstance(); } public static final int SCHEDULE_TIME_FIELD_NUMBER = 5; private com.google.protobuf.Timestamp scheduleTime_; /** * * * <pre> * The time when the task is scheduled to be attempted. * For App Engine queues, this is when the task will be attempted or retried. * For pull queues, this is the time when the task is available to * be leased; if a task is currently leased, this is the time when * the current lease expires, that is, the time that the task was * leased plus the [lease_duration][google.cloud.tasks.v2beta2.LeaseTasksRequest.lease_duration]. * `schedule_time` will be truncated to the nearest microsecond. * </pre> * * <code>.google.protobuf.Timestamp schedule_time = 5;</code> * * @return Whether the scheduleTime field is set. */ public boolean hasScheduleTime() { return scheduleTime_ != null; } /** * * * <pre> * The time when the task is scheduled to be attempted. * For App Engine queues, this is when the task will be attempted or retried. * For pull queues, this is the time when the task is available to * be leased; if a task is currently leased, this is the time when * the current lease expires, that is, the time that the task was * leased plus the [lease_duration][google.cloud.tasks.v2beta2.LeaseTasksRequest.lease_duration]. * `schedule_time` will be truncated to the nearest microsecond. * </pre> * * <code>.google.protobuf.Timestamp schedule_time = 5;</code> * * @return The scheduleTime. */ public com.google.protobuf.Timestamp getScheduleTime() { return scheduleTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : scheduleTime_; } /** * * * <pre> * The time when the task is scheduled to be attempted. * For App Engine queues, this is when the task will be attempted or retried. * For pull queues, this is the time when the task is available to * be leased; if a task is currently leased, this is the time when * the current lease expires, that is, the time that the task was * leased plus the [lease_duration][google.cloud.tasks.v2beta2.LeaseTasksRequest.lease_duration]. * `schedule_time` will be truncated to the nearest microsecond. * </pre> * * <code>.google.protobuf.Timestamp schedule_time = 5;</code> */ public com.google.protobuf.TimestampOrBuilder getScheduleTimeOrBuilder() { return getScheduleTime(); } public static final int CREATE_TIME_FIELD_NUMBER = 6; private com.google.protobuf.Timestamp createTime_; /** * * * <pre> * Output only. The time that the task was created. * `create_time` will be truncated to the nearest second. * </pre> * * <code>.google.protobuf.Timestamp create_time = 6;</code> * * @return Whether the createTime field is set. */ public boolean hasCreateTime() { return createTime_ != null; } /** * * * <pre> * Output only. The time that the task was created. * `create_time` will be truncated to the nearest second. * </pre> * * <code>.google.protobuf.Timestamp create_time = 6;</code> * * @return The createTime. */ public com.google.protobuf.Timestamp getCreateTime() { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } /** * * * <pre> * Output only. The time that the task was created. * `create_time` will be truncated to the nearest second. * </pre> * * <code>.google.protobuf.Timestamp create_time = 6;</code> */ public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() { return getCreateTime(); } public static final int STATUS_FIELD_NUMBER = 7; private com.google.cloud.tasks.v2beta2.TaskStatus status_; /** * * * <pre> * Output only. The task status. * </pre> * * <code>.google.cloud.tasks.v2beta2.TaskStatus status = 7;</code> * * @return Whether the status field is set. */ public boolean hasStatus() { return status_ != null; } /** * * * <pre> * Output only. The task status. * </pre> * * <code>.google.cloud.tasks.v2beta2.TaskStatus status = 7;</code> * * @return The status. */ public com.google.cloud.tasks.v2beta2.TaskStatus getStatus() { return status_ == null ? com.google.cloud.tasks.v2beta2.TaskStatus.getDefaultInstance() : status_; } /** * * * <pre> * Output only. The task status. * </pre> * * <code>.google.cloud.tasks.v2beta2.TaskStatus status = 7;</code> */ public com.google.cloud.tasks.v2beta2.TaskStatusOrBuilder getStatusOrBuilder() { return getStatus(); } public static final int VIEW_FIELD_NUMBER = 8; private int view_; /** * * * <pre> * Output only. The view specifies which subset of the [Task][google.cloud.tasks.v2beta2.Task] has * been returned. * </pre> * * <code>.google.cloud.tasks.v2beta2.Task.View view = 8;</code> * * @return The enum numeric value on the wire for view. */ public int getViewValue() { return view_; } /** * * * <pre> * Output only. The view specifies which subset of the [Task][google.cloud.tasks.v2beta2.Task] has * been returned. * </pre> * * <code>.google.cloud.tasks.v2beta2.Task.View view = 8;</code> * * @return The view. */ public com.google.cloud.tasks.v2beta2.Task.View getView() { @SuppressWarnings("deprecation") com.google.cloud.tasks.v2beta2.Task.View result = com.google.cloud.tasks.v2beta2.Task.View.valueOf(view_); return result == null ? com.google.cloud.tasks.v2beta2.Task.View.UNRECOGNIZED : result; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (payloadTypeCase_ == 3) { output.writeMessage(3, (com.google.cloud.tasks.v2beta2.AppEngineHttpRequest) payloadType_); } if (payloadTypeCase_ == 4) { output.writeMessage(4, (com.google.cloud.tasks.v2beta2.PullMessage) payloadType_); } if (scheduleTime_ != null) { output.writeMessage(5, getScheduleTime()); } if (createTime_ != null) { output.writeMessage(6, getCreateTime()); } if (status_ != null) { output.writeMessage(7, getStatus()); } if (view_ != com.google.cloud.tasks.v2beta2.Task.View.VIEW_UNSPECIFIED.getNumber()) { output.writeEnum(8, view_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } if (payloadTypeCase_ == 3) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 3, (com.google.cloud.tasks.v2beta2.AppEngineHttpRequest) payloadType_); } if (payloadTypeCase_ == 4) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 4, (com.google.cloud.tasks.v2beta2.PullMessage) payloadType_); } if (scheduleTime_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(5, getScheduleTime()); } if (createTime_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(6, getCreateTime()); } if (status_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(7, getStatus()); } if (view_ != com.google.cloud.tasks.v2beta2.Task.View.VIEW_UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(8, view_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.tasks.v2beta2.Task)) { return super.equals(obj); } com.google.cloud.tasks.v2beta2.Task other = (com.google.cloud.tasks.v2beta2.Task) obj; if (!getName().equals(other.getName())) return false; if (hasScheduleTime() != other.hasScheduleTime()) return false; if (hasScheduleTime()) { if (!getScheduleTime().equals(other.getScheduleTime())) return false; } if (hasCreateTime() != other.hasCreateTime()) return false; if (hasCreateTime()) { if (!getCreateTime().equals(other.getCreateTime())) return false; } if (hasStatus() != other.hasStatus()) return false; if (hasStatus()) { if (!getStatus().equals(other.getStatus())) return false; } if (view_ != other.view_) return false; if (!getPayloadTypeCase().equals(other.getPayloadTypeCase())) return false; switch (payloadTypeCase_) { case 3: if (!getAppEngineHttpRequest().equals(other.getAppEngineHttpRequest())) return false; break; case 4: if (!getPullMessage().equals(other.getPullMessage())) return false; break; case 0: default: } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); if (hasScheduleTime()) { hash = (37 * hash) + SCHEDULE_TIME_FIELD_NUMBER; hash = (53 * hash) + getScheduleTime().hashCode(); } if (hasCreateTime()) { hash = (37 * hash) + CREATE_TIME_FIELD_NUMBER; hash = (53 * hash) + getCreateTime().hashCode(); } if (hasStatus()) { hash = (37 * hash) + STATUS_FIELD_NUMBER; hash = (53 * hash) + getStatus().hashCode(); } hash = (37 * hash) + VIEW_FIELD_NUMBER; hash = (53 * hash) + view_; switch (payloadTypeCase_) { case 3: hash = (37 * hash) + APP_ENGINE_HTTP_REQUEST_FIELD_NUMBER; hash = (53 * hash) + getAppEngineHttpRequest().hashCode(); break; case 4: hash = (37 * hash) + PULL_MESSAGE_FIELD_NUMBER; hash = (53 * hash) + getPullMessage().hashCode(); break; case 0: default: } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.tasks.v2beta2.Task parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.tasks.v2beta2.Task parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.tasks.v2beta2.Task parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.tasks.v2beta2.Task parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.tasks.v2beta2.Task parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.tasks.v2beta2.Task parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.tasks.v2beta2.Task parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.tasks.v2beta2.Task parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.tasks.v2beta2.Task parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.tasks.v2beta2.Task parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.tasks.v2beta2.Task parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.tasks.v2beta2.Task parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.tasks.v2beta2.Task prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * A unit of scheduled work. * </pre> * * Protobuf type {@code google.cloud.tasks.v2beta2.Task} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.tasks.v2beta2.Task) com.google.cloud.tasks.v2beta2.TaskOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.tasks.v2beta2.TaskProto .internal_static_google_cloud_tasks_v2beta2_Task_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.tasks.v2beta2.TaskProto .internal_static_google_cloud_tasks_v2beta2_Task_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.tasks.v2beta2.Task.class, com.google.cloud.tasks.v2beta2.Task.Builder.class); } // Construct using com.google.cloud.tasks.v2beta2.Task.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); name_ = ""; if (scheduleTimeBuilder_ == null) { scheduleTime_ = null; } else { scheduleTime_ = null; scheduleTimeBuilder_ = null; } if (createTimeBuilder_ == null) { createTime_ = null; } else { createTime_ = null; createTimeBuilder_ = null; } if (statusBuilder_ == null) { status_ = null; } else { status_ = null; statusBuilder_ = null; } view_ = 0; payloadTypeCase_ = 0; payloadType_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.tasks.v2beta2.TaskProto .internal_static_google_cloud_tasks_v2beta2_Task_descriptor; } @java.lang.Override public com.google.cloud.tasks.v2beta2.Task getDefaultInstanceForType() { return com.google.cloud.tasks.v2beta2.Task.getDefaultInstance(); } @java.lang.Override public com.google.cloud.tasks.v2beta2.Task build() { com.google.cloud.tasks.v2beta2.Task result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.tasks.v2beta2.Task buildPartial() { com.google.cloud.tasks.v2beta2.Task result = new com.google.cloud.tasks.v2beta2.Task(this); result.name_ = name_; if (payloadTypeCase_ == 3) { if (appEngineHttpRequestBuilder_ == null) { result.payloadType_ = payloadType_; } else { result.payloadType_ = appEngineHttpRequestBuilder_.build(); } } if (payloadTypeCase_ == 4) { if (pullMessageBuilder_ == null) { result.payloadType_ = payloadType_; } else { result.payloadType_ = pullMessageBuilder_.build(); } } if (scheduleTimeBuilder_ == null) { result.scheduleTime_ = scheduleTime_; } else { result.scheduleTime_ = scheduleTimeBuilder_.build(); } if (createTimeBuilder_ == null) { result.createTime_ = createTime_; } else { result.createTime_ = createTimeBuilder_.build(); } if (statusBuilder_ == null) { result.status_ = status_; } else { result.status_ = statusBuilder_.build(); } result.view_ = view_; result.payloadTypeCase_ = payloadTypeCase_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.tasks.v2beta2.Task) { return mergeFrom((com.google.cloud.tasks.v2beta2.Task) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.tasks.v2beta2.Task other) { if (other == com.google.cloud.tasks.v2beta2.Task.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; onChanged(); } if (other.hasScheduleTime()) { mergeScheduleTime(other.getScheduleTime()); } if (other.hasCreateTime()) { mergeCreateTime(other.getCreateTime()); } if (other.hasStatus()) { mergeStatus(other.getStatus()); } if (other.view_ != 0) { setViewValue(other.getViewValue()); } switch (other.getPayloadTypeCase()) { case APP_ENGINE_HTTP_REQUEST: { mergeAppEngineHttpRequest(other.getAppEngineHttpRequest()); break; } case PULL_MESSAGE: { mergePullMessage(other.getPullMessage()); break; } case PAYLOADTYPE_NOT_SET: { break; } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.tasks.v2beta2.Task parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.tasks.v2beta2.Task) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int payloadTypeCase_ = 0; private java.lang.Object payloadType_; public PayloadTypeCase getPayloadTypeCase() { return PayloadTypeCase.forNumber(payloadTypeCase_); } public Builder clearPayloadType() { payloadTypeCase_ = 0; payloadType_ = null; onChanged(); return this; } private java.lang.Object name_ = ""; /** * * * <pre> * Optionally caller-specified in [CreateTask][google.cloud.tasks.v2beta2.CloudTasks.CreateTask]. * The task name. * The task name must have the following format: * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` * * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), * hyphens (-), colons (:), or periods (.). * For more information, see * [Identifying * projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) * * `LOCATION_ID` is the canonical ID for the task's location. * The list of available locations can be obtained by calling * [ListLocations][google.cloud.location.Locations.ListLocations]. * For more information, see https://cloud.google.com/about/locations/. * * `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or * hyphens (-). The maximum length is 100 characters. * * `TASK_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), * hyphens (-), or underscores (_). The maximum length is 500 characters. * </pre> * * <code>string name = 1;</code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optionally caller-specified in [CreateTask][google.cloud.tasks.v2beta2.CloudTasks.CreateTask]. * The task name. * The task name must have the following format: * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` * * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), * hyphens (-), colons (:), or periods (.). * For more information, see * [Identifying * projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) * * `LOCATION_ID` is the canonical ID for the task's location. * The list of available locations can be obtained by calling * [ListLocations][google.cloud.location.Locations.ListLocations]. * For more information, see https://cloud.google.com/about/locations/. * * `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or * hyphens (-). The maximum length is 100 characters. * * `TASK_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), * hyphens (-), or underscores (_). The maximum length is 500 characters. * </pre> * * <code>string name = 1;</code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optionally caller-specified in [CreateTask][google.cloud.tasks.v2beta2.CloudTasks.CreateTask]. * The task name. * The task name must have the following format: * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` * * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), * hyphens (-), colons (:), or periods (.). * For more information, see * [Identifying * projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) * * `LOCATION_ID` is the canonical ID for the task's location. * The list of available locations can be obtained by calling * [ListLocations][google.cloud.location.Locations.ListLocations]. * For more information, see https://cloud.google.com/about/locations/. * * `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or * hyphens (-). The maximum length is 100 characters. * * `TASK_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), * hyphens (-), or underscores (_). The maximum length is 500 characters. * </pre> * * <code>string name = 1;</code> * * @param value The name to set. * @return This builder for chaining. */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; onChanged(); return this; } /** * * * <pre> * Optionally caller-specified in [CreateTask][google.cloud.tasks.v2beta2.CloudTasks.CreateTask]. * The task name. * The task name must have the following format: * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` * * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), * hyphens (-), colons (:), or periods (.). * For more information, see * [Identifying * projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) * * `LOCATION_ID` is the canonical ID for the task's location. * The list of available locations can be obtained by calling * [ListLocations][google.cloud.location.Locations.ListLocations]. * For more information, see https://cloud.google.com/about/locations/. * * `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or * hyphens (-). The maximum length is 100 characters. * * `TASK_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), * hyphens (-), or underscores (_). The maximum length is 500 characters. * </pre> * * <code>string name = 1;</code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * * * <pre> * Optionally caller-specified in [CreateTask][google.cloud.tasks.v2beta2.CloudTasks.CreateTask]. * The task name. * The task name must have the following format: * `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` * * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), * hyphens (-), colons (:), or periods (.). * For more information, see * [Identifying * projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) * * `LOCATION_ID` is the canonical ID for the task's location. * The list of available locations can be obtained by calling * [ListLocations][google.cloud.location.Locations.ListLocations]. * For more information, see https://cloud.google.com/about/locations/. * * `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or * hyphens (-). The maximum length is 100 characters. * * `TASK_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), * hyphens (-), or underscores (_). The maximum length is 500 characters. * </pre> * * <code>string name = 1;</code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; onChanged(); return this; } private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.tasks.v2beta2.AppEngineHttpRequest, com.google.cloud.tasks.v2beta2.AppEngineHttpRequest.Builder, com.google.cloud.tasks.v2beta2.AppEngineHttpRequestOrBuilder> appEngineHttpRequestBuilder_; /** * * * <pre> * App Engine HTTP request that is sent to the task's target. Can * be set only if * [app_engine_http_target][google.cloud.tasks.v2beta2.Queue.app_engine_http_target] is set * on the queue. * An App Engine task is a task that has [AppEngineHttpRequest][google.cloud.tasks.v2beta2.AppEngineHttpRequest] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.AppEngineHttpRequest app_engine_http_request = 3;</code> * * @return Whether the appEngineHttpRequest field is set. */ public boolean hasAppEngineHttpRequest() { return payloadTypeCase_ == 3; } /** * * * <pre> * App Engine HTTP request that is sent to the task's target. Can * be set only if * [app_engine_http_target][google.cloud.tasks.v2beta2.Queue.app_engine_http_target] is set * on the queue. * An App Engine task is a task that has [AppEngineHttpRequest][google.cloud.tasks.v2beta2.AppEngineHttpRequest] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.AppEngineHttpRequest app_engine_http_request = 3;</code> * * @return The appEngineHttpRequest. */ public com.google.cloud.tasks.v2beta2.AppEngineHttpRequest getAppEngineHttpRequest() { if (appEngineHttpRequestBuilder_ == null) { if (payloadTypeCase_ == 3) { return (com.google.cloud.tasks.v2beta2.AppEngineHttpRequest) payloadType_; } return com.google.cloud.tasks.v2beta2.AppEngineHttpRequest.getDefaultInstance(); } else { if (payloadTypeCase_ == 3) { return appEngineHttpRequestBuilder_.getMessage(); } return com.google.cloud.tasks.v2beta2.AppEngineHttpRequest.getDefaultInstance(); } } /** * * * <pre> * App Engine HTTP request that is sent to the task's target. Can * be set only if * [app_engine_http_target][google.cloud.tasks.v2beta2.Queue.app_engine_http_target] is set * on the queue. * An App Engine task is a task that has [AppEngineHttpRequest][google.cloud.tasks.v2beta2.AppEngineHttpRequest] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.AppEngineHttpRequest app_engine_http_request = 3;</code> */ public Builder setAppEngineHttpRequest( com.google.cloud.tasks.v2beta2.AppEngineHttpRequest value) { if (appEngineHttpRequestBuilder_ == null) { if (value == null) { throw new NullPointerException(); } payloadType_ = value; onChanged(); } else { appEngineHttpRequestBuilder_.setMessage(value); } payloadTypeCase_ = 3; return this; } /** * * * <pre> * App Engine HTTP request that is sent to the task's target. Can * be set only if * [app_engine_http_target][google.cloud.tasks.v2beta2.Queue.app_engine_http_target] is set * on the queue. * An App Engine task is a task that has [AppEngineHttpRequest][google.cloud.tasks.v2beta2.AppEngineHttpRequest] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.AppEngineHttpRequest app_engine_http_request = 3;</code> */ public Builder setAppEngineHttpRequest( com.google.cloud.tasks.v2beta2.AppEngineHttpRequest.Builder builderForValue) { if (appEngineHttpRequestBuilder_ == null) { payloadType_ = builderForValue.build(); onChanged(); } else { appEngineHttpRequestBuilder_.setMessage(builderForValue.build()); } payloadTypeCase_ = 3; return this; } /** * * * <pre> * App Engine HTTP request that is sent to the task's target. Can * be set only if * [app_engine_http_target][google.cloud.tasks.v2beta2.Queue.app_engine_http_target] is set * on the queue. * An App Engine task is a task that has [AppEngineHttpRequest][google.cloud.tasks.v2beta2.AppEngineHttpRequest] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.AppEngineHttpRequest app_engine_http_request = 3;</code> */ public Builder mergeAppEngineHttpRequest( com.google.cloud.tasks.v2beta2.AppEngineHttpRequest value) { if (appEngineHttpRequestBuilder_ == null) { if (payloadTypeCase_ == 3 && payloadType_ != com.google.cloud.tasks.v2beta2.AppEngineHttpRequest.getDefaultInstance()) { payloadType_ = com.google.cloud.tasks.v2beta2.AppEngineHttpRequest.newBuilder( (com.google.cloud.tasks.v2beta2.AppEngineHttpRequest) payloadType_) .mergeFrom(value) .buildPartial(); } else { payloadType_ = value; } onChanged(); } else { if (payloadTypeCase_ == 3) { appEngineHttpRequestBuilder_.mergeFrom(value); } appEngineHttpRequestBuilder_.setMessage(value); } payloadTypeCase_ = 3; return this; } /** * * * <pre> * App Engine HTTP request that is sent to the task's target. Can * be set only if * [app_engine_http_target][google.cloud.tasks.v2beta2.Queue.app_engine_http_target] is set * on the queue. * An App Engine task is a task that has [AppEngineHttpRequest][google.cloud.tasks.v2beta2.AppEngineHttpRequest] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.AppEngineHttpRequest app_engine_http_request = 3;</code> */ public Builder clearAppEngineHttpRequest() { if (appEngineHttpRequestBuilder_ == null) { if (payloadTypeCase_ == 3) { payloadTypeCase_ = 0; payloadType_ = null; onChanged(); } } else { if (payloadTypeCase_ == 3) { payloadTypeCase_ = 0; payloadType_ = null; } appEngineHttpRequestBuilder_.clear(); } return this; } /** * * * <pre> * App Engine HTTP request that is sent to the task's target. Can * be set only if * [app_engine_http_target][google.cloud.tasks.v2beta2.Queue.app_engine_http_target] is set * on the queue. * An App Engine task is a task that has [AppEngineHttpRequest][google.cloud.tasks.v2beta2.AppEngineHttpRequest] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.AppEngineHttpRequest app_engine_http_request = 3;</code> */ public com.google.cloud.tasks.v2beta2.AppEngineHttpRequest.Builder getAppEngineHttpRequestBuilder() { return getAppEngineHttpRequestFieldBuilder().getBuilder(); } /** * * * <pre> * App Engine HTTP request that is sent to the task's target. Can * be set only if * [app_engine_http_target][google.cloud.tasks.v2beta2.Queue.app_engine_http_target] is set * on the queue. * An App Engine task is a task that has [AppEngineHttpRequest][google.cloud.tasks.v2beta2.AppEngineHttpRequest] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.AppEngineHttpRequest app_engine_http_request = 3;</code> */ public com.google.cloud.tasks.v2beta2.AppEngineHttpRequestOrBuilder getAppEngineHttpRequestOrBuilder() { if ((payloadTypeCase_ == 3) && (appEngineHttpRequestBuilder_ != null)) { return appEngineHttpRequestBuilder_.getMessageOrBuilder(); } else { if (payloadTypeCase_ == 3) { return (com.google.cloud.tasks.v2beta2.AppEngineHttpRequest) payloadType_; } return com.google.cloud.tasks.v2beta2.AppEngineHttpRequest.getDefaultInstance(); } } /** * * * <pre> * App Engine HTTP request that is sent to the task's target. Can * be set only if * [app_engine_http_target][google.cloud.tasks.v2beta2.Queue.app_engine_http_target] is set * on the queue. * An App Engine task is a task that has [AppEngineHttpRequest][google.cloud.tasks.v2beta2.AppEngineHttpRequest] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.AppEngineHttpRequest app_engine_http_request = 3;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.tasks.v2beta2.AppEngineHttpRequest, com.google.cloud.tasks.v2beta2.AppEngineHttpRequest.Builder, com.google.cloud.tasks.v2beta2.AppEngineHttpRequestOrBuilder> getAppEngineHttpRequestFieldBuilder() { if (appEngineHttpRequestBuilder_ == null) { if (!(payloadTypeCase_ == 3)) { payloadType_ = com.google.cloud.tasks.v2beta2.AppEngineHttpRequest.getDefaultInstance(); } appEngineHttpRequestBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.tasks.v2beta2.AppEngineHttpRequest, com.google.cloud.tasks.v2beta2.AppEngineHttpRequest.Builder, com.google.cloud.tasks.v2beta2.AppEngineHttpRequestOrBuilder>( (com.google.cloud.tasks.v2beta2.AppEngineHttpRequest) payloadType_, getParentForChildren(), isClean()); payloadType_ = null; } payloadTypeCase_ = 3; onChanged(); ; return appEngineHttpRequestBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.tasks.v2beta2.PullMessage, com.google.cloud.tasks.v2beta2.PullMessage.Builder, com.google.cloud.tasks.v2beta2.PullMessageOrBuilder> pullMessageBuilder_; /** * * * <pre> * [LeaseTasks][google.cloud.tasks.v2beta2.CloudTasks.LeaseTasks] to process the task. Can be * set only if [pull_target][google.cloud.tasks.v2beta2.Queue.pull_target] is set on the queue. * A pull task is a task that has [PullMessage][google.cloud.tasks.v2beta2.PullMessage] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.PullMessage pull_message = 4;</code> * * @return Whether the pullMessage field is set. */ public boolean hasPullMessage() { return payloadTypeCase_ == 4; } /** * * * <pre> * [LeaseTasks][google.cloud.tasks.v2beta2.CloudTasks.LeaseTasks] to process the task. Can be * set only if [pull_target][google.cloud.tasks.v2beta2.Queue.pull_target] is set on the queue. * A pull task is a task that has [PullMessage][google.cloud.tasks.v2beta2.PullMessage] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.PullMessage pull_message = 4;</code> * * @return The pullMessage. */ public com.google.cloud.tasks.v2beta2.PullMessage getPullMessage() { if (pullMessageBuilder_ == null) { if (payloadTypeCase_ == 4) { return (com.google.cloud.tasks.v2beta2.PullMessage) payloadType_; } return com.google.cloud.tasks.v2beta2.PullMessage.getDefaultInstance(); } else { if (payloadTypeCase_ == 4) { return pullMessageBuilder_.getMessage(); } return com.google.cloud.tasks.v2beta2.PullMessage.getDefaultInstance(); } } /** * * * <pre> * [LeaseTasks][google.cloud.tasks.v2beta2.CloudTasks.LeaseTasks] to process the task. Can be * set only if [pull_target][google.cloud.tasks.v2beta2.Queue.pull_target] is set on the queue. * A pull task is a task that has [PullMessage][google.cloud.tasks.v2beta2.PullMessage] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.PullMessage pull_message = 4;</code> */ public Builder setPullMessage(com.google.cloud.tasks.v2beta2.PullMessage value) { if (pullMessageBuilder_ == null) { if (value == null) { throw new NullPointerException(); } payloadType_ = value; onChanged(); } else { pullMessageBuilder_.setMessage(value); } payloadTypeCase_ = 4; return this; } /** * * * <pre> * [LeaseTasks][google.cloud.tasks.v2beta2.CloudTasks.LeaseTasks] to process the task. Can be * set only if [pull_target][google.cloud.tasks.v2beta2.Queue.pull_target] is set on the queue. * A pull task is a task that has [PullMessage][google.cloud.tasks.v2beta2.PullMessage] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.PullMessage pull_message = 4;</code> */ public Builder setPullMessage( com.google.cloud.tasks.v2beta2.PullMessage.Builder builderForValue) { if (pullMessageBuilder_ == null) { payloadType_ = builderForValue.build(); onChanged(); } else { pullMessageBuilder_.setMessage(builderForValue.build()); } payloadTypeCase_ = 4; return this; } /** * * * <pre> * [LeaseTasks][google.cloud.tasks.v2beta2.CloudTasks.LeaseTasks] to process the task. Can be * set only if [pull_target][google.cloud.tasks.v2beta2.Queue.pull_target] is set on the queue. * A pull task is a task that has [PullMessage][google.cloud.tasks.v2beta2.PullMessage] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.PullMessage pull_message = 4;</code> */ public Builder mergePullMessage(com.google.cloud.tasks.v2beta2.PullMessage value) { if (pullMessageBuilder_ == null) { if (payloadTypeCase_ == 4 && payloadType_ != com.google.cloud.tasks.v2beta2.PullMessage.getDefaultInstance()) { payloadType_ = com.google.cloud.tasks.v2beta2.PullMessage.newBuilder( (com.google.cloud.tasks.v2beta2.PullMessage) payloadType_) .mergeFrom(value) .buildPartial(); } else { payloadType_ = value; } onChanged(); } else { if (payloadTypeCase_ == 4) { pullMessageBuilder_.mergeFrom(value); } pullMessageBuilder_.setMessage(value); } payloadTypeCase_ = 4; return this; } /** * * * <pre> * [LeaseTasks][google.cloud.tasks.v2beta2.CloudTasks.LeaseTasks] to process the task. Can be * set only if [pull_target][google.cloud.tasks.v2beta2.Queue.pull_target] is set on the queue. * A pull task is a task that has [PullMessage][google.cloud.tasks.v2beta2.PullMessage] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.PullMessage pull_message = 4;</code> */ public Builder clearPullMessage() { if (pullMessageBuilder_ == null) { if (payloadTypeCase_ == 4) { payloadTypeCase_ = 0; payloadType_ = null; onChanged(); } } else { if (payloadTypeCase_ == 4) { payloadTypeCase_ = 0; payloadType_ = null; } pullMessageBuilder_.clear(); } return this; } /** * * * <pre> * [LeaseTasks][google.cloud.tasks.v2beta2.CloudTasks.LeaseTasks] to process the task. Can be * set only if [pull_target][google.cloud.tasks.v2beta2.Queue.pull_target] is set on the queue. * A pull task is a task that has [PullMessage][google.cloud.tasks.v2beta2.PullMessage] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.PullMessage pull_message = 4;</code> */ public com.google.cloud.tasks.v2beta2.PullMessage.Builder getPullMessageBuilder() { return getPullMessageFieldBuilder().getBuilder(); } /** * * * <pre> * [LeaseTasks][google.cloud.tasks.v2beta2.CloudTasks.LeaseTasks] to process the task. Can be * set only if [pull_target][google.cloud.tasks.v2beta2.Queue.pull_target] is set on the queue. * A pull task is a task that has [PullMessage][google.cloud.tasks.v2beta2.PullMessage] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.PullMessage pull_message = 4;</code> */ public com.google.cloud.tasks.v2beta2.PullMessageOrBuilder getPullMessageOrBuilder() { if ((payloadTypeCase_ == 4) && (pullMessageBuilder_ != null)) { return pullMessageBuilder_.getMessageOrBuilder(); } else { if (payloadTypeCase_ == 4) { return (com.google.cloud.tasks.v2beta2.PullMessage) payloadType_; } return com.google.cloud.tasks.v2beta2.PullMessage.getDefaultInstance(); } } /** * * * <pre> * [LeaseTasks][google.cloud.tasks.v2beta2.CloudTasks.LeaseTasks] to process the task. Can be * set only if [pull_target][google.cloud.tasks.v2beta2.Queue.pull_target] is set on the queue. * A pull task is a task that has [PullMessage][google.cloud.tasks.v2beta2.PullMessage] set. * </pre> * * <code>.google.cloud.tasks.v2beta2.PullMessage pull_message = 4;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.tasks.v2beta2.PullMessage, com.google.cloud.tasks.v2beta2.PullMessage.Builder, com.google.cloud.tasks.v2beta2.PullMessageOrBuilder> getPullMessageFieldBuilder() { if (pullMessageBuilder_ == null) { if (!(payloadTypeCase_ == 4)) { payloadType_ = com.google.cloud.tasks.v2beta2.PullMessage.getDefaultInstance(); } pullMessageBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.tasks.v2beta2.PullMessage, com.google.cloud.tasks.v2beta2.PullMessage.Builder, com.google.cloud.tasks.v2beta2.PullMessageOrBuilder>( (com.google.cloud.tasks.v2beta2.PullMessage) payloadType_, getParentForChildren(), isClean()); payloadType_ = null; } payloadTypeCase_ = 4; onChanged(); ; return pullMessageBuilder_; } private com.google.protobuf.Timestamp scheduleTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> scheduleTimeBuilder_; /** * * * <pre> * The time when the task is scheduled to be attempted. * For App Engine queues, this is when the task will be attempted or retried. * For pull queues, this is the time when the task is available to * be leased; if a task is currently leased, this is the time when * the current lease expires, that is, the time that the task was * leased plus the [lease_duration][google.cloud.tasks.v2beta2.LeaseTasksRequest.lease_duration]. * `schedule_time` will be truncated to the nearest microsecond. * </pre> * * <code>.google.protobuf.Timestamp schedule_time = 5;</code> * * @return Whether the scheduleTime field is set. */ public boolean hasScheduleTime() { return scheduleTimeBuilder_ != null || scheduleTime_ != null; } /** * * * <pre> * The time when the task is scheduled to be attempted. * For App Engine queues, this is when the task will be attempted or retried. * For pull queues, this is the time when the task is available to * be leased; if a task is currently leased, this is the time when * the current lease expires, that is, the time that the task was * leased plus the [lease_duration][google.cloud.tasks.v2beta2.LeaseTasksRequest.lease_duration]. * `schedule_time` will be truncated to the nearest microsecond. * </pre> * * <code>.google.protobuf.Timestamp schedule_time = 5;</code> * * @return The scheduleTime. */ public com.google.protobuf.Timestamp getScheduleTime() { if (scheduleTimeBuilder_ == null) { return scheduleTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : scheduleTime_; } else { return scheduleTimeBuilder_.getMessage(); } } /** * * * <pre> * The time when the task is scheduled to be attempted. * For App Engine queues, this is when the task will be attempted or retried. * For pull queues, this is the time when the task is available to * be leased; if a task is currently leased, this is the time when * the current lease expires, that is, the time that the task was * leased plus the [lease_duration][google.cloud.tasks.v2beta2.LeaseTasksRequest.lease_duration]. * `schedule_time` will be truncated to the nearest microsecond. * </pre> * * <code>.google.protobuf.Timestamp schedule_time = 5;</code> */ public Builder setScheduleTime(com.google.protobuf.Timestamp value) { if (scheduleTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } scheduleTime_ = value; onChanged(); } else { scheduleTimeBuilder_.setMessage(value); } return this; } /** * * * <pre> * The time when the task is scheduled to be attempted. * For App Engine queues, this is when the task will be attempted or retried. * For pull queues, this is the time when the task is available to * be leased; if a task is currently leased, this is the time when * the current lease expires, that is, the time that the task was * leased plus the [lease_duration][google.cloud.tasks.v2beta2.LeaseTasksRequest.lease_duration]. * `schedule_time` will be truncated to the nearest microsecond. * </pre> * * <code>.google.protobuf.Timestamp schedule_time = 5;</code> */ public Builder setScheduleTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (scheduleTimeBuilder_ == null) { scheduleTime_ = builderForValue.build(); onChanged(); } else { scheduleTimeBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * The time when the task is scheduled to be attempted. * For App Engine queues, this is when the task will be attempted or retried. * For pull queues, this is the time when the task is available to * be leased; if a task is currently leased, this is the time when * the current lease expires, that is, the time that the task was * leased plus the [lease_duration][google.cloud.tasks.v2beta2.LeaseTasksRequest.lease_duration]. * `schedule_time` will be truncated to the nearest microsecond. * </pre> * * <code>.google.protobuf.Timestamp schedule_time = 5;</code> */ public Builder mergeScheduleTime(com.google.protobuf.Timestamp value) { if (scheduleTimeBuilder_ == null) { if (scheduleTime_ != null) { scheduleTime_ = com.google.protobuf.Timestamp.newBuilder(scheduleTime_) .mergeFrom(value) .buildPartial(); } else { scheduleTime_ = value; } onChanged(); } else { scheduleTimeBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * The time when the task is scheduled to be attempted. * For App Engine queues, this is when the task will be attempted or retried. * For pull queues, this is the time when the task is available to * be leased; if a task is currently leased, this is the time when * the current lease expires, that is, the time that the task was * leased plus the [lease_duration][google.cloud.tasks.v2beta2.LeaseTasksRequest.lease_duration]. * `schedule_time` will be truncated to the nearest microsecond. * </pre> * * <code>.google.protobuf.Timestamp schedule_time = 5;</code> */ public Builder clearScheduleTime() { if (scheduleTimeBuilder_ == null) { scheduleTime_ = null; onChanged(); } else { scheduleTime_ = null; scheduleTimeBuilder_ = null; } return this; } /** * * * <pre> * The time when the task is scheduled to be attempted. * For App Engine queues, this is when the task will be attempted or retried. * For pull queues, this is the time when the task is available to * be leased; if a task is currently leased, this is the time when * the current lease expires, that is, the time that the task was * leased plus the [lease_duration][google.cloud.tasks.v2beta2.LeaseTasksRequest.lease_duration]. * `schedule_time` will be truncated to the nearest microsecond. * </pre> * * <code>.google.protobuf.Timestamp schedule_time = 5;</code> */ public com.google.protobuf.Timestamp.Builder getScheduleTimeBuilder() { onChanged(); return getScheduleTimeFieldBuilder().getBuilder(); } /** * * * <pre> * The time when the task is scheduled to be attempted. * For App Engine queues, this is when the task will be attempted or retried. * For pull queues, this is the time when the task is available to * be leased; if a task is currently leased, this is the time when * the current lease expires, that is, the time that the task was * leased plus the [lease_duration][google.cloud.tasks.v2beta2.LeaseTasksRequest.lease_duration]. * `schedule_time` will be truncated to the nearest microsecond. * </pre> * * <code>.google.protobuf.Timestamp schedule_time = 5;</code> */ public com.google.protobuf.TimestampOrBuilder getScheduleTimeOrBuilder() { if (scheduleTimeBuilder_ != null) { return scheduleTimeBuilder_.getMessageOrBuilder(); } else { return scheduleTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : scheduleTime_; } } /** * * * <pre> * The time when the task is scheduled to be attempted. * For App Engine queues, this is when the task will be attempted or retried. * For pull queues, this is the time when the task is available to * be leased; if a task is currently leased, this is the time when * the current lease expires, that is, the time that the task was * leased plus the [lease_duration][google.cloud.tasks.v2beta2.LeaseTasksRequest.lease_duration]. * `schedule_time` will be truncated to the nearest microsecond. * </pre> * * <code>.google.protobuf.Timestamp schedule_time = 5;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getScheduleTimeFieldBuilder() { if (scheduleTimeBuilder_ == null) { scheduleTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getScheduleTime(), getParentForChildren(), isClean()); scheduleTime_ = null; } return scheduleTimeBuilder_; } private com.google.protobuf.Timestamp createTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> createTimeBuilder_; /** * * * <pre> * Output only. The time that the task was created. * `create_time` will be truncated to the nearest second. * </pre> * * <code>.google.protobuf.Timestamp create_time = 6;</code> * * @return Whether the createTime field is set. */ public boolean hasCreateTime() { return createTimeBuilder_ != null || createTime_ != null; } /** * * * <pre> * Output only. The time that the task was created. * `create_time` will be truncated to the nearest second. * </pre> * * <code>.google.protobuf.Timestamp create_time = 6;</code> * * @return The createTime. */ public com.google.protobuf.Timestamp getCreateTime() { if (createTimeBuilder_ == null) { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } else { return createTimeBuilder_.getMessage(); } } /** * * * <pre> * Output only. The time that the task was created. * `create_time` will be truncated to the nearest second. * </pre> * * <code>.google.protobuf.Timestamp create_time = 6;</code> */ public Builder setCreateTime(com.google.protobuf.Timestamp value) { if (createTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } createTime_ = value; onChanged(); } else { createTimeBuilder_.setMessage(value); } return this; } /** * * * <pre> * Output only. The time that the task was created. * `create_time` will be truncated to the nearest second. * </pre> * * <code>.google.protobuf.Timestamp create_time = 6;</code> */ public Builder setCreateTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (createTimeBuilder_ == null) { createTime_ = builderForValue.build(); onChanged(); } else { createTimeBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Output only. The time that the task was created. * `create_time` will be truncated to the nearest second. * </pre> * * <code>.google.protobuf.Timestamp create_time = 6;</code> */ public Builder mergeCreateTime(com.google.protobuf.Timestamp value) { if (createTimeBuilder_ == null) { if (createTime_ != null) { createTime_ = com.google.protobuf.Timestamp.newBuilder(createTime_).mergeFrom(value).buildPartial(); } else { createTime_ = value; } onChanged(); } else { createTimeBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Output only. The time that the task was created. * `create_time` will be truncated to the nearest second. * </pre> * * <code>.google.protobuf.Timestamp create_time = 6;</code> */ public Builder clearCreateTime() { if (createTimeBuilder_ == null) { createTime_ = null; onChanged(); } else { createTime_ = null; createTimeBuilder_ = null; } return this; } /** * * * <pre> * Output only. The time that the task was created. * `create_time` will be truncated to the nearest second. * </pre> * * <code>.google.protobuf.Timestamp create_time = 6;</code> */ public com.google.protobuf.Timestamp.Builder getCreateTimeBuilder() { onChanged(); return getCreateTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Output only. The time that the task was created. * `create_time` will be truncated to the nearest second. * </pre> * * <code>.google.protobuf.Timestamp create_time = 6;</code> */ public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() { if (createTimeBuilder_ != null) { return createTimeBuilder_.getMessageOrBuilder(); } else { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } } /** * * * <pre> * Output only. The time that the task was created. * `create_time` will be truncated to the nearest second. * </pre> * * <code>.google.protobuf.Timestamp create_time = 6;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getCreateTimeFieldBuilder() { if (createTimeBuilder_ == null) { createTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getCreateTime(), getParentForChildren(), isClean()); createTime_ = null; } return createTimeBuilder_; } private com.google.cloud.tasks.v2beta2.TaskStatus status_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.tasks.v2beta2.TaskStatus, com.google.cloud.tasks.v2beta2.TaskStatus.Builder, com.google.cloud.tasks.v2beta2.TaskStatusOrBuilder> statusBuilder_; /** * * * <pre> * Output only. The task status. * </pre> * * <code>.google.cloud.tasks.v2beta2.TaskStatus status = 7;</code> * * @return Whether the status field is set. */ public boolean hasStatus() { return statusBuilder_ != null || status_ != null; } /** * * * <pre> * Output only. The task status. * </pre> * * <code>.google.cloud.tasks.v2beta2.TaskStatus status = 7;</code> * * @return The status. */ public com.google.cloud.tasks.v2beta2.TaskStatus getStatus() { if (statusBuilder_ == null) { return status_ == null ? com.google.cloud.tasks.v2beta2.TaskStatus.getDefaultInstance() : status_; } else { return statusBuilder_.getMessage(); } } /** * * * <pre> * Output only. The task status. * </pre> * * <code>.google.cloud.tasks.v2beta2.TaskStatus status = 7;</code> */ public Builder setStatus(com.google.cloud.tasks.v2beta2.TaskStatus value) { if (statusBuilder_ == null) { if (value == null) { throw new NullPointerException(); } status_ = value; onChanged(); } else { statusBuilder_.setMessage(value); } return this; } /** * * * <pre> * Output only. The task status. * </pre> * * <code>.google.cloud.tasks.v2beta2.TaskStatus status = 7;</code> */ public Builder setStatus(com.google.cloud.tasks.v2beta2.TaskStatus.Builder builderForValue) { if (statusBuilder_ == null) { status_ = builderForValue.build(); onChanged(); } else { statusBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Output only. The task status. * </pre> * * <code>.google.cloud.tasks.v2beta2.TaskStatus status = 7;</code> */ public Builder mergeStatus(com.google.cloud.tasks.v2beta2.TaskStatus value) { if (statusBuilder_ == null) { if (status_ != null) { status_ = com.google.cloud.tasks.v2beta2.TaskStatus.newBuilder(status_) .mergeFrom(value) .buildPartial(); } else { status_ = value; } onChanged(); } else { statusBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Output only. The task status. * </pre> * * <code>.google.cloud.tasks.v2beta2.TaskStatus status = 7;</code> */ public Builder clearStatus() { if (statusBuilder_ == null) { status_ = null; onChanged(); } else { status_ = null; statusBuilder_ = null; } return this; } /** * * * <pre> * Output only. The task status. * </pre> * * <code>.google.cloud.tasks.v2beta2.TaskStatus status = 7;</code> */ public com.google.cloud.tasks.v2beta2.TaskStatus.Builder getStatusBuilder() { onChanged(); return getStatusFieldBuilder().getBuilder(); } /** * * * <pre> * Output only. The task status. * </pre> * * <code>.google.cloud.tasks.v2beta2.TaskStatus status = 7;</code> */ public com.google.cloud.tasks.v2beta2.TaskStatusOrBuilder getStatusOrBuilder() { if (statusBuilder_ != null) { return statusBuilder_.getMessageOrBuilder(); } else { return status_ == null ? com.google.cloud.tasks.v2beta2.TaskStatus.getDefaultInstance() : status_; } } /** * * * <pre> * Output only. The task status. * </pre> * * <code>.google.cloud.tasks.v2beta2.TaskStatus status = 7;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.tasks.v2beta2.TaskStatus, com.google.cloud.tasks.v2beta2.TaskStatus.Builder, com.google.cloud.tasks.v2beta2.TaskStatusOrBuilder> getStatusFieldBuilder() { if (statusBuilder_ == null) { statusBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.tasks.v2beta2.TaskStatus, com.google.cloud.tasks.v2beta2.TaskStatus.Builder, com.google.cloud.tasks.v2beta2.TaskStatusOrBuilder>( getStatus(), getParentForChildren(), isClean()); status_ = null; } return statusBuilder_; } private int view_ = 0; /** * * * <pre> * Output only. The view specifies which subset of the [Task][google.cloud.tasks.v2beta2.Task] has * been returned. * </pre> * * <code>.google.cloud.tasks.v2beta2.Task.View view = 8;</code> * * @return The enum numeric value on the wire for view. */ public int getViewValue() { return view_; } /** * * * <pre> * Output only. The view specifies which subset of the [Task][google.cloud.tasks.v2beta2.Task] has * been returned. * </pre> * * <code>.google.cloud.tasks.v2beta2.Task.View view = 8;</code> * * @param value The enum numeric value on the wire for view to set. * @return This builder for chaining. */ public Builder setViewValue(int value) { view_ = value; onChanged(); return this; } /** * * * <pre> * Output only. The view specifies which subset of the [Task][google.cloud.tasks.v2beta2.Task] has * been returned. * </pre> * * <code>.google.cloud.tasks.v2beta2.Task.View view = 8;</code> * * @return The view. */ public com.google.cloud.tasks.v2beta2.Task.View getView() { @SuppressWarnings("deprecation") com.google.cloud.tasks.v2beta2.Task.View result = com.google.cloud.tasks.v2beta2.Task.View.valueOf(view_); return result == null ? com.google.cloud.tasks.v2beta2.Task.View.UNRECOGNIZED : result; } /** * * * <pre> * Output only. The view specifies which subset of the [Task][google.cloud.tasks.v2beta2.Task] has * been returned. * </pre> * * <code>.google.cloud.tasks.v2beta2.Task.View view = 8;</code> * * @param value The view to set. * @return This builder for chaining. */ public Builder setView(com.google.cloud.tasks.v2beta2.Task.View value) { if (value == null) { throw new NullPointerException(); } view_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Output only. The view specifies which subset of the [Task][google.cloud.tasks.v2beta2.Task] has * been returned. * </pre> * * <code>.google.cloud.tasks.v2beta2.Task.View view = 8;</code> * * @return This builder for chaining. */ public Builder clearView() { view_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.tasks.v2beta2.Task) } // @@protoc_insertion_point(class_scope:google.cloud.tasks.v2beta2.Task) private static final com.google.cloud.tasks.v2beta2.Task DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.tasks.v2beta2.Task(); } public static com.google.cloud.tasks.v2beta2.Task getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Task> PARSER = new com.google.protobuf.AbstractParser<Task>() { @java.lang.Override public Task parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Task(input, extensionRegistry); } }; public static com.google.protobuf.Parser<Task> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Task> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.tasks.v2beta2.Task getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
923d33c8e3c6936c6a35714413eed6a535134875
2,451
java
Java
src/main/java/com/manywho/services/identity/authentication/AuthenticationManager.java
manywho/service-identity
7d888567ba276a2b811abaaafe3e67543efada7f
[ "MIT" ]
3
2017-05-27T11:23:28.000Z
2020-05-24T13:57:06.000Z
src/main/java/com/manywho/services/identity/authentication/AuthenticationManager.java
manywho/service-identity
7d888567ba276a2b811abaaafe3e67543efada7f
[ "MIT" ]
53
2017-09-29T13:09:55.000Z
2022-02-16T00:49:56.000Z
src/main/java/com/manywho/services/identity/authentication/AuthenticationManager.java
manywho/service-identity
7d888567ba276a2b811abaaafe3e67543efada7f
[ "MIT" ]
1
2019-10-16T04:06:33.000Z
2019-10-16T04:06:33.000Z
46.245283
112
0.747858
1,000,216
package com.manywho.services.identity.authentication; import com.manywho.sdk.api.security.AuthenticatedWhoResult; import com.manywho.sdk.api.security.AuthenticationCredentials; import com.manywho.sdk.services.configuration.ConfigurationParser; import com.manywho.services.identity.ServiceConfiguration; import com.manywho.services.identity.users.User; import org.springframework.security.crypto.bcrypt.BCrypt; import javax.inject.Inject; import java.util.UUID; public class AuthenticationManager { private final AuthenticationRepository repository; private final ConfigurationParser configurationParser; @Inject public AuthenticationManager(AuthenticationRepository repository, ConfigurationParser configurationParser) { this.repository = repository; this.configurationParser = configurationParser; } public AuthenticatedWhoResult authenticate(AuthenticationCredentials credentials) { ServiceConfiguration configuration = configurationParser.from(credentials); // See if the user exists by the given email address User user = repository.findUserByEmail(configuration, credentials.getUsername()); if (user == null || !user.hasPassword()) { return AuthenticatedWhoResult.createDeniedResult(); } // Check the given credentials against the database and either authenticate or don't if (BCrypt.checkpw(credentials.getPassword(), user.getPassword())) { AuthenticatedWhoResult authenticatedWhoResult = new AuthenticatedWhoResult(); authenticatedWhoResult.setDirectoryId("manywho-identity"); authenticatedWhoResult.setDirectoryName("ManyWho Identity"); authenticatedWhoResult.setEmail(user.getEmail()); authenticatedWhoResult.setFirstName(user.getFirstName()); authenticatedWhoResult.setIdentityProvider("?"); authenticatedWhoResult.setLastName(user.getLastName()); authenticatedWhoResult.setStatus(AuthenticatedWhoResult.AuthenticationStatus.Authenticated); authenticatedWhoResult.setTenantName("?"); authenticatedWhoResult.setToken(UUID.randomUUID().toString()); authenticatedWhoResult.setUserId(user.getId().toString()); authenticatedWhoResult.setUsername(user.getEmail()); return authenticatedWhoResult; } return AuthenticatedWhoResult.createDeniedResult(); } }
923d34bbe638b320c7963ca6700e61f616190e83
289
java
Java
codegen/src/test/java/io/automatiko/engine/codegen/data/Results.java
automatiko-io/automatiko-engine
463ee717912c50c8e244f361c1948a0916f804fc
[ "Apache-2.0" ]
26
2021-01-25T19:56:07.000Z
2022-03-07T00:03:18.000Z
codegen/src/test/java/io/automatiko/engine/codegen/data/Results.java
automatiko-io/automatiko-engine
463ee717912c50c8e244f361c1948a0916f804fc
[ "Apache-2.0" ]
99
2021-01-28T10:57:27.000Z
2022-03-29T16:19:19.000Z
codegen/src/test/java/io/automatiko/engine/codegen/data/Results.java
automatiko-io/automatiko-engine
463ee717912c50c8e244f361c1948a0916f804fc
[ "Apache-2.0" ]
3
2021-01-25T22:06:10.000Z
2022-03-03T10:08:01.000Z
15.210526
56
0.712803
1,000,217
package io.automatiko.engine.codegen.data; import java.util.ArrayList; import java.util.List; public class Results { private final List<String> results = new ArrayList<>(); public void add(String s) { results.add(s); } public List<String> getResults() { return results; } }
923d35cd4a7adfde57fd6fd67b85cd266f0896b5
16,278
java
Java
src/com/melib/Base/CMathLibMe.java
kakaalakaka/mechart_android
f1bc9b29b10d91bd4cb45a561f93f11e9a5c6332
[ "MIT" ]
1
2019-03-19T07:59:13.000Z
2019-03-19T07:59:13.000Z
src/com/melib/Base/CMathLibMe.java
kakaalakaka/mechart_android
f1bc9b29b10d91bd4cb45a561f93f11e9a5c6332
[ "MIT" ]
null
null
null
src/com/melib/Base/CMathLibMe.java
kakaalakaka/mechart_android
f1bc9b29b10d91bd4cb45a561f93f11e9a5c6332
[ "MIT" ]
1
2019-11-10T07:26:17.000Z
2019-11-10T07:26:17.000Z
32.233663
116
0.599214
1,000,218
package com.melib.Base; import java.util.Calendar; import java.util.GregorianCalendar; import com.melib.Indicator.LPDATA; /** * @file * @copyright defined in mechart_android/LICENSE */ public class CMathLibMe { public static void M001(int index, int n, double s, double m, double high, double low, double hhv, double llv, int last_state, double last_sar, double last_af, RefObject<Integer> state, RefObject<Double> af, RefObject<Double> sar) { if (index >= n) { if (index == n) { af.argvalue = Double.valueOf(s); if (llv < low) { sar.argvalue = Double.valueOf(llv); state.argvalue = Integer.valueOf(1); } if (hhv > high) { sar.argvalue = Double.valueOf(hhv); state.argvalue = Integer.valueOf(2); } } else { state.argvalue = Integer.valueOf(last_state); af.argvalue = Double.valueOf(last_af); RefObject<Double> localRefObject; if (((Integer) state.argvalue).intValue() == 1) { if (high > hhv) { localRefObject = af; localRefObject.argvalue = Double.valueOf(((Double) localRefObject.argvalue).doubleValue() + s); if (((Double) af.argvalue).doubleValue() > m) { af.argvalue = Double.valueOf(m); } } sar.argvalue = Double.valueOf(last_sar + ((Double) af.argvalue).doubleValue() * (hhv - last_sar)); if (((Double) sar.argvalue).doubleValue() < low) { state.argvalue = Integer.valueOf(1); } else { state.argvalue = Integer.valueOf(3); } } else if (((Integer) state.argvalue).intValue() == 2) { if (low < llv) { localRefObject = af; localRefObject.argvalue = Double.valueOf(((Double) localRefObject.argvalue).doubleValue() + s); if (((Double) af.argvalue).doubleValue() > m) af.argvalue = Double.valueOf(m); } sar.argvalue = Double.valueOf(last_sar + ((Double) af.argvalue).doubleValue() * (llv - last_sar)); if (((Double) sar.argvalue).doubleValue() > high) { state.argvalue = Integer.valueOf(2); } else { state.argvalue = Integer.valueOf(4); } } else if (((Integer) state.argvalue).intValue() == 3) { sar.argvalue = Double.valueOf(hhv); if (((Double) sar.argvalue).doubleValue() > high) { state.argvalue = Integer.valueOf(2); } else { state.argvalue = Integer.valueOf(4); } af.argvalue = Double.valueOf(s); } else if (((Integer) state.argvalue).intValue() == 4) { sar.argvalue = Double.valueOf(llv); if (((Double) sar.argvalue).doubleValue() < low) { state.argvalue = Integer.valueOf(1); } else { state.argvalue = Integer.valueOf(3); } af.argvalue = Double.valueOf(s); } } } } public static double M002(double value, double[] listForAvedev, int listForAvedev_length, double avg) { int i = 0; if (listForAvedev_length > 0) { double sum = Math.abs(value - avg); for (i = 0; i < listForAvedev_length; i++) { sum += Math.abs(listForAvedev[i] - avg); } return sum / listForAvedev_length; } return 0.0D; } public static double M003(int index, int n, double value, LPDATA last_MA) { double sum = 0.0D; if (last_MA.mode == 0) { sum = last_MA.sum + value; } else { if (index > n - 1) { sum = last_MA.lastvalue * n; sum -= last_MA.first_value; } else { sum = last_MA.lastvalue * index; n = index + 1; } sum += value; } return sum / n; } public static double M004(int index, int n, double value, LPDATA last_SUM) { double sum = 0.0D; if (last_SUM.mode == 0) { sum = last_SUM.sum + value; } else { sum = last_SUM.lastvalue; if (index > n - 1) { sum -= last_SUM.first_value; } sum += value; } return sum; } public static double M005(int n, int weight, double value, double lastWMA) { return (value * weight + (n - weight) * lastWMA) / n; } public static double M006(int n, double value, double lastEMA) { return (value * 2.0D + lastEMA * (n - 1)) / (n + 1); } public static double M007(double[] list, int length, double avg, double standardDeviation) { int i = 0; if (length > 0) { double sum = 0.0D; for (i = 0; i < length; i++) { sum += (list[i] - avg) * (list[i] - avg); } return standardDeviation * Math.sqrt(sum / length); } return 0.0D; } public static double GetMin(double[] list, int length) { double min = 0.0D; int i = 0; for (i = 0; i < length; i++) { if (i == 0) { min = list[i]; } else if (min > list[i]) { min = list[i]; } } return min; } public static double GetMax(double[] list, int length) { double max = 0.0D; int i = 0; for (i = 0; i < length; i++) { if (i == 0) { max = list[i]; } else if (max < list[i]) { max = list[i]; } } return max; } public static double M010(double[] list, int length) { int i = 0; double sum = 0.0D; if (length > 0) { for (i = 0; i < length; i++) { sum += list[i]; } return sum / length; } return 0.0D; } public static double M011(double[] list, int length) { double sum = 0.0D; int i = 0; for (i = 0; i < length; i++) { sum += list[i]; } return sum; } public static int M012(double min, double max, int yLen, int maxSpan, int minSpan, int defCount, RefObject<Double> step, RefObject<Integer> digit) { double sub = max - min; int nMinCount = (int) Math.ceil(yLen / maxSpan); int nMaxCount = (int) Math.floor(yLen / minSpan); int nCount = defCount; double logStep = sub / nCount; boolean start = false; double divisor = 0.0D; int i = 0; int nTemp = 0; step.argvalue = Double.valueOf(0.0D); digit.argvalue = Integer.valueOf(0); nCount = Math.max(nMinCount, nCount); nCount = Math.min(nMaxCount, nCount); nCount = Math.max(nCount, 1); for (i = 15; i >= -6; i--) { divisor = Math.pow(10.0D, i); Object localObject; Integer localInteger1; Integer localInteger2; if (divisor < 1.0D) { localObject = digit; localInteger1 = (Integer) ((RefObject) localObject).argvalue; localInteger2 = (Integer) (((RefObject) localObject).argvalue = Integer .valueOf(((Integer) ((RefObject) localObject).argvalue).intValue() + 1)); } nTemp = (int) Math.floor(logStep / divisor); if (start) { if (nTemp < 4) { if (((Integer) digit.argvalue).intValue() <= 0) break; localObject = digit; localInteger1 = (Integer) ((RefObject) localObject).argvalue; localInteger2 = (Integer) (((RefObject) localObject).argvalue = Integer .valueOf(((Integer) ((RefObject) localObject).argvalue).intValue() - 1)); break; } if ((nTemp >= 4) && (nTemp <= 6)) { nTemp = 5; localObject = step; ((RefObject) localObject).argvalue = Double .valueOf(((Double) ((RefObject) localObject).argvalue).doubleValue() + nTemp * divisor); break; } localObject = step; ((RefObject) localObject).argvalue = Double .valueOf(((Double) ((RefObject) localObject).argvalue).doubleValue() + 10.0D * divisor); if (((Integer) digit.argvalue).intValue() <= 0) break; localObject = digit; localInteger1 = (Integer) ((RefObject) localObject).argvalue; localInteger2 = (Integer) (((RefObject) localObject).argvalue = Integer .valueOf(((Integer) ((RefObject) localObject).argvalue).intValue() - 1)); break; } if (nTemp > 0) { step.argvalue = Double.valueOf(nTemp * divisor + ((Double) step.argvalue).doubleValue()); logStep -= ((Double) step.argvalue).doubleValue(); start = true; } } return 0; } public static void M013(int index, double close, double p, RefObject<Double> sxp, RefObject<Integer> sxi, RefObject<Double> exp, RefObject<Integer> exi, RefObject<Integer> state, RefObject<Integer> cStart, RefObject<Integer> cEnd, RefObject<Double> k, RefObject<Double> b) { boolean reverse = false; boolean ex = false; if (index == 0) { sxp.argvalue = Double.valueOf(close); exp.argvalue = Double.valueOf(close); } else if (index == 1) { if (close >= ((Double) exp.argvalue).doubleValue()) { state.argvalue = Integer.valueOf(0); } else { state.argvalue = Integer.valueOf(1); } exp.argvalue = Double.valueOf(close); exi.argvalue = Integer.valueOf(1); } else { if (((Integer) state.argvalue).intValue() == 0) { if (100.0D * (((Double) exp.argvalue).doubleValue() - close) / ((Double) exp.argvalue).doubleValue() > p) { reverse = true; } else if (close >= ((Double) exp.argvalue).doubleValue()) { ex = true; } } else if (100.0D * (close - ((Double) exp.argvalue).doubleValue()) / ((Double) exp.argvalue).doubleValue() > p) { reverse = true; } else if (close <= ((Double) exp.argvalue).doubleValue()) { ex = true; } if (reverse == true) { if (((Integer) state.argvalue).intValue() == 1) { state.argvalue = Integer.valueOf(0); } else { state.argvalue = Integer.valueOf(1); } k.argvalue = Double .valueOf((((Double) exp.argvalue).doubleValue() - ((Double) sxp.argvalue).doubleValue()) / (((Integer) exi.argvalue).intValue() - ((Integer) sxi.argvalue).intValue())); b.argvalue = Double.valueOf(((Double) exp.argvalue).doubleValue() - ((Double) k.argvalue).doubleValue() * ((Integer) exi.argvalue).intValue()); cStart.argvalue = sxi.argvalue; cEnd.argvalue = exi.argvalue; sxi.argvalue = exi.argvalue; sxp.argvalue = exp.argvalue; exi.argvalue = Integer.valueOf(index); exp.argvalue = Double.valueOf(close); } else if (ex == true) { exp.argvalue = Double.valueOf(close); exi.argvalue = Integer.valueOf(index); k.argvalue = Double .valueOf((((Double) exp.argvalue).doubleValue() - ((Double) sxp.argvalue).doubleValue()) / (((Integer) exi.argvalue).intValue() - ((Integer) sxi.argvalue).intValue())); b.argvalue = Double.valueOf(((Double) exp.argvalue).doubleValue() - ((Double) k.argvalue).doubleValue() * ((Integer) exi.argvalue).intValue()); cStart.argvalue = sxi.argvalue; cEnd.argvalue = exi.argvalue; } else { k.argvalue = Double.valueOf((close - ((Double) exp.argvalue).doubleValue()) / (index - ((Integer) exi.argvalue).intValue())); b.argvalue = Double.valueOf(close - ((Double) k.argvalue).doubleValue() * index); cStart.argvalue = exi.argvalue; cEnd.argvalue = Integer.valueOf(index); } } } public static void M014(double[] list, int length, RefObject<Float> k, RefObject<Float> b) { int i = 0; double sumX = 0.0D; double sumY = 0.0D; double sumUp = 0.0D; double sumDown = 0.0D; double xAvg = 0.0D; double yAvg = 0.0D; k.argvalue = Float.valueOf(0.0F); b.argvalue = Float.valueOf(0.0F); if (length > 1) { for (i = 0; i < length; i++) { sumX += i + 1; sumY += list[i]; } xAvg = sumX / length; yAvg = sumY / length; for (i = 0; i < length; i++) { sumUp += (i + 1 - xAvg) * (list[i] - yAvg); sumDown += (i + 1 - xAvg) * (i + 1 - xAvg); } k.argvalue = Float.valueOf((float) (sumUp / sumDown)); b.argvalue = Float.valueOf((float) (yAvg - ((Float) k.argvalue).floatValue() * xAvg)); } } public static double M015(double close, double lastSma, int n, int m) { return (close * m + lastSma * (n - m)) / n; } public static void M105(int x1, int y1, int x2, int y2, RefObject<Integer> x, RefObject<Integer> y, RefObject<Integer> w, RefObject<Integer> h) { x.argvalue = Integer.valueOf(x1 < x2 ? x1 : x2); y.argvalue = Integer.valueOf(y1 < y2 ? y1 : y2); w.argvalue = Integer.valueOf(Math.abs(x1 - x2)); h.argvalue = Integer.valueOf(Math.abs(y1 - y2)); if (((Integer) w.argvalue).intValue() <= 0) { w.argvalue = Integer.valueOf(4); } if (((Integer) h.argvalue).intValue() <= 0) { h.argvalue = Integer.valueOf(4); } } public static double M106(float x1, float y1, float x2, float y2, float oX, float oY) { if (x1 - oX != x2 - oX) { return (y2 - oY - (y1 - oY)) / (x2 - oX - (x1 - oX)); } return 0.0D; } public static void M107(float x1, float y1, float x2, float y2, float oX, float oY, RefObject<Float> k, RefObject<Float> b) { k.argvalue = Float.valueOf(0.0F); b.argvalue = Float.valueOf(0.0F); if (x1 - oX != x2 - oX) { k.argvalue = Float.valueOf((y2 - oY - (y1 - oY)) / (x2 - oX - (x1 - oX))); b.argvalue = Float.valueOf(y1 - oY - ((Float) k.argvalue).floatValue() * (x1 - oX)); } } public static void M108(float width, float height, RefObject<Float> a, RefObject<Float> b) { a.argvalue = Float.valueOf(width / 2.0F); b.argvalue = Float.valueOf(height / 2.0F); } public static boolean M109(float x, float y, float oX, float oY, float a, float b) { x -= oX; y -= oY; if ((a == 0.0F) && (b == 0.0F) && (x == 0.0F) && (y == 0.0F)) { return true; } if (a == 0.0F) { if ((x == 0.0F) && (y >= -b) && (y <= b)) { return false; } } if (b == 0.0F) { if ((y == 0.0F) && (x >= -a) && (x <= a)) { return true; } } if ((x * x / (a * a) + y * y / (b * b) >= 0.8D) && (x * x / (a * a) + y * y / (b * b) <= 1.2D)) { return true; } return false; } public static void M110(float x1, float y1, float x2, float y2, float x3, float y3, RefObject<Float> oX, RefObject<Float> oY, RefObject<Float> r) { oX.argvalue = Float.valueOf(((y3 - y1) * (y2 * y2 - y1 * y1 + x2 * x2 - x1 * x1) + (y2 - y1) * (y1 * y1 - y3 * y3 + x1 * x1 - x3 * x3)) / (2.0F * (x2 - x1) * (y3 - y1) - 2.0F * (x3 - x1) * (y2 - y1))); oY.argvalue = Float.valueOf(((x3 - x1) * (x2 * x2 - x1 * x1 + y2 * y2 - y1 * y1) + (x2 - x1) * (x1 * x1 - x3 * x3 + y1 * y1 - y3 * y3)) / (2.0F * (y2 - y1) * (x3 - x1) - 2.0F * (y3 - y1) * (x2 - x1))); r.argvalue = Float.valueOf( (float) Math.sqrt((x1 - ((Float) oX.argvalue).floatValue()) * (x1 - ((Float) oX.argvalue).floatValue()) + (y1 - ((Float) oY.argvalue).floatValue()) * (y1 - ((Float) oY.argvalue).floatValue()))); } public static int M112(int index) { if (index < 1) { return 0; } int i = 0; int result = 0; int[] vList = new int[index]; for (i = 0; i <= index - 1; i++) { if ((i == 0) || (i == 1)) { vList[i] = 1; } else { vList[i] = (vList[(i - 1)] + vList[(i - 2)]); } } result = vList[(index - 1)]; return result; } public static void M124(float x1, float y1, float x2, float y2, float x3, float y3, RefObject<Float> x4, RefObject<Float> y4) { x4.argvalue = Float.valueOf(x1 + x3 - x2); y4.argvalue = Float.valueOf(y1 + y3 - y2); } public static int IsLeapYear(int year) { return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0) ? 1 : 0; } public static int[][] m_ytab = { { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } }; public static double M129(int tm_year, int tm_mon, int tm_mday, int tm_hour, int tm_min, int tm_sec, int tm_msec) { double tn = 0.0D; tm_mon -= 2; if (tm_mon <= 0) { tm_mon += 12; tm_year--; } double day = tm_year / 4 - tm_year / 100 + tm_year / 400 + 367 * tm_mon / 12 + tm_mday; double year = tm_year * 365 - 719499; tn = (day + year) * 24.0D * 60.0D * 60.0D + tm_hour * 3600 + tm_min * 60 + tm_sec; return tn + tm_msec / 1000; } public static void M130(double num, RefObject<Integer> tm_year, RefObject<Integer> tm_mon, RefObject<Integer> tm_mday, RefObject<Integer> tm_hour, RefObject<Integer> tm_min, RefObject<Integer> tm_sec, RefObject<Integer> tm_msec) { long date = (long) num; int seconds = (int) (date % 86400L); int days = (int) (date / 86400L); int startYear = 1970; tm_sec.argvalue = Integer.valueOf(seconds % 60); tm_min.argvalue = Integer.valueOf(seconds % 3600 / 60); tm_hour.argvalue = Integer.valueOf(seconds / 3600); int index = 0; while (days >= (index = IsLeapYear(startYear) == 1 ? 366 : 365)) { days -= index; startYear++; } tm_year.argvalue = Integer.valueOf(startYear); int monthIndex = 0; while (days >= m_ytab[IsLeapYear(startYear)][monthIndex]) { days -= m_ytab[IsLeapYear(startYear)][monthIndex]; monthIndex++; } tm_mon.argvalue = Integer.valueOf(monthIndex + 1); tm_mday.argvalue = Integer.valueOf(days + 1); tm_msec.argvalue = Integer.valueOf((int) (num * 1000.0D - Math.floor(num) * 1000.0D)); } }
923d35ce6b95bcec8fa21a6883d386bb9df7a868
1,420
java
Java
src/test/java/com/roy/algorithm/inflearn/retry2/string/Palindrome.java
roy-zz/algorithm
d5d07e1bd59c8595426b2dec9fc13de199e5f046
[ "Apache-2.0" ]
null
null
null
src/test/java/com/roy/algorithm/inflearn/retry2/string/Palindrome.java
roy-zz/algorithm
d5d07e1bd59c8595426b2dec9fc13de199e5f046
[ "Apache-2.0" ]
null
null
null
src/test/java/com/roy/algorithm/inflearn/retry2/string/Palindrome.java
roy-zz/algorithm
d5d07e1bd59c8595426b2dec9fc13de199e5f046
[ "Apache-2.0" ]
null
null
null
28.4
70
0.609859
1,000,219
package com.roy.algorithm.inflearn.retry2.string; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; // 유효한 팰린드롬 // // 앞에서 읽을 때나 뒤에서 읽을 때나 같은 문자열을 팰린드롬이라고 합니다. // 문자열이 입력되면 해당 문자열이 팰린드롬이면 "YES", 아니면 “NO"를 출력하는 프로그램을 작성하세요. // 단 회문을 검사할 때 알파벳만 가지고 회문을 검사하며, 대소문자를 구분하지 않습니다. 알파벳 이외의 문자들의 무시합니다. // - 입력설명 // 첫 줄에 길이 100을 넘지 않는 공백이 없는 문자열이 주어집니다. // - 출력설명 // 첫 번째 줄에 팰린드롬인지의 결과를 YES 또는 NO로 출력합니다. // - 입력예제 1 // found7, time: study; Yduts; emit, 7Dnuof // - 출력예제 1 // YES @SuppressWarnings("NewClassNamingConvention") public class Palindrome { public String solution1(String input) { char[] charOfInput = input.toUpperCase().toCharArray(); int left = 0; int right = charOfInput.length - 1; while (right >= left) { if (Character.isAlphabetic(charOfInput[left]) && Character.isAlphabetic(charOfInput[right]) && charOfInput[left] != charOfInput[right]) { return "NO"; } left++; right--; } return "YES"; } @Test @DisplayName("유효한 팰린드롬") public void main() { String input = "found7, time: study; Yduts; emit, 7Dnuof"; String expectedAnswer = "YES"; String answer = solution1(input); assertEquals(expectedAnswer, answer); } }
923d35d7c5666f7e1cc3143fb0c45431af4e21d8
1,840
java
Java
src/abstracts/VendorConnectionPool.java
didizlatkova/Mail-Sender-With-Creational-Patterns
ccb8a281be582df5df3c12d1b180c166c2431ec6
[ "MIT" ]
null
null
null
src/abstracts/VendorConnectionPool.java
didizlatkova/Mail-Sender-With-Creational-Patterns
ccb8a281be582df5df3c12d1b180c166c2431ec6
[ "MIT" ]
null
null
null
src/abstracts/VendorConnectionPool.java
didizlatkova/Mail-Sender-With-Creational-Patterns
ccb8a281be582df5df3c12d1b180c166c2431ec6
[ "MIT" ]
null
null
null
24.864865
64
0.692935
1,000,220
package abstracts; import java.util.List; import concrete.VendorType; public abstract class VendorConnectionPool { protected static final int MIN_CONNECTION_COUNT = 5; protected static final int MAX_CONNECTION_COUNT = 10; final List<VendorConnection> available; final List<VendorConnection> inUse; final VendorType connectionType; public VendorConnectionPool(List<VendorConnection> available, List<VendorConnection> inUse, VendorType connectionType) { this.available = available; this.inUse = inUse; this.connectionType = connectionType; } public VendorConnection getConnection() throws Exception { synchronized (available) { if (available.size() == 0) { if (inUse.size() < MAX_CONNECTION_COUNT) { this.addConnectionToPool(); System.out.println("Debug: Added new connection to " + this.connectionType + " pool"); } else { System.out.println("Debug: Maximum connections reached in " + this.connectionType + " pool"); } } if (available.size() != 0) { VendorConnection connection = available.get(0); inUse.add(connection); available.remove(0); System.out.println("Debug: Connections left in " + this.connectionType + " pool" + ": " + available.size()); return connection; } else { throw new Exception("No connections available in " + this.connectionType + " pool"); } } } public void releaseConnection(VendorConnection connection) { reset(connection); synchronized (available) { available.add(connection); inUse.remove(connection); System.out .println("Debug: Connections Left in " + this.connectionType + " pool" + ": " + available.size()); } } private void reset(VendorConnection connection) { connection = null; } protected abstract void addConnectionToPool(); }
923d3702a0815a5f58a4b4f9312cfa76a9aa2b17
43,221
java
Java
src/View/arquivo/Cad_prazo.java
barcellosLuizFernando/centralcontabil
b01d24d4d7fbf30adb1af07e5aa41913fa016cbb
[ "MIT" ]
null
null
null
src/View/arquivo/Cad_prazo.java
barcellosLuizFernando/centralcontabil
b01d24d4d7fbf30adb1af07e5aa41913fa016cbb
[ "MIT" ]
null
null
null
src/View/arquivo/Cad_prazo.java
barcellosLuizFernando/centralcontabil
b01d24d4d7fbf30adb1af07e5aa41913fa016cbb
[ "MIT" ]
null
null
null
44.975026
174
0.601698
1,000,221
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package View.arquivo; import conexoes.ConexaoMySQL; import View.TelaInicial; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author luiz.barcellos */ public class Cad_prazo extends javax.swing.JInternalFrame { ConexaoMySQL cn = new ConexaoMySQL(); private int var_consulta; DateFormat dateOut = new SimpleDateFormat("yyyy/MM/dd"); DateFormat dateIn = new SimpleDateFormat("dd/MM/yyyy"); /** * Creates new form Cad_prazo */ public Cad_prazo() { initComponents(); } /** * 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() { jPesquisar = new javax.swing.JFrame(); jPanel3 = new javax.swing.JPanel(); jTxtPesquisa_Multi = new javax.swing.JTextField(); jBtnConfirmar = new javax.swing.JButton(); jBtnCancelar = new javax.swing.JButton(); jScrollPane4 = new javax.swing.JScrollPane(); jTblConsulta_Multi = new javax.swing.JTable(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jTxtIdObrigação = new javax.swing.JTextField(); jTxtNomeObrigacao = new javax.swing.JTextField(); jBtnPesquisaObrigacao = new javax.swing.JButton(); jTxtIdEstabelecimento = new javax.swing.JTextField(); jTxtNomeEmpresa = new javax.swing.JTextField(); jBtnPesquisaEstab = new javax.swing.JButton(); jTxtId = new javax.swing.JTextField(); jBtnPesquisar = new javax.swing.JButton(); jTxtProtocolo = new javax.swing.JTextField(); jSpSolicitacao = new javax.swing.JSpinner(); jSpVencimento = new javax.swing.JSpinner(); jTxtObs = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jTxtId1 = new javax.swing.JTextField(); jBtnPesquisar1 = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jBtnIncluir = new javax.swing.JButton(); jBtnEditar = new javax.swing.JButton(); jBtnGravar = new javax.swing.JButton(); jPesquisar.setTitle("Pesquisar"); jPesquisar.setMinimumSize(new java.awt.Dimension(700, 400)); jTxtPesquisa_Multi.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTxtPesquisa_Multi.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { jTxtPesquisa_MultiKeyReleased(evt); } }); jBtnConfirmar.setText("Adicionar"); jBtnConfirmar.setEnabled(false); jBtnConfirmar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBtnConfirmarActionPerformed(evt); } }); jBtnCancelar.setText("Cancelar"); jBtnCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBtnCancelarActionPerformed(evt); } }); jTblConsulta_Multi.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jTblConsulta_Multi.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jTblConsulta_Multi.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTblConsulta_MultiMouseClicked(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { jTblConsulta_MultiMouseEntered(evt); } }); jScrollPane4.setViewportView(jTblConsulta_Multi); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addGap(0, 453, Short.MAX_VALUE) .addComponent(jBtnCancelar) .addGap(18, 18, 18) .addComponent(jBtnConfirmar)) .addComponent(jTxtPesquisa_Multi) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jTxtPesquisa_Multi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jBtnConfirmar) .addComponent(jBtnCancelar)) .addContainerGap()) ); javax.swing.GroupLayout jPesquisarLayout = new javax.swing.GroupLayout(jPesquisar.getContentPane()); jPesquisar.getContentPane().setLayout(jPesquisarLayout); jPesquisarLayout.setHorizontalGroup( jPesquisarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPesquisarLayout.setVerticalGroup( jPesquisarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); setClosable(true); setTitle("Controle de prazos"); jLabel1.setText("Código"); jLabel2.setText("Obrigação"); jLabel3.setText("Empresa"); jLabel4.setText("Data da Solicitação"); jLabel5.setText("Protocolo"); jLabel6.setText("Vencimento"); jTxtIdObrigação.setEnabled(false); jTxtIdObrigação.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { jTxtIdObrigaçãoFocusLost(evt); } }); jTxtNomeObrigacao.setEnabled(false); jBtnPesquisaObrigacao.setText("..."); jBtnPesquisaObrigacao.setEnabled(false); jBtnPesquisaObrigacao.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBtnPesquisaObrigacaoActionPerformed(evt); } }); jTxtIdEstabelecimento.setEnabled(false); jTxtIdEstabelecimento.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { jTxtIdEstabelecimentoFocusLost(evt); } }); jTxtNomeEmpresa.setEnabled(false); jBtnPesquisaEstab.setText("..."); jBtnPesquisaEstab.setEnabled(false); jBtnPesquisaEstab.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBtnPesquisaEstabActionPerformed(evt); } }); jTxtId.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { jTxtIdFocusLost(evt); } }); jBtnPesquisar.setText("..."); jBtnPesquisar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBtnPesquisarActionPerformed(evt); } }); jTxtProtocolo.setEnabled(false); jSpSolicitacao.setModel(new javax.swing.SpinnerDateModel()); jSpSolicitacao.setEditor(new javax.swing.JSpinner.DateEditor(jSpSolicitacao, "dd/MM/yyyy")); jSpSolicitacao.setEnabled(false); jSpVencimento.setModel(new javax.swing.SpinnerDateModel()); jSpVencimento.setEditor(new javax.swing.JSpinner.DateEditor(jSpVencimento, "dd/MM/yyyy")); jSpVencimento.setEnabled(false); jTxtObs.setEnabled(false); jLabel7.setText("Obs"); jLabel8.setText("Prazo Anterior"); jTxtId1.setEnabled(false); jTxtId1.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { jTxtId1FocusLost(evt); } }); jBtnPesquisar1.setText("..."); jBtnPesquisar1.setEnabled(false); jBtnPesquisar1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBtnPesquisar1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel1)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTxtIdObrigação, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE) .addComponent(jTxtId)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jBtnPesquisar) .addGap(18, 18, 18) .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTxtId1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jBtnPesquisar1) .addGap(354, 354, 354)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel5) .addComponent(jLabel7)) .addGap(22, 22, 22) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jTxtProtocolo) .addGap(18, 18, 18) .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSpVencimento, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jTxtIdEstabelecimento, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jTxtNomeObrigacao, javax.swing.GroupLayout.DEFAULT_SIZE, 273, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jBtnPesquisaObrigacao) .addGap(18, 18, 18) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSpSolicitacao, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jTxtNomeEmpresa) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jBtnPesquisaEstab)))) .addComponent(jTxtObs)))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTxtId1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jBtnPesquisar1)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTxtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jBtnPesquisar) .addComponent(jLabel8))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTxtIdObrigação, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTxtNomeObrigacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jBtnPesquisaObrigacao) .addComponent(jLabel4) .addComponent(jSpSolicitacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTxtIdEstabelecimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTxtNomeEmpresa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jBtnPesquisaEstab)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jLabel6) .addComponent(jTxtProtocolo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jSpVencimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTxtObs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jBtnIncluir.setText("Incluir"); jBtnIncluir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBtnIncluirActionPerformed(evt); } }); jBtnEditar.setText("Editar"); jBtnEditar.setEnabled(false); jBtnEditar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBtnEditarActionPerformed(evt); } }); jBtnGravar.setText("Gravar"); jBtnGravar.setEnabled(false); jBtnGravar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBtnGravarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jBtnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jBtnIncluir, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jBtnGravar, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jBtnIncluir) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jBtnEditar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jBtnGravar) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jBtnIncluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnIncluirActionPerformed if ("Incluir".equals(jBtnIncluir.getText())) { jBtnIncluir.setText("Cancelar"); jTxtId.setText("NOVO"); jBtnEditar.setEnabled(false); habilitarEdicao(); } else { desabilitarEdicao(); limpaCampos(); } }//GEN-LAST:event_jBtnIncluirActionPerformed private void jBtnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnEditarActionPerformed if ("Editar".equals(jBtnEditar.getText())) { jBtnEditar.setText("Cancelar"); habilitarEdicao(); jBtnIncluir.setEnabled(false); } else { desabilitarEdicao(); } }//GEN-LAST:event_jBtnEditarActionPerformed private void jBtnGravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnGravarActionPerformed String id = jTxtId.getText(); String obrigacao = jTxtIdObrigação.getText(); String empresa = jTxtIdEstabelecimento.getText(); String obs = jTxtObs.getText(); String protocolo = jTxtProtocolo.getText(); String dt_sol = dateOut.format(jSpSolicitacao.getValue()); String dt_venc = dateOut.format(jSpVencimento.getValue()); int usuario = TelaInicial.usuariosys; String sql; cn.conecta(); if ("Cancelar".equals(jBtnIncluir.getText())) { cn.executeConsulta("show table status like 'cad_prazos';"); try { while (cn.rs.next()) { id = cn.rs.getString("auto_increment"); } cn.rs.close(); } catch (SQLException ex) { ConexaoMySQL.resultadoUpd = 2; JOptionPane.showMessageDialog(null, "Erro ao consultar o banco de dados: " + ex); } sql = "INSERT INTO cad_prazos (id_obrigacao, id_estabelecimento, " + "protocolo, dt_solicitacao, dt_vencimento, obs, usu_inc, dt_inc) " + "VALUES (" + obrigacao + "," + empresa + ",'" + protocolo + "'," + "'" + dt_sol + "','" + dt_venc + "','" + obs + "'," + usuario + ", current_date());"; } else { sql = "UPDATE cad_prazos set id_obrigacao = " + obrigacao + ", " + "id_estabelecimento = " + empresa + ", " + "protocolo = '" + protocolo + "', dt_solicitacao = '" + dt_sol + "', " + "dt_vencimento = '" + dt_venc + "', obs = '" + obs + "', " + "usu_alt = " + usuario + ", dt_alt = current_date() " + "WHERE id = " + id + "; "; } cn.executeAtualizacao(sql); cn.desconecta(); if (ConexaoMySQL.resultadoUpd < 1) { desabilitarEdicao(); jTxtId.setText(id); } }//GEN-LAST:event_jBtnGravarActionPerformed private void jTxtPesquisa_MultiKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTxtPesquisa_MultiKeyReleased montaLista(); // TODO add your handling code here: }//GEN-LAST:event_jTxtPesquisa_MultiKeyReleased private void jBtnConfirmarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnConfirmarActionPerformed IncluiPesquisa(); jPesquisar.dispose();// TODO add your handling code here: }//GEN-LAST:event_jBtnConfirmarActionPerformed private void jBtnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnCancelarActionPerformed jPesquisar.setVisible(false); // TODO add your handling code here: jPesquisar.dispose(); // TODO add your handling code here: }//GEN-LAST:event_jBtnCancelarActionPerformed private void jTblConsulta_MultiMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTblConsulta_MultiMouseClicked jBtnConfirmar.setEnabled(true); // TODO add your handling code here: }//GEN-LAST:event_jTblConsulta_MultiMouseClicked private void jTblConsulta_MultiMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTblConsulta_MultiMouseEntered // TODO add your handling code here: }//GEN-LAST:event_jTblConsulta_MultiMouseEntered private void jBtnPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnPesquisarActionPerformed var_consulta = 1; jPesquisar.setVisible(true); montaLista(); }//GEN-LAST:event_jBtnPesquisarActionPerformed private void jBtnPesquisaObrigacaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnPesquisaObrigacaoActionPerformed var_consulta = 2; jPesquisar.setVisible(true); montaLista(); }//GEN-LAST:event_jBtnPesquisaObrigacaoActionPerformed private void jBtnPesquisaEstabActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnPesquisaEstabActionPerformed var_consulta = 3; jPesquisar.setVisible(true); montaLista(); }//GEN-LAST:event_jBtnPesquisaEstabActionPerformed private void jTxtIdObrigaçãoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTxtIdObrigaçãoFocusLost jTxtNomeObrigacao.setText(""); if (!"".equals(jTxtIdObrigação.getText())) { var_consulta = 22; IncluiPesquisa(); } }//GEN-LAST:event_jTxtIdObrigaçãoFocusLost private void jTxtIdEstabelecimentoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTxtIdEstabelecimentoFocusLost jTxtNomeEmpresa.setText(""); if (!"".equals(jTxtIdEstabelecimento.getText())) { var_consulta = 33; IncluiPesquisa(); } }//GEN-LAST:event_jTxtIdEstabelecimentoFocusLost private void jTxtIdFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTxtIdFocusLost String id = jTxtId.getText(); limpaCampos(); jTxtId.setText(id); if (!"".equals(jTxtId.getText())) { var_consulta = 11; IncluiPesquisa(); } if (!"".equals(jTxtNomeObrigacao.getText())) { jBtnEditar.setEnabled(true); } else { jBtnEditar.setEnabled(false); } }//GEN-LAST:event_jTxtIdFocusLost private void jTxtId1FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTxtId1FocusLost String id = jTxtId1.getText(); limpaCampos(); jTxtId1.setText(id); if (!"".equals(jTxtId1.getText())) { var_consulta = 44; IncluiPesquisa(); } }//GEN-LAST:event_jTxtId1FocusLost private void jBtnPesquisar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnPesquisar1ActionPerformed var_consulta = 4; jPesquisar.setVisible(true); montaLista(); }//GEN-LAST:event_jBtnPesquisar1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jBtnCancelar; private javax.swing.JButton jBtnConfirmar; private javax.swing.JButton jBtnEditar; private javax.swing.JButton jBtnGravar; private javax.swing.JButton jBtnIncluir; private javax.swing.JButton jBtnPesquisaEstab; private javax.swing.JButton jBtnPesquisaObrigacao; private javax.swing.JButton jBtnPesquisar; private javax.swing.JButton jBtnPesquisar1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JFrame jPesquisar; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JSpinner jSpSolicitacao; private javax.swing.JSpinner jSpVencimento; private javax.swing.JTable jTblConsulta_Multi; private javax.swing.JTextField jTxtId; private javax.swing.JTextField jTxtId1; private javax.swing.JTextField jTxtIdEstabelecimento; private javax.swing.JTextField jTxtIdObrigação; private javax.swing.JTextField jTxtNomeEmpresa; private javax.swing.JTextField jTxtNomeObrigacao; private javax.swing.JTextField jTxtObs; private javax.swing.JTextField jTxtPesquisa_Multi; private javax.swing.JTextField jTxtProtocolo; // End of variables declaration//GEN-END:variables private void habilitarEdicao() { jTxtId.setEnabled(false); jTxtIdObrigação.setEnabled(true); jTxtIdEstabelecimento.setEnabled(true); jTxtProtocolo.setEnabled(true); jTxtObs.setEnabled(true); jTxtId1.setEnabled(true); jSpVencimento.setEnabled(true); jSpSolicitacao.setEnabled(true); jBtnPesquisar.setEnabled(false); jBtnPesquisaEstab.setEnabled(true); jBtnPesquisaObrigacao.setEnabled(true); jBtnPesquisar1.setEnabled(true); jBtnGravar.setEnabled(true); } private void desabilitarEdicao() { jTxtId.setEnabled(true); jTxtIdObrigação.setEnabled(false); jTxtIdEstabelecimento.setEnabled(false); jTxtProtocolo.setEnabled(false); jTxtObs.setEnabled(false); jTxtId1.setEnabled(false); jSpVencimento.setEnabled(false); jSpSolicitacao.setEnabled(false); jBtnPesquisar.setEnabled(true); jBtnPesquisaEstab.setEnabled(false); jBtnPesquisaObrigacao.setEnabled(false); jBtnIncluir.setEnabled(true); jBtnEditar.setEnabled(false); jBtnPesquisar1.setEnabled(false); jBtnGravar.setEnabled(false); jBtnEditar.setText("Editar"); jBtnIncluir.setText("Incluir"); } private void limpaCampos() { jTxtId.setText(""); jTxtId1.setText(""); jTxtIdObrigação.setText(""); jTxtNomeObrigacao.setText(""); jTxtIdEstabelecimento.setText(""); jTxtNomeEmpresa.setText(""); jTxtProtocolo.setText(""); jTxtObs.setText(""); } private void IncluiPesquisa() { int linha = jTblConsulta_Multi.getSelectedRow(); String id; String sql; switch (var_consulta) { case 1: jTxtId.setText(jTblConsulta_Multi.getValueAt(linha, 0).toString()); case 11: id = jTxtId.getText(); sql = "SELECT * FROM cad_prazos WHERE id = " + id; cn.conecta(); cn.executeConsulta(sql); try { while (cn.rs.next()) { String dts = dateIn.format(cn.rs.getObject("dt_solicitacao")); String dtv = dateIn.format(cn.rs.getObject("dt_vencimento")); jTxtIdObrigação.setText(cn.rs.getString("id_obrigacao")); jTxtIdEstabelecimento.setText(cn.rs.getString("id_estabelecimento")); jTxtProtocolo.setText(cn.rs.getString("protocolo")); jTxtObs.setText(cn.rs.getString("obs")); jSpSolicitacao.setValue(dateIn.parse(dts)); jSpVencimento.setValue(dateIn.parse(dtv)); } } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Erro ao consultar o banco de dados: " + ex); } cn.desconecta(); if (!"".equals(jTxtIdEstabelecimento.getText()) && !"".equals(jTxtIdObrigação.getText())) { var_consulta = 22; IncluiPesquisa(); var_consulta = 33; IncluiPesquisa(); } break; case 2: jTxtIdObrigação.setText(jTblConsulta_Multi.getValueAt(linha, 0).toString()); case 22: id = jTxtIdObrigação.getText(); sql = "SELECT * FROM cad_prazos_tipos WHERE id = " + id; cn.conecta(); cn.executeConsulta(sql); try { while (cn.rs.next()) { jTxtNomeObrigacao.setText(cn.rs.getString("descricao")); } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao consultar o banco de dados: " + ex); } cn.desconecta(); break; case 3: jTxtIdEstabelecimento.setText(jTblConsulta_Multi.getValueAt(linha, 0).toString()); case 33: id = jTxtIdEstabelecimento.getText(); sql = "SELECT a.id, a.razao_social, b.nome, a.inscricao_federal " + "FROM cad_estabelecimentos a " + "LEFT JOIN cad_empresas b on (b.id = a.id_empresa) " + "WHERE a.id = " + id; cn.conecta(); cn.executeConsulta(sql); try { while (cn.rs.next()) { jTxtNomeEmpresa.setText(cn.rs.getString("razao_social") + " (" + cn.rs.getString("nome") + ")"); } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao consultar o banco de dados: " + ex); } cn.desconecta(); break; case 4: jTxtId1.setText(jTblConsulta_Multi.getValueAt(linha, 0).toString()); case 44: id = jTxtId1.getText(); sql = "SELECT * FROM cad_prazos WHERE id = " + id; cn.conecta(); cn.executeConsulta(sql); try { while (cn.rs.next()) { jTxtIdObrigação.setText(cn.rs.getString("id_obrigacao")); jTxtIdEstabelecimento.setText(cn.rs.getString("id_estabelecimento")); } } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Erro ao consultar o banco de dados: " + ex); } cn.desconecta(); if (!"".equals(jTxtIdEstabelecimento.getText()) && !"".equals(jTxtIdObrigação.getText())) { var_consulta = 22; IncluiPesquisa(); var_consulta = 33; IncluiPesquisa(); } } } private void montaLista() { DefaultTableModel lista = (DefaultTableModel) jTblConsulta_Multi.getModel(); jTxtPesquisa_Multi.grabFocus(); lista.setColumnCount(0); lista.setRowCount(0); String sql; String id; String condicao; switch (var_consulta) { case 1: lista.addColumn("Id"); lista.addColumn("Obrigação"); lista.addColumn("Protocolo"); lista.addColumn("Empresa"); jTblConsulta_Multi.getColumnModel().getColumn(0).setMaxWidth(60); jTblConsulta_Multi.getColumnModel().getColumn(0).setMinWidth(60); jTblConsulta_Multi.getTableHeader().getColumnModel().getColumn(0).setMaxWidth(60); jTblConsulta_Multi.getTableHeader().getColumnModel().getColumn(0).setMinWidth(60); if (!"".equals(jTxtPesquisa_Multi.getText())) { condicao = "WHERE UPPER(c.razao_social) " + "LIKE '%" + jTxtPesquisa_Multi.getText().toUpperCase() + "%' " + "OR UPPER(a.protocolo) " + "LIKE '%" + jTxtPesquisa_Multi.getText().toUpperCase() + "%' "; } else { condicao = " "; } sql = "SELECT a.id, b.descricao as obrigacao, a.protocolo, c.razao_social " + "FROM cad_prazos A " + "LEFT JOIN cad_prazos_tipos B on (B.id = A.id_obrigacao) " + "LEFT JOIN cad_estabelecimentos C on (C.id = A.id_estabelecimento)" + condicao + " ORDER BY c.razao_social, b.descricao, a.protocolo;"; cn.conecta(); cn.executeConsulta(sql); try { while (cn.rs.next()) { lista.addRow(new String[]{ cn.rs.getString("id"), cn.rs.getString("obrigacao"), cn.rs.getString("protocolo"), cn.rs.getString("razao_social") }); } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao consultar o banco de dados: " + ex); } cn.desconecta(); break; case 2: lista.addColumn("Id"); lista.addColumn("Descrição"); jTblConsulta_Multi.getColumnModel().getColumn(0).setMaxWidth(60); jTblConsulta_Multi.getColumnModel().getColumn(0).setMinWidth(60); jTblConsulta_Multi.getTableHeader().getColumnModel().getColumn(0).setMaxWidth(60); jTblConsulta_Multi.getTableHeader().getColumnModel().getColumn(0).setMinWidth(60); if (!"".equals(jTxtPesquisa_Multi.getText())) { condicao = "WHERE UPPER(descricao) " + "LIKE '%" + jTxtPesquisa_Multi.getText().toUpperCase() + "%'"; } else { condicao = ""; } sql = "SELECT * FROM cad_prazos_tipos " + condicao + " ORDER BY descricao"; cn.conecta(); cn.executeConsulta(sql); try { while (cn.rs.next()) { lista.addRow(new String[]{ cn.rs.getString("id"), cn.rs.getString("descricao"),}); } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao consultar o banco de dados: " + ex); } cn.desconecta(); break; case 3: lista.addColumn("Id"); lista.addColumn("Estabelecimento"); lista.addColumn("Razão Social"); jTblConsulta_Multi.getColumnModel().getColumn(0).setMaxWidth(60); jTblConsulta_Multi.getColumnModel().getColumn(0).setMinWidth(60); jTblConsulta_Multi.getTableHeader().getColumnModel().getColumn(0).setMaxWidth(60); jTblConsulta_Multi.getTableHeader().getColumnModel().getColumn(0).setMinWidth(60); if (!"".equals(jTxtPesquisa_Multi.getText())) { condicao = "WHERE UPPER(razao_social) " + "LIKE '%" + jTxtPesquisa_Multi.getText().toUpperCase() + "%'"; } else { condicao = ""; } sql = "SELECT a.id, a.razao_social, b.nome, a.inscricao_federal " + "FROM cad_estabelecimentos a " + "LEFT JOIN cad_empresas b on (b.id = a.id_empresa) " + condicao + " ORDER BY razao_social"; cn.conecta(); cn.executeConsulta(sql); try { while (cn.rs.next()) { lista.addRow(new String[]{ cn.rs.getString("id"), cn.rs.getString("razao_social"), cn.rs.getString("nome") }); } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao consultar o banco de dados: " + ex); } cn.desconecta(); case 4: var_consulta = 1; montaLista(); var_consulta = 4; } } }
923d37b54ceae2b9caabcccb2b320c9988fa6298
490
java
Java
src/de/quaddy_services/report/TimeAndSubtasks.java
rscadrde/projekt-task-capturing
5af5831f3eef58e017aa76cbbe1740a460590d5f
[ "Apache-2.0" ]
1
2018-06-26T09:05:27.000Z
2018-06-26T09:05:27.000Z
src/de/quaddy_services/report/TimeAndSubtasks.java
rscadrde/projekt-task-capturing
5af5831f3eef58e017aa76cbbe1740a460590d5f
[ "Apache-2.0" ]
12
2015-05-18T14:57:43.000Z
2021-08-30T20:43:59.000Z
src/de/quaddy_services/report/TimeAndSubtasks.java
rscadrde/projekt-task-capturing
5af5831f3eef58e017aa76cbbe1740a460590d5f
[ "Apache-2.0" ]
3
2015-05-18T20:05:04.000Z
2019-06-04T08:01:44.000Z
22.272727
80
0.720408
1,000,222
package de.quaddy_services.report; import java.util.HashMap; import java.util.Map; /** * Sum Tasks with one subtask will be ignored in report because they have * the same time-sum. * * @author Stefan Cordes */ class TimeAndSubtasks { String taskName; String partName; long time; Map<String, TimeAndSubtasks> subtasks = new HashMap<String, TimeAndSubtasks>(); @Override public String toString() { return super.toString()+"\r"+taskName+" ("+partName+")"+subtasks.size(); } }
923d37cca5926f4315545337b43d1bd4fbfb49a4
1,620
java
Java
src/main/java/ga/strikepractice/fights/FightStatistics.java
toppev/StrikePracticeAPI
77cf84bdee1d842a18623547701cd40da9c997ff
[ "MIT" ]
2
2020-02-05T16:59:14.000Z
2021-09-11T17:35:45.000Z
src/main/java/ga/strikepractice/fights/FightStatistics.java
toppev/StrikePracticeAPI
77cf84bdee1d842a18623547701cd40da9c997ff
[ "MIT" ]
4
2020-01-25T22:12:38.000Z
2020-05-05T07:46:47.000Z
src/main/java/ga/strikepractice/fights/FightStatistics.java
toppev/StrikePracticeAPI
77cf84bdee1d842a18623547701cd40da9c997ff
[ "MIT" ]
null
null
null
22.5
78
0.588272
1,000,223
package ga.strikepractice.fights; public class FightStatistics { private int hits; private int currentCombo; private int longestCombo; private int potionsThrow; private int potionsMissed; private double potionIntensities; public int getHits() { return this.hits; } public void setHits(int hits) { this.hits = hits; } public int getCurrentCombo() { return this.currentCombo; } public void setCurrentCombo(int currentCombo) { this.currentCombo = currentCombo; if (currentCombo > this.longestCombo) { this.longestCombo = currentCombo; } } public int getLongestCombo() { return this.longestCombo; } public void setLongestCombo(int longestCombo) { this.longestCombo = longestCombo; } public int getPotionsThrow() { return this.potionsThrow; } public void setPotionsThrow(int potionsThrow) { this.potionsThrow = potionsThrow; } public int getPotionsMissed() { return this.potionsMissed; } public void setPotionsMissed(int potionsMissed) { this.potionsMissed = potionsMissed; } public void addIntensity(double intensity) { this.potionIntensities += intensity; } /** * * @return 0-100 */ public int getAccuracy() { int x = this.potionsThrow; if (x == 0) { return 0; } return (int) Math.round(Math.ceil(this.potionIntensities / x * 100)); } }
923d381a947b6455d5656bd827d83120f9e2b6a8
303
java
Java
TuyaSmartCommercialLightingSdkDemo/app/src/main/java/com/tuya/smart/commercial/lighting/demo/widget/recyclerview/exception/RvAdapterException.java
wangchunlei000/tuya-commerciallighting-sdk
39b3f75aa6d633101c0140f5f8416238b269715d
[ "MIT" ]
2
2021-12-22T07:05:06.000Z
2021-12-23T06:41:38.000Z
TuyaSmartCommercialLightingSdkDemo/app/src/main/java/com/tuya/smart/commercial/lighting/demo/widget/recyclerview/exception/RvAdapterException.java
wangchunlei000/tuya-commerciallighting-sdk
39b3f75aa6d633101c0140f5f8416238b269715d
[ "MIT" ]
null
null
null
TuyaSmartCommercialLightingSdkDemo/app/src/main/java/com/tuya/smart/commercial/lighting/demo/widget/recyclerview/exception/RvAdapterException.java
wangchunlei000/tuya-commerciallighting-sdk
39b3f75aa6d633101c0140f5f8416238b269715d
[ "MIT" ]
3
2021-08-20T02:48:28.000Z
2021-11-17T07:49:55.000Z
25.25
78
0.768977
1,000,224
package com.tuya.smart.commercial.lighting.demo.widget.recyclerview.exception; import android.text.TextUtils; public class RvAdapterException extends RuntimeException { public RvAdapterException(String errMsg) { super(!TextUtils.isEmpty(errMsg) ? errMsg : "RvAdapterException"); } }
923d38602d98a3a3230fd153c9990a7076f9c36a
1,308
java
Java
xworker_app/src/main/java/xworker/app/monitor/res/MessageSender.java
x-meta/xworker
430fba081a78b5d3871669bf6fcb1e952ad258b2
[ "Apache-2.0" ]
2
2015-01-03T18:14:59.000Z
2015-08-05T10:11:21.000Z
xworker_app/src/main/java/xworker/app/monitor/res/MessageSender.java
x-meta/xworker
430fba081a78b5d3871669bf6fcb1e952ad258b2
[ "Apache-2.0" ]
16
2020-05-15T21:54:11.000Z
2021-08-14T06:42:58.000Z
xworker_app/src/main/java/xworker/app/monitor/res/MessageSender.java
x-meta/xworker
430fba081a78b5d3871669bf6fcb1e952ad258b2
[ "Apache-2.0" ]
2
2015-06-24T07:39:35.000Z
2015-08-05T10:11:23.000Z
35.351351
111
0.707187
1,000,225
package xworker.app.monitor.res; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xmeta.Action; import org.xmeta.ActionContext; import org.xmeta.Thing; import org.xmeta.World; import xworker.dataObject.DataObject; public class MessageSender { private static Logger logger = LoggerFactory.getLogger(MessageSender.class); public static void sendMessage(DataObject monitor, String subject, String content){ try{ logger.info("发送监控邮件,监控标识:" + monitor.get("id")); String mailSessionThingStr = monitor.getString("mailSessionThing"); if(mailSessionThingStr != null){ Thing mailSessionThing = World.getInstance().getThing(mailSessionThingStr); long receiveUserGroupId = monitor.getLong("mailReceiveUserGroupId"); if(mailSessionThing != null && receiveUserGroupId != 0){ Action sendMail = World.getInstance().getAction("xworker.app.monitor.MonitorActions/@actions/@SendMail"); ActionContext ac = new ActionContext(); ac.put("sessionThing", mailSessionThing); ac.put("userGroupId", receiveUserGroupId); ac.put("subject", subject); ac.put("content", content); sendMail.run(ac); } } }catch(Exception e){ logger.error("监控发送邮件失败,监控标识:" + monitor.get("id") + ",内容:" + content, e); } } }
923d38b0d390adf424b58f8052ba65fb124024f5
3,434
java
Java
src/test/java/cn/com/myproject/learn/leetcode/editor/cn/NAryTreePreorderTraversal.java
liyang2012/qd
2de66458b83022ffae57980d0faf6467b9ff01f3
[ "Apache-2.0" ]
null
null
null
src/test/java/cn/com/myproject/learn/leetcode/editor/cn/NAryTreePreorderTraversal.java
liyang2012/qd
2de66458b83022ffae57980d0faf6467b9ff01f3
[ "Apache-2.0" ]
2
2021-02-24T17:05:13.000Z
2022-02-09T12:34:52.000Z
src/test/java/cn/com/myproject/learn/leetcode/editor/cn/NAryTreePreorderTraversal.java
liyang2012/qd
2de66458b83022ffae57980d0faf6467b9ff01f3
[ "Apache-2.0" ]
null
null
null
26.21374
80
0.529121
1,000,226
//Given an n-ary tree, return the preorder traversal of its nodes' values. // // Nary-Tree input serialization is represented in their level order traversal, //each group of children is separated by the null value (See examples). // // // // Follow up: // // Recursive solution is trivial, could you do it iteratively? // // // Example 1: // // // // //Input: root = [1,null,3,2,4,null,5,6] //Output: [1,3,5,6,2,4] // // // Example 2: // // // // //Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null //,12,null,13,null,null,14] //Output: [1,2,3,6,7,11,14,4,8,12,5,9,13,10] // // // // Constraints: // // // The height of the n-ary tree is less than or equal to 1000 // The total number of nodes is between [0, 10^4] // // Related Topics 树 package cn.com.myproject.learn.leetcode.editor.cn; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; public class NAryTreePreorderTraversal{ public static void main(String[] args) { Solution solution = new NAryTreePreorderTraversal().new Solution(); Node root = new Node(1); List<Node> children2 = new ArrayList<>(); children2.add(new Node(5)); children2.add(new Node(6)); List<Node> children1 = new ArrayList<>(); Node node = new Node(3); node.children = children2; children1.add(node); children1.add(new Node(2)); children1.add(new Node(4)); root.children = children1; List<Integer> list = solution.preorder(root); System.out.println(list.toString()); } //leetcode submit region begin(Prohibit modification and deletion) /* // Definition for a Node. class Node { public int val; public List<Node> children; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, List<Node> _children) { val = _val; children = _children; } }; */ class Solution { /** * 递归 * @param root * @return */ public List<Integer> preorder1(Node root) { List<Integer> result = new ArrayList<>(); helper(root, result); return result; } private void helper (Node root, List<Integer> result) { if (root == null) { return; } result.add(root.val); if (root.children != null && root.children.size() != 0) { for (Node node : root.children) { helper(node, result); } } } public List<Integer> preorder(Node root) { List<Integer> result = new ArrayList<>(); Deque<Node> deque = new ArrayDeque(); if (root == null) { return result; } deque.offer(root); while (!deque.isEmpty()) { Node d = deque.pollLast(); result.add(d.val); if (d.children != null && d.children.size() != 0) { for (int i = d.children.size() - 1; i >= 0; i--) { deque.offer(d.children.get(i)); } } } return result; } } //leetcode submit region end(Prohibit modification and deletion) }
923d3a36a625b982bf7c8574a31301805d517983
7,112
java
Java
index/src/main/java/org/dbpedia/spotlight/spot/cooccurrence/training/WiktionaryExtractor.java
jodaiber/dbpedia-spotlight-db
f5ee5f1b9bff35c54874a6b2eb09087cb6693d1b
[ "Apache-2.0" ]
2
2015-02-01T18:49:02.000Z
2017-01-30T00:41:56.000Z
index/src/main/java/org/dbpedia/spotlight/spot/cooccurrence/training/WiktionaryExtractor.java
pablomendes/dbpedia-spotlight
a613380d54fd5e611ba372ad40d6cf8839317874
[ "Apache-2.0" ]
6
2020-11-16T20:30:43.000Z
2022-02-01T00:57:40.000Z
index/src/main/java/org/dbpedia/spotlight/spot/cooccurrence/training/WiktionaryExtractor.java
pablomendes/dbpedia-spotlight
a613380d54fd5e611ba372ad40d6cf8839317874
[ "Apache-2.0" ]
1
2015-01-18T13:20:08.000Z
2015-01-18T13:20:08.000Z
28.448
212
0.72216
1,000,227
package org.dbpedia.spotlight.spot.cooccurrence.training; import au.com.bytecode.opencsv.CSVWriter; import org.apache.commons.lang.StringUtils; import org.dbpedia.helper.CoreUtil; import org.openrdf.model.Statement; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.RDFParser; import org.openrdf.rio.helpers.StatementCollector; import org.openrdf.rio.ntriples.NTriplesParserFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Proof-of-concept implementation of an extractor of linguistic knowledge from Wiktionary. * * @author Joachim Daiber */ public class WiktionaryExtractor extends DefaultHandler { private String currentTitle; private CSVWriter csvWriterIdioms; private CSVWriter csvWriterGeneralReference; private int iRead = 0; private StringBuilder contentBuilder = new StringBuilder(); private HashMap<String, Statement> confusables; private static final String WIKI_LANG = "en"; public void setConfusables(List<Statement> confusablesRDF) { this.confusables = new HashMap<String, Statement>(); for(Statement statement : confusablesRDF) { this.confusables.put(statement.getObject().stringValue().replaceFirst("http://en.wiktionary.org/wiki/", ""), statement); } } private enum Tag {title, text}; private Tag currentTag = null; Pattern idiomPattern = Pattern.compile("[\\s]*# (\\{\\{(idiomatic|[^\\}]*)+\\}\\}).*[\\s]*", Pattern.MULTILINE); public WiktionaryExtractor(CSVWriter csvWriterIdiom, CSVWriter csvWriterGeneralReference) { super(); this.csvWriterIdioms = csvWriterIdiom; this.csvWriterGeneralReference = csvWriterGeneralReference; } public void startDocument (){ iRead++; if(iRead % 10 == 0) System.err.println("Read " + iRead + " documents."); } public void startElement (String uri, String name, String qName, Attributes atts) { if(name.equals("title")) currentTag = Tag.title; else if(name.equals("text")) currentTag = Tag.text; else currentTag = null; } public void endElement (String uri, String name, String qName) { if(name.equals("text")){ boolean properNoun = false; boolean commonNoun = false; List<String> wikipediaParts = new LinkedList<String>(); for(String line : contentBuilder.toString().split("\\r?\\n")) { if(line.contains("=Noun=")) { commonNoun = true; }else if(line.contains("=Proper noun=")) { properNoun = true; } if(line.contains("{{wikipedia")) { wikipediaParts = extractTemplate(line); for(String wikipediaPart : wikipediaParts){ if(wikipediaPart.startsWith("lang=") && !wikipediaPart.equals("lang=" + WIKI_LANG)){ /** * We only want links to the Wikipedia of the current language. */ wikipediaParts.clear(); break; } } } if(line.contains("{{idiomatic") || line.contains("|idiomatic")){ Matcher m = idiomPattern.matcher(line); if(m.matches()) writeIdiom(m); } } if(commonNoun && !properNoun && (wikipediaParts.size() > 0 || confusables.containsKey(currentTitle))) { String dbpediaResource; if(confusables.containsKey(currentTitle)) { dbpediaResource = confusables.get(currentTitle).getSubject().stringValue(); }else{ String wikiLink = null; for(String wikipediaPart : wikipediaParts) { if(!wikipediaPart.equals("wikipedia") && !wikipediaPart.contains("=")) { wikiLink = wikipediaPart; break; } } if(wikiLink == null) dbpediaResource = "http://dbpedia.org/resource/" + wikipediaEncode(currentTitle); else dbpediaResource = "http://dbpedia.org/resource/" + wikipediaEncode(wikiLink); } writeGeneralReference(dbpediaResource); } contentBuilder = new StringBuilder(); } } private String wikipediaEncode(String wikiLink) { String link = CoreUtil.wikipediaEncode(wikiLink); return link.substring(0,1).toUpperCase() + link.substring(1); } private String l1 = null; public void characters(char[] ch, int start, int end) throws SAXException { if(currentTag == null) return; if(currentTag == Tag.title) { String s = new String(ch, start, end); currentTitle = s; currentTag = null; //Only read first line, next line will be whitespace }else if(currentTag == Tag.text){ String s = new String(ch, start, end); contentBuilder.append(s); } } private void writeIdiom(Matcher m) { try{ List<String> types = extractTemplate(m.group(1)); types.remove("idiomatic"); csvWriterIdioms.writeNext(new String[]{currentTitle, "idiomatic", StringUtils.join(types, ",")}); }catch (IllegalStateException e) { System.out.println(m.group(0)); } } private void writeGeneralReference(String uri) { csvWriterGeneralReference.writeNext(new String[]{uri}); } private List<String> extractTemplate(String template) { return new LinkedList<String>(Arrays.asList(template.replaceAll(".*\\{\\{", "").replaceAll("\\}\\}.*", "").split("\\|"))); } public void close() throws IOException { csvWriterGeneralReference.close(); csvWriterIdioms.close(); } public static void main(String[] args) throws SAXException, IOException, RDFHandlerException, RDFParseException { // NTriplesParser nTriplesParser = new NTriplesParser(); // nTriplesParser.parse(new FileReader(new File("/Users/jodaiber/Documents/workspace/ba/BachelorThesis/02 Implementation/DBPedia Spotlight data/confusables_with_wiktionary.nt")), "http://dbpedia.org/property/"); XMLReader xmlReader = XMLReaderFactory.createXMLReader(); WiktionaryExtractor wiktionaryExtractor = new WiktionaryExtractor( new CSVWriter(new FileWriter(new File("/Users/jodaiber/Desktop/idioms.csv"))), new CSVWriter(new FileWriter(new File("/Users/jodaiber/Desktop/generalReference.csv"))) ); List<Statement> confusables = new LinkedList<Statement>(); StatementCollector inputCollector = new StatementCollector(confusables); NTriplesParserFactory nTriplesParserFactory = new NTriplesParserFactory(); RDFParser parser = nTriplesParserFactory.getParser(); parser.setRDFHandler(inputCollector); parser.parse(new FileReader(new File("/Users/jodaiber/Documents/workspace/ba/BachelorThesis/01 Evaluation/03 Training/Training Set/data/confusables_with_wiktionary.nt")), ""); wiktionaryExtractor.setConfusables(confusables); xmlReader.setContentHandler(wiktionaryExtractor); InputSource inputSource = new InputSource(new FileReader(new File("/Users/jodaiber/Desktop/wiktionary-parser/enwiktionary-20110512-pages-articles.xml"))); xmlReader.parse(inputSource); wiktionaryExtractor.close(); } }
923d3a92c9cd4f2872aed38dc6ae2053e19e58fa
828
java
Java
aTalk/src/main/java/org/atalk/service/fileaccess/FileCategory.java
FihlaTV/atalk-android
cd3069568236ab593f4001a9c2b4649b7504eace
[ "Apache-2.0" ]
120
2018-01-07T12:31:45.000Z
2022-03-30T13:36:58.000Z
aTalk/src/main/java/org/atalk/service/fileaccess/FileCategory.java
FihlaTV/atalk-android
cd3069568236ab593f4001a9c2b4649b7504eace
[ "Apache-2.0" ]
176
2018-02-10T18:04:04.000Z
2022-03-07T05:02:35.000Z
aTalk/src/main/java/org/atalk/service/fileaccess/FileCategory.java
FihlaTV/atalk-android
cd3069568236ab593f4001a9c2b4649b7504eace
[ "Apache-2.0" ]
72
2018-01-07T12:23:37.000Z
2022-03-30T04:53:50.000Z
25.875
106
0.727053
1,000,228
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. See terms of license at gnu.org. */ package org.atalk.service.fileaccess; /** * High-level classification for files or directories created by Jitsi. * * @author Ingo Bauersachs */ public enum FileCategory { /** * For files or directories that contain configuration data or similar data that belongs to a * specific user, but might non-simultaneously be shared across different computers or operating systems. */ PROFILE, /** * For files or directories that contain cached data. It must be safe to delete these files at any time. */ CACHE, /** * For files or directories that contain log data that is bound to a specific user and * computer. This is NOT for history related data. */ LOG }
923d3b192b125dfc27fbcbd5f20620b95a992225
1,819
java
Java
src/main/java/com/platformnexus/retry/kafka/KafkaPublisherImpl.java
felixchiu/Advanced-Retry-Library
201e927be666c0322aa250bb5bfb128b78b6ddb3
[ "Apache-2.0" ]
null
null
null
src/main/java/com/platformnexus/retry/kafka/KafkaPublisherImpl.java
felixchiu/Advanced-Retry-Library
201e927be666c0322aa250bb5bfb128b78b6ddb3
[ "Apache-2.0" ]
null
null
null
src/main/java/com/platformnexus/retry/kafka/KafkaPublisherImpl.java
felixchiu/Advanced-Retry-Library
201e927be666c0322aa250bb5bfb128b78b6ddb3
[ "Apache-2.0" ]
null
null
null
36.38
107
0.769104
1,000,229
package com.platformnexus.retry.kafka; import com.platformnexus.retry.exception.ScheduleRetryException; import com.platformnexus.retry.kafka.config.KafkaConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.header.internals.RecordHeaders; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.stereotype.Component; import java.util.UUID; import java.util.concurrent.TimeUnit; @Component public class KafkaPublisherImpl implements KafkaPublisher { private static final Logger LOGGER = LoggerFactory.getLogger(KafkaPublisherImpl.class); private final KafkaConfig kafkaConfig; private final KafkaTemplate<String, String> kafkaTemplate; public KafkaPublisherImpl(KafkaConfig kafkaConfig, KafkaTemplate<String, String> kafkaTemplate) { this.kafkaConfig = kafkaConfig; this.kafkaTemplate = kafkaTemplate; } @Override public void publish(String value, String topicName, RecordMetadata metadata) { doPublish(topicName, value, metadata); } private void doPublish(String topic, String messageBody, RecordMetadata metadata) { String id = UUID.randomUUID().toString(); final ProducerRecord<String, String> record = new ProducerRecord<>(topic, id, messageBody); RecordHeaders headers = metadata.toRecordHeaders(); headers.forEach(header -> record.headers().add(header)); try { LOGGER.debug("Sending message [id={} ] on topic={}", id, topic); kafkaTemplate.send(record).get(kafkaConfig.getProducer().getTimeOutMilliSeconds(), TimeUnit.SECONDS); } catch (Exception e) { String message = String.format("Could not publish a message id=%s on topic=%s", id, topic); throw new ScheduleRetryException(message, e); } } }
923d3b4b88a1c247043549aac23c36485ea01609
25,291
java
Java
src/main/java/pjq/commons/utils/DateTimeUtils.java
qqxadyy/pjq-commons-utils
95f0df2e734feb65834d5fa8bba597d7d3ee55de
[ "MIT" ]
null
null
null
src/main/java/pjq/commons/utils/DateTimeUtils.java
qqxadyy/pjq-commons-utils
95f0df2e734feb65834d5fa8bba597d7d3ee55de
[ "MIT" ]
null
null
null
src/main/java/pjq/commons/utils/DateTimeUtils.java
qqxadyy/pjq-commons-utils
95f0df2e734feb65834d5fa8bba597d7d3ee55de
[ "MIT" ]
null
null
null
29.649472
118
0.59539
1,000,230
/* * Copyright © 2021 pengjianqiang * All rights reserved. * 项目名称:pjq-commons-utils * 项目描述:pjq-commons-utils * 项目地址:https://github.com/qqxadyy/pjq-commons-utils * 许可证信息:见下文 * * ====================================================================== * * The MIT License * Copyright © 2021 pengjianqiang * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package pjq.commons.utils; import java.text.SimpleDateFormat; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.MonthDay; import java.time.Period; import java.time.Year; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalAccessor; import java.util.Date; import java.util.Optional; import lombok.AccessLevel; import lombok.NoArgsConstructor; import pjq.commons.constant.DateTimePattern; import pjq.commons.utils.reflect.MethodUtils; /** * <p> * 使用java.time实现的日期时间工具类 * <p> * Create at 2018年11月15日 * * @author pengjianqiang */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class DateTimeUtils { private static final String startTime = " 00:00:00"; private static final String endTime = " 23:59:59"; private static ZoneId defaultZone = ZoneId.systemDefault(); public static Date localDateToDate(LocalDate date) { return temporalAccessorToDate(date); } public static Date localDateTimeToDate(LocalDateTime dateTime) { return temporalAccessorToDate(dateTime); } public static LocalDate localDateTimeToLocalDate(LocalDateTime dateTime) { return dateTime.toLocalDate(); } private static Date temporalAccessorToDate(TemporalAccessor temporal) { Class<?> clazz = temporal.getClass(); if (LocalDate.class.isAssignableFrom(clazz)) { return Date.from(((LocalDate)temporal).atStartOfDay(defaultZone).toInstant()); } else if (LocalDateTime.class.isAssignableFrom(clazz)) { return Date.from(((LocalDateTime)temporal).atZone(defaultZone).toInstant()); } else { throw new RuntimeException("暂不支持".concat(clazz.getName()).concat("转换为").concat(Date.class.getName())); } } public static LocalDateTime dateToLocalDateTime(Date date) { return (LocalDateTime)dateToTemporalAccessor(date, LocalDateTime.class); } public static LocalDate dateToLocalDate(Date date) { return (LocalDate)dateToTemporalAccessor(date, LocalDate.class); } private static TemporalAccessor dateToTemporalAccessor(Date date, Class<? extends TemporalAccessor> clazz) { CheckUtils.checkNotNull(date, "需要转换的日期对象不能为空"); if (LocalDate.class.isAssignableFrom(clazz)) { return LocalDateTime.ofInstant(date.toInstant(), defaultZone).toLocalDate(); } else if (LocalDateTime.class.isAssignableFrom(clazz)) { return LocalDateTime.ofInstant(date.toInstant(), defaultZone).withNano(0); } else { throw new RuntimeException("暂不支持".concat(Date.class.getName()).concat("转换为").concat(clazz.getName())); } } /** * 把yyyy-MM-dd格式的日期字符串转成{@link Date}对象 * * @param dateStr * @return */ public static Date parseDate(String dateStr) { return parseDate(dateStr, DateTimePattern.PATTERN_DEFAULT); } /** * 把指定格式的日期字符串转成{@link Date}对象 * * @param dateStr * @param pattern * @return */ public static Date parseDate(String dateStr, DateTimePattern pattern) { return parseDate(dateStr, pattern.value()); } /** * 把指定格式的日期字符串转成{@link Date}对象 * * @param dateStr * @param pattern * @return */ public static Date parseDate(String dateStr, String pattern) { DateTimeFormatter formatter = ofPattern(pattern); return temporalAccessorToDate(DateTimePattern.isDatePattern(pattern) ? LocalDate.parse(dateStr, formatter) : LocalDateTime.parse(dateStr, formatter)); } /** * 把yyyy-MM-dd格式的日期字符串转成{@link LocalDate}对象 * * @param dateStr * @return */ public static LocalDate parseLocalDate(String dateStr) { return parseLocalDate(dateStr, DateTimePattern.PATTERN_DEFAULT); } /** * 把指定格式的日期字符串转成{@link LocalDate}对象 * * @param dateStr * @param pattern * @return */ public static LocalDate parseLocalDate(String dateStr, DateTimePattern pattern) { return parseLocalDate(dateStr, pattern.value()); } /** * 把指定格式的日期字符串转成{@link LocalDate}对象 * * @param dateStr * @param pattern * @return */ public static LocalDate parseLocalDate(String dateStr, String pattern) { DateTimeFormatter formatter = ofPattern(pattern); return DateTimePattern.isDatePattern(pattern) ? LocalDate.parse(dateStr, formatter) : LocalDateTime.parse(dateStr, formatter).toLocalDate(); } /** * 把yyyy-MM-dd HH:mm:ss格式的日期字符串转成{@link LocalDateTime}对象 * * @param dateStr * @return */ public static LocalDateTime parseLocalDateTime(String dateStr) { return parseLocalDateTime(dateStr, DateTimePattern.PATTERN_DATETIME); } /** * 把指定格式的日期字符串转成{@link LocalDateTime}对象 * * @param dateStr * @param pattern * @return */ public static LocalDateTime parseLocalDateTime(String dateStr, DateTimePattern pattern) { return parseLocalDateTime(dateStr, pattern.value()); } /** * 把指定格式的日期字符串转成{@link LocalDateTime}对象 * * @param dateStr * @param pattern * @return */ public static LocalDateTime parseLocalDateTime(String dateStr, String pattern) { DateTimeFormatter formatter = ofPattern(pattern); LocalDateTime isoDateTime = parseISOLocalDateTime(dateStr); return Optional.ofNullable(isoDateTime).orElseGet(() -> LocalDateTime.parse(dateStr, formatter)); } /** * 通用日期时间格式化,用于直接指定pattern<br/> * 其它parse方法都限定成使用较多的pattern才能使用,而该方法可直接指定不常用的pattern,但是必须根据date的类型指定可用的pattern * * @param dateStr * @param pattern * @param dateClass * {@link Date}、{@link LocalDate}、{@link LocalDate}、{@link LocalTime}的Class对象 * @return */ @SuppressWarnings("unchecked") public static <R> R commonParse(String dateStr, String pattern, Class<R> dateClass) { DateTimeFormatter formatter = ofPattern(pattern); if (Date.class.isAssignableFrom(dateClass)) { try { return (R)new SimpleDateFormat(pattern).parse(dateStr); } catch (Exception e) { throw new RuntimeException(dateStr.concat("转换为").concat(Date.class.getName()).concat("失败")); } } else if (LocalDate.class.isAssignableFrom(dateClass)) { return (R)LocalDate.parse(dateStr, formatter); } else if (LocalDateTime.class.isAssignableFrom(dateClass)) { return (R)parseLocalDateTime(dateStr, pattern); } else if (LocalTime.class.isAssignableFrom(dateClass)) { return (R)LocalTime.parse(dateStr, formatter); } else { throw new RuntimeException("不支持类".concat(dateClass.getClass().getName()).concat("的日期时间转换")); } } /** * 通用日期时间格式化,用于直接指定pattern<br/> * 其它parse方法都限定成使用较多的pattern才能使用,而该方法可直接指定不常用的pattern,但是必须根据date的类型指定可用的pattern * * @param <R> * @param dateStr * @param formatter * @param dateClass * @return */ @SuppressWarnings("unchecked") public static <R> R commonParse(String dateStr, DateTimeFormatter formatter, Class<R> dateClass) { if (Date.class.isAssignableFrom(dateClass)) { try { return (R)localDateTimeToDate(LocalDateTime.parse(dateStr, formatter)); } catch (Exception e) { throw new RuntimeException(dateStr.concat("转换为").concat(Date.class.getName()).concat("失败")); } } else if (LocalDate.class.isAssignableFrom(dateClass)) { return (R)LocalDate.parse(dateStr, formatter); } else if (LocalDateTime.class.isAssignableFrom(dateClass)) { return (R)LocalDateTime.parse(dateStr, formatter); } else if (LocalTime.class.isAssignableFrom(dateClass)) { return (R)LocalTime.parse(dateStr, formatter); } else { throw new RuntimeException("不支持类".concat(dateClass.getClass().getName()).concat("的日期时间转换")); } } /** * JavaScript生成JSON字符串时,Date对象为(UTC/ISO instant,'yyyy-MM-ddTHH:mm:ss.SSSZ')格式,需要特殊处理 * * @param dateStr * @return */ private static LocalDateTime parseISOLocalDateTime(String dateStr) { LocalDateTime dateTime = null; try { if (CheckUtils.isEmpty(dateStr)) { return dateTime; } if (dateStr.length() > 10 && (dateStr.charAt(10) == 'T' || dateStr.charAt(10) == 't')) { if (dateStr.endsWith("Z") || dateStr.endsWith("z")) { return LocalDateTime.ofInstant(Instant.parse(dateStr), ZoneOffset.UTC); } else { return LocalDateTime.parse(dateStr, DateTimeFormatter.ISO_LOCAL_DATE_TIME); } } } catch (Exception e) { } return dateTime; } /** * 把{@link Date}对象转成yyyy-MM-dd格式的日期字符串 * * @param date * @return */ public static String format(Date date) { return format(date, DateTimePattern.PATTERN_DEFAULT); } /** * 把{@link Date}对象转成指定格式的日期字符串 * * @param dateStr * @param pattern * @return */ public static String format(Date date, DateTimePattern pattern) { return format(date, pattern.value()); } /** * 把{@link Date}对象转成指定格式的日期字符串 * * @param dateStr * @param pattern * @return */ public static String format(Date date, String pattern) { return java8TimeCommonFormat(dateToTemporalAccessor(date, DateTimePattern.isDatePattern(pattern) ? LocalDate.class : LocalDateTime.class), pattern); } /** * 把{@link java.time.LocalDate}对象转成yyyy-MM-dd格式的日期字符串 * * @param date * @return */ public static String format(LocalDate date) { return format(date, DateTimePattern.PATTERN_DEFAULT); } /** * 把{@link java.time.LocalDateTime}对象转成yyyy-MM-dd格式的日期字符串 * * @param date * @return */ public static String format(LocalDateTime dateTime) { return format(dateTime, DateTimePattern.PATTERN_DEFAULT); } /** * 把{@link java.time.LocalDate}对象转成指定格式的日期字符串 * * @param date * @param pattern * @return */ public static String format(LocalDate date, DateTimePattern pattern) { return format(date, pattern.value()); } /** * 把{@link java.time.LocalDate}对象转成指定格式的日期字符串 * * @param date * @param pattern * @return */ public static String format(LocalDate date, String pattern) { return format(localDateToDateTime(date), pattern); } /** * 把{@link java.time.LocalDateTime}对象转成指定格式的日期字符串 * * @param dateTime * @param pattern * @return */ public static String format(LocalDateTime dateTime, DateTimePattern pattern) { return format(dateTime, pattern.value()); } /** * 把{@link java.time.LocalDateTime}对象转成指定格式的日期字符串 * * @param dateTime * @param pattern * @return */ public static String format(LocalDateTime dateTime, String pattern) { return java8TimeCommonFormat(DateTimePattern.isDatePattern(pattern) ? dateTime.toLocalDate() : dateTime, pattern); } /** * 通用日期时间格式化,用于直接指定pattern<br/> * 其它format方法都限定成使用较多的pattern才能使用,而该方法可直接指定不常用的pattern,但是必须根据date的类型指定可用的pattern * * @param date * {@link Date}、{@link LocalDate}、{@link LocalDate}、{@link LocalTime}对象 * @param pattern * @return */ public static <T> String commonFormat(T date, String pattern) { if (date instanceof Date) { return java8TimeCommonFormat(dateToLocalDateTime(Date.class.cast(date)), pattern); } else if (date instanceof TemporalAccessor) { return java8TimeCommonFormat(TemporalAccessor.class.cast(date), pattern); } else { throw new RuntimeException("不支持类".concat(date.getClass().getName()).concat("的日期时间格式化")); } } private static String java8TimeCommonFormat(TemporalAccessor temporal, String pattern) { return ofPattern(pattern).format(temporal); } private static DateTimeFormatter ofPattern(String pattern) { return DateTimeFormatter.ofPattern(pattern); } private static LocalDateTime localDateToDateTime(LocalDate date) { return date.atTime(0, 0, 0, 0); } /** * 获取当前日期时间对象 * * @return */ public static Date currentDateObj() { return localDateTimeToDate(LocalDateTime.now()); } /** * 获取当前日期对象 * * @return */ public static LocalDate currentDate() { return LocalDate.now(); } /** * 获取当前日期时间对象 * * @return */ public static LocalDateTime currentDateTime() { return LocalDateTime.now(); } /** * 获取当前日期,格式为yyyy-MM-dd的字符串 * * @return */ public static String currentDateStr() { return format(LocalDate.now(), DateTimePattern.PATTERN_DEFAULT); } /** * 获取当前日期,格式为yyyyMMdd的字符串 * * @return */ public static String currentDateCompactStr() { return format(LocalDate.now(), DateTimePattern.PATTERN_DATE_COMPACT); } /** * 获取当前时间,格式为yyyy-MM-dd HH:mm:ss的字符串 * * @return */ public static String currentDateTimeStr() { return format(LocalDateTime.now(), DateTimePattern.PATTERN_DATETIME); } /** * 获取当前时间,格式为yyyyMMddHHmmss的字符串 * * @return */ public static String currentDateTimeCompactStr() { return format(LocalDateTime.now(), DateTimePattern.PATTERN_DATETIME_COMPACT); } /** * 获取当前年份 * * @return */ public static int currentYear() { return Year.now().getValue(); } /** * 获取当前月份 * * @return */ public static int currentMonth() { return MonthDay.now().getMonthValue(); } /** * 获取当前日期 * * @return */ public static int currentDay() { return MonthDay.now().getDayOfMonth(); } /** * 获取当前年月,格式为yyyyMM的字符串 * * @return */ public static String currentYearMonth() { return format(LocalDate.now(), DateTimePattern.PATTERN_YEARMONTH); } /** * 获取两个时间相差的天数 * * @param d1 * @param d2 * @return */ public static int durationDays(Date d1, Date d2) { return durationDays(dateToLocalDate(d1), dateToLocalDate(d2)); } /** * 获取两个时间相差的天数 * * @param d1 * @param d2 * @return */ public static int durationDays(LocalDateTime d1, LocalDateTime d2) { return durationDays(d1.toLocalDate(), d2.toLocalDate()); } /** * 获取两个日期相差的天数 * * @param d1 * @param d2 * @return */ public static int durationDays(LocalDate d1, LocalDate d2) { if (d1.isAfter(d2)) { return Period.between(d2, d1).getDays(); } else { return Period.between(d1, d2).getDays(); } } /** * 获取两个时间相差的秒数 * * @param d1 * @param d2 * @return */ public static long durationSeconds(Date d1, Date d2) { return durationSeconds(dateToLocalDateTime(d1), dateToLocalDateTime(d2)); } /** * 获取两个日期相差的秒数 * * @param d1 * @param d2 * @return */ public static long durationSeconds(LocalDate d1, LocalDate d2) { return durationSeconds(localDateToDateTime(d1), localDateToDateTime(d2)); } /** * 获取两个时间相差的秒数 * * @param d1 * @param d2 * @return */ public static long durationSeconds(LocalDateTime d1, LocalDateTime d2) { if (d1.isAfter(d2)) { return Duration.between(d2, d1).getSeconds(); } else { return Duration.between(d1, d2).getSeconds(); } } /** * 根据日期得到当天开始时间的字符串,格式为yyyy-MM-dd HH:mm:ss * * @param date * @return */ public static String getDayStart(Date date) { return format(date).concat(startTime); } /** * 根据日期得到当天开始时间的字符串,格式为yyyy-MM-dd HH:mm:ss * * @param date * @return */ public static String getDayStart(LocalDate date) { return format(date).concat(startTime); } /** * 根据日期得到当天开始时间的字符串,格式为yyyy-MM-dd HH:mm:ss * * @param dateTime * @return */ public static String getDayStart(LocalDateTime dateTime) { return format(dateTime).concat(startTime); } /** * 根据日期得到当天开始时间的字符串,格式为yyyy-MM-dd HH:mm:ss,并转为对应的日期时间对象 * * @param date * @param dateClass * @return */ public static <T, R> R getDayStart(T date, Class<R> dateClass) { return getDayStartOrEnd(date, dateClass, "getDayStart"); } /** * 根据日期得到当天结束时间的字符串,格式为yyyy-MM-dd HH:mm:ss * * @param date * @return */ public static String getDayEnd(Date date) { return format(date).concat(endTime); } /** * 根据日期得到当天结束时间的字符串,格式为yyyy-MM-dd HH:mm:ss * * @param date * @return */ public static String getDayEnd(LocalDate date) { return format(date).concat(endTime); } /** * 根据日期得到当天结束时间的字符串,格式为yyyy-MM-dd HH:mm:ss * * @param dateTime * @return */ public static String getDayEnd(LocalDateTime dateTime) { return format(dateTime).concat(endTime); } /** * 根据日期得到当天结束时间的字符串,格式为yyyy-MM-dd HH:mm:ss,并转为对应的日期时间对象 * * @param date * @param dateClass * @return */ public static <T, R> R getDayEnd(T date, Class<R> dateClass) { return getDayStartOrEnd(date, dateClass, "getDayEnd"); } private static <T, R> R getDayStartOrEnd(T date, Class<R> dateClass, String methodName) { try { String dateStr = (String)MethodUtils.invokeStaticOrDefault(DateTimeUtils.class, DateTimeUtils.class.getMethod(methodName, date.getClass()), date); return commonParse(dateStr, DateTimePattern.PATTERN_DATETIME.value(), dateClass); } catch (Throwable e) { throw new RuntimeException(e); } } /** * 日期相加/减<br/> * * @param dateTime * @param amountToAdd * 传入负值可实现相减 * @param unit * 只支持年(YEARS)、月(MONTHS)、日(DAYS)、时(HOURS)、分(MINUTES)、秒(SECONDS) * @return */ public static Date plus(Date date, long amountToAdd, ChronoUnit unit) { return localDateTimeToDate(plus(dateToLocalDateTime(date), amountToAdd, unit)); } /** * 日期相加/减<br/> * (实际相当于00:00:00的日期做时间相加减,然后返回缺少时分秒信息的日期对象) * * @param dateTime * @param amountToAdd * 传入负值可实现相减 * @param unit * 只支持年(YEARS)、月(MONTHS)、日(DAYS)、时(HOURS)、分(MINUTES)、秒(SECONDS) * @return */ public static LocalDate plus(LocalDate date, long amountToAdd, ChronoUnit unit) { return plus(localDateToDateTime(date), amountToAdd, unit).toLocalDate(); } /** * 时间相加/减 * * @param dateTime * @param amountToAdd * 传入负值可实现相减 * @param unit * 只支持年(YEARS)、月(MONTHS)、日(DAYS)、时(HOURS)、分(MINUTES)、秒(SECONDS) * @return */ public static LocalDateTime plus(LocalDateTime dateTime, long amountToAdd, ChronoUnit unit) { dateTime = dateTime.withNano(0); switch (unit) { case SECONDS: return dateTime.plusSeconds(amountToAdd); case MINUTES: return dateTime.plusMinutes(amountToAdd); case HOURS: return dateTime.plusHours(amountToAdd); case DAYS: return dateTime.plusDays(amountToAdd); case MONTHS: return dateTime.plusMonths(amountToAdd); case YEARS: return dateTime.plusYears(amountToAdd); default: throw new RuntimeException("只支持年(YEARS)、月(MONTHS)、日(DAYS)、时(HOURS)、分(MINUTES)、秒(SECONDS)这几个单位的日期计算"); } } /** * 获取日期月份的第一天 * * @param date * @return */ public static Date firstDayOfMonth(Date date) { return localDateTimeToDate(firstDayOfMonth(dateToLocalDateTime(date))); } /** * 获取日期月份的第一天 * * @param date * @return */ public static LocalDate firstDayOfMonth(LocalDate date) { return firstDayOfMonth(localDateToDateTime(date)).toLocalDate(); } /** * 获取日期月份的第一天 * * @param dateTime * @return */ public static LocalDateTime firstDayOfMonth(LocalDateTime dateTime) { // 当前日期-(当前日期的天)+(1天),再带上日期开始的时分秒信息 return plus(dateTime, -1 * dateTime.getDayOfMonth() + 1, ChronoUnit.DAYS) .with(LocalTime.parse(startTime, ofPattern(" HH:mm:ss"))); } /** * 获取日期月份的最后一天 * * @param date * @return */ public static Date lastDayOfMonth(Date date) { return localDateTimeToDate(lastDayOfMonth(dateToLocalDateTime(date))); } /** * 获取日期月份的最后一天 * * @param date * @return */ public static LocalDate lastDayOfMonth(LocalDate date) { return lastDayOfMonth(localDateToDateTime(date)).toLocalDate(); } /** * 获取日期月份的最后一天 * * @param dateTime * @return */ public static LocalDateTime lastDayOfMonth(LocalDateTime dateTime) { // 当前日期+(1月)-(当前日期的天),再带上日期结束的时分秒信息 return plus(plus(dateTime, 1, ChronoUnit.MONTHS), -1 * dateTime.getDayOfMonth(), ChronoUnit.DAYS) .with(LocalTime.parse(endTime, ofPattern(" HH:mm:ss"))); } /** * 获取UTC时间戳,单位秒 * * @param dateTime * @return */ public static long getUTCSeconds(LocalDateTime dateTime) { return dateTime.toEpochSecond(ZoneOffset.UTC); } /** * 获取UTC时间戳,单位毫秒 * * @param dateTime * @return */ public static long getUTCMillSeconds(LocalDateTime dateTime) { return dateTime.toInstant(ZoneOffset.UTC).toEpochMilli(); } /** * 时间戳转换为LocalDateTime(时区为UTC+8) * * @param timeMillis * @return */ public static LocalDateTime timestampToLocalDateTime(long timeMillis) { return Instant.ofEpochMilli(timeMillis).atZone(ZoneOffset.ofHours(8)).toLocalDateTime(); } /** * 时间戳转换为Date(时区为UTC+8) * * @param timeMillis * @return */ public static Date timestampToDate(long timeMillis) { return localDateTimeToDate(timestampToLocalDateTime(timeMillis)); } }
923d3c0ecd075e0336c48bb93fe1ece1762bceb3
139
java
Java
src/test/java/io/github/vlsergey/springdatarestutils/withenum/TestEnum.java
vlsergey/spring-data-rest-utils
eb109367f8dea9eae8a2b8951ab5942a90a0ea2a
[ "MIT" ]
1
2022-01-12T14:12:17.000Z
2022-01-12T14:12:17.000Z
src/test/java/io/github/vlsergey/springdatarestutils/withenum/TestEnum.java
vlsergey/spring-data-rest-utils
eb109367f8dea9eae8a2b8951ab5942a90a0ea2a
[ "MIT" ]
5
2021-05-31T13:48:33.000Z
2021-08-30T18:32:20.000Z
src/test/java/io/github/vlsergey/springdatarestutils/withenum/TestEnum.java
vlsergey/spring-data-rest-utils
eb109367f8dea9eae8a2b8951ab5942a90a0ea2a
[ "MIT" ]
1
2022-01-12T14:04:21.000Z
2022-01-12T14:04:21.000Z
11.583333
56
0.733813
1,000,231
package io.github.vlsergey.springdatarestutils.withenum; public enum TestEnum { TEST_ENUM_VALUE_A, TEST_ENUM_VALUE_B, ; }
923d3c3a25648c5fde4572a2b9d828a85679478d
1,580
java
Java
src/simpleserver/command/AreaSayCommand.java
mildfuzz/SimpleServer
62e4bb24af1b69b62afc7010075eca93eb793a41
[ "MIT" ]
39
2015-09-27T06:05:27.000Z
2022-02-14T07:10:53.000Z
src/simpleserver/command/AreaSayCommand.java
mildfuzz/SimpleServer
62e4bb24af1b69b62afc7010075eca93eb793a41
[ "MIT" ]
4
2016-09-15T18:41:11.000Z
2018-04-15T21:44:14.000Z
src/simpleserver/command/AreaSayCommand.java
mildfuzz/SimpleServer
62e4bb24af1b69b62afc7010075eca93eb793a41
[ "MIT" ]
26
2015-01-16T04:17:48.000Z
2022-01-09T09:53:09.000Z
40.512821
80
0.768354
1,000,232
/* * Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package simpleserver.command; import simpleserver.Player; import simpleserver.message.AreaChat; import simpleserver.message.Chat; public class AreaSayCommand extends MessageCommand implements PlayerCommand { public AreaSayCommand() { super("areasay MESSAGE", "Send message to all players in your area"); } @Override protected Chat getMessageInstance(Player sender, String message) { return new AreaChat(sender); } }
923d3c508455dee781723e56552e2b22a80ada89
1,423
java
Java
srv/src/main/java/com/yankaizhang/movielikes/srv/security/handle/AuthenticationEntryPointImpl.java
dzzhyk/movielikes
074c214adca1802dd3f202a3888e956728758dfe
[ "MIT" ]
1
2022-03-18T02:27:42.000Z
2022-03-18T02:27:42.000Z
srv/src/main/java/com/yankaizhang/movielikes/srv/security/handle/AuthenticationEntryPointImpl.java
dzzhyk/movielikes
074c214adca1802dd3f202a3888e956728758dfe
[ "MIT" ]
null
null
null
srv/src/main/java/com/yankaizhang/movielikes/srv/security/handle/AuthenticationEntryPointImpl.java
dzzhyk/movielikes
074c214adca1802dd3f202a3888e956728758dfe
[ "MIT" ]
null
null
null
35.575
109
0.80253
1,000,233
package com.yankaizhang.movielikes.srv.security.handle; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.fasterxml.jackson.databind.ObjectMapper; import com.yankaizhang.movielikes.srv.api.AjaxResult; import com.yankaizhang.movielikes.srv.constant.HttpStatus; import com.yankaizhang.movielikes.srv.util.ServletUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.Serializable; /** * 认证失败处理类 返回未授权 * * @author ruoyi */ @Component public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable { private static final long serialVersionUID = -8970718410437077606L; @Autowired private ObjectMapper objectMapper; @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException { int code = HttpStatus.UNAUTHORIZED; String msg = StringUtils.format("请求访问:{},认证失败,无法访问系统资源", request.getRequestURI()); ServletUtils.renderString(response, objectMapper.writeValueAsString(AjaxResult.error(code, msg))); } }
923d3c9b86aead0e46898288fc3257b57eafc287
33,994
java
Java
src/com.mentor.nucleus.bp.core/src/com/mentor/nucleus/bp/core/SequenceInSequence_c.java
hjjohny/editor
c85d3329f00327f2fd9010ab617c70e031ed5e00
[ "Apache-2.0" ]
null
null
null
src/com.mentor.nucleus.bp.core/src/com/mentor/nucleus/bp/core/SequenceInSequence_c.java
hjjohny/editor
c85d3329f00327f2fd9010ab617c70e031ed5e00
[ "Apache-2.0" ]
1
2015-09-11T07:14:45.000Z
2015-09-11T07:14:45.000Z
src/com.mentor.nucleus.bp.core/src/com/mentor/nucleus/bp/core/SequenceInSequence_c.java
hjjohny/editor
c85d3329f00327f2fd9010ab617c70e031ed5e00
[ "Apache-2.0" ]
null
null
null
33.458661
166
0.664235
1,000,234
package com.mentor.nucleus.bp.core ; //==================================================================== // // File: com.mentor.nucleus.bp.core.SequenceInSequence_c.java // // WARNING: Do not edit this generated file // Generated by ../MC-Java/java.arc, $Revision: 1.111 $ // // (c) Copyright 2005-2014 by Mentor Graphics Corp. All rights reserved. // //==================================================================== // No special imports import java.util.* ; import java.lang.reflect.*; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import com.mentor.nucleus.bp.core.util.PersistenceUtil; import org.eclipse.core.runtime.NullProgressMonitor; import com.mentor.nucleus.bp.core.ui.marker.UmlProblem; import com.mentor.nucleus.bp.core.common.*; abstract class EV_SEQUENCE_IN_SEQUENCE extends genericEvent_c { public abstract int getEvtcode() ; } public class SequenceInSequence_c extends NonRootModelElement implements IAdaptable, Cloneable { // Public Constructors public SequenceInSequence_c(ModelRoot modelRoot, java.util.UUID p_m_package_id) { super(modelRoot); //pre-process the uuid so that we re-use null uuid instance rather then creating a new one. m_package_id = IdAssigner.preprocessUUID(p_m_package_id); Object [] key = {m_package_id}; addInstanceToMap(key); } static public SequenceInSequence_c createProxy(ModelRoot modelRoot, java.util.UUID p_m_package_id, String p_contentPath, IPath p_localPath) { ModelRoot resolvedModelRoot = ModelRoot.findModelRoot(modelRoot, p_contentPath, p_localPath); // if a model root was not resolved it is most likely // due to a missing file of the proxy, defualt back to // the original model root if(resolvedModelRoot != null) modelRoot = resolvedModelRoot; InstanceList instances = modelRoot.getInstanceList(SequenceInSequence_c.class); SequenceInSequence_c new_inst = null; synchronized(instances) { Object[] key = {p_m_package_id}; new_inst = (SequenceInSequence_c) instances.get(key) ; } String contentPath = PersistenceUtil.resolveRelativePath( p_localPath, new Path(p_contentPath)); if(modelRoot.isNewCompareRoot()) { // for comparisons we do not want to change // the content path contentPath = p_contentPath; } if ( new_inst != null && !modelRoot.isCompareRoot()) { PersistableModelComponent pmc = new_inst.getPersistableComponent(); if (pmc == null) { // dangling reference, redo this instance new_inst.batchUnrelate(); //pre-process the uuid so that we re-use null uuid instance rather then creating a new one. new_inst.m_package_id = IdAssigner.preprocessUUID(p_m_package_id); } } if ( new_inst == null ) { // there is no instance matching the id, create a proxy // if the resource doesn't exist then this will be a dangling reference new_inst = new SequenceInSequence_c(modelRoot, p_m_package_id ); new_inst.m_contentPath = contentPath; } return new_inst; } static public SequenceInSequence_c resolveInstance(ModelRoot modelRoot, java.util.UUID p_m_package_id){ InstanceList instances = modelRoot.getInstanceList(SequenceInSequence_c.class); SequenceInSequence_c source = null; synchronized(instances) { Object [] key = { p_m_package_id }; source = (SequenceInSequence_c) instances.get(key); if (source != null && !modelRoot.isCompareRoot()) { source.convertFromProxy(); source.batchUnrelate(); //pre-process the uuid so that we re-use null uuid instance rather then creating a new one. source.m_package_id = IdAssigner.preprocessUUID(p_m_package_id); return source ; } } // there is no instance matching the id SequenceInSequence_c new_inst = new SequenceInSequence_c(modelRoot, p_m_package_id ); return new_inst; } public SequenceInSequence_c(ModelRoot modelRoot) { super(modelRoot); m_package_id = IdAssigner.NULL_UUID; Object [] key = {m_package_id}; addInstanceToMap(key); } public Object getInstanceKey() { Object [] key = {m_package_id}; return key; } public boolean setInstanceKey(UUID p_newKey){ boolean changed = false; // round p1 // round p2 // round p3 // round p4 // round p5 if (m_package_id != p_newKey ){ m_package_id = p_newKey; changed = true; } return changed; } public boolean equals (Object elem) { if (!(elem instanceof SequenceInSequence_c)) { return false; } // check that the model-roots are the same if (((NonRootModelElement)elem).getModelRoot() != getModelRoot()) { return false; } return identityEquals(elem); } public boolean identityEquals(Object elem) { if (!(elem instanceof SequenceInSequence_c)) { return false; } SequenceInSequence_c me = (SequenceInSequence_c)elem; // don't allow an empty id-value to produce a false positive result; // in this case, use whether the two instances are actually the same // one in memory, instead if ((IdAssigner.NULL_UUID.equals(getPackage_id()) || IdAssigner.NULL_UUID.equals(((SequenceInSequence_c)elem).getPackage_id())) && this != elem) { return false; } if (!getPackage_id().equals(((SequenceInSequence_c)elem).getPackage_id())) return false; return true; } public boolean cachedIdentityEquals(Object elem) { if (!(elem instanceof SequenceInSequence_c)) { return false; } SequenceInSequence_c me = (SequenceInSequence_c)elem; if (!getPackage_idCachedValue().equals(((SequenceInSequence_c)elem).getPackage_idCachedValue())) return false; return true; } // Attributes private java.util.UUID m_package_id ; // declare association references from this class // referring navigation Sequence_c IsShownInSequence ; public void relateAcrossR911To(Sequence_c target) { relateAcrossR911To(target, true); } public void relateAcrossR911To(Sequence_c target, boolean notifyChanges) { if (target == null) return; if (target == IsShownInSequence) return; // already related if ( IsShownInSequence != target ) { Object oldKey = getInstanceKey(); if (IsShownInSequence != null) { UmlProblem.removeXtUMLProblem(this, IsShownInSequence); IsShownInSequence.clearBackPointerR911To(this); if (Boolean.valueOf(System.getenv("PTC_MCC_ENABLED")) == true) { //$NON-NLS-1$ Ooaofooa.log.println(ILogger.CONSISTENCY, "SequenceInSequence_c.relateAcrossR911To(Sequence_c target)", "Relate performed across R911 from Sequence in Sequence to Sequence without unrelate of prior instance."); } } IsShownInSequence = target ; if(IdAssigner.NULL_UUID.equals(target.getPackage_id())) { // do not update cached value } else { // update cached value m_package_id = target.getPackage_idCachedValue(); } updateInstanceKey(oldKey, getInstanceKey()); target.setBackPointerR911To(this); target.addRef(); UmlProblem.handleDanglingReference(this, target); if(notifyChanges) { RelationshipChangeModelDelta change = new RelationshipChangeModelDelta(Modeleventnotification_c.DELTA_ELEMENT_RELATED, this, target, "911", ""); Ooaofooa.getDefaultInstance().fireModelElementRelationChanged(change); } } } public void unrelateAcrossR911From(Sequence_c target) { unrelateAcrossR911From(target, true); } public void unrelateAcrossR911From(Sequence_c target, boolean notifyChanges) { if (target == null) return; if (IsShownInSequence == null) return; // already unrelated if (target != IsShownInSequence) { Exception e = new Exception(); e.fillInStackTrace(); CorePlugin.logError("Tried to unrelate from non-related instance across R911", e); return; } if (target != null) { target.clearBackPointerR911To(this); } if(IsShownInSequence != null) { m_package_id = IsShownInSequence.getPackage_id(); if(IdAssigner.NULL_UUID.equals(m_package_id)) { m_package_id = IsShownInSequence.getPackage_idCachedValue(); } IsShownInSequence = null ; target.removeRef(); UmlProblem.removeXtUMLProblem(this, target); if(notifyChanges) { RelationshipChangeModelDelta change = new RelationshipChangeModelDelta(Modeleventnotification_c.DELTA_ELEMENT_UNRELATED, this, target, "911", ""); Ooaofooa.getDefaultInstance().fireModelElementRelationChanged(change); } } } public static SequenceInSequence_c getOneSQ_SISOnR911(Sequence_c [] targets) { return getOneSQ_SISOnR911(targets, null); } public static SequenceInSequence_c getOneSQ_SISOnR911(Sequence_c [] targets, ClassQueryInterface_c test) { SequenceInSequence_c ret_val = null; if (targets != null) { for (int i = 0; i < targets.length && ret_val == null; ++i ) { ret_val = getOneSQ_SISOnR911(targets[i], test); } } return ret_val; } public static SequenceInSequence_c getOneSQ_SISOnR911(Sequence_c target) { return getOneSQ_SISOnR911(target, null); } public static SequenceInSequence_c getOneSQ_SISOnR911(Sequence_c target, boolean loadComponent) { return getOneSQ_SISOnR911(target.getModelRoot(), target, null, loadComponent); } public static SequenceInSequence_c getOneSQ_SISOnR911(Sequence_c target, ClassQueryInterface_c test) { if (target != null) { return getOneSQ_SISOnR911(target.getModelRoot(), target, test); } return null; } public static SequenceInSequence_c getOneSQ_SISOnR911(ModelRoot modelRoot, Sequence_c target, ClassQueryInterface_c test) { return getOneSQ_SISOnR911(modelRoot, target, test, true); } public static SequenceInSequence_c getOneSQ_SISOnR911(ModelRoot modelRoot, Sequence_c target, ClassQueryInterface_c test, boolean loadComponent) { SequenceInSequence_c result = null; result=find_getOneSQ_SISOnR911(modelRoot,target,test); if (result==null && (loadComponent)) { // Containment Relation List comps = PersistenceManager.findAllChildComponents(target.getPersistableComponent(),modelRoot,SequenceInSequence_c.class); for (int i = 0; i < comps.size(); i++) { PersistableModelComponent component = (PersistableModelComponent) comps.get(i); if (!component.isLoaded()) { try { component.load(new NullProgressMonitor()); result=find_getOneSQ_SISOnR911(modelRoot,target,test); if(result!=null) return result; } catch (Exception e) { CorePlugin.logError("Error Loading component", e); } } } } return result; } private static SequenceInSequence_c find_getOneSQ_SISOnR911(ModelRoot modelRoot, Sequence_c target, ClassQueryInterface_c test) { if (target != null) { SequenceInSequence_c source = (SequenceInSequence_c)target.backPointer_CanShowSequenceInSequenceCanShow_R911; if (source != null && (test == null || test.evaluate(source))) { return source; } } // not found return null ; } public static SequenceInSequence_c [] getManySQ_SISsOnR911(Sequence_c [] targets) { return getManySQ_SISsOnR911(targets, null); } public static SequenceInSequence_c [] getManySQ_SISsOnR911(Sequence_c [] targets, boolean loadComponent) { return getManySQ_SISsOnR911(targets, null, loadComponent); } public static SequenceInSequence_c [] getManySQ_SISsOnR911(Sequence_c [] targets, ClassQueryInterface_c test) { return getManySQ_SISsOnR911(targets, test, true); } public static SequenceInSequence_c [] getManySQ_SISsOnR911(Sequence_c [] targets, ClassQueryInterface_c test, boolean loadComponent) { if(targets == null || targets.length == 0 || targets[0] == null) return new SequenceInSequence_c[0]; ModelRoot modelRoot = targets[0].getModelRoot(); if(loadComponent){ //Containment Relation PersistableModelComponent[] pmcs= new PersistableModelComponent[targets.length]; for (int i = 0; i < targets.length; i++) { pmcs[i]=targets[i].getPersistableComponent(); } PersistenceManager.ensureAllChildInstancesLoaded(pmcs,modelRoot, SequenceInSequence_c.class); } InstanceList instances = modelRoot.getInstanceList(SequenceInSequence_c.class); Vector matches = new Vector(); for (int i = 0 ; i < targets.length ; i++) { SequenceInSequence_c source = (SequenceInSequence_c)targets[i].backPointer_CanShowSequenceInSequenceCanShow_R911; if (source != null && (test == null || test.evaluate(source))) { matches.add(source); } } if (matches.size() > 0) { SequenceInSequence_c[] ret_set = new SequenceInSequence_c[matches.size()]; matches.copyInto(ret_set); return ret_set; } else { return new SequenceInSequence_c[0]; } } public static SequenceInSequence_c [] getManySQ_SISsOnR911(Sequence_c target) { if (target != null) { Sequence_c [] targetArray = new Sequence_c[1]; targetArray[0] = target; return getManySQ_SISsOnR911(targetArray); } else { SequenceInSequence_c [] result = new SequenceInSequence_c [0] ; return result ; } } public static SequenceInSequence_c [] getManySQ_SISsOnR911(Sequence_c target, boolean loadComponent) { if (target != null) { Sequence_c [] targetArray = new Sequence_c[1]; targetArray[0] = target; return getManySQ_SISsOnR911(targetArray, loadComponent); } else { SequenceInSequence_c [] result = new SequenceInSequence_c [0] ; return result ; } } // declare associations referring to this class // referred to navigation ArrayList<Sequence_c> backPointer_HasChildrenSequenceHasChildren_R928 = new ArrayList<Sequence_c>(); public void setSequenceOrderInChildListR928(Sequence_c target, int index) { unrelateAcrossR928From(target); Sequence_c[] elements = Sequence_c.getManySQ_SsOnR928(this); int count = 0; for(int i = 0; i < elements.length; i++) { if(count >= index) { unrelateAcrossR928From((Sequence_c) elements[i]); } count++; } relateAcrossR928To(target); count = 0; for(int i = 0; i < elements.length; i++) { if(count >= index) { relateAcrossR928To((Sequence_c) elements[i]); } count++; } } public void relateAcrossR928To(Sequence_c target) { if (target != null) { target.relateAcrossR928To(this, true) ; } } public void relateAcrossR928To(Sequence_c target, boolean notifyChanges) { if (target != null) { target.relateAcrossR928To(this, notifyChanges) ; } } public void setBackPointerR928To(Sequence_c target) { synchronized (backPointer_HasChildrenSequenceHasChildren_R928) { backPointer_HasChildrenSequenceHasChildren_R928.add(target); } } public void unrelateAcrossR928From(Sequence_c target) { if (target != null) { target.unrelateAcrossR928From(this, true) ; } } public void unrelateAcrossR928From(Sequence_c target, boolean notifyChanges) { if (target != null) { target.unrelateAcrossR928From(this, notifyChanges) ; } } public void clearBackPointerR928To(Sequence_c target) { synchronized (backPointer_HasChildrenSequenceHasChildren_R928) { backPointer_HasChildrenSequenceHasChildren_R928.remove(target); } } public static SequenceInSequence_c getOneSQ_SISOnR928(Sequence_c [] targets) { return getOneSQ_SISOnR928(targets, null); } public static SequenceInSequence_c getOneSQ_SISOnR928(Sequence_c [] targets, ClassQueryInterface_c test) { return getOneSQ_SISOnR928(targets, test, true); } public static SequenceInSequence_c getOneSQ_SISOnR928(Sequence_c [] targets, ClassQueryInterface_c test, boolean loadComponent) { SequenceInSequence_c ret_val = null; if (targets != null) { for (int i = 0; i < targets.length && ret_val == null; ++i ) { if (test != null) { SequenceInSequence_c candidate_val = getOneSQ_SISOnR928(targets[i],true); if ( candidate_val != null && test.evaluate(candidate_val) ) { ret_val = candidate_val; break; } } else { ret_val = getOneSQ_SISOnR928(targets[i], loadComponent); if (ret_val != null) { break; } } } } return ret_val; } public static SequenceInSequence_c getOneSQ_SISOnR928(Sequence_c target) { return getOneSQ_SISOnR928(target, true); } public static SequenceInSequence_c getOneSQ_SISOnR928(Sequence_c target, boolean loadComponent) { if (target != null) { if(loadComponent){ target.loadProxy(); } return target.IsDisplayedInSequenceInSequence ; } else { return null; } } public static SequenceInSequence_c [] getManySQ_SISsOnR928(Sequence_c [] targets, ClassQueryInterface_c test) { return getManySQ_SISsOnR928(targets, test, true); } public static SequenceInSequence_c [] getManySQ_SISsOnR928(Sequence_c [] targets, ClassQueryInterface_c test, boolean loadComponent) { if(targets == null || targets.length == 0 || targets[0] == null) return new SequenceInSequence_c[0]; LinkedHashSet<SequenceInSequence_c> elementsSet = new LinkedHashSet<SequenceInSequence_c>(); for (int i = 0; i < targets.length; i++) { if(loadComponent && targets[i] != null && targets[i].IsDisplayedInSequenceInSequence == null) targets[i].loadProxy(); SequenceInSequence_c associate = targets[i].IsDisplayedInSequenceInSequence; if (targets[i] != null && associate != null && (test == null || test.evaluate(associate))) { if (elementsSet.add(associate)){ } } } SequenceInSequence_c[] result = new SequenceInSequence_c[elementsSet.size()]; elementsSet.toArray(result); return result; } public static SequenceInSequence_c [] getManySQ_SISsOnR928(Sequence_c [] targets) { return getManySQ_SISsOnR928(targets, null); } public static SequenceInSequence_c [] getManySQ_SISsOnR928(Sequence_c target, ClassQueryInterface_c test, boolean loadComponent) { if (target != null) { Sequence_c [] targetArray = new Sequence_c[1]; targetArray[0] = target; return getManySQ_SISsOnR928(targetArray, test, loadComponent); } else { SequenceInSequence_c [] result = new SequenceInSequence_c [0] ; return result ; } } public static SequenceInSequence_c [] getManySQ_SISsOnR928(Sequence_c target, ClassQueryInterface_c test) { return getManySQ_SISsOnR928(target, null, true); } public static SequenceInSequence_c [] getManySQ_SISsOnR928(Sequence_c target) { return getManySQ_SISsOnR928(target, null, true); } public static SequenceInSequence_c [] getManySQ_SISsOnR928(Sequence_c target, boolean loadComponent) { return getManySQ_SISsOnR928(target, null, loadComponent); } public void batchRelate(ModelRoot modelRoot, boolean notifyChanges, boolean searchAllRoots) { batchRelate(modelRoot, false, notifyChanges, searchAllRoots); } public void batchRelate(ModelRoot modelRoot, boolean relateProxies, boolean notifyChanges, boolean searchAllRoots) { InstanceList instances=null; ModelRoot baseRoot = modelRoot; if (IsShownInSequence == null) { // R911 Sequence_c relInst38755 = (Sequence_c) baseRoot.getInstanceList(Sequence_c.class).get(new Object[] {m_package_id}); // if there was no local element, check for any global elements // failing that proceed to check other model roots if (relInst38755 == null) { relInst38755 = (Sequence_c) Ooaofooa.getDefaultInstance().getInstanceList(Sequence_c.class).get(new Object[] {m_package_id}); } if (relInst38755 == null && searchAllRoots && !baseRoot.isCompareRoot()) { Ooaofooa[] roots = Ooaofooa.getInstances(); for (int i = 0; i < roots.length; i++) { if(roots[i].isCompareRoot()) { // never use elements from any compare root continue; } relInst38755 = (Sequence_c) roots[i].getInstanceList(Sequence_c.class).get(new Object[] {m_package_id}); if (relInst38755 != null) break; } } //synchronized if ( relInst38755 != null ) { if (relateProxies || !isProxy() || (inSameComponent(this, relInst38755) && !isProxy())) { relInst38755.relateAcrossR911To(this, notifyChanges); } } } } public void batchUnrelate(boolean notifyChanges) { NonRootModelElement inst=null; // R911 // SQ_S inst=IsShownInSequence; unrelateAcrossR911From(IsShownInSequence, notifyChanges); if ( inst != null ) { inst.removeRef(); } } public static void batchRelateAll(ModelRoot modelRoot, boolean notifyChanges, boolean searchAllRoots) { batchRelateAll(modelRoot, notifyChanges, searchAllRoots, false); } public static void batchRelateAll(ModelRoot modelRoot, boolean notifyChanges, boolean searchAllRoots, boolean relateProxies) { InstanceList instances = modelRoot.getInstanceList(SequenceInSequence_c.class); synchronized(instances) { Iterator<NonRootModelElement> cursor = instances.iterator() ; while (cursor.hasNext()) { final SequenceInSequence_c inst = (SequenceInSequence_c)cursor.next() ; inst.batchRelate(modelRoot, relateProxies, notifyChanges, searchAllRoots ); } } } public static void clearInstances(ModelRoot modelRoot) { InstanceList instances = modelRoot.getInstanceList(SequenceInSequence_c.class); synchronized(instances) { for(int i=instances.size()-1; i>=0; i--){ ((NonRootModelElement)instances.get(i)).delete_unchecked(); } } } public static SequenceInSequence_c SequenceInSequenceInstance(ModelRoot modelRoot, ClassQueryInterface_c test, boolean loadComponent) { SequenceInSequence_c result=findSequenceInSequenceInstance(modelRoot,test,loadComponent); if(result==null && loadComponent){ List pmcs = PersistenceManager.findAllComponents(modelRoot,SequenceInSequence_c.class); for (int i = 0; i < pmcs.size(); i++) { PersistableModelComponent component = (PersistableModelComponent) pmcs .get(i); if (!component.isLoaded()) { try { component.load(new NullProgressMonitor()); result=findSequenceInSequenceInstance(modelRoot,test,loadComponent); if(result!=null) return result; } catch (Exception e) { CorePlugin.logError("Error Loading component", e); } } } } if(result!=null && loadComponent){ result.loadProxy(); } return result; } private static SequenceInSequence_c findSequenceInSequenceInstance(ModelRoot modelRoot, ClassQueryInterface_c test, boolean loadComponent) { InstanceList instances = modelRoot.getInstanceList(SequenceInSequence_c.class); synchronized (instances) { for (int i = 0; i < instances.size(); ++i) { SequenceInSequence_c x = (SequenceInSequence_c) instances.get(i); if (test==null || test.evaluate(x)){ if(x.ensureLoaded(loadComponent)) return x; } } } return null; } public static SequenceInSequence_c SequenceInSequenceInstance(ModelRoot modelRoot, ClassQueryInterface_c test){ return SequenceInSequenceInstance(modelRoot,test,true); } public static SequenceInSequence_c SequenceInSequenceInstance(ModelRoot modelRoot) { return SequenceInSequenceInstance(modelRoot,null,true); } public static SequenceInSequence_c [] SequenceInSequenceInstances(ModelRoot modelRoot, ClassQueryInterface_c test, boolean loadComponent) { if(loadComponent){ PersistenceManager.ensureAllInstancesLoaded(modelRoot, SequenceInSequence_c.class); } InstanceList instances = modelRoot.getInstanceList(SequenceInSequence_c.class); Vector matches = new Vector(); synchronized (instances) { for (int i = 0; i < instances.size(); ++i) { SequenceInSequence_c x = (SequenceInSequence_c) instances.get(i); if (test==null ||test.evaluate(x)){ if(x.ensureLoaded(loadComponent)) matches.add(x); } } if (matches.size() > 0) { SequenceInSequence_c[] ret_set = new SequenceInSequence_c[matches.size()]; matches.copyInto(ret_set); return ret_set; } else { return new SequenceInSequence_c[0]; } } } public static SequenceInSequence_c [] SequenceInSequenceInstances(ModelRoot modelRoot, ClassQueryInterface_c test){ return SequenceInSequenceInstances(modelRoot,test,true); } public static SequenceInSequence_c [] SequenceInSequenceInstances(ModelRoot modelRoot) { return SequenceInSequenceInstances(modelRoot,null,true); } public boolean delete() { boolean result = super.delete(); boolean delete_error = false; String errorMsg = "The following relationships were not torn down by the Sequence in Sequence.dispose call: "; Sequence_c testR928Inst = Sequence_c.getOneSQ_SOnR928(this, false); if ( testR928Inst != null ) { delete_error = true; errorMsg = errorMsg + "928 "; } Sequence_c testR911Inst = Sequence_c.getOneSQ_SOnR911(this, false); if ( testR911Inst != null ) { delete_error = true; errorMsg = errorMsg + "911 "; } if(delete_error == true) { if(CorePlugin.getDefault().isDebugging()) { Ooaofooa.log.println(ILogger.DELETE, "Sequence in Sequence", errorMsg); } else { Exception e = new Exception(); e.fillInStackTrace(); CorePlugin.logError(errorMsg, e); } } return result; } // end declare instance pool // declare attribute accessors public boolean isUUID(String attributeName){ if(attributeName.equals("package_id")){ return true; } return false; } public String getCompUniqueID(){ UUID tempID=null; long longID=0L; StringBuffer result= new StringBuffer(); tempID= getPackage_id(); if(IdAssigner.NULL_UUID.equals(tempID)) tempID=getPackage_idCachedValue(); result.append(Long.toHexString(tempID.getMostSignificantBits())); result.append(Long.toHexString(tempID.getLeastSignificantBits())); return result.toString(); } // declare attribute accessors public long getPackage_idLongBased() { if ( IsShownInSequence != null ) { return IsShownInSequence.getPackage_idLongBased(); } return 0; } public java.util.UUID getPackage_id() { if ( IsShownInSequence != null ) { return IsShownInSequence.getPackage_id(); } return IdAssigner.NULL_UUID; } public java.util.UUID getPackage_idCachedValue() { if ( !IdAssigner.NULL_UUID.equals(m_package_id) ) return m_package_id; else return getPackage_id(); } public void setPackage_id(java.util.UUID newValue) { if(newValue != null){ if(newValue.equals(m_package_id)){ return; } }else if(m_package_id != null){ if(m_package_id.equals(newValue)){ return; } }else{ return; } AttributeChangeModelDelta change = new AttributeChangeModelDelta(Modeleventnotification_c.DELTA_ATTRIBUTE_CHANGE, this, "Package_id", m_package_id, newValue,true); m_package_id = IdAssigner.preprocessUUID(newValue); Ooaofooa.getDefaultInstance().fireModelElementAttributeChanged(change); } // end declare accessors public static void checkClassConsistency (ModelRoot modelRoot) { Ooaofooa.log.println( ILogger.OPERATION, "Sequence in Sequence", //$NON-NLS-1$ " Operation entered: Sequence in Sequence::checkClassConsistency"); //$NON-NLS-1$ if (Boolean.valueOf(System.getenv("PTC_MCC_ENABLED")) == false) { //$NON-NLS-1$ return; } SequenceInSequence_c [] objs = SequenceInSequence_c.SequenceInSequenceInstances(modelRoot,null,false); for ( int i = 0; i < objs.length; i++) { objs[i].checkConsistency(); } } public boolean checkConsistency () { Ooaofooa.log.println( ILogger.OPERATION, "Sequence in Sequence", //$NON-NLS-1$ " Operation entered: Sequence in Sequence::checkConsistency"); //$NON-NLS-1$ if (Boolean.valueOf(System.getenv("PTC_MCC_ENABLED")) == false) { //$NON-NLS-1$ return true; } ModelRoot modelRoot = getModelRoot(); boolean retval = true; class SequenceInSequence_c_test38757_c implements ClassQueryInterface_c { SequenceInSequence_c_test38757_c( java.util.UUID p38758 ) { m_p38758 = p38758; } private java.util.UUID m_p38758; public boolean evaluate (Object candidate) { SequenceInSequence_c selected = (SequenceInSequence_c) candidate; boolean retval = false; retval = (selected.getPackage_id().equals(m_p38758)); return retval; } } SequenceInSequence_c [] objs38756 = SequenceInSequence_c.SequenceInSequenceInstances(modelRoot, new SequenceInSequence_c_test38757_c(getPackage_id())) ; if ( ( (objs38756.length) == 0) ) { if (CorePlugin.getDefault().isDebugging()){ Ooaofooa.log.println(ILogger.CONSISTENCY, "Sequence in Sequence", //$NON-NLS-1$ "Consistency: Object: Sequence in Sequence: Cardinality of an identifier is zero. " //$NON-NLS-1$ + "Actual Value: " + Integer.toString( objs38756.length ) ); //$NON-NLS-1$ } else { Exception e = new Exception(); CorePlugin.logError("Consistency: Object: Sequence in Sequence: Cardinality of an identifier is zero. " //$NON-NLS-1$ + "Actual Value: " //$NON-NLS-1$ + Integer.toString( objs38756.length ) , e); } retval = false; } if ( ( (objs38756.length) > 1) ) { if (CorePlugin.getDefault().isDebugging()){ Ooaofooa.log.println(ILogger.CONSISTENCY, "Sequence in Sequence", //$NON-NLS-1$ "Consistency: Object: Sequence in Sequence: Cardinality of an identifier is greater than 1. " //$NON-NLS-1$ + "Actual Value: " //$NON-NLS-1$ + Integer.toString( objs38756.length ) + " Package_ID: " + "Not Printable" ); //$NON-NLS-1$ } else { Exception e = new Exception(); CorePlugin.logError("Consistency: Object: Sequence in Sequence: Cardinality of an identifier is greater than 1. " //$NON-NLS-1$ + "Actual Value: " //$NON-NLS-1$ + Integer.toString( objs38756.length ) + " Package_ID: " + "Not Printable" , e); //$NON-NLS-1$ } retval = false; } // Sequence in Sequence is a referring class in association: rel.Numb = 911 // The participating class is: Sequence class Sequence_c_test38762_c implements ClassQueryInterface_c { Sequence_c_test38762_c( java.util.UUID p38763 ) { m_p38763 = p38763; } private java.util.UUID m_p38763; public boolean evaluate (Object candidate) { Sequence_c selected = (Sequence_c) candidate; boolean retval = false; retval = (selected.getPackage_id().equals(m_p38763)); return retval; } } Sequence_c [] objs38761 = Sequence_c.SequenceInstances(modelRoot, new Sequence_c_test38762_c(getPackage_id())) ; // The participant is unconditional // The multiplicity of the participant is one if ( ( (objs38761.length) != 1) ) { if (CorePlugin.getDefault().isDebugging()){ Ooaofooa.log.println(ILogger.CONSISTENCY, "Sequence in Sequence", //$NON-NLS-1$ "Consistency: Object: Sequence in Sequence: Association: 911: Cardinality of a participant is not equal to 1. " //$NON-NLS-1$ + "Actual Value: " //$NON-NLS-1$ + Integer.toString( objs38761.length ) + " Package_ID: " + "Not Printable" ); //$NON-NLS-1$ } else { Exception e = new Exception(); CorePlugin.logError("Consistency: Object: Sequence in Sequence: Association: 911: Cardinality of a participant is not equal to 1. " //$NON-NLS-1$ + "Actual Value: " //$NON-NLS-1$ + Integer.toString( objs38761.length ) + " Package_ID: " + "Not Printable" , e); //$NON-NLS-1$ } retval = false; } // Sequence in Sequence is a participating class in association: rel.Numb = 928 // Object: Sequence return retval; } public Object getAdapter(Class adapter) { Object superAdapter = super.getAdapter(adapter); if(superAdapter != null) { return superAdapter; } return null; } } // end Sequence in Sequence
923d3d10486629b1863ab45f1e1b81aa57192e3c
2,719
java
Java
src/dataflow/jobnavi/jobnavi-runner/src/main/java/com/tencent/bk/base/dataflow/jobnavi/runner/event/KillTaskEventListener.java
Chromico/bk-base
be822d9bbee544a958bed4831348185a75604791
[ "MIT" ]
84
2021-06-30T06:20:23.000Z
2022-03-22T03:05:49.000Z
src/dataflow/jobnavi/jobnavi-runner/src/main/java/com/tencent/bk/base/dataflow/jobnavi/runner/event/KillTaskEventListener.java
Chromico/bk-base
be822d9bbee544a958bed4831348185a75604791
[ "MIT" ]
7
2021-06-30T06:21:16.000Z
2022-03-29T07:36:13.000Z
src/dataflow/jobnavi/jobnavi-runner/src/main/java/com/tencent/bk/base/dataflow/jobnavi/runner/event/KillTaskEventListener.java
Chromico/bk-base
be822d9bbee544a958bed4831348185a75604791
[ "MIT" ]
40
2021-06-30T06:21:26.000Z
2022-03-29T12:42:26.000Z
52.288462
114
0.745127
1,000,235
/* * Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. * * Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. * * BK-BASE 蓝鲸基础平台 is licensed under the MIT License. * * License for BK-BASE 蓝鲸基础平台: * -------------------------------------------------------------------- * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.tencent.bk.base.dataflow.jobnavi.runner.event; import com.tencent.bk.base.dataflow.jobnavi.runner.service.LogAggregationService; import com.tencent.bk.base.dataflow.jobnavi.runner.task.process.TaskProcessManager; import com.tencent.bk.base.dataflow.jobnavi.runner.task.thread.TaskThreadManager; import com.tencent.bk.base.dataflow.jobnavi.state.TaskMode; import com.tencent.bk.base.dataflow.jobnavi.state.event.TaskEvent; import com.tencent.bk.base.dataflow.jobnavi.state.event.TaskEventInfo; import com.tencent.bk.base.dataflow.jobnavi.state.event.TaskEventListener; import com.tencent.bk.base.dataflow.jobnavi.state.event.TaskEventResult; public class KillTaskEventListener implements TaskEventListener { @Override public TaskEventResult doEvent(TaskEventInfo taskEventInfo) { TaskEvent event = taskEventInfo.getTaskEvent(); TaskEventResult result = new TaskEventResult(); Long executeId = event.getContext().getExecuteInfo().getId(); if (event.getContext().getTaskInfo().getType().getTaskMode() == TaskMode.thread) { TaskThreadManager.unregisterTask(executeId); } else { TaskProcessManager.unregisterTask(executeId); LogAggregationService.callAggregateLog(executeId); } return result; } }
923d3d85677403eb8a4e4a73ffb4cc494ba7338b
462
java
Java
herokudemo-business/src/main/java/capgemini/webappdemo/repository/Employee/EmployeeRepository.java
VuAnhNguyenDuc/lvtn_server
5bc4d5cd97b1feae92045dcb925a6a2db4e40909
[ "Apache-2.0" ]
null
null
null
herokudemo-business/src/main/java/capgemini/webappdemo/repository/Employee/EmployeeRepository.java
VuAnhNguyenDuc/lvtn_server
5bc4d5cd97b1feae92045dcb925a6a2db4e40909
[ "Apache-2.0" ]
null
null
null
herokudemo-business/src/main/java/capgemini/webappdemo/repository/Employee/EmployeeRepository.java
VuAnhNguyenDuc/lvtn_server
5bc4d5cd97b1feae92045dcb925a6a2db4e40909
[ "Apache-2.0" ]
null
null
null
23.1
72
0.800866
1,000,236
package capgemini.webappdemo.repository.Employee; import capgemini.webappdemo.domain.Detail; import capgemini.webappdemo.domain.Employee; import capgemini.webappdemo.repository.EntityRepository; import java.util.List; public interface EmployeeRepository extends EntityRepository<Employee> { /** * Our app has a need for a fast method for deleting names */ public void deleteAll(); public List<Employee> getEmployeesByManagerId(int manager_id); }
923d3d878a4d5c9cb48921fe0818f3433646d2af
527
java
Java
src/main/java/syntaxtree/ClassDeclExtends.java
AndrewHancock/MiniJava-compiler
788dee3b9c5f3bba8255678a6607909555bc92d9
[ "Apache-2.0" ]
1
2020-06-06T06:46:53.000Z
2020-06-06T06:46:53.000Z
src/main/java/syntaxtree/ClassDeclExtends.java
AndrewHancock/MiniJava-compiler
788dee3b9c5f3bba8255678a6607909555bc92d9
[ "Apache-2.0" ]
null
null
null
src/main/java/syntaxtree/ClassDeclExtends.java
AndrewHancock/MiniJava-compiler
788dee3b9c5f3bba8255678a6607909555bc92d9
[ "Apache-2.0" ]
2
2015-03-03T03:33:45.000Z
2020-11-15T09:14:05.000Z
21.958333
56
0.702087
1,000,237
package syntaxtree; import syntaxtree.visitor.TypeVisitor; import syntaxtree.visitor.Visitor; public class ClassDeclExtends extends ClassDecl { public Identifier i; public Identifier j; public VarDeclList vl; public MethodDeclList ml; public ClassDeclExtends(Identifier ai, Identifier aj, VarDeclList avl, MethodDeclList aml) { i=ai; j=aj; vl=avl; ml=aml; } public void accept(Visitor v) { v.visit(this); } public Type accept(TypeVisitor v) { return v.visit(this); } }
923d3db70291dcc2fb37f303fed2064422f03a70
1,741
java
Java
src/main/java/com/webrest/hobbyte/core/dao/IGenericDao.java
EWojewodka/Hobbyte
d747426495bacb11eddb3e578b8d17b621314768
[ "Apache-2.0" ]
null
null
null
src/main/java/com/webrest/hobbyte/core/dao/IGenericDao.java
EWojewodka/Hobbyte
d747426495bacb11eddb3e578b8d17b621314768
[ "Apache-2.0" ]
null
null
null
src/main/java/com/webrest/hobbyte/core/dao/IGenericDao.java
EWojewodka/Hobbyte
d747426495bacb11eddb3e578b8d17b621314768
[ "Apache-2.0" ]
null
null
null
18.135417
81
0.664561
1,000,238
/** * */ package com.webrest.hobbyte.core.dao; import java.io.Serializable; import java.util.List; import javax.persistence.Id; import javax.persistence.Table; import com.webrest.hobbyte.core.criteria.ICriteriaFilter; import com.webrest.hobbyte.core.model.DatabaseObject; /** * @author Emil Wojewódka * * @since 24 mar 2018 */ public interface IGenericDao<T extends DatabaseObject, ID extends Serializable> { /** * Save entity in database * * @param t * @throws Exception */ void save(T t) throws Exception; /** * Count all database rows of T entity * * @return * @throws Exception */ Long count() throws Exception; T create(); /** * Delete row from database * * @param t * @throws Exception */ void delete(T t) throws Exception; /** * Delete row with specified {@link Id} in database from {@link Table} * * @param id * @throws Exception */ void delete(ID id) throws Exception; /** * Return true if object exists in database. * * @param t * @return * @throws Exception */ boolean exists(T t) throws Exception; /** * Return true if object with specified id exists in database in {@link Table} * * @param id * @return * @throws Exception */ boolean exists(ID id) throws Exception; /** * Return instance of {@link DatabaseObject} with specified ID. * * @param id * @return * @throws Exception */ T getById(ID id) throws Exception; /** * Return {@link List} of entities which are in database where fieldName=value * * @param fieldName * @param value * @return */ List<T> findAllBy(String fieldName, Object value); List<T> find(ICriteriaFilter<?> criteriaFilter); T findBy(String fieldName, Object value); }
923d3e2349583779a49695d12423e9f881917fd9
5,988
java
Java
tools/consistency_checker/src/com/facebook/buck/tools/consistency/RuleKeyFileParser.java
FightJames/buck
ae2347e05da6f0ef9e0ec21497a654757aca7ad5
[ "Apache-2.0" ]
8,027
2015-01-02T05:31:44.000Z
2022-03-31T07:08:09.000Z
tools/consistency_checker/src/com/facebook/buck/tools/consistency/RuleKeyFileParser.java
FightJames/buck
ae2347e05da6f0ef9e0ec21497a654757aca7ad5
[ "Apache-2.0" ]
2,355
2015-01-01T15:30:53.000Z
2022-03-30T20:21:16.000Z
tools/consistency_checker/src/com/facebook/buck/tools/consistency/RuleKeyFileParser.java
FightJames/buck
ae2347e05da6f0ef9e0ec21497a654757aca7ad5
[ "Apache-2.0" ]
1,280
2015-01-09T03:29:04.000Z
2022-03-30T15:14:14.000Z
36.290909
103
0.631764
1,000,239
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.buck.tools.consistency; import com.facebook.buck.log.thrift.rulekeys.FullRuleKey; import com.facebook.buck.tools.consistency.RuleKeyLogFileReader.ParseException; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.nio.file.Path; import java.time.Duration; import java.util.HashMap; import java.util.Map; /** A class that can parse out length prefixed, thrift compact encoded rule keys. */ public class RuleKeyFileParser { private final RuleKeyLogFileReader reader; public RuleKeyFileParser(RuleKeyLogFileReader reader) { this.reader = reader; } /** * A node in the set of all rule keys. When parsing, it tracks whether the node has been visited * yet or not. */ static class RuleKeyNode { public final FullRuleKey ruleKey; public int lastVisitId; public RuleKeyNode(FullRuleKey ruleKey) { this.ruleKey = ruleKey; } public String toString() { return ruleKey.toString(); } } /** A parsed rule key file with details of the parse, and all rules contained in the file. */ static class ParsedRuleKeyFile { public final Path filename; public final ImmutableMap<String, RuleKeyNode> rootNodes; public final Map<String, RuleKeyNode> rules; public final Duration parseTime; public ParsedRuleKeyFile( Path filename, ImmutableMap<String, RuleKeyNode> rootNodes, Map<String, RuleKeyNode> rules, Duration parseTime) { this.filename = filename; this.rootNodes = rootNodes; this.rules = rules; this.parseTime = parseTime; } } /** Arbitrary estimate of an average rule key size when serialized */ public final int THRIFT_STRUCT_SIZE = 300; /** * Parse a thrift compact serialized file * * @param filename The name of the file * @param targetNames The name of the targets that should be found * @return A {@link ParsedRuleKeyFile} object that all deserialized rules, and the rule key hash * of the specified target * @throws ParseException If an IO or serialization error occurs, or if the target could not be * found in the file */ public ParsedRuleKeyFile parseFile(Path filename, ImmutableSet<String> targetNames) throws ParseException { // If //foo/bar/... is passed in, we want to find all targets that start with // //foo/bar, and that are of the right type, and add them as root nodes ImmutableList<String> recursiveTargetPrefixes = targetNames.stream() .filter(name -> name.endsWith("/...") || name.endsWith(":")) .map( name -> { int idx = name.lastIndexOf("/..."); if (idx != -1) { return name.substring(0, idx); } else { return name; } }) .collect(ImmutableList.toImmutableList()); long startNanos = System.nanoTime(); int initialSize; try { initialSize = Math.toIntExact(filename.toFile().length() / THRIFT_STRUCT_SIZE); } catch (ArithmeticException e) { throw new ParseException( e, filename, "File size is too large (>2.1 billion objects would be deserialized"); } ImmutableMap.Builder<String, RuleKeyNode> rootNodesBuilder = ImmutableMap.builder(); Map<String, RuleKeyNode> rules = new HashMap<>(); try { reader.readFile( filename, ruleKey -> { RuleKeyNode newNode = new RuleKeyNode(ruleKey); if ("DEFAULT".equals(ruleKey.type)) { // If either a specific rule is present, or if the target starts with one of the // prefixes if (targetNames.contains(ruleKey.name) || recursiveTargetPrefixes.stream() .filter(prefix -> ruleKey.name.startsWith(prefix)) .findFirst() .isPresent()) { rootNodesBuilder.put(ruleKey.name, newNode); } } RuleKeyNode oldValue = rules.put(ruleKey.key, newNode); if (oldValue != null && !oldValue.ruleKey.equals(newNode.ruleKey)) { throw new RuntimeException( new ParseException( filename, "Found two rules with the same key, but different values. Key: %s, first value: " + "%s, second value: %s", ruleKey.key, oldValue.ruleKey, newNode.ruleKey)); } return false; }); } catch (RuntimeException e) { if (e.getCause() instanceof ParseException) { throw (ParseException) e.getCause(); } } ImmutableMap<String, RuleKeyNode> rootNodes = rootNodesBuilder.build(); for (String targetName : targetNames) { if (!targetName.endsWith("/...") && !targetName.endsWith(":") && !rootNodes.containsKey(targetName)) { throw new ParseException(filename, "Could not find %s in %s", targetName, filename); } } Duration runtime = Duration.ofNanos(System.nanoTime() - startNanos); return new ParsedRuleKeyFile(filename, rootNodes, rules, runtime); } }
923d3e9c588098a90c8ae0a3c477f9783bbc279c
3,242
java
Java
src/cn/nh121/echarts/style/itemstyle/ItemLabel.java
GoldyMark/EChartSummoner
6b2437d4a0440e1ef7edccbf900d96d89ea38427
[ "Apache-2.0" ]
2
2015-03-26T08:48:03.000Z
2019-12-27T12:22:56.000Z
src/cn/nh121/echarts/style/itemstyle/ItemLabel.java
GoldyMark/EChartSummoner
6b2437d4a0440e1ef7edccbf900d96d89ea38427
[ "Apache-2.0" ]
null
null
null
src/cn/nh121/echarts/style/itemstyle/ItemLabel.java
GoldyMark/EChartSummoner
6b2437d4a0440e1ef7edccbf900d96d89ea38427
[ "Apache-2.0" ]
6
2015-02-15T17:45:34.000Z
2019-12-27T12:22:58.000Z
17.911602
80
0.460518
1,000,240
/** * */ package cn.nh121.echarts.style.itemstyle; import cn.nh121.echarts.style.TextStyle; /** * @author ODMark * @creation 2014-7-11 */ public class ItemLabel { /** * 说明: * 标签显示策略,可选为:true(显示) | false(隐藏)<br> * * 默认值: * TRUE */ private Boolean show; /** * 说明: * 标签显示位置,地图标签不可指定位置 * 饼图可选为:'outer'(外部) | 'inner'(内部), * 折线图,柱形图,K线图,散点图默认根据布局自适应为'top'或者'right',可选的还有:'inside' | 'left' | * 'bottom' * 柱形图可选的还有,'insideLeft' | 'insideRight' | 'insideTop' | 'insideBottom'<br> * * 默认值: * 'outer' | null */ private EItemLabelPosition position; /** * 说明: * 和弦图有效,文本标签自动旋转<br> * * 默认值: * FALSE */ private Boolean rotate; /** * 说明: * 和弦图有效,文本标签旋转后于弦的间隔<br> * * 默认值: * 10 */ private Integer distance; /** * 说明: * 标签文本格式器,通用,同Tooltip.formatter,支持模板、方法回调,不支持异步回调<br> * * 默认值: * null */ private String formatter; /** * 说明: * 标签的文本样式(详见textStyle)<br> * * 默认值: * null */ private TextStyle textStyle; /** * @return the show */ public Boolean getShow() { return show; } /** * @param show * the show to set */ public ItemLabel setShow(Boolean show) { this.show = show; return this; } /** * @return the position */ public EItemLabelPosition getPosition() { return position; } /** * @param position * the position to set */ public ItemLabel setPosition(EItemLabelPosition position) { this.position = position; return this; } /** * @return the rotate */ public Boolean getRotate() { return rotate; } /** * @param rotate * the rotate to set */ public ItemLabel setRotate(Boolean rotate) { this.rotate = rotate; return this; } /** * @return the distance */ public Integer getDistance() { return distance; } /** * @param distance * the distance to set */ public ItemLabel setDistance(Integer distance) { this.distance = distance; return this; } /** * @return the formatter */ public String getFormatter() { return formatter; } /** * @param formatter * the formatter to set */ public ItemLabel setFormatter(String formatter) { this.formatter = formatter; return this; } /** * @return the textStyle */ public TextStyle getTextStyle() { return textStyle; } /** * @param textStyle * the textStyle to set */ public ItemLabel setTextStyle(TextStyle textStyle) { this.textStyle = textStyle; return this; } }
923d3ee1a7a333f73a7ce6eb1d442feaa0947fe6
3,975
java
Java
src/main/java/ro/ne8/oauth2/authorizationserver/controller/UserController.java
ne8/authorization-server
7edbffa6dfc22b4fd097f62d2a6548b97a4fec65
[ "Apache-2.0" ]
null
null
null
src/main/java/ro/ne8/oauth2/authorizationserver/controller/UserController.java
ne8/authorization-server
7edbffa6dfc22b4fd097f62d2a6548b97a4fec65
[ "Apache-2.0" ]
null
null
null
src/main/java/ro/ne8/oauth2/authorizationserver/controller/UserController.java
ne8/authorization-server
7edbffa6dfc22b4fd097f62d2a6548b97a4fec65
[ "Apache-2.0" ]
null
null
null
48.47561
138
0.735346
1,000,241
package ro.ne8.oauth2.authorizationserver.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.util.UriComponentsBuilder; import ro.ne8.oauth2.authorizationserver.dto.UserDTO; import ro.ne8.oauth2.authorizationserver.facades.UserFacade; import javax.validation.Valid; import java.util.List; @RestController @Api(value = "User handler API for spring security projects", description = "User handler API that supports basic CRUD operations", tags = {"UserHandler"}) @RequestMapping(value = "/users/", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public class UserController { private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class); private static final String BY_ID = "{id}"; private static final String EMAIL = "email"; @Autowired private UserFacade userFacade; @ApiOperation( value = "Retrieves all users from the database. Note that the password is hashed", response = UserDTO.class, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @ApiResponses({ @ApiResponse(code = 200, responseContainer = "List", response = UserDTO.class, message = "User list retrieved successfully")}) @RequestMapping(method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<List<UserDTO>> getAll() { UserController.LOGGER.debug("fetching users from the database"); final List<UserDTO> userDTOList = this.userFacade.findAll(); return new ResponseEntity<>(userDTOList, HttpStatus.OK); } @ApiOperation( value = "Retrieves one user from the database. ", response = UserDTO.class) @ApiResponses({ @ApiResponse(code = 200, responseContainer = "List", response = UserDTO.class, message = "User retrieved successfully")}) @RequestMapping(value = UserController.EMAIL, method = RequestMethod.GET) public ResponseEntity<UserDTO> getByEmail(@RequestParam("email") final String email) { UserController.LOGGER.debug("fetching users from the database based on email"); return new ResponseEntity<>(this.userFacade.getByEmail(email), HttpStatus.OK); } @RequestMapping(method = RequestMethod.POST) public ResponseEntity<Void> saveUser(@Valid @RequestBody final UserDTO userDTO, final UriComponentsBuilder ucBuilder) { UserController.LOGGER.debug("creating new user"); this.userFacade.save(userDTO); final HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setLocation(ucBuilder.path("/users/{id}").buildAndExpand(userDTO.getUsername()).toUri()); return new ResponseEntity<>(httpHeaders, HttpStatus.CREATED); } @ApiOperation( value = "Removes user based on email", response = UserDTO.class) @ApiResponses({ @ApiResponse(code = 200, responseContainer = "List", response = UserDTO.class, message = "User successfully removed")}) @RequestMapping(value = UserController.BY_ID, method = RequestMethod.DELETE) public ResponseEntity<Void> delete(@PathVariable("id") final Long id) { UserController.LOGGER.debug("removing user based on email"); final UserDTO userDTO = this.userFacade.getById(id); //TODO: USE deleteById at repository level this.userFacade.delete(userDTO); return new ResponseEntity<>(HttpStatus.OK); } }
923d3f1c7d6a6c3d04b95a711de631bd02002951
922
java
Java
product-service/src/main/java/org/efbiz/product/facility/model/FacilityLocationKey.java
efbiz/efbiz-service
142087cdd078e5b5081cd05643948ae726662c1e
[ "Apache-2.0" ]
null
null
null
product-service/src/main/java/org/efbiz/product/facility/model/FacilityLocationKey.java
efbiz/efbiz-service
142087cdd078e5b5081cd05643948ae726662c1e
[ "Apache-2.0" ]
null
null
null
product-service/src/main/java/org/efbiz/product/facility/model/FacilityLocationKey.java
efbiz/efbiz-service
142087cdd078e5b5081cd05643948ae726662c1e
[ "Apache-2.0" ]
null
null
null
25.611111
82
0.664859
1,000,242
package org.efbiz.product.facility.model; import com.google.gson.Gson; import java.io.Serializable; import org.efbiz.common.model.ObjectValue; public class FacilityLocationKey extends ObjectValue implements Serializable { private String facilityId; private String locationSeqId; private static final long serialVersionUID = 1L; public String getFacilityId() { return facilityId; } public void setFacilityId(String facilityId) { this.facilityId = facilityId == null ? null : facilityId.trim(); } public String getLocationSeqId() { return locationSeqId; } public void setLocationSeqId(String locationSeqId) { this.locationSeqId = locationSeqId == null ? null : locationSeqId.trim(); } @Override public String toString() { Gson gson = new Gson(); return gson.toJson(this); } }
923d401d9160fdeded76f92288ebf0bbea353c59
3,477
java
Java
hapi-fhir-structures-r4/src/main/java/org/hl7/fhir/r4/model/codesystems/ImmunizationProgramEligibility.java
santoshkumar2016/hapi-fhir
72cf22e3a9a8de5c564a31281e6b7c05ba5d98b6
[ "Apache-2.0" ]
null
null
null
hapi-fhir-structures-r4/src/main/java/org/hl7/fhir/r4/model/codesystems/ImmunizationProgramEligibility.java
santoshkumar2016/hapi-fhir
72cf22e3a9a8de5c564a31281e6b7c05ba5d98b6
[ "Apache-2.0" ]
null
null
null
hapi-fhir-structures-r4/src/main/java/org/hl7/fhir/r4/model/codesystems/ImmunizationProgramEligibility.java
santoshkumar2016/hapi-fhir
72cf22e3a9a8de5c564a31281e6b7c05ba5d98b6
[ "Apache-2.0" ]
2
2017-12-04T16:09:40.000Z
2019-02-08T07:56:59.000Z
39.511364
114
0.645959
1,000,243
package org.hl7.fhir.r4.model.codesystems; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Generated on Tue, Jan 9, 2018 14:51-0500 for FHIR v3.2.0 import org.hl7.fhir.exceptions.FHIRException; public enum ImmunizationProgramEligibility { /** * The patient is not eligible for the funding program. */ INELIGIBLE, /** * The patient is eligible for the funding program because they are uninsured. */ UNINSURED, /** * added to help the parsers */ NULL; public static ImmunizationProgramEligibility fromCode(String codeString) throws FHIRException { if (codeString == null || "".equals(codeString)) return null; if ("ineligible".equals(codeString)) return INELIGIBLE; if ("uninsured".equals(codeString)) return UNINSURED; throw new FHIRException("Unknown ImmunizationProgramEligibility code '"+codeString+"'"); } public String toCode() { switch (this) { case INELIGIBLE: return "ineligible"; case UNINSURED: return "uninsured"; default: return "?"; } } public String getSystem() { return "http://hl7.org/fhir/immunization-program-eligibility"; } public String getDefinition() { switch (this) { case INELIGIBLE: return "The patient is not eligible for the funding program."; case UNINSURED: return "The patient is eligible for the funding program because they are uninsured."; default: return "?"; } } public String getDisplay() { switch (this) { case INELIGIBLE: return "Not Eligible"; case UNINSURED: return "Uninsured"; default: return "?"; } } }
923d408af700a9b359ee9f3e2159676ba8785816
1,077
java
Java
src/test/java/ctciCh4/testListOfDepths4Dot3.java
asarenski/algorithms-and-data-structures
c10e0abd3ae36839d91004cd6df1e321c35da763
[ "MIT" ]
null
null
null
src/test/java/ctciCh4/testListOfDepths4Dot3.java
asarenski/algorithms-and-data-structures
c10e0abd3ae36839d91004cd6df1e321c35da763
[ "MIT" ]
null
null
null
src/test/java/ctciCh4/testListOfDepths4Dot3.java
asarenski/algorithms-and-data-structures
c10e0abd3ae36839d91004cd6df1e321c35da763
[ "MIT" ]
null
null
null
23.413043
70
0.622098
1,000,244
package ctciCh4; import basicStructures.BSTree; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import util.TreeNode; public class testListOfDepths4Dot3 { TreeNode<Integer> root; BSTree<Integer> tree; ListOfDepths4Dot3 fourDotThree; @Before public void setUp() throws Exception { root = new TreeNode<>(5); tree = new BSTree<>(root); TreeNode<Integer> l1 = new TreeNode<>(3); TreeNode<Integer> r1 = new TreeNode<>(6); root.setLeft(l1); root.setRight(r1); TreeNode<Integer> ll1 = new TreeNode<>(1); TreeNode<Integer> lr1 = new TreeNode<>(2); l1.setLeft(ll1); l1.setRight(lr1); TreeNode<Integer> rr1 = new TreeNode<>(7); r1.setRight(rr1); fourDotThree = new ListOfDepths4Dot3(root); fourDotThree.loadLists(); } @Test public void test() { Assert.assertEquals(fourDotThree.getListAtDepth(0).size(), 1); } @Test public void testPrintList() { fourDotThree.printLists(); } }
923d40f327ee519f5a70dbcce0fb448e78fab233
10,292
java
Java
tis-taskflow/src/main/java/com/qlangtech/tis/dump/hive/HiveRemoveHistoryDataTask.java
jhonyang/tis-solr
ab1dfe0bc4a4d2ab78709b2d271f153988285d30
[ "MIT" ]
1
2019-09-26T03:08:34.000Z
2019-09-26T03:08:34.000Z
tis-taskflow/src/main/java/com/qlangtech/tis/dump/hive/HiveRemoveHistoryDataTask.java
jhonyang/tis-solr
ab1dfe0bc4a4d2ab78709b2d271f153988285d30
[ "MIT" ]
null
null
null
tis-taskflow/src/main/java/com/qlangtech/tis/dump/hive/HiveRemoveHistoryDataTask.java
jhonyang/tis-solr
ab1dfe0bc4a4d2ab78709b2d271f153988285d30
[ "MIT" ]
null
null
null
29.155807
100
0.698407
1,000,245
/* * The MIT License * * Copyright (c) 2018-2022, qinglangtech Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.qlangtech.tis.dump.hive; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.qlangtech.tis.common.utils.TSearcherConfigFetcher; import com.qlangtech.tis.dump.hive.HiveDBUtils.ResultProcess; /* * * @author 百岁(baisui@qlangtech.com) * @date 2019年1月17日 */ public class HiveRemoveHistoryDataTask { private static final Logger log = LoggerFactory.getLogger(HiveRemoveHistoryDataTask.class); private final String tableName; private static final int MAX_PARTITION_SAVE = 1; // daily ps name private final String pt = "pt"; private final String userName; private final FileSystem fileSystem; // private final Connection hiveConnection; public static void main(String[] arg) { // Matcher matcher = INDEX_NAME_PATTERN.matcher("4xxxxx"); // if (!matcher.matches()) { // throw new IllegalStateException( // "table name is not illegal,tableName:"); // } // // System.out.println(matcher.group(2)); List<PathInfo> timestampList = new ArrayList<PathInfo>(); PathInfo path = null; for (int i = 0; i < 100; i++) { path = new PathInfo(); path.setTimeStamp(i); timestampList.add(path); } sortTimestamp(timestampList); for (PathInfo info : timestampList) { System.out.println(info.timeStamp); } } public HiveRemoveHistoryDataTask(// , String tableName, // , String userName, // , FileSystem fileSystem) // Connection // hiveConnection { super(); if (StringUtils.isBlank(tableName)) { throw new IllegalArgumentException("tableName can not be null"); } this.tableName = tableName; this.userName = userName; this.fileSystem = fileSystem; // this.hiveConnection = hiveConnection; } public String getTableName() { return tableName; } // 20160106131304 public static final Pattern DATE_PATTERN = Pattern.compile("20\\d{12}"); /** * @param execConetxt * @param t * @throws Exception * @throws IOException * @throws FileNotFoundException */ public void deleteHdfsHistoryFile(Connection hiveConnection) throws Exception { this.deleteMetadata(); this.deleteHdfsFile(false); // 索引数据: /search4totalpay/all/0/output/20160104003306 this.deleteHdfsFile(true); this.dropHistoryHiveTable(hiveConnection); } /** * 删除dump的metadata<br> * example:/search4customerregistercard/all/20160106131304 * * @param execConetxt */ private void deleteMetadata() throws Exception { String hdfsPath = getJoinTableStorePath(this.userName, this.getTableName()) + "/all"; FileSystem fileSys = this.fileSystem; Path parent = new Path(hdfsPath); if (!fileSys.exists(parent)) { return; } FileStatus[] child = fileSys.listStatus(parent); List<PathInfo> timestampList = new ArrayList<PathInfo>(); PathInfo pathinfo = null; Matcher matcher = null; for (FileStatus c : child) { matcher = DATE_PATTERN.matcher(c.getPath().getName()); if (matcher.matches()) { pathinfo = new PathInfo(); pathinfo.pathName = c.getPath().getName(); pathinfo.timeStamp = Long.parseLong(matcher.group()); timestampList.add(pathinfo); } } deleteOldHdfsfile(fileSys, parent, timestampList); } /** * @param fileSys * @param parent * @param timestampList * @throws IOException */ public static void deleteOldHdfsfile(FileSystem fileSys, Path parent, List<PathInfo> timestampList) throws IOException { sortTimestamp(timestampList); Path toDelete = null; for (int index = (MAX_PARTITION_SAVE); index < timestampList.size(); index++) { toDelete = new Path(parent, timestampList.get(index).pathName); // 删除历史数据 log.info("history old hdfs file path:" + toDelete.toString() + " delete,success:" + fileSys.delete(toDelete, true) + ",getMaxPartitionSave:" + MAX_PARTITION_SAVE); } } public static class PathInfo { private long timeStamp; private String pathName; public long getTimeStamp() { return timeStamp; } public void setTimeStamp(long timeStamp) { this.timeStamp = timeStamp; } public String getPathName() { return pathName; } public void setPathName(String pathName) { this.pathName = pathName; } } /** * 删除历史索引build文件 * * @throws IOException * @throws FileNotFoundException */ public void removeHistoryBuildFile() throws IOException, FileNotFoundException { this.deleteHdfsFile(true); } /** * 删除hdfs中的文件 * * @param execConetxt * @param fileSys * @param t * @throws IOException * @throws FileNotFoundException */ private void deleteHdfsFile(boolean isBuildFile) throws IOException, FileNotFoundException { String hdfsPath = null; // dump数据:/search4totalpay/all/0/20160105003307 hdfsPath = getJoinTableStorePath(this.userName, this.getTableName()) + "/all"; FileSystem fileSys = this.fileSystem; int group = 0; List<PathInfo> dumptimestamps = null; PathInfo pathinfo = null; FileStatus[] child = null; Path parent = null; while (true) { parent = new Path(hdfsPath + "/" + (group++)); if (isBuildFile) { parent = new Path(parent.toString(), "output"); } if (!fileSys.exists(parent)) { break; } child = fileSys.listStatus(parent); dumptimestamps = new ArrayList<PathInfo>(); pathinfo = new PathInfo(); for (FileStatus f : child) { try { pathinfo = new PathInfo(); pathinfo.pathName = f.getPath().getName(); pathinfo.timeStamp = Long.parseLong(f.getPath().getName()); dumptimestamps.add(pathinfo); } catch (Throwable e) { } } deleteOldHdfsfile(fileSys, parent, dumptimestamps); } } /** * @param dumptimestamps */ private static void sortTimestamp(List<PathInfo> timestampList) { // 最大的应该的index为0的位置上 Collections.sort(timestampList, new Comparator<PathInfo>() { @Override public int compare(PathInfo o1, PathInfo o2) { return (int) (o2.timeStamp - o1.timeStamp); } }); } private static final Pattern INDEX_NAME_PATTERN = Pattern.compile("(search4)?(.+)"); /** * 删除hive中的历史表 */ public void dropHistoryHiveTable(Connection hiveConn) { Matcher matcher = INDEX_NAME_PATTERN.matcher(this.tableName); if (!matcher.matches()) { throw new IllegalStateException("table name is not illegal,tableName:" + this.tableName); } final String hiveTableName = matcher.group(2); if (StringUtils.isBlank(pt)) { throw new IllegalStateException("pt name shall be set"); } // HiveTaskFactory.getConnection(this.getContext()); Connection conn = hiveConn; final Set<String> ptSet = new HashSet<String>(); try { final AtomicBoolean isExist = new AtomicBoolean(false); // 判断表是否存在 String showTables = "show tables like '" + hiveTableName + "'"; HiveDBUtils.getInstance().query(conn, showTables, new ResultProcess() { @Override public void callback(ResultSet result) throws Exception { isExist.set(true); } }); if (!isExist.get()) { // 表不存在 log.info(hiveTableName + " is not exist"); return; } final String showPartition = "show partitions " + hiveTableName; final Pattern ptPattern = Pattern.compile(pt + "=(\\d+)"); HiveDBUtils.getInstance().query(conn, showPartition, new ResultProcess() { @Override public void callback(ResultSet result) throws Exception { Matcher matcher = ptPattern.matcher(result.getString(1)); if (matcher.find()) { ptSet.add(matcher.group(1)); } else { log.warn(hiveTableName + ",partition" + result.getString(1) + ",is not match pattern:" + ptPattern); } // } }); List<String> ptList = new LinkedList<>(ptSet); Collections.sort(ptList); int count = 0; log.info("maxPartitionSave:" + MAX_PARTITION_SAVE); for (int i = ptList.size() - 1; i >= 0; i--) { if ((++count) > MAX_PARTITION_SAVE) { String alterSql = "alter table " + hiveTableName + " drop partition ( " + pt + " = '" + ptList.get(i) + "' )"; try { HiveDBUtils.getInstance().execute(conn, alterSql); } catch (Throwable e) { log.error("alterSql:" + alterSql, e); } log.info("history table:" + hiveTableName + ", partition:" + this.pt + "='" + ptList.get(i) + "', have been removed"); } } } catch (Exception e) { throw new RuntimeException(e); } } public static String getJoinTableStorePath(String user, String targetTableName) { return TSearcherConfigFetcher.get().getHDFSRootDir() + "/" + targetTableName; } public String getPt() { return pt; } // /** // * 这个标记位表示在绑定表的时候 是否需要绑定hive表,因为宽表是不需要绑定的 // * // * @return // */ // public boolean isBindtable() { // return bindtable; // } }
923d4137800354c62fc40b70f4a93863555479d8
4,934
java
Java
src/test/java/net/oneandone/lavender/index/IndexTest.java
mlhartme/lavender
b8e03689216d36cb6bd5345a96d1414bbb23f5b0
[ "Apache-2.0" ]
1
2018-06-27T00:07:02.000Z
2018-06-27T00:07:02.000Z
src/test/java/net/oneandone/lavender/index/IndexTest.java
mlhartme/lavender
b8e03689216d36cb6bd5345a96d1414bbb23f5b0
[ "Apache-2.0" ]
8
2015-09-23T04:55:50.000Z
2020-12-17T09:49:47.000Z
src/test/java/net/oneandone/lavender/index/IndexTest.java
mlhartme/lavender
b8e03689216d36cb6bd5345a96d1414bbb23f5b0
[ "Apache-2.0" ]
6
2015-09-21T11:09:10.000Z
2021-01-12T14:00:30.000Z
38.183333
126
0.700131
1,000,246
/* * Copyright 1&1 Internet AG, https://github.com/1and1/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.oneandone.lavender.index; import net.oneandone.sushi.fs.World; import net.oneandone.sushi.fs.file.FileNode; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; public class IndexTest { private static final World WORLD = World.createMinimal(); private FileNode indexFile; private Index index; @BeforeEach public void setup() throws IOException { indexFile = WORLD.getTemp().createTempFile(); index = new Index(); index.add(new Label("img/close.gif", "app/kgfhvu9qnh3mr6eel97y6fq2hezzol8z-close.gif", Hex.decodeString("9jnerlff23u8ed01np9g6ysbhsh0dvcs"))); index.save(indexFile); } @Test public void testWriteToExistingFile() throws IOException { Label l1 = new Label("img/test.png", "app/kgfhvu9qnh3mr6eel97y6fq2hezzol8z-test.png", Hex.decodeString("kgfhvu9qnh3mr6eel97y6fq2hezzol8z")); Label l2 = new Label("modules/stageassistent/img/test.gif", "stageassistent/kgfhvu9qnh3mr6eel97y6fq2hezzol8z-test.gif", Hex.decodeString("kgfhvu9qnh3mr6eel97y6fq2hezzol8z")); index.add(l1); index.add(l2); index.save(indexFile); assertTrue(indexFile.exists()); String readFileToString = indexFile.readString(); assertTrue(readFileToString.contains("img/close.gif=app/kgfhvu9qnh3mr6eel97y6fq2hezzol8z-close.gif\\:9jnerlff23u8ed01np9g6ysbhsh0dvcs")); assertTrue(readFileToString.contains("img/test.png=app/kgfhvu9qnh3mr6eel97y6fq2hezzol8z-test.png\\:9jnerlff23u8ed01np9g6ysbhsh0dvcs")); assertTrue(readFileToString .contains("modules/stageassistent/img/test.gif=stageassistent/kgfhvu9qnh3mr6eel97y6fq2hezzol8z-test.gif\\:9jnerlff23u8ed01np9g6ysbhsh0dvcs")); } @Test public void testWriteToNonExistingFile() throws IOException { FileNode nonexistingfile = WORLD.getTemp().createTempFile().deleteFile(); assertFalse(nonexistingfile.exists()); Index myIndex = new Index(); Label l1 = new Label("img/test.png", "app/kgfhvu9qnh3mr6eel97y6fq2hezzol8z-test.png", Hex.decodeString("kgfhvu9qnh3mr6eel97y6fq2hezzol8z")); Label l2 = new Label("modules/stageassistent/img/test.gif", "stageassistent/kgfhvu9qnh3mr6eel97y6fq2hezzol8z-test.gif", Hex.decodeString("kgfhvu9qnh3mr6eel97y6fq2hezzol8z")); myIndex.add(l1); myIndex.add(l2); myIndex.save(nonexistingfile); assertTrue(nonexistingfile.exists()); String readFileToString = nonexistingfile.readString(); assertTrue(readFileToString.contains("img/test.png=app/kgfhvu9qnh3mr6eel97y6fq2hezzol8z-test.png\\:9jnerlff23u8ed01np9g6ysbhsh0dvcs")); assertTrue(readFileToString .contains("modules/stageassistent/img/test.gif=stageassistent/kgfhvu9qnh3mr6eel97y6fq2hezzol8z-test.gif\\:9jnerlff23u8ed01np9g6ysbhsh0dvcs")); } @Test public void testLookup() { Label label = index.lookup("img/close.gif"); assertNotNull(label); assertEquals("app/kgfhvu9qnh3mr6eel97y6fq2hezzol8z-close.gif", label.getLavendelizedPath()); assertEquals("9jnerlff23u8ed01np9g6ysbhsh0dvcs", Hex.encodeString(label.md5())); } @Test public void testLookupNonExistingRef() { assertNull(index.lookup("img/nonexisting.gif")); } @Test public void testPropertiesConstructor() throws Exception { Index.load(indexFile); } @Test() public void testPropertiesConstructorNonExistingFile() throws Exception { assertThrows(IOException.class, () -> { Index.load(indexFile.join("file:///nosuchfile")); }); } @Test() public void testPropertiesConstructorCorruptPropertiesFile() throws Exception { indexFile.writeString("\\u00"); assertThrows(RuntimeException.class, () -> { Index.load(indexFile); }); } }
923d43321663bf29f1bac7d72cdb8860f1ae8ba7
93
java
Java
rxjava2-jdbc/src/main/java/org/davidmoten/rx/jdbc/callable/internal/ParameterPlaceholder.java
kazabubu/rxjava2-jdbc
de677ed0ef0a91dfe6b64c7246253c6f40e67e70
[ "Apache-2.0" ]
393
2017-02-05T21:25:11.000Z
2022-03-31T19:40:57.000Z
rxjava2-jdbc/src/main/java/org/davidmoten/rx/jdbc/callable/internal/ParameterPlaceholder.java
kazabubu/rxjava2-jdbc
de677ed0ef0a91dfe6b64c7246253c6f40e67e70
[ "Apache-2.0" ]
69
2017-09-19T15:31:46.000Z
2022-03-26T09:06:16.000Z
rxjava2-jdbc/src/main/java/org/davidmoten/rx/jdbc/callable/internal/ParameterPlaceholder.java
kazabubu/rxjava2-jdbc
de677ed0ef0a91dfe6b64c7246253c6f40e67e70
[ "Apache-2.0" ]
44
2017-05-26T18:32:59.000Z
2021-10-10T14:05:12.000Z
18.6
49
0.827957
1,000,247
package org.davidmoten.rx.jdbc.callable.internal; public interface ParameterPlaceholder { }
923d435a276e4fcaa3a97b64382987da95274e55
3,864
java
Java
src/com/ms/silverking/cloud/dht/client/test/RequiredPreviousVersionTest.java
duyangzhou/SilverKing
b1b582f96d3771c01bf8239c64e99869f54bb3a1
[ "Apache-2.0" ]
null
null
null
src/com/ms/silverking/cloud/dht/client/test/RequiredPreviousVersionTest.java
duyangzhou/SilverKing
b1b582f96d3771c01bf8239c64e99869f54bb3a1
[ "Apache-2.0" ]
null
null
null
src/com/ms/silverking/cloud/dht/client/test/RequiredPreviousVersionTest.java
duyangzhou/SilverKing
b1b582f96d3771c01bf8239c64e99869f54bb3a1
[ "Apache-2.0" ]
null
null
null
43.909091
118
0.662267
1,000,248
package com.ms.silverking.cloud.dht.client.test; import com.ms.silverking.cloud.dht.NamespaceVersionMode; import com.ms.silverking.cloud.dht.PutOptions; import com.ms.silverking.cloud.dht.RevisionMode; import com.ms.silverking.cloud.dht.client.DHTSession; import com.ms.silverking.cloud.dht.client.FailureCause; import com.ms.silverking.cloud.dht.client.Namespace; import com.ms.silverking.cloud.dht.client.PutException; import com.ms.silverking.cloud.dht.client.SynchronousNamespacePerspective; import com.ms.silverking.collection.Pair; import com.ms.silverking.log.Log; public class RequiredPreviousVersionTest extends BaseClientTest { public static final String testName = "RequiredPreviousVersionTest"; private static final String testKey = "k1"; private static final String initialValue = "v1.1"; private static final String failedPutValue = "v1.2"; private static final String modifiedValue = "v1.3"; private static final String modifiedValue2 = "v1.4"; public RequiredPreviousVersionTest() { super(testName, NamespaceVersionMode.CLIENT_SPECIFIED, RevisionMode.NO_REVISIONS); } @Override public Pair<Integer,Integer> runTest(DHTSession session, Namespace ns) { SynchronousNamespacePerspective<String,String> syncNSP; syncNSP = ns.openSyncPerspective(ns.getDefaultNSPOptions(String.class, String.class)); return testRequiredPreviousVersion(syncNSP); } public Pair<Integer,Integer> testRequiredPreviousVersion(SynchronousNamespacePerspective<String,String> syncNSP) { int successful; int failed; successful = 0; failed = 0; try { PutOptions defaultPutOptions; defaultPutOptions = syncNSP.getNamespace().getOptions().getDefaultPutOptions(); System.out.println("Writing"); syncNSP.put(testKey, initialValue, defaultPutOptions.version(1)); // Test the advisory lock System.out.println("Writing - should fail due to version <= requiredPreviousVersion"); try { syncNSP.put(testKey, failedPutValue, defaultPutOptions.requiredPreviousVersion(2).version(2)); throw new RuntimeException("Failed to generate IllegalArgumentException"); } catch (IllegalArgumentException iae) { // Expected System.out.println("Correctly generated IllegalArgumentException"); } checkValue(syncNSP, testKey, initialValue); System.out.println("Writing - should fail due to requiredPreviousVersion not met"); try { syncNSP.put(testKey, failedPutValue, defaultPutOptions.requiredPreviousVersion(5).version(6)); } catch (PutException pe) { if (pe.getFailureCause(testKey) == FailureCause.INVALID_VERSION) { System.out.println("Correctly detected invalid version"); } else { throw new RuntimeException("Unexpected failure", pe); } } checkValue(syncNSP, testKey, initialValue); // Test requiredPreviousVersion syncNSP.put(testKey, modifiedValue, defaultPutOptions.requiredPreviousVersion(1).version(2)); checkValue(syncNSP, testKey, modifiedValue); // Test requiredPreviousVersion syncNSP.put(testKey, modifiedValue2, defaultPutOptions.requiredPreviousVersion(2).version(3)); checkValue(syncNSP, testKey, modifiedValue2); ++successful; } catch (Exception e) { Log.logErrorWarning(e, "testRequiredPreviousVersion failed"); ++failed; } return Pair.of(successful, failed); } }
923d43728c8b86c367f89eb547d95e43b9ef40a7
826
java
Java
spring-digger/common/common-base/src/main/java/com/klaus/interview/commonbase/exception/BaseException.java
olderzhou/spring-2019
a1a4db3ec93ea5a6cc0ac8373ade1286aba5e4dc
[ "MIT" ]
null
null
null
spring-digger/common/common-base/src/main/java/com/klaus/interview/commonbase/exception/BaseException.java
olderzhou/spring-2019
a1a4db3ec93ea5a6cc0ac8373ade1286aba5e4dc
[ "MIT" ]
null
null
null
spring-digger/common/common-base/src/main/java/com/klaus/interview/commonbase/exception/BaseException.java
olderzhou/spring-2019
a1a4db3ec93ea5a6cc0ac8373ade1286aba5e4dc
[ "MIT" ]
null
null
null
22.944444
80
0.684019
1,000,249
package com.klaus.interview.commonbase.exception; import com.klaus.interview.commonbase.error.ErrorType; import com.klaus.interview.commonbase.error.SystemErrorType; import lombok.Getter; @Getter public class BaseException extends RuntimeException { /** * 异常对应的错误类型 */ private final ErrorType errorType; /** * 默认是系统异常 */ public BaseException() { this.errorType = SystemErrorType.SYSTEM_ERROR; } public BaseException(ErrorType errorType) { this.errorType = errorType; } public BaseException(ErrorType errorType, String message) { super(message); this.errorType = errorType; } public BaseException(ErrorType errorType, String message, Throwable cause) { super(message, cause); this.errorType = errorType; } }
923d441c239b0051468b5f821145c03b28e0e239
1,208
java
Java
src/test/java/au/com/codeka/carrot/util/RenderHelper.java
codeka/carrot
39d1e4ff88ba8b2ed6c14537e3d083875487a75a
[ "Apache-2.0" ]
14
2016-09-09T10:38:50.000Z
2020-10-05T10:48:54.000Z
src/test/java/au/com/codeka/carrot/util/RenderHelper.java
codeka/carrot
39d1e4ff88ba8b2ed6c14537e3d083875487a75a
[ "Apache-2.0" ]
37
2017-07-06T20:54:50.000Z
2020-05-22T18:33:16.000Z
src/test/java/au/com/codeka/carrot/util/RenderHelper.java
codeka/carrot
39d1e4ff88ba8b2ed6c14537e3d083875487a75a
[ "Apache-2.0" ]
9
2017-07-06T16:26:23.000Z
2021-01-21T08:15:38.000Z
31.789474
90
0.681291
1,000,250
package au.com.codeka.carrot.util; import au.com.codeka.carrot.CarrotEngine; import au.com.codeka.carrot.CarrotException; import au.com.codeka.carrot.Configuration; import au.com.codeka.carrot.bindings.MapBindings; import au.com.codeka.carrot.resource.MemoryResourceLocator; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; /** * Helpers for rendering templates in tests. */ public class RenderHelper { public static String render(String content, Object... bindings) throws CarrotException { CarrotEngine engine = new CarrotEngine(new Configuration.Builder() .setLogger(new Configuration.Logger() { @Override public void print(int level, String msg) { if (level > Configuration.Logger.LEVEL_DEBUG) { System.err.println(msg); } } }) .setResourceLocator(new MemoryResourceLocator.Builder().add("index", content)) .build()); Map<String, Object> bindingsMap = new HashMap<>(); for (int i = 0; i < bindings.length; i += 2) { bindingsMap.put(bindings[i].toString(), bindings[i + 1]); } return engine.process("index", new MapBindings(bindingsMap)); } }
923d4426b48a1b6df76712e3861e24cc20f3d4c1
220
java
Java
src/main/java/json/sql/commands/exception/ProcessingException.java
saranrajj/json-sql
394b7e6cb85267c7ca1b26e856fd839242cca942
[ "Apache-2.0" ]
null
null
null
src/main/java/json/sql/commands/exception/ProcessingException.java
saranrajj/json-sql
394b7e6cb85267c7ca1b26e856fd839242cca942
[ "Apache-2.0" ]
5
2019-11-28T23:06:33.000Z
2021-12-09T21:59:41.000Z
src/main/java/json/sql/commands/exception/ProcessingException.java
saranrajj/json-sql
394b7e6cb85267c7ca1b26e856fd839242cca942
[ "Apache-2.0" ]
null
null
null
20
58
0.8
1,000,251
package json.sql.commands.exception; public class ProcessingException extends JsonSqlException{ public ProcessingException(String errorMessage) { super(errorMessage); // TODO Auto-generated constructor stub } }
923d44a235e4324cc7dce319fb1255581f9811f1
1,164
java
Java
src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue_2.java
contextshuffling/fastjson
3f72c76aebb4c0a60ad8ed9e7afa7126a011cf8d
[ "Apache-2.0" ]
28,056
2015-01-01T12:01:05.000Z
2022-03-31T14:16:43.000Z
src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue_2.java
contextshuffling/fastjson
3f72c76aebb4c0a60ad8ed9e7afa7126a011cf8d
[ "Apache-2.0" ]
3,688
2015-01-03T15:42:09.000Z
2022-03-31T19:01:45.000Z
src/test/java/com/alibaba/json/bvt/path/JSONPath_containsValue_2.java
contextshuffling/fastjson
3f72c76aebb4c0a60ad8ed9e7afa7126a011cf8d
[ "Apache-2.0" ]
7,752
2015-01-03T08:37:26.000Z
2022-03-31T09:59:18.000Z
37.548387
82
0.679553
1,000,252
package com.alibaba.json.bvt.path; import org.junit.Assert; import com.alibaba.fastjson.JSONPath; import junit.framework.TestCase; public class JSONPath_containsValue_2 extends TestCase { public void test_root() throws Exception { Model model = new Model(); model.value = 1001; Assert.assertTrue(JSONPath.containsValue(model, "/value", 1001)); Assert.assertTrue(JSONPath.containsValue(model, "/value", 1001L)); Assert.assertTrue(JSONPath.containsValue(model, "/value", (short) 1001)); Assert.assertTrue(JSONPath.containsValue(model, "/value", 1001F)); Assert.assertTrue(JSONPath.containsValue(model, "/value", 1001D)); Assert.assertFalse(JSONPath.containsValue(model, "/value", 1002)); Assert.assertFalse(JSONPath.containsValue(model, "/value", 1002L)); Assert.assertFalse(JSONPath.containsValue(model, "/value", (short) 1002)); Assert.assertFalse(JSONPath.containsValue(model, "/value", 1002F)); Assert.assertFalse(JSONPath.containsValue(model, "/value", 1002D)); } public static class Model { public int value; } }
923d44ad8d92cae630c530b379007207e4047587
5,407
java
Java
src/main/java/Vistas/ListadoEspectaculos.java
Makorli/Espectaculos_AD_PRJ
3823d7b5e4217587e53abcae82ac8cfb592fb326
[ "CC0-1.0" ]
null
null
null
src/main/java/Vistas/ListadoEspectaculos.java
Makorli/Espectaculos_AD_PRJ
3823d7b5e4217587e53abcae82ac8cfb592fb326
[ "CC0-1.0" ]
null
null
null
src/main/java/Vistas/ListadoEspectaculos.java
Makorli/Espectaculos_AD_PRJ
3823d7b5e4217587e53abcae82ac8cfb592fb326
[ "CC0-1.0" ]
null
null
null
29.872928
139
0.614759
1,000,253
package Vistas; import Controllers.ControladorEmpleado; import Controllers.ControladorEspectaculo; import Modelos.Empleado; import Modelos.Espectaculo; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; public class ListadoEspectaculos { private JPanel JPGeneral, JPListadoEspectaculo; private JLabel lbTituloParque, lbEspectaculo, lbIdEspectaculo, lbNombre, lbDescripcion, lbLugar, lbNumero, lbAforo, lbFecha, lbHorario, lbCoste, lbResponsable, lbBaja; private JCheckBox cbBaja; private JComboBox cbResponsable; private JTextField txtNombre, txtDescripcion, txtNumero, txtLugar, txtFecha, txtHorario, txtCoste, txtAforo; private JButton btnVolver; private JScrollPane JPListaEspectaculos; private JList<Espectaculo> lstEspectaculos; private JCheckBox cbVerEspectBajas; private ControladorEmpleado ce = new ControladorEmpleado(); private ControladorEspectaculo cs = new ControladorEspectaculo(); public ListadoEspectaculos() { lstEspectaculos.addListSelectionListener(e -> { Espectaculo espectaculo = lstEspectaculos.getSelectedValue(); if (espectaculo != null) { Empleado responsable = ce.selectById(espectaculo.getIdResponsable()); txtNumero.setText(String.format("%d", espectaculo.getNumero())); txtNombre.setText(espectaculo.getNombre()); txtAforo.setText(String.format("%d", espectaculo.getAforo())); txtDescripcion.setText(espectaculo.getDescripcion()); txtLugar.setText(espectaculo.getLugar()); txtCoste.setText(espectaculo.getCoste().toString()); txtFecha.setText(espectaculo.getFecha()); txtHorario.setText(espectaculo.getHorario()); cbBaja.setSelected(espectaculo.getBaja()); cbResponsable.setSelectedItem(responsable); } }); cbBaja.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { refrescar(); } }); btnVolver.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { autoDestroy(); } }); cbVerEspectBajas.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean state = cbVerEspectBajas.isSelected(); try { if (state) { limpiar(); mostrarEspectaculos(cs.selectByState(true)); } else { limpiar(); mostrarEspectaculos(cs.selectByState(false)); } } catch (NullPointerException ex) { } } }); } public void mostrarEspectaculos(List<Espectaculo> espectaculos) { DefaultListModel<Espectaculo> modelo = new DefaultListModel<>(); for (Espectaculo empleado : espectaculos) { modelo.addElement(empleado); } lstEspectaculos.setModel(modelo); } public void mostrarEspectaculo(int idEspectaculo) { DefaultListModel<Espectaculo> modelo = new DefaultListModel<>(); List<Espectaculo> espectaculos; espectaculos = cs.selectAll(); for (Espectaculo e : espectaculos) { if (e.getIdEspectaculo() == idEspectaculo) { modelo.addElement(e); } } lstEspectaculos.setModel(modelo); } public JPanel getJPListadoEspectaculo() { return JPListadoEspectaculo; } public void autoDestroy() { JPListadoEspectaculo.removeAll(); JPListadoEspectaculo.repaint(); } public void refrescar() { JPListadoEspectaculo.repaint(); } public void limpiar() { txtNumero.setText(""); txtNombre.setText(""); txtAforo.setText(""); txtDescripcion.setText(""); txtLugar.setText(""); txtCoste.setText(""); txtFecha.setText(""); txtHorario.setText(""); cbBaja.setSelected(false); cbResponsable.setSelectedItem(null); } public void loadCbResponsable(List<Empleado> responsables) { DefaultComboBoxModel<Empleado> defaultComboBoxModel = new DefaultComboBoxModel<Empleado>(); for (Empleado e : responsables) { defaultComboBoxModel.addElement(e); } cbResponsable.setModel(defaultComboBoxModel); cbResponsable.setRenderer(new responsableListCellRenderer()); } private class responsableListCellRenderer extends DefaultListCellRenderer { @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value instanceof Empleado) { Empleado e = (Empleado) value; value = e.getDni() + " - " + e.getApellidos(); } return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); } } }
923d46c85f85f5730bcadb707f8b83ead13e8597
1,642
java
Java
Java-OOP/Interfaces-and-abstraction/src/Exercise/Telephony/Smartphone.java
angelovvelizar/SoftUni
58485038128c7481d0103b805726a11e4ccf71e0
[ "MIT" ]
null
null
null
Java-OOP/Interfaces-and-abstraction/src/Exercise/Telephony/Smartphone.java
angelovvelizar/SoftUni
58485038128c7481d0103b805726a11e4ccf71e0
[ "MIT" ]
null
null
null
Java-OOP/Interfaces-and-abstraction/src/Exercise/Telephony/Smartphone.java
angelovvelizar/SoftUni
58485038128c7481d0103b805726a11e4ccf71e0
[ "MIT" ]
null
null
null
27.366667
95
0.512789
1,000,254
package Exercise.Telephony; import Exercise.Telephony.Browsable; import Exercise.Telephony.Callable; import java.util.List; public class Smartphone implements Callable, Browsable { private List<String> numbers; private List<String> urls; public Smartphone(List<String> numbers, List<String> urls) { this.numbers = numbers; this.urls = urls; } @Override public String browse() { StringBuilder sb = new StringBuilder(); for (String url : urls) { boolean isValid = true; for (int i = 0; i < url.length(); i++) { if(Character.isDigit(url.charAt(i))){ sb.append("Invalid URL!").append(System.lineSeparator()); isValid = false; break; } } if(isValid) { sb.append("Browsing: ").append(url).append("!").append(System.lineSeparator()); } } return sb.toString(); } @Override public String call() { StringBuilder sb = new StringBuilder(); for (String number : numbers) { boolean isValid = true; for (int i = 0; i < number.length(); i++) { if(!Character.isDigit(number.charAt(i))){ sb.append("Invalid number!").append(System.lineSeparator()); isValid = false; break; } } if(isValid) { sb.append("Calling... ").append(number).append(System.lineSeparator()); } } return sb.toString(); } }
923d470f8ee6e9926bb0372cd88099be8215bd4d
92
java
Java
src/net/m4christ/usb/GlobalConfigs.java
lijamie98/usb-copier
46a2e114f3719595a712781b7594ac7c8cfe4363
[ "Apache-2.0" ]
null
null
null
src/net/m4christ/usb/GlobalConfigs.java
lijamie98/usb-copier
46a2e114f3719595a712781b7594ac7c8cfe4363
[ "Apache-2.0" ]
null
null
null
src/net/m4christ/usb/GlobalConfigs.java
lijamie98/usb-copier
46a2e114f3719595a712781b7594ac7c8cfe4363
[ "Apache-2.0" ]
null
null
null
13.142857
28
0.695652
1,000,255
package net.m4christ.usb; public class GlobalConfigs { public GlobalConfigs() {} }
923d476eb7243e01f6f07250f31bd31bcc8239ee
1,259
java
Java
sbk-gem/src/main/java/io/sbk/logger/impl/GemRamPrometheusLogger.java
kmgowda/SBK
66fa367b29b5532a3628176663298286530ad325
[ "Apache-2.0" ]
27
2020-02-03T05:52:02.000Z
2022-01-22T05:44:19.000Z
sbk-gem/src/main/java/io/sbk/logger/impl/GemRamPrometheusLogger.java
neharika25/SBK
e5edf37b2ab7874182c420d4e3c3827ca9c2ce12
[ "Apache-2.0" ]
56
2020-02-14T11:03:11.000Z
2022-03-24T13:19:48.000Z
sbk-gem/src/main/java/io/sbk/logger/impl/GemRamPrometheusLogger.java
neharika25/SBK
e5edf37b2ab7874182c420d4e3c3827ca9c2ce12
[ "Apache-2.0" ]
56
2020-03-16T15:25:08.000Z
2022-03-21T10:42:43.000Z
32.282051
91
0.607625
1,000,256
/** * Copyright (c) KMG. 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 */ package io.sbk.logger.impl; import io.sbk.logger.GemLogger; public class GemRamPrometheusLogger extends RamPrometheusLogger implements GemLogger { @Override public String[] getOptionsArgs() { return new String[]{"-time", "-minlatency", "-maxlatency", "-csvfile", "-context"}; } @Override public String[] getParsedArgs() { if (csvEnable) { return new String[]{"-csvfile", csvFile, "-time", getTimeUnit().name(), "-minlatency", String.valueOf(getMinLatency()), "-maxlatency", String.valueOf(getMaxLatency()), "-context", metricsConfig.port + metricsConfig.context}; } return new String[]{"-time", getTimeUnit().name(), "-minlatency", String.valueOf(getMinLatency()), "-maxlatency", String.valueOf(getMaxLatency()), "-context", metricsConfig.port + metricsConfig.context}; } }
923d4926e3dfb289ff9a1e8703214ebfaf7a1ad8
3,204
java
Java
clustered/ehcache-client/src/main/java/org/ehcache/clustered/client/internal/store/lock/LockingServerStoreProxyImpl.java
LLcat1217/ehcache3
643d923e59967a2361ec104d76a823714e4687eb
[ "Apache-2.0" ]
1,900
2015-01-16T13:52:10.000Z
2022-03-31T02:30:15.000Z
clustered/ehcache-client/src/main/java/org/ehcache/clustered/client/internal/store/lock/LockingServerStoreProxyImpl.java
LLcat1217/ehcache3
643d923e59967a2361ec104d76a823714e4687eb
[ "Apache-2.0" ]
1,912
2015-01-05T22:27:45.000Z
2022-03-18T06:19:35.000Z
clustered/ehcache-client/src/main/java/org/ehcache/clustered/client/internal/store/lock/LockingServerStoreProxyImpl.java
LLcat1217/ehcache3
643d923e59967a2361ec104d76a823714e4687eb
[ "Apache-2.0" ]
632
2015-01-13T04:07:13.000Z
2022-02-25T08:57:49.000Z
27.152542
92
0.723159
1,000,257
/* * Copyright Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ehcache.clustered.client.internal.store.lock; import org.ehcache.clustered.client.internal.store.ServerStoreProxy; import org.ehcache.clustered.common.internal.store.Chain; import org.ehcache.clustered.common.internal.store.Element; import java.nio.ByteBuffer; import java.util.Iterator; import java.util.Map; import java.util.concurrent.TimeoutException; public class LockingServerStoreProxyImpl implements LockingServerStoreProxy { private final ServerStoreProxy storeProxy; private final LockManager lockManager; public LockingServerStoreProxyImpl(ServerStoreProxy storeProxy, LockManager lockManager) { this.storeProxy = storeProxy; this.lockManager = lockManager; } @Override public String getCacheId() { return storeProxy.getCacheId(); } @Override public void close() { storeProxy.close(); } @Override public ChainEntry lock(long key) throws TimeoutException { Chain chain = lockManager.lock(key); return new ChainEntry() { @Override public void append(ByteBuffer payLoad) throws TimeoutException { LockingServerStoreProxyImpl.this.append(key, payLoad); } @Override public void replaceAtHead(Chain equivalent) { LockingServerStoreProxyImpl.this.replaceAtHead(key, chain, equivalent); } @Override public boolean isEmpty() { return chain.isEmpty(); } @Override public int length() { return chain.length(); } @Override public Iterator<Element> iterator() { return chain.iterator(); } }; } @Override public void unlock(long key, boolean localonly) throws TimeoutException { lockManager.unlock(key, localonly); } @Override public ChainEntry get(long key) throws TimeoutException { return storeProxy.get(key); } @Override public void append(long key, ByteBuffer payLoad) throws TimeoutException { storeProxy.append(key, payLoad); } @Override public ChainEntry getAndAppend(long key, ByteBuffer payLoad) throws TimeoutException { return storeProxy.getAndAppend(key, payLoad); } @Override public void enableEvents(boolean enable) throws TimeoutException { storeProxy.enableEvents(enable); } @Override public void replaceAtHead(long key, Chain expect, Chain update) { storeProxy.replaceAtHead(key, expect, update); } @Override public void clear() throws TimeoutException { storeProxy.clear(); } @Override public Iterator<Map.Entry<Long, Chain>> iterator() throws TimeoutException { return storeProxy.iterator(); } }
923d497f8519d95800955ee97a40b8c6f49f33bf
3,437
java
Java
client/src/main/java/com/lzf/flyingsocks/client/proxy/http/AuthenticationStrategy.java
suyeq/flyingsocks
cd2aa86f5e472b28df236046297a33cb509ef6d7
[ "MIT" ]
78
2019-05-27T01:10:45.000Z
2022-03-31T12:31:31.000Z
client/src/main/java/com/lzf/flyingsocks/client/proxy/http/AuthenticationStrategy.java
suyeq/flyingsocks
cd2aa86f5e472b28df236046297a33cb509ef6d7
[ "MIT" ]
7
2019-06-23T13:04:19.000Z
2021-12-06T16:59:49.000Z
client/src/main/java/com/lzf/flyingsocks/client/proxy/http/AuthenticationStrategy.java
suyeq/flyingsocks
cd2aa86f5e472b28df236046297a33cb509ef6d7
[ "MIT" ]
34
2019-06-03T14:31:51.000Z
2022-03-31T12:30:03.000Z
29.886957
105
0.682281
1,000,258
/* * Copyright (c) 2019 abc123lzf <hzdkv@example.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.lzf.flyingsocks.client.proxy.http; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.http.HttpHeaderNames; import org.apache.commons.lang3.StringUtils; import java.util.Base64; /** * HTTP代理认证逻辑 * 基于请求头proxy-authorization实现 * 具体规范参考<a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Proxy-Authorization" /> * * @see HttpHeaderNames#PROXY_AUTHORIZATION * @author lzf hzdkv@example.com * @since 2021/1/23 1:00 */ interface AuthenticationStrategy { /** * 认证未通过或者未发送认证信息时响应头包含的proxy-authenticate字段 * * @return proxy-authenticate字段值 */ String proxyAuthenticateHeader(); /** * 执行认证 * * @param type 认证类型 * @param credentials 认证凭据 * @return 认证是否通过 */ boolean grantAuthorization(String type, String credentials); /** * 认证成功后对{@link ChannelPipeline}的操作 * * @param pipeline 当前HTTP代理连接管道对象 * @param type 认证类型 * @param credentials 认证凭据 */ default void afterAuthorizationSuccess(ChannelPipeline pipeline, String type, String credentials) { } } /** * 固定用户名和密码 */ class SimpleAuthenticationStrategy implements AuthenticationStrategy { private final String username; private final String password; public SimpleAuthenticationStrategy(String username, String password) { if (StringUtils.isAnyBlank(username, password)) { throw new IllegalArgumentException(); } this.username = username; this.password = password; } @Override public String proxyAuthenticateHeader() { return "Basic realm=\"flyingsocks HTTP Proxy service\""; } @Override public boolean grantAuthorization(String type, String credentials) { if (StringUtils.isBlank(type) || StringUtils.isBlank(credentials)) { return false; } if (!type.equals("Basic")) { return false; } try { String[] arr = StringUtils.split(new String(Base64.getDecoder().decode(credentials)), ':'); if (arr.length != 2) { return false; } return this.username.equals(arr[0]) && this.password.equals(arr[1]); } catch (RuntimeException e) { return false; } } }
923d4a0c96c19e7e536bdfefdfe915fca23ec2f3
1,124
java
Java
pro-spring-5-master/chapter06/spring-jdbc-rowmapper/src/test/java/com/apress/prospring5/ch6/RowMapperTest.java
dhanu10896/tech-notes
fd64525e587172e8c80c1764117c6b15b5da30b5
[ "MIT" ]
1
2019-03-08T03:15:54.000Z
2019-03-08T03:15:54.000Z
java/spring/pro-spring-5/pro-spring-5-chapter06-spring-jdbc-support/pro-spring-5-chapter06-part05-spring-jdbc-rowmapper/src/test/java/com/apress/prospring5/ch6/RowMapperTest.java
fernando-romulo-silva/myStudies
33097bb4f5441a64f3647d8eceec4550c84822dc
[ "Apache-2.0" ]
4
2021-08-02T23:29:06.000Z
2021-09-28T22:43:34.000Z
pro-spring-5-master/chapter06/spring-jdbc-rowmapper/src/test/java/com/apress/prospring5/ch6/RowMapperTest.java
dhanu10896/tech-notes
fd64525e587172e8c80c1764117c6b15b5da30b5
[ "MIT" ]
null
null
null
27.414634
93
0.755338
1,000,259
package com.apress.prospring5.ch6; import com.apress.prospring5.ch6.config.NamedJdbcCfg; import com.apress.prospring5.ch6.dao.SingerDao; import com.apress.prospring5.ch6.entities.Album; import com.apress.prospring5.ch6.entities.Singer; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.GenericApplicationContext; import java.util.List; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * Created by iuliana.cosmina on 4/16/17. */ public class RowMapperTest { @Test public void testRowMapper() { GenericApplicationContext ctx = new AnnotationConfigApplicationContext(NamedJdbcCfg.class); SingerDao singerDao = ctx.getBean(SingerDao.class); assertNotNull(singerDao); List<Singer> singers = singerDao.findAll(); assertTrue(singers.size() == 3); singers.forEach(singer -> { System.out.println(singer); if (singer.getAlbums() != null) { for (Album album : singer.getAlbums()) { System.out.println("---" + album); } } }); ctx.close(); } }
923d4a406d977a334b8d2b04f29859cc4574ebbd
2,765
java
Java
src/main/java/dev/mrsterner/bewitchmentplus/common/block/StructureSaplingBlock.java
mrsterner/Bewitchment-Plus-nof
078e839f12e4c8034c3ba56adf240ecbf48b8039
[ "MIT" ]
null
null
null
src/main/java/dev/mrsterner/bewitchmentplus/common/block/StructureSaplingBlock.java
mrsterner/Bewitchment-Plus-nof
078e839f12e4c8034c3ba56adf240ecbf48b8039
[ "MIT" ]
null
null
null
src/main/java/dev/mrsterner/bewitchmentplus/common/block/StructureSaplingBlock.java
mrsterner/Bewitchment-Plus-nof
078e839f12e4c8034c3ba56adf240ecbf48b8039
[ "MIT" ]
null
null
null
35.448718
190
0.721157
1,000,260
package dev.mrsterner.bewitchmentplus.common.block; import dev.mrsterner.bewitchmentplus.BewitchmentPlus; import dev.mrsterner.bewitchmentplus.common.utils.WorldgenHelper; import net.minecraft.block.*; import net.minecraft.server.world.ServerWorld; import net.minecraft.state.StateManager; import net.minecraft.state.property.IntProperty; import net.minecraft.state.property.Properties; import net.minecraft.util.Identifier; import net.minecraft.util.math.BlockPos; import net.minecraft.util.shape.VoxelShape; import net.minecraft.world.BlockView; import net.minecraft.world.World; import java.util.Random; public class StructureSaplingBlock extends PlantBlock implements Fertilizable { public static final IntProperty STAGE = Properties.STAGE; protected static final VoxelShape SHAPE = Block.createCuboidShape(2.0, 0.0, 2.0, 14.0, 12.0, 14.0); private final String nbtLocation; private final int variants; public StructureSaplingBlock(int variants, String nbtLocation, AbstractBlock.Settings settings) { super(settings); this.nbtLocation = nbtLocation; this.variants = variants; this.setDefaultState(this.stateManager.getDefaultState().with(STAGE, 0)); } @Override public VoxelShape getOutlineShape(BlockState state, BlockView world, BlockPos pos, ShapeContext context) { return SHAPE; } @Override public void randomTick(BlockState state, ServerWorld world, BlockPos pos, Random random) { if (world.getLightLevel(pos.up()) >= 9 && random.nextInt(7) == 0) { this.generate(world, pos, state); } } public void generate(ServerWorld world, BlockPos pos, BlockState state) { if (state.get(STAGE) == 0) { world.setBlockState(pos, state.cycle(STAGE), Block.NO_REDRAW); } else { generateStructureTree(world, pos); } } private void generateStructureTree(ServerWorld world, BlockPos pos) { WorldgenHelper.generateNbtFeature(new Identifier(BewitchmentPlus.MODID, nbtLocation+"_"+world.getRandom().nextInt(variants)), world, pos, BewitchmentPlus.config.world.yewTreeWeight); } @Override public boolean isFertilizable(BlockView world, BlockPos pos, BlockState state, boolean isClient) { return true; } @Override public boolean canGrow(World world, Random random, BlockPos pos, BlockState state) { return (double)world.random.nextFloat() < 0.45; } @Override public void grow(ServerWorld world, Random random, BlockPos pos, BlockState state) { this.generate(world, pos, state); } @Override protected void appendProperties(StateManager.Builder<Block, BlockState> builder) { builder.add(STAGE); } }
923d4cbad2ce78bcef815f47f5fb743f58f8edc8
1,662
java
Java
src/jorphan/src/main/java/org/apache/jorphan/gui/NumberRenderer.java
Chromico/jmeter
f4d93f32624f5574e43db4e171f96c56d7e8f22d
[ "Apache-2.0" ]
6,160
2015-01-03T00:03:36.000Z
2022-03-31T03:07:12.000Z
src/jorphan/src/main/java/org/apache/jorphan/gui/NumberRenderer.java
Chromico/jmeter
f4d93f32624f5574e43db4e171f96c56d7e8f22d
[ "Apache-2.0" ]
439
2015-01-26T15:30:59.000Z
2022-03-30T01:30:39.000Z
src/jorphan/src/main/java/org/apache/jorphan/gui/NumberRenderer.java
Chromico/jmeter
f4d93f32624f5574e43db4e171f96c56d7e8f22d
[ "Apache-2.0" ]
2,009
2015-01-04T13:59:25.000Z
2022-03-30T14:47:28.000Z
32.588235
75
0.73225
1,000,261
/* * 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.jorphan.gui; import java.text.DecimalFormat; import java.text.NumberFormat; import javax.swing.SwingConstants; import javax.swing.table.DefaultTableCellRenderer; /** * Renders numbers in a JTable with a specified format */ public class NumberRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = 240L; protected final NumberFormat formatter; public NumberRenderer() { super(); formatter = NumberFormat.getInstance(); setHorizontalAlignment(SwingConstants.RIGHT); } public NumberRenderer(String format) { super(); formatter = new DecimalFormat(format); setHorizontalAlignment(SwingConstants.RIGHT); } @Override public void setValue(Object value) { setText((value == null) ? "" : formatter.format(value)); } }
923d4d76f6b1f38dc52073cf50a49bbcbd53218c
3,849
java
Java
src/main/java/com/davidgjm/oss/wechat/auth/WxAuthFilter.java
davidgjm/mini-program-backend
3b7830715a0ea0cd8a4f6ebd5cf379854e00c102
[ "MIT" ]
null
null
null
src/main/java/com/davidgjm/oss/wechat/auth/WxAuthFilter.java
davidgjm/mini-program-backend
3b7830715a0ea0cd8a4f6ebd5cf379854e00c102
[ "MIT" ]
null
null
null
src/main/java/com/davidgjm/oss/wechat/auth/WxAuthFilter.java
davidgjm/mini-program-backend
3b7830715a0ea0cd8a4f6ebd5cf379854e00c102
[ "MIT" ]
null
null
null
37.735294
151
0.713952
1,000,262
package com.davidgjm.oss.wechat.auth; import com.davidgjm.oss.wechat.base.ApiErrorDetails; import com.davidgjm.oss.wechat.wxsession.WxSession; import com.davidgjm.oss.wechat.wxsession.WxSessionService; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; 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.Optional; /** * This filter checks the value of HTTP header <code>skey</code>. * The filter chain will pass on if the skey is valid and a registered user exists in the system. * Otherwise, this filter will fail. */ @Slf4j @Component public class WxAuthFilter extends OncePerRequestFilter { private final WxSessionService sessionService; private final ObjectMapper objectMapper=new ObjectMapper(); @Value("#{'${config.whitelist-url}'.split(',')}") private List<String> whitelistUrls; public WxAuthFilter(WxSessionService sessionService) { this.sessionService = sessionService; } public List<String> getWhitelistUrls() { return whitelistUrls; } public void setWhitelistUrls(List<String> whitelistUrls) { this.whitelistUrls = whitelistUrls; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String uri=request.getRequestURI(); String method = request.getMethod(); String requestInfo = method + " " + uri; log.debug("REST API request: {}", requestInfo); String skey = request.getHeader("skey"); log.info("Validating skey {}", skey); if (skey == null || skey.isEmpty()) { log.error("Header \"skey\" is required!"); response.sendError(HttpStatus.UNAUTHORIZED.value(), "skey is required!"); return; } //check if session valid first log.debug("Validating session..."); Optional<WxSession> sessionOptional = validateSession(skey); if (!sessionOptional.isPresent()) { log.error("User not found with the skey!"); handleException(response, HttpStatus.BAD_REQUEST, new WxSkeyNotFoundException("Skey not found")); return; } log.debug("session ID: {}", sessionOptional.get().getId()); log.debug("skey is valid and corresponding user exists. {}", skey); chain.doFilter(request, response); } private Optional<WxSession> validateSession(String skey) { return sessionService.findBySkey(skey); } @Override protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException { String uri=request.getRequestURI(); String method = request.getMethod(); String requestInfo = method + ":" + uri; if (whitelistUrls==null || whitelistUrls.isEmpty()) return false; return whitelistUrls.parallelStream().anyMatch(requestInfo::matches); } private void handleException(HttpServletResponse response, HttpStatus status, Exception e) throws IOException { ApiErrorDetails errorDetails = ApiErrorDetails.from(status, e); response.setStatus(status.value()); response.getWriter().write(toJson(errorDetails)); } private String toJson(ApiErrorDetails errorDetails) throws JsonProcessingException { return objectMapper.writeValueAsString(errorDetails); } }
923d4da8060db93f2efa3e53360a07b2b633dbab
66
java
Java
search-impl/src/main/java/com/example/elasticsearch/Filter.java
dwijnand/online-auction-java
cebdee4d696ee56863ea5654bdf92896e3088695
[ "Apache-2.0" ]
139
2016-10-25T01:05:05.000Z
2022-03-12T22:21:37.000Z
search-impl/src/main/java/com/example/elasticsearch/Filter.java
dwijnand/online-auction-java
cebdee4d696ee56863ea5654bdf92896e3088695
[ "Apache-2.0" ]
147
2016-10-26T00:43:53.000Z
2019-04-24T20:16:54.000Z
search-impl/src/main/java/com/example/elasticsearch/Filter.java
dwijnand/online-auction-java
cebdee4d696ee56863ea5654bdf92896e3088695
[ "Apache-2.0" ]
121
2016-10-25T05:04:10.000Z
2021-11-01T06:22:40.000Z
9.428571
34
0.772727
1,000,263
package com.example.elasticsearch; public interface Filter { }
923d4dac8d9c2dd3cd458722a87a8440054cabbf
220
java
Java
Dish.java
awakoto384/test
f60b6b2141dacd94b0de74a3f00f3a7114cf3697
[ "MIT" ]
null
null
null
Dish.java
awakoto384/test
f60b6b2141dacd94b0de74a3f00f3a7114cf3697
[ "MIT" ]
null
null
null
Dish.java
awakoto384/test
f60b6b2141dacd94b0de74a3f00f3a7114cf3697
[ "MIT" ]
null
null
null
13.75
50
0.554545
1,000,264
package menu; public class Dish { int id; String name; double price; public Dish(int id,String name,double price) { this.id = id; this.name = name; this.price = price; } }
923d4edf06ce185fbab0167a5e40c38ecfe9046e
2,774
java
Java
VisitorDemo/src/model/VisitorDemoModel.java
git-malu/OOP-Projects
8a44e4acf60111acdc946dc8bcd39478cfa20621
[ "MIT" ]
null
null
null
VisitorDemo/src/model/VisitorDemoModel.java
git-malu/OOP-Projects
8a44e4acf60111acdc946dc8bcd39478cfa20621
[ "MIT" ]
null
null
null
VisitorDemo/src/model/VisitorDemoModel.java
git-malu/OOP-Projects
8a44e4acf60111acdc946dc8bcd39478cfa20621
[ "MIT" ]
null
null
null
28.020202
133
0.658976
1,000,265
package model; import java.awt.Graphics; import visitors.*; /** * The main model object for the Visitor Demo system. * @author swong * */ public class VisitorDemoModel { /** * The adapter out to the view */ private IViewAdapter view; /** * The installed IPaintCmd instance. Initially set to a no-op cmd. */ private IPaintCmd paintCmd = IPaintCmd.NULL_OBJECT; /** * Teh cosntructor for the class * @param view the adapter to the view */ public VisitorDemoModel(IViewAdapter view) { this.view = view; } /** * Get an array of the available host types, i.e. IHost subclasses. * @return */ public IHost[] getHosts() { return new IHost[]{new HostA(), new HostB(), new HostC()}; } /** * Return the results of having the given host object execute the visitor corresponding to the given class name. A reference * to this model object is given as the visitor's input parameter. * @param host An IHost object * @param visitorClassname The name of the visitor class, without the leading "visitors.impl." * @return The results of the visitor execution on the given host. */ public Object run(IHost host, String visitorClassname) { return host.execute(loadVisitor(visitorClassname), this); } /** * Utility method to load a visitor given its classname, without the leading "visitors.impl.". * @param classname the visitor's classname * @return An IVisitor object */ private IVisitor loadVisitor(String classname){ try { Object[] args = new Object[]{}; java.lang.reflect.Constructor<?> cs[] = Class.forName("visitors.impl."+classname).getConstructors(); // get all the constructors java.lang.reflect.Constructor<?> c = null; for(int i=0;i < cs.length; i++) { // find the first constructor with the right number of input parameters if(args.length == (cs[i]).getParameterTypes().length) { c = cs[i]; break; } } return (IVisitor) c.newInstance(args); } catch(Exception ex) { System.err.println("Class "+classname+" failed to load. \nException = \n"+ ex); ex.printStackTrace(); // print the stack trace to help in debugging. return null; } } /** * Set the model's IPaintCmd instance to the given instance. * The view is called to repaint after setting the paint cmd so the * results on the viwe will show up. * @param cmd The new IPaintCmd */ public void setPaintCmd(IPaintCmd cmd){ paintCmd = cmd; view.repaint(); } /** * Paint on the given Graphics object using the current IPaintCmd object in the model. * @param g The Graphics context on which to draw. */ public void paint(Graphics g) { paintCmd.apply(g); } }
923d4f0150168eb7949933ac4c9484511209dfaa
503
java
Java
Algorithms/Java/src/A_Common_Package/NestedInteger.java
TongqiLiu/leetcode
ae36f71958d3307d868df6e03717af3ae1743323
[ "MIT" ]
2
2017-04-11T14:15:33.000Z
2018-11-23T02:37:35.000Z
Algorithms/Java/src/A_Common_Package/NestedInteger.java
TongqiLiu/leetcode
ae36f71958d3307d868df6e03717af3ae1743323
[ "MIT" ]
1
2018-08-02T12:32:19.000Z
2018-08-02T12:32:19.000Z
Algorithms/Java/src/A_Common_Package/NestedInteger.java
TongqiLiu/leetcode
ae36f71958d3307d868df6e03717af3ae1743323
[ "MIT" ]
null
null
null
12.897436
42
0.590457
1,000,266
package src.A_Common_Package; import java.util.List; /** * @author mingqiao * @Date 2020/2/17 */ public class NestedInteger { public NestedInteger() { } public NestedInteger(int value) { } public boolean isInteger() { return true; } public Integer getInteger() { return 0; } public void setInteger(int value) { } public void add(NestedInteger ni) { } public List<NestedInteger> getList() { return null; } }