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
3e0546c9fc7daaf48907fbde680d18be06e7d9e0
3,678
java
Java
src/main/java/io/github/ennuil/libzoomer/mixin/MouseMixin.java
joaoh1/LibZoomer
0de1bebbdc3e4d2e3c13d371484a2b90a844e5a1
[ "MIT" ]
3
2020-12-19T20:26:41.000Z
2021-06-09T21:34:02.000Z
src/main/java/io/github/ennuil/libzoomer/mixin/MouseMixin.java
joaoh1/LibZoomer
0de1bebbdc3e4d2e3c13d371484a2b90a844e5a1
[ "MIT" ]
1
2020-12-19T18:00:24.000Z
2021-01-23T17:03:03.000Z
src/main/java/io/github/ennuil/libzoomer/mixin/MouseMixin.java
joaoh1/LibZoomer
0de1bebbdc3e4d2e3c13d371484a2b90a844e5a1
[ "MIT" ]
1
2021-02-17T17:50:36.000Z
2021-02-17T17:50:36.000Z
33.436364
120
0.656063
2,213
package io.github.ennuil.libzoomer.mixin; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.ModifyArgs; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import org.spongepowered.asm.mixin.injection.invoke.arg.Args; import io.github.ennuil.libzoomer.api.ZoomInstance; import io.github.ennuil.libzoomer.api.ZoomRegistry; import net.minecraft.client.MinecraftClient; import net.minecraft.client.Mouse; @Mixin(Mouse.class) public class MouseMixin { @Final @Shadow private MinecraftClient client; @Shadow private double cursorDeltaX; @Shadow private double cursorDeltaY; @Unique private double cursorSensitivity; @Unique private boolean modifyMouse; @Unique private double finalCursorDeltaX; @Unique private double finalCursorDeltaY; // Mixin really hates me doing the way saner way of doing this, so, we went with the cursed one @Inject( at = @At( value = "FIELD", target = "net.minecraft.client.option/GameOptions.smoothCameraEnabled:Z" ), method = "updateMouse()V", locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true ) public void getSensitivity(CallbackInfo ci, double e, double f, double g, double h) { this.cursorSensitivity = h; } @Inject( at = @At( value = "FIELD", target = "net/minecraft/client/Mouse.cursorDeltaX:D", ordinal = 4 ), method = "updateMouse()V", locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true ) public void applyZoomChanges(CallbackInfo ci, double e, double o, double p) { this.modifyMouse = false; for (ZoomInstance instance : ZoomRegistry.getZoomInstances()) { boolean zoom = instance.getZoom(); if (zoom || instance.isModifierActive()) { instance.getMouseModifier().tick(zoom); double zoomDivisor = zoom ? instance.getZoomDivisor() : 1.0F; double transitionDivisor = instance.getTransitionMode().getInternalMultiplier(); o = instance.getMouseModifier().applyXModifier(o, cursorSensitivity, e, zoomDivisor, transitionDivisor); p = instance.getMouseModifier().applyYModifier(p, cursorSensitivity, e, zoomDivisor, transitionDivisor); this.modifyMouse = true; } } this.finalCursorDeltaX = o; this.finalCursorDeltaY = p; } @ModifyArgs( at = @At( value = "INVOKE", target = "net/minecraft/client/tutorial/TutorialManager.onUpdateMouse(DD)V" ), method = "updateMouse()V" ) private void modifyTutorialUpdate(Args args) { if (this.modifyMouse == false) return; args.set(0, finalCursorDeltaX); args.set(1, finalCursorDeltaY); } @ModifyArgs( at = @At( value = "INVOKE", target = "net/minecraft/client/network/ClientPlayerEntity.changeLookDirection(DD)V" ), method = "updateMouse()V" ) private void modifyLookDirection(Args args) { if (this.modifyMouse == false) return; args.set(0, finalCursorDeltaX); args.set(1, finalCursorDeltaY * (this.client.options.invertYMouse ? -1 : 1)); } }
3e0546f7d28245e72c5bc658fcd396b92ac44a7c
3,215
java
Java
libraries/transformer/src/main/java/androidx/media3/transformer/SingleFrameGlTextureProcessor.java
androidx/media
2c7201024ebdbfccf32e291f816fe426cc5540d8
[ "Apache-2.0" ]
155
2021-10-29T18:39:29.000Z
2022-03-31T07:26:03.000Z
libraries/transformer/src/main/java/androidx/media3/transformer/SingleFrameGlTextureProcessor.java
androidx/media
2c7201024ebdbfccf32e291f816fe426cc5540d8
[ "Apache-2.0" ]
56
2021-10-29T20:25:04.000Z
2022-03-29T14:30:57.000Z
libraries/transformer/src/main/java/androidx/media3/transformer/SingleFrameGlTextureProcessor.java
androidx/media
2c7201024ebdbfccf32e291f816fe426cc5540d8
[ "Apache-2.0" ]
17
2021-10-30T20:53:27.000Z
2022-03-25T21:27:12.000Z
39.207317
100
0.731882
2,214
/* * Copyright 2022 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 androidx.media3.transformer; import android.content.Context; import android.util.Size; import androidx.media3.common.util.UnstableApi; import java.io.IOException; /** * Manages a GLSL shader program for processing a frame. Implementations generally copy input pixels * into an output frame, with changes to pixels specific to the implementation. * * <p>Methods must be called in the following order: * * <ol> * <li>The constructor, for implementation-specific arguments. * <li>{@link #initialize(Context, int, int, int)}, to set up graphics initialization. * <li>{@link #drawFrame(long)}, to process one frame. * <li>{@link #release()}, upon conclusion of processing. * </ol> */ @UnstableApi // TODO(b/227625423): Add GlTextureProcessor interface for async texture processors and make this an // abstract class with a default implementation of GlTextureProcessor methods. public interface SingleFrameGlTextureProcessor { /** * Performs all initialization that requires OpenGL, such as, loading and compiling a GLSL shader * program. * * <p>This method may only be called if there is a current OpenGL context. * * @param context The {@link Context}. * @param inputTexId Identifier of a 2D OpenGL texture. * @param inputWidth The input width, in pixels. * @param inputHeight The input height, in pixels. * @throws IOException If an error occurs while reading resources. */ void initialize(Context context, int inputTexId, int inputWidth, int inputHeight) throws IOException; /** * Returns the output {@link Size} of frames processed through {@link #drawFrame(long)}. * * <p>This method may only be called after the texture processor has been {@link * #initialize(Context, int, int, int) initialized}. */ Size getOutputSize(); /** * Draws one frame. * * <p>This method may only be called after the texture processor has been {@link * #initialize(Context, int, int, int) initialized}. The caller is responsible for focussing the * correct render target before calling this method. * * <p>A minimal implementation should tell OpenGL to use its shader program, bind the shader * program's vertex attributes and uniforms, and issue a drawing command. * * @param presentationTimeUs The presentation timestamp of the current frame, in microseconds. * @throws FrameProcessingException If an error occurs while processing or drawing the frame. */ void drawFrame(long presentationTimeUs) throws FrameProcessingException; /** Releases all resources. */ void release(); }
3e05470fd30e37e88901b434975f70ef901f631f
3,591
java
Java
src/java/com/google/feedserver/filters/SimpleOAuthFilter.java
Type-of-iframe/google-feedserver
620de22e23bb7bc50cd155e53e92cbd4a0bd41ff
[ "Apache-2.0" ]
1
2016-06-03T18:27:40.000Z
2016-06-03T18:27:40.000Z
src/java/com/google/feedserver/filters/SimpleOAuthFilter.java
Type-of-iframe/google-feedserver
620de22e23bb7bc50cd155e53e92cbd4a0bd41ff
[ "Apache-2.0" ]
1
2016-03-30T22:33:46.000Z
2016-03-30T22:33:46.000Z
src/java/com/google/feedserver/filters/SimpleOAuthFilter.java
Type-of-iframe/google-feedserver
620de22e23bb7bc50cd155e53e92cbd4a0bd41ff
[ "Apache-2.0" ]
null
null
null
39.472527
100
0.775612
2,215
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * 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.feedserver.filters; import com.google.feedserver.adapters.AbstractManagedCollectionAdapter; import com.google.feedserver.config.UserInfo; import com.google.feedserver.config.UserInfo.UserInfoProperties; import com.google.feedserver.samples.config.HashMapBasedUserInfo; import net.oauth.OAuthAccessor; import net.oauth.OAuthConsumer; import net.oauth.OAuthException; import net.oauth.OAuthMessage; import net.oauth.server.OAuthServlet; import java.io.IOException; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; /** * OAuth filter for FeedServer. It uses {@link KeyManager} to store the public * consumer keys. * * @author [email protected] (Abhinav Khandelwal) * */ public class SimpleOAuthFilter extends AbstractOAuthFilter { private static final Logger logger = Logger.getLogger(SimpleOAuthFilter.class.getName()); public SimpleOAuthFilter(KeyManager keyManager) { super(keyManager); } @Override public String authenticate(HttpServletRequest request) throws IOException, OAuthException, URISyntaxException { OAuthMessage message = OAuthServlet.getMessage(request, null); String consumerKey = message.getConsumerKey(); String signatureMethod = message.getSignatureMethod(); OAuthConsumer consumer = keyManager.getOAuthConsumer(provider, consumerKey, signatureMethod); if (null == consumer) { logger.info("signed fetch verification failed: consumer is null"); throw new OAuthException("Unauthorized"); } OAuthAccessor accessor = new OAuthAccessor(consumer); message.validateMessage(accessor, validator); String viewerEmail = message.getParameter("opensocial_viewer_email"); if (viewerEmail == null) { logger.info("signed fetch verification failed: viewer email is null"); throw new OAuthException("Missing user identity opensocial_viewer_email"); } // Retrieve and set the user info with the OAuth parameters Map<UserInfoProperties, Object> oauthParams = new HashMap<UserInfoProperties, Object>(); oauthParams.put(UserInfoProperties.EMAIL, urlDecode(viewerEmail)); oauthParams.put(UserInfoProperties.VIEWER_ID, message.getParameter("opensocial_viewer_id")); oauthParams.put(UserInfoProperties.OWNER_EMAIL, urlDecode(message.getParameter("opensocial_owner_email"))); oauthParams.put(UserInfoProperties.OWNER_ID, message.getParameter("opensocial_owner_id")); oauthParams.put(UserInfoProperties.APPLICATION_ID, message.getParameter("opensocial_app_id")); oauthParams.put(UserInfoProperties.APPLICATION_URL, message.getParameter("opensocial_app_url")); UserInfo userInfo = new HashMapBasedUserInfo(oauthParams); request.setAttribute(AbstractManagedCollectionAdapter.USER_INFO, userInfo); logger.info("signed fetch verified: " + viewerEmail); return message.getParameter("opensocial_viewer_id"); } }
3e05472e44e2bb0b7212984ea27d57286f574a64
5,457
java
Java
src/test/java/org/sagebionetworks/bridge/sdk/integration/UserParticipantTest.java
liujoshua/BridgeIntegrationTests
f8d2cfd3af99bc23a3e8282b27d00d011abc9a1c
[ "Apache-2.0" ]
null
null
null
src/test/java/org/sagebionetworks/bridge/sdk/integration/UserParticipantTest.java
liujoshua/BridgeIntegrationTests
f8d2cfd3af99bc23a3e8282b27d00d011abc9a1c
[ "Apache-2.0" ]
null
null
null
src/test/java/org/sagebionetworks/bridge/sdk/integration/UserParticipantTest.java
liujoshua/BridgeIntegrationTests
f8d2cfd3af99bc23a3e8282b27d00d011abc9a1c
[ "Apache-2.0" ]
null
null
null
41.976923
122
0.707715
2,216
package org.sagebionetworks.bridge.sdk.integration; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.sagebionetworks.bridge.sdk.integration.Tests.assertListsEqualIgnoringOrder; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import org.sagebionetworks.bridge.sdk.integration.TestUserHelper.TestUser; import org.sagebionetworks.bridge.rest.api.ForConsentedUsersApi; import org.sagebionetworks.bridge.rest.api.ParticipantsApi; import org.sagebionetworks.bridge.rest.model.Role; import org.sagebionetworks.bridge.rest.model.StudyParticipant; import java.util.List; /** * Test of the participant APIs that act on the currently authenticated user, which have replaced the * user profile APIs as well as individual calls to update things like dataGroups, externalId, or * sharing settings. * */ @Category(IntegrationSmokeTest.class) public class UserParticipantTest { private static TestUser developer; @BeforeClass public static void before() throws Exception { developer = TestUserHelper.createAndSignInUser(UserParticipantTest.class, true, Role.DEVELOPER); } @AfterClass public static void after() throws Exception { if (developer != null) { developer.signOutAndDeleteUser(); } } @Test public void canUpdateProfile() throws Exception { TestUser user = TestUserHelper.createAndSignInUser(UserParticipantTest.class, true); try { ParticipantsApi participantsApi = user.getClient(ParticipantsApi.class); StudyParticipant participant = participantsApi.getUsersParticipantRecord().execute().body(); // This should be true by default, once a participant is created: assertTrue(participant.getNotifyByEmail()); participant.setFirstName("Davey"); participant.setLastName("Crockett"); participant.setAttributes(new ImmutableMap.Builder<String,String>().put("can_be_recontacted","true").build()); participant.setNotifyByEmail(null); // this should have no effect participantsApi.updateUsersParticipantRecord(participant).execute().body(); participant = participantsApi.getUsersParticipantRecord().execute().body(); assertEquals("Davey", participant.getFirstName()); assertEquals("Crockett", participant.getLastName()); assertEquals("true", participant.getAttributes().get("can_be_recontacted")); // This should not have been changed as the result of updating other fields assertTrue(participant.getNotifyByEmail()); // Now update only some of the record but verify the map is still there participant = participantsApi.getUsersParticipantRecord().execute().body(); participant.setFirstName("Davey2"); participant.setLastName("Crockett2"); participant.setNotifyByEmail(false); participantsApi.updateUsersParticipantRecord(participant).execute().body(); participant = participantsApi.getUsersParticipantRecord().execute().body(); assertEquals("First name updated", "Davey2", participant.getFirstName()); assertEquals("Last name updated", "Crockett2", participant.getLastName()); assertEquals("true", participant.getAttributes().get("can_be_recontacted")); assertFalse(participant.getNotifyByEmail()); } finally { user.signOutAndDeleteUser(); } } @Test public void canAddExternalIdentifier() throws Exception { ForConsentedUsersApi usersApi = developer.getClient(ForConsentedUsersApi.class); StudyParticipant participant = usersApi.getUsersParticipantRecord().execute().body(); participant.setExternalId("ABC-123-XYZ"); usersApi.updateUsersParticipantRecord(participant).execute(); participant = usersApi.getUsersParticipantRecord().execute().body(); assertEquals(developer.getEmail(), participant.getEmail()); assertEquals("ABC-123-XYZ", participant.getExternalId()); } @Test public void canUpdateDataGroups() throws Exception { List<String> dataGroups = Lists.newArrayList("sdk-int-1", "sdk-int-2"); ForConsentedUsersApi usersApi = developer.getClient(ForConsentedUsersApi.class); StudyParticipant participant = new StudyParticipant(); participant.setDataGroups(dataGroups); usersApi.updateUsersParticipantRecord(participant).execute(); developer.signOut(); developer.signInAgain(); participant = usersApi.getUsersParticipantRecord().execute().body(); assertListsEqualIgnoringOrder(dataGroups, participant.getDataGroups()); // now clear the values, it should be possible to remove them. participant.setDataGroups(Lists.newArrayList()); usersApi.updateUsersParticipantRecord(participant).execute(); developer.signOut(); developer.signInAgain(); participant = usersApi.getUsersParticipantRecord().execute().body(); assertTrue(participant.getDataGroups().isEmpty()); } }
3e05478a8dca4fdfade4269379ae229997054c6e
5,821
java
Java
Product/Production/Adapters/General/CONNECTDirectConfig/src/main/java/gov/hhs/fha/nhinc/directconfig/dao/DNSDao.java
connect-cgi/CONNECT
5f71b77155ac2c68a323eb8ea1549bc8a356e78c
[ "BSD-3-Clause" ]
37
2015-02-11T15:26:13.000Z
2021-12-08T06:48:47.000Z
Product/Production/Adapters/General/CONNECTDirectConfig/src/main/java/gov/hhs/fha/nhinc/directconfig/dao/DNSDao.java
connect-cgi/CONNECT
5f71b77155ac2c68a323eb8ea1549bc8a356e78c
[ "BSD-3-Clause" ]
519
2015-01-06T18:06:52.000Z
2019-09-04T18:25:11.000Z
Product/Production/Adapters/General/CONNECTDirectConfig/src/main/java/gov/hhs/fha/nhinc/directconfig/dao/DNSDao.java
connect-cgi/CONNECT
5f71b77155ac2c68a323eb8ea1549bc8a356e78c
[ "BSD-3-Clause" ]
63
2015-01-04T07:35:46.000Z
2021-06-24T19:40:38.000Z
43.118519
150
0.75073
2,217
/* * Copyright (c) 2009-2019, United States Government, as represented by the Secretary of Health and Human Services. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the United States Government 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 UNITED STATES GOVERNMENT 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. */ /* Copyright (c) 2010, NHIN Direct Project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the The NHIN Direct Project (nhindirect.org) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package gov.hhs.fha.nhinc.directconfig.dao; import gov.hhs.fha.nhinc.directconfig.entity.DNSRecord; import java.util.Collection; /** * DAO interface for DNS records * @author Greg Meyer * @since 1.1 */ public interface DNSDao { /** * Gets the number of records in the DNS store. * @return The number of records in the DNS store. */ public int count(); /** * Gets DNS records by record name. * @param name The record name. * @return A collection of records matching the name and of any type. */ public Collection<DNSRecord> get(String name); /** * Gets DNS records by record name and a specific record type. * @param name The record name. * @param type The record type to search for. * @return A collection of records matching the name and record type. */ public Collection<DNSRecord> get(String name, int type); /** * Gets all DNS records or a given type. Using type ANY will return all records in the store. * @param type The record type to search for. * @return A collection of records matching the record type. */ public Collection<DNSRecord> get(int type); /** * Gets DNS records by the internal record ids. * @param recordIds Array of record ids to search for. * @return A collection of records matching the record ids. */ public Collection<DNSRecord> get(long[] recordIds); /** * Gets a single DNS record for an internal record id. * @param recordId The internal record id to search for. * @return A DNS record matching the record id. */ public DNSRecord get(long recordId); /** * Adds multiple new DNS records to the store. The type cannot be ANY. * @param records The records to add the store. If a record already exists, then an exception is thrown. */ public void add(Collection<DNSRecord> records); /** * Removes a single DNS record by an existing internal record id. * @param recordId The internal record id to delete. */ public void remove(long recordId); /** * Removes DNS records by existing internal record ids. * @param recordIds The internal record ids to delete. */ public void remove(long[] recordIds); /** * Removes DNS records matching the DNS records' name and type. * @param records Records to delete. Matching is done by name and type. */ public void remove(Collection<DNSRecord> records); /** * Update a DNS record for a specific internal id. If a record does not exist, then an exception is thrown. The type cannot be ANY. * @param id The internal record id to update. * @param record Data to update the record with. */ public void update(long id, DNSRecord record); }
3e054831e203d61b630db16cdbf2a03983eabb69
10,995
java
Java
app/src/main/java/java/android/quanlybanhang/DatBan/History/Data/DonHang.java
congbui2502/DatHangOnline
d4e385a65416f2b07a3f387a98060d45d6c4aebe
[ "Apache-2.0" ]
null
null
null
app/src/main/java/java/android/quanlybanhang/DatBan/History/Data/DonHang.java
congbui2502/DatHangOnline
d4e385a65416f2b07a3f387a98060d45d6c4aebe
[ "Apache-2.0" ]
null
null
null
app/src/main/java/java/android/quanlybanhang/DatBan/History/Data/DonHang.java
congbui2502/DatHangOnline
d4e385a65416f2b07a3f387a98060d45d6c4aebe
[ "Apache-2.0" ]
null
null
null
30.798319
360
0.648295
2,218
package java.android.quanlybanhang.DatBan.History.Data; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; public class DonHang implements Serializable { private String diaChi; private String diemnhan; private String time; private int trangthai; private String idKhachhang; private Double giaKhuyenMai; private ArrayList<SanPham> sanpham; private double donGia; private String key; private Date date; private String sdtkhachhang; private String tenKhachhang; private String nhanVien; private String shipper; private String phoneShipper; private int phuongThucThanhToan; private String idQuan; private String idDonHang; private String tencuahang; private String idShipper; private long thunhap; public DonHang() { } public DonHang(String diaChi, String diemnhan, String time, int trangthai, String idKhachhang, Double giaKhuyenMai, ArrayList<SanPham> sanpham, double donGia, String key, Date date, String sdtkhachhang, String tenKhachhang, String nhanVien, String shipper, String phoneShipper, int phuongThucThanhToan, String idQuan, String idDonHang, String tencuahang) { this.diaChi = diaChi; this.diemnhan = diemnhan; this.time = time; this.trangthai = trangthai; this.idKhachhang = idKhachhang; this.giaKhuyenMai = giaKhuyenMai; this.sanpham = sanpham; this.donGia = donGia; this.key = key; this.date = date; this.sdtkhachhang = sdtkhachhang; this.tenKhachhang = tenKhachhang; this.nhanVien = nhanVien; this.shipper = shipper; this.phoneShipper = phoneShipper; this.phuongThucThanhToan = phuongThucThanhToan; this.idQuan = idQuan; this.idDonHang = idDonHang; this.tencuahang = tencuahang; } public DonHang(String diaChi, String time, int trangthai, String idKhachhang, String sdtkhachhang, Double giaKhuyenMai, ArrayList<SanPham> sanpham, int phuongThucThanhToan, String diemnhan) { this.diaChi = diaChi; this.time = time; this.trangthai = trangthai; this.idKhachhang = idKhachhang; this.giaKhuyenMai = giaKhuyenMai; this.sanpham = sanpham; this.donGia = 0; this.phuongThucThanhToan = phuongThucThanhToan; this.key = ""; this.date = null; this.tenKhachhang = ""; this.nhanVien = ""; this.phoneShipper = ""; this.shipper = ""; this.diemnhan = diemnhan; } public DonHang(String diaChi, String diemnhan, String time, int trangthai, String idKhachhang,String sdtkhachhang, Double giaKhuyenMai, ArrayList<SanPham> sanpham, double donGia, String key, Date date, String tenKhachhang, String nhanVien, String shipper, String phoneShipper, int phuongThucThanhToan, String idQuan, String idDonHang) { this.diaChi = diaChi; this.diemnhan = diemnhan; this.time = time; this.trangthai = trangthai; this.idKhachhang = idKhachhang; this.giaKhuyenMai = giaKhuyenMai; this.sanpham = sanpham; this.donGia = donGia; this.key = key; this.date = date; this.tenKhachhang = tenKhachhang; this.nhanVien = nhanVien; this.shipper = shipper; this.phoneShipper = phoneShipper; this.phuongThucThanhToan = phuongThucThanhToan; this.idQuan = idQuan; this.idDonHang = idDonHang; } public DonHang(String diaChi, String time, int trangthai, String idKhachhang, Double giaKhuyenMai, ArrayList<SanPham> sanpham, double donGia, String key, Date date, String tenKhachhang, int phuongThucThanhToan) { this.diaChi = diaChi; this.time = time; this.trangthai = trangthai; this.idKhachhang = idKhachhang; this.giaKhuyenMai = giaKhuyenMai; this.sanpham = sanpham; this.donGia = donGia; this.key = key; this.date = date; this.phuongThucThanhToan = phuongThucThanhToan; this.tenKhachhang = tenKhachhang; this.nhanVien = ""; this.phoneShipper = ""; this.shipper = ""; this.diemnhan = "123 Trần Duy Hưng"; } public DonHang(String diaChi, String time, int trangthai, String idKhachhang, Double giaKhuyenMai, ArrayList<SanPham> sanpham, double donGia, String key, Date date, String tenKhachhang, String nhanVien, int phuongThucThanhToan) { this.diaChi = diaChi; this.time = time; this.trangthai = trangthai; this.idKhachhang = idKhachhang; this.giaKhuyenMai = giaKhuyenMai; this.sanpham = sanpham; this.donGia = donGia; this.key = key; this.date = date; this.tenKhachhang = tenKhachhang; this.nhanVien = nhanVien; this.phuongThucThanhToan = phuongThucThanhToan; this.phoneShipper = ""; this.shipper = ""; this.diemnhan = "123 Trần Duy Hưng"; } public DonHang(String diaChi, String time, int trangthai, String idKhachhang, Double giaKhuyenMai, ArrayList<SanPham> sanpham, double donGia, String key, Date date, String tenKhachhang, String nhanVien, String shipper, String phoneShipper, int phuongThucThanhToan) { this.diaChi = diaChi; this.time = time; this.trangthai = trangthai; this.idKhachhang = idKhachhang; this.giaKhuyenMai = giaKhuyenMai; this.sanpham = sanpham; this.donGia = donGia; this.key = key; this.date = date; this.phuongThucThanhToan = phuongThucThanhToan; this.tenKhachhang = tenKhachhang; this.nhanVien = nhanVien; this.shipper = shipper; this.phoneShipper = phoneShipper; this.diemnhan = "123 Trần Duy Hưng"; } public DonHang(String diaChi, String diemnhan, String time, int trangthai, String idKhachhang, Double giaKhuyenMai, ArrayList<SanPham> sanpham, double donGia, String key, Date date, String tenKhachhang, String nhanVien, String shipper, String phoneShipper, int phuongThucThanhToan, String idQuan) { this.diaChi = diaChi; this.diemnhan = diemnhan; this.time = time; this.trangthai = trangthai; this.idKhachhang = idKhachhang; this.giaKhuyenMai = giaKhuyenMai; this.sanpham = sanpham; this.donGia = donGia; this.key = key; this.date = date; this.tenKhachhang = tenKhachhang; this.nhanVien = nhanVien; this.shipper = shipper; this.phoneShipper = phoneShipper; this.phuongThucThanhToan = phuongThucThanhToan; this.idQuan = idQuan; } public DonHang(String diaChi, String diemnhan, String time, int trangthai, String idKhachhang, Double giaKhuyenMai, ArrayList<SanPham> sanpham, double donGia, String key, Date date, String sdtkhachhang, String tenKhachhang, String nhanVien, String shipper, String phoneShipper, int phuongThucThanhToan, String idQuan, String idDonHang) { this.diaChi = diaChi; this.diemnhan = diemnhan; this.time = time; this.trangthai = trangthai; this.idKhachhang = idKhachhang; this.giaKhuyenMai = giaKhuyenMai; this.sanpham = sanpham; this.donGia = donGia; this.key = key; this.date = date; this.sdtkhachhang = sdtkhachhang; this.tenKhachhang = tenKhachhang; this.nhanVien = nhanVien; this.shipper = shipper; this.phoneShipper = phoneShipper; this.phuongThucThanhToan = phuongThucThanhToan; this.idQuan = idQuan; this.idDonHang = idDonHang; } public long getThunhap() { return thunhap; } public void setThunhap(long thunhap) { this.thunhap = thunhap; } public String getTencuahang() { return tencuahang; } public void setTencuahang(String tencuahang) { this.tencuahang = tencuahang; } public String getSdtkhachhang() { return sdtkhachhang; } public void setSdtkhachhang(String sdtkhachhang) { this.sdtkhachhang = sdtkhachhang; } public String getIdDonHang() { return idDonHang; } public void setIdDonHang(String idDonHang) { this.idDonHang = idDonHang; } public String getIdQuan() { return idQuan; } public void setIdQuan(String idQuan) { this.idQuan = idQuan; } public String getDiemnhan() { return diemnhan; } public void setDiemnhan(String diemnhan) { this.diemnhan = diemnhan; } public String getNhanVien() { return nhanVien; } public void setNhanVien(String nhanVien) { this.nhanVien = nhanVien; } public String getShipper() { return shipper; } public void setShipper(String shipper) { this.shipper = shipper; } public String getPhoneShipper() { return phoneShipper; } public void setPhoneShipper(String phoneShipper) { this.phoneShipper = phoneShipper; } public String getTenKhachhang() { return tenKhachhang; } public void setTenKhachhang(String tenKhachhang) { this.tenKhachhang = tenKhachhang; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getDiaChi() { return diaChi; } public void setDiaChi(String diaChi) { this.diaChi = diaChi; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public int getTrangthai() { return trangthai; } public void setTrangthai(int trangthai) { this.trangthai = trangthai; } public String getIdKhachhang() { return idKhachhang; } public void setIdKhachhang(String idKhachhang) { this.idKhachhang = idKhachhang; } public Double getGiaKhuyenMai() { return giaKhuyenMai; } public void setGiaKhuyenMai(Double giaKhuyenMai) { this.giaKhuyenMai = giaKhuyenMai; } public ArrayList<SanPham> getSanpham() { return sanpham; } public void setSanpham(ArrayList<SanPham> sanpham) { this.sanpham = sanpham; } public double getDonGia() { return donGia; } public void setDonGia(double donGia) { this.donGia = donGia; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public int getPhuongThucThanhToan() { return phuongThucThanhToan; } public void setPhuongThucThanhToan(int phuongThucThanhToan) { this.phuongThucThanhToan = phuongThucThanhToan; } public String getIdShipper() { return idShipper; } public void setIdShipper(String idShipper) { this.idShipper = idShipper; } }
3e054871d7c0e551f350f9f98ff5e3824c876754
11,276
java
Java
blueflood-rollupTools/src/main/java/com/rackspacecloud/blueflood/CloudFilesBackfiller/download/CloudFilesManager.java
GeorgeJahad/blueflood
f6daf3dc6be1781d94b2b82f508b0c048d4f7f65
[ "Apache-2.0" ]
390
2015-01-08T00:48:27.000Z
2022-01-21T09:48:33.000Z
blueflood-rollupTools/src/main/java/com/rackspacecloud/blueflood/CloudFilesBackfiller/download/CloudFilesManager.java
GeorgeJahad/blueflood
f6daf3dc6be1781d94b2b82f508b0c048d4f7f65
[ "Apache-2.0" ]
428
2015-01-07T18:12:56.000Z
2022-01-05T16:58:00.000Z
blueflood-rollupTools/src/main/java/com/rackspacecloud/blueflood/CloudFilesBackfiller/download/CloudFilesManager.java
GeorgeJahad/blueflood
f6daf3dc6be1781d94b2b82f508b0c048d4f7f65
[ "Apache-2.0" ]
91
2015-01-03T02:40:20.000Z
2022-01-16T08:03:15.000Z
42.23221
156
0.61121
2,219
/* * Copyright 2014 Rackspace * * 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. * Original author: gdusbabek * Modified by: chinmay */ package com.rackspacecloud.blueflood.CloudFilesBackfiller.download; import com.codahale.metrics.Timer; import com.rackspacecloud.blueflood.CloudFilesBackfiller.service.BackFillerConfig; import com.rackspacecloud.blueflood.rollup.Granularity; import com.rackspacecloud.blueflood.service.Configuration; import com.rackspacecloud.blueflood.types.Range; import com.rackspacecloud.blueflood.utils.Metrics; import org.jclouds.ContextBuilder; import org.jclouds.blobstore.BlobStore; import org.jclouds.blobstore.BlobStoreContext; import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.PageSet; import org.jclouds.blobstore.domain.StorageMetadata; import org.jclouds.blobstore.options.ListContainerOptions; import org.jclouds.io.Payload; import org.jclouds.location.reference.LocationConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class CloudFilesManager implements FileManager { private static final Logger log = LoggerFactory.getLogger(CloudFilesManager.class); private static final int BUF_SIZE = 0x00100000; // 1MB. private static final String lastMarkerPath = ".last_marker"; // Marker really important for this tool. Manually start hacking till we start seeing files private final String user; private final String key; private final String provider; // = "cloudfiles-us"; private final String zone; // = "IAD"; private final String container; // = "metric-data-archive"; private final int batchSize; private final List<NewFileListener> listeners = new ArrayList<NewFileListener>(); private String lastMarker = MarkerUtils.readLastMarker(); private ExecutorService downloadWorkers = Executors.newFixedThreadPool(5); public static final long START_TIME = Configuration.getInstance().getLongProperty(BackFillerConfig.REPLAY_PERIOD_START); public static final long STOP_TIME = Configuration.getInstance().getLongProperty(BackFillerConfig.REPLAY_PERIOD_STOP);; public static final Iterable<Range> ranges = Range.rangesForInterval(Granularity.MIN_5, START_TIME, STOP_TIME); private static Timer downloadTimer = Metrics.timer(CloudFilesManager.class, "Cloud Files Download Timer"); public CloudFilesManager(String user, String key, String provider, String zone, String container, int batchSize) { this.user = user; this.key = key; this.provider = provider; this.zone = zone; this.container = container; this.batchSize = batchSize; } public synchronized boolean hasNewFiles() { // see if there are any files since lastMarker. BlobStoreContext ctx = ContextBuilder.newBuilder(provider) .credentials(user, key) .overrides(new Properties() {{ setProperty(LocationConstants.PROPERTY_ZONE, zone); }}) .buildView(BlobStoreContext.class); BlobStore store = ctx.getBlobStore(); ListContainerOptions options = new ListContainerOptions().maxResults(batchSize).afterMarker(lastMarker); PageSet<? extends StorageMetadata> pages = store.list(container, options); log.debug("Saw {} new files since {}", pages.size() == batchSize ? "many" : Integer.toString(pages.size()), lastMarker); boolean emptiness = getBlobsWithinRange(pages).isEmpty(); if(emptiness) { log.warn("No file found within range {}", new Range(START_TIME, STOP_TIME)); } else { log.debug("New files found within range {}", new Range(START_TIME, STOP_TIME)); } return !emptiness; } private NavigableMap<Long,String> getBlobsWithinRange(PageSet<? extends StorageMetadata> pages) { // TreeMap used because of sorted property TreeMap<Long, String> tsToBlobName = new TreeMap<Long, String>(); for (StorageMetadata blobMeta : pages) { String fileName = blobMeta.getName(); // 20140226_1393442533000.json.gz String dateAndTs = fileName.split("\\.", 2)[0].trim(); // 20140226_1393442533000 String tsCreated = dateAndTs.split("_")[1].trim(); // 1393442533000 long ts = Long.parseLong(tsCreated); tsToBlobName.put(ts, fileName); } //Gets key within the time range specified NavigableMap<Long, String> mapWithinRange = tsToBlobName.subMap(START_TIME - 60000*15, true, STOP_TIME + 60000*30, true); if(mapWithinRange.isEmpty()) { lastMarker = tsToBlobName.lastEntry().getValue().trim(); synchronized (CloudFilesManager.this) { // this is where we resume from. MarkerUtils.writeLastMarker(tsToBlobName.lastEntry().getValue().trim()); } } return mapWithinRange; } private class BlobDownload implements Callable<String> { private final File downloadDir; private final String container; private final String name; private final BlobStore store; public BlobDownload(File downloadDir, BlobStore store, String container, String name) { this.downloadDir = downloadDir; this.store = store; this.container = container; this.name = name; } public String call() throws Exception { Blob blob = store.getBlob(container, name); Payload payload = blob.getPayload(); InputStream is = payload.getInput(); File tempFile = new File(downloadDir, name + ".tmp"); Timer.Context downloadContext = downloadTimer.time(); try { long read = 0; long length = payload.getContentMetadata().getContentLength(); OutputStream out = new FileOutputStream(tempFile, false); byte[] buf = new byte[BUF_SIZE]; while (read < length) { int avail = Math.min(is.available(), BUF_SIZE); if (avail < 0) { try { Thread.sleep(100); } catch (Exception ex) {} } else { int readLength = is.read(buf); read += readLength; out.write(buf, 0, readLength); } } out.flush(); out.close(); File permFile = new File(downloadDir, name); if (tempFile.renameTo(permFile)) { notifyListeners(permFile); } else { throw new IOException("Could not rename file"); } } catch (IOException ex) { tempFile.delete(); } finally { payload.release(); downloadContext.stop(); } return name; } } public synchronized void downloadNewFiles(File downloadDir) { log.info("Downloading new files since {}", lastMarker); BlobStoreContext ctx = ContextBuilder.newBuilder(provider) .credentials(user, key) .overrides(new Properties() {{ setProperty(LocationConstants.PROPERTY_ZONE, zone); }}) .buildView(BlobStoreContext.class); // threadsafe according to https://jclouds.apache.org/documentation/userguide/blobstore-guide/ BlobStore store = ctx.getBlobStore(); ListContainerOptions options = new ListContainerOptions().maxResults(batchSize).afterMarker(lastMarker); PageSet<? extends StorageMetadata> pages = store.list(container, options); //Gets key within the time range specified NavigableMap<Long, String> mapWithinRange = getBlobsWithinRange(pages); //Download only for keys within that range for(Map.Entry<Long, String> blobMeta : mapWithinRange.entrySet()) { log.info("Downloading file: " + blobMeta.getValue()); downloadWorkers.submit(new BlobDownload(downloadDir, store, container, blobMeta.getValue())); lastMarker = blobMeta.getValue(); synchronized (CloudFilesManager.this) { // this is where we resume from. MarkerUtils.writeLastMarker(blobMeta.getValue()); } } log.info("Updated the last marker value as " + lastMarker); } public void addNewFileListener(NewFileListener listener) { if (!listeners.contains(listener)) listeners.add(listener); } private void notifyListeners(File newFile) { for (NewFileListener listener : listeners) { try { listener.fileReceived(newFile); } catch (Throwable allSortsOfBadness) { log.error(allSortsOfBadness.getMessage(), allSortsOfBadness); } } } private static class MarkerUtils { private static final Lock lock = new ReentrantLock(); public static String readLastMarker() { lock.lock(); try { File f = new File(lastMarkerPath); if (!f.exists()) return ""; else { try { byte[] buf = new byte[(int)f.length()]; InputStream in = new FileInputStream(f); int read = 0; while (read < buf.length) read += in.read(buf, read, buf.length - read); in.close(); return new String(buf).trim(); } catch (Throwable th) { log.error(th.getMessage(), th); return ""; } } } finally { lock.unlock(); } } public static void writeLastMarker(String s) { lock.lock(); try { OutputStream out = new FileOutputStream(new File(lastMarkerPath)); out.write(s.getBytes()); out.close(); } catch (Throwable th) { log.error(th.getMessage(), th); } finally { lock.unlock(); } } } }
3e05488c42314b5e6df5804c88a181bcb9b433e3
2,615
java
Java
backend/src/main/java/es/dawequipo3/growing/controllerREST/LoginController.java
CodeURJC-DAW-2020-21/webapp3
1bec5e016420662377e689d8bced4f67117dead2
[ "Apache-2.0" ]
null
null
null
backend/src/main/java/es/dawequipo3/growing/controllerREST/LoginController.java
CodeURJC-DAW-2020-21/webapp3
1bec5e016420662377e689d8bced4f67117dead2
[ "Apache-2.0" ]
null
null
null
backend/src/main/java/es/dawequipo3/growing/controllerREST/LoginController.java
CodeURJC-DAW-2020-21/webapp3
1bec5e016420662377e689d8bced4f67117dead2
[ "Apache-2.0" ]
1
2021-03-17T08:09:23.000Z
2021-03-17T08:09:23.000Z
31.890244
113
0.744551
2,220
package es.dawequipo3.growing.controllerREST; import es.dawequipo3.growing.security.jwt.AuthResponse; import es.dawequipo3.growing.security.jwt.LoginRequest; import es.dawequipo3.growing.security.jwt.UserLoginService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @RestController @RequestMapping("/api/auth") public class LoginController { @Autowired private UserLoginService userService; @Operation(summary = "Login for registered users") @ApiResponses(value = { @ApiResponse( responseCode = "200", description = "Successfully logged in", content = {@Content( schema = @Schema(implementation = AuthResponse.class) )} ), @ApiResponse( responseCode = "401", description = "Incorrect email or password", content = @Content ) }) @PostMapping("/login") public ResponseEntity<AuthResponse> login( @CookieValue(name = "accessToken", required = false) String accessToken, @CookieValue(name = "refreshToken", required = false) String refreshToken, @RequestBody LoginRequest loginRequest) { return userService.login(loginRequest, accessToken, refreshToken); } @Operation(summary = "Refresh the session token") @ApiResponses(value = { @ApiResponse( responseCode = "200", description = "Token successfully refreshed", content = {@Content( schema = @Schema(implementation = AuthResponse.class) )} ) }) @PostMapping("/refresh") public ResponseEntity<AuthResponse> refreshToken( @CookieValue(name = "refreshToken", required = false) String refreshToken) { return userService.refresh(refreshToken); } @Operation(summary = "Logout for started sessions") @ApiResponses(value = { @ApiResponse( responseCode = "200", description = "Successfully logged out", content = {@Content( schema = @Schema(implementation = AuthResponse.class) )} ) }) @PostMapping("/logout") public ResponseEntity<AuthResponse> logout(HttpServletRequest request, HttpServletResponse response) { return ResponseEntity.ok(new AuthResponse(AuthResponse.Status.SUCCESS, userService.logout(request, response))); } }
3e054a4274939d3dbce76e3458d353ed5d6fb930
2,666
java
Java
aws-rds-dbclusterparametergroup/src/main/java/software/amazon/rds/dbclusterparametergroup/UpdateHandler.java
Outige/aws-cloudformation-resource-providers-rds
e7ed8fadd2ecd7d57a395ba3d53fb40b4ec82332
[ "Apache-2.0" ]
null
null
null
aws-rds-dbclusterparametergroup/src/main/java/software/amazon/rds/dbclusterparametergroup/UpdateHandler.java
Outige/aws-cloudformation-resource-providers-rds
e7ed8fadd2ecd7d57a395ba3d53fb40b4ec82332
[ "Apache-2.0" ]
null
null
null
aws-rds-dbclusterparametergroup/src/main/java/software/amazon/rds/dbclusterparametergroup/UpdateHandler.java
Outige/aws-cloudformation-resource-providers-rds
e7ed8fadd2ecd7d57a395ba3d53fb40b4ec82332
[ "Apache-2.0" ]
null
null
null
54.408163
130
0.65979
2,221
package software.amazon.rds.dbclusterparametergroup; import software.amazon.awssdk.services.rds.RdsClient; import software.amazon.cloudformation.proxy.AmazonWebServicesClientProxy; import software.amazon.cloudformation.proxy.Logger; import software.amazon.cloudformation.proxy.ProgressEvent; import software.amazon.cloudformation.proxy.ProxyClient; import software.amazon.cloudformation.proxy.ResourceHandlerRequest; import software.amazon.rds.common.handler.HandlerConfig; import software.amazon.rds.common.handler.Tagging; public class UpdateHandler extends BaseHandlerStd { public UpdateHandler() { this(HandlerConfig.builder().build()); } public UpdateHandler(final HandlerConfig config) { super(config); } @Override protected ProgressEvent<ResourceModel, CallbackContext> handleRequest(final AmazonWebServicesClientProxy proxy, final ResourceHandlerRequest<ResourceModel> request, final CallbackContext callbackContext, final ProxyClient<RdsClient> proxyClient, final Logger logger) { final ResourceModel model = request.getDesiredResourceState(); final Tagging.TagSet previousTags = Tagging.TagSet.builder() .systemTags(Tagging.translateTagsToSdk(request.getPreviousSystemTags())) .stackTags(Tagging.translateTagsToSdk(request.getPreviousResourceTags())) .resourceTags(Translator.translateTagsToSdk(request.getPreviousResourceState().getTags())) .build(); final Tagging.TagSet desiredTags = Tagging.TagSet.builder() .systemTags(Tagging.translateTagsToSdk(request.getSystemTags())) .stackTags(Tagging.translateTagsToSdk(request.getDesiredResourceTags())) .resourceTags(Translator.translateTagsToSdk(request.getDesiredResourceState().getTags())) .build(); return ProgressEvent.progress(model, callbackContext) .then(progress -> updateTags(proxy, proxyClient, progress, previousTags, desiredTags)) .then(progress -> resetAllParameters(progress, proxy, proxyClient)) .then(progress -> applyParameters(proxy, proxyClient, progress.getResourceModel(), progress.getCallbackContext())) .then(progress -> new ReadHandler().handleRequest(proxy, request, callbackContext, proxyClient, logger)); } }
3e054aba75fc791ad3e79ddf9501096e1328535e
635
java
Java
src/main/java/com/topcheer/ybt/transservice/controller/RePrintConfirmInsController.java
xutao6936/archYBT
1d459fb9426bfa699278b3b5e3ebca2ec304e7c9
[ "Apache-2.0" ]
1
2016-09-06T01:43:56.000Z
2016-09-06T01:43:56.000Z
src/main/java/com/topcheer/ybt/transservice/controller/RePrintConfirmInsController.java
xutao6936/archYBT
1d459fb9426bfa699278b3b5e3ebca2ec304e7c9
[ "Apache-2.0" ]
4
2019-11-13T02:30:11.000Z
2021-01-20T22:16:30.000Z
src/main/java/com/topcheer/ybt/transservice/controller/RePrintConfirmInsController.java
xutao6936/archYBT
1d459fb9426bfa699278b3b5e3ebca2ec304e7c9
[ "Apache-2.0" ]
1
2016-09-06T01:44:33.000Z
2016-09-06T01:44:33.000Z
25.4
63
0.770079
2,222
package com.topcheer.ybt.transservice.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * 当日投保确认补打 * * @author liuc * */ @Controller @RequestMapping("/topRePrintConfirmIns") public class RePrintConfirmInsController { private static Logger logger = LoggerFactory .getLogger(RePrintConfirmInsController.class); @RequestMapping("/turnToRePrintConfirmInsInfo.do") public String turnToRePrintConfirmInsInfo() { return "transservice/rePrintConfirmInsInfo"; } }
3e054afc7d41f30a9bd39ad966988f9b07fa244e
8,343
java
Java
src/main/java/de/clusterfreak/ClusterCore/PossibilisticCMeans.java
clusterfreak/ClusterCore
ff0ebe9670eb18ad1330dbb631e9ea5ad24f2237
[ "MIT" ]
3
2020-06-06T13:02:33.000Z
2021-09-17T02:44:54.000Z
src/main/java/de/clusterfreak/ClusterCore/PossibilisticCMeans.java
clusterfreak/ClusterCore
ff0ebe9670eb18ad1330dbb631e9ea5ad24f2237
[ "MIT" ]
2
2020-10-25T18:22:27.000Z
2021-05-13T17:12:18.000Z
src/main/java/de/clusterfreak/ClusterCore/PossibilisticCMeans.java
clusterfreak/ClusterCore
ff0ebe9670eb18ad1330dbb631e9ea5ad24f2237
[ "MIT" ]
null
null
null
32.846457
119
0.478245
2,223
package de.clusterfreak.ClusterCore; import java.util.Vector; /** * Possivilistic-C-Means (PCM) * <p> * Cluster analysis with Possivilistic-C-Means clustering algorithm * * <PRE> * Step 1: Initialization * Step 2: Determination of the cluster centers * Step 3: Calculate the new partition matrix and ni * Step 4: Termination or repetition * Step 5: optional - Repeat calculation (steps 2 to 4) * </PRE> * * @author Thomas Heym * @version 1.2.3 (2020-11-01) * @see FuzzyCMeans */ public class PossibilisticCMeans { /** * Quantity/number of clusters */ private final int cluster; /** * Euclidean distance norm, exponent, initial value 2 */ private final static int m = 2; /** * Termination threshold, initial value 1.0e-7 */ private double e = 1.0e-7; /** * Each Object represents 1 cluster vi */ private final double[][] object; /** * Cluster centers vi */ private double[][] vi; /** * Complete search path */ private double[][] viPath; /** * npcm */ private final double[] ni; /** * Number of PCM passes */ private int repeat; /** * Partition matrix (Membership values of the k-th object to the i-th * cluster) */ private static double[][] getMik; /** * Generates PCM-Object from a set of Points * * @param object Objects * @param clusterCount Number of clusters * @param repeat Number of PCM passes for determination of the cluster centers * @see FuzzyCMeans */ public PossibilisticCMeans(double[][] object, int clusterCount, int repeat) { this.object = object; this.cluster = clusterCount; this.vi = new double[cluster][2]; this.ni = new double[cluster]; this.repeat = repeat; } /** * Generates PCM-Object from a set of Points * * @param object Objects * @param clusterCount Number of clusters * @param repeat Number of PCM passes for determination of the cluster centers * @param e Termination threshold, initial value 1.0e-7 * @see FuzzyCMeans */ public PossibilisticCMeans(double[][] object, int clusterCount, int repeat, double e) { this.object = object; this.cluster = clusterCount; this.vi = new double[cluster][2]; this.ni = new double[cluster]; this.repeat = repeat; this.e = e; } /** * Returns the cluster centers * * @param random random initialization * @param returnPath Determines whether return the complete search path. Values: * <code>true</code>, <code>false</code> * @return Cluster centers and serarch path (optional); The cluster centers * are at the end. */ public double[][] determineClusterCenters(boolean random, boolean returnPath) { double euclideanDistance; /* * When false return only the class centers */ Vector<Point2D> viPathRec = new Vector<>(); // Step 1: Initialization FuzzyCMeans fcm; if (e == 1.0e-7) { fcm = new FuzzyCMeans(object, cluster); } else { fcm = new FuzzyCMeans(object, cluster, e); } double[][] getViPath = fcm.determineClusterCenters(random, true); for (double[] doubles : getViPath) viPathRec.add(new Point2D(doubles[0], doubles[1])); vi = fcm.getVi(); double[][] mik = fcm.getMik(); do { // while (repeat>0) repeat--; /* * Perform calculation of ni */ boolean ni_calc = true; do { // while (euclideanDistance>=e) // Step 2: Determination of the cluster centers // --> Step 5: optional - Repeat calculation (steps 2 to 4) for (int k = 0; k < vi.length; k++) { double mikm, mikm0 = 0.0, mikm1 = 0.0, mikms = 0.0; for (int i = 0; i < mik.length; i++) { mikm = Math.pow(mik[i][k], m); mikm0 += mikm * object[i][0]; mikm1 += mikm * object[i][1]; mikms += mikm; } vi[k][0] = mikm0 / mikms; vi[k][1] = mikm1 / mikms; } // record cluster points if (returnPath) { for (double[] doubles : vi) viPathRec.add(new Point2D(doubles[0], doubles[1])); } // Step 3: Calculate the new partition matrix and ni double[][] mik_before = new double[mik.length][cluster]; double[] miks = new double[vi.length]; if (ni_calc) { // Calulate ni (Distance from the class center to the point // with a membership value of 0.5 to the actual cluster) // initial ni = 0 for (int i = 0; i < vi.length; i++) { ni[i] = 0.0; miks[i] = 0.0; } // ni = sum mik&sup2;*dik&sup2; for (int i = 0; i < mik.length; i++) { for (int k = 0; k < vi.length; k++) { double dik = Math .sqrt(Math.pow(object[i][0] - vi[k][0], 2) + Math.pow(object[i][1] - vi[k][1], 2)); ni[k] += Math.pow(Math.pow(mik[i][k], 2), 2) * Math.pow(dik, 2); miks[k] += Math.pow(mik[i][k], 2); } } // ni = sum(mik&sup2;*dik&sup2;) / sum mik&sup2; for (int i = 0; i < vi.length; i++) { ni[i] /= miks[i]; } ni_calc = false; } for (int k = 0; k < vi.length; k++) { for (int i = 0; i < mik.length; i++) { mik_before[i][k] = mik[i][k]; mik[i][k] = 1 / (1 + (Math.pow( Math.sqrt(Math.pow(object[i][0] - vi[k][0], 2) + Math.pow(object[i][1] - vi[k][1], 2)), 2)) / ni[k]); // NaN-Error if (Double.isNaN(mik[i][k])) mik[i][k] = 1.0; } } // calculate euclidean distance euclideanDistance = 0.0; for (int k = 0; k < vi.length; k++) { for (int i = 0; i < mik.length; i++) { euclideanDistance += Math.pow((mik[i][k] - mik_before[i][k]), 2); } } euclideanDistance = Math.sqrt(euclideanDistance); } // Step 4: Termination or repetition while (euclideanDistance >= e); } while (repeat > 0); getMik = mik; // Value return if (returnPath) { double[][] viPathCut = new double[viPathRec.size()][2]; for (int k = 0; k < viPathCut.length; k++) { Point2D cut = viPathRec.elementAt(k); viPathCut[k][0] = cut.x; viPathCut[k][1] = cut.y; } setViPath(viPathCut); } return vi; } /** * Returns the partition matrix (Membership values of the k-th object to the * i-th cluster) * * @return Partition matrix */ public double[][] getMik() { return getMik; } /** * Set partition matrix * * @param setMik partition matrix */ public static void setMik(double[][] setMik) { getMik = setMik; } /** * Returns cluster centers vi * * @return vi */ public double[][] getVi() { return vi; } /** * Set viPath * * @param setViPath Set viPath */ private void setViPath(double[][] setViPath) { viPath = setViPath; } /** * Returns the complete search path * * @return viPath */ public double[][] getViPath() { return viPath; } }
3e054b85e4603b3e3848a58d1e52ef9b7549d965
23,203
java
Java
java/form/test/unit/src/org/netbeans/modules/form/layoutdesign/ALT_Indent01Test.java
tusharvjoshi/incubator-netbeans
a61bd21f4324f7e73414633712522811cb20ac93
[ "Apache-2.0" ]
1,056
2019-04-25T20:00:35.000Z
2022-03-30T04:46:14.000Z
java/form/test/unit/src/org/netbeans/modules/form/layoutdesign/ALT_Indent01Test.java
Marc382/netbeans
4bee741d24a3fdb05baf135de5e11a7cd95bd64e
[ "Apache-2.0" ]
1,846
2019-04-25T20:50:05.000Z
2022-03-31T23:40:41.000Z
java/form/test/unit/src/org/netbeans/modules/form/layoutdesign/ALT_Indent01Test.java
Marc382/netbeans
4bee741d24a3fdb05baf135de5e11a7cd95bd64e
[ "Apache-2.0" ]
550
2019-04-25T20:04:33.000Z
2022-03-25T17:43:01.000Z
60.900262
150
0.653536
2,224
/* * 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.netbeans.modules.form.layoutdesign; import java.awt.Dimension; import java.awt.Point; import java.awt.Rectangle; import java.io.File; import java.io.IOException; import java.util.*; import org.openide.filesystems.FileUtil; public class ALT_Indent01Test extends LayoutTestCase { public ALT_Indent01Test(String name) { super(name); try { className = this.getClass().getName(); className = className.substring(className.lastIndexOf('.') + 1, className.length()); startingFormFile = FileUtil.toFileObject(new File(url.getFile() + goldenFilesPath + className + "-StartingForm.form").getCanonicalFile()); } catch (IOException ioe) { fail(ioe.toString()); } } // Add a label below the first one at indented position. public void doChanges0() { ld.externalSizeChangeHappened(); // > UPDATE CURRENT STATE contInterior.put("Form", new Rectangle(0, 0, 400, 300)); compBounds.put("jLabel1", new Rectangle(10, 11, 34, 14)); baselinePosition.put("jLabel1-34-14", new Integer(11)); compPrefSize.put("jLabel1", new Dimension(34, 14)); compBounds.put("jLabel2", new Rectangle(50, 11, 34, 14)); baselinePosition.put("jLabel2-34-14", new Integer(11)); compPrefSize.put("jLabel2", new Dimension(34, 14)); contInterior.put("Form", new Rectangle(0, 0, 400, 300)); compBounds.put("jLabel1", new Rectangle(10, 11, 34, 14)); baselinePosition.put("jLabel1-34-14", new Integer(11)); compBounds.put("jLabel2", new Rectangle(50, 11, 34, 14)); baselinePosition.put("jLabel2-34-14", new Integer(11)); ld.updateCurrentState(); // < UPDATE CURRENT STATE lc = new LayoutComponent("jLabel3", false); // > START ADDING baselinePosition.put("jLabel3-34-14", new Integer(11)); { LayoutComponent[] comps = new LayoutComponent[] { lc }; Rectangle[] bounds = new Rectangle[] { new Rectangle(0, 0, 34, 14) }; String defaultContId = null; Point hotspot = new Point(13,7); ld.startAdding(comps, bounds, hotspot, defaultContId); } // < START ADDING prefPaddingInParent.put("Form-jLabel3-1-0", new Integer(11)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jLabel3-1-1", new Integer(11)); // parentId-compId-dimension-compAlignment prefPadding.put("jLabel1-jLabel3-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel2-jLabel3-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel3-jLabel1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel3-jLabel2-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPaddingInParent.put("Form-jLabel3-0-0", new Integer(10)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jLabel3-0-1", new Integer(10)); // parentId-compId-dimension-compAlignment prefPadding.put("jLabel1-jLabel3-0-0-2", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel2-jLabel3-0-0-2", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType // > MOVE { Point p = new Point(36,41); String containerId= "Form"; boolean autoPositioning = true; boolean lockDimension = false; Rectangle[] bounds = new Rectangle[] { new Rectangle(20, 31, 34, 14) }; ld.move(p, containerId, autoPositioning, lockDimension, bounds); } // < MOVE prefPaddingInParent.put("Form-jLabel3-1-0", new Integer(11)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jLabel3-1-1", new Integer(11)); // parentId-compId-dimension-compAlignment prefPadding.put("jLabel1-jLabel3-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel2-jLabel3-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel3-jLabel1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel3-jLabel2-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPaddingInParent.put("Form-jLabel3-0-0", new Integer(10)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jLabel3-0-1", new Integer(10)); // parentId-compId-dimension-compAlignment prefPadding.put("jLabel1-jLabel3-0-0-2", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel2-jLabel3-0-0-2", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType // > MOVE { Point p = new Point(36,40); String containerId= "Form"; boolean autoPositioning = true; boolean lockDimension = false; Rectangle[] bounds = new Rectangle[] { new Rectangle(20, 31, 34, 14) }; ld.move(p, containerId, autoPositioning, lockDimension, bounds); } // < MOVE // > END MOVING compPrefSize.put("jLabel3", new Dimension(34, 14)); compPrefSize.put("jLabel3", new Dimension(34, 14)); prefPaddingInParent.put("Form-jLabel3-0-1", new Integer(10)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jLabel3-1-1", new Integer(10)); // parentId-compId-dimension-compAlignment ld.endMoving(true); // < END MOVING ld.externalSizeChangeHappened(); // > UPDATE CURRENT STATE contInterior.put("Form", new Rectangle(0, 0, 400, 300)); compBounds.put("jLabel1", new Rectangle(10, 11, 34, 14)); baselinePosition.put("jLabel1-34-14", new Integer(11)); compPrefSize.put("jLabel1", new Dimension(34, 14)); compBounds.put("jLabel2", new Rectangle(50, 11, 34, 14)); baselinePosition.put("jLabel2-34-14", new Integer(11)); compPrefSize.put("jLabel2", new Dimension(34, 14)); compBounds.put("jLabel3", new Rectangle(20, 31, 34, 14)); baselinePosition.put("jLabel3-34-14", new Integer(11)); compPrefSize.put("jLabel3", new Dimension(34, 14)); contInterior.put("Form", new Rectangle(0, 0, 400, 300)); compBounds.put("jLabel1", new Rectangle(10, 11, 34, 14)); baselinePosition.put("jLabel1-34-14", new Integer(11)); compBounds.put("jLabel2", new Rectangle(50, 11, 34, 14)); baselinePosition.put("jLabel2-34-14", new Integer(11)); compBounds.put("jLabel3", new Rectangle(20, 31, 34, 14)); baselinePosition.put("jLabel3-34-14", new Integer(11)); ld.updateCurrentState(); // < UPDATE CURRENT STATE } // Make the third label longer (append "aaa"). Add a new label like it would // like to go indented with jLabel2 - but indent should not be offered, and // the new label should be added after jLabel3 in sequence. public void doChanges1() { ld.externalSizeChangeHappened(); // > UPDATE CURRENT STATE contInterior.put("Form", new Rectangle(0, 0, 400, 300)); compBounds.put("jLabel1", new Rectangle(10, 11, 34, 14)); baselinePosition.put("jLabel1-34-14", new Integer(11)); compPrefSize.put("jLabel1", new Dimension(34, 14)); compBounds.put("jLabel2", new Rectangle(50, 11, 34, 14)); baselinePosition.put("jLabel2-34-14", new Integer(11)); compPrefSize.put("jLabel2", new Dimension(34, 14)); compBounds.put("jLabel3", new Rectangle(20, 31, 52, 14)); baselinePosition.put("jLabel3-52-14", new Integer(11)); compPrefSize.put("jLabel3", new Dimension(52, 14)); contInterior.put("Form", new Rectangle(0, 0, 400, 300)); compBounds.put("jLabel1", new Rectangle(10, 11, 34, 14)); baselinePosition.put("jLabel1-34-14", new Integer(11)); compBounds.put("jLabel2", new Rectangle(50, 11, 34, 14)); baselinePosition.put("jLabel2-34-14", new Integer(11)); compBounds.put("jLabel3", new Rectangle(20, 31, 52, 14)); baselinePosition.put("jLabel3-52-14", new Integer(11)); ld.updateCurrentState(); // < UPDATE CURRENT STATE lc = new LayoutComponent("jLabel4", false); // > START ADDING baselinePosition.put("jLabel4-34-14", new Integer(11)); { LayoutComponent[] comps = new LayoutComponent[] { lc }; Rectangle[] bounds = new Rectangle[] { new Rectangle(0, 0, 34, 14) }; String defaultContId = null; Point hotspot = new Point(13,7); ld.startAdding(comps, bounds, hotspot, defaultContId); } // < START ADDING prefPaddingInParent.put("Form-jLabel4-1-0", new Integer(11)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jLabel4-1-1", new Integer(11)); // parentId-compId-dimension-compAlignment prefPadding.put("jLabel1-jLabel4-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel2-jLabel4-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel4-jLabel1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel4-jLabel2-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel3-jLabel4-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel4-jLabel3-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPaddingInParent.put("Form-jLabel4-0-0", new Integer(10)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jLabel4-0-1", new Integer(10)); // parentId-compId-dimension-compAlignment prefPadding.put("jLabel3-jLabel4-0-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel1-jLabel4-0-0-2", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel2-jLabel4-0-0-2", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType // > MOVE { Point p = new Point(72,41); String containerId= "Form"; boolean autoPositioning = true; boolean lockDimension = false; Rectangle[] bounds = new Rectangle[] { new Rectangle(59, 31, 34, 14) }; ld.move(p, containerId, autoPositioning, lockDimension, bounds); } // < MOVE prefPaddingInParent.put("Form-jLabel4-1-0", new Integer(11)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jLabel4-1-1", new Integer(11)); // parentId-compId-dimension-compAlignment prefPadding.put("jLabel1-jLabel4-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel2-jLabel4-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel4-jLabel1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel4-jLabel2-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel3-jLabel4-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel4-jLabel3-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPaddingInParent.put("Form-jLabel4-0-0", new Integer(10)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jLabel4-0-1", new Integer(10)); // parentId-compId-dimension-compAlignment prefPadding.put("jLabel3-jLabel4-0-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel4-jLabel3-0-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel1-jLabel4-0-0-2", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel2-jLabel4-0-0-2", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType // > MOVE { Point p = new Point(71,41); String containerId= "Form"; boolean autoPositioning = true; boolean lockDimension = false; Rectangle[] bounds = new Rectangle[] { new Rectangle(58, 31, 34, 14) }; ld.move(p, containerId, autoPositioning, lockDimension, bounds); } // < MOVE // > END MOVING compPrefSize.put("jLabel4", new Dimension(34, 14)); compPrefSize.put("jLabel4", new Dimension(34, 14)); prefPaddingInParent.put("Form-jLabel4-0-1", new Integer(10)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jLabel2-0-1", new Integer(10)); // parentId-compId-dimension-compAlignment ld.endMoving(true); // < END MOVING ld.externalSizeChangeHappened(); // > UPDATE CURRENT STATE contInterior.put("Form", new Rectangle(0, 0, 400, 300)); compBounds.put("jLabel1", new Rectangle(10, 11, 34, 14)); baselinePosition.put("jLabel1-34-14", new Integer(11)); compPrefSize.put("jLabel1", new Dimension(34, 14)); compBounds.put("jLabel2", new Rectangle(50, 11, 34, 14)); baselinePosition.put("jLabel2-34-14", new Integer(11)); compPrefSize.put("jLabel2", new Dimension(34, 14)); compBounds.put("jLabel3", new Rectangle(20, 31, 52, 14)); baselinePosition.put("jLabel3-52-14", new Integer(11)); compPrefSize.put("jLabel3", new Dimension(52, 14)); compBounds.put("jLabel4", new Rectangle(78, 31, 34, 14)); baselinePosition.put("jLabel4-34-14", new Integer(11)); compPrefSize.put("jLabel4", new Dimension(34, 14)); prefPaddingInParent.put("Form-jLabel4-0-1", new Integer(10)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jLabel2-0-1", new Integer(10)); // parentId-compId-dimension-compAlignment contInterior.put("Form", new Rectangle(0, 0, 400, 300)); compBounds.put("jLabel1", new Rectangle(10, 11, 34, 14)); baselinePosition.put("jLabel1-34-14", new Integer(11)); compBounds.put("jLabel2", new Rectangle(50, 11, 34, 14)); baselinePosition.put("jLabel2-34-14", new Integer(11)); compBounds.put("jLabel3", new Rectangle(20, 31, 52, 14)); baselinePosition.put("jLabel3-52-14", new Integer(11)); compBounds.put("jLabel4", new Rectangle(78, 31, 34, 14)); baselinePosition.put("jLabel4-34-14", new Integer(11)); ld.updateCurrentState(); // < UPDATE CURRENT STATE } // Add a label at indented position with jLabel3. public void doChanges2() { lc = new LayoutComponent("jLabel5", false); // > START ADDING baselinePosition.put("jLabel5-34-14", new Integer(11)); { LayoutComponent[] comps = new LayoutComponent[] { lc }; Rectangle[] bounds = new Rectangle[] { new Rectangle(0, 0, 34, 14) }; String defaultContId = null; Point hotspot = new Point(13,7); ld.startAdding(comps, bounds, hotspot, defaultContId); } // < START ADDING prefPaddingInParent.put("Form-jLabel5-1-0", new Integer(11)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jLabel5-1-1", new Integer(11)); // parentId-compId-dimension-compAlignment prefPadding.put("jLabel1-jLabel5-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel2-jLabel5-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel5-jLabel1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel5-jLabel2-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel3-jLabel5-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel4-jLabel5-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel5-jLabel3-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel5-jLabel4-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPaddingInParent.put("Form-jLabel5-0-0", new Integer(10)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jLabel5-0-1", new Integer(10)); // parentId-compId-dimension-compAlignment prefPadding.put("jLabel3-jLabel5-0-0-2", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel4-jLabel5-0-0-2", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType // > MOVE { Point p = new Point(45,57); String containerId= "Form"; boolean autoPositioning = true; boolean lockDimension = false; Rectangle[] bounds = new Rectangle[] { new Rectangle(30, 51, 34, 14) }; ld.move(p, containerId, autoPositioning, lockDimension, bounds); } // < MOVE prefPaddingInParent.put("Form-jLabel5-1-0", new Integer(11)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jLabel5-1-1", new Integer(11)); // parentId-compId-dimension-compAlignment prefPadding.put("jLabel1-jLabel5-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel2-jLabel5-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel5-jLabel1-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel5-jLabel2-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel3-jLabel5-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel4-jLabel5-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel5-jLabel3-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel5-jLabel4-1-0-0", new Integer(6)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPaddingInParent.put("Form-jLabel5-0-0", new Integer(10)); // parentId-compId-dimension-compAlignment prefPaddingInParent.put("Form-jLabel5-0-1", new Integer(10)); // parentId-compId-dimension-compAlignment prefPadding.put("jLabel3-jLabel5-0-0-2", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType prefPadding.put("jLabel4-jLabel5-0-0-2", new Integer(10)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType // > MOVE { Point p = new Point(44,57); String containerId= "Form"; boolean autoPositioning = true; boolean lockDimension = false; Rectangle[] bounds = new Rectangle[] { new Rectangle(30, 51, 34, 14) }; ld.move(p, containerId, autoPositioning, lockDimension, bounds); } // < MOVE // > END MOVING compPrefSize.put("jLabel5", new Dimension(34, 14)); compPrefSize.put("jLabel5", new Dimension(34, 14)); prefPaddingInParent.put("Form-jLabel5-1-1", new Integer(10)); // parentId-compId-dimension-compAlignment ld.endMoving(true); // < END MOVING ld.externalSizeChangeHappened(); // > UPDATE CURRENT STATE contInterior.put("Form", new Rectangle(0, 0, 400, 300)); compBounds.put("jLabel1", new Rectangle(10, 11, 34, 14)); baselinePosition.put("jLabel1-34-14", new Integer(11)); compPrefSize.put("jLabel1", new Dimension(34, 14)); compBounds.put("jLabel2", new Rectangle(50, 11, 34, 14)); baselinePosition.put("jLabel2-34-14", new Integer(11)); compPrefSize.put("jLabel2", new Dimension(34, 14)); compBounds.put("jLabel3", new Rectangle(20, 31, 52, 14)); baselinePosition.put("jLabel3-52-14", new Integer(11)); compPrefSize.put("jLabel3", new Dimension(52, 14)); compBounds.put("jLabel4", new Rectangle(78, 31, 34, 14)); baselinePosition.put("jLabel4-34-14", new Integer(11)); compPrefSize.put("jLabel4", new Dimension(34, 14)); compBounds.put("jLabel5", new Rectangle(30, 51, 34, 14)); baselinePosition.put("jLabel5-34-14", new Integer(11)); compPrefSize.put("jLabel5", new Dimension(34, 14)); contInterior.put("Form", new Rectangle(0, 0, 400, 300)); compBounds.put("jLabel1", new Rectangle(10, 11, 34, 14)); baselinePosition.put("jLabel1-34-14", new Integer(11)); compBounds.put("jLabel2", new Rectangle(50, 11, 34, 14)); baselinePosition.put("jLabel2-34-14", new Integer(11)); compBounds.put("jLabel3", new Rectangle(20, 31, 52, 14)); baselinePosition.put("jLabel3-52-14", new Integer(11)); compBounds.put("jLabel4", new Rectangle(78, 31, 34, 14)); baselinePosition.put("jLabel4-34-14", new Integer(11)); compBounds.put("jLabel5", new Rectangle(30, 51, 34, 14)); baselinePosition.put("jLabel5-34-14", new Integer(11)); ld.updateCurrentState(); // < UPDATE CURRENT STATE } }
3e054c0c71e8464ef93ff0f58d844b8359a78228
3,453
java
Java
src/main/java/com/anmong/core/dao/FileDAO.java
84369982/anmong
33b5de341f564dae6c539558441f8b7a792fc689
[ "MIT" ]
null
null
null
src/main/java/com/anmong/core/dao/FileDAO.java
84369982/anmong
33b5de341f564dae6c539558441f8b7a792fc689
[ "MIT" ]
8
2020-04-23T21:00:27.000Z
2021-12-14T20:48:59.000Z
src/main/java/com/anmong/core/dao/FileDAO.java
84369982/anmong
33b5de341f564dae6c539558441f8b7a792fc689
[ "MIT" ]
null
null
null
53.123077
262
0.653924
2,225
package com.anmong.core.dao; import com.anmong.common.fastsql.dao.BaseDAO; import com.anmong.common.fastsql.dto.ResultPage; import com.anmong.common.util.DateUtil; import com.anmong.core.dto.web.file.WebFileIndexDTO; import com.anmong.core.entity.File; import com.anmong.core.enums.CommonEnum; import com.anmong.core.vo.wap.file.FileIndexVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.namedparam.EmptySqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class FileDAO extends BaseDAO<File, String>{ @Autowired private NamedParameterJdbcTemplate namedParameterJdbcTemplate; public void insertBatch(List<File> entityList){ StringBuilder sql = new StringBuilder("INSERT INTO files (id,module_name,module_code,name,old_file_name,new_file_name,url,path,store_type,suffix,size,type,state,create_at,create_man) values "); for (File entity : entityList){ sql.append("('"+entity.getId()+"','"+entity.getModuleName()+"','"+entity.getModuleCode()+"','"+entity.getName()) .append("','"+entity.getOldFileName()+"','"+entity.getNewFileName()+"','"+entity.getUrl()+"','"+entity.getPath()) .append("','"+entity.getStoreType()+"','"+entity.getSuffix()+"','"+entity.getSize()+"','"+entity.getType()) .append("','"+entity.getState()+"','"+ DateUtil.getYYYYmmDDhhMMss(entity.getCreateAt())+"','"+entity.getCreateMan()+"'),"); } sql.replace(sql.lastIndexOf(","),sql.lastIndexOf(",")+1,";"); namedParameterJdbcTemplate.update(sql.toString(), EmptySqlParameterSource.INSTANCE); } public ResultPage<File> findAllFile(WebFileIndexDTO dto) { return getSQL() .useSql("SELECT files.id,files.module_name,files.name,files.old_file_name,files.new_file_name,files.url,files.store_type,files.suffix,files.state,files.create_at,files.size,files.type,files.biz_id,files.module_code,users.username AS create_man ") .FROM("files") .LEFT_JOIN_ON("users","files.create_man = users.id") .WHERE() .ifPresentAND("files.create_at >= ",dto.getStartTime()) .ifPresentAND("files.create_at >= ",dto.getEndTime()) .ifPresentAND("files.state = ",dto.getState()) .ifPresentAND("files.biz_id = ",dto.getBizId()) .ifPresentAND("users.username LIKE ","%"+dto.getCreateMan()+"%") .ifPresentAND("files.module_code = ",dto.getModuleCode()) .ifPresentAND("files.store_type = ",dto.getStoreType()) .ifPresentAND("files.type = ",dto.getType()) .ifTrueAND("files.biz_id IS NULL",CommonEnum.Is.否.code.equals(dto.getHasBizId())) .ifTrueAND("files.biz_id IS NOT NULL",CommonEnum.Is.是.code.equals(dto.getHasBizId())) .ORDER_BY("files.create_at").DESC() .queryPage(dto.getPageNO(),dto.getPageSize(),File.class); } public List<FileIndexVO> findFileListByBizId(String bizId){ return getSQL() .SELECT("type,url") .FROM("files") .WHERE("biz_id").eqByType(bizId) .ORDER_BY("create_at").ASC() .queryList(FileIndexVO.class); } }
3e054c2f247e407882f072956cc75aadacc2088b
789
java
Java
actor-apps/runtime/src/main/java/im/actor/runtime/Network.java
liruqi/actor-platform-v0.9
29724f0028f84b642e935b6381d5effe556b4a24
[ "MIT" ]
1
2015-10-10T22:49:13.000Z
2015-10-10T22:49:13.000Z
actor-apps/runtime/src/main/java/im/actor/runtime/Network.java
liruqi/actor-platform-v0.9
29724f0028f84b642e935b6381d5effe556b4a24
[ "MIT" ]
null
null
null
actor-apps/runtime/src/main/java/im/actor/runtime/Network.java
liruqi/actor-platform-v0.9
29724f0028f84b642e935b6381d5effe556b4a24
[ "MIT" ]
16
2017-01-12T10:03:02.000Z
2019-04-18T21:09:39.000Z
39.45
111
0.711027
2,226
package im.actor.runtime; import im.actor.runtime.mtproto.ConnectionCallback; import im.actor.runtime.mtproto.ConnectionEndpoint; import im.actor.runtime.mtproto.CreateConnectionCallback; /** * Created by ex3ndr on 08.08.15. */ public class Network { private static NetworkRuntime runtime = new NetworkRuntimeProvider(); public static void createConnection(int connectionId, int mtprotoVersion, int apiMajorVersion, int apiMinorVersion, ConnectionEndpoint endpoint, ConnectionCallback callback, CreateConnectionCallback createCallback) { runtime.createConnection(connectionId, mtprotoVersion, apiMajorVersion, apiMinorVersion, endpoint, callback, createCallback); } }
3e054c4daa35350ae1d3abb7d9ef05c1733f43ab
1,280
java
Java
src/main/java/io/choerodon/iam/infra/dto/UserGuideMenuRelDTO.java
choerodon/base-service
50d39cffb2c306757b12c3af6dab97443386cfa4
[ "Apache-2.0" ]
5
2020-03-20T02:31:52.000Z
2020-07-25T02:35:23.000Z
src/main/java/io/choerodon/iam/infra/dto/UserGuideMenuRelDTO.java
choerodon/base-service
50d39cffb2c306757b12c3af6dab97443386cfa4
[ "Apache-2.0" ]
2
2020-04-13T02:46:40.000Z
2020-07-30T07:13:51.000Z
src/main/java/io/choerodon/iam/infra/dto/UserGuideMenuRelDTO.java
choerodon/base-service
50d39cffb2c306757b12c3af6dab97443386cfa4
[ "Apache-2.0" ]
15
2019-12-05T01:05:49.000Z
2020-09-27T02:43:39.000Z
18.550725
54
0.660156
2,227
package io.choerodon.iam.infra.dto; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import io.swagger.annotations.ApiModelProperty; import io.choerodon.mybatis.domain.AuditDomain; /** * 〈功能简述〉 * 〈〉 * * @author wanghao * @since 2021/5/18 11:05 */ @Table(name = "fd_user_guide_menu_rel") public class UserGuideMenuRelDTO extends AuditDomain { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @ApiModelProperty("菜单id") private Long menuId; @ApiModelProperty("指引id") private Long userGuideId; @ApiModelProperty("tab页code") private String tabCode; public String getTabCode() { return tabCode; } public void setTabCode(String tabCode) { this.tabCode = tabCode; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUserGuideId() { return userGuideId; } public void setUserGuideId(Long userGuideId) { this.userGuideId = userGuideId; } public Long getMenuId() { return menuId; } public void setMenuId(Long menuId) { this.menuId = menuId; } }
3e054d2e989592c0e4d837f437ee7414be5f99cd
7,581
java
Java
src/main/java/us/hebi/matlab/mat/types/Sources.java
diffplug/MatFileIO
6b7cc2661a20523c3cbc3918977bc50d6e1127dd
[ "Apache-2.0" ]
null
null
null
src/main/java/us/hebi/matlab/mat/types/Sources.java
diffplug/MatFileIO
6b7cc2661a20523c3cbc3918977bc50d6e1127dd
[ "Apache-2.0" ]
null
null
null
src/main/java/us/hebi/matlab/mat/types/Sources.java
diffplug/MatFileIO
6b7cc2661a20523c3cbc3918977bc50d6e1127dd
[ "Apache-2.0" ]
null
null
null
29.045977
105
0.579211
2,228
/*- * #%L * Mat-File IO * %% * Copyright (C) 2018 HEBI Robotics * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package us.hebi.matlab.mat.types; import us.hebi.matlab.mat.util.Unsafe9R; import java.io.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import static us.hebi.matlab.mat.util.Preconditions.*; /** * Factory methods for creating sources from various underlying inputs * * @author Florian Enner * @since 03 May 2018 */ public class Sources { public static Source openFile(String file) throws IOException { return openFile(new File((file))); } public static Source openFile(File file) throws IOException { checkNotNull(file); checkArgument(file.exists() && file.isFile(), "must be an existing file"); // File is larger than the max capacity (2 GB) of a buffer, so we use an InputStream instead. // Unfortunately, this limits us to read a very large file using a single thread :( At some point // we could build more complex logic that can map to more than a single buffer. if (file.length() > Integer.MAX_VALUE) { return wrapInputStream(new FileInputStream(file)); } // File is small enough to be memory-mapped into a single buffer final FileChannel channel = new RandomAccessFile(file, "r").getChannel(); final ByteBuffer buffer = channel .map(FileChannel.MapMode.READ_ONLY, 0, (int) channel.size()) .load(); buffer.order(ByteOrder.nativeOrder()); // Wrap as source return new ByteBufferSource(buffer, 512) { @Override public void close() throws IOException { super.close(); Unsafe9R.invokeCleaner(buffer); channel.close(); } }; } public static Source wrap(byte[] bytes) { return wrap(ByteBuffer.wrap(bytes)); } public static Source wrap(ByteBuffer buffer) { return new ByteBufferSource(buffer, 128); } public static Source wrapInputStream(InputStream inputStream) { return wrapInputStream(inputStream, 512); } public static Source wrapInputStream(InputStream inputStream, int bufferSize) { return new InputStreamSource(checkNotNull(inputStream), bufferSize); } private static class ByteBufferSource extends AbstractSource { private ByteBufferSource(ByteBuffer buffer, int bufferSize) { super(bufferSize); this.buffer = buffer; } @Override public InputStream readBytesAsStream(long numBytes) throws IOException { if (numBytes > buffer.remaining()) throw new EOFException(); // Create buffer on subsection ByteBuffer slice = buffer.asReadOnlyBuffer(); slice.limit(buffer.position() + (int) numBytes); // Move underlying buffer along buffer.position(buffer.position() + (int) numBytes); return new ByteBufferInputStream(slice); } @Override public void close() throws IOException { } @Override public boolean isMutatedByChildren() { return false; } @Override public void readByteBuffer(ByteBuffer dst) throws IOException { if (dst.remaining() > buffer.remaining()) throw new EOFException(); // Set dummy limit as there is no bb.get(bb) method int limit = buffer.limit(); try { buffer.limit(buffer.position() + dst.remaining()); dst.put(buffer); } finally { buffer.limit(limit); } } @Override public void readBytes(byte[] bytes, int offset, int length) throws IOException { if (length > buffer.remaining()) throw new EOFException(); buffer.get(bytes, offset, length); } @Override public long getPosition() { return buffer.position(); } final ByteBuffer buffer; } private static class ByteBufferInputStream extends InputStream { private ByteBufferInputStream(ByteBuffer buffer) { this.buffer = buffer; } @Override public int read() { if (buffer.remaining() > 0) return buffer.get() & 0xFF; return -1; } @Override public int read(byte b[], int off, int len) { len = Math.min(len, buffer.remaining()); if (len > 0) { buffer.get(b, off, len); return len; } return -1; } @Override public void close() throws IOException { super.close(); } private final ByteBuffer buffer; } private static class InputStreamSource extends AbstractSource { InputStreamSource(InputStream input, int bufferSize) { super(bufferSize); this.input = input; } @Override public long getPosition() { return position; } @Override public void readBytes(byte[] bytes, int offset, int length) throws IOException { int n = 0; while (n < length) { int count = input.read(bytes, offset + n, length - n); if (count < 0) { String format = "Reached end of stream after reading %d bytes. Expected %d bytes."; throw new EOFException(String.format(format, n, length)); } n += count; } position += length; } @Override public boolean isMutatedByChildren() { return true; } @Override protected InputStream readBytesAsStream(long numBytes) { return new SourceInputStream(this, numBytes); } @Override public void close() throws IOException { input.close(); } long position = 0; final InputStream input; } private static class SourceInputStream extends InputStream { private SourceInputStream(Source matInput, long maxLength) { this.matInput = matInput; this.maxLength = maxLength; } @Override public int read(byte b[], int off, int len) throws IOException { int remaining = (int) (maxLength - position); if (remaining == 0) return -1; len = Math.min(len, remaining); matInput.readBytes(b, off, len); position += len; return len; } @Override public int read() { throw new IllegalStateException("not implemented"); } long position = 0; final Source matInput; final long maxLength; } private Sources() { } }
3e054dac38ed33291ff30c2fd85af494790d8364
1,685
java
Java
src/main/java/com/tradenity/sdk/model/CustomerGroup.java
tradenity/java-sdk
0722ca324a26483141968edf4e18a8076a6a2c7e
[ "Apache-2.0" ]
null
null
null
src/main/java/com/tradenity/sdk/model/CustomerGroup.java
tradenity/java-sdk
0722ca324a26483141968edf4e18a8076a6a2c7e
[ "Apache-2.0" ]
null
null
null
src/main/java/com/tradenity/sdk/model/CustomerGroup.java
tradenity/java-sdk
0722ca324a26483141968edf4e18a8076a6a2c7e
[ "Apache-2.0" ]
null
null
null
21.329114
60
0.632047
2,229
package com.tradenity.sdk.model; import java.util.Map; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.LinkedHashSet; import java.util.Date; public class CustomerGroup extends BaseModel{ public static final String STATUS_ENABLED = "enabled"; public static final String STATUS_DISABLED = "disabled"; private String name; private String slug; private String status; private String description; public CustomerGroup(){ } public CustomerGroup id(String id) { this.setId(id); return this; } public String getName() { return name; } public void setName(String name) { this.name = name; } public CustomerGroup name(String name) { this.setName(name); return this; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public CustomerGroup slug(String slug) { this.setSlug(slug); return this; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public CustomerGroup status(String status) { this.setStatus(status); return this; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public CustomerGroup description(String description) { this.setDescription(description); return this; } }
3e054e56ee4ab62bb072aa36558d0ab0c1715ab4
3,526
java
Java
src/sources/com/google/common/graph/NetworkBuilder.java
ghuntley/COVIDSafe_1.0.11.apk
ba4133e6c8092d7c2881562fcb0c46ec7af04ecb
[ "Apache-2.0" ]
50
2020-04-26T12:26:18.000Z
2020-05-08T12:59:45.000Z
src/sources/com/google/common/graph/NetworkBuilder.java
ghuntley/COVIDSafe_1.0.11.apk
ba4133e6c8092d7c2881562fcb0c46ec7af04ecb
[ "Apache-2.0" ]
null
null
null
src/sources/com/google/common/graph/NetworkBuilder.java
ghuntley/COVIDSafe_1.0.11.apk
ba4133e6c8092d7c2881562fcb0c46ec7af04ecb
[ "Apache-2.0" ]
8
2020-04-27T00:37:19.000Z
2020-05-05T07:54:07.000Z
39.617978
190
0.675269
2,230
package com.google.common.graph; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.graph.ImmutableNetwork; public final class NetworkBuilder<N, E> extends AbstractGraphBuilder<N> { boolean allowsParallelEdges = false; ElementOrder<? super E> edgeOrder = ElementOrder.insertion(); Optional<Integer> expectedEdgeCount = Optional.absent(); private <N1 extends N, E1 extends E> NetworkBuilder<N1, E1> cast() { return this; } private NetworkBuilder(boolean z) { super(z); } public static NetworkBuilder<Object, Object> directed() { return new NetworkBuilder<>(true); } public static NetworkBuilder<Object, Object> undirected() { return new NetworkBuilder<>(false); } /* JADX WARNING: type inference failed for: r2v0, types: [com.google.common.graph.Network<N, E>, com.google.common.graph.Network] */ /* JADX WARNING: Unknown variable types count: 1 */ /* Code decompiled incorrectly, please refer to instructions dump. */ public static <N, E> com.google.common.graph.NetworkBuilder<N, E> from(com.google.common.graph.Network<N, E> r2) { /* com.google.common.graph.NetworkBuilder r0 = new com.google.common.graph.NetworkBuilder boolean r1 = r2.isDirected() r0.<init>(r1) boolean r1 = r2.allowsParallelEdges() com.google.common.graph.NetworkBuilder r0 = r0.allowsParallelEdges(r1) boolean r1 = r2.allowsSelfLoops() com.google.common.graph.NetworkBuilder r0 = r0.allowsSelfLoops(r1) com.google.common.graph.ElementOrder r1 = r2.nodeOrder() com.google.common.graph.NetworkBuilder r0 = r0.nodeOrder(r1) com.google.common.graph.ElementOrder r2 = r2.edgeOrder() com.google.common.graph.NetworkBuilder r2 = r0.edgeOrder(r2) return r2 */ throw new UnsupportedOperationException("Method not decompiled: com.google.common.graph.NetworkBuilder.from(com.google.common.graph.Network):com.google.common.graph.NetworkBuilder"); } public <N1 extends N, E1 extends E> ImmutableNetwork.Builder<N1, E1> immutable() { return new ImmutableNetwork.Builder<>(cast()); } public NetworkBuilder<N, E> allowsParallelEdges(boolean z) { this.allowsParallelEdges = z; return this; } public NetworkBuilder<N, E> allowsSelfLoops(boolean z) { this.allowsSelfLoops = z; return this; } public NetworkBuilder<N, E> expectedNodeCount(int i) { this.expectedNodeCount = Optional.of(Integer.valueOf(Graphs.checkNonNegative(i))); return this; } public NetworkBuilder<N, E> expectedEdgeCount(int i) { this.expectedEdgeCount = Optional.of(Integer.valueOf(Graphs.checkNonNegative(i))); return this; } public <N1 extends N> NetworkBuilder<N1, E> nodeOrder(ElementOrder<N1> elementOrder) { NetworkBuilder<N1, E> cast = cast(); cast.nodeOrder = (ElementOrder) Preconditions.checkNotNull(elementOrder); return cast; } public <E1 extends E> NetworkBuilder<N, E1> edgeOrder(ElementOrder<E1> elementOrder) { NetworkBuilder<N, E1> cast = cast(); cast.edgeOrder = (ElementOrder) Preconditions.checkNotNull(elementOrder); return cast; } public <N1 extends N, E1 extends E> MutableNetwork<N1, E1> build() { return new ConfigurableMutableNetwork(this); } }
3e054e6604389f28a88078346739df193315e3bd
1,246
java
Java
rest/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/core/PropertyKeyMapping.java
K-Beach/sw360
6c2d4614f4b8ff95999a05103fcd483a77a65b63
[ "CC0-1.0" ]
1
2020-04-01T14:54:30.000Z
2020-04-01T14:54:30.000Z
rest/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/core/PropertyKeyMapping.java
tswcos/sw360
003aba48bdc132d882f7df387e4f4853b786220a
[ "CC0-1.0" ]
null
null
null
rest/resource-server/src/main/java/org/eclipse/sw360/rest/resourceserver/core/PropertyKeyMapping.java
tswcos/sw360
003aba48bdc132d882f7df387e4f4853b786220a
[ "CC0-1.0" ]
null
null
null
29.666667
76
0.682986
2,231
/* * Copyright Bosch Software Innovations GmbH, 2018. * Part of the SW360 Portal Project. * * SPDX-License-Identifier: EPL-1.0 * * 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 */ package org.eclipse.sw360.rest.resourceserver.core; class PropertyKeyMapping { private static final String COMPONENT_VENDOR_KEY_THRIFT = "vendorNames"; static final String COMPONENT_VENDOR_KEY_JSON = "vendors"; private static final String RELEASE_CPEID_KEY_THRIFT = "cpeid"; static final String RELEASE_CPEID_KEY_JSON = "cpeId"; static String componentThriftKeyFromJSONKey(String jsonKey) { switch (jsonKey) { case COMPONENT_VENDOR_KEY_JSON: return COMPONENT_VENDOR_KEY_THRIFT; default: return jsonKey; } } static String releaseThriftKeyFromJSONKey(String jsonKey) { switch (jsonKey) { case RELEASE_CPEID_KEY_JSON: return RELEASE_CPEID_KEY_THRIFT; default: return jsonKey; } } }
3e054ea0b44dfb1545107b0ac44198e7f90481f9
22,387
java
Java
Android/SAIOT/app/src/main/java/androidtown/org/saiot/HomeFragment.java
ChangYeop-Yang/Activity-CapstoneDesign
9bbf78a832194370298c28ea92b2abe8e666f3e5
[ "MIT" ]
1
2018-03-14T04:35:31.000Z
2018-03-14T04:35:31.000Z
Android/SAIOT/app/src/main/java/androidtown/org/saiot/HomeFragment.java
ChangYeop-Yang/Activity-CapstoneDesign
9bbf78a832194370298c28ea92b2abe8e666f3e5
[ "MIT" ]
19
2018-03-22T03:27:22.000Z
2018-06-20T08:06:25.000Z
Android/SAIOT/app/src/main/java/androidtown/org/saiot/HomeFragment.java
ChangYeop-Yang/Activity-CapstoneDesign
9bbf78a832194370298c28ea92b2abe8e666f3e5
[ "MIT" ]
1
2018-04-02T05:00:39.000Z
2018-04-02T05:00:39.000Z
31.664781
118
0.581454
2,232
package androidtown.org.saiot; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.github.mikephil.charting.charts.LineChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.LineData; import com.github.mikephil.charting.data.LineDataSet; import com.github.mikephil.charting.interfaces.datasets.ILineDataSet; import com.github.mikephil.charting.utils.ColorTemplate; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; /** * A simple {@link Fragment} subclass. */ public class HomeFragment extends Fragment { MainActivity activity; private static final String ARG_PARAM1="param1"; private static final String ARG_PARAM2="param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private Button huebtn; private OnFragmentInteractionListener mListener; //꺽은선 그래프 LineChart tempchart; LineChart cdschart; LineChart gaschart; LineChart noisechart; int X_RANGE = 100; int DATA_RANGE = 30; ArrayList<Entry> xVal,xVal2,xVal3,xVal4; LineDataSet setXcomp,setXcomp2,setXcomp3,setXcomp4; ArrayList<String> xVals,xVals2,xVals3,xVals4; ArrayList<ILineDataSet> lineDataSets,lineDataSets2,lineDataSets3,lineDataSets4; LineData lineData,lineData2,lineData3,lineData4; //json추가 TextView txtView; phpDown task; ArrayList<ListItem> listItem= new ArrayList<ListItem>(); ListItem Item; public HomeFragment() { // Required empty public constructor } public static HomeFragment newInstance(String param1, String param2) { HomeFragment fragment = new HomeFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } //init(); // threadStart(); } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); activity = (MainActivity)getActivity(); } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_home,container,false); //json task = new phpDown(); //imView = (ImageView) findViewById(R.id.imageView1); task.execute("http://yeop9657.duckdns.org/select.php"); tempchart = (LineChart)view.findViewById(R.id.chart2); tempchart.setAutoScaleMinMaxEnabled(true); tempchart.setDescription(""); tempchart.setNoDataTextDescription("No data for the moment"); //하이라이팅 tempchart.setHighlightPerDragEnabled(true); tempchart.setTouchEnabled(true); tempchart.setDragEnabled(true); tempchart.setDrawGridBackground(false); //chart.setPinchZoom(true); tempchart.setBackgroundColor(Color.GRAY); xVal = new ArrayList<Entry>(); setXcomp = new LineDataSet(xVal, "TEMPERATURE"); setXcomp.setDrawCubic(true); setXcomp.setCubicIntensity(0.2f); setXcomp.setAxisDependency(YAxis.AxisDependency.LEFT); setXcomp.setColor(ColorTemplate.getHoloBlue()); setXcomp.setCircleColor(ColorTemplate.getHoloBlue()); setXcomp.setLineWidth(2f); setXcomp.setCircleRadius(2f); setXcomp.setFillAlpha(65); setXcomp.setFillColor(ColorTemplate.getHoloBlue()); setXcomp.setHighLightColor(Color.rgb(244,117,177)); setXcomp.setDrawValues(false); setXcomp.setAxisDependency(YAxis.AxisDependency.LEFT); lineDataSets = new ArrayList<ILineDataSet>(); lineDataSets.add(setXcomp); Legend l = tempchart.getLegend(); l.setForm(Legend.LegendForm.LINE); l.setTextColor(Color.WHITE); XAxis x1 = tempchart.getXAxis(); x1.setTextColor(Color.WHITE); x1.setDrawGridLines(false); x1.setAvoidFirstLastClipping(true); YAxis y1=tempchart.getAxisLeft(); y1.setTextColor(Color.WHITE); y1.setDrawGridLines(true); YAxis y12=tempchart.getAxisRight(); y12.setEnabled(false); tempchart.invalidate(); //CDS그래프 cdschart = (LineChart)view.findViewById(R.id.chart3); cdschart.setAutoScaleMinMaxEnabled(true); cdschart.setDescription(""); cdschart.setNoDataTextDescription("No data for the moment"); //하이라이팅 cdschart.setHighlightPerDragEnabled(true); cdschart.setTouchEnabled(true); cdschart.setDragEnabled(true); cdschart.setDrawGridBackground(false); //chart.setPinchZoom(true); cdschart.setBackgroundColor(Color.GRAY); xVal2 = new ArrayList<Entry>(); setXcomp2 = new LineDataSet(xVal2, "CDS"); setXcomp2.setDrawCubic(true); setXcomp2.setCubicIntensity(0.2f); setXcomp2.setAxisDependency(YAxis.AxisDependency.LEFT); setXcomp2.setColor(ColorTemplate.getHoloBlue()); setXcomp2.setCircleColor(ColorTemplate.getHoloBlue()); setXcomp2.setLineWidth(2f); setXcomp2.setCircleRadius(2f); setXcomp2.setFillAlpha(65); setXcomp2.setFillColor(ColorTemplate.getHoloBlue()); setXcomp2.setHighLightColor(Color.rgb(244,117,177)); setXcomp2.setDrawValues(false); setXcomp2.setAxisDependency(YAxis.AxisDependency.LEFT); lineDataSets2 = new ArrayList<ILineDataSet>(); lineDataSets2.add(setXcomp2); Legend l2 = cdschart.getLegend(); l2.setForm(Legend.LegendForm.LINE); l2.setTextColor(Color.WHITE); XAxis x2 = cdschart.getXAxis(); x2.setTextColor(Color.WHITE); x2.setDrawGridLines(false); x2.setAvoidFirstLastClipping(true); YAxis y2=cdschart.getAxisLeft(); y2.setTextColor(Color.WHITE); y2.setDrawGridLines(true); YAxis y22=cdschart.getAxisRight(); y22.setEnabled(false); cdschart.invalidate(); //GAS 그래프 gaschart = (LineChart)view.findViewById(R.id.chart4); gaschart.setAutoScaleMinMaxEnabled(true); gaschart.setDescription(""); gaschart.setNoDataTextDescription("No data for the moment"); //하이라이팅 gaschart.setHighlightPerDragEnabled(true); gaschart.setTouchEnabled(true); gaschart.setDragEnabled(true); gaschart.setDrawGridBackground(false); //chart.setPinchZoom(true); gaschart.setBackgroundColor(Color.GRAY); xVal3 = new ArrayList<Entry>(); setXcomp3 = new LineDataSet(xVal3, "GAS"); setXcomp3.setDrawCubic(true); setXcomp3.setCubicIntensity(0.2f); setXcomp3.setAxisDependency(YAxis.AxisDependency.LEFT); setXcomp3.setColor(ColorTemplate.getHoloBlue()); setXcomp3.setCircleColor(ColorTemplate.getHoloBlue()); setXcomp3.setLineWidth(2f); setXcomp3.setCircleRadius(2f); setXcomp3.setFillAlpha(65); setXcomp3.setFillColor(ColorTemplate.getHoloBlue()); setXcomp3.setHighLightColor(Color.rgb(244,117,177)); setXcomp3.setDrawValues(false); setXcomp3.setAxisDependency(YAxis.AxisDependency.LEFT); lineDataSets3 = new ArrayList<ILineDataSet>(); lineDataSets3.add(setXcomp3); Legend l3 = gaschart.getLegend(); l3.setForm(Legend.LegendForm.LINE); l3.setTextColor(Color.WHITE); XAxis x3 = gaschart.getXAxis(); x3.setTextColor(Color.WHITE); x3.setDrawGridLines(false); x3.setAvoidFirstLastClipping(true); YAxis y3=gaschart.getAxisLeft(); y3.setTextColor(Color.WHITE); y3.setDrawGridLines(true); YAxis y33=gaschart.getAxisRight(); y33.setEnabled(false); gaschart.invalidate(); //NOISE 그래프 noisechart = (LineChart)view.findViewById(R.id.chart5); noisechart.setAutoScaleMinMaxEnabled(true); noisechart.setDescription(""); noisechart.setNoDataTextDescription("No data for the moment"); //하이라이팅 noisechart.setHighlightPerDragEnabled(true); noisechart.setTouchEnabled(true); noisechart.setDragEnabled(true); noisechart.setDrawGridBackground(false); //chart.setPinchZoom(true); noisechart.setBackgroundColor(Color.GRAY); xVal4 = new ArrayList<Entry>(); setXcomp4 = new LineDataSet(xVal4, "NOISE"); setXcomp4.setDrawCubic(true); setXcomp4.setCubicIntensity(0.2f); setXcomp4.setAxisDependency(YAxis.AxisDependency.LEFT); setXcomp4.setColor(ColorTemplate.getHoloBlue()); setXcomp4.setCircleColor(ColorTemplate.getHoloBlue()); setXcomp4.setLineWidth(2f); setXcomp4.setCircleRadius(2f); setXcomp4.setFillAlpha(65); setXcomp4.setFillColor(ColorTemplate.getHoloBlue()); setXcomp4.setHighLightColor(Color.rgb(244,117,177)); setXcomp4.setDrawValues(false); setXcomp4.setAxisDependency(YAxis.AxisDependency.LEFT); lineDataSets4= new ArrayList<ILineDataSet>(); lineDataSets4.add(setXcomp4); Legend l4 = noisechart.getLegend(); l4.setForm(Legend.LegendForm.LINE); l4.setTextColor(Color.WHITE); XAxis x4 = noisechart.getXAxis(); x4.setTextColor(Color.WHITE); x4.setDrawGridLines(false); x4.setAvoidFirstLastClipping(true); YAxis y4=noisechart.getAxisLeft(); y4.setTextColor(Color.WHITE); y4.setDrawGridLines(true); YAxis y44=noisechart.getAxisRight(); y44.setEnabled(false); noisechart.invalidate(); //init(); //threadStart(); //데이터 입력 // if (xVal.size() > DATA_RANGE) { // xVal.remove(0); // for (int i = 0; i < DATA_RANGE; i++) { // xVal.get(i).setXIndex(i); // } // } // xVal.add(new Entry(Integer.parseInt(listItem.get(0).getData(1)), xVal.size())); // setXcomp.notifyDataSetChanged(); // chart.notifyDataSetChanged(); // chart.invalidate(); //buttonoutside=(Button) getActivity().findViewById(R.id.buttonoutside); //휴 버튼 huebtn = (Button) view.findViewById(R.id.huebtn); huebtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Handler().postDelayed(new Runnable() {//1초후 실행 @Override public void run() { //1초후 실행할 Activity root = getActivity(); //이 클래스가 프레그먼트이기 때문에 액티비티 정보를 얻는다. Toast.makeText(root, "토스트 사용!", Toast.LENGTH_SHORT).show(); Intent intent1 = new Intent(getActivity(), CustomDialogActivity.class); startActivity(intent1); } },1000); // view.startAnimation(animation); //return view; } }); //충돌때문에 여기로 5.26 //final String addr = "coldy24.iptime.org"; //new ConnectServer(addr, 8090, getActivity()).execute(); return view; // Inflate the layout for this fragment //return inflater.inflate(R.layout.fragment_home, container, false); } private class phpDown extends AsyncTask<String, Integer,String> { @Override protected String doInBackground(String... urls) { StringBuilder jsonHtml = new StringBuilder(); try{ // 연결 url 설정 URL url = new URL(urls[0]); // 커넥션 객체 생성 HttpURLConnection conn = (HttpURLConnection)url.openConnection(); // 연결되었으면. if(conn != null){ conn.setConnectTimeout(10000); conn.setUseCaches(false); // 연결되었음 코드가 리턴되면. if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){ BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); for(;;){ // 웹상에 보여지는 텍스트를 라인단위로 읽어 저장. String line = br.readLine(); if(line == null) break; // 저장된 텍스트 라인을 jsonHtml에 붙여넣음 jsonHtml.append(line + "\n"); } br.close(); } conn.disconnect(); } } catch(Exception ex){ ex.printStackTrace(); } return jsonHtml.toString(); } protected void onPostExecute(String str){ String datetime; String temp; String cmd; String noise; String gas; int num=0; try{ JSONObject root = new JSONObject(str); JSONArray ja=root.getJSONArray("SensorDatas"); num= ja.length(); for(int i=0; i<ja.length();i++){ JSONObject jo = ja.getJSONObject(i); datetime = jo.getString("Insert_DT"); temp = jo.getString("AVG(Temp_NO)"); cmd = jo.getString("AVG(Cmd_NO)"); noise = jo.getString("AVG(Noise_NO)"); gas = jo.getString("AVG(Gas_FL)"); listItem.add(new ListItem(datetime,temp,cmd,noise,gas)); } }catch (JSONException e){ e.printStackTrace(); } // if (xVal.size() > DATA_RANGE) { // xVal.remove(0); // for (int i = 0; i < DATA_RANGE; i++) { // xVal.get(i).setXIndex(i); // } // } int a; //온도 그래프차트 //날짜 데이터 시간만 표시 xVals = new ArrayList<String>(); for (int i = 0; i < num; i++) { // xVals.add(listItem.get(i).getData(0)); String oldstring = listItem.get(i).getData(0); try { Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(oldstring); String newstring = new SimpleDateFormat("HH:mm").format(date); xVals.add(newstring); } catch (ParseException e) { e.printStackTrace(); } } lineData = new LineData(xVals, lineDataSets); tempchart.setData(lineData); for(int i=0; i<num; i++) { xVal.add(new Entry((int)Double.parseDouble(listItem.get(i).getData(1)), xVal.size())); setXcomp.notifyDataSetChanged(); tempchart.notifyDataSetChanged(); } tempchart.invalidate(); //CDS그래프 차트 xVals2 = new ArrayList<String>(); for (int i = 0; i < num; i++) { // xVals.add(listItem.get(i).getData(0)); String oldstring = listItem.get(i).getData(0); try { Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(oldstring); String newstring = new SimpleDateFormat("HH:mm").format(date); xVals2.add(newstring); } catch (ParseException e) { e.printStackTrace(); } } lineData2 = new LineData(xVals2, lineDataSets2); cdschart.setData(lineData2); for(int i=0; i<num; i++) { xVal2.add(new Entry((int)Double.parseDouble(listItem.get(i).getData(2)), xVal2.size())); setXcomp2.notifyDataSetChanged(); cdschart.notifyDataSetChanged(); } cdschart.invalidate(); //GAS그래프 차트 xVals3 = new ArrayList<String>(); for (int i = 0; i < num; i++) { // xVals.add(listItem.get(i).getData(0)); String oldstring = listItem.get(i).getData(0); try { Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(oldstring); String newstring = new SimpleDateFormat("HH:mm").format(date); xVals3.add(newstring); } catch (ParseException e) { e.printStackTrace(); } } lineData3 = new LineData(xVals3, lineDataSets3); gaschart.setData(lineData3); for(int i=0; i<num; i++) { xVal3.add(new Entry((int)Double.parseDouble(listItem.get(i).getData(3)), xVal3.size())); setXcomp3.notifyDataSetChanged(); gaschart.notifyDataSetChanged(); } gaschart.invalidate(); //noise그래프 차트 xVals4 = new ArrayList<String>(); for (int i = 0; i < num; i++) { // xVals.add(listItem.get(i).getData(0)); String oldstring = listItem.get(i).getData(0); try { Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(oldstring); String newstring = new SimpleDateFormat("HH:mm").format(date); xVals4.add(newstring); } catch (ParseException e) { e.printStackTrace(); } } lineData4 = new LineData(xVals4, lineDataSets4); noisechart.setData(lineData4); for(int i=0; i<num; i++) { xVal4.add(new Entry((int)Double.parseDouble(listItem.get(i).getData(4)), xVal4.size())); setXcomp4.notifyDataSetChanged(); noisechart.notifyDataSetChanged(); } noisechart.invalidate(); } } /* private void init() { chart = (LineChart)getActivity().findViewById(R.id.chart2); chart.setAutoScaleMinMaxEnabled(true); xVal = new ArrayList<Entry>(); setXcomp = new LineDataSet(xVal, "TEMPERATURE"); setXcomp.setColor(Color.RED); setXcomp.setDrawValues(false); setXcomp.setDrawCircles(false); setXcomp.setAxisDependency(YAxis.AxisDependency.LEFT); lineDataSets = new ArrayList<ILineDataSet>(); lineDataSets.add(setXcomp); xVals = new ArrayList<String>(); for (int i = 0; i < X_RANGE; i++) { xVals.add(""); } lineData = new LineData(xVals, lineDataSets); chart.setData(lineData); chart.invalidate(); }*/ /* private void chartInit() { chart.setAutoScaleMinMaxEnabled(true); xVal = new ArrayList<Entry>(); setXcomp = new LineDataSet(xVal, "TEMPERATURE"); setXcomp.setColor(Color.RED); setXcomp.setDrawValues(false); setXcomp.setDrawCircles(false); setXcomp.setAxisDependency(YAxis.AxisDependency.LEFT); lineDataSets = new ArrayList<ILineDataSet>(); lineDataSets.add(setXcomp); xVals = new ArrayList<String>(); for (int i = 0; i < X_RANGE; i++) { xVals.add(""); } lineData = new LineData(xVals, lineDataSets); chart.setData(lineData); chart.invalidate(); } */ // public void chartUpdate(int x) { // // if (xVal.size() > DATA_RANGE) { // xVal.remove(0); // for (int i = 0; i < DATA_RANGE; i++) { // xVal.get(i).setXIndex(i); // } // } // xVal.add(new Entry(x, xVal.size())); // setXcomp.notifyDataSetChanged(); // chart.notifyDataSetChanged(); // chart.invalidate(); // // // // // } // // // Handler handler = new Handler() { // @Override // public void handleMessage(Message msg) { // if (msg.what == 0) { // Message id 가 0 이면 // int a = 0; // a = (int) (Math.random() * 200); // chartUpdate(a); // } // } // }; // // class MyThread extends Thread { // @Override // public void run() { // while (true) { // handler.sendEmptyMessage(0); // try { // Thread.sleep(500); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // } // } // // private void threadStart() { // MyThread thread = new MyThread(); // thread.setDaemon(true); // thread.start(); // } public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } }
3e055132d12272e2dff800f51c79dc89bfced6b7
14,973
java
Java
core/src/main/java/arez/Task.java
arez/arez
f2872c54b639524a60caf67c65ec4a63a93dc500
[ "Apache-2.0" ]
11
2018-01-26T13:05:03.000Z
2022-02-24T08:43:46.000Z
core/src/main/java/arez/Task.java
arez/arez
f2872c54b639524a60caf67c65ec4a63a93dc500
[ "Apache-2.0" ]
103
2018-02-05T23:04:59.000Z
2022-02-11T03:47:44.000Z
core/src/main/java/arez/Task.java
arez/arez
f2872c54b639524a60caf67c65ec4a63a93dc500
[ "Apache-2.0" ]
3
2018-05-16T00:00:33.000Z
2018-07-17T07:04:56.000Z
29.073786
112
0.63147
2,233
package arez; import arez.spy.Priority; import arez.spy.TaskCompleteEvent; import arez.spy.TaskInfo; import arez.spy.TaskStartEvent; import grim.annotations.OmitSymbol; import java.util.Objects; import javax.annotation.Nonnull; import javax.annotation.Nullable; import static org.realityforge.braincheck.Guards.*; /** * A task represents an executable element that can be run by the task executor. */ public final class Task extends Node { /** * The code to invoke when task is executed. */ @Nonnull private final SafeProcedure _work; /** * State of the task. */ private int _flags; /** * Cached info object associated with element. * This should be null if {@link Arez#areSpiesEnabled()} is false; */ @OmitSymbol( unless = "arez.enable_spies" ) @Nullable private TaskInfo _info; Task( @Nullable final ArezContext context, @Nullable final String name, @Nonnull final SafeProcedure work, final int flags ) { super( context, name ); if ( Arez.shouldCheckApiInvariants() ) { apiInvariant( () -> ( ~Flags.CONFIG_FLAGS_MASK & flags ) == 0, () -> "Arez-0224: Task named '" + name + "' passed invalid flags: " + ( ~Flags.CONFIG_FLAGS_MASK & flags ) ); } _work = Objects.requireNonNull( work ); _flags = flags | Flags.STATE_IDLE | Flags.runType( flags ) | Flags.priority( flags ); if ( Arez.areRegistriesEnabled() && 0 == ( _flags & Flags.NO_REGISTER_TASK ) ) { getContext().registerTask( this ); } } /** * Re-schedule this task if it is idle and trigger the scheduler if it is not active. */ public void schedule() { if ( isIdle() ) { queueTask(); } getContext().triggerScheduler(); } int getFlags() { return _flags; } void queueTask() { getContext().getTaskQueue().queueTask( this ); } void initialSchedule() { queueTask(); triggerSchedulerInitiallyUnlessRunLater(); } void triggerSchedulerInitiallyUnlessRunLater() { // If we have not explicitly supplied the RUN_LATER flag then assume it is a run now and // trigger the scheduler if ( 0 == ( _flags & Flags.RUN_LATER ) ) { getContext().triggerScheduler(); } } /** * Return the priority of the task. * This is only meaningful when TaskQueue observes priority. * * @return the priority of the task. */ int getPriorityIndex() { return Flags.getPriorityIndex( _flags ); } /** * Return the priority enum for task. * * @return the priority. */ @Nonnull Priority getPriority() { return Priority.values()[ getPriorityIndex() ]; } /** * Return the task. * * @return the task. */ @Nonnull SafeProcedure getWork() { return _work; } /** * Execute the work associated with the task. */ void executeTask() { // It is possible that the task was executed outside the executor and // may no longer need to be executed. This particularly true when executing tasks // using the "idle until urgent" strategy. if ( isQueued() ) { markAsIdle(); if ( 0 == ( _flags & Flags.NO_WRAP_TASK ) ) { runTask(); } else { // It is expected that the task/observers currently catch error // and handle internally. Thus no need to catch errors here. _work.call(); } // If this task has been marked as a task to dispose on completion then do so if ( 0 != ( _flags & Flags.DISPOSE_ON_COMPLETE ) ) { dispose(); } } } /** * Actually execute the task, capture errors and send spy events. */ private void runTask() { long startedAt = 0L; if ( willPropagateSpyEvents() ) { startedAt = System.currentTimeMillis(); getSpy().reportSpyEvent( new TaskStartEvent( asInfo() ) ); } Throwable error = null; try { getWork().call(); } catch ( final Throwable t ) { // Should we handle it with a per-task handler or a global error handler? error = t; } if ( willPropagateSpyEvents() ) { final long duration = System.currentTimeMillis() - startedAt; getSpy().reportSpyEvent( new TaskCompleteEvent( asInfo(), error, (int) duration ) ); } } @Override public void dispose() { if ( isNotDisposed() ) { _flags = Flags.setState( _flags, Flags.STATE_DISPOSED ); if ( Arez.areRegistriesEnabled() && 0 == ( _flags & Flags.NO_REGISTER_TASK ) ) { getContext().deregisterTask( this ); } } } @Override public boolean isDisposed() { return Flags.STATE_DISPOSED == Flags.getState( _flags ); } /** * Return the info associated with this class. * * @return the info associated with this class. */ @SuppressWarnings( "ConstantConditions" ) @OmitSymbol( unless = "arez.enable_spies" ) @Nonnull TaskInfo asInfo() { if ( Arez.shouldCheckInvariants() ) { invariant( Arez::areSpiesEnabled, () -> "Arez-0130: Task.asInfo() invoked but Arez.areSpiesEnabled() returned false." ); } if ( Arez.areSpiesEnabled() && null == _info ) { _info = new TaskInfoImpl( this ); } return Arez.areSpiesEnabled() ? _info : null; } /** * Mark task as being queued, first verifying that it is not already queued. * This is used so that task will not be able to be queued again until it has run. */ void markAsQueued() { if ( Arez.shouldCheckInvariants() ) { invariant( this::isIdle, () -> "Arez-0128: Attempting to queue task named '" + getName() + "' when task is not idle." ); } _flags = Flags.setState( _flags, Flags.STATE_QUEUED ); } /** * Clear the queued flag, first verifying that the task is queued. */ void markAsIdle() { if ( Arez.shouldCheckInvariants() ) { invariant( this::isQueued, () -> "Arez-0129: Attempting to clear queued flag on task named '" + getName() + "' but task is not queued." ); } _flags = Flags.setState( _flags, Flags.STATE_IDLE ); } /** * Return true if task is idle or not disposed and not scheduled. * * @return true if task is idle. */ boolean isIdle() { return Flags.STATE_IDLE == Flags.getState( _flags ); } /** * Return true if task is already scheduled. * * @return true if task is already scheduled. */ boolean isQueued() { return Flags.STATE_QUEUED == Flags.getState( _flags ); } public static final class Flags { /** * Highest priority. * This priority should be used when the task will dispose or release other reactive elements * (and thus remove elements from being scheduled). * * <p>Only one of the PRIORITY_* flags should be applied to a task.</p> * * @see arez.annotations.Priority#HIGHEST * @see Priority#HIGHEST */ public static final int PRIORITY_HIGHEST = 0b001 << 15; /** * High priority. * To reduce the chance that downstream elements will react multiple times within a single * reaction round, this priority should be used when the task may trigger many downstream tasks. * <p>Only one of the PRIORITY_* flags should be applied to a task.</p> * * @see arez.annotations.Priority#HIGH * @see Priority#HIGH */ public static final int PRIORITY_HIGH = 0b010 << 15; /** * Normal priority if no other priority otherwise specified. * * <p>Only one of the PRIORITY_* flags should be applied to a task.</p> * * @see arez.annotations.Priority#NORMAL * @see Priority#NORMAL */ public static final int PRIORITY_NORMAL = 0b011 << 15; /** * Low priority. * Usually used to schedule tasks that reflect state onto non-reactive * application components. i.e. Tasks that are used to build html views, * perform network operations etc. These reactions are often at low priority * to avoid recalculation of dependencies (i.e. {@link ComputableValue}s) triggering * this reaction multiple times within a single reaction round. * * <p>Only one of the PRIORITY_* flags should be applied to a task.</p> * * @see arez.annotations.Priority#LOW * @see Priority#LOW */ public static final int PRIORITY_LOW = 0b100 << 15; /** * Lowest priority. Use this priority if the task is a {@link ComputableValue} that * may be unobserved when a {@link #PRIORITY_LOW} observer reacts. This is used to avoid * recomputing state that is likely to either be unobserved or recomputed as part of * another observers reaction. * <p>Only one of the PRIORITY_* flags should be applied to a task.</p> * * @see arez.annotations.Priority#LOWEST * @see Priority#LOWEST */ public static final int PRIORITY_LOWEST = 0b101 << 15; /** * Mask used to extract priority bits. */ static final int PRIORITY_MASK = 0b111 << 15; /** * Shift used to extract priority after applying mask. */ private static final int PRIORITY_SHIFT = 15; /** * The number of priority levels. */ static final int PRIORITY_COUNT = 5; /** * The scheduler will be triggered when the task is created to immediately invoke the task. * This should not be specified if {@link #RUN_LATER} is specified. */ public static final int RUN_NOW = 1 << 22; /** * The scheduler will not be triggered when the task is created. The application is responsible * for ensuring thatthe {@link ArezContext#triggerScheduler()} method is invoked at a later time. * This should not be specified if {@link #RUN_NOW} is specified. */ public static final int RUN_LATER = 1 << 21; /** * Mask used to extract run type bits. */ static final int RUN_TYPE_MASK = RUN_NOW | RUN_LATER; /** * The flag that indicates that task should not be wrapped. * The wrapping is responsible for ensuring the task never generates an exception and for generating * the spy events. If wrapping is disabled it is expected that the caller is responsible for integrating * with the spy subsystem and catching exceptions if any. */ public static final int NO_WRAP_TASK = 1 << 20; /** * The flag that specifies that the task should be disposed after it has completed execution. */ public static final int DISPOSE_ON_COMPLETE = 1 << 19; /** * The flag that indicates that task should not be registered in top level registry. * This is used when Observers etc create tasks and do not need them exposed to the spy framework. */ static final int NO_REGISTER_TASK = 1 << 18; /** * Mask containing flags that can be applied to a task. */ static final int CONFIG_FLAGS_MASK = PRIORITY_MASK | RUN_TYPE_MASK | DISPOSE_ON_COMPLETE | NO_REGISTER_TASK | NO_WRAP_TASK; /** * Mask containing flags that can be applied to a task representing an observer. * This omits DISPOSE_ON_COMPLETE as observer is responsible for disposing task */ static final int OBSERVER_TASK_FLAGS_MASK = PRIORITY_MASK | RUN_TYPE_MASK; /** * State when the task has not been scheduled. */ static final int STATE_IDLE = 0; /** * State when the task has been scheduled and should not be re-scheduled until next executed. */ static final int STATE_QUEUED = 1; /** * State when the task has been disposed and should no longer be scheduled. */ static final int STATE_DISPOSED = 2; /** * Invalid state that should never be set. */ static final int STATE_INVALID = 3; /** * Mask used to extract state bits. */ private static final int STATE_MASK = STATE_IDLE | STATE_QUEUED | STATE_DISPOSED; /** * Mask containing flags that are used to track runtime state. */ static final int RUNTIME_FLAGS_MASK = STATE_MASK; /** * Return true if flags contains valid priority. * * @param flags the flags. * @return true if flags contains priority. */ static boolean isStateValid( final int flags ) { assert Arez.shouldCheckInvariants() || Arez.shouldCheckApiInvariants(); return STATE_INVALID != ( STATE_MASK & flags ); } static int setState( final int flags, final int state ) { return ( ~STATE_MASK & flags ) | state; } static int getState( final int flags ) { return STATE_MASK & flags; } /** * Return true if flags contains a valid react type. * * @param flags the flags. * @return true if flags contains react type. */ static boolean isRunTypeValid( final int flags ) { assert Arez.shouldCheckInvariants() || Arez.shouldCheckApiInvariants(); return RUN_NOW == ( flags & RUN_NOW ) ^ RUN_LATER == ( flags & RUN_LATER ); } /** * Return the RUN_NOW flag if run type not specified. * * @param flags the flags. * @return the default run type if run type unspecified else 0. */ static int runType( final int flags ) { return runType( flags, RUN_NOW ); } /** * Return the default run type flag if run type not specified. * * @param flags the flags. * @param defaultFlag the default flag. * @return the default run type if run type unspecified else 0. */ static int runType( final int flags, final int defaultFlag ) { return 0 == ( flags & RUN_TYPE_MASK ) ? defaultFlag : 0; } /** * Return true if flags contains valid priority. * * @param flags the flags. * @return true if flags contains priority. */ static boolean isPriorityValid( final int flags ) { assert Arez.shouldCheckInvariants() || Arez.shouldCheckApiInvariants(); final int priorityIndex = getPriorityIndex( flags ); return priorityIndex <= 4 && priorityIndex >= 0; } /** * Extract and return the priority flag. * This method will not attempt to check priority value is valid. * * @param flags the flags. * @return the priority. */ static int getPriority( final int flags ) { return flags & PRIORITY_MASK; } /** * Extract and return the priority value ranging from the highest priority 0 and lowest priority 4. * This method assumes that flags has valid priority and will not attempt to re-check. * * @param flags the flags. * @return the priority. */ static int getPriorityIndex( final int flags ) { return ( getPriority( flags ) >> PRIORITY_SHIFT ) - 1; } static int priority( final int flags ) { return 0 != getPriority( flags ) ? 0 : PRIORITY_NORMAL; } private Flags() { } } }
3e05522b8416ef445d5427aa30b2a7723215b7c9
2,626
java
Java
android/app/src/main/java/org/haobtc/onekey/constant/Vm.java
huazhouwang/electrum
3d7cf4aa05593ea71caec264065a1116b25324a6
[ "MIT" ]
null
null
null
android/app/src/main/java/org/haobtc/onekey/constant/Vm.java
huazhouwang/electrum
3d7cf4aa05593ea71caec264065a1116b25324a6
[ "MIT" ]
null
null
null
android/app/src/main/java/org/haobtc/onekey/constant/Vm.java
huazhouwang/electrum
3d7cf4aa05593ea71caec264065a1116b25324a6
[ "MIT" ]
null
null
null
25.495146
124
0.548363
2,234
package org.haobtc.onekey.constant; import androidx.annotation.IntDef; import androidx.annotation.StringDef; import org.haobtc.onekey.BuildConfig; /** * 存放钱包运行时状态 * * @author Onekey@QuincySx * @create 2021-01-15 6:08 PM */ public class Vm { public enum CoinType { BTC("btc", true), ETH("eth", true); public final String coinName; public final boolean enable; CoinType(String coinName, boolean enable) { this.coinName = coinName; this.enable = enable; } public static CoinType convert(String coinName) { for (CoinType item : CoinType.values()) { if (item.coinName.equals(coinName)) { return item; } } return CoinType.BTC; } } @StringDef public @interface PyenvETHNetworkType { String MainNet = "mainnet"; String TestNet = "testnet"; } @PyenvETHNetworkType public static String getEthNetwork() { if (BuildConfig.net_type.equals("MainNet")) { return PyenvETHNetworkType.MainNet; } else { return PyenvETHNetworkType.TestNet; } } @IntDef({WalletType.MAIN, WalletType.STANDARD, WalletType.IMPORT_WATCH, WalletType.IMPORT_PRIVATE, WalletType.HARDWARE}) public @interface WalletType { /** * HD 派生钱包 */ int MAIN = 0; /** * 创建的独立钱包,助记词导入的钱包。 */ int STANDARD = 1; /** * 通过地址导入的观察钱包 */ int IMPORT_WATCH = 2; /** * 通过私钥导入的钱包 */ int IMPORT_PRIVATE = 3; /** * 硬件钱包 */ int HARDWARE = 4; } @WalletType public static int convertWalletType(String type) { if (type.contains("derived-standard")) { return WalletType.MAIN; } else if (type.contains("private-standard")) { return WalletType.IMPORT_PRIVATE; } else if (type.contains("watch-standard")) { return WalletType.IMPORT_WATCH; } else if (type.contains("hw-derived")) { return WalletType.HARDWARE; } else if (type.contains("standard")) { return WalletType.STANDARD; } else { return WalletType.STANDARD; } } public static Vm.CoinType convertCoinType(String type) { if (type.contains("btc")) { return Vm.CoinType.BTC; } else if (type.contains("eth")) { return Vm.CoinType.ETH; } else { return Vm.CoinType.BTC; } } }
3e0552387a07dbcaa2b4ff7e84b1f6fcf7eb30c5
3,334
java
Java
src/test/java/specs/keys/kdf/example/DerivingFromCryptographicKeys.java
user9209/bouncy-gpg
f11eae65068afd94dd5eccbdb0cd1bb8ab5f5f0b
[ "Apache-2.0" ]
192
2017-02-18T23:01:39.000Z
2022-03-07T18:04:44.000Z
src/test/java/specs/keys/kdf/example/DerivingFromCryptographicKeys.java
user9209/bouncy-gpg
f11eae65068afd94dd5eccbdb0cd1bb8ab5f5f0b
[ "Apache-2.0" ]
65
2017-02-28T08:37:10.000Z
2022-03-20T03:37:04.000Z
src/test/java/specs/keys/kdf/example/DerivingFromCryptographicKeys.java
user9209/bouncy-gpg
f11eae65068afd94dd5eccbdb0cd1bb8ab5f5f0b
[ "Apache-2.0" ]
61
2017-03-21T20:48:44.000Z
2022-03-25T01:57:31.000Z
42.202532
168
0.795741
2,235
package specs.keys.kdf.example; import static specs.helper.InputConverters.ByteArray.fromHexString; import static specs.helper.InputConverters.ByteArray.toHexString; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.SecretKeySpec; import name.neuhalfen.projects.crypto.symmetric.keygeneration.DerivedKeyGenerator; import name.neuhalfen.projects.crypto.symmetric.keygeneration.DerivedKeyGeneratorFactory; import org.concordion.api.extension.Extensions; import org.concordion.ext.apidoc.ExecutableSpecExtension; import org.concordion.integration.junit4.ConcordionRunner; import org.junit.runner.RunWith; import specs.helper.KeyAndMetaData; @RunWith(ConcordionRunner.class) @Extensions(ExecutableSpecExtension.class) public class DerivingFromCryptographicKeys { public static final String MASTER_KEY = "0x81d0994d0aa21b786d6b8dc45fc09f31"; public static final String SALT = "0xb201445d3bcdc7a07c469b7d7ef8988c"; public static final String ENCRYPTED_AND_AUTHENTICATED = "Authenticated and encrypted"; public static final String AUTHENTICATED_NOT_ENCRYPTED = "Authenticated, not encrypted"; private static final int GCM_TAG_LENGTH_BITS = 96; public String toHex(byte[] bytes) { return toHexString(bytes); } public KeyAndMetaData deriveKey(String context, String idUniqueInContext, String recordVersion) throws GeneralSecurityException { context = context.trim(); idUniqueInContext = idUniqueInContext.trim(); recordVersion = recordVersion.trim(); byte[] masterkey = fromHexString(MASTER_KEY); byte[] salt = fromHexString(SALT); final DerivedKeyGenerator derivedKeyGenerator = DerivedKeyGeneratorFactory .fromInputKey(masterkey).andSalt(salt).withHKDFsha256(); final byte[] iv = new byte[128 / 8]; final byte[] key = new byte[128 / 8]; { final byte[] keyAndIV = derivedKeyGenerator .deriveKey(context, idUniqueInContext, recordVersion, (iv.length + key.length) * 8); System.arraycopy(keyAndIV, 0, key, 0, key.length); System.arraycopy(keyAndIV, key.length, iv, 0, iv.length); } return KeyAndMetaData.fromKeyMaterial(key); } public byte[] aesGCM(byte[] nonce, byte[] keyBytes) throws InvalidAlgorithmParameterException, InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException { GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH_BITS, nonce); final SecretKey secretKeySpec = new SecretKeySpec(keyBytes, "AES"); final Cipher aes = Cipher.getInstance("AES/GCM/NoPadding"); aes.init(Cipher.ENCRYPT_MODE, secretKeySpec, gcmParameterSpec); aes.updateAAD(AUTHENTICATED_NOT_ENCRYPTED.getBytes(StandardCharsets.UTF_8)); aes.update(ENCRYPTED_AND_AUTHENTICATED.getBytes(StandardCharsets.UTF_8)); final byte[] cipherText = aes.doFinal(); return cipherText; } }
3e0552a3795a308f96f01c775b2751ed8f7584ad
1,129
java
Java
api/src/main/java/org/jboss/shrinkwrap/resolver/api/ResolverSystem.java
proksch/shrinkwrap-resolver
6d8df88f72d0647e404a6524a272b9b2d1cdfe61
[ "Apache-2.0" ]
111
2015-01-15T17:17:19.000Z
2022-01-15T02:12:21.000Z
api/src/main/java/org/jboss/shrinkwrap/resolver/api/ResolverSystem.java
proksch/shrinkwrap-resolver
6d8df88f72d0647e404a6524a272b9b2d1cdfe61
[ "Apache-2.0" ]
56
2015-02-17T16:28:30.000Z
2022-01-13T15:15:27.000Z
api/src/main/java/org/jboss/shrinkwrap/resolver/api/ResolverSystem.java
proksch/shrinkwrap-resolver
6d8df88f72d0647e404a6524a272b9b2d1cdfe61
[ "Apache-2.0" ]
61
2015-02-11T17:31:42.000Z
2022-03-18T08:32:28.000Z
40.178571
110
0.747556
2,236
/* * JBoss, Home of Professional Open Source * Copyright 2012, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.shrinkwrap.resolver.api; /** * Top-level of a resolver system; subtypes may be passed in as an argument to {@link Resolvers#use(Class)} or * {@link Resolvers#use(Class, ClassLoader)} to create a new instance. * * @author <a href="mailto:[email protected]">Andrew Lee Rubinger</a> */ public interface ResolverSystem { }
3e0559005cb30a4862dd7ee87f90d28f41bde875
2,421
java
Java
helospark-core/helospark-core-webapp/src/main/java/com/helospark/site/core/web/article/comment/ArticleCommentVoteController.java
helospark/helospark-site
acea96899b8356ed4a423c173a14b74da23df6c3
[ "MIT" ]
null
null
null
helospark-core/helospark-core-webapp/src/main/java/com/helospark/site/core/web/article/comment/ArticleCommentVoteController.java
helospark/helospark-site
acea96899b8356ed4a423c173a14b74da23df6c3
[ "MIT" ]
null
null
null
helospark-core/helospark-core-webapp/src/main/java/com/helospark/site/core/web/article/comment/ArticleCommentVoteController.java
helospark/helospark-site
acea96899b8356ed4a423c173a14b74da23df6c3
[ "MIT" ]
null
null
null
46.557692
133
0.801735
2,237
package com.helospark.site.core.web.article.comment; import java.util.List; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.helospark.site.core.service.article.comment.CommentVoteService; import com.helospark.site.core.service.article.comment.domain.CommentVoteEntity; import com.helospark.site.core.service.article.comment.repository.CommentVoteRepository; import com.helospark.site.core.service.article.user.ApplicationUser; import com.helospark.site.core.web.article.comment.converter.ArticleVoteConverter; import com.helospark.site.core.web.article.comment.domain.MyVoteResponse; import com.helospark.site.core.web.security.annotation.InjectLoggedInUser; @RestController public class ArticleCommentVoteController { private CommentVoteRepository commentVoteRepository; private ArticleVoteConverter voteConverter; private CommentVoteService voteService; public ArticleCommentVoteController(CommentVoteRepository commentVoteRepository, ArticleVoteConverter voteConverter, CommentVoteService voteService) { this.commentVoteRepository = commentVoteRepository; this.voteConverter = voteConverter; this.voteService = voteService; } @PostMapping("/comment/{commentId}/vote") @PreAuthorize("hasRole('ROLE_USER')") public void voteForComment(@PathVariable("commentId") @NotNull Integer comment, @NotNull @RequestParam("number") Integer number, @InjectLoggedInUser ApplicationUser activeUser) { voteService.voteForComment(comment, number, activeUser); } @GetMapping("/comment/vote/me") @PreAuthorize("hasRole('ROLE_USER')") public List<MyVoteResponse> haveIVoted(@RequestParam("comments") @NotEmpty @NotNull List<Integer> comments, @InjectLoggedInUser ApplicationUser activeUser) { List<CommentVoteEntity> result = commentVoteRepository.findAllByPrimaryKeyUserAndPrimaryKeyCommentIdIn(activeUser, comments); return voteConverter.convert(comments, result); } }
3e055967a82cd1a437a0e40096514882a6168508
1,132
java
Java
Practica2/practica2/src/main/java/es/ucm/abd/practica2/controller/FightController.java
javlop05/BBDD
b45a9952a193c90e5215b69cf6e5146cce97486a
[ "MIT" ]
null
null
null
Practica2/practica2/src/main/java/es/ucm/abd/practica2/controller/FightController.java
javlop05/BBDD
b45a9952a193c90e5215b69cf6e5146cce97486a
[ "MIT" ]
null
null
null
Practica2/practica2/src/main/java/es/ucm/abd/practica2/controller/FightController.java
javlop05/BBDD
b45a9952a193c90e5215b69cf6e5146cce97486a
[ "MIT" ]
null
null
null
28.25
73
0.621239
2,238
package es.ucm.abd.practica2.controller; import es.ucm.abd.practica2.controller.FightResult.Winner; import es.ucm.abd.practica2.dao.AbedemonDAO; import es.ucm.abd.practica2.model.Abedemon; /** * Controlador de la ventana principal (excl. paneles) * * @author Manuel Montenegro ([email protected]) */ public class FightController { private final AbedemonDAO dao; public FightController(AbedemonDAO dao) { this.dao = dao; } public FightResult fight(Abedemon one, Abedemon two) { Integer damage2Integer = dao.getDamage(one.getId(), two.getId()); Integer damage1Integer = dao.getDamage(two.getId(), one.getId()); int damage2 = (damage2Integer == null) ? 0 : damage2Integer; int damage1 = (damage1Integer == null) ? 0 : damage1Integer; Winner winner; if (damage1 == damage2) { winner = Winner.TIE; } else if (damage1 > damage2) { winner = Winner.TWO; } else { winner = Winner.ONE; } return new FightResult(one, two, damage1, damage2, winner); } }
3e055a9afd3621a2c9d7125b108a4d4efa2b6bcd
2,919
java
Java
redis-lettuce/src/main/java/io/micronaut/configuration/lettuce/DefaultRedisClusterClientFactory.java
alextu/micronaut-redis
f345ceb2a01698b09b22cb662443d1051e5c4bed
[ "Apache-2.0" ]
25
2019-02-01T13:35:28.000Z
2022-02-01T16:53:49.000Z
redis-lettuce/src/main/java/io/micronaut/configuration/lettuce/DefaultRedisClusterClientFactory.java
alextu/micronaut-redis
f345ceb2a01698b09b22cb662443d1051e5c4bed
[ "Apache-2.0" ]
120
2019-03-15T11:08:09.000Z
2022-03-31T18:29:23.000Z
redis-lettuce/src/main/java/io/micronaut/configuration/lettuce/DefaultRedisClusterClientFactory.java
alextu/micronaut-redis
f345ceb2a01698b09b22cb662443d1051e5c4bed
[ "Apache-2.0" ]
30
2019-04-29T07:02:04.000Z
2022-03-19T21:28:39.000Z
34.341176
146
0.740665
2,239
/* * Copyright 2017-2020 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.micronaut.configuration.lettuce; import io.lettuce.core.RedisURI; import io.lettuce.core.cluster.RedisClusterClient; import io.lettuce.core.cluster.api.StatefulRedisClusterConnection; import io.lettuce.core.pubsub.StatefulRedisPubSubConnection; import io.lettuce.core.resource.ClientResources; import io.micronaut.context.annotation.Bean; import io.micronaut.context.annotation.Factory; import io.micronaut.context.annotation.Primary; import io.micronaut.context.annotation.Requires; import io.micronaut.context.exceptions.ConfigurationException; import io.micronaut.core.util.CollectionUtils; import io.micronaut.core.annotation.Nullable; import jakarta.inject.Singleton; import java.util.List; /** * Allows connecting to a Redis cluster via the the {@code "redis.uris"} setting. * * @author Graeme Rocher * @since 1.0 */ @Requires(property = RedisSetting.REDIS_URIS) @Singleton @Factory public class DefaultRedisClusterClientFactory { /** * Create the client based on config URIs. * @param config config * @param defaultClientResources default {@link ClientResources} * @return client */ @Bean(preDestroy = "shutdown") @Singleton @Primary public RedisClusterClient redisClient(@Primary AbstractRedisConfiguration config, @Primary @Nullable ClientResources defaultClientResources) { List<RedisURI> uris = config.getUris(); if (CollectionUtils.isEmpty(uris)) { throw new ConfigurationException("Redis URIs must be specified"); } return defaultClientResources == null ? RedisClusterClient.create(uris) : RedisClusterClient.create(defaultClientResources, uris); } /** * Establish redis connection. * @param redisClient client. * @return connection */ @Bean(preDestroy = "close") @Singleton @Primary public StatefulRedisClusterConnection<String, String> redisConnection(@Primary RedisClusterClient redisClient) { return redisClient.connect(); } /** * * @param redisClient redisClient * @return connection */ @Bean(preDestroy = "close") @Singleton public StatefulRedisPubSubConnection<String, String> redisPubSubConnection(@Primary RedisClusterClient redisClient) { return redisClient.connectPubSub(); } }
3e055ab423190f8dc13f208ba89b600ba6d18886
925
java
Java
Lecture 08/Question05.java
ankittojha/Codetantra-Programming-In-Java-Solution
07949084bf83ca85f4a864990544e774c839a6b1
[ "MIT" ]
1
2022-02-13T16:07:34.000Z
2022-02-13T16:07:34.000Z
Lecture 08/Question05.java
akaAkhiil/Codetantra-Programming-In-Java-Solution
ee801ab8d2d98eabf6fd6f5b6e2a369cffea7d92
[ "MIT" ]
1
2022-02-23T16:08:18.000Z
2022-02-23T16:08:18.000Z
Lecture 08/Question05.java
akaAkhiil/Codetantra-Programming-In-Java-Solution
ee801ab8d2d98eabf6fd6f5b6e2a369cffea7d92
[ "MIT" ]
2
2022-02-25T09:15:46.000Z
2022-03-06T12:33:36.000Z
51.388889
156
0.785946
2,240
In Java, the char data type denotes a 16-bit unsigned integer (between 0 and 65535), which represent the Unicode values between '\u0000' and '\uffff' . The primitive type char has a corresponding wrapper class called Character. Both char and Character can be used interchangeably. Which means, we can say: char gender1 = 'M'; Character gender2 = gender1; A character literal must be wrapped in single quotes and it cannot span multiple lines. The fixed value 'M' assigned to gender1 is called character literal. The default value of a primitive char is 0, when not initialized. However, the default value of a reference of type Character is null, when not initialized. Since char is a 16-bit integer type, it can be interchangeably used with int. We will learn more about the wrapper class Character later. Select all the correct statements given below. Answer A char literal value can be a number between 0 and 216-1.
3e055b0deeb7fdd984d0b77b6fc7e321cf1ad181
4,633
java
Java
Source/Java/BaseWebFacade/main/src/java/gov/va/med/imaging/webapp/ImageExchangeApplicationContext.java
VHAINNOVATIONS/Telepathology
989c06ccc602b0282c58c4af3455c5e0a33c8593
[ "Apache-2.0" ]
3
2015-04-09T14:29:34.000Z
2015-11-10T19:39:06.000Z
Source/Java/BaseWebFacade/main/src/java/gov/va/med/imaging/webapp/ImageExchangeApplicationContext.java
VHAINNOVATIONS/Telepathology
989c06ccc602b0282c58c4af3455c5e0a33c8593
[ "Apache-2.0" ]
null
null
null
Source/Java/BaseWebFacade/main/src/java/gov/va/med/imaging/webapp/ImageExchangeApplicationContext.java
VHAINNOVATIONS/Telepathology
989c06ccc602b0282c58c4af3455c5e0a33c8593
[ "Apache-2.0" ]
9
2015-04-14T14:11:09.000Z
2018-09-26T07:48:23.000Z
40.640351
154
0.679042
2,241
/** * Package: MAG - VistA Imaging WARNING: Per VHA Directive 2004-038, this routine should not be modified. Date Created: August 6, 2006 Site Name: Washington OI Field Office, Silver Spring, MD Developer: VHAISWBUCKD Description: ;; +--------------------------------------------------------------------+ ;; Property of the US Government. ;; No permission to copy or redistribute this software is given. ;; Use of unreleased versions of this software requires the user ;; to execute a written test agreement with the VistA Imaging ;; Development Office of the Department of Veterans Affairs, ;; telephone (301) 734-0100. ;; ;; The Food and Drug Administration classifies this software as ;; a Class II medical device. As such, it may not be changed ;; in any way. Modifications to this software may result in an ;; adulterated medical device under 21CFR820, the use of which ;; is considered to be a violation of US Federal Statutes. ;; +--------------------------------------------------------------------+ */ package gov.va.med.imaging.webapp; import org.apache.log4j.Logger; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author VHAISWBUCKD * * This static class is responsible for holding the single instance of the spring factory that will be used by * the exchange applications. * * This class implements a Singleton pattern, but allows for an initialization parameter. * The one-arg form of the static getSingleton() method should be called only once, though it * may be safely called multiple times if the single-arg is identical to the original call. If * the single-arg getSingleton() called and the single-arg is not identical to that on the original * call then getSingleton() will throw a runtime exception (i.e. unchecked, stop the VM kind of error). * * Once initialized, the no-arg version of getSingleton() should be called. * * If the no-arg version of getSingleton() is called before the singleton is initialized then this class * will be initialized using the default context file - "applicationContext.xml" */ public class ImageExchangeApplicationContext extends ClassPathXmlApplicationContext { private static String[] effectiveApplicationContext = null; private static ImageExchangeApplicationContext singleton = null; private static Logger log = Logger.getLogger(ImageExchangeApplicationContext.class); public static synchronized ImageExchangeApplicationContext getSingleton(String[] contexts) { if(singleton == null && contexts == null) throw new ImageExchangeApplicationContextInitializationError("ImageExchangeApplicationContext may not be explicitly initialized with a null context."); if(singleton != null) { if(contexts.length != effectiveApplicationContext.length) throw new ImageExchangeApplicationContextInitializationError("ImageExchangeApplicationContext may not be re-initialized with a different context."); for(int index=0; index < contexts.length; ++index) if(! contexts[index].equalsIgnoreCase(effectiveApplicationContext[index])) throw new ImageExchangeApplicationContextInitializationError("ImageExchangeApplicationContext may not be re-initialized with a different context."); log.warn("ImageExchangeApplicationContext.getSingleton was called twice with the same context."); } if( singleton == null ) { effectiveApplicationContext = contexts; singleton = new ImageExchangeApplicationContext(); } return singleton; } public static ImageExchangeApplicationContext getSingleton() // used to be synchronized - DKB { if (singleton == null) { log.error("ImageExchangeApplicationContext was not initialized when getSingleton() was called."); throw new ImageExchangeApplicationContextInitializationError("ImageExchangeApplicationContext was not initialized when getSingleton() was called."); } return singleton; } /* * =========================================================================================================================== * Instance Fields/Methods/Constructors * =========================================================================================================================== */ /** * * */ private ImageExchangeApplicationContext() { super( effectiveApplicationContext ); } // public IManager getVAManager() { // return (IManager) getBean("vaManager"); // } // // public IManager getDODManager() { // return (IManager) getBean("dodManager"); // } }
3e055b1c4f3b8d6b5c1cfbc8d92550aa443f5e9f
1,936
java
Java
apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigRepository.java
HuangSheng/apollo
edb20c8a65af39c62a8d33ecd07f4c81cdafc58d
[ "Apache-2.0" ]
2
2017-10-03T08:40:44.000Z
2018-07-31T05:45:56.000Z
apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigRepository.java
HuangSheng/apollo
edb20c8a65af39c62a8d33ecd07f4c81cdafc58d
[ "Apache-2.0" ]
23
2019-01-31T13:03:33.000Z
2021-03-28T15:36:36.000Z
apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigRepository.java
HuangSheng/apollo
edb20c8a65af39c62a8d33ecd07f4c81cdafc58d
[ "Apache-2.0" ]
2
2017-09-23T12:56:22.000Z
2018-09-17T08:04:55.000Z
31.721311
107
0.737984
2,242
package com.ctrip.framework.apollo.internals; import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.util.factory.PropertiesFactory; import java.util.List; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ctrip.framework.apollo.tracer.Tracer; import com.ctrip.framework.apollo.util.ExceptionUtil; import com.google.common.collect.Lists; /** * @author Jason Song([email protected]) */ public abstract class AbstractConfigRepository implements ConfigRepository { private static final Logger logger = LoggerFactory.getLogger(AbstractConfigRepository.class); private List<RepositoryChangeListener> m_listeners = Lists.newCopyOnWriteArrayList(); protected PropertiesFactory propertiesFactory = ApolloInjector.getInstance(PropertiesFactory.class); protected boolean trySync() { try { sync(); return true; } catch (Throwable ex) { Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex)); logger .warn("Sync config failed, will retry. Repository {}, reason: {}", this.getClass(), ExceptionUtil .getDetailMessage(ex)); } return false; } protected abstract void sync(); @Override public void addChangeListener(RepositoryChangeListener listener) { if (!m_listeners.contains(listener)) { m_listeners.add(listener); } } @Override public void removeChangeListener(RepositoryChangeListener listener) { m_listeners.remove(listener); } protected void fireRepositoryChange(String namespace, Properties newProperties) { for (RepositoryChangeListener listener : m_listeners) { try { listener.onRepositoryChange(namespace, newProperties); } catch (Throwable ex) { Tracer.logError(ex); logger.error("Failed to invoke repository change listener {}", listener.getClass(), ex); } } } }
3e055b8b8d7262fa8e58eee2bff6dc5188766a3e
853
java
Java
app/src/main/java/com/codepath/apps/erastustweet/models/ScreenNameId.java
erastus-murungi/SimpleTweet
12dfc2c00ed8efd2b63a8153bbb1dd0826edcaaf
[ "MIT" ]
null
null
null
app/src/main/java/com/codepath/apps/erastustweet/models/ScreenNameId.java
erastus-murungi/SimpleTweet
12dfc2c00ed8efd2b63a8153bbb1dd0826edcaaf
[ "MIT" ]
1
2020-07-03T17:54:20.000Z
2020-07-04T10:53:43.000Z
app/src/main/java/com/codepath/apps/erastustweet/models/ScreenNameId.java
erastus-murungi/SimpleTweet
12dfc2c00ed8efd2b63a8153bbb1dd0826edcaaf
[ "MIT" ]
null
null
null
25.848485
99
0.6483
2,243
package com.codepath.apps.erastustweet.models; import android.util.Log; import org.json.JSONException; import org.json.JSONObject; import org.parceler.Parcel; @Parcel public class ScreenNameId { public long id; public String screenName; public ScreenNameId(long id, String screenName) { this.id = id; this.screenName = screenName; } public ScreenNameId() {} public static ScreenNameId fromJson(JSONObject jsonObject) { try { ScreenNameId sid = new ScreenNameId(); sid.id = jsonObject.getLong("in_reply_to_user_id"); sid.screenName = jsonObject.getString(jsonObject.getString("in_reply_to_screen_name")); return sid; } catch (JSONException e) { Log.e("ScreenNameId", "JSON Exception", e); return null; } } }
3e055be562820054d123822019c8ac15a61a4062
676
java
Java
mymall-seckill/src/main/java/com/atguigu/mymall/seckill/vo/SeckillSkuVo.java
mingchiuli/myMall
148bee2a1bda103f09167a43205e567dbfa543a8
[ "Apache-2.0" ]
null
null
null
mymall-seckill/src/main/java/com/atguigu/mymall/seckill/vo/SeckillSkuVo.java
mingchiuli/myMall
148bee2a1bda103f09167a43205e567dbfa543a8
[ "Apache-2.0" ]
1
2022-03-04T05:22:21.000Z
2022-03-04T05:22:21.000Z
mymall-seckill/src/main/java/com/atguigu/mymall/seckill/vo/SeckillSkuVo.java
mingchiuli/myMall
148bee2a1bda103f09167a43205e567dbfa543a8
[ "Apache-2.0" ]
null
null
null
14.083333
38
0.534024
2,244
package com.atguigu.mymall.seckill.vo; import lombok.Data; import java.math.BigDecimal; /** * @author 孟享广 * @date 2021-02-20 12:48 下午 * @description */ @Data public class SeckillSkuVo { /** * id */ private Long id; /** * 活动id */ private Long promotionId; /** * 活动场次id */ private Long promotionSessionId; /** * 商品id */ private Long skuId; /** * 秒杀价格 */ private BigDecimal seckillPrice; /** * 秒杀总量 */ private BigDecimal seckillCount; /** * 每人限购数量 */ private BigDecimal seckillLimit; /** * 排序 */ private Integer seckillSort; }
3e055c4011939b9d9e10afc90c9c0d8c9d02b3a4
4,300
java
Java
src/main/java/io/jboot/utils/ReflectUtil.java
alany9552/jboot
09d48f85ca65e7f0cc02900152aefc4d9dbf907c
[ "Apache-2.0" ]
1
2021-11-06T16:13:00.000Z
2021-11-06T16:13:00.000Z
src/main/java/io/jboot/utils/ReflectUtil.java
icewater2020/jboot
09d48f85ca65e7f0cc02900152aefc4d9dbf907c
[ "Apache-2.0" ]
null
null
null
src/main/java/io/jboot/utils/ReflectUtil.java
icewater2020/jboot
09d48f85ca65e7f0cc02900152aefc4d9dbf907c
[ "Apache-2.0" ]
null
null
null
31.859259
114
0.581028
2,245
/** * Copyright (c) 2015-2021, Michael Yang 杨福海 ([email protected]). * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.jboot.utils; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.function.Predicate; /** * 反射相关操作的工具类 */ public class ReflectUtil { public static <T> T getStaticFieldValue(Class<?> dClass, String fieldName) { return getFieldValue(dClass, fieldName, null); } public static <T> T getFieldValue(Class<?> dClass, String fieldName, Object from) { try { if (StrUtil.isBlank(fieldName)) { throw new IllegalArgumentException("fieldName must not be null or empty."); } Field field = searchField(dClass, f -> f.getName().equals(fieldName)); if (field == null) { throw new NoSuchFieldException(fieldName); } field.setAccessible(true); return (T) field.get(from); } catch (NoSuchFieldException | IllegalAccessException e) { throw new RuntimeException(e); } } public static Field searchField(Class<?> dClass, Predicate<Field> filter) { if (dClass == null) { return null; } Field[] fields = dClass.getDeclaredFields(); for (Field field : fields) { if (filter.test(field)) { return field; } } return searchField(dClass.getSuperclass(), filter); } public static List<Field> searchFieldList(Class<?> dClass, Predicate<Field> filter) { List<Field> fields = new LinkedList<>(); doSearchFieldList(dClass, filter, fields); return fields; } private static void doSearchFieldList(Class<?> dClass, Predicate<Field> filter, List<Field> searchToList) { if (dClass == null || dClass == Object.class) { return; } Field[] fields = dClass.getDeclaredFields(); if (fields.length > 0) { if (filter != null) { for (Field field : fields) { if (filter.test(field)) { searchToList.add(field); } } } else { searchToList.addAll(Arrays.asList(fields)); } } doSearchFieldList(dClass.getSuperclass(), filter, searchToList); } public static Method searchMethod(Class<?> dClass, Predicate<Method> filter) { if (dClass == null) { return null; } Method[] methods = dClass.getDeclaredMethods(); for (Method method : methods) { if (filter.test(method)) { return method; } } return searchMethod(dClass.getSuperclass(), filter); } public static List<Method> searchMethodList(Class<?> dClass, Predicate<Method> filter) { List<Method> methods = new LinkedList<>(); doSearchMethodList(dClass, filter, methods); return methods; } private static void doSearchMethodList(Class<?> dClass, Predicate<Method> filter, List<Method> searchToList) { if (dClass == null) { return; } Method[] methods = dClass.getDeclaredMethods(); if (methods.length > 0) { if (filter != null) { for (Method method : methods) { if (filter.test(method)) { searchToList.add(method); } } } else { searchToList.addAll(Arrays.asList(methods)); } } doSearchMethodList(dClass.getSuperclass(), filter, searchToList); } }
3e055c559228599da870a47d1d22cd905f3f5c68
4,002
java
Java
src/test/java/guru/springframework/sfgpetclinic/controllers/OwnerControllerMockitoVerificationOrderOfInteractions.java
TomaszJarych/Testing-Spring-Boot-Beginner-to-Guru-Mockito
6c26b611692ed3f8e3a0b3ce6c87e894a990c243
[ "Apache-2.0" ]
null
null
null
src/test/java/guru/springframework/sfgpetclinic/controllers/OwnerControllerMockitoVerificationOrderOfInteractions.java
TomaszJarych/Testing-Spring-Boot-Beginner-to-Guru-Mockito
6c26b611692ed3f8e3a0b3ce6c87e894a990c243
[ "Apache-2.0" ]
null
null
null
src/test/java/guru/springframework/sfgpetclinic/controllers/OwnerControllerMockitoVerificationOrderOfInteractions.java
TomaszJarych/Testing-Spring-Boot-Beginner-to-Guru-Mockito
6c26b611692ed3f8e3a0b3ce6c87e894a990c243
[ "Apache-2.0" ]
null
null
null
33.35
111
0.684658
2,246
package guru.springframework.sfgpetclinic.controllers; import guru.springframework.sfgpetclinic.fauxspring.BindingResult; import guru.springframework.sfgpetclinic.fauxspring.Model; import guru.springframework.sfgpetclinic.model.Owner; import guru.springframework.sfgpetclinic.services.OwnerService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.*; import org.mockito.junit.jupiter.MockitoExtension; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class OwnerControllerMockitoVerificationOrderOfInteractions { private static final String OWNERS_CREATE_OR_UPDATE_OWNER_FORM = "owners/createOrUpdateOwnerForm"; private static final String REDIRECT_OWNERS_5 = "redirect:/owners/5"; @Mock private OwnerService ownerService; @Mock BindingResult bindingResult; @Mock Model model; private OwnerController controller; @Captor ArgumentCaptor<String> annotatedArgumentCaptor; @BeforeEach void setUp() { controller = new OwnerController(ownerService); given(ownerService.findAllByLastNameLike(annotatedArgumentCaptor.capture())).willAnswer(invocation -> { List<Owner> stubList = new ArrayList<>(); String name = invocation.getArgument(0); if (name.equals("%Buck%")) { stubList.add(new Owner(1L, "Joe", "Buck")); return stubList; } else if (name.equals("%DontFindMe%")) { return stubList; } else if (name.equals("%FindMe%")) { stubList.add(new Owner(1L, "Joe", "FindMe")); stubList.add(new Owner(2L, "John", "FindMe")); return stubList; } else { throw new RuntimeException("Invalid argument has been passed"); } }); } @Test @DisplayName("Order verification") void orderVerification() { //given Owner owner = new Owner(1L, "Joe", "FindMe"); InOrder order = inOrder(ownerService, model); //when String viewName = controller.processFindForm(owner, bindingResult, model); //then assertThat("%FindMe%").isEqualToIgnoringCase(annotatedArgumentCaptor.getValue()); assertThat("owners/ownersList").isEqualToIgnoringCase(viewName); //inOrderAssertions order.verify(ownerService).findAllByLastNameLike(anyString()); order.verify(model).addAttribute(anyString(), anyList()); //verify no more interactions with model verifyNoMoreInteractions(model); } @Test void processFindFromWildcardStringArgumentCaptorAnnotation() { //given Owner owner = new Owner(1L, "Joe", "Buck"); //when String viewName = controller.processFindForm(owner, bindingResult, null); //then assertThat("%Buck%").isEqualToIgnoringCase(annotatedArgumentCaptor.getValue()); assertThat("redirect:/owners/1").isEqualToIgnoringCase(viewName); //verify no interactions with model verifyZeroInteractions(model); } @Test void processFindFromWildcardNotFound() { //given Owner owner = new Owner(1L, "Joe", "DontFindMe"); //when String viewName = controller.processFindForm(owner, bindingResult, Mockito.mock(Model.class)); //then assertThat("%DontFindMe%").isEqualToIgnoringCase(annotatedArgumentCaptor.getValue()); assertThat("owners/findOwners").isEqualToIgnoringCase(viewName); //verify no interactions with model verifyZeroInteractions(model); } }
3e055d2b3792269e135afb37a529156ff0616987
8,161
java
Java
javar/jdk8-analysis/src/com/sun/xml/internal/ws/util/InjectionPlan.java
vitahlin/kennen
b0de36d3b6e766b59291d885a0699b6be59318a7
[ "MIT" ]
12
2018-04-04T12:47:40.000Z
2022-01-02T04:36:38.000Z
openjdk-8u45-b14/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/util/InjectionPlan.java
ams-ts-ikvm-bag/ikvm-src
60009f5bdb4c9db68121f393b8b4c790a326bd32
[ "Zlib" ]
2
2020-07-19T08:29:50.000Z
2020-07-21T01:20:56.000Z
openjdk-8u45-b14/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/util/InjectionPlan.java
ams-ts-ikvm-bag/ikvm-src
60009f5bdb4c9db68121f393b8b4c790a326bd32
[ "Zlib" ]
1
2020-11-04T07:02:06.000Z
2020-11-04T07:02:06.000Z
34.876068
135
0.57787
2,247
/* * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.xml.internal.ws.util; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import javax.annotation.Resource; import javax.xml.ws.WebServiceException; /** * Encapsulates which field/method the injection is done, and performs the * injection. */ public abstract class InjectionPlan<T, R> { /** * Perform injection * * @param instance * Instance * @param resource * Resource */ public abstract void inject(T instance, R resource); /** * Perform injection, but resource is only generated if injection is * necessary. * * @param instance * @param resource */ public void inject(T instance, Callable<R> resource) { try { inject(instance, resource.call()); } catch(Exception e) { throw new WebServiceException(e); } } /* * Injects to a field. */ public static class FieldInjectionPlan<T, R> extends InjectionPlan<T, R> { private final Field field; public FieldInjectionPlan(Field field) { this.field = field; } public void inject(final T instance, final R resource) { AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { try { if (!field.isAccessible()) { field.setAccessible(true); } field.set(instance, resource); return null; } catch (IllegalAccessException e) { throw new WebServiceException(e); } } }); } } /* * Injects to a method. */ public static class MethodInjectionPlan<T, R> extends InjectionPlan<T, R> { private final Method method; public MethodInjectionPlan(Method method) { this.method = method; } public void inject(T instance, R resource) { invokeMethod(method, instance, resource); } } /* * Helper for invoking a method with elevated privilege. */ private static void invokeMethod(final Method method, final Object instance, final Object... args) { if(method==null) return; AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { try { if (!method.isAccessible()) { method.setAccessible(true); } method.invoke(instance,args); } catch (IllegalAccessException e) { throw new WebServiceException(e); } catch (InvocationTargetException e) { throw new WebServiceException(e); } return null; } }); } /* * Combines multiple {@link InjectionPlan}s into one. */ private static class Compositor<T, R> extends InjectionPlan<T, R> { private final Collection<InjectionPlan<T, R>> children; public Compositor(Collection<InjectionPlan<T, R>> children) { this.children = children; } public void inject(T instance, R res) { for (InjectionPlan<T, R> plan : children) plan.inject(instance, res); } public void inject(T instance, Callable<R> resource) { if (!children.isEmpty()) { super.inject(instance, resource); } } } /* * Creates an {@link InjectionPlan} that injects the given resource type to the given class. * * @param isStatic * Only look for static field/method * */ public static <T,R> InjectionPlan<T,R> buildInjectionPlan(Class<? extends T> clazz, Class<R> resourceType, boolean isStatic) { List<InjectionPlan<T,R>> plan = new ArrayList<InjectionPlan<T,R>>(); Class<?> cl = clazz; while(cl != Object.class) { for(Field field: cl.getDeclaredFields()) { Resource resource = field.getAnnotation(Resource.class); if (resource != null) { if(isInjectionPoint(resource, field.getType(), "Incorrect type for field"+field.getName(), resourceType)) { if(isStatic && !Modifier.isStatic(field.getModifiers())) throw new WebServiceException("Static resource "+resourceType+" cannot be injected to non-static "+field); plan.add(new FieldInjectionPlan<T,R>(field)); } } } cl = cl.getSuperclass(); } cl = clazz; while(cl != Object.class) { for(Method method : cl.getDeclaredMethods()) { Resource resource = method.getAnnotation(Resource.class); if (resource != null) { Class[] paramTypes = method.getParameterTypes(); if (paramTypes.length != 1) throw new WebServiceException("Incorrect no of arguments for method "+method); if(isInjectionPoint(resource,paramTypes[0], "Incorrect argument types for method"+method.getName(), resourceType)) { if(isStatic && !Modifier.isStatic(method.getModifiers())) throw new WebServiceException("Static resource "+resourceType+" cannot be injected to non-static "+method); plan.add(new MethodInjectionPlan<T,R>(method)); } } } cl = cl.getSuperclass(); } return new Compositor<T,R>(plan); } /* * Returns true if the combination of {@link Resource} and the field/method type * are consistent for {@link WebServiceContext} injection. */ private static boolean isInjectionPoint(Resource resource, Class fieldType, String errorMessage, Class resourceType ) { Class t = resource.type(); if (t.equals(Object.class)) { return fieldType.equals(resourceType); } else if (t.equals(resourceType)) { if (fieldType.isAssignableFrom(resourceType)) { return true; } else { // type compatibility error throw new WebServiceException(errorMessage); } } return false; } }
3e055d410b6fa65b69f3ea963c953852e2022391
7,855
java
Java
core/sla/sla-core/src/main/java/com/thinkbiganalytics/metadata/sla/spi/core/SimpleServiceLevelAssessment.java
mdashaikh/kylo
0ca8cf21e6020ea1fbca51d5da7eead5b2c4827c
[ "Apache-2.0" ]
1,016
2017-03-03T12:05:19.000Z
2022-03-26T20:47:38.000Z
core/sla/sla-core/src/main/java/com/thinkbiganalytics/metadata/sla/spi/core/SimpleServiceLevelAssessment.java
mdashaikh/kylo
0ca8cf21e6020ea1fbca51d5da7eead5b2c4827c
[ "Apache-2.0" ]
86
2017-03-03T23:22:32.000Z
2022-03-17T22:24:39.000Z
core/sla/sla-core/src/main/java/com/thinkbiganalytics/metadata/sla/spi/core/SimpleServiceLevelAssessment.java
rohituppalapati/kylo-source
cc794fb8a128a1bb6453e029ab7f6354e75c863e
[ "Apache-2.0" ]
632
2017-03-02T04:37:05.000Z
2022-03-22T03:23:39.000Z
28.460145
155
0.645194
2,248
/** * */ package com.thinkbiganalytics.metadata.sla.spi.core; /*- * #%L * thinkbig-sla-core * %% * Copyright (C) 2017 ThinkBig Analytics * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.google.common.collect.ComparisonChain; import com.thinkbiganalytics.metadata.sla.api.AssessmentResult; import com.thinkbiganalytics.metadata.sla.api.ObligationAssessment; import com.thinkbiganalytics.metadata.sla.api.ServiceLevelAgreement; import com.thinkbiganalytics.metadata.sla.api.ServiceLevelAgreementDescription; import com.thinkbiganalytics.metadata.sla.api.ServiceLevelAssessment; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; /** * */ public class SimpleServiceLevelAssessment implements ServiceLevelAssessment { private static final long serialVersionUID = 2752726049105871947L; private DateTime time; private ServiceLevelAgreement sla; private String message = ""; private AssessmentResult result = AssessmentResult.SUCCESS; private Set<ObligationAssessment> obligationAssessments; private ServiceLevelAssessment.ID id; /** * */ protected SimpleServiceLevelAssessment() { this.id = new AssessmentId(UUID.randomUUID()); this.time = DateTime.now(); this.obligationAssessments = new HashSet<ObligationAssessment>(); } public SimpleServiceLevelAssessment(ServiceLevelAgreement sla) { this(); this.sla = sla; } public SimpleServiceLevelAssessment(ServiceLevelAgreement sla, String message, AssessmentResult result) { super(); this.id = new AssessmentId(UUID.randomUUID()); this.sla = sla; this.message = message; this.result = result; } /* (non-Javadoc) * @see com.thinkbiganalytics.metadata.sla.api.ServiceLevelAssessment#getTime() */ @Override public DateTime getTime() { return this.time; } protected void setTime(DateTime time) { this.time = time; } /* (non-Javadoc) * @see com.thinkbiganalytics.metadata.sla.api.ServiceLevelAssessment#getSLA() */ @Override public ServiceLevelAgreement getAgreement() { return this.sla; } @Override public ServiceLevelAgreement.ID getServiceLevelAgreementId() { return this.sla != null ? this.sla.getId() : null; } /* (non-Javadoc) * @see com.thinkbiganalytics.metadata.sla.api.ServiceLevelAssessment#getMessage() */ @Override public String getMessage() { return this.message; } protected void setMessage(String message) { this.message = message; } /* (non-Javadoc) * @see com.thinkbiganalytics.metadata.sla.api.ServiceLevelAssessment#getResult() */ @Override public AssessmentResult getResult() { return this.result; } protected void setResult(AssessmentResult result) { this.result = result; } /* (non-Javadoc) * @see com.thinkbiganalytics.metadata.sla.api.ServiceLevelAssessment#getObligationAssessments() */ @Override public Set<ObligationAssessment> getObligationAssessments() { return new HashSet<ObligationAssessment>(this.obligationAssessments); } @Override public int compareTo(ServiceLevelAssessment sla) { ComparisonChain chain = ComparisonChain .start() .compare(this.getResult(), sla.getResult()) .compare(this.getAgreement().getName(), sla.getAgreement().getName()); if (chain.result() != 0) { return chain.result(); } List<ObligationAssessment> list1 = new ArrayList<>(this.getObligationAssessments()); List<ObligationAssessment> list2 = new ArrayList<>(sla.getObligationAssessments()); chain = chain.compare(list1.size(), list2.size()); Collections.sort(list1); Collections.sort(list2); for (int idx = 0; idx < list1.size(); idx++) { chain = chain.compare(list1.get(idx), list2.get(idx)); } return chain.result(); } protected boolean add(ObligationAssessment assessment) { return this.obligationAssessments.add(assessment); } protected boolean addAll(Collection<? extends ObligationAssessment> assessments) { return this.obligationAssessments.addAll(assessments); } protected void setSla(ServiceLevelAgreement sla) { this.sla = sla; } @Override public ServiceLevelAgreementDescription getServiceLevelAgreementDescription() { return new SimpleServiceLevelAgreementDescription(this.getAgreement().getId(),this.getAgreement().getName(),this.getAgreement().getDescription()); } @Override public ID getId() { return this.id; } public static class AssessmentId implements ID { private static final long serialVersionUID = -9084653006891727475L; private String idValue; public AssessmentId() { } public AssessmentId(Serializable ser) { if (ser instanceof String) { String uuid = (String) ser; if (!StringUtils.contains(uuid, "-")) { uuid = ((String) ser).replaceFirst("([0-9a-fA-F]{8})([0-9a-fA-F]{4})([0-9a-fA-F]{4})([0-9a-fA-F]{4})([0-9a-fA-F]+)", "$1-$2-$3-$4-$5"); } setUuid(UUID.fromString(uuid)); } else if (ser instanceof UUID) { setUuid((UUID) ser); } else { throw new IllegalArgumentException("Unknown ID value: " + ser); } } public String getIdValue() { return idValue; } @Override public String toString() { return idValue; } public UUID getUuid() { return UUID.fromString(idValue); } private void setUuid(UUID uuid) { this.idValue = uuid.toString(); } } private static class SimpleServiceLevelAgreementDescription implements ServiceLevelAgreementDescription { private String description; private ServiceLevelAgreement.ID slaId; private String name; public SimpleServiceLevelAgreementDescription() { } public SimpleServiceLevelAgreementDescription(ServiceLevelAgreement.ID slaId, String name,String description) { this.description = description; this.slaId = slaId; this.name = name; } @Override public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public ServiceLevelAgreement.ID getSlaId() { return slaId; } public void setSlaId(ServiceLevelAgreement.ID slaId) { this.slaId = slaId; } @Override public String getName() { return name; } public void setName(String name) { this.name = name; } } }
3e055e01e22848fb98a589743fa5b27318db4272
2,312
java
Java
engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Mutable.java
Termina1/enso
8b023e2549faa927794dcd8a419e23d4e331fc50
[ "Apache-2.0" ]
1,994
2020-06-23T18:36:08.000Z
2022-03-31T21:56:39.000Z
engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Mutable.java
Termina1/enso
8b023e2549faa927794dcd8a419e23d4e331fc50
[ "Apache-2.0" ]
816
2020-06-24T15:30:15.000Z
2022-03-29T13:34:23.000Z
engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Mutable.java
Termina1/enso
8b023e2549faa927794dcd8a419e23d4e331fc50
[ "Apache-2.0" ]
105
2020-06-24T12:59:55.000Z
2022-03-28T17:59:32.000Z
44.461538
99
0.75692
2,249
package org.enso.interpreter.runtime.builtin; import org.enso.interpreter.Language; import org.enso.interpreter.node.expression.builtin.mutable.*; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.scope.ModuleScope; /** Container for builtin array-related types and functions. */ public class Mutable { private final AtomConstructor array; private final AtomConstructor ref; /** * Creates a new instance of this class, registering all relevant bindings in the provided scope. * * @param language the current language instance. * @param scope the scope for builtin methods. */ public Mutable(Language language, ModuleScope scope) { array = new AtomConstructor("Array", scope).initializeFields(); scope.registerConstructor(array); scope.registerMethod(array, "empty", EmptyMethodGen.makeFunction(language)); scope.registerMethod(array, "new", NewMethodGen.makeFunction(language)); scope.registerMethod(array, "new_1", New1MethodGen.makeFunction(language)); scope.registerMethod(array, "new_2", New2MethodGen.makeFunction(language)); scope.registerMethod(array, "new_3", New3MethodGen.makeFunction(language)); scope.registerMethod(array, "new_4", New4MethodGen.makeFunction(language)); scope.registerMethod(array, "length", LengthMethodGen.makeFunction(language)); scope.registerMethod(array, "to_array", ToArrayMethodGen.makeFunction(language)); scope.registerMethod(array, "at", GetAtMethodGen.makeFunction(language)); scope.registerMethod(array, "set_at", SetAtMethodGen.makeFunction(language)); scope.registerMethod(array, "copy", CopyMethodGen.makeFunction(language)); scope.registerMethod(array, "sort", SortMethodGen.makeFunction(language)); ref = new AtomConstructor("Ref", scope).initializeFields(); scope.registerConstructor(ref); scope.registerMethod(ref, "new", NewRefMethodGen.makeFunction(language)); scope.registerMethod(ref, "get", GetRefMethodGen.makeFunction(language)); scope.registerMethod(ref, "put", PutRefMethodGen.makeFunction(language)); } /** @return the Array constructor. */ public AtomConstructor array() { return array; } /** @return the Ref constructor. */ public AtomConstructor ref() { return ref; } }
3e055f0ef2b943f433dd7ff4a4059866490dd61f
1,840
java
Java
src/main/java/me/unei/configuration/formats/nbtlib/NBTIO.java
Unei/UneiConfiguration
e553f5abcaf8becf7f4cbdd07da9e9c9baf46f40
[ "Apache-2.0" ]
2
2018-11-16T13:12:22.000Z
2020-12-17T09:58:40.000Z
src/main/java/me/unei/configuration/formats/nbtlib/NBTIO.java
Unei/UneiConfiguration
e553f5abcaf8becf7f4cbdd07da9e9c9baf46f40
[ "Apache-2.0" ]
2
2018-07-30T22:48:51.000Z
2020-03-02T14:58:30.000Z
src/main/java/me/unei/configuration/formats/nbtlib/NBTIO.java
Unei/UneiConfiguration
e553f5abcaf8becf7f4cbdd07da9e9c9baf46f40
[ "Apache-2.0" ]
null
null
null
24.210526
105
0.71413
2,250
package me.unei.configuration.formats.nbtlib; import java.io.*; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import me.unei.configuration.api.format.TagType; public final class NBTIO { public static TagCompound readCompressed(InputStream input) throws IOException { DataInputStream datin = new DataInputStream(new BufferedInputStream(new GZIPInputStream(input))); TagCompound main; try { main = NBTIO.read(datin); } finally { datin.close(); } return main; } public static void writeCompressed(TagCompound compound, OutputStream stream) throws IOException { DataOutputStream datout = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(stream))); try { NBTIO.write(compound, datout); } finally { datout.close(); } } public static TagCompound read(DataInput input) throws IOException { Tag tag = NBTIO.readNBT(input); if (tag instanceof TagCompound) { return (TagCompound) tag; } throw new IOException("Root tag must be a named compound tag"); } public static void write(TagCompound compound, DataOutput output) throws IOException { NBTIO.writeTag(compound, output); } private static void writeTag(Tag tag, DataOutput output) throws IOException { output.writeByte(tag.getTypeId()); if (tag.getType() != TagType.TAG_End) { output.writeUTF(""); tag.write(output); } } private static Tag readNBT(DataInput input) throws IOException { byte type = input.readByte(); if (type == TagType.TAG_End.getId()) { return new TagEnd(); } else { input.readUTF(); Tag base = Tag.newTag(type); try { base.read(input); return base; } catch (IOException exception) { throw new RuntimeException("Unable to load NBT data [UNNAMED TAG] (" + Byte.toString(type) + ")", exception); } } } }
3e055f6a7794279fe37c196939408f29bcf8a497
3,571
java
Java
src/controller/cadastro/ControleCadastroPSF.java
L30n4rd0/controle-farmacia
7d73a10b13d985e885108b1e390df7cbfbb4b5ed
[ "MIT" ]
null
null
null
src/controller/cadastro/ControleCadastroPSF.java
L30n4rd0/controle-farmacia
7d73a10b13d985e885108b1e390df7cbfbb4b5ed
[ "MIT" ]
null
null
null
src/controller/cadastro/ControleCadastroPSF.java
L30n4rd0/controle-farmacia
7d73a10b13d985e885108b1e390df7cbfbb4b5ed
[ "MIT" ]
null
null
null
28.11811
143
0.672641
2,251
package controller.cadastro; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Date; import javax.swing.JOptionPane; import model.Fachada; import model.vos.PsfVO; import view.cadastro.TelaCadastroPosto; public class ControleCadastroPSF implements ActionListener{ private TelaCadastroPosto telaCadastroPSF; public ControleCadastroPSF(TelaCadastroPosto telaCadastroPSF) { this.telaCadastroPSF=telaCadastroPSF; } @Override public void actionPerformed(ActionEvent arg0) { try { verificarDados(this.telaCadastroPSF.getTextFieldNome().getText(), this.telaCadastroPSF.getTextFieldCidade().getText(), this.telaCadastroPSF.getTextFieldBairro().getText(), this.telaCadastroPSF.getTextFieldCEP().getText(), this.telaCadastroPSF.getTextFieldFone().getText()); int id=0; if (this.telaCadastroPSF.getEditarPosto()!=null) { id=this.telaCadastroPSF.getEditarPosto().getId(); } PsfVO psf=new PsfVO(id, this.telaCadastroPSF.getTextFieldNome().getText(), this.telaCadastroPSF.getTextFieldCidade().getText(), this.telaCadastroPSF.getTextFieldBairro().getText(), this.telaCadastroPSF.getComboBoxUF().getSelectedItem().toString(), this.telaCadastroPSF.getTextFieldCEP().getText(), this.telaCadastroPSF.getTextFieldFone().getText(), new Date(System.currentTimeMillis())); Fachada fachada=new Fachada(); String mensagemUsuario="Posto de Sa"+(char)250+"de cadastrado com sucesso!"; if (id==0) { fachada.inserirPSF(psf); }else { fachada.alterarPSF(psf); mensagemUsuario="Posto de Sa"+(char)250+"de editado com sucesso!"; } JOptionPane.showMessageDialog(this.telaCadastroPSF, mensagemUsuario, "Informa"+(char)231+""+(char)227+"o", JOptionPane.INFORMATION_MESSAGE); this.telaCadastroPSF.dispose(); } catch (Exception e) { JOptionPane.showMessageDialog(this.telaCadastroPSF, e.getMessage(), "Aten"+(char)231+""+(char)227+"o", JOptionPane.ERROR_MESSAGE); } } private void verificarDados(String nome, String cidade, String bairro, String cep, String fone) throws Exception { String erro=""; //validar nome do posto if (nome.equals("")) erro+="Erro!!\nPor favor digite um nome v"+(char)225+"lido para o posto de sa"+(char)250+"de."; else if (nome.length()>45) erro+="Erro!!\nVoc"+(char)234+" excedeu limite de caracteres para o nome do posto de sa"+(char)250+"de."; //validar cidade do posto if (cidade.equals("")){ if (erro.equals("")) erro="Erro!!"; erro+="\nPor favor digite um nome v"+(char)225+"lido para a cidade."; }else if (cidade.length()>45){ if (erro.equals("")) erro="Erro!!"; erro+="\nVoc"+(char)234+" excedeu limite de caracteres para o nome da cidade."; } //validar bairro do posto if (bairro.equals("")) { if (erro.equals("")) erro="Erro!!"; erro+="\nPor favor digite um nome v"+(char)225+"lido para bairro."; }else if (bairro.length()>45){ if (erro.equals("")) erro="Erro!!"; erro+="\nVoc"+(char)234+" excedeu limite de caracteres para o nome da bairro."; } //validar cep do posto if (cep.contains("_")) { if (erro.equals("")) erro="Erro!!"; erro+="\nPor favor digite um CEP v"+(char)225+"lido."; } //validar fone do posto if (fone.contains("_")) { if (erro.equals("")) erro="Erro!!"; erro+="\nPor favor digite um telefone v"+(char)225+"lido."; } if (!erro.equals("")) { throw new Exception(erro); } } }
3e05603dd035c6c89a62a490a28901eae94f3a69
521
java
Java
app/src/main/java/com/il360/shenghecar/model/user/OutPaginationBank.java
fuxingguoee/ShengHeCar
ed3518152ba8b47bef3f2f6df1ec2124c9c3719e
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/il360/shenghecar/model/user/OutPaginationBank.java
fuxingguoee/ShengHeCar
ed3518152ba8b47bef3f2f6df1ec2124c9c3719e
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/il360/shenghecar/model/user/OutPaginationBank.java
fuxingguoee/ShengHeCar
ed3518152ba8b47bef3f2f6df1ec2124c9c3719e
[ "Apache-2.0" ]
null
null
null
16.806452
56
0.71977
2,252
package com.il360.shenghecar.model.user; import java.io.Serializable; import java.util.List; public class OutPaginationBank implements Serializable { /** * */ private static final long serialVersionUID = 1L; private int totalCount; private List<Bank> list; public List<Bank> getList() { return list; } public void setList(List<Bank> list) { this.list = list; } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } }
3e05605795e3beb245c8250122e56df4566f804c
12,178
java
Java
packet/src/main/java/com/kraftics/liberium/packet/PacketRegistry.java
KrafticsTeam/Liberium
5b9499694f3aaa62cd635600674b4d908d20695f
[ "MIT" ]
2
2021-07-27T14:26:20.000Z
2021-07-27T14:26:22.000Z
packet/src/main/java/com/kraftics/liberium/packet/PacketRegistry.java
KrafticsTeam/Liberium
5b9499694f3aaa62cd635600674b4d908d20695f
[ "MIT" ]
3
2021-08-31T19:09:45.000Z
2021-11-29T21:31:46.000Z
packet/src/main/java/com/kraftics/liberium/packet/PacketRegistry.java
KrafticsTeam/Liberium
5b9499694f3aaa62cd635600674b4d908d20695f
[ "MIT" ]
2
2021-02-09T18:52:24.000Z
2021-03-03T13:24:51.000Z
65.827027
110
0.751601
2,253
package com.kraftics.liberium.packet; import com.kraftics.liberium.packet.reflection.ConstructorInvoker; import com.kraftics.liberium.packet.reflection.Reflection; import java.util.HashMap; import java.util.Map; /** * This class is used to register packet types */ public class PacketRegistry { private static final Map<Class<?>, PacketType> REGISTRY = new HashMap<>(); private static final Map<PacketType, Class<?>> REVERSE_REGISTRY = new HashMap<>(); static { //<editor-fold desc="PacketOut" defaultstate="collapsed"> register("PacketPlayOutAbilities", PacketType.Play.Out.ABILITIES); register("PacketPlayOutAdvancements", PacketType.Play.Out.ADVANCEMENTS); register("PacketPlayOutAnimation", PacketType.Play.Out.ANIMATION); register("PacketPlayOutAttachEntity", PacketType.Play.Out.ATTACH_ENTITY); register("PacketPlayOutAutoRecipe", PacketType.Play.Out.AUTO_RECIPE); register("PacketPlayOutBlockAction", PacketType.Play.Out.BLOCK_ACTION); register("PacketPlayOutBlockBreak", PacketType.Play.Out.BLOCK_BREAK); register("PacketPlayOutBlockBreakAnimation", PacketType.Play.Out.BLOCK_BREAK_ANIMATION); register("PacketPlayOutBlockChange", PacketType.Play.Out.BLOCK_CHANGE); register("PacketPlayOutBoss", PacketType.Play.Out.BOSS); register("PacketPlayOutCamera", PacketType.Play.Out.CAMERA); register("PacketPlayOutCloseWindow", PacketType.Play.Out.CLOSE_WINDOW); register("PacketPlayOutCollect", PacketType.Play.Out.COLLECT); register("PacketPlayOutCombatEvent", PacketType.Play.Out.COMBAT_EVENT); register("PacketPlayOutCommands", PacketType.Play.Out.COMMANDS); register("PacketPlayOutCustomPayload", PacketType.Play.Out.CUSTOM_PAYLOAD); register("PacketPlayOutCustomSoundEffect", PacketType.Play.Out.CUSTOM_SOUND_EFFECT); register("PacketPlayOutEntity", PacketType.Play.Out.ENTITY); register("PacketPlayOutEntityDestroy", PacketType.Play.Out.ENTITY_DESTROY); register("PacketPlayOutEntityEffect", PacketType.Play.Out.ENTITY_EFFECT); register("PacketPlayOutEntityEquipment", PacketType.Play.Out.ENTITY_EQUIPMENT); register("PacketPlayOutEntityHeadRotation", PacketType.Play.Out.ENTITY_HEAD_ROTATION); register("PacketPlayOutEntityMetadata", PacketType.Play.Out.ENTITY_METADATA); register("PacketPlayOutEntitySound", PacketType.Play.Out.ENTITY_SOUND); register("PacketPlayOutEntityStatus", PacketType.Play.Out.ENTITY_STATUS); register("PacketPlayOutEntityTeleport", PacketType.Play.Out.ENTITY_TELEPORT); register("PacketPlayOutEntityVelocity", PacketType.Play.Out.ENTITY_VELOCITY); register("PacketPlayOutExperience", PacketType.Play.Out.EXPERIENCE); register("PacketPlayOutExplosion", PacketType.Play.Out.EXPLOSION); register("PacketPlayOutGameStateChange", PacketType.Play.Out.GAME_STATE_CHANGE); register("PacketPlayOutHeldItemSlot", PacketType.Play.Out.HELD_ITEM_SLOT); register("PacketPlayOutChat", PacketType.Play.Out.CHAT); register("PacketPlayOutKeepAlive", PacketType.Play.Out.KEEP_ALIVE); register("PacketPlayOutKickDisconnect", PacketType.Play.Out.KICK_DISCONNECT); register("PacketPlayOutLightUpdate", PacketType.Play.Out.LIGHT_UPDATE); register("PacketPlayOutLogin", PacketType.Play.Out.LOGIN); register("PacketPlayOutLookAt", PacketType.Play.Out.LOOK_AT); register("PacketPlayOutMap", PacketType.Play.Out.MAP); register("PacketPlayOutMapChunk", PacketType.Play.Out.MAP_CHUNK); register("PacketPlayOutMount", PacketType.Play.Out.MOUNT); register("PacketPlayOutMultiBlockChange", PacketType.Play.Out.MULTI_BLOCK_CHANGE); register("PacketPlayOutNamedEntitySpawn", PacketType.Play.Out.NAMED_ENTITY_SPAWN); register("PacketPlayOutNamedSoundEffect", PacketType.Play.Out.NAMED_SOUND_EFFECT); register("PacketPlayOutNBTQuery", PacketType.Play.Out.NBT_QUERY); register("PacketPlayOutOpenBook", PacketType.Play.Out.OPEN_BOOK); register("PacketPlayOutOpenSignEditor", PacketType.Play.Out.OPEN_SIGN_EDITOR); register("PacketPlayOutOpenWindow", PacketType.Play.Out.OPEN_WINDOW); register("PacketPlayOutOpenWindowHorse", PacketType.Play.Out.OPEN_WINDOW_HORSE); register("PacketPlayOutOpenWindowMerchant", PacketType.Play.Out.OPEN_WINDOW_MERCHANT); register("PacketPlayOutPlayerInfo", PacketType.Play.Out.PLAYER_INFO); register("PacketPlayOutPlayerListHeaderFooter", PacketType.Play.Out.PLAYER_LIST_HEADER_FOOTER); register("PacketPlayOutPosition", PacketType.Play.Out.POSITION); register("PacketPlayOutRecipes", PacketType.Play.Out.RECIPES); register("PacketPlayOutRecipeUpdate", PacketType.Play.Out.RECIPE_UPDATE); register("PacketPlayOutRemoveEntityEffect", PacketType.Play.Out.REMOVE_ENTITY_EFFECT); register("PacketPlayOutResourcePackSend", PacketType.Play.Out.RESOURCE_PACK_SEND); register("PacketPlayOutRespawn", PacketType.Play.Out.RESPAWN); register("PacketPlayOutScoreboardDisplayObjective", PacketType.Play.Out.SCOREBOARD_DISPLAY_OBJECTIVE); register("PacketPlayOutScoreboardObjective", PacketType.Play.Out.SCOREBOARD_OBJECTIVE); register("PacketPlayOutScoreboardScore", PacketType.Play.Out.SCOREBOARD_SCORE); register("PacketPlayOutScoreboardTeam", PacketType.Play.Out.SCOREBOARD_TEAM); register("PacketPlayOutSelectAdvancementTab", PacketType.Play.Out.SELECT_ADVANCEMENT_TAB); register("PacketPlayOutServerDifficulty", PacketType.Play.Out.SERVER_DIFFICULTY); register("PacketPlayOutSetCooldown", PacketType.Play.Out.SET_COOLDOWN); register("PacketPlayOutSetSlot", PacketType.Play.Out.SET_SLOT); register("PacketPlayOutSpawnEntity", PacketType.Play.Out.SPAWN_ENTITY); register("PacketPlayOutSpawnEntityExperienceOrb", PacketType.Play.Out.SPAWN_EXPERIENCE); register("PacketPlayOutSpawnEntityLiving", PacketType.Play.Out.SPAWN_LIVING); register("PacketPlayOutSpawnEntityPainting", PacketType.Play.Out.SPAWN_ENTITY_PAINTING); register("PacketPlayOutSpawnPosition", PacketType.Play.Out.SPAWN_POSITION); register("PacketPlayOutStatistic", PacketType.Play.Out.STATISTIC); register("PacketPlayOutStopSound", PacketType.Play.Out.STOP_SOUND); register("PacketPlayOutTabComplete", PacketType.Play.Out.TAB_COMPLETE); register("PacketPlayOutTags", PacketType.Play.Out.TAGS); register("PacketPlayOutTileEntityData", PacketType.Play.Out.TILE_ENTITY_DATA); register("PacketPlayOutTitle", PacketType.Play.Out.TITLE); register("PacketPlayOutTransaction", PacketType.Play.Out.TRANSACTION); register("PacketPlayOutUnloadChunk", PacketType.Play.Out.UNLOAD_CHUNK); register("PacketPlayOutUpdateAttributes", PacketType.Play.Out.UPDATE_ATTRIBUTES); register("PacketPlayOutUpdateHealth", PacketType.Play.Out.UPDATE_HEALTH); register("PacketPlayOutUpdateTime", PacketType.Play.Out.UPDATE_TIME); register("PacketPlayOutVehicleMove", PacketType.Play.Out.VEHICLE_MOVE); register("PacketPlayOutViewCentre", PacketType.Play.Out.VIEW_CENTRE); register("PacketPlayOutViewDistance", PacketType.Play.Out.VIEW_DISTANCE); register("PacketPlayOutWindowData", PacketType.Play.Out.WINDOW_DATA); register("PacketPlayOutWindowItems", PacketType.Play.Out.WINDOW_ITEMS); register("PacketPlayOutWorldBorder", PacketType.Play.Out.WORLD_BORDER); register("PacketPlayOutWorldEvent", PacketType.Play.Out.WORLD_EVENT); register("PacketPlayOutWorldParticles", PacketType.Play.Out.WORLD_PARTICLES); //</editor-fold> //<editor-fold desc="PacketIn" defaultstate="collapsed"> register("PacketPlayInAbilities", PacketType.Play.In.ABILITIES); register("PacketPlayInAdvancements", PacketType.Play.In.ADVANCEMENTS); register("PacketPlayInArmAnimation", PacketType.Play.In.ARM_ANIMATION); register("PacketPlayInAutoRecipe", PacketType.Play.In.AUTO_RECIPE); register("PacketPlayInBeacon", PacketType.Play.In.BEACON); register("PacketPlayInBEdit", PacketType.Play.In.BEDIT); register("PacketPlayInBlockDig", PacketType.Play.In.BLOCK_DIG); register("PacketPlayInBlockPlace", PacketType.Play.In.BLOCK_PLACE); register("PacketPlayInBoatMove", PacketType.Play.In.BOAT_MOVE); register("PacketPlayInClientCommand", PacketType.Play.In.CLIENT_COMMAND); register("PacketPlayInCloseWindow", PacketType.Play.In.CLOSE_WINDOW); register("PacketPlayInCustomPayload", PacketType.Play.In.CUSTOM_PAYLOAD); register("PacketPlayInDifficultyChange", PacketType.Play.In.DIFFICULTY_CHANGE); register("PacketPlayInDifficultyLock", PacketType.Play.In.DIFFICULTY_LOCK); register("PacketPlayInEnchantItem", PacketType.Play.In.ENCHANT_ITEM); register("PacketPlayInEntityAction", PacketType.Play.In.ENTITY_ACTION); register("PacketPlayInEntityNBTQuery", PacketType.Play.In.ENTITY_NBT_QUERY); register("PacketPlayInFlying", PacketType.Play.In.FLYING); register("PacketPlayInHeldItemSlot", PacketType.Play.In.HELD_ITEM_SLOT); register("PacketPlayInChat", PacketType.Play.In.CHAT); register("PacketPlayInItemName", PacketType.Play.In.ITEM_NAME); register("PacketPlayInJigsawGenerate", PacketType.Play.In.JIGSAW_GENERATE); register("PacketPlayInKeepAlive", PacketType.Play.In.KEEP_ALIVE); register("PacketPlayInPickItem", PacketType.Play.In.PICK_ITEM); register("PacketPlayInRecipeDisplayed", PacketType.Play.In.RECIPE_DISPLAYED); register("PacketPlayInRecipeSettings", PacketType.Play.In.RECIPE_SETTINGS); register("PacketPlayInResourcePackStatus", PacketType.Play.In.RESOURCE_PACK_STATUS); register("PacketPlayInSetCommandBlock", PacketType.Play.In.SET_COMMAND_BLOCK); register("PacketPlayInSetCommandMinecart", PacketType.Play.In.SET_COMMAND_MINECART); register("PacketPlayInSetCreativeSlot", PacketType.Play.In.SET_CREATIVE_SLOT); register("PacketPlayInSetJigsaw", PacketType.Play.In.SET_JIGSAW); register("PacketPlayInSettings", PacketType.Play.In.SETTINGS); register("PacketPlayInSpectate", PacketType.Play.In.SPECTATE); register("PacketPlayInSteerVehicle", PacketType.Play.In.STEER_VEHICLE); register("PacketPlayInStruct", PacketType.Play.In.STRUCT); register("PacketPlayInTabComplete", PacketType.Play.In.TAB_COMPLETE); register("PacketPlayInTeleportAccept", PacketType.Play.In.TELEPORT_ACCEPT); register("PacketPlayInTileNBTQuery", PacketType.Play.In.TILE_NBT_QUERY); register("PacketPlayInTransaction", PacketType.Play.In.TRANSACTION); register("PacketPlayInTrSel", PacketType.Play.In.TR_SEL); register("PacketPlayInUpdateSign", PacketType.Play.In.UPDATE_SIGN); register("PacketPlayInUseEntity", PacketType.Play.In.USE_ENTITY); register("PacketPlayInUseItem", PacketType.Play.In.USE_ITEM); register("PacketPlayInVehicleMove", PacketType.Play.In.VEHICLE_MOVE); register("PacketPlayInWindowClick", PacketType.Play.In.WINDOW_CLICK); //</editor-fold> } public static void register(Class<?> clazz, PacketType packet) { REGISTRY.put(clazz, packet); REVERSE_REGISTRY.put(packet, clazz); } public static void register(String clazz, PacketType packet) { register(Reflection.getNMSClass(clazz), packet); } public static PacketType get(Object o) { return get(o.getClass()); } public static PacketType get(Class<?> o) { return REGISTRY.get(o); } public static Object getNew(PacketType type) { Class<?> clazz = get(type); ConstructorInvoker<?> constructor = Reflection.getConstructor(clazz); return constructor.invoke(); } public static Class<?> get(PacketType type) { return REVERSE_REGISTRY.get(type); } }
3e05626c798d20da489f2b75e8404b8d5231983b
741
java
Java
app/src/main/java/net/coding/mart/json/mpay/FreezeDynamic.java
JingMeng/Mart-Android
150e5d9c47d6c20ae114728115ebd6537b8bba2d
[ "MIT" ]
1
2021-05-19T05:38:56.000Z
2021-05-19T05:38:56.000Z
app/src/main/java/net/coding/mart/json/mpay/FreezeDynamic.java
JingMeng/Mart-Android
150e5d9c47d6c20ae114728115ebd6537b8bba2d
[ "MIT" ]
null
null
null
app/src/main/java/net/coding/mart/json/mpay/FreezeDynamic.java
JingMeng/Mart-Android
150e5d9c47d6c20ae114728115ebd6537b8bba2d
[ "MIT" ]
null
null
null
21.794118
71
0.707152
2,254
package net.coding.mart.json.mpay; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.io.Serializable; /** * Created by chenchao on 16/9/1. */ public class FreezeDynamic implements Serializable { private static final long serialVersionUID = -6197270171397300081L; @SerializedName("id") @Expose public int id; @SerializedName("user") @Expose public FreezeUser user; @SerializedName("amount") @Expose public String amount; @SerializedName("source") @Expose public String source; @SerializedName("createdAt") @Expose public String createdAt; @SerializedName("updatedAt") @Expose public String updatedAt; }
3e056332d56e5b439a04ce777dfbd5c331776132
3,671
java
Java
environment/src/main/java/com/sequenceiq/environment/environment/validation/cloudstorage/EnvironmentStorageConfigurationValidator.java
Beast2709/cloudbreak
6fefcf8e1ba441f46d3e7fe253e41381622a6b4d
[ "Apache-2.0" ]
174
2017-07-14T03:20:42.000Z
2022-03-25T05:03:18.000Z
environment/src/main/java/com/sequenceiq/environment/environment/validation/cloudstorage/EnvironmentStorageConfigurationValidator.java
Beast2709/cloudbreak
6fefcf8e1ba441f46d3e7fe253e41381622a6b4d
[ "Apache-2.0" ]
2,242
2017-07-12T05:52:01.000Z
2022-03-31T15:50:08.000Z
environment/src/main/java/com/sequenceiq/environment/environment/validation/cloudstorage/EnvironmentStorageConfigurationValidator.java
Beast2709/cloudbreak
6fefcf8e1ba441f46d3e7fe253e41381622a6b4d
[ "Apache-2.0" ]
172
2017-07-12T08:53:48.000Z
2022-03-24T12:16:33.000Z
58.968254
160
0.686137
2,255
package com.sequenceiq.environment.environment.validation.cloudstorage; import org.apache.logging.log4j.util.Strings; import com.sequenceiq.cloudbreak.common.type.CloudConstants; import com.sequenceiq.cloudbreak.util.DocumentationLinkProvider; import com.sequenceiq.cloudbreak.validation.ValidationResult; import com.sequenceiq.environment.environment.domain.Environment; public abstract class EnvironmentStorageConfigurationValidator { protected void validateGcsConfig(Environment environment, ValidationResult.ValidationResultBuilder resultBuilder, String serviceAccountEmail) { if (Strings.isNotBlank(serviceAccountEmail)) { if (!serviceAccountEmail.contains(".iam.gserviceaccount.com")) { resultBuilder.error("Must be a full valid google service account in the format of " + "[email protected]." + getDocLink(environment.getCloudPlatform())); } } else { resultBuilder.error("Google Service Account must be specified in the requested Environment. " + getDocLink(environment.getCloudPlatform())); } } protected void validateAdlsGen2Config(Environment environment, ValidationResult.ValidationResultBuilder resultBuilder, String managedIdentity) { if (Strings.isNotBlank(managedIdentity)) { if (!managedIdentity.matches("^/subscriptions/[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}/" + "(resourceGroups|resourcegroups)/[-\\w._()]+/providers/Microsoft.ManagedIdentity/userAssignedIdentities/[A-Za-z0-9-_]*$")) { resultBuilder.error("Must be a full valid managed identity resource ID in the format of /subscriptions/[your-subscription-id]/resourceGroups/" + "[your-resource-group]/providers/Microsoft.ManagedIdentity/userAssignedIdentities/[name-of-your-identity]. " + getDocLink(environment.getCloudPlatform())); } } else { resultBuilder.error("Managed Identity must be specified in the requested Environment. " + getDocLink(environment.getCloudPlatform())); } } protected void validateS3Config(Environment environment, ValidationResult.ValidationResultBuilder resultBuilder, String instanceProfile) { if (Strings.isNotBlank(instanceProfile)) { if (!instanceProfile.startsWith("arn:aws:iam::") || !(instanceProfile.contains(":instance-profile/"))) { resultBuilder.error("Must be a full valid amazon instance profile in the format of arn:aws:iam::[account-id]:instance-profile/[role-name]." + getDocLink(environment.getCloudPlatform())); } } else { resultBuilder.error("Instance Profile must be specified in the requested Environment. " + getDocLink(environment.getCloudPlatform())); } } private String getDocLink(String cloudPlatform) { String docReferenceLink = " Refer to Cloudera documentation at %s for the required setup."; if (cloudPlatform.equals(CloudConstants.AWS)) { return String.format(docReferenceLink, DocumentationLinkProvider.awsCloudStorageSetupLink()); } else if (cloudPlatform.equals(CloudConstants.AZURE)) { return String.format(docReferenceLink, DocumentationLinkProvider.azureCloudStorageSetupLink()); } else if (cloudPlatform.equals(CloudConstants.GCP)) { return String.format(docReferenceLink, DocumentationLinkProvider.googleCloudStorageSetupLink()); } return ""; } }
3e0563a52cddebfadf9b898db4369e65e291964e
547
java
Java
src/main/java/com/learn/designpattern/templatemethod/AbstractWashing.java
chainren/design-pattern
215ab551752415bc88ede58200ddb2e90828f7a0
[ "Apache-2.0" ]
1
2017-05-16T04:41:40.000Z
2017-05-16T04:41:40.000Z
src/main/java/com/learn/designpattern/templatemethod/AbstractWashing.java
chainren/design-pattern
215ab551752415bc88ede58200ddb2e90828f7a0
[ "Apache-2.0" ]
null
null
null
src/main/java/com/learn/designpattern/templatemethod/AbstractWashing.java
chainren/design-pattern
215ab551752415bc88ede58200ddb2e90828f7a0
[ "Apache-2.0" ]
null
null
null
13.02381
47
0.616088
2,256
package com.learn.designpattern.templatemethod; /** * 洗衣服功能粗象类 * * @author chenrg * @date 2017年5月11日 */ public abstract class AbstractWashing { /** * 定义洗衣流程 * * @author chenrg * @date 2017年5月11日 */ public void washClothes() { this.washing(); this.dryClothes(); } /** * 把衣服弄干 * * @param cleanClothes * @author chenrg * @date 2017年5月11日 */ public abstract void dryClothes(); /** * 清洗衣服 * * @param clothes * @return * @author chenrg * @date 2017年5月11日 */ public abstract void washing(); }
3e05641e8a3073430f21ba761b51c6b85c667bc6
1,879
java
Java
leopard-boot-mvc-parent/leopard-boot-view/src/main/java/io/leopard/boot/view/QrcodeView.java
tanhaichao/leopard-boot
5b7d03bb59f11b7e48733ab97cf7f1da95abe87f
[ "Apache-2.0" ]
2
2018-10-26T02:30:42.000Z
2019-08-09T09:48:02.000Z
leopard-boot-mvc-parent/leopard-boot-view/src/main/java/io/leopard/boot/view/QrcodeView.java
tanhaichao/leopard-boot
5b7d03bb59f11b7e48733ab97cf7f1da95abe87f
[ "Apache-2.0" ]
11
2020-03-04T22:17:02.000Z
2021-04-19T11:17:20.000Z
leopard-boot-mvc-parent/leopard-boot-view/src/main/java/io/leopard/boot/view/QrcodeView.java
tanhaichao/leopard-boot
5b7d03bb59f11b7e48733ab97cf7f1da95abe87f
[ "Apache-2.0" ]
5
2018-10-23T08:46:20.000Z
2022-01-13T01:17:24.000Z
23.78481
145
0.681213
2,257
package io.leopard.boot.view; import java.awt.image.BufferedImage; import java.io.File; import java.util.Map; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.AbstractUrlBasedView; import io.leopard.boot.qrcode.Logo; import io.leopard.boot.qrcode.QrcodeUtil; /** * 二维码 * * @author 阿海 * */ public class QrcodeView extends ModelAndView { /** * 二维码尺寸 */ private int qrcodeSize; private String content; private Logo logo; public QrcodeView(String content) { this(content, 300); } public QrcodeView(String content, int qrcodeSize) { super.setView(view); this.content = content; this.qrcodeSize = qrcodeSize; } public void setLogo(File logo) { this.logo = new Logo(); this.logo.setFile(logo); } public void setLogo(File logo, int size) { this.logo = new Logo(); this.logo.setFile(logo); this.logo.setHeight(size); this.logo.setWidth(size); } public String getContent() { return content; } private AbstractUrlBasedView view = new AbstractUrlBasedView() { @Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType("image/png"); BufferedImage image = QrcodeUtil.createImage(content, qrcodeSize, logo); // InputStream input = new ByteArrayInputStream(data); java.io.OutputStream out = response.getOutputStream(); ImageIO.write(image, "png", out); // byte[] b = new byte[1024]; // int i = 0; // while ((i = input.read(b)) > 0) { // out.write(b, 0, i); // } // input.close(); out.flush(); // output.close(); } }; }
3e0564f667e963c3feac8da66b0dd0ac27fa1aeb
664
java
Java
BloodBankManagementSystem/src/main/java/com/neu/bloodbankmanagement/validation/CheckHospitalEmail.java
hsarthak/Blood-Bank-Management-System
168ef7309f82e43da99447466c8c607a1428a0a7
[ "MIT" ]
null
null
null
BloodBankManagementSystem/src/main/java/com/neu/bloodbankmanagement/validation/CheckHospitalEmail.java
hsarthak/Blood-Bank-Management-System
168ef7309f82e43da99447466c8c607a1428a0a7
[ "MIT" ]
null
null
null
BloodBankManagementSystem/src/main/java/com/neu/bloodbankmanagement/validation/CheckHospitalEmail.java
hsarthak/Blood-Bank-Management-System
168ef7309f82e43da99447466c8c607a1428a0a7
[ "MIT" ]
null
null
null
25.538462
69
0.793675
2,258
package com.neu.bloodbankmanagement.validation; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Constraint(validatedBy = CheckHospitalEmailContraintValidator.class) @Target({ElementType.METHOD,ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface CheckHospitalEmail { //public String value(); public String message() default "Email Already Exists"; public Class<?>[] groups() default{}; public Class<? extends Payload>[] payload() default{}; }
3e05665dd8103c9d661e61ff100df03c183899f5
9,553
java
Java
src/main/java/com/cloudogu/conveyor/internal/SourceCodeGenerator.java
cloudogu/conveyor
af3ba38107917350a2f5a4a3cc70d557afb2cc1f
[ "MIT" ]
null
null
null
src/main/java/com/cloudogu/conveyor/internal/SourceCodeGenerator.java
cloudogu/conveyor
af3ba38107917350a2f5a4a3cc70d557afb2cc1f
[ "MIT" ]
null
null
null
src/main/java/com/cloudogu/conveyor/internal/SourceCodeGenerator.java
cloudogu/conveyor
af3ba38107917350a2f5a4a3cc70d557afb2cc1f
[ "MIT" ]
null
null
null
35.913534
122
0.71276
2,259
/* * MIT License * * Copyright (c) 2021, Cloudogu GmbH * * 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.cloudogu.conveyor.internal; import com.cloudogu.conveyor.View; import com.cloudogu.conveyor.Include; import com.google.auto.common.MoreElements; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import de.otto.edison.hal.Embedded; import de.otto.edison.hal.HalRepresentation; import de.otto.edison.hal.Links; import javax.annotation.Nullable; import javax.annotation.processing.Filer; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.tools.JavaFileObject; import java.io.IOException; import java.io.Writer; import java.lang.annotation.Annotation; class SourceCodeGenerator { private static final String FIELD_LINKS = "links"; private static final String FIELD_EMBEDDED = "embedded"; private static final String FIELD_ENTITY = "entity"; private static final String FIELD_DTO = "dto"; private static final String METHOD_FROM = "from"; private static final String METHOD_UPDATE = "update"; private static final String METHOD_TO_ENTITY = "toEntity"; private static final String NULL = "null"; private final Filer filer; public SourceCodeGenerator(Filer filer) { this.filer = filer; } void generate(Model model) throws IOException { TypeSpec.Builder builder = TypeSpec.classBuilder(model.getSimpleClassName()) .superclass(HalRepresentation.class) .addModifiers(Modifier.PUBLIC) .addMethod(MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .addParameter(ParameterSpec.builder(Links.class, FIELD_LINKS) .addAnnotation(Nullable.class) .build() ) .addParameter(ParameterSpec.builder(Embedded.class, FIELD_EMBEDDED) .addAnnotation(Nullable.class) .build() ) .addStatement("super($N, $N)", FIELD_LINKS, FIELD_EMBEDDED) .build() ) .addMethod(MethodSpec.constructorBuilder() .build() ); for (ViewModel view : model.getViews()) { createInterface(model, view); builder.addSuperinterface(ClassName.get(model.getPackageName(), view.getSimpleClassName())); } for (DtoField exportedField : model.getExportedFields()) { appendField(builder, exportedField); } appendFrom(model, builder); appendUpdate(model, builder); appendToEntity(model, builder); write(model, builder.build()); } private void createInterface(Model model, ViewModel view) throws IOException { TypeSpec.Builder builder = TypeSpec.interfaceBuilder(view.getSimpleClassName()) .addModifiers(Modifier.PUBLIC); for (DtoField field : view.getFields()) { builder.addMethod( MethodSpec.methodBuilder(field.getGetter().getSimpleName().toString()) .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .returns(TypeName.get(field.getType())) .build() ); } write(model, builder.build()); } private void write(Model model, TypeSpec typeSpec) throws IOException { JavaFile javaFile = JavaFile.builder(model.getPackageName(), typeSpec).build(); String className = model.getPackageName() + "." + typeSpec.name; JavaFileObject jfo = filer.createSourceFile(className, model.getClassElement()); try (Writer writer = jfo.openWriter()) { javaFile.writeTo(writer); } } private void appendToEntity(Model model, TypeSpec.Builder builder) { TypeName entityType = TypeName.get(model.getClassElement().asType()); MethodSpec.Builder method = MethodSpec.methodBuilder(METHOD_TO_ENTITY) .addModifiers(Modifier.PUBLIC) .returns(entityType) .addStatement( "$T $N = new $T()", entityType, FIELD_ENTITY, entityType ).addStatement( "$N($N)", METHOD_UPDATE, FIELD_ENTITY ).addStatement( "return $N", FIELD_ENTITY ); builder.addMethod(method.build()); } private void appendUpdate(Model model, TypeSpec.Builder builder) { TypeName entityType = TypeName.get(model.getClassElement().asType()); MethodSpec.Builder updateMethod = MethodSpec.methodBuilder(METHOD_UPDATE) .addModifiers(Modifier.PUBLIC) .addParameter(entityType, FIELD_ENTITY); for (DtoField field : model.getExportedFields()) { field.getSetter().ifPresent(element -> updateMethod.addStatement( "$N.$N(this.$N)", FIELD_ENTITY, element.getSimpleName(), field.getName() )); } builder.addMethod(updateMethod.build()); } private void appendFrom(Model model, TypeSpec.Builder builder) { TypeName entityType = TypeName.get(model.getClassElement().asType()); ClassName dtoType = ClassName.bestGuess(model.getSimpleClassName()); builder.addMethod(MethodSpec.methodBuilder(METHOD_FROM) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addParameter(entityType, FIELD_ENTITY) .returns(dtoType) .addStatement("return from($N, $N, $N)", FIELD_ENTITY, NULL, NULL) .build() ); builder.addMethod(MethodSpec.methodBuilder(METHOD_FROM) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addParameter(entityType, FIELD_ENTITY) .addParameter(ParameterSpec.builder(Links.class, FIELD_LINKS) .addAnnotation(Nullable.class) .build() ) .returns(dtoType) .addStatement("return from($N, $N, $N)", FIELD_ENTITY, FIELD_LINKS, NULL) .build() ); MethodSpec.Builder method = MethodSpec.methodBuilder(METHOD_FROM) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addParameter(entityType, FIELD_ENTITY) .addParameter(ParameterSpec.builder(Links.class, FIELD_LINKS) .addAnnotation(Nullable.class) .build() ) .addParameter(ParameterSpec.builder(Embedded.class, FIELD_EMBEDDED) .addAnnotation(Nullable.class) .build() ) .returns(dtoType) .addStatement("$T $N = new $T($N, $N)", dtoType, FIELD_DTO, dtoType, FIELD_LINKS, FIELD_EMBEDDED); for (DtoField field : model.getExportedFields()) { method.addStatement("$N.$N = $N.$N()", FIELD_DTO, field.getName(), FIELD_ENTITY, field.getGetter().getSimpleName()); } method.addStatement("return $N", FIELD_DTO); builder.addMethod(method.build()); } private void appendField(TypeSpec.Builder builder, DtoField field) { TypeName typeName = TypeName.get(field.getType()); FieldSpec.Builder fieldSpec = FieldSpec.builder(typeName, field.getName(), Modifier.PRIVATE); for (AnnotationMirror mirror : field.getField().getAnnotationMirrors()) { if (!isTypeOf(mirror, Include.class) && !isTypeOf(mirror, View.class)) { fieldSpec.addAnnotation(AnnotationSpec.get(mirror)); } } builder.addField(fieldSpec.build()); appendGetter(builder, field, typeName); field.getSetter().ifPresent(element -> appendSetter(builder, field, element)); } private boolean isTypeOf(AnnotationMirror annotationMirror, Class<? extends Annotation> annotation) { return isTypeOf(annotationMirror.getAnnotationType().asElement(), annotation); } @SuppressWarnings("UnstableApiUsage") private boolean isTypeOf(Element element, Class<?> type) { TypeElement typeElement = MoreElements.asType(element); return typeElement.getQualifiedName().contentEquals(type.getName()); } private void appendSetter(TypeSpec.Builder builder, DtoField field, Element setter) { builder.addMethod( MethodSpec.methodBuilder(setter.getSimpleName().toString()) .addModifiers(Modifier.PUBLIC) .addParameter(TypeName.get(field.getType()), field.getName()) .addStatement("this.$N = $N", field.getName(), field.getName()) .build() ); } private void appendGetter(TypeSpec.Builder builder, DtoField field, TypeName typeName) { String getterName = field.getGetter().getSimpleName().toString(); builder.addMethod( MethodSpec.methodBuilder(getterName) .addModifiers(Modifier.PUBLIC) .addStatement("return $N", field.getName()) .returns(typeName) .build() ); } }
3e0567b3ff761b03c6f3ea4ea25e7f9b2846a16e
2,384
java
Java
src/main/java/com/poloniex/domain/account/Withdrawal.java
mr-legion/poloniex-client
d6a1ed94e1e3a81f4d187c8931c936fa8fea08b4
[ "MIT" ]
null
null
null
src/main/java/com/poloniex/domain/account/Withdrawal.java
mr-legion/poloniex-client
d6a1ed94e1e3a81f4d187c8931c936fa8fea08b4
[ "MIT" ]
null
null
null
src/main/java/com/poloniex/domain/account/Withdrawal.java
mr-legion/poloniex-client
d6a1ed94e1e3a81f4d187c8931c936fa8fea08b4
[ "MIT" ]
null
null
null
28.380952
106
0.638842
2,260
package com.poloniex.domain.account; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lombok.NoArgsConstructor; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; /** * Withdrawal information. */ @NoArgsConstructor @Data @JsonIgnoreProperties(ignoreUnknown = true) public class Withdrawal { /** * The unique Poloniex specific withdrawal ID for this withdrawal. */ private Long id; /** * Asset symbol. */ private String asset; /** * The total amount withdrawn including the fee. */ private Double quantity; private Double fee; /** * The address to which the withdrawal was made. */ private String address; /** * Optionally the transaction ID of the withdrawal. */ private String txid; private WithdrawalStatus status; /** * The IP address which initiated the withdrawal request. */ private String ipAddress; /** * The paymentID specified for this withdrawal. If none were specified, the field will be null. */ private String paymentID; private LocalDateTime dateTime; @JsonCreator public Withdrawal(@JsonProperty("withdrawalNumber") Long id, @JsonProperty("currency") String asset, @JsonProperty("amount") Double quantity, @JsonProperty("fee") Double fee, @JsonProperty("address") String address, @JsonProperty("status") String statusInfo, @JsonProperty("ipAddress") String ipAddress, @JsonProperty("paymentID") String paymentID, @JsonProperty("timestamp") Long timestamp) { String[] statusAndTxid = statusInfo.split(":"); this.id = id; this.asset = asset; this.quantity = quantity; this.fee = fee; this.address = address; this.txid = statusAndTxid[1].trim(); this.status = WithdrawalStatus.valueOf(statusAndTxid[0]); this.ipAddress = ipAddress; this.paymentID = paymentID; this.dateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(timestamp), ZoneId.systemDefault()); } }
3e0568004a42289d58fce55f88ec7f628854ed05
5,415
java
Java
app/src/main/java/com/abishek/android/apps/exposurenotification/debug/KeysMatchingViewModel.java
abishekvashok/exposure-notifications-android
4de024ed2ad51f5e50716f157860d114a45e6af5
[ "Apache-2.0" ]
5
2020-05-28T12:10:08.000Z
2022-03-07T11:06:26.000Z
app/src/main/java/com/abishek/android/apps/exposurenotification/debug/KeysMatchingViewModel.java
abishekvashok/exposure-notifications-android
4de024ed2ad51f5e50716f157860d114a45e6af5
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/abishek/android/apps/exposurenotification/debug/KeysMatchingViewModel.java
abishekvashok/exposure-notifications-android
4de024ed2ad51f5e50716f157860d114a45e6af5
[ "Apache-2.0" ]
2
2020-12-20T13:26:46.000Z
2021-03-18T15:04:05.000Z
41.335878
100
0.708772
2,261
/* * Copyright 2020 Google LLC * Modifications Copyright 2020 Abishek V Ashok * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.abishek.android.apps.exposurenotification.debug; import android.app.Application; import android.util.Log; import androidx.annotation.NonNull; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import com.abishek.android.apps.exposurenotification.common.SingleLiveEvent; import com.abishek.android.apps.exposurenotification.nearby.ExposureNotificationClientWrapper; import com.abishek.android.apps.exposurenotification.common.SingleLiveEvent; import com.abishek.android.apps.exposurenotification.nearby.ExposureNotificationClientWrapper; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.nearby.exposurenotification.ExposureNotificationStatusCodes; import com.google.android.gms.nearby.exposurenotification.TemporaryExposureKey; import com.google.android.gms.tasks.Tasks; import java.util.ArrayList; import java.util.List; /** View model for {@link KeysMatchingFragment}. */ public class KeysMatchingViewModel extends AndroidViewModel { private static final String TAG = "ViewKeysViewModel"; private MutableLiveData<List<TemporaryExposureKey>> temporaryExposureKeysLiveData; private final MutableLiveData<Boolean> inFlightResolutionLiveData = new MutableLiveData<>(false); private final SingleLiveEvent<Void> apiDisabledLiveEvent = new SingleLiveEvent<>(); private final SingleLiveEvent<Void> apiErrorLiveEvent = new SingleLiveEvent<>(); private final SingleLiveEvent<ApiException> resolutionRequiredLiveEvent = new SingleLiveEvent<>(); public KeysMatchingViewModel(@NonNull Application application) { super(application); temporaryExposureKeysLiveData = new MutableLiveData<>(new ArrayList<>()); } /** An event that requests a resolution with the given {@link ApiException}. */ public SingleLiveEvent<ApiException> getResolutionRequiredLiveEvent() { return resolutionRequiredLiveEvent; } /** An event that triggers when the API is disabled. */ public SingleLiveEvent<Void> getApiDisabledLiveEvent() { return apiDisabledLiveEvent; } /** An event that triggers when there is an error in the API. */ public SingleLiveEvent<Void> getApiErrorLiveEvent() { return apiErrorLiveEvent; } /** The {@link LiveData} representing the {@link List} of {@link TemporaryExposureKey}. */ public LiveData<List<TemporaryExposureKey>> getTemporaryExposureKeysLiveData() { return temporaryExposureKeysLiveData; } /** Requests updating the {@link TemporaryExposureKey} from GMSCore API. */ public void updateTemporaryExposureKeys() { ExposureNotificationClientWrapper clientWrapper = ExposureNotificationClientWrapper.get(getApplication()); clientWrapper .isEnabled() .continueWithTask( isEnabled -> { if (isEnabled.getResult()) { return clientWrapper.getTemporaryExposureKeyHistory(); } else { apiDisabledLiveEvent.call(); return Tasks.forResult(new ArrayList<>()); } }) .addOnSuccessListener( temporaryExposureKeys -> temporaryExposureKeysLiveData.setValue(temporaryExposureKeys)) .addOnFailureListener( exception -> { if (!(exception instanceof ApiException)) { Log.e(TAG, "Unknown error when attempting to start API", exception); apiErrorLiveEvent.call(); return; } ApiException apiException = (ApiException) exception; if (apiException.getStatusCode() == ExposureNotificationStatusCodes.RESOLUTION_REQUIRED) { if (inFlightResolutionLiveData.getValue()) { Log.e(TAG, "Error, has in flight resolution", exception); return; } else { inFlightResolutionLiveData.setValue(true); resolutionRequiredLiveEvent.postValue(apiException); } } else { Log.w(TAG, "No RESOLUTION_REQUIRED in result", apiException); apiErrorLiveEvent.call(); } }); } /** Handles {@value android.app.Activity#RESULT_OK} for a resolution. User chose to share keys. */ public void startResolutionResultOk() { inFlightResolutionLiveData.setValue(false); ExposureNotificationClientWrapper.get(getApplication()) .getTemporaryExposureKeyHistory() .addOnSuccessListener(temporaryExposureKeysLiveData::setValue) .addOnFailureListener( exception -> { Log.e(TAG, "Error handling resolution", exception); apiErrorLiveEvent.call(); }); } }
3e0568c9f0b599c552be3f66f385b2f44292d6cd
1,757
java
Java
app/src/main/java/com/aaron/doubanmovie/bz/photo/PhotoWallActivityPresenterImpl.java
AaronChanSunny/DoubanMoview
29a948472a5b46a2e091cbac937003cf0a85ac8a
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/aaron/doubanmovie/bz/photo/PhotoWallActivityPresenterImpl.java
AaronChanSunny/DoubanMoview
29a948472a5b46a2e091cbac937003cf0a85ac8a
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/aaron/doubanmovie/bz/photo/PhotoWallActivityPresenterImpl.java
AaronChanSunny/DoubanMoview
29a948472a5b46a2e091cbac937003cf0a85ac8a
[ "Apache-2.0" ]
null
null
null
29.283333
83
0.657371
2,262
package com.aaron.doubanmovie.bz.photo; import android.content.Context; import com.aaron.doubanmovie.util.LogUtil; import me.aaron.dao.api.Api; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import rx.subscriptions.CompositeSubscription; import static android.content.ContentValues.TAG; import static me.aaron.base.util.Utils.checkNotNull; /** * Created by Chenll on 2016/10/13. */ public class PhotoWallActivityPresenterImpl implements PhotoWallActivityPresenter { private Context mContext; private Api mApi; private IView mView; private CompositeSubscription mAllSubscription; public PhotoWallActivityPresenterImpl(Context context, IView view, Api api) { mContext = checkNotNull(context, "context == null"); mView = checkNotNull(view, "view == null"); mApi = checkNotNull(api, "api == null"); mAllSubscription = new CompositeSubscription(); } @Override public void fetchAllPhotos(String id) { mView.showProgressBar(); Subscription subscription = mApi.getMoviePhotos(id, Integer.MAX_VALUE) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(photos -> { mView.hideProgressBar(); mView.showAllPhotos(photos); }, throwable -> { LogUtil.error(TAG, "fetchAllPhotos", throwable); mView.hideProgressBar(); }); mAllSubscription.add(subscription); } @Override public void onDestroy() { if (!mAllSubscription.isUnsubscribed()) { mAllSubscription.unsubscribe(); } } }
3e056964964ef630f067575ce762d4d2c6151d8a
5,666
java
Java
src/main/java/com/gargoylesoftware/htmlunit/javascript/host/dom/DocumentFragment.java
santosh66508/htmlunit
23dedf1d89bd1665db85b8ec1506c86c1a11eb9e
[ "Apache-2.0" ]
8
2018-03-30T08:20:12.000Z
2020-08-12T14:21:40.000Z
src/main/java/com/gargoylesoftware/htmlunit/javascript/host/dom/DocumentFragment.java
santosh66508/htmlunit
23dedf1d89bd1665db85b8ec1506c86c1a11eb9e
[ "Apache-2.0" ]
null
null
null
src/main/java/com/gargoylesoftware/htmlunit/javascript/host/dom/DocumentFragment.java
santosh66508/htmlunit
23dedf1d89bd1665db85b8ec1506c86c1a11eb9e
[ "Apache-2.0" ]
3
2018-03-30T08:25:52.000Z
2020-08-12T14:21:42.000Z
35.4125
104
0.682139
2,263
/* * Copyright (c) 2002-2017 Gargoyle Software 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 com.gargoylesoftware.htmlunit.javascript.host.dom; import static com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName.CHROME; import static com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName.EDGE; import static com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName.FF; import static com.gargoylesoftware.htmlunit.javascript.configuration.BrowserName.IE; import java.util.ArrayList; import java.util.List; import org.w3c.css.sac.CSSException; import com.gargoylesoftware.htmlunit.html.DomDocumentFragment; import com.gargoylesoftware.htmlunit.html.DomNode; import com.gargoylesoftware.htmlunit.javascript.configuration.JsxClass; import com.gargoylesoftware.htmlunit.javascript.configuration.JsxConstructor; import com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction; import com.gargoylesoftware.htmlunit.javascript.configuration.WebBrowser; import com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument; import net.sourceforge.htmlunit.corejs.javascript.Context; /** * A JavaScript object for {@code DocumentFragment}. * * @author Ahmed Ashour * @author Frank Danek * * @see <a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level-one-core.html#ID-B63ED1A3"> * W3C Dom Level 1</a> */ @JsxClass(domClass = DomDocumentFragment.class) public class DocumentFragment extends Node { //TODO: seems that in IE, DocumentFragment extends HTMLDocument /** * Creates an instance. */ @JsxConstructor({@WebBrowser(CHROME), @WebBrowser(FF), @WebBrowser(EDGE)}) public DocumentFragment() { } /** * Creates a new HTML attribute with the specified name. * * @param attributeName the name of the attribute to create * @return an attribute with the specified name */ @JsxFunction(@WebBrowser(IE)) public Object createAttribute(final String attributeName) { return getDocument().createAttribute(attributeName); } /** * Returns HTML document. * @return HTML document */ protected HTMLDocument getDocument() { return (HTMLDocument) getDomNodeOrDie().getPage().getScriptableObject(); } /** * Creates a new Comment. * @param comment the comment text * @return the new Comment */ @JsxFunction(@WebBrowser(IE)) public Object createComment(final String comment) { return getDocument().createComment(comment); } /** * Creates a new document fragment. * @return a newly created document fragment */ @JsxFunction(@WebBrowser(IE)) public Object createDocumentFragment() { return getDocument().createDocumentFragment(); } /** * Create a new DOM text node with the given data. * * @param newData the string value for the text node * @return the new text node or NOT_FOUND if there is an error */ @JsxFunction(@WebBrowser(IE)) public Object createTextNode(final String newData) { return getDocument().createTextNode(newData); } /** * Retrieves all element nodes from descendants of the starting element node that match any selector * within the supplied selector strings. * The NodeList object returned by the querySelectorAll() method must be static, not live. * @param selectors the selectors * @return the static node list */ @JsxFunction public NodeList querySelectorAll(final String selectors) { try { final List<Object> nodes = new ArrayList<>(); for (final DomNode domNode : getDomNodeOrDie().querySelectorAll(selectors)) { nodes.add(domNode.getScriptableObject()); } return NodeList.staticNodeList(this, nodes); } catch (final CSSException e) { throw Context.reportRuntimeError("An invalid or illegal selector was specified (selector: '" + selectors + "' error: " + e.getMessage() + ")."); } } /** * Returns the first element within the document that matches the specified group of selectors. * @param selectors the selectors * @return null if no matches are found; otherwise, it returns the first matching element */ @JsxFunction public Node querySelector(final String selectors) { try { final DomNode node = getDomNodeOrDie().querySelector(selectors); if (node != null) { return (Node) node.getScriptableObject(); } return null; } catch (final CSSException e) { throw Context.reportRuntimeError("An invalid or illegal selector was specified (selector: '" + selectors + "' error: " + e.getMessage() + ")."); } } /** * {@inheritDoc} */ @Override public Object getDefaultValue(final Class<?> hint) { if (String.class.equals(hint) || hint == null) { return "[object " + getClassName() + "]"; } return super.getDefaultValue(hint); } }
3e056a1bcd60d10ded7f9683af4ee755d65d6437
4,683
java
Java
commons-server/src/main/java/com/navercorp/pinpoint/common/server/util/time/Range.java
donghun-cho/pinpoint
5003b67bf38e913ec358132d225f2416934b84ad
[ "Apache-2.0" ]
null
null
null
commons-server/src/main/java/com/navercorp/pinpoint/common/server/util/time/Range.java
donghun-cho/pinpoint
5003b67bf38e913ec358132d225f2416934b84ad
[ "Apache-2.0" ]
null
null
null
commons-server/src/main/java/com/navercorp/pinpoint/common/server/util/time/Range.java
donghun-cho/pinpoint
5003b67bf38e913ec358132d225f2416934b84ad
[ "Apache-2.0" ]
null
null
null
27.875
91
0.631433
2,264
/* * Copyright 2014 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.pinpoint.common.server.util.time; import com.navercorp.pinpoint.common.server.util.DateTimeFormatUtils; import com.navercorp.pinpoint.common.util.Assert; import org.codehaus.jackson.annotate.JsonIgnore; import java.time.Duration; import java.time.Instant; import java.util.Objects; import java.util.concurrent.TimeUnit; /** * @author emeroad * @author netspider */ public final class Range { private final Instant from; private final Instant to; private Range(Instant from, Instant to) { this.from = Objects.requireNonNull(from, "from"); this.to = Objects.requireNonNull(to, "to"); } @Deprecated public static Range newRange(long from, long to) { return between(from, to); } public static Range between(long from, long to) { return between(toInstant(from), toInstant(to)); } private static Instant toInstant(long timestamp) { return Instant.ofEpochMilli(timestamp); } public static Range between(Instant from, Instant to) { Objects.requireNonNull(from, "from"); Objects.requireNonNull(to, "to"); final Range range = new Range(from, to); range.validate(); return range; } public static Range newRange(TimeUnit timeUnit, long duration, long toTimestamp) { Assert.isTrue(duration > 0, "duration must be '> 0'"); Assert.isTrue(toTimestamp > 0, "toTimestamp must be '> 0'"); final long durationMillis = timeUnit.toMillis(duration); return Range.between(toTimestamp - durationMillis, toTimestamp); } public static Range newUncheckedRange(long from, long to) { return new Range(toInstant(from), toInstant(to)); } public long getFrom() { return from.toEpochMilli(); } @JsonIgnore public Instant getFromInstant() { return from; } public String getFromDateTime() { return DateTimeFormatUtils.formatSimple(from); } public long getTo() { return to.toEpochMilli(); } @JsonIgnore public Instant getToInstant() { return to; } public String getToDateTime() { return DateTimeFormatUtils.formatSimple(from); } public long durationMillis() { return duration().toMillis(); } public Duration duration() { return Duration.between(from, to); } public void validate() { if (from.isAfter(to)) { throw new IllegalArgumentException("invalid range:" + this); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Range range = (Range) o; if (!from.equals(range.from)) return false; return to.equals(range.to); } @Override public int hashCode() { int result = from.hashCode(); result = 31 * result + to.hashCode(); return result; } @Override public String toString() { final StringBuilder sb = new StringBuilder(64); sb.append("Range{"); sb.append(DateTimeFormatUtils.formatSimple(from)); sb.append(' '); sb.append(getSign(from, to)); sb.append(" ").append(DateTimeFormatUtils.formatSimple(to)); sb.append(" duration=").append(duration()); sb.append('}'); return sb.toString(); } static char getSign(Instant from, Instant to) { int compareTo = from.compareTo(to); if (compareTo < 0) { return '<'; } else if (compareTo == 0) { return '='; } else { return '>'; } } public String prettyToString() { final StringBuilder sb = new StringBuilder("Range{"); sb.append("from=").append(DateTimeFormatUtils.formatSimple(from)); sb.append(", to=").append(DateTimeFormatUtils.formatSimple(to)); sb.append(", duration=").append(TimeUnit.MILLISECONDS.toSeconds(durationMillis())); sb.append('}'); return sb.toString(); } }
3e056a450da5028ff222d8711c7eb0dad704bfbc
1,815
java
Java
sample/src/com/handmark/pulltorefresh/sample/PullToRefreshWebViewActivity.java
serso/Android-PullToRefresh
f3582dbc386aabfd6da32470bfd823313b2aba67
[ "Apache-2.0" ]
3
2015-09-23T16:25:00.000Z
2017-03-08T04:48:12.000Z
sample/src/com/handmark/pulltorefresh/sample/PullToRefreshWebViewActivity.java
serso/Android-PullToRefresh
f3582dbc386aabfd6da32470bfd823313b2aba67
[ "Apache-2.0" ]
null
null
null
sample/src/com/handmark/pulltorefresh/sample/PullToRefreshWebViewActivity.java
serso/Android-PullToRefresh
f3582dbc386aabfd6da32470bfd823313b2aba67
[ "Apache-2.0" ]
null
null
null
33.611111
87
0.712397
2,265
/******************************************************************************* * Copyright 2011, 2012 Chris Banes. * * 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.handmark.pulltorefresh.sample; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; import com.handmark.pulltorefresh.library.PullToRefreshWebView; public class PullToRefreshWebViewActivity extends Activity { PullToRefreshWebView mPullRefreshWebView; WebView mWebView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.pull_to_refresh_webview); mPullRefreshWebView = (PullToRefreshWebView) findViewById(R.id.pull_refresh_webview); mWebView = mPullRefreshWebView.getRefreshableView(); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.setWebViewClient(new SampleWebViewClient()); mWebView.loadUrl("http://www.google.com"); } private static class SampleWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } } }
3e056bbfd42e9e0d45a28e681e47ad24fbadb9a7
1,440
java
Java
core/src/com/bazola/roomsworld/AnimatedCharacter.java
bazola/roomsworld
8b67fd114382f292b12a45a6d779b7c9eaa9f970
[ "MIT" ]
2
2019-01-02T15:37:03.000Z
2019-01-02T15:48:47.000Z
core/src/com/bazola/roomsworld/AnimatedCharacter.java
bazola/roomsworld
8b67fd114382f292b12a45a6d779b7c9eaa9f970
[ "MIT" ]
null
null
null
core/src/com/bazola/roomsworld/AnimatedCharacter.java
bazola/roomsworld
8b67fd114382f292b12a45a6d779b7c9eaa9f970
[ "MIT" ]
1
2019-01-31T18:59:52.000Z
2019-01-31T18:59:52.000Z
27.169811
102
0.630556
2,266
package com.bazola.roomsworld; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.utils.ObjectMap; public class AnimatedCharacter { private float stateTime = 0; private AnimationType currentAnimation; private final ObjectMap<AnimationType, Animation<TextureRegion>> animations; private boolean stopped = false; public AnimatedCharacter(ObjectMap<AnimationType, Animation<TextureRegion>> animations) { this.animations = animations; this.currentAnimation = AnimationType.PLAYER_DOWN; } public AnimationType getAnimation() { return this.currentAnimation; } public void setAnimation(AnimationType type) { if (this.currentAnimation == type) { return; } this.stateTime = 0; this.currentAnimation = type; } public void stop() { this.stopped = true; } public void start() { this.stopped = false; } public TextureRegion getRegionForTime(float delta) { if (this.stopped) { return this.animations.get(this.currentAnimation) .getKeyFrame(0); } return this.animations.get(this.currentAnimation) .getKeyFrame(this.stateTime += delta, this.currentAnimation.shouldLoop); } }
3e056bce6c088194d6c718a9d7d15ce99558c7c5
657
java
Java
codesignal/src/main/java/examples/BasicHashtable.java
hatinder/javaexamples
90134ae67b8e1b990a60977455c6b4fe732e19cf
[ "MIT" ]
null
null
null
codesignal/src/main/java/examples/BasicHashtable.java
hatinder/javaexamples
90134ae67b8e1b990a60977455c6b4fe732e19cf
[ "MIT" ]
null
null
null
codesignal/src/main/java/examples/BasicHashtable.java
hatinder/javaexamples
90134ae67b8e1b990a60977455c6b4fe732e19cf
[ "MIT" ]
null
null
null
21.193548
53
0.61796
2,267
package examples; import java.util.*; import java.util.stream.*; public class BasicHashtable<K, V> { private final Object[] values = new Object[128]; public void put(K key, V value) { values[calculatePosition(key)] = value; } public V get(K key) { return (V) values[calculatePosition(key)]; } private int calculatePosition(K key) { int hash = key.hashCode(); int pos = hash & 127; if (pos < 0) pos += values.length; return pos; } public String toString() { return Stream.of(values) .filter(Objects::nonNull) .map(Object::toString) .collect(Collectors.joining(", ", "{", "}")); } }
3e056c3541295c3ceab81014750e908ce62bd5a1
3,531
java
Java
resultlistener/src/test/java/jp/sago/resultlistener/ResultListenersTest.java
hideakisago/ResultListener
a02497b1616672559c98df60f9f12cf11cee1dbd
[ "Apache-2.0" ]
null
null
null
resultlistener/src/test/java/jp/sago/resultlistener/ResultListenersTest.java
hideakisago/ResultListener
a02497b1616672559c98df60f9f12cf11cee1dbd
[ "Apache-2.0" ]
1
2016-04-23T08:35:19.000Z
2016-04-23T08:35:19.000Z
resultlistener/src/test/java/jp/sago/resultlistener/ResultListenersTest.java
hideakisago/ResultListener
a02497b1616672559c98df60f9f12cf11cee1dbd
[ "Apache-2.0" ]
null
null
null
36.78125
97
0.672897
2,268
package jp.sago.resultlistener; import android.app.Activity; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class ResultListenersTest { @Test public void normal() throws Exception { NormalData data = new NormalData(); ResultListeners target = new ResultListeners(); target.registerAll(data); assertThat(target.getNumListeners(), is(3)); assertThat(target.requestCodeOf((OnResultListener<?>) data.mObjectListener), is(0)); assertThat(target.requestCodeOf((OnResultListener<?>) data.mFinalObjectListener), is(0)); assertThat(target.requestCodeOf(data.mOnResultListener), is(1)); assertThat(target.requestCodeOf(data.mOnResultListenerAnonymous), is(2)); MockOnResultListener.initCalled(data.mFinalObjectListener); target.notifyResult(0, Activity.RESULT_OK, null); assertThat(MockOnResultListener.isCalled(data.mFinalObjectListener), is(true)); MockOnResultListener.initCalled(data.mOnResultListener); target.notifyResult(1, Activity.RESULT_OK, null); assertThat(MockOnResultListener.isCalled(data.mOnResultListener), is(true)); target.notifyResult(2, Activity.RESULT_OK, null); OnResultListener l = new OnResultListener<Object>() { @Override public void onResult(int resultCode, Object o) { } }; target.register(l); assertThat(target.getNumListeners(), is(4)); assertThat(target.requestCodeOf(l), is(3)); target.notifyResult(3, Activity.RESULT_OK, null); target.notifyResult(Integer.MAX_VALUE, Activity.RESULT_OK, null); target.notifyResult(Integer.MIN_VALUE, Activity.RESULT_OK, null); // fragment request code target.notifyResult(0x00010000, Activity.RESULT_OK, null); } @Test public void abnormal() throws Exception { ResultListeners target = new ResultListeners(); assertThat(target.requestCodeOf(null), is(-1)); assertThat(target.requestCodeOf(new MockOnResultListener()), is(-1)); assertThat(target.getNumListeners(), is(0)); target.notifyResult(Integer.MAX_VALUE, Activity.RESULT_OK, null); target.notifyResult(Integer.MIN_VALUE, Activity.RESULT_OK, null); // fragment request code target.notifyResult(0x00010000, Activity.RESULT_OK, null); } static class NormalData { private static final int CONSTANT = 1; private final int mField = 1; private Object mField2 = ""; private Object mObjectListener = new MockOnResultListener(); private final Object mFinalObjectListener = mObjectListener; private OnResultListener mNull = null; private OnResultListener mOnResultListener = new MockOnResultListener(); private OnResultListener mOnResultListenerAnonymous = new OnResultListener<Object>() { @Override public void onResult(int resultCode, Object o) { } }; } static class MockOnResultListener implements OnResultListener<Object> { boolean called = false; @Override public void onResult(int resultCode, Object o) { called = true; } static void initCalled(Object o) { ((MockOnResultListener) o).called = false; } static boolean isCalled(Object o) { return ((MockOnResultListener) o).called; } } }
3e056d1f7c7d3bb25c3c9fd022d9e95fa5d1ac07
2,119
java
Java
src/ConstructivismMain.java
palmdrop/sandbox
175f902f662b2a99d76a1d2b1f56b0f06b203d6b
[ "MIT" ]
16
2021-03-01T19:22:24.000Z
2021-11-28T16:29:49.000Z
src/ConstructivismMain.java
palmdrop/sandbox
175f902f662b2a99d76a1d2b1f56b0f06b203d6b
[ "MIT" ]
null
null
null
src/ConstructivismMain.java
palmdrop/sandbox
175f902f662b2a99d76a1d2b1f56b0f06b203d6b
[ "MIT" ]
1
2021-07-29T10:55:04.000Z
2021-07-29T10:55:04.000Z
26.160494
119
0.603587
2,269
import processing.core.PApplet; import processing.core.PGraphics; import sketch.constructivism.ConstructivismSketch; import util.geometry.Rectangle; public class ConstructivismMain extends PApplet { private int screenSize = 1000; private int screenWidth = screenSize; private int screenHeight = screenWidth; private double renderQuality = 1.0; private double saveQuality = renderQuality * 3; private int sketchWidth = (int) (screenWidth * renderQuality); private int sketchHeight = (int) (screenHeight * renderQuality); private ConstructivismSketch sketch; private PGraphics canvas; @Override public void settings() { size(screenWidth, screenHeight); } @Override public void setup() { canvas = createGraphics(sketchWidth, sketchHeight); Rectangle bounds = new Rectangle(canvas.width, canvas.height); sketch = new ConstructivismSketch(bounds); canvas.beginDraw(); canvas.background(255); sketch.draw(canvas); canvas.endDraw(); } @Override public void draw() { background(0); image(canvas, 0, 0, screenWidth, screenHeight); } public static void main(String[] args) { PApplet.main("ConstructivismMain"); } private void reset() { setup(); } public void keyPressed() { switch(key) { case 'r': reset(); break; case 's': { PGraphics render = createGraphics((int)(screenWidth * saveQuality), (int)(screenHeight * saveQuality)); Rectangle oldBounds = sketch.getBounds(); sketch.setBounds(new Rectangle(render.width, render.height)); render.beginDraw(); sketch.draw(render, 1.0/saveQuality, true); render.endDraw(); String name ="output/shapes/" + System.currentTimeMillis() + ".png"; render.save(name); System.out.println("Saved \"" + name + "\""); sketch.setBounds(oldBounds); } } } }
3e056d25701d28660890f6708fa2ff2eb08659b8
2,037
java
Java
testsuite/src/main/org/jboss/test/jca/test/InflowUnitTestCase.java
cquoss/jboss-4.2.3.GA-jdk8
f3acab9a69c764365bb3f38c0e9a01708dd22b4b
[ "Apache-2.0" ]
null
null
null
testsuite/src/main/org/jboss/test/jca/test/InflowUnitTestCase.java
cquoss/jboss-4.2.3.GA-jdk8
f3acab9a69c764365bb3f38c0e9a01708dd22b4b
[ "Apache-2.0" ]
null
null
null
testsuite/src/main/org/jboss/test/jca/test/InflowUnitTestCase.java
cquoss/jboss-4.2.3.GA-jdk8
f3acab9a69c764365bb3f38c0e9a01708dd22b4b
[ "Apache-2.0" ]
null
null
null
32.31746
102
0.714145
2,270
/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.jca.test; import junit.framework.Test; import org.jboss.test.JBossTestCase; import org.jboss.test.jca.inflow.TestResourceAdapter; import org.jboss.test.jca.inflow.TestResourceAdapterInflowResults; /** * Inflow Unit Tests * * @author <a href="mailto:[email protected]">Adrian Brock</a> * @version $Revision: 57211 $ */ public class InflowUnitTestCase extends JBossTestCase { public InflowUnitTestCase (String name) { super(name); } public static Test suite() throws Exception { Test t1 = getDeploySetup(InflowUnitTestCase.class, "jcainflowmdb.jar"); Test t2 = getDeploySetup(t1, "jcainflow.rar"); return t2; } public void testInflow() throws Throwable { TestResourceAdapterInflowResults results = (TestResourceAdapterInflowResults) getServer().invoke ( TestResourceAdapter.mbean, "testInflow", new Object[0], new String[0] ); results.check(); } }
3e056d9ac383f3cb3051b427058131c31719f706
699
java
Java
Aeon.Core/src/main/java/com/ultimatesoftware/aeon/core/command/execution/commands/QuitCommand.java
dgonz371/aeon-1
9af6630f7c9b28df59d84da044f28a292085eb0f
[ "Apache-2.0" ]
null
null
null
Aeon.Core/src/main/java/com/ultimatesoftware/aeon/core/command/execution/commands/QuitCommand.java
dgonz371/aeon-1
9af6630f7c9b28df59d84da044f28a292085eb0f
[ "Apache-2.0" ]
null
null
null
Aeon.Core/src/main/java/com/ultimatesoftware/aeon/core/command/execution/commands/QuitCommand.java
dgonz371/aeon-1
9af6630f7c9b28df59d84da044f28a292085eb0f
[ "Apache-2.0" ]
null
null
null
24.964286
76
0.685265
2,271
package com.ultimatesoftware.aeon.core.command.execution.commands; import com.ultimatesoftware.aeon.core.common.Resources; import com.ultimatesoftware.aeon.core.framework.abstraction.drivers.IDriver; /** * Quits the browser (all windows). */ public class QuitCommand extends Command { /** * Initializes a new instance of the {@link QuitCommand} class. */ public QuitCommand() { super(Resources.getString("QuitCommand_Info")); } /** * The method which provides the logic for the command. * * @param driver The framework abstraction facade. */ @Override protected void driverDelegate(IDriver driver) { driver.quit(); } }
3e056e0162beb0aae17db0091c74f1f9b0ac35d3
13,770
java
Java
kie-remote/kie-services-remote/src/main/java/org/kie/services/remote/rest/RuntimeResource.java
rsynek/droolsjbpm-integration
1ded85fded50003f52615187524b6c3b912a2a19
[ "Apache-2.0" ]
null
null
null
kie-remote/kie-services-remote/src/main/java/org/kie/services/remote/rest/RuntimeResource.java
rsynek/droolsjbpm-integration
1ded85fded50003f52615187524b6c3b912a2a19
[ "Apache-2.0" ]
null
null
null
kie-remote/kie-services-remote/src/main/java/org/kie/services/remote/rest/RuntimeResource.java
rsynek/droolsjbpm-integration
1ded85fded50003f52615187524b6c3b912a2a19
[ "Apache-2.0" ]
null
null
null
48.315789
131
0.708932
2,272
package org.kie.services.remote.rest; import static org.kie.services.remote.util.CommandsRequestUtil.processJaxbCommandsRequest; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import org.drools.core.command.runtime.process.AbortProcessInstanceCommand; import org.drools.core.command.runtime.process.AbortWorkItemCommand; import org.drools.core.command.runtime.process.CompleteWorkItemCommand; import org.drools.core.command.runtime.process.GetProcessInstanceCommand; import org.drools.core.command.runtime.process.SignalEventCommand; import org.drools.core.command.runtime.process.StartProcessCommand; import org.drools.core.command.runtime.process.StartProcessInstanceCommand; import org.jboss.resteasy.spi.BadRequestException; import org.jbpm.process.audit.NodeInstanceLog; import org.jbpm.process.audit.ProcessInstanceLog; import org.jbpm.process.audit.VariableInstanceLog; import org.jbpm.process.audit.command.ClearHistoryLogsCommand; import org.jbpm.process.audit.command.FindNodeInstancesCommand; import org.jbpm.process.audit.command.FindProcessInstanceCommand; import org.jbpm.process.audit.command.FindProcessInstancesCommand; import org.jbpm.process.audit.command.FindSubProcessInstancesCommand; import org.jbpm.process.audit.command.FindVariableInstancesCommand; import org.kie.api.command.Command; import org.kie.api.runtime.process.ProcessInstance; import org.kie.services.client.serialization.jaxb.JaxbCommandsRequest; import org.kie.services.client.serialization.jaxb.JaxbCommandsResponse; import org.kie.services.client.serialization.jaxb.impl.JaxbHistoryLogList; import org.kie.services.client.serialization.jaxb.impl.JaxbProcessInstanceResponse; import org.kie.services.client.serialization.jaxb.rest.JaxbGenericResponse; import org.kie.services.remote.cdi.ProcessRequestBean; import org.kie.services.remote.util.Paginator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Path("/runtime/{id: [a-zA-Z0-9-:\\.]+}") @RequestScoped @SuppressWarnings("unchecked") public class RuntimeResource extends ResourceBase { private static final Logger logger = LoggerFactory.getLogger(RuntimeResource.class); @Inject private ProcessRequestBean processRequestBean; @PathParam("id") private String deploymentId; @Context private HttpServletRequest request; // Rest methods -------------------------------------------------------------------------------------------------------------- @POST @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) @Path("/execute") public JaxbCommandsResponse execute(JaxbCommandsRequest cmdsRequest) { return processJaxbCommandsRequest(cmdsRequest, processRequestBean); } @POST @Produces(MediaType.APPLICATION_XML) @Path("/process/{processDefId: [a-zA-Z0-9-:\\.]+}/start") public JaxbProcessInstanceResponse startNewProcess(@PathParam("processDefId") String processId) { Map<String, List<String>> formParams = getRequestParams(request); Map<String, Object> params = extractMapFromParams(formParams, "process/" + processId + "/start"); Command<?> cmd = new StartProcessCommand(processId, params); ProcessInstance procInst = (ProcessInstance) processRequestBean.doKieSessionOperation(cmd, deploymentId); JaxbProcessInstanceResponse resp = new JaxbProcessInstanceResponse(procInst, request); return resp; } @GET @Produces(MediaType.APPLICATION_XML) @Path("/process/instance/{procInstId: [0-9]+}") public JaxbProcessInstanceResponse getProcessInstanceDetails(@PathParam("procInstId") Long procInstId) { Command<?> cmd = new GetProcessInstanceCommand(procInstId); Object result = processRequestBean.doKieSessionOperation(cmd, deploymentId); if (result != null) { return new JaxbProcessInstanceResponse((ProcessInstance) result); } else { throw new BadRequestException("Unable to retrieve process instance " + procInstId + " since it has been completed. Please see the history operations."); } } @POST @Produces(MediaType.APPLICATION_XML) @Path("/process/instance/{procInstId: [0-9]+}/abort") public JaxbGenericResponse abortProcessInstanceOperation(@PathParam("procInstId") Long procInstId) { Command<?> cmd = new AbortProcessInstanceCommand(); ((AbortProcessInstanceCommand) cmd).setProcessInstanceId(procInstId); processRequestBean.doKieSessionOperation(cmd, deploymentId); return new JaxbGenericResponse(request); } @POST @Produces(MediaType.APPLICATION_XML) @Path("/process/instance/{procInstId: [0-9]+}/signal") public JaxbGenericResponse signalProcessInstanceOperation(@PathParam("procInstId") Long procInstId) { Map<String, List<String>> params = getRequestParams(request); String eventType = getStringParam("eventType", true, params, "signal"); Object event = getObjectParam("event", false, params, "signal"); Command<?> cmd = new SignalEventCommand(procInstId, eventType, event); processRequestBean.doKieSessionOperation(cmd, deploymentId); return new JaxbGenericResponse(request); } @POST @Produces(MediaType.APPLICATION_XML) @Path("/process/instance/{procInstId: [0-9]+}/start") public JaxbProcessInstanceResponse startProcessInstanceOperation(@PathParam("procInstId") Long procInstId) { Command<?> cmd = new StartProcessInstanceCommand(procInstId); ProcessInstance procInst = (ProcessInstance) processRequestBean.doKieSessionOperation(cmd, deploymentId); return new JaxbProcessInstanceResponse(procInst, request); } @POST @Produces(MediaType.APPLICATION_XML) @Path("/signal/{signal: [a-zA-Z0-9-]+}") public JaxbGenericResponse signalEvent(@PathParam("signal") String signal) { Map<String, List<String>> formParams = getRequestParams(request); Object event = getObjectParam("event", false, formParams, "signal/" + signal); Command<?> cmd = new SignalEventCommand(signal, event); processRequestBean.doKieSessionOperation(cmd, deploymentId); return new JaxbGenericResponse(request); } @POST @Path("/workitem/{workItemId: [0-9-]+}/{oper: [a-zA-Z]+}") public JaxbGenericResponse doWorkItemOperation(@PathParam("workItemId") Long workItemId, @PathParam("oper") String operation) { Map<String, List<String>> params = getRequestParams(request); Command<?> cmd = null; if ("complete".equalsIgnoreCase((operation.trim()))) { Map<String, Object> results = extractMapFromParams(params, operation); cmd = new CompleteWorkItemCommand(workItemId, results); } else if ("abort".equalsIgnoreCase(operation.toLowerCase())) { cmd = new AbortWorkItemCommand(workItemId); } else { throw new BadRequestException("Unsupported operation: /process/instance/" + workItemId + "/" + operation); } processRequestBean.doKieSessionOperation(cmd, deploymentId); return new JaxbGenericResponse(request); } /** * History methods */ @POST @Produces(MediaType.APPLICATION_XML) @Path("/history/clear") public JaxbGenericResponse clearProcessInstanceLogs() { Command<?> cmd = new ClearHistoryLogsCommand(); processRequestBean.doKieSessionOperation(cmd, deploymentId); return new JaxbGenericResponse(request); } @GET @Produces(MediaType.APPLICATION_XML) @Path("/history/instance") public JaxbHistoryLogList getProcessInstanceLogs() { Map<String, List<String>> params = getRequestParams(request); int [] pageInfo = getPageNumAndPageSize(params); Command<?> cmd = new FindProcessInstancesCommand(); List<ProcessInstanceLog> results = (List<ProcessInstanceLog>) processRequestBean.doKieSessionOperation(cmd, deploymentId); results = (new Paginator<ProcessInstanceLog>()).paginate(pageInfo, results); return new JaxbHistoryLogList(results); } @GET @Produces(MediaType.APPLICATION_XML) @Path("/history/instance/{procInstId: [0-9]+}") public JaxbHistoryLogList getSpecificProcessInstanceLogs(@PathParam("procInstId") long procInstId) { Map<String, List<String>> params = getRequestParams(request); int [] pageInfo = getPageNumAndPageSize(params); Command<?> cmd = new FindProcessInstanceCommand(procInstId); ProcessInstanceLog procInstLog = (ProcessInstanceLog) processRequestBean.doKieSessionOperation(cmd, deploymentId); List<ProcessInstanceLog> logList = new ArrayList<ProcessInstanceLog>(); logList.add(procInstLog); logList = (new Paginator<ProcessInstanceLog>()).paginate(pageInfo, logList); return new JaxbHistoryLogList(logList); } @GET @Produces(MediaType.APPLICATION_XML) @Path("/history/instance/{procInstId: [0-9]+}/{oper: [a-zA-Z]+}") public JaxbHistoryLogList getVariableOrNodeHistoryList(@PathParam("procInstId") Long processInstanceId, @PathParam("oper") String operation) { Map<String, List<String>> params = getRequestParams(request); int [] pageInfo = getPageNumAndPageSize(params); JaxbHistoryLogList resultList; Command<?> cmd; if ("child".equalsIgnoreCase(operation)) { cmd = new FindSubProcessInstancesCommand(processInstanceId); List<ProcessInstanceLog> procInstLogList = (List<ProcessInstanceLog>) processRequestBean.doKieSessionOperation(cmd, deploymentId); procInstLogList = (new Paginator<ProcessInstanceLog>()).paginate(pageInfo, procInstLogList); resultList = new JaxbHistoryLogList(procInstLogList); } else if ("node".equalsIgnoreCase(operation)) { cmd = new FindNodeInstancesCommand(processInstanceId); List<NodeInstanceLog> nodeInstLogList = (List<NodeInstanceLog>) processRequestBean.doKieSessionOperation(cmd, deploymentId); nodeInstLogList = (new Paginator<NodeInstanceLog>()).paginate(pageInfo, nodeInstLogList); resultList = new JaxbHistoryLogList(nodeInstLogList); } else if ("variable".equalsIgnoreCase(operation)) { cmd = new FindVariableInstancesCommand(processInstanceId); List<VariableInstanceLog> varInstLogList = (List<VariableInstanceLog>) processRequestBean.doKieSessionOperation(cmd, deploymentId); varInstLogList = (new Paginator<VariableInstanceLog>()).paginate(pageInfo, varInstLogList); resultList = new JaxbHistoryLogList(varInstLogList); } else { throw new BadRequestException("Unsupported operation: /history/instance/" + processInstanceId + "/" + operation); } return resultList; } @GET @Produces(MediaType.APPLICATION_XML) @Path("/history/instance/{procInstId: [0-9]+}/{oper: [a-zA-Z]+}/{id: [a-zA-Z0-9-:\\.]+}") public JaxbHistoryLogList getSpecificVariableOrNodeHistoryList(@PathParam("procInstId") Long processInstanceId, @PathParam("oper") String operation, @PathParam("id") String id) { Map<String, List<String>> params = getRequestParams(request); int [] pageInfo = getPageNumAndPageSize(params); JaxbHistoryLogList resultList; Command<?> cmd; if ("node".equalsIgnoreCase(operation)) { cmd = new FindNodeInstancesCommand(processInstanceId, id); List<NodeInstanceLog> nodeInstLogList = (List<NodeInstanceLog>) processRequestBean.doKieSessionOperation(cmd, deploymentId); nodeInstLogList = (new Paginator<NodeInstanceLog>()).paginate(pageInfo, nodeInstLogList); resultList = new JaxbHistoryLogList(nodeInstLogList); } else if ("variable".equalsIgnoreCase(operation)) { cmd = new FindVariableInstancesCommand(processInstanceId, id); List<VariableInstanceLog> varInstLogList = (List<VariableInstanceLog>) processRequestBean.doKieSessionOperation(cmd, deploymentId); varInstLogList = (new Paginator<VariableInstanceLog>()).paginate(pageInfo, varInstLogList); resultList = new JaxbHistoryLogList(varInstLogList); } else { throw new BadRequestException("Unsupported operation: /history/instance/" + processInstanceId + "/" + operation + "/" + id); } return resultList; } @GET @Produces(MediaType.APPLICATION_XML) @Path("/history/process/{procId: [a-zA-Z0-9-:\\.]+}") public JaxbHistoryLogList getProcessInstanceLogs(@PathParam("procId") String processId) { Map<String, List<String>> params = getRequestParams(request); int [] pageInfo = getPageNumAndPageSize(params); Command<?> cmd = new FindProcessInstancesCommand(processId); List<ProcessInstanceLog> procInstLogList = (List<ProcessInstanceLog>) processRequestBean.doKieSessionOperation(cmd, deploymentId); procInstLogList = (new Paginator<ProcessInstanceLog>()).paginate(pageInfo, procInstLogList); return new JaxbHistoryLogList(procInstLogList); } }
3e056ec7fd0aa0c6ba4c3a5fc735067ade7abae6
1,376
java
Java
src/java/org/apache/ojb/broker/transaction/tm/WeblogicTransactionManagerFactory.java
iu-uits-es/ojb
fb2f8d0e8efaa7dd21db233b9a61d13cf45df3e0
[ "Apache-2.0" ]
null
null
null
src/java/org/apache/ojb/broker/transaction/tm/WeblogicTransactionManagerFactory.java
iu-uits-es/ojb
fb2f8d0e8efaa7dd21db233b9a61d13cf45df3e0
[ "Apache-2.0" ]
null
null
null
src/java/org/apache/ojb/broker/transaction/tm/WeblogicTransactionManagerFactory.java
iu-uits-es/ojb
fb2f8d0e8efaa7dd21db233b9a61d13cf45df3e0
[ "Apache-2.0" ]
null
null
null
35.282051
97
0.71875
2,273
package org.apache.ojb.broker.transaction.tm; /* Copyright 2003-2005 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.ojb.broker.transaction.tm.AbstractTransactionManagerFactory; /** * Weblogic {@link javax.transaction.TransactionManager} lookup. * * @author matthew.baird * @version $Id: WeblogicTransactionManagerFactory.java,v 1.1 2007-08-24 22:17:41 ewestfal Exp $ */ public class WeblogicTransactionManagerFactory extends AbstractTransactionManagerFactory { private static final String[][] config = { {"Weblogic", "javax.transaction.TransactionManager", null}}; /** * @see org.apache.ojb.broker.transaction.tm.AbstractTransactionManagerFactory#getLookupInfo */ public String[][] getLookupInfo() { return config; } }
3e056fe5bd898eef31873e6eb15e92f006549231
4,694
java
Java
src/main/java/run/halo/app/controller/admin/api/UserController.java
SeanGaoTesing/halo-master
759070caf92e04af2ad4cc4e0dd40c7789f524f5
[ "MIT" ]
null
null
null
src/main/java/run/halo/app/controller/admin/api/UserController.java
SeanGaoTesing/halo-master
759070caf92e04af2ad4cc4e0dd40c7789f524f5
[ "MIT" ]
1
2021-07-05T20:11:04.000Z
2021-07-05T20:11:04.000Z
src/main/java/run/halo/app/controller/admin/api/UserController.java
SeanGaoTesing/halo-master
759070caf92e04af2ad4cc4e0dd40c7789f524f5
[ "MIT" ]
1
2021-07-05T20:01:46.000Z
2021-07-05T20:01:46.000Z
38.793388
98
0.703025
2,274
package run.halo.app.controller.admin.api; import cn.hutool.core.codec.Base64; import cn.hutool.core.util.StrUtil; import cn.hutool.extra.qrcode.QrCodeUtil; import io.swagger.annotations.ApiOperation; import javax.validation.Valid; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import run.halo.app.annotation.DisableOnCondition; import run.halo.app.cache.lock.CacheLock; import run.halo.app.exception.BadRequestException; import run.halo.app.model.dto.UserDTO; import run.halo.app.model.entity.User; import run.halo.app.model.enums.MFAType; import run.halo.app.model.params.MultiFactorAuthParam; import run.halo.app.model.params.PasswordParam; import run.halo.app.model.params.UserParam; import run.halo.app.model.support.BaseResponse; import run.halo.app.model.support.UpdateCheck; import run.halo.app.model.vo.MultiFactorAuthVO; import run.halo.app.service.UserService; import run.halo.app.utils.TwoFactorAuthUtils; import run.halo.app.utils.ValidationUtils; /** * User controller. * * @author johnniang * @date 2019-03-19 */ @RestController @RequestMapping("/api/admin/users") public class UserController { private final UserService userService; public UserController(UserService userService) { this.userService = userService; } @GetMapping("profiles") @ApiOperation("Gets user profile") public UserDTO getProfile(User user) { return new UserDTO().convertFrom(user); } @PutMapping("profiles") @ApiOperation("Updates user profile") @DisableOnCondition public UserDTO updateProfile(@RequestBody UserParam userParam, User user) { // Validate the user param ValidationUtils.validate(userParam, UpdateCheck.class); // Update properties userParam.update(user); // Update user and convert to dto return new UserDTO().convertFrom(userService.update(user)); } @PutMapping("profiles/password") @ApiOperation("Updates user's password") @DisableOnCondition public BaseResponse<String> updatePassword(@RequestBody @Valid PasswordParam passwordParam, User user) { userService.updatePassword(passwordParam.getOldPassword(), passwordParam.getNewPassword(), user.getId()); return BaseResponse.ok("密码修改成功"); } @PutMapping("mfa/generate") @ApiOperation("Generate Multi-Factor Auth qr image") @DisableOnCondition public MultiFactorAuthVO generateMFAQrImage( @RequestBody MultiFactorAuthParam multiFactorAuthParam, User user) { if (MFAType.NONE == user.getMfaType()) { if (MFAType.TFA_TOTP == multiFactorAuthParam.getMfaType()) { String mfaKey = TwoFactorAuthUtils.generateTFAKey(); String optAuthUrl = TwoFactorAuthUtils.generateOtpAuthUrl(user.getNickname(), mfaKey); String qrImageBase64 = "data:image/png;base64," + Base64.encode(QrCodeUtil.generatePng(optAuthUrl, 128, 128)); return new MultiFactorAuthVO(qrImageBase64, optAuthUrl, mfaKey, MFAType.TFA_TOTP); } else { throw new BadRequestException("暂不支持的 MFA 认证的方式"); } } else { throw new BadRequestException("MFA 认证已启用,无需重复操作"); } } @PutMapping("mfa/update") @ApiOperation("Updates user's Multi Factor Auth") @CacheLock(autoDelete = false, prefix = "mfa") @DisableOnCondition public MultiFactorAuthVO updateMFAuth( @RequestBody @Valid MultiFactorAuthParam multiFactorAuthParam, User user) { if (StrUtil.isNotBlank(user.getMfaKey()) && MFAType.useMFA(multiFactorAuthParam.getMfaType())) { return new MultiFactorAuthVO(MFAType.TFA_TOTP); } else if (StrUtil.isBlank(user.getMfaKey()) && !MFAType.useMFA(multiFactorAuthParam.getMfaType())) { return new MultiFactorAuthVO(MFAType.NONE); } else { final String tfaKey = StrUtil.isNotBlank(user.getMfaKey()) ? user.getMfaKey() : multiFactorAuthParam.getMfaKey(); TwoFactorAuthUtils.validateTFACode(tfaKey, multiFactorAuthParam.getAuthcode()); } // update MFA key User updateUser = userService .updateMFA(multiFactorAuthParam.getMfaType(), multiFactorAuthParam.getMfaKey(), user.getId()); return new MultiFactorAuthVO(updateUser.getMfaType()); } }
3e05707bcd9dbc2927a022ae5ec7eb6397476f94
495
java
Java
WorkbenchProject/src/main/java/edu/uwb/braingrid/workbenchdashboard/threads/RunInit.java
etcadinfinitum/WorkBench
c8206eaefb846e9590d99ac870c932c1789f1069
[ "Apache-2.0" ]
null
null
null
WorkbenchProject/src/main/java/edu/uwb/braingrid/workbenchdashboard/threads/RunInit.java
etcadinfinitum/WorkBench
c8206eaefb846e9590d99ac870c932c1789f1069
[ "Apache-2.0" ]
null
null
null
WorkbenchProject/src/main/java/edu/uwb/braingrid/workbenchdashboard/threads/RunInit.java
etcadinfinitum/WorkBench
c8206eaefb846e9590d99ac870c932c1789f1069
[ "Apache-2.0" ]
null
null
null
23.571429
83
0.775758
2,275
package edu.uwb.braingrid.workbenchdashboard.threads; import java.util.logging.Logger; import edu.uwb.braingrid.workbenchdashboard.utils.Init; import edu.uwb.braingrid.workbenchdashboard.utils.ThreadManager; public class RunInit extends Thread implements Runnable { public RunInit() { } public void run() { ThreadManager.addThread("Init"); Init.init(); ThreadManager.removeThread("Init"); } private static final Logger LOG = Logger.getLogger(RunUpdateRepo.class.getName()); }
3e0571a0f8e47fbaf58e5099a98a0b56323365f4
19,104
java
Java
gateway-spi/src/test/java/org/apache/knox/gateway/dispatch/ConfigurableDispatchTest.java
newHE3DBer/knox
b56a424008f6444ea9f83e3381ddb0d31c6b0722
[ "Apache-2.0" ]
1
2020-11-27T06:18:01.000Z
2020-11-27T06:18:01.000Z
gateway-spi/src/test/java/org/apache/knox/gateway/dispatch/ConfigurableDispatchTest.java
smallstudent666/knox
b56a424008f6444ea9f83e3381ddb0d31c6b0722
[ "Apache-2.0" ]
null
null
null
gateway-spi/src/test/java/org/apache/knox/gateway/dispatch/ConfigurableDispatchTest.java
smallstudent666/knox
b56a424008f6444ea9f83e3381ddb0d31c6b0722
[ "Apache-2.0" ]
null
null
null
49.492228
292
0.74152
2,276
/* * 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.knox.gateway.dispatch; import static org.apache.knox.gateway.dispatch.DefaultDispatch.SET_COOKIE; import static org.apache.knox.gateway.dispatch.DefaultDispatch.WWW_AUTHENTICATE; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.net.URI; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.http.Header; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.message.BasicHeader; import org.apache.knox.test.TestUtils; import org.apache.knox.test.mock.MockHttpServletResponse; import org.easymock.Capture; import org.easymock.EasyMock; import org.junit.Test; public class ConfigurableDispatchTest { @Test( timeout = TestUtils.SHORT_TIMEOUT ) public void testGetDispatchUrl() { HttpServletRequest request; String path; String query; URI uri; ConfigurableDispatch dispatch = new ConfigurableDispatch(); path = "http://test-host:42/test-path"; request = EasyMock.createNiceMock( HttpServletRequest.class ); EasyMock.expect( request.getRequestURI() ).andReturn( path ).anyTimes(); EasyMock.expect( request.getRequestURL() ).andReturn( new StringBuffer( path ) ).anyTimes(); EasyMock.expect( request.getQueryString() ).andReturn( null ).anyTimes(); EasyMock.replay( request ); uri = dispatch.getDispatchUrl( request ); assertThat( uri.toASCIIString(), is( "http://test-host:42/test-path" ) ); path = "http://test-host:42/test,path"; request = EasyMock.createNiceMock( HttpServletRequest.class ); EasyMock.expect( request.getRequestURI() ).andReturn( path ).anyTimes(); EasyMock.expect( request.getRequestURL() ).andReturn( new StringBuffer( path ) ).anyTimes(); EasyMock.expect( request.getQueryString() ).andReturn( null ).anyTimes(); EasyMock.replay( request ); uri = dispatch.getDispatchUrl( request ); assertThat( uri.toASCIIString(), is( "http://test-host:42/test,path" ) ); path = "http://test-host:42/test%2Cpath"; query = "service_config_version_note.matches(Updated%20Kerberos-related%20configurations"; request = EasyMock.createNiceMock( HttpServletRequest.class ); EasyMock.expect( request.getRequestURI() ).andReturn( path ).anyTimes(); EasyMock.expect( request.getRequestURL() ).andReturn( new StringBuffer( path ) ).anyTimes(); EasyMock.expect( request.getQueryString() ).andReturn( query ).anyTimes(); EasyMock.replay( request ); uri = dispatch.getDispatchUrl( request ); assertThat( uri.toASCIIString(), is( "http://test-host:42/test%2Cpath?service_config_version_note.matches(Updated%20Kerberos-related%20configurations" ) ); path = "http://test-host:42/test%2Cpath"; request = EasyMock.createNiceMock( HttpServletRequest.class ); EasyMock.expect( request.getRequestURI() ).andReturn( path ).anyTimes(); EasyMock.expect( request.getRequestURL() ).andReturn( new StringBuffer( path ) ).anyTimes(); EasyMock.expect( request.getQueryString() ).andReturn( null ).anyTimes(); EasyMock.replay( request ); uri = dispatch.getDispatchUrl( request ); assertThat( uri.toASCIIString(), is( "http://test-host:42/test%2Cpath" ) ); path = "http://test-host:42/test%2Cpath"; query = "test%26name=test%3Dvalue"; request = EasyMock.createNiceMock( HttpServletRequest.class ); EasyMock.expect( request.getRequestURI() ).andReturn( path ).anyTimes(); EasyMock.expect( request.getRequestURL() ).andReturn( new StringBuffer( path ) ).anyTimes(); EasyMock.expect( request.getQueryString() ).andReturn( query ).anyTimes(); EasyMock.replay( request ); uri = dispatch.getDispatchUrl( request ); assertThat( uri.toASCIIString(), is( "http://test-host:42/test%2Cpath?test%26name=test%3Dvalue" ) ); } @Test( timeout = TestUtils.SHORT_TIMEOUT ) public void testGetDispatchUrlNoUrlEncoding() { HttpServletRequest request; String path; String query; URI uri; ConfigurableDispatch dispatch = new ConfigurableDispatch(); dispatch.setRemoveUrlEncoding(Boolean.TRUE.toString()); path = "http://test-host:42/test-path"; request = EasyMock.createNiceMock( HttpServletRequest.class ); EasyMock.expect( request.getRequestURI() ).andReturn( path ).anyTimes(); EasyMock.expect( request.getRequestURL() ).andReturn( new StringBuffer( path ) ).anyTimes(); EasyMock.expect( request.getQueryString() ).andReturn( null ).anyTimes(); EasyMock.replay( request ); uri = dispatch.getDispatchUrl( request ); assertThat( uri.toASCIIString(), is( "http://test-host:42/test-path" ) ); path = "http://test-host:42/test,path"; request = EasyMock.createNiceMock( HttpServletRequest.class ); EasyMock.expect( request.getRequestURI() ).andReturn( path ).anyTimes(); EasyMock.expect( request.getRequestURL() ).andReturn( new StringBuffer( path ) ).anyTimes(); EasyMock.expect( request.getQueryString() ).andReturn( null ).anyTimes(); EasyMock.replay( request ); uri = dispatch.getDispatchUrl( request ); assertThat( uri.toASCIIString(), is( "http://test-host:42/test,path" ) ); // encoding in the patch remains path = "http://test-host:42/test%2Cpath"; request = EasyMock.createNiceMock( HttpServletRequest.class ); EasyMock.expect( request.getRequestURI() ).andReturn( path ).anyTimes(); EasyMock.expect( request.getRequestURL() ).andReturn( new StringBuffer( path ) ).anyTimes(); EasyMock.expect( request.getQueryString() ).andReturn( null ).anyTimes(); EasyMock.replay( request ); uri = dispatch.getDispatchUrl( request ); assertThat( uri.toASCIIString(), is( "http://test-host:42/test%2Cpath" ) ); // encoding in query %20 is not removed path = "http://test-host:42/test%2Cpath"; query = "service_config_version_note.matches(Updated%20Kerberos-related%20configurations"; request = EasyMock.createNiceMock( HttpServletRequest.class ); EasyMock.expect( request.getRequestURI() ).andReturn( path ).anyTimes(); EasyMock.expect( request.getRequestURL() ).andReturn( new StringBuffer( path ) ).anyTimes(); EasyMock.expect( request.getQueryString() ).andReturn( query ).anyTimes(); EasyMock.replay( request ); uri = dispatch.getDispatchUrl( request ); assertThat( uri.toASCIIString(), is( "http://test-host:42/test%2Cpath?service_config_version_note.matches(Updated%20Kerberos-related%20configurations" ) ); // encoding in query string is removed path = "http://test-host:42/test%2Cpath"; query = "test%26name=test%3Dvalue"; request = EasyMock.createNiceMock( HttpServletRequest.class ); EasyMock.expect( request.getRequestURI() ).andReturn( path ).anyTimes(); EasyMock.expect( request.getRequestURL() ).andReturn( new StringBuffer( path ) ).anyTimes(); EasyMock.expect( request.getQueryString() ).andReturn( query ).anyTimes(); EasyMock.replay( request ); uri = dispatch.getDispatchUrl( request ); assertThat( uri.toASCIIString(), is( "http://test-host:42/test%2Cpath?test&name=test=value" ) ); // double quotes removed path = "https://test-host:42/api/v1/views/TEZ/versions/0.7.0.2.6.2.0-205/instances/TEZ_CLUSTER_INSTANCE/resources/atsproxy/ws/v1/timeline/TEZ_DAG_ID"; query = "limit=9007199254740991&primaryFilter=applicationId:%22application_1518808140659_0007%22&_=1519053586839"; request = EasyMock.createNiceMock( HttpServletRequest.class ); EasyMock.expect( request.getRequestURI() ).andReturn( path ).anyTimes(); EasyMock.expect( request.getRequestURL() ).andReturn( new StringBuffer( path ) ).anyTimes(); EasyMock.expect( request.getQueryString() ).andReturn( query ).anyTimes(); EasyMock.replay( request ); uri = dispatch.getDispatchUrl( request ); assertThat( uri.toASCIIString(), is( "https://test-host:42/api/v1/views/TEZ/versions/0.7.0.2.6.2.0-205/instances/TEZ_CLUSTER_INSTANCE/resources/atsproxy/ws/v1/timeline/TEZ_DAG_ID?limit=9007199254740991&primaryFilter=applicationId:%22application_1518808140659_0007%22&_=1519053586839" ) ); // encode < and > sign path = "http://test-host:8080/api/v1/clusters/mmolnar-knox2/configurations/service_config_versions"; query = "group_id%3E0&fields=*&_=1541527314780"; request = EasyMock.createNiceMock( HttpServletRequest.class ); EasyMock.expect( request.getRequestURI() ).andReturn( path ).anyTimes(); EasyMock.expect( request.getRequestURL() ).andReturn( new StringBuffer( path ) ).anyTimes(); EasyMock.expect( request.getQueryString() ).andReturn( query ).anyTimes(); EasyMock.replay( request ); uri = dispatch.getDispatchUrl( request ); assertThat( uri.toASCIIString(), is( "http://test-host:8080/api/v1/clusters/mmolnar-knox2/configurations/service_config_versions?group_id%3E0&fields=*&_=1541527314780" ) ); } @Test( timeout = TestUtils.SHORT_TIMEOUT ) public void testRequestExcludeHeadersDefault() { ConfigurableDispatch dispatch = new ConfigurableDispatch(); Map<String, String> headers = new HashMap<>(); headers.put(HttpHeaders.AUTHORIZATION, "Basic ..."); headers.put(HttpHeaders.ACCEPT, "abc"); headers.put("TEST", "test"); HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class); EasyMock.expect(inboundRequest.getHeaderNames()).andReturn(Collections.enumeration(headers.keySet())).anyTimes(); Capture<String> capturedArgument = Capture.newInstance(); EasyMock.expect(inboundRequest.getHeader(EasyMock.capture(capturedArgument))) .andAnswer(() -> headers.get(capturedArgument.getValue())).anyTimes(); EasyMock.replay(inboundRequest); HttpUriRequest outboundRequest = new HttpGet(); dispatch.copyRequestHeaderFields(outboundRequest, inboundRequest); Header[] outboundRequestHeaders = outboundRequest.getAllHeaders(); assertThat(outboundRequestHeaders.length, is(2)); assertThat(outboundRequestHeaders[0].getName(), is(HttpHeaders.ACCEPT)); assertThat(outboundRequestHeaders[1].getName(), is("TEST")); } @Test( timeout = TestUtils.SHORT_TIMEOUT ) public void testRequestExcludeHeadersConfig() { ConfigurableDispatch dispatch = new ConfigurableDispatch(); dispatch.setRequestExcludeHeaders(String.join(",", Arrays.asList(HttpHeaders.ACCEPT, "TEST"))); Map<String, String> headers = new HashMap<>(); headers.put(HttpHeaders.AUTHORIZATION, "Basic ..."); headers.put(HttpHeaders.ACCEPT, "abc"); headers.put("TEST", "test"); HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class); EasyMock.expect(inboundRequest.getHeaderNames()).andReturn(Collections.enumeration(headers.keySet())).anyTimes(); Capture<String> capturedArgument = Capture.newInstance(); EasyMock.expect(inboundRequest.getHeader(EasyMock.capture(capturedArgument))) .andAnswer(() -> headers.get(capturedArgument.getValue())).anyTimes(); EasyMock.replay(inboundRequest); HttpUriRequest outboundRequest = new HttpGet(); dispatch.copyRequestHeaderFields(outboundRequest, inboundRequest); Header[] outboundRequestHeaders = outboundRequest.getAllHeaders(); assertThat(outboundRequestHeaders.length, is(1)); assertThat(outboundRequestHeaders[0].getName(), is(HttpHeaders.AUTHORIZATION)); } @Test public void testResponseExcludeHeadersDefault() { ConfigurableDispatch dispatch = new ConfigurableDispatch(); Header[] headers = new Header[]{ new BasicHeader(SET_COOKIE, "abc"), new BasicHeader(WWW_AUTHENTICATE, "negotiate"), new BasicHeader("TEST", "testValue"), new BasicHeader("Accept", "applcation/json") }; HttpResponse inboundResponse = EasyMock.createNiceMock(HttpResponse.class); EasyMock.expect(inboundResponse.getAllHeaders()).andReturn(headers).anyTimes(); EasyMock.replay(inboundResponse); HttpServletResponse outboundResponse = new MockHttpServletResponse(); dispatch.copyResponseHeaderFields(outboundResponse, inboundResponse); assertThat(outboundResponse.getHeaderNames().size(), is(2)); assertThat(outboundResponse.getHeader("TEST"), is("testValue")); assertThat(outboundResponse.getHeader("Accept"), is("applcation/json")); } @Test public void testResponseExcludeHeadersConfig() { ConfigurableDispatch dispatch = new ConfigurableDispatch(); dispatch.setResponseExcludeHeaders(String.join(",", Arrays.asList("test", "caseINSENSITIVEheader"))); Header[] headers = new Header[]{ new BasicHeader(SET_COOKIE, "abc"), new BasicHeader(WWW_AUTHENTICATE, "negotiate"), new BasicHeader("TEST", "testValue"), new BasicHeader("caseInsensitiveHeader", "caseInsensitiveHeaderValue") }; HttpResponse inboundResponse = EasyMock.createNiceMock(HttpResponse.class); EasyMock.expect(inboundResponse.getAllHeaders()).andReturn(headers).anyTimes(); EasyMock.replay(inboundResponse); HttpServletResponse outboundResponse = new MockHttpServletResponse(); dispatch.copyResponseHeaderFields(outboundResponse, inboundResponse); assertThat(outboundResponse.getHeaderNames().size(), is(2)); assertThat(outboundResponse.getHeader(SET_COOKIE), is("abc")); assertThat(outboundResponse.getHeader(WWW_AUTHENTICATE), is("negotiate")); } @Test public void shouldExcludeCertainPartsFromSetCookieHeader() throws Exception { final Header[] headers = new Header[] { new BasicHeader(SET_COOKIE, "Domain=localhost; Secure; HttpOnly; Max-Age=1") }; final HttpResponse inboundResponse = EasyMock.createNiceMock(HttpResponse.class); EasyMock.expect(inboundResponse.getAllHeaders()).andReturn(headers).anyTimes(); EasyMock.replay(inboundResponse); final ConfigurableDispatch dispatch = new ConfigurableDispatch(); final String setCookieExludeHeaders = SET_COOKIE + ": Domain=localhost; HttpOnly"; dispatch.setResponseExcludeHeaders(setCookieExludeHeaders); final HttpServletResponse outboundResponse = new MockHttpServletResponse(); dispatch.copyResponseHeaderFields(outboundResponse, inboundResponse); assertThat(outboundResponse.getHeaderNames().size(), is(1)); assertThat(outboundResponse.getHeader(SET_COOKIE), is("Secure; Max-Age=1")); } /** * When exclude list is defined and set-cookie is not in the list * make sure auth cookies are blocked. * @throws Exception */ @Test public void testPreventSetCookieHeaderDirectivesDefault() throws Exception { final Header[] headers = new Header[] { new BasicHeader(SET_COOKIE, "hadoop.auth=\"u=knox&p=knox/[email protected]&t=kerberos&e=1604347441986c=\"; Path=/; Domain=knox.local; Expires=Fri, 13-Nov-2020 17:26:18 GMT; Secure; HttpOnly[\\r][\\n]")}; final HttpResponse inboundResponse = EasyMock.createNiceMock(HttpResponse.class); EasyMock.expect(inboundResponse.getAllHeaders()).andReturn(headers).anyTimes(); EasyMock.replay(inboundResponse); final ConfigurableDispatch dispatch = new ConfigurableDispatch(); final String setCookieExludeHeaders = "WWW-AUTHENTICATE"; dispatch.setResponseExcludeHeaders(setCookieExludeHeaders); final HttpServletResponse outboundResponse = new MockHttpServletResponse(); dispatch.copyResponseHeaderFields(outboundResponse, inboundResponse); assertThat(outboundResponse.getHeaderNames().size(), is(0)); } /** * When exclude list is defined and set-cookie is not in the list * make sure non-auth cookies are not blocked. * @throws Exception */ @Test public void testAllowSetCookieHeaderDirectivesDefault() throws Exception { final Header[] headers = new Header[] { new BasicHeader(SET_COOKIE, "RANGERADMINSESSIONID=5C0C1805BD3B43BA8E9FC04A63586505; Path=/; Secure; HttpOnly")}; final HttpResponse inboundResponse = EasyMock.createNiceMock(HttpResponse.class); EasyMock.expect(inboundResponse.getAllHeaders()).andReturn(headers).anyTimes(); EasyMock.replay(inboundResponse); final ConfigurableDispatch dispatch = new ConfigurableDispatch(); final String setCookieExludeHeaders = "WWW-AUTHENTICATE"; dispatch.setResponseExcludeHeaders(setCookieExludeHeaders); final HttpServletResponse outboundResponse = new MockHttpServletResponse(); dispatch.copyResponseHeaderFields(outboundResponse, inboundResponse); assertThat(outboundResponse.getHeaderNames().size(), is(1)); assertThat(outboundResponse.getHeader(SET_COOKIE), is("Secure; Path=/; RANGERADMINSESSIONID=5C0C1805BD3B43BA8E9FC04A63586505; HttpOnly")); } /** * Case where auth cookie can be configured to pass through * * @throws Exception */ @Test public void testPassthroughSetCookieHeaderDirectivesDefault() throws Exception { final Header[] headers = new Header[] { new BasicHeader(SET_COOKIE, "hadoop.auth=\"u=knox&p=knox/[email protected]&t=kerberos&e=1604347441986c=\"; Path=/; Domain=knox.local; Expires=Fri, 13-Nov-2020 17:26:18 GMT; Secure; HttpOnly[\\r][\\n]") }; final HttpResponse inboundResponse = EasyMock .createNiceMock(HttpResponse.class); EasyMock.expect(inboundResponse.getAllHeaders()).andReturn(headers) .anyTimes(); EasyMock.replay(inboundResponse); final ConfigurableDispatch dispatch = new ConfigurableDispatch(); /** * NOTE: here we are defining what set-cookie attributes we * want to block. We are blocking only 'Secure' attribute * other attributes such as 'hadoop.auth' are free to pass **/ final String setCookieExludeHeaders = "WWW-AUTHENTICATE, SET-COOKIE: Secure"; dispatch.setResponseExcludeHeaders(setCookieExludeHeaders); final HttpServletResponse outboundResponse = new MockHttpServletResponse(); dispatch.copyResponseHeaderFields(outboundResponse, inboundResponse); assertThat(outboundResponse.getHeaderNames().size(), is(1)); assertThat(outboundResponse.getHeader(SET_COOKIE), containsString("hadoop.auth=")); } }
3e0571e3d6e9bcf1be90cc7f7cd94166911ee1ef
2,307
java
Java
src/main/java/br/com/zupacademy/william/ecommerce/produto/ProdutoDetalhesResponse.java
almeidawilliam/e-commerce
0577589eaa8e29bfc4f7b9e2e3d2c45cf8ea5a36
[ "Apache-2.0" ]
null
null
null
src/main/java/br/com/zupacademy/william/ecommerce/produto/ProdutoDetalhesResponse.java
almeidawilliam/e-commerce
0577589eaa8e29bfc4f7b9e2e3d2c45cf8ea5a36
[ "Apache-2.0" ]
null
null
null
src/main/java/br/com/zupacademy/william/ecommerce/produto/ProdutoDetalhesResponse.java
almeidawilliam/e-commerce
0577589eaa8e29bfc4f7b9e2e3d2c45cf8ea5a36
[ "Apache-2.0" ]
null
null
null
32.041667
95
0.669701
2,277
package br.com.zupacademy.william.ecommerce.produto; import br.com.zupacademy.william.ecommerce.produto.avaliacao.ProdutoAvaliacao; import br.com.zupacademy.william.ecommerce.produto.avaliacao.ProdutoAvaliacaoDetalhe; import br.com.zupacademy.william.ecommerce.produto.caracteristica.ProdutoCaracteristicaDetalhe; import br.com.zupacademy.william.ecommerce.produto.pergunta.ProdutoPerguntaDetalhe; import java.util.Set; import java.util.stream.Collectors; public class ProdutoDetalhesResponse { private ProdutoDetalheDto produto; private Set<ProdutoCaracteristicaDetalhe> caracteristicas; private Set<String> imagens; private double mediaNotas; private int totalNotas; private Set<ProdutoPerguntaDetalhe> perguntas; private Set<ProdutoAvaliacaoDetalhe> avaliacoes; public ProdutoDetalhesResponse(Produto produto) { this.produto = new ProdutoDetalheDto(produto); this.caracteristicas = produto.getCaracteristicas() .stream() .map(ProdutoCaracteristicaDetalhe::new) .collect(Collectors.toSet()); this.imagens = produto.getLinksImagens(); this.perguntas = produto.getPerguntas() .stream() .map(ProdutoPerguntaDetalhe::new) .collect(Collectors.toSet()); this.avaliacoes = produto.getAvaliacoes() .stream() .map(ProdutoAvaliacaoDetalhe::new) .collect(Collectors.toSet()); this.mediaNotas = produto.getAvaliacoes() .stream() .mapToInt(ProdutoAvaliacao::getNota) .average() .orElse(0); this.totalNotas = produto.getAvaliacoes().size(); } public ProdutoDetalheDto getProduto() { return produto; } public Set<ProdutoCaracteristicaDetalhe> getCaracteristicas() { return caracteristicas; } public Set<String> getImagens() { return imagens; } public double getMediaNotas() { return mediaNotas; } public int getTotalNotas() { return totalNotas; } public Set<ProdutoPerguntaDetalhe> getPerguntas() { return perguntas; } public Set<ProdutoAvaliacaoDetalhe> getAvaliacoes() { return avaliacoes; } }
3e057202b2fdf98ce3e23fa6c3692c433db56459
964
java
Java
impl/src/test/java/net/cpollet/seles/impl/testsupport/VoidAccessLevel.java
cpollet/seles
e14b36e919ae2a71dd2289f1ae99d7b5480cf23f
[ "Apache-2.0" ]
3
2019-04-16T22:18:26.000Z
2019-05-11T05:29:15.000Z
impl/src/test/java/net/cpollet/seles/impl/testsupport/VoidAccessLevel.java
cpollet/seles
e14b36e919ae2a71dd2289f1ae99d7b5480cf23f
[ "Apache-2.0" ]
2
2019-04-16T20:07:03.000Z
2021-10-20T05:36:35.000Z
impl/src/test/java/net/cpollet/seles/impl/testsupport/VoidAccessLevel.java
cpollet/seles
e14b36e919ae2a71dd2289f1ae99d7b5480cf23f
[ "Apache-2.0" ]
1
2019-04-16T19:59:49.000Z
2019-04-16T19:59:49.000Z
34.428571
75
0.748963
2,278
/* * Copyright 2019 Christophe Pollet * * 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.cpollet.seles.impl.testsupport; import net.cpollet.seles.api.attribute.AccessLevel; public class VoidAccessLevel implements AccessLevel { public static final VoidAccessLevel INSTANCE_1 = new VoidAccessLevel(); public static final VoidAccessLevel INSTANCE_2 = new VoidAccessLevel(); private VoidAccessLevel() { //nothing } }
3e0573b9e71caaf7cdc941c92b8b61f2852e664e
2,617
java
Java
x-language-samples/graphql-samples/graphql-springboot-kickstart-samples/src/main/java/xyz/flysium/photon/dao/repository/AuthorRepository.java
SvenAugustus/photon
1adf8fb7cfcc450fb04af5daaccc8513d46a16e8
[ "MIT" ]
2
2020-05-22T16:30:52.000Z
2021-05-10T13:40:04.000Z
x-language-samples/graphql-samples/graphql-springboot-kickstart-samples/src/main/java/xyz/flysium/photon/dao/repository/AuthorRepository.java
SvenAugustus/photon
1adf8fb7cfcc450fb04af5daaccc8513d46a16e8
[ "MIT" ]
4
2020-07-22T05:45:43.000Z
2022-02-02T13:04:12.000Z
x-language-samples/graphql-samples/graphql-springboot-kickstart-samples/src/main/java/xyz/flysium/photon/dao/repository/AuthorRepository.java
SvenAugustus/photon
1adf8fb7cfcc450fb04af5daaccc8513d46a16e8
[ "MIT" ]
3
2020-11-25T05:01:05.000Z
2021-11-21T13:05:59.000Z
40.890625
113
0.71112
2,279
/* * MIT License * * Copyright (c) 2020 SvenAugustus * * 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 xyz.flysium.photon.dao.repository; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import java.util.List; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Component; import xyz.flysium.photon.dao.entity.Author; /** * @author zeno (Sven Augustus) * @version 1.0 */ @Component @Mapper public interface AuthorRepository extends BaseMapper<Author> { // private static final List<Author> authors = Arrays.asList( // AuthorBuilder.anAuthor().id(1).firstName("Joanne").lastName("Rowling").build(), // AuthorBuilder.anAuthor().id(2).firstName("Herman").lastName("Melville").build(), // AuthorBuilder.anAuthor().id(3).firstName("Anne").lastName("Rice").build() // ); @Select("select ID, FIRST_NAME FIRSTNAME, LAST_NAME AS LASTNAME from author where id = #{authorId}") public Author findById(@Param("authorId") int authorId); /*{ return authors .stream() .filter(author -> author.getId() == authorId) .findFirst() .orElse(null); }*/ @Select("<script>" + "SELECT ID, FIRST_NAME FIRSTNAME, LAST_NAME AS LASTNAME from author WHERE id IN " + "<foreach item='key' index='index' collection='keys' open='(' separator=',' close=')'>" + "#{key}" + "</foreach>" + "</script>") List<Author> findAllById(@Param("keys") List<Integer> keys); }
3e0573c36cbe11db865e475913f9ec426ea76f2c
3,921
java
Java
server/src/main/java/org/jboss/as/server/deployment/module/ModuleClassPathProcessor.java
xjusko/wildfly-core
9bc5dc8f386bdc28c629df008d323e6aeaddf698
[ "Apache-2.0" ]
156
2015-01-05T09:12:40.000Z
2022-03-10T05:38:05.000Z
server/src/main/java/org/jboss/as/server/deployment/module/ModuleClassPathProcessor.java
xjusko/wildfly-core
9bc5dc8f386bdc28c629df008d323e6aeaddf698
[ "Apache-2.0" ]
3,440
2015-01-04T17:16:56.000Z
2022-03-31T16:47:13.000Z
server/src/main/java/org/jboss/as/server/deployment/module/ModuleClassPathProcessor.java
xjusko/wildfly-core
9bc5dc8f386bdc28c629df008d323e6aeaddf698
[ "Apache-2.0" ]
448
2015-01-08T15:47:49.000Z
2022-03-17T03:12:10.000Z
50.987013
176
0.72975
2,280
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.server.deployment.module; import java.util.List; import org.jboss.as.server.deployment.AttachmentList; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.modules.ModuleIdentifier; import org.jboss.modules.ModuleLoader; /** * The processor which adds {@code MANIFEST.MF} {@code Class-Path} entries to the module configuration. * * @author <a href="mailto:[email protected]">David M. Lloyd</a> * @author Stuart Douglas */ public final class ModuleClassPathProcessor implements DeploymentUnitProcessor { public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); final ModuleLoader moduleLoader = deploymentUnit.getAttachment(Attachments.SERVICE_MODULE_LOADER); final AttachmentList<ModuleIdentifier> entries = deploymentUnit.getAttachment(Attachments.CLASS_PATH_ENTRIES); if (entries != null) { for (ModuleIdentifier entry : entries) { //class path items are always exported to make transitive dependencies work moduleSpecification.addLocalDependency(new ModuleDependency(moduleLoader, entry, false, true, true, false)); } } final List<AdditionalModuleSpecification> additionalModules = deploymentUnit.getAttachment(Attachments.ADDITIONAL_MODULES); if (additionalModules != null) { for (AdditionalModuleSpecification additionalModule : additionalModules) { final AttachmentList<ModuleIdentifier> dependencies = additionalModule.getAttachment(Attachments.CLASS_PATH_ENTRIES); if (dependencies == null || dependencies.isEmpty()) { continue; } // additional modules export any class-path entries // this means that a module that references the additional module // gets access to the transitive closure of its call-path entries for (ModuleIdentifier entry : dependencies) { additionalModule.addLocalDependency(new ModuleDependency(moduleLoader, entry, false, true, true, false)); } // add a dependency on the top ear itself for good measure additionalModule.addLocalDependency(new ModuleDependency(moduleLoader, deploymentUnit.getAttachment(Attachments.MODULE_IDENTIFIER), false, false, true, false)); } } } }
3e057482e2097caf52d9281776fe88f77faa5dd8
1,843
java
Java
src/main/java/br/com/Uana/farmacia/model/Produto.java
WilliRamon/Farmacia_CRUD
640a40dbcc1063cdfa27047049ecd802da6f1f91
[ "MIT" ]
1
2022-01-29T19:10:23.000Z
2022-01-29T19:10:23.000Z
src/main/java/br/com/Uana/farmacia/model/Produto.java
WilliRamon/Farmacia_CRUD
640a40dbcc1063cdfa27047049ecd802da6f1f91
[ "MIT" ]
null
null
null
src/main/java/br/com/Uana/farmacia/model/Produto.java
WilliRamon/Farmacia_CRUD
640a40dbcc1063cdfa27047049ecd802da6f1f91
[ "MIT" ]
null
null
null
19.4
84
0.743896
2,281
package br.com.Uana.farmacia.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @Entity @Table(name = "tb_produto") public class Produto { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @NotBlank(message = "O atributo Nome não pode ser vazio") @Column(unique = true) @Size(max = 50, message = "O atributo Nome permite no máximo 50 caracteres") private String nome; @NotNull @Size(max = 500, message = "O atributo Descrição permite no máximo 500 caracteres") private String descricao; @Min(0) private double preco; @Min(0) private int qtdEstoque; @ManyToOne @JsonIgnoreProperties("produto") private Categoria categoria; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public double getPreco() { return preco; } public void setPreco(double preco) { this.preco = preco; } public int getQtdEstoque() { return qtdEstoque; } public void setQtdEstoque(int qtdEstoque) { this.qtdEstoque = qtdEstoque; } public Categoria getCategoria() { return categoria; } public void setCategoria(Categoria categoria) { this.categoria = categoria; } }
3e0574dd55b93a65a9f533620c3ae4a865c6689d
2,202
java
Java
config/config/src/test/java/io/helidon/config/internal/OverrideSourcesTest.java
akarnokd/helidon
0a2485d9dccfec57479c8859df261547dad66989
[ "Apache-2.0" ]
1
2020-01-26T08:59:31.000Z
2020-01-26T08:59:31.000Z
config/config/src/test/java/io/helidon/config/internal/OverrideSourcesTest.java
jahau/helidon
808bcf8bf718671e99b4293e226f5045ac843eb3
[ "Apache-2.0" ]
null
null
null
config/config/src/test/java/io/helidon/config/internal/OverrideSourcesTest.java
jahau/helidon
808bcf8bf718671e99b4293e226f5045ac843eb3
[ "Apache-2.0" ]
null
null
null
33.363636
127
0.675749
2,282
/* * Copyright (c) 2017, 2019 Oracle and/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. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.helidon.config.internal; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import io.helidon.config.Config; import io.helidon.config.OverrideSources; import io.helidon.config.spi.OverrideSource; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.sameInstance; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsInstanceOf.instanceOf; /** * Tests {@link OverrideSources}. */ public class OverrideSourcesTest { private static final String WILDCARDS = "*.*.audit.host"; @Test public void testEmptyIsAlwaysTheSameInstance() { assertThat(OverrideSources.empty(), sameInstance(OverrideSources.empty())); } @Test public void testFromWildcards() { OverrideSource overrideSource = OverrideSources.create(Map.of(WILDCARDS, "localhost")); assertThat(overrideSource.load() .get() .data() .stream() .findFirst() .get() .getKey() .test(Config.Key.create("prod.tenant1.audit.host")), is(true)); } @Test public void testUrlBuilder() throws MalformedURLException { UrlOverrideSource.UrlBuilder builder = (UrlOverrideSource.UrlBuilder) OverrideSources.url(new URL("http://localhost")); assertThat(builder.build(), instanceOf(UrlOverrideSource.class)); } }
3e057523642f818a5605d92123d78b6b8a31f321
11,535
java
Java
rt/frontend/jaxws/src/main/java/org/apache/cxf/jaxws/handler/soap/SOAPMessageContextImpl.java
sho25/cxf
4e2e93d8335f22575bf366df2a1b6cde681ad0ec
[ "Apache-2.0" ]
null
null
null
rt/frontend/jaxws/src/main/java/org/apache/cxf/jaxws/handler/soap/SOAPMessageContextImpl.java
sho25/cxf
4e2e93d8335f22575bf366df2a1b6cde681ad0ec
[ "Apache-2.0" ]
5
2021-02-03T19:35:39.000Z
2022-03-31T20:59:21.000Z
rt/frontend/jaxws/src/main/java/org/apache/cxf/jaxws/handler/soap/SOAPMessageContextImpl.java
sho25/cxf
4e2e93d8335f22575bf366df2a1b6cde681ad0ec
[ "Apache-2.0" ]
null
null
null
13.350694
810
0.797659
2,283
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|cxf operator|. name|jaxws operator|. name|handler operator|. name|soap package|; end_package begin_import import|import name|java operator|. name|util operator|. name|ArrayList import|; end_import begin_import import|import name|java operator|. name|util operator|. name|HashSet import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Iterator import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Map import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Set import|; end_import begin_import import|import name|javax operator|. name|xml operator|. name|bind operator|. name|JAXBContext import|; end_import begin_import import|import name|javax operator|. name|xml operator|. name|bind operator|. name|JAXBException import|; end_import begin_import import|import name|javax operator|. name|xml operator|. name|namespace operator|. name|QName import|; end_import begin_import import|import name|javax operator|. name|xml operator|. name|soap operator|. name|SOAPException import|; end_import begin_import import|import name|javax operator|. name|xml operator|. name|soap operator|. name|SOAPHeader import|; end_import begin_import import|import name|javax operator|. name|xml operator|. name|soap operator|. name|SOAPHeaderElement import|; end_import begin_import import|import name|javax operator|. name|xml operator|. name|soap operator|. name|SOAPMessage import|; end_import begin_import import|import name|javax operator|. name|xml operator|. name|ws operator|. name|WebServiceException import|; end_import begin_import import|import name|javax operator|. name|xml operator|. name|ws operator|. name|handler operator|. name|MessageContext import|; end_import begin_import import|import name|javax operator|. name|xml operator|. name|ws operator|. name|handler operator|. name|soap operator|. name|SOAPMessageContext import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|cxf operator|. name|binding operator|. name|soap operator|. name|SoapMessage import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|cxf operator|. name|binding operator|. name|soap operator|. name|saaj operator|. name|SAAJInInterceptor import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|cxf operator|. name|common operator|. name|jaxb operator|. name|JAXBUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|cxf operator|. name|helpers operator|. name|CastUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|cxf operator|. name|jaxws operator|. name|context operator|. name|WrappedMessageContext import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|cxf operator|. name|message operator|. name|Message import|; end_import begin_class specifier|public class|class name|SOAPMessageContextImpl extends|extends name|WrappedMessageContext implements|implements name|SOAPMessageContext block|{ specifier|private specifier|static specifier|final name|SAAJInInterceptor name|SAAJ_IN init|= operator|new name|SAAJInInterceptor argument_list|() decl_stmt|; specifier|private name|Set argument_list|< name|String argument_list|> name|roles init|= operator|new name|HashSet argument_list|<> argument_list|() decl_stmt|; specifier|public name|SOAPMessageContextImpl parameter_list|( name|Message name|m parameter_list|) block|{ name|super argument_list|( name|m argument_list|, name|Scope operator|. name|HANDLER argument_list|) expr_stmt|; name|roles operator|. name|add argument_list|( name|getWrappedSoapMessage argument_list|() operator|. name|getVersion argument_list|() operator|. name|getNextRole argument_list|() argument_list|) expr_stmt|; block|} specifier|public name|void name|setMessage parameter_list|( name|SOAPMessage name|message parameter_list|) block|{ if|if condition|( name|getWrappedMessage argument_list|() operator|. name|getContent argument_list|( name|Object operator|. name|class argument_list|) operator|instanceof name|SOAPMessage condition|) block|{ name|getWrappedMessage argument_list|() operator|. name|setContent argument_list|( name|Object operator|. name|class argument_list|, name|message argument_list|) expr_stmt|; block|} else|else block|{ name|getWrappedMessage argument_list|() operator|. name|setContent argument_list|( name|SOAPMessage operator|. name|class argument_list|, name|message argument_list|) expr_stmt|; block|} block|} specifier|public name|SOAPMessage name|getMessage parameter_list|() block|{ name|SOAPMessage name|message init|= literal|null decl_stmt|; if|if condition|( name|getWrappedMessage argument_list|() operator|. name|getContent argument_list|( name|Object operator|. name|class argument_list|) operator|instanceof name|SOAPMessage condition|) block|{ name|message operator|= operator|( name|SOAPMessage operator|) name|getWrappedMessage argument_list|() operator|. name|getContent argument_list|( name|Object operator|. name|class argument_list|) expr_stmt|; block|} else|else block|{ name|message operator|= name|getWrappedMessage argument_list|() operator|. name|getContent argument_list|( name|SOAPMessage operator|. name|class argument_list|) expr_stmt|; block|} comment|//Only happens to non-Dispatch/Provider case. if|if condition|( literal|null operator|== name|message condition|) block|{ name|Boolean name|outboundProperty init|= operator|( name|Boolean operator|) name|get argument_list|( name|MessageContext operator|. name|MESSAGE_OUTBOUND_PROPERTY argument_list|) decl_stmt|; if|if condition|( name|outboundProperty operator|== literal|null operator||| operator|! name|outboundProperty condition|) block|{ comment|//No SOAPMessage exists yet, so lets create one name|SAAJ_IN operator|. name|handleMessage argument_list|( name|getWrappedSoapMessage argument_list|() argument_list|) expr_stmt|; name|message operator|= name|getWrappedSoapMessage argument_list|() operator|. name|getContent argument_list|( name|SOAPMessage operator|. name|class argument_list|) expr_stmt|; block|} block|} return|return name|message return|; block|} specifier|public name|Object index|[] name|getHeaders parameter_list|( name|QName name|name parameter_list|, name|JAXBContext name|context parameter_list|, name|boolean name|allRoles parameter_list|) block|{ name|SOAPMessage name|msg init|= name|getMessage argument_list|() decl_stmt|; name|SOAPHeader name|header decl_stmt|; try|try block|{ name|header operator|= name|msg operator|. name|getSOAPPart argument_list|() operator|. name|getEnvelope argument_list|() operator|. name|getHeader argument_list|() expr_stmt|; if|if condition|( name|header operator|== literal|null operator||| operator|! name|header operator|. name|hasChildNodes argument_list|() condition|) block|{ return|return operator|new name|Object index|[ literal|0 index|] return|; block|} name|List argument_list|< name|Object argument_list|> name|ret init|= operator|new name|ArrayList argument_list|<> argument_list|() decl_stmt|; name|Iterator argument_list|< name|SOAPHeaderElement argument_list|> name|it init|= name|CastUtils operator|. name|cast argument_list|( name|header operator|. name|examineAllHeaderElements argument_list|() argument_list|) decl_stmt|; while|while condition|( name|it operator|. name|hasNext argument_list|() condition|) block|{ name|SOAPHeaderElement name|she init|= name|it operator|. name|next argument_list|() decl_stmt|; if|if condition|( operator|( name|allRoles operator||| name|roles operator|. name|contains argument_list|( name|she operator|. name|getActor argument_list|() argument_list|) operator|) operator|&& name|name operator|. name|equals argument_list|( name|she operator|. name|getElementQName argument_list|() argument_list|) condition|) block|{ name|ret operator|. name|add argument_list|( name|JAXBUtils operator|. name|unmarshall argument_list|( name|context argument_list|, name|she argument_list|) argument_list|) expr_stmt|; block|} block|} return|return name|ret operator|. name|toArray argument_list|( operator|new name|Object index|[ literal|0 index|] argument_list|) return|; block|} catch|catch parameter_list|( name|SOAPException decl|| name|JAXBException name|e parameter_list|) block|{ throw|throw operator|new name|WebServiceException argument_list|( name|e argument_list|) throw|; block|} block|} specifier|public name|Set argument_list|< name|String argument_list|> name|getRoles parameter_list|() block|{ return|return name|roles return|; block|} specifier|private name|SoapMessage name|getWrappedSoapMessage parameter_list|() block|{ return|return operator|( name|SoapMessage operator|) name|getWrappedMessage argument_list|() return|; block|} specifier|public name|Object name|get parameter_list|( name|Object name|key parameter_list|) block|{ name|Object name|o init|= name|super operator|. name|get argument_list|( name|key argument_list|) decl_stmt|; if|if condition|( name|MessageContext operator|. name|HTTP_RESPONSE_HEADERS operator|. name|equals argument_list|( name|key argument_list|) operator||| name|MessageContext operator|. name|HTTP_REQUEST_HEADERS operator|. name|equals argument_list|( name|key argument_list|) condition|) block|{ name|Map argument_list|< name|? argument_list|, name|? argument_list|> name|mp init|= operator|( name|Map argument_list|< name|? argument_list|, name|? argument_list|> operator|) name|o decl_stmt|; if|if condition|( name|mp operator|!= literal|null condition|) block|{ if|if condition|( name|mp operator|. name|isEmpty argument_list|() condition|) block|{ return|return literal|null return|; block|} if|if condition|( operator|! name|isRequestor argument_list|() operator|&& name|isOutbound argument_list|() operator|&& name|MessageContext operator|. name|HTTP_RESPONSE_HEADERS operator|. name|equals argument_list|( name|key argument_list|) condition|) block|{ return|return literal|null return|; block|} if|if condition|( name|isRequestor argument_list|() operator|&& operator|! name|isOutbound argument_list|() operator|&& name|MessageContext operator|. name|HTTP_REQUEST_HEADERS operator|. name|equals argument_list|( name|key argument_list|) condition|) block|{ return|return literal|null return|; block|} block|} block|} return|return name|o return|; block|} block|} end_class end_unit
3e0575cd93d547e1e4f5205084d149a7fe473529
54,471
java
Java
environments/se/core/src/main/java/org/jboss/weld/environment/se/Weld.java
1tchy/core
76413e25e8e9d15ff3ca405b642a092274fa8f9e
[ "Apache-2.0" ]
1
2019-07-08T06:11:23.000Z
2019-07-08T06:11:23.000Z
environments/se/core/src/main/java/org/jboss/weld/environment/se/Weld.java
1tchy/core
76413e25e8e9d15ff3ca405b642a092274fa8f9e
[ "Apache-2.0" ]
15
2021-12-01T02:04:12.000Z
2022-02-01T02:07:29.000Z
environments/se/core/src/main/java/org/jboss/weld/environment/se/Weld.java
1tchy/core
76413e25e8e9d15ff3ca405b642a092274fa8f9e
[ "Apache-2.0" ]
null
null
null
39.730853
168
0.660021
2,284
/* * JBoss, Home of Professional Open Source * Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual * contributors by the @authors tag. See the copyright.txt in the * distribution for a full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.weld.environment.se; import static org.jboss.weld.config.ConfigurationKey.EXECUTOR_THREAD_POOL_TYPE; import static org.jboss.weld.environment.util.URLUtils.JAR_URL_SEPARATOR; import static org.jboss.weld.environment.util.URLUtils.PROCOTOL_FILE; import static org.jboss.weld.environment.util.URLUtils.PROCOTOL_JAR; import static org.jboss.weld.environment.util.URLUtils.PROTOCOL_FILE_PART; import static org.jboss.weld.executor.ExecutorServicesFactory.ThreadPoolType.COMMON; import java.io.File; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.security.AccessController; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.UUID; import java.util.jar.JarEntry; import java.util.jar.JarFile; import jakarta.annotation.Priority; import jakarta.enterprise.context.spi.CreationalContext; import jakarta.enterprise.inject.UnsatisfiedResolutionException; import jakarta.enterprise.inject.Vetoed; import jakarta.enterprise.inject.se.SeContainerInitializer; import jakarta.enterprise.inject.spi.Bean; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.enterprise.inject.spi.Extension; import org.jboss.weld.bootstrap.WeldBootstrap; import org.jboss.weld.bootstrap.api.CDI11Bootstrap; import org.jboss.weld.bootstrap.api.Environments; import org.jboss.weld.bootstrap.api.Service; import org.jboss.weld.bootstrap.api.SingletonProvider; import org.jboss.weld.bootstrap.api.TypeDiscoveryConfiguration; import org.jboss.weld.bootstrap.api.helpers.RegistrySingletonProvider; import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive; import org.jboss.weld.bootstrap.spi.BeanDiscoveryMode; import org.jboss.weld.bootstrap.spi.BeansXml; import org.jboss.weld.bootstrap.spi.Deployment; import org.jboss.weld.bootstrap.spi.Metadata; import org.jboss.weld.bootstrap.spi.Scanning; import org.jboss.weld.bootstrap.spi.helpers.MetadataImpl; import org.jboss.weld.config.ConfigurationKey; import org.jboss.weld.configuration.spi.ExternalConfiguration; import org.jboss.weld.configuration.spi.helpers.ExternalConfigurationBuilder; import org.jboss.weld.environment.ContainerInstanceFactory; import org.jboss.weld.environment.deployment.WeldBeanDeploymentArchive; import org.jboss.weld.environment.deployment.WeldDeployment; import org.jboss.weld.environment.deployment.WeldResourceLoader; import org.jboss.weld.environment.deployment.discovery.ClassPathBeanArchiveScanner; import org.jboss.weld.environment.deployment.discovery.DiscoveryStrategy; import org.jboss.weld.environment.deployment.discovery.DiscoveryStrategyFactory; import org.jboss.weld.environment.deployment.discovery.jandex.Jandex; import org.jboss.weld.environment.logging.CommonLogger; import org.jboss.weld.environment.se.ContainerLifecycleObserver.ContainerLifecycleObserverExtension; import org.jboss.weld.environment.se.contexts.ThreadScoped; import org.jboss.weld.environment.se.logging.WeldSELogger; import org.jboss.weld.environment.util.BeanArchives; import org.jboss.weld.environment.util.DevelopmentMode; import org.jboss.weld.environment.util.Files; import org.jboss.weld.environment.util.Reflections; import org.jboss.weld.lite.extension.translator.BuildCompatibleExtensionLoader; import org.jboss.weld.lite.extension.translator.LiteExtensionTranslator; import org.jboss.weld.metadata.BeansXmlImpl; import org.jboss.weld.resources.ClassLoaderResourceLoader; import org.jboss.weld.resources.spi.ClassFileServices; import org.jboss.weld.resources.spi.ResourceLoader; import org.jboss.weld.security.GetClassLoaderAction; import org.jboss.weld.security.GetSystemPropertyAction; import org.jboss.weld.util.Preconditions; import org.jboss.weld.util.ServiceLoader; import org.jboss.weld.util.Services; import org.jboss.weld.util.collections.ImmutableList; import org.jboss.weld.util.collections.ImmutableSet; import org.jboss.weld.util.collections.Iterables; import org.jboss.weld.util.collections.Multimap; import org.jboss.weld.util.collections.WeldCollections; /** * <p> * This builder is a preferred method of booting Weld SE container. * </p> * * <p> * Typical usage looks like this: * </p> * * <pre> * WeldContainer container = new Weld().initialize(); * container.select(Foo.class).get(); * container.event().select(Bar.class).fire(new Bar()); * container.shutdown(); * </pre> * * <p> * The {@link WeldContainer} implements AutoCloseable: * </p> * * <pre> * try (WeldContainer container = new Weld().initialize()) { * container.select(Foo.class).get(); * } * </pre> * * <p> * By default, the discovery is enabled so that all beans from all discovered bean archives are considered. However, it's possible to define a "synthetic" bean * archive, or the set of bean classes and enablement respectively: * </p> * * <pre> * WeldContainer container = new Weld().beanClasses(Foo.class, Bar.class).alternatives(Bar.class).initialize()) { * </pre> * * <p> * Moreover, it's also possible to disable the discovery completely so that only the "synthetic" bean archive is considered: * </p> * * <pre> * WeldContainer container = new Weld().disableDiscovery().beanClasses(Foo.class, Bar.class).initialize()) { * </pre> * * * <p> * In the same manner, it is possible to explicitly declare interceptors, decorators, extensions and Weld-specific options (such as relaxed construction) using * the builder. * </p> * * <pre> * Weld builder = new Weld() * .disableDiscovery() * .packages(Main.class, Utils.class) * .interceptors(TransactionalInterceptor.class) * .property("org.jboss.weld.construction.relaxed", true); * WeldContainer container = builder.initialize(); * </pre> * * <p> * The builder is reusable which means that it's possible to initialize multiple Weld containers with one builder. However, note that containers must have a * unique identifier assigned when running multiple Weld instances at the same time. * </p> * * @author Peter Royle * @author Pete Muir * @author Ales Justin * @author Martin Kouba * @see WeldContainer */ @Vetoed public class Weld extends SeContainerInitializer implements ContainerInstanceFactory { /** * By default, the set of bean-defining annotations is fixed. If set to a {@link Set} of annotation classes, the set of bean-defining annotations is * augmented with the contents of the {@link Set}. * <p> * This key can be used through {@link #property(String, Object}. */ public static final String ADDITIONAL_BEAN_DEFINING_ANNOTATIONS_PROPERTY = "org.jboss.weld.se.additionalBeanDefiningAnnotations"; /** * By default, bean archive isolation is enabled. If set to false, Weld will use a "flat" deployment structure - all bean classes share the same bean * archive and all beans.xml descriptors are automatically merged into one. * <p> * This key can be also used through {@link #property(String, Object)}. */ public static final String ARCHIVE_ISOLATION_SYSTEM_PROPERTY = "org.jboss.weld.se.archive.isolation"; /** * By default, the development mode is disabled. If set to true, the development mode is activated * <p> * This key can be also used through {@link #property(String, Object)}. */ public static final String DEV_MODE_SYSTEM_PROPERTY = "org.jboss.weld.development"; /** * Standard behavior is that empty {@code beans.xml} is treated as discovery mode {@code annotated}. * This configuration property allows to change the behavior to discovery mode {@code all} which is how it used to work prior to * CDI 4.0. * <p/> * Note that this option is temporary and servers to easy migration. As such, it will be eventually removed. */ public static final String EMPTY_BEANS_XML_DISCOVERY_MODE_ALL = "org.jboss.weld.se.discovery.emptyBeansXmlModeAll"; /** * By default, Weld automatically registers shutdown hook during initialization. If set to false, the registration of a shutdown hook is skipped. * <p> * This key can be also used through {@link #property(String, Object)}. */ public static final String SHUTDOWN_HOOK_SYSTEM_PROPERTY = "org.jboss.weld.se.shutdownHook"; /** * By default, Weld SE does not support implicit bean archives without beans.xml. If set to true, Weld scans the class path entries and implicit bean * archives which don't contain a beans.xml file are also supported. * <p> * This key can be also used through {@link #property(String, Object)}. */ public static final String SCAN_CLASSPATH_ENTRIES_SYSTEM_PROPERTY = "org.jboss.weld.se.scan.classpath.entries"; /** * See also the CDI specification, section <b>15.1 Bean archive in Java SE</b>. */ public static final String JAVAX_ENTERPRISE_INJECT_SCAN_IMPLICIT = "jakarta.enterprise.inject.scan.implicit"; /** * By default, Weld is allowed to perform efficient cleanup and further optimizations after bootstrap. This feature is normally controlled by integrator * through {@link ConfigurationKey#ALLOW_OPTIMIZED_CLEANUP} but in Weld SE a client of the bootstrap API is de facto in the role of integrator. * <p> * This key can be also used through {@link #property(String, Object)}. */ public static final String ALLOW_OPTIMIZED_CLEANUP = "org.jboss.weld.bootstrap.allowOptimizedCleanup"; private static final String SYNTHETIC_LOCATION_PREFIX = "synthetic:"; static { if (!(SingletonProvider.instance() instanceof RegistrySingletonProvider)) { // make sure RegistrySingletonProvider is used (required for supporting multiple parallel Weld instances) SingletonProvider.reset(); SingletonProvider.initialize(new RegistrySingletonProvider()); } } private final Map<String, WeldContainer> initializedContainers; private String containerId; private boolean discoveryEnabled = true; protected final Set<Class<?>> beanClasses; protected final Set<Class<? extends Annotation>> extendedBeanDefiningAnnotations; protected BeanDiscoveryMode beanDiscoveryMode = BeanDiscoveryMode.ANNOTATED; private final List<Metadata<String>> selectedAlternatives; private final List<Metadata<String>> selectedAlternativeStereotypes; private final List<Metadata<String>> enabledInterceptors; private final List<Metadata<String>> enabledDecorators; private final Set<Metadata<Extension>> extensions; private final Map<String, Object> properties; private final Set<PackInfo> packages; private final List<ContainerLifecycleObserver<?>> containerLifecycleObservers; private ResourceLoader resourceLoader; protected final Map<Class<? extends Service>, Service> additionalServices; public Weld() { this(null); } /** * * @param containerId The container identifier * @see Weld#containerId(String) */ public Weld(String containerId) { this.containerId = containerId; this.initializedContainers = new HashMap<String, WeldContainer>(); this.beanClasses = new HashSet<Class<?>>(); this.selectedAlternatives = new ArrayList<Metadata<String>>(); this.selectedAlternativeStereotypes = new ArrayList<Metadata<String>>(); this.enabledInterceptors = new ArrayList<Metadata<String>>(); this.enabledDecorators = new ArrayList<Metadata<String>>(); this.extensions = new HashSet<Metadata<Extension>>(); this.properties = new HashMap<String, Object>(); this.packages = new HashSet<PackInfo>(); this.containerLifecycleObservers = new LinkedList<>(); this.resourceLoader = new WeldResourceLoader(); this.additionalServices = new HashMap<>(); this.extendedBeanDefiningAnnotations = new HashSet<>(); } /** * Containers must have a unique identifier assigned when running multiple Weld instances at the same time. * * @param containerId * @return self */ public Weld containerId(String containerId) { this.containerId = containerId; return this; } /** * * @return a container identifier * @see #containerId(String) */ public String getContainerId() { return containerId; } /** * Define the set of bean classes for the synthetic bean archive. * * @param classes * @return self */ public Weld beanClasses(Class<?>... classes) { beanClasses.clear(); addBeanClasses(classes); return this; } /** * Add a bean class to the set of bean classes for the synthetic bean archive. * * @param beanClass * @return self */ public Weld addBeanClass(Class<?> beanClass) { beanClasses.add(beanClass); return this; } @Override public Weld addBeanClasses(Class<?>... classes) { for (Class<?> aClass : classes) { addBeanClass(aClass); } return this; } /** * All classes from the packages of the specified classes will be added to the set of bean classes for the synthetic bean archive. * * <p> * Note that the scanning possibilities are limited. Therefore, only directories and jar files from the filesystem are supported. * </p> * * <p> * Scanning may also have negative impact on bootstrap performance. * </p> * * @param packageClasses classes whose packages are to be added to synthetic bean archive * @return self */ public Weld packages(Class<?>... packageClasses) { packages.clear(); addPackages(false, packageClasses); return this; } /** * Packages of the specified classes will be scanned and found classes will be added to the set of bean classes for the synthetic bean archive. * * @param scanRecursively * @param packageClasses * @return self */ public Weld addPackages(boolean scanRecursively, Class<?>... packageClasses) { for (Class<?> packageClass : packageClasses) { addPackage(scanRecursively, packageClass); } return this; } @Override public Weld addPackages(Class<?>... packageClasses) { addPackages(false, packageClasses); return this; } @Override public Weld addPackages(Package... packages) { addPackages(false, packages); return this; } @Override public Weld addPackages(boolean scanRecursively, Package... packages) { for (Package pack : packages) { this.packages.add(new PackInfo(pack, scanRecursively)); } return this; } /** * A package of the specified class will be scanned and found classes will be added to the set of bean classes for the synthetic bean archive. * * @param scanRecursively * @param packageClass * @return self */ public Weld addPackage(boolean scanRecursively, Class<?> packageClass) { packages.add(new PackInfo(packageClass, scanRecursively)); return this; } /** * Define the set of extensions. * * @param extensions * @return self */ public Weld extensions(Extension... extensions) { this.extensions.clear(); for (Extension extension : extensions) { addExtension(extension); } return this; } /** * Add an extension to the set of extensions. * * @param extension an extension */ public Weld addExtension(Extension extension) { extensions.add(new MetadataImpl<Extension>(extension, SYNTHETIC_LOCATION_PREFIX + extension.getClass().getName())); return this; } @Override public Weld addExtensions(Extension... extensions) { for (Extension extension : extensions) { addExtension(extension); } return this; } @SuppressWarnings("unchecked") @Override public Weld addExtensions(Class<? extends Extension>... extensionClasses) { for (Class<? extends Extension> extensionClass : extensionClasses) { try { Extension extension = SecurityActions.newInstance(extensionClass); addExtension(extension); } catch (Exception ex) { CommonLogger.LOG.unableToInstantiate(extensionClass, new Object[] {}, ex); } } return this; } /** * Add a synthetic container lifecycle event observer. * * @param observer * @return self * @see ContainerLifecycleObserver */ public Weld addContainerLifecycleObserver(ContainerLifecycleObserver<?> observer) { containerLifecycleObservers.add(observer); return this; } /** * Enable interceptors for the synthetic bean archive, all previous values are removed. * <p> * This method does not add any class to the set of bean classes for the synthetic bean archive. It's purpose is solely to compensate the absence of the * <code>beans.xml</code> descriptor. * * @param interceptorClasses * @return self */ public Weld interceptors(Class<?>... interceptorClasses) { enabledInterceptors.clear(); enableInterceptors(interceptorClasses); return this; } /** * Add an interceptor class to the list of enabled interceptors for the synthetic bean archive. * <p> * This method does not add any class to the set of bean classes for the synthetic bean archive. It's purpose is solely to compensate the absence of the * <code>beans.xml</code> descriptor. * * @param interceptorClass * @return self */ public Weld addInterceptor(Class<?> interceptorClass) { enabledInterceptors.add(syntheticMetadata(interceptorClass)); return this; } @Override public Weld enableInterceptors(Class<?>... interceptorClasses) { for (Class<?> interceptorClass : interceptorClasses) { addInterceptor(interceptorClass); } return this; } /** * Enable decorators for the synthetic bean archive, all previous values are removed. * <p> * This method does not add any class to the set of bean classes for the synthetic bean archive. It's purpose is solely to compensate the absence of the * <code>beans.xml</code> descriptor. * * @param decoratorClasses * @return self */ public Weld decorators(Class<?>... decoratorClasses) { enabledDecorators.clear(); enableDecorators(decoratorClasses); return this; } /** * Add a decorator class to the list of enabled decorators for the synthetic bean archive. * <p> * This method does not add any class to the set of bean classes for the synthetic bean archive. It's purpose is solely to compensate the absence of the * <code>beans.xml</code> descriptor. * * @param decoratorClass * @return self */ public Weld addDecorator(Class<?> decoratorClass) { enabledDecorators.add(syntheticMetadata(decoratorClass)); return this; } @Override public Weld enableDecorators(Class<?>... decoratorClasses) { for (Class<?> decoratorClass : decoratorClasses) { addDecorator(decoratorClass); } return this; } /** * Select alternatives for the synthetic bean archive, all previous values are removed. * <p> * This method does not add any class to the set of bean classes for the synthetic bean archive. It's purpose is solely to compensate the absence of the * <code>beans.xml</code> descriptor. * * @param alternativeClasses * @return self */ public Weld alternatives(Class<?>... alternativeClasses) { selectedAlternatives.clear(); selectAlternatives(alternativeClasses); return this; } /** * Add an alternative class to the list of selected alternatives for a synthetic bean archive. * <p> * This method does not add any class to the set of bean classes for the synthetic bean archive. It's purpose is solely to compensate the absence of the * <code>beans.xml</code> descriptor. * * @param alternativeClass * @return self */ public Weld addAlternative(Class<?> alternativeClass) { selectedAlternatives.add(syntheticMetadata(alternativeClass)); return this; } @Override public Weld selectAlternatives(Class<?>... alternativeClasses) { for (Class<?> alternativeClass : alternativeClasses) { addAlternative(alternativeClass); } return this; } /** * Select alternative stereotypes for the synthetic bean archive, all previous values are removed. * <p> * This method does not add any class to the set of bean classes for the synthetic bean archive. It's purpose is solely to compensate the absence of the * <code>beans.xml</code> descriptor. * * @param alternativeStereotypeClasses * @return self */ @SafeVarargs public final Weld alternativeStereotypes(Class<? extends Annotation>... alternativeStereotypeClasses) { selectedAlternativeStereotypes.clear(); selectAlternativeStereotypes(alternativeStereotypeClasses); return this; } @SuppressWarnings("unchecked") @Override public Weld selectAlternativeStereotypes(Class<? extends Annotation>... alternativeStereotypeClasses) { for (Class<? extends Annotation> alternativeStereotypeClass : alternativeStereotypeClasses) { addAlternativeStereotype(alternativeStereotypeClass); } return this; } /** * Add an alternative stereotype class to the list of selected alternative stereotypes for a synthetic bean archive. * <p> * This method does not add any class to the set of bean classes for the synthetic bean archive. It's purpose is solely to compensate the absence of the * <code>beans.xml</code> descriptor. * * @param alternativeStereotypeClass * @return self */ public Weld addAlternativeStereotype(Class<? extends Annotation> alternativeStereotypeClass) { selectedAlternativeStereotypes.add(syntheticMetadata(alternativeStereotypeClass)); return this; } /** * Set the configuration property. * * @param key * @param value * @return self * @see #ARCHIVE_ISOLATION_SYSTEM_PROPERTY * @see #SHUTDOWN_HOOK_SYSTEM_PROPERTY * @see #DEV_MODE_SYSTEM_PROPERTY * @see ConfigurationKey */ public Weld property(String key, Object value) { properties.put(key, value); return this; } /** * Set all the configuration properties. * * @param properties * @return self */ public Weld properties(Map<String, Object> properties) { this.properties.putAll(properties); return this; } @Override public Weld addProperty(String key, Object value) { property(key, value); return this; } @Override public Weld setProperties(Map<String, Object> propertiesMap) { properties.clear(); properties.putAll(propertiesMap); return this; } /** * Register per-deployment services which are shared across the entire application. * <p> * Weld uses services to communicate with its environment, e.g. {@link org.jboss.weld.manager.api.ExecutorServices} or * {@link org.jboss.weld.transaction.spi.TransactionServices}. * </p> * <p> * Service implementation may specify their priority using {@link Priority}. Services with higher priority have precedence. Services that do not specify * priority have the default priority of 4500. * </p> * * @param services * @return self * @see Service */ public Weld addServices(Service... services) { for (Service service : services) { for (Class<? extends Service> serviceInterface : Services.identifyServiceInterfaces(service.getClass(), new HashSet<>())) { additionalServices.put(serviceInterface, service); } } return this; } /** * Sets the bean discovery mode for synthetic bean archive. Default mode is ANNOTATED. * @param mode bean discovery mode in a form of an enum from {@link org.jboss.weld.bootstrap.spi.BeanDiscoveryMode}. Accepted values are ALL, ANNOTATED * * @return self * @throws IllegalArgumentException if BeanDiscoveryMode.NONE is passed as an argument */ public Weld setBeanDiscoveryMode(BeanDiscoveryMode mode) { // NONE makes no sense as an option if (mode.equals(BeanDiscoveryMode.NONE)) { throw WeldSELogger.LOG.beanArchiveWithModeNone(containerId); } beanDiscoveryMode = mode; return this; } /** * Reset the synthetic bean archive (bean classes and enablement), explicitly added extensions and services. * * @return self */ public Weld reset() { beanClasses.clear(); packages.clear(); selectedAlternatives.clear(); selectedAlternativeStereotypes.clear(); enabledInterceptors.clear(); enabledDecorators.clear(); extensions.clear(); containerLifecycleObservers.clear(); additionalServices.clear(); return this; } /** * Reset all the state, except for initialized containers. * * @return self * @see Weld#reset() */ public Weld resetAll() { reset(); properties.clear(); enableDiscovery(); containerId(null); return this; } /** * * @return self * @see #disableDiscovery() */ public Weld enableDiscovery() { this.discoveryEnabled = true; return this; } /** * By default, the discovery is enabled. However, it's possible to disable the discovery completely so that only the "synthetic" bean archive is considered. * * @return self */ public Weld disableDiscovery() { this.discoveryEnabled = false; return this; } /** * * @return <code>true</code> if the discovery is enabled, <code>false</code> otherwise * @see #disableDiscovery() */ public boolean isDiscoveryEnabled() { return discoveryEnabled; } /** * Bootstraps a new Weld SE container with the current container id (generated value if not set through {@link #containerId(String)}). * <p/> * The container must be shut down properly when an application is stopped. Applications are encouraged to use the try-with-resources statement or invoke * {@link WeldContainer#shutdown()} explicitly. * <p/> * However, a shutdown hook is also registered during initialization so that all running containers are shut down automatically when a program exits or VM * is terminated. This means that it's not necessary to implement the shutdown logic in a class where a main method is used to start the container. * * @return the Weld container * @see #enableDiscovery() * @see WeldContainer#shutdown() */ public WeldContainer initialize() { // If also building a synthetic bean archive or the implicit scan is enabled, the check for beans.xml is not necessary if (!isSyntheticBeanArchiveRequired() && !isImplicitScanEnabled() && resourceLoader.getResource(WeldDeployment.BEANS_XML) == null) { throw CommonLogger.LOG.missingBeansXml(); } final WeldBootstrap bootstrap = new WeldBootstrap(); // load possible additional BDA parseAdditionalBeanDefiningAnnotations(); final Deployment deployment = createDeployment(resourceLoader, bootstrap); final ExternalConfigurationBuilder configurationBuilder = new ExternalConfigurationBuilder() // weld-se uses CommonForkJoinPoolExecutorServices by default .add(EXECUTOR_THREAD_POOL_TYPE.get(), COMMON.toString()) // weld-se uses relaxed construction by default .add(ConfigurationKey.RELAXED_CONSTRUCTION.get(), true) // allow optimized cleanup by default .add(ConfigurationKey.ALLOW_OPTIMIZED_CLEANUP.get(), isEnabled(ALLOW_OPTIMIZED_CLEANUP, true)); for (Entry<String, Object> property : properties.entrySet()) { String key = property.getKey(); if (SHUTDOWN_HOOK_SYSTEM_PROPERTY.equals(key) || ARCHIVE_ISOLATION_SYSTEM_PROPERTY.equals(key) || DEV_MODE_SYSTEM_PROPERTY.equals(key) || SCAN_CLASSPATH_ENTRIES_SYSTEM_PROPERTY.equals(key) || JAVAX_ENTERPRISE_INJECT_SCAN_IMPLICIT.equals(key) || ADDITIONAL_BEAN_DEFINING_ANNOTATIONS_PROPERTY.equals(key)) { continue; } configurationBuilder.add(key, property.getValue()); } deployment.getServices().add(ExternalConfiguration.class, configurationBuilder.build()); final String containerId = this.containerId != null ? this.containerId : UUID.randomUUID().toString(); bootstrap.startContainer(containerId, Environments.SE, deployment); final WeldContainer weldContainer = WeldContainer.startInitialization(containerId, deployment, bootstrap); try { bootstrap.startInitialization(); bootstrap.deployBeans(); bootstrap.validateBeans(); bootstrap.endInitialization(); WeldContainer.endInitialization(weldContainer, isEnabled(SHUTDOWN_HOOK_SYSTEM_PROPERTY, true)); initializedContainers.put(containerId, weldContainer); } catch (Throwable e) { // Discard the container if a bootstrap problem occurs, e.g. validation error WeldContainer.discard(weldContainer.getId()); throw e; } return weldContainer; } /** * Shuts down all the containers initialized by this builder. */ public void shutdown() { if (!initializedContainers.isEmpty()) { for (WeldContainer container : initializedContainers.values()) { container.shutdown(); } } } /** * Set a {@link ClassLoader}. The given {@link ClassLoader} will be scanned automatically for bean archives if scanning is enabled. * * @param classLoader * @return self */ public Weld setClassLoader(ClassLoader classLoader) { Preconditions.checkNotNull(classLoader); resourceLoader = new ClassLoaderResourceLoader(classLoader); return this; } /** * Set a {@link ResourceLoader} used to scan the application for bean archives. If you only want to use a specific {@link ClassLoader} for scanning, use * {@link #setClassLoader(ClassLoader)} instead. * * @param resourceLoader * @return self * @see #isDiscoveryEnabled() */ public Weld setResourceLoader(ResourceLoader resourceLoader) { Preconditions.checkNotNull(resourceLoader); this.resourceLoader = resourceLoader; return this; } /** * Disable bean archive isolation, i.e. use a "flat" deployment structure. * * @return self * @see #ARCHIVE_ISOLATION_SYSTEM_PROPERTY */ public Weld disableIsolation() { return property(ARCHIVE_ISOLATION_SYSTEM_PROPERTY, false); } /** * Skip shutdown hook registration. * * @return self * @see #SHUTDOWN_HOOK_SYSTEM_PROPERTY */ public Weld skipShutdownHook() { return property(SHUTDOWN_HOOK_SYSTEM_PROPERTY, false); } /** * Scans the class path entries - implicit bean archives which don't contain a beans.xml file are supported. * * @return self * @see #SCAN_CLASSPATH_ENTRIES_SYSTEM_PROPERTY */ public Weld scanClasspathEntries() { return property(SCAN_CLASSPATH_ENTRIES_SYSTEM_PROPERTY, true); } /** * Enable the development mode. * * @return self * @see #DEV_MODE_SYSTEM_PROPERTY */ public Weld enableDevMode() { return property(DEV_MODE_SYSTEM_PROPERTY, true); } /** * Registers annotations which will be considered as bean defining annotations. * * NOTE - If used along with {@code <trim/>} bean archives and/or with Weld configuration key * {@code org.jboss.weld.bootstrap.vetoTypesWithoutBeanDefiningAnnotation}, these annotations will be ignored. * * @param annotations annotations which will be considered as Bean Defining Annotations. * @return self */ public Weld addBeanDefiningAnnotations(Class<? extends Annotation>... annotations) { for (Class<? extends Annotation> annotation : annotations) { this.extendedBeanDefiningAnnotations.add(annotation); } return this; } /** * <p> * Extensions to Weld SE can subclass and override this method to customize the deployment before weld boots up. For example, to add a custom * ResourceLoader, you would subclass Weld like so: * </p> * * <pre> * public class MyWeld extends Weld { * protected Deployment createDeployment(ResourceLoader resourceLoader, CDI11Bootstrap bootstrap) { * return super.createDeployment(new MyResourceLoader(), bootstrap); * } * } * </pre> * * <p> * This could then be used as normal: * </p> * * <pre> * WeldContainer container = new MyWeld().initialize(); * </pre> * * @param resourceLoader * @param bootstrap */ protected Deployment createDeployment(ResourceLoader resourceLoader, CDI11Bootstrap bootstrap) { final BeanDiscoveryMode emptyBeansXmlDiscoveryMode = isEnabled(EMPTY_BEANS_XML_DISCOVERY_MODE_ALL, false) ? BeanDiscoveryMode.ALL : BeanDiscoveryMode.ANNOTATED; final Iterable<Metadata<Extension>> extensions = getExtensions(); final TypeDiscoveryConfiguration typeDiscoveryConfiguration = bootstrap.startExtensions(extensions); final Deployment deployment; final Set<WeldBeanDeploymentArchive> beanDeploymentArchives = new HashSet<WeldBeanDeploymentArchive>(); final Map<Class<? extends Service>, Service> additionalServices = new HashMap<>(this.additionalServices); final Set<Class<? extends Annotation>> beanDefiningAnnotations = ImmutableSet.<Class<? extends Annotation>> builder() .addAll(typeDiscoveryConfiguration.getKnownBeanDefiningAnnotations()) // Add ThreadScoped manually as Weld SE doesn't support implicit bean archives without beans.xml .add(ThreadScoped.class) // Add all custom bean defining annotations user registered via Weld.addBeanDefiningAnnotations() .addAll(extendedBeanDefiningAnnotations) .build(); if (discoveryEnabled) { DiscoveryStrategy strategy = DiscoveryStrategyFactory.create(resourceLoader, bootstrap, beanDefiningAnnotations, isEnabled(Jandex.DISABLE_JANDEX_DISCOVERY_STRATEGY, false), emptyBeansXmlDiscoveryMode); if (isImplicitScanEnabled()) { strategy.setScanner(new ClassPathBeanArchiveScanner(bootstrap, emptyBeansXmlDiscoveryMode)); } beanDeploymentArchives.addAll(strategy.performDiscovery()); ClassFileServices classFileServices = strategy.getClassFileServices(); if (classFileServices != null) { additionalServices.put(ClassFileServices.class, classFileServices); } } if (isSyntheticBeanArchiveRequired()) { ImmutableSet.Builder<String> beanClassesBuilder = ImmutableSet.builder(); beanClassesBuilder.addAll(scanPackages()); Set<String> setOfAllBeanClasses = beanClassesBuilder.build(); // the creation process differs based on bean discovery mode if (BeanDiscoveryMode.ANNOTATED.equals(beanDiscoveryMode)) { // Annotated bean discovery mode, filter classes ImmutableSet.Builder<String> filteredSetbuilder = ImmutableSet.builder(); for (String className : setOfAllBeanClasses) { Class<?> clazz = Reflections.loadClass(resourceLoader, className); if (clazz != null && Reflections.hasBeanDefiningAnnotation(clazz, beanDefiningAnnotations)) { filteredSetbuilder.add(className); } } setOfAllBeanClasses = filteredSetbuilder.build(); } WeldBeanDeploymentArchive syntheticBeanArchive = new WeldBeanDeploymentArchive(WeldDeployment.SYNTHETIC_BDA_ID, setOfAllBeanClasses, null, buildSyntheticBeansXml(), Collections.emptySet(), ImmutableSet.copyOf(beanClasses)); beanDeploymentArchives.add(syntheticBeanArchive); } if (beanDeploymentArchives.isEmpty() && this.containerLifecycleObservers.isEmpty() && this.extensions.isEmpty()) { throw WeldSELogger.LOG.weldContainerCannotBeInitializedNoBeanArchivesFound(); } Multimap<String, BeanDeploymentArchive> problems = BeanArchives.findBeanClassesDeployedInMultipleBeanArchives(beanDeploymentArchives); if (!problems.isEmpty()) { // Right now, we only log a warning for each bean class deployed in multiple bean archives for (Entry<String, Collection<BeanDeploymentArchive>> entry : problems.entrySet()) { WeldSELogger.LOG.beanClassDeployedInMultipleBeanArchives(entry.getKey(), WeldCollections.toMultiRowString(entry.getValue())); } } if (isEnabled(ARCHIVE_ISOLATION_SYSTEM_PROPERTY, true)) { deployment = new WeldDeployment(resourceLoader, bootstrap, beanDeploymentArchives, extensions); CommonLogger.LOG.archiveIsolationEnabled(); } else { Set<WeldBeanDeploymentArchive> flatDeployment = new HashSet<WeldBeanDeploymentArchive>(); flatDeployment.add(WeldBeanDeploymentArchive.merge(bootstrap, beanDeploymentArchives)); deployment = new WeldDeployment(resourceLoader, bootstrap, flatDeployment, extensions); CommonLogger.LOG.archiveIsolationDisabled(); } // Register additional services if a service with higher priority not present for (Entry<Class<? extends Service>, Service> entry : additionalServices.entrySet()) { Services.put(deployment.getServices(), entry.getKey(), entry.getValue()); } return deployment; } /** * Utility method allowing managed instances of beans to provide entry points for non-managed beans (such as {@link WeldContainer}). Should only called once * Weld has finished booting. * * @param manager the BeanManager to use to access the managed instance * @param type the type of the Bean * @param bindings the bean's qualifiers * @return a managed instance of the bean * @throws IllegalArgumentException if the given type represents a type variable * @throws IllegalArgumentException if two instances of the same qualifier type are given * @throws IllegalArgumentException if an instance of an annotation that is not a qualifier type is given * @throws UnsatisfiedResolutionException if no beans can be resolved * @throws AmbiguousResolutionException if the ambiguous dependency resolution rules * fail * @throws IllegalArgumentException if the given type is not a bean type of the given bean */ protected <T> T getInstanceByType(BeanManager manager, Class<T> type, Annotation... bindings) { final Bean<?> bean = manager.resolve(manager.getBeans(type, bindings)); if (bean == null) { throw CommonLogger.LOG.unableToResolveBean(type, Arrays.asList(bindings)); } CreationalContext<?> cc = manager.createCreationalContext(bean); return type.cast(manager.getReference(bean, type, cc)); } protected boolean isImplicitScanEnabled() { return isEnabled(SCAN_CLASSPATH_ENTRIES_SYSTEM_PROPERTY, false) || isEnabled(JAVAX_ENTERPRISE_INJECT_SCAN_IMPLICIT, false); } protected boolean isSyntheticBeanArchiveRequired() { return !beanClasses.isEmpty() || !packages.isEmpty(); } protected Iterable<Metadata<Extension>> getExtensions() { Set<Metadata<Extension>> result = new HashSet<Metadata<Extension>>(); if (discoveryEnabled) { Iterables.addAll(result, loadExtensions(resourceLoader)); } if (!extensions.isEmpty()) { result.addAll(extensions); } // Ensure that WeldSEBeanRegistrant is present WeldSEBeanRegistrant weldSEBeanRegistrant = null; for (Metadata<Extension> metadata : result) { if (metadata.getValue().getClass().getName().equals(WeldSEBeanRegistrant.class.getName())) { weldSEBeanRegistrant = (WeldSEBeanRegistrant) metadata.getValue(); break; } } if (weldSEBeanRegistrant == null) { try { weldSEBeanRegistrant = SecurityActions.newInstance(WeldSEBeanRegistrant.class); result.add(new MetadataImpl<Extension>(weldSEBeanRegistrant, SYNTHETIC_LOCATION_PREFIX + WeldSEBeanRegistrant.class.getName())); } catch (Exception e) { throw new RuntimeException(e); } } if (isEnabled(DEV_MODE_SYSTEM_PROPERTY, false)) { // The development mode is enabled - register the Probe extension result.add(new MetadataImpl<Extension>(DevelopmentMode.getProbeExtension(resourceLoader), "N/A")); } // Register org.jboss.weld.lite.extension.translator.LiteExtensionTranslator in order to be able to execute build compatible extensions // Note that we only register this if we detect any BuildCompatibleExtension implementations if (!BuildCompatibleExtensionLoader.getBuildCompatibleExtensions().isEmpty()) { try { result.add(new MetadataImpl<Extension>(SecurityActions.newInstance(LiteExtensionTranslator.class), SYNTHETIC_LOCATION_PREFIX + LiteExtensionTranslator.class.getName())); } catch (Exception e) { throw new RuntimeException(e); } } if (!containerLifecycleObservers.isEmpty()) { result.add(new MetadataImpl<Extension>(new ContainerLifecycleObserverExtension(containerLifecycleObservers), SYNTHETIC_LOCATION_PREFIX + ContainerLifecycleObserver.class.getName())); } return result; } private Iterable<Metadata<Extension>> loadExtensions(ResourceLoader resourceLoader) { return ServiceLoader.load(Extension.class, resourceLoader); } protected BeansXml buildSyntheticBeansXml() { return new BeansXmlImpl(ImmutableList.copyOf(selectedAlternatives), ImmutableList.copyOf(selectedAlternativeStereotypes), ImmutableList.copyOf(enabledDecorators), ImmutableList.copyOf(enabledInterceptors), Scanning.EMPTY_SCANNING, null, beanDiscoveryMode, null, false); } private MetadataImpl<String> syntheticMetadata(Class<?> clazz) { return new MetadataImpl<String>(clazz.getName(), SYNTHETIC_LOCATION_PREFIX + clazz.getName()); } protected Set<String> scanPackages() { if (packages.isEmpty()) { return Collections.emptySet(); } Set<String> foundClasses = new HashSet<String>(); for (PackInfo packInfo : packages) { String packName = packInfo.getPackName(); URL resourceUrl = packInfo.getResourceUrl(resourceLoader); if (resourceUrl != null) { WeldSELogger.LOG.scanningPackage(packName, resourceUrl); try { URI resourceUri = resourceUrl.toURI(); if (PROCOTOL_FILE.equals(resourceUrl.getProtocol())) { File file = new File(resourceUri); handleDir(file.isDirectory() ? file : file.getParentFile(), packInfo.isScanRecursively(), packName, foundClasses); } else if (PROCOTOL_JAR.equals(resourceUrl.getProtocol())) { handleJar(resourceUri, packInfo.isScanRecursively(), packName, foundClasses); } else { WeldSELogger.LOG.resourceUrlProtocolNotSupported(resourceUrl); } } catch (URISyntaxException e) { CommonLogger.LOG.couldNotReadResource(resourceUrl, e); } } else { WeldSELogger.LOG.packageNotFound(packName); } } return foundClasses; } private void handleDir(File packDir, boolean scanRecursively, String packName, Set<String> foundClasses) { if (packDir != null && packDir.exists() && packDir.canRead()) { for (File file : packDir.listFiles()) { if (file.isFile()) { if (file.canRead() && Files.isClass(file.getName())) { foundClasses.add(Files.filenameToClassname(packName + "." + file.getName())); } } if (file.isDirectory() && scanRecursively) { handleDir(file, scanRecursively, packName + "." + file.getName(), foundClasses); } } } } private void handleJar(URI resourceUri, boolean scanRecursively, String packName, Set<String> foundClasses) { // Currently we only support jar:file if (resourceUri.getSchemeSpecificPart().startsWith(PROCOTOL_FILE)) { // Get the JAR file path, e.g. "jar:file:/home/duke/duke.jar!/com/foo/Bar" becomes "/home/duke/duke.jar" String path = resourceUri.getSchemeSpecificPart().substring(PROTOCOL_FILE_PART.length()); if (path.lastIndexOf(JAR_URL_SEPARATOR) > 0) { path = path.substring(0, path.lastIndexOf(JAR_URL_SEPARATOR)); } JarFile jar = null; String packNamePath = packName.replace('.', '/'); int expectedPartsLength = splitBySlash(packNamePath).length + 1; try { jar = new JarFile(new File(path)); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (!entry.getName().endsWith(Files.CLASS_FILE_EXTENSION)) { continue; } if (entry.getName().startsWith(packNamePath + '/')) { if (scanRecursively) { foundClasses.add(Files.filenameToClassname(entry.getName())); } else { String[] parts = splitBySlash(entry.getName()); if (parts.length == expectedPartsLength) { foundClasses.add(Files.filenameToClassname(entry.getName())); } } } } } catch (IOException e) { CommonLogger.LOG.couldNotReadResource(resourceUri, e); } finally { if (jar != null) { try { jar.close(); } catch (IOException ignored) { } } } } } private String[] splitBySlash(String value) { return value.split("/"); } protected boolean isEnabled(String key, boolean defaultValue) { Object value = properties.get(key); if (value != null) { return Boolean.TRUE.equals(value); } String system = AccessController.doPrivileged(new GetSystemPropertyAction(key)); if (system != null) { return Boolean.valueOf(system); } return defaultValue; } protected Object getPropertyValue(String key, Object defaultValue) { Object value = properties.get(key); if (value != null) { return value; } return defaultValue; } /** * Parses additional bean defining annotations from either system properties, or SE container properties. */ private void parseAdditionalBeanDefiningAnnotations() { // parse additional bean defining annotations from SE container properties if (properties.containsKey(ADDITIONAL_BEAN_DEFINING_ANNOTATIONS_PROPERTY)) { Object valueObj = properties.get(ADDITIONAL_BEAN_DEFINING_ANNOTATIONS_PROPERTY); if (valueObj instanceof Collection) { for (Object element : ((Collection<?>) valueObj)) { if (element instanceof Class<?> && Annotation.class.isAssignableFrom((Class<?>) element)) { extendedBeanDefiningAnnotations.add((Class<? extends Annotation>) element); } else { // one of the values is not an annotation, log warning WeldSELogger.LOG.unexpectedItemsInValueCollection(element.getClass()); } } } else { // value is not a collection, throw IAE throw WeldSELogger.LOG.unexpectedValueForAdditionalBeanDefiningAnnotations(valueObj.getClass()); } } // parse from system properties String stringValue = AccessController.doPrivileged(new GetSystemPropertyAction(ADDITIONAL_BEAN_DEFINING_ANNOTATIONS_PROPERTY)); if (stringValue != null) { for (String className : stringValue.split(",")) { if (!className.isEmpty()) { try { Class<?> loadedClass = Class.forName(className); if (loadedClass.isAnnotation()) { extendedBeanDefiningAnnotations.add((Class<? extends Annotation>) loadedClass); } else { // one of the values is not an annotation, log warning WeldSELogger.LOG.unexpectedItemsInValueCollection(loadedClass); } } catch (LinkageError | ClassNotFoundException e) { throw WeldSELogger.LOG.failedToLoadClass(className, e.toString()); } } } } } private static class PackInfo { private final String packName; private final String packClassName; private final boolean scanRecursively; private final WeakReference<ClassLoader> classLoaderRef; PackInfo(Class<?> packClass, boolean recursiveScan) { this.packName = packClass.getPackage().getName(); this.packClassName = packClass.getName(); this.scanRecursively = recursiveScan; this.classLoaderRef = new WeakReference<ClassLoader>(AccessController.doPrivileged(new GetClassLoaderAction(packClass))); } PackInfo(Package pack, boolean recursiveScan) { this.packName = pack.getName(); this.scanRecursively = recursiveScan; this.packClassName = null; this.classLoaderRef = null; } public URL getResourceUrl(ResourceLoader resourceLoader) { if (classLoaderRef != null) { return classLoaderRef.get().getResource(this.getPackClassName().replace('.', '/') + Files.CLASS_FILE_EXTENSION); } else { return resourceLoader.getResource(getPackName().replace('.', '/')); } } public String getPackName() { return packName; } public String getPackClassName() { return packClassName; } public boolean isScanRecursively() { return scanRecursively; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((packClassName == null) ? 0 : packClassName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } PackInfo other = (PackInfo) obj; if (packName == null) { if (other.packName != null) { return false; } } else if (!packName.equals(other.packName)) { return false; } return true; } } }
3e0575da2b3308866076bb41edbfd15d84378799
8,358
java
Java
src/test/java/serializer/TypeCheckerTest.java
webetes/Serializer
f54eff9183c040dbce87313dd0d52d9b8462365b
[ "MIT" ]
5
2018-12-17T08:14:29.000Z
2019-10-01T13:49:27.000Z
src/test/java/serializer/TypeCheckerTest.java
webetes/Serializer
f54eff9183c040dbce87313dd0d52d9b8462365b
[ "MIT" ]
67
2018-12-13T14:19:39.000Z
2022-03-29T04:00:30.000Z
src/test/java/serializer/TypeCheckerTest.java
webetes/Serializer
f54eff9183c040dbce87313dd0d52d9b8462365b
[ "MIT" ]
2
2019-04-07T07:20:02.000Z
2019-06-18T11:36:09.000Z
31.900763
120
0.682939
2,285
package serializer; import es.webbeta.serializer.*; import es.webbeta.serializer.base.Cache; import es.webbeta.serializer.base.ConfigurationProvider; import es.webbeta.serializer.base.Environment; import es.webbeta.serializer.base.SerializerMetadataProvider; import org.junit.Before; import org.junit.Test; import util.serializer.BeanWithWrongDefinedMetadata; import util.serializer.BeanWithoutMetadata; import util.serializer.Foo; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.file.Paths; import java.security.SecureRandom; import java.util.*; import static org.fest.assertions.Assertions.assertThat; public class TypeCheckerTest { private static SerializerMetadataProvider metadataProvider; enum Sample { READ, WRITE } @Before public void setUp() throws Exception { Map<String, String> config = new HashMap<>(); config.put(ConfigurationManager.METADATA_DIR_KEY, "src/test/resources"); ConfigurationProvider configurationProvider = new ConfigurationProvider() { @Override public boolean getBoolean(String key, boolean defaultValue) { return false; } @Override public String getString(String key, String defaultValue) { return config.get(key) == null ? defaultValue : config.get(key); } }; Environment environment = () -> false; FileMetadataAccessor fileMetadataAccessor = new FileMetadataAccessor(); fileMetadataAccessor.setMetadataPath(Paths.get(config.get(ConfigurationManager.METADATA_DIR_KEY))); Cache cache = new Cache() { @Override public String get(String key) { return null; } @Override public void set(String key, String content) { } @Override public void remove(String key) { } }; ConfigurationManager configurationManager = new ConfigurationManager(configurationProvider, environment, cache); metadataProvider = configurationManager.newMetadataProvider(); } @Test public void test_it_detects_byte_as_numeric() { TypeChecker typeChecker = new TypeChecker(metadataProvider); Byte type = 1; byte typePrimitive = 1; assertThat(typeChecker.isByte(type)).isTrue(); assertThat(typeChecker.isNumeric(type)).isTrue(); assertThat(typeChecker.isByte(typePrimitive)).isTrue(); assertThat(typeChecker.isNumeric(typePrimitive)).isTrue(); } @Test public void test_it_detects_short_as_numeric() { TypeChecker typeChecker = new TypeChecker(metadataProvider); Short type = 1; short typePrimitive = 1; assertThat(typeChecker.isShort(type)).isTrue(); assertThat(typeChecker.isNumeric(type)).isTrue(); assertThat(typeChecker.isShort(typePrimitive)).isTrue(); assertThat(typeChecker.isNumeric(typePrimitive)).isTrue(); } @Test public void test_it_detects_integer_as_numeric() { TypeChecker typeChecker = new TypeChecker(metadataProvider); Integer type = 1; int typePrimitive = 1; assertThat(typeChecker.isInteger(type)).isTrue(); assertThat(typeChecker.isNumeric(type)).isTrue(); assertThat(typeChecker.isInteger(typePrimitive)).isTrue(); assertThat(typeChecker.isNumeric(typePrimitive)).isTrue(); } @Test public void test_it_detects_biginteger_as_numeric() { TypeChecker typeChecker = new TypeChecker(metadataProvider); SecureRandom random = new SecureRandom(); BigInteger type = new BigInteger(130, random); assertThat(typeChecker.isBigInteger(type)).isTrue(); assertThat(typeChecker.isNumeric(type)).isTrue(); } @Test public void test_it_detects_long_as_numeric() { TypeChecker typeChecker = new TypeChecker(metadataProvider); Long type = 1L; long typePrimitive = 1L; assertThat(typeChecker.isLong(type)).isTrue(); assertThat(typeChecker.isNumeric(type)).isTrue(); assertThat(typeChecker.isLong(typePrimitive)).isTrue(); assertThat(typeChecker.isNumeric(typePrimitive)).isTrue(); } @Test public void test_it_detects_float_as_numeric() { TypeChecker typeChecker = new TypeChecker(metadataProvider); Float type = 1F; float typePrimitive = 1F; assertThat(typeChecker.isFloat(type)).isTrue(); assertThat(typeChecker.isNumeric(type)).isTrue(); assertThat(typeChecker.isFloat(typePrimitive)).isTrue(); assertThat(typeChecker.isNumeric(typePrimitive)).isTrue(); } @Test public void test_it_detects_double_as_numeric() { TypeChecker typeChecker = new TypeChecker(metadataProvider); Double type = 1.0; double typePrimitive = 1.0; assertThat(typeChecker.isDouble(type)).isTrue(); assertThat(typeChecker.isNumeric(type)).isTrue(); assertThat(typeChecker.isDouble(typePrimitive)).isTrue(); assertThat(typeChecker.isNumeric(typePrimitive)).isTrue(); } @Test public void test_it_detects_bigdecimal_as_numeric() { TypeChecker typeChecker = new TypeChecker(metadataProvider); BigDecimal type = new BigDecimal(1.0); assertThat(typeChecker.isBigDecimal(type)).isTrue(); assertThat(typeChecker.isNumeric(type)).isTrue(); } @Test public void test_it_detects_string() { TypeChecker typeChecker = new TypeChecker(metadataProvider); String type = "foo"; assertThat(typeChecker.isString(type)).isTrue(); } @Test public void test_it_detects_string_parseable() { TypeChecker typeChecker = new TypeChecker(metadataProvider); UUID typeUUID = UUID.randomUUID(); Sample typeEnum = Sample.READ; assertThat(typeChecker.isStringParseable(typeUUID)).isTrue(); assertThat(typeChecker.isStringParseable(typeEnum)).isTrue(); } @Test public void test_it_detects_boolean() { TypeChecker typeChecker = new TypeChecker(metadataProvider); Boolean type = true; boolean typePrimitive = false; assertThat(typeChecker.isBoolean(type)).isTrue(); assertThat(typeChecker.isBoolean(typePrimitive)).isTrue(); } @Test public void test_it_detects_date() { TypeChecker typeChecker = new TypeChecker(metadataProvider); Date type = new Date(); assertThat(typeChecker.isDate(type)).isTrue(); } @Test public void test_it_detects_serializable_object() { TypeChecker typeChecker = new TypeChecker(metadataProvider); Foo type = new Foo(); assertThat(typeChecker.isSerializableObject(type)).isTrue(); assertThat(typeChecker.isUnserializableObject(type)).isFalse(); } @Test public void test_it_detects_unserializable_object_with_not_defined_metadata_object() { TypeChecker typeChecker = new TypeChecker(metadataProvider); BeanWithoutMetadata type = new BeanWithoutMetadata(); assertThat(typeChecker.isUnserializableObject(type)).isTrue(); assertThat(typeChecker.isSerializableObject(type)).isFalse(); } @Test public void test_it_detects_unserializable_object_with_wrong_defined_metadata_object() { TypeChecker typeChecker = new TypeChecker(metadataProvider); BeanWithWrongDefinedMetadata type = new BeanWithWrongDefinedMetadata(); assertThat(typeChecker.isUnserializableObject(type)).isTrue(); assertThat(typeChecker.isSerializableObject(type)).isFalse(); } @Test public void test_it_detects_iterable() { TypeChecker typeChecker = new TypeChecker(metadataProvider); List<Integer> typeList = new ArrayList<>(); String[] typeStringArr = new String[] {"a", "b"}; assertThat(typeChecker.isIterable(typeList)).isTrue(); assertThat(typeChecker.isIterable(typeStringArr)).isFalse(); } @Test public void test_it_detects_map() { TypeChecker typeChecker = new TypeChecker(metadataProvider); Map<Integer, Integer> type = new HashMap<>(); assertThat(typeChecker.isMap(type)).isTrue(); } }
3e0576e32d904c832ab5d236b737c7b335e3094f
454
java
Java
src/main/java/com/iotticket/api/v1/validation/APIRequirement.java
IoT-Ticket/IoT-JavaClient
8a693f191787240a3beea09df6f25f47a0bdfbe3
[ "MIT" ]
2
2020-05-12T08:52:03.000Z
2021-05-11T14:20:16.000Z
src/main/java/com/iotticket/api/v1/validation/APIRequirement.java
IoT-Ticket/IoT-JavaClient
8a693f191787240a3beea09df6f25f47a0bdfbe3
[ "MIT" ]
5
2020-10-02T07:37:26.000Z
2021-03-03T01:19:08.000Z
src/main/java/com/iotticket/api/v1/validation/APIRequirement.java
IoT-Ticket/IoT-JavaClient
8a693f191787240a3beea09df6f25f47a0bdfbe3
[ "MIT" ]
4
2015-06-07T12:56:08.000Z
2021-02-24T12:27:20.000Z
20.636364
44
0.773128
2,286
package com.iotticket.api.v1.validation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface APIRequirement { int UNRESTRICTED = -1; int maxLength() default UNRESTRICTED; String regexPattern() default ""; boolean nullable() default true; }
3e0577de8bd77b1dc702d9c97dee88cb3a078ca1
2,052
java
Java
framework/src/main/java/com/suredy/formbuilder/design/srv/FormDefineSrv.java
ynbz/framework
65effc284952e9f8ab99bfffb627d7e0d10cd79f
[ "MIT" ]
null
null
null
framework/src/main/java/com/suredy/formbuilder/design/srv/FormDefineSrv.java
ynbz/framework
65effc284952e9f8ab99bfffb627d7e0d10cd79f
[ "MIT" ]
null
null
null
framework/src/main/java/com/suredy/formbuilder/design/srv/FormDefineSrv.java
ynbz/framework
65effc284952e9f8ab99bfffb627d7e0d10cd79f
[ "MIT" ]
null
null
null
26.649351
85
0.709552
2,287
package com.suredy.formbuilder.design.srv; import org.apache.commons.lang3.StringUtils; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Service; import com.suredy.core.service.BaseSrvWithEntity; import com.suredy.core.service.GBKOrder; import com.suredy.formbuilder.design.model.FormDefine; @Service public class FormDefineSrv extends BaseSrvWithEntity<FormDefine> { public FormDefineSrv() { this.addDefOrder(GBKOrder.asc("name")); this.defDesc("enable"); this.defAsc("version"); } @Override public DetachedCriteria getDc(FormDefine t, String alias) { return this.putClause(null, t, alias); } @Override public DetachedCriteria putClause(DetachedCriteria dc, FormDefine t, String alias) { if (dc == null) dc = super.getDc(t, alias); if (t == null) return dc; if (!StringUtils.isBlank(t.getId())) { dc.add(Restrictions.eq("id", t.getId())); } if (t.getEnable() != null) { dc.add(Restrictions.eq("enable", t.getEnable())); } if (!StringUtils.isBlank(t.getName())) { dc.add(Restrictions.like("name", t.getName(), MatchMode.ANYWHERE)); } if (!StringUtils.isBlank(t.getVersion())) { dc.add(Restrictions.eq("version", t.getVersion())); } if (t.getMinCreateTime() != null) { dc.add(Restrictions.ge("createTime", t.getMinCreateTime())); } if (t.getMaxCreateTime() != null) { dc.add(Restrictions.le("createTime", t.getMaxCreateTime())); } return dc; } public boolean exists(String name, String version, String... excludeId) { if (StringUtils.isBlank(name) || StringUtils.isBlank(version)) return false; FormDefine search = new FormDefine(); search.setVersion(version); DetachedCriteria dc = this.getDc(search); dc.add(Restrictions.eq("name", name)); if (excludeId != null && excludeId.length > 0) { dc.add(Restrictions.not(Restrictions.in("id", excludeId))); } int count = this.getCountByCriteria(dc); return count > 0; } }
3e057800c809b2fc09014e81697a5756bb0d0cc6
2,687
java
Java
src/excx/entities/exception/HomingBullet.java
egladysz/External-Xylene-Combustion-X
89dc702c462805b4804e29dc2c5980a89bc3799e
[ "MIT" ]
null
null
null
src/excx/entities/exception/HomingBullet.java
egladysz/External-Xylene-Combustion-X
89dc702c462805b4804e29dc2c5980a89bc3799e
[ "MIT" ]
null
null
null
src/excx/entities/exception/HomingBullet.java
egladysz/External-Xylene-Combustion-X
89dc702c462805b4804e29dc2c5980a89bc3799e
[ "MIT" ]
null
null
null
25.590476
81
0.653517
2,288
package excx.entities.exception; import excx.data.SpriteSheet; import excx.entities.BasicBullet; import excx.entities.Enemy; import excx.entities.GameField; import excx.entities.Sprite; import excx.movement.Movement; import excx.movement.Vector; import excx.movement.VectorMath; public class HomingBullet extends BasicBullet{ Enemy target; private boolean on; public HomingBullet(double x, double y, Movement type,boolean homing) { super(x, y, type); this.setImageNode(SpriteSheet.getInstance().getSpriteNode(this.toString())); setOn(homing); } @Override public void tick() { if(!isOn()){ super.tick(); return; } else{ Enemy closest = null; double sqrDistance = 0; for(Sprite e:getWorld().getEntityList()){ if (e instanceof Enemy){ if(closest == null){ closest = (Enemy) e; sqrDistance = Math.pow(getX()-e.getX(),2)+Math.pow(getY()-e.getY(),2); } if(sqrDistance > Math.pow(getX()-e.getX(),2)+Math.pow(getY()-e.getY(),2)){ closest = (Enemy) e; sqrDistance = Math.pow(getX()-e.getX(),2)+Math.pow(getY()-e.getY(),2); } } } target = closest; } if(target == null){ super.tick(); return; } double angleToTarget= this.getVectorToTarget(target).getAngleRadians(); double angleOfMe= getMovement().getVelocityAngleRadians(); double consta = 1;//60D/60D; double fast = this.getMovement().getVelocity(); Vector dir = this.getVectorToTarget(target); Vector vel = (Vector) this.getMovement().getVelocityVector().clone(); if(Math.abs(angleToTarget-angleOfMe)>Math.PI/2){ //TODO: Test this Vector yay = VectorMath.rejection(dir, vel); yay.setMagnitude(consta); this.getMovement().setAccelerationVector(yay); } else{ Vector yay = VectorMath.rejection(VectorMath.normalize(dir), vel); yay = VectorMath.scalarMultiply(yay, consta); this.getMovement().setAccelerationVector(yay); } super.tick(); this.getMovement().setVelocity(fast); this.getMovement().setAcceleration(0); //TODO: Configure angle rotation. /* * Projection of desired velocity over perpendicular velocity. * Overridden by generic maximum angle. * */ } @Override public Object clone() { return new HomingBullet(getX(),getY(),(Movement)getMovement().clone(),isOn()); } public String toString(){ return super.toString() + "_homing"; } public boolean isOn() { return on; } public void setOn(boolean on) { this.on = on; } @Override public void checkCollision(GameField world) { // TODO Auto-generated method stub } }
3e0578968b13a33c31d89000a9c9661bae5403b5
19,470
java
Java
evosuite/runtime/src/main/java/org/evosuite/runtime/mock/java/util/zip/MockZipFile.java
racoq/TESRAC
75a33741bd7a0c27a5fcd183fb4418d7b7146e80
[ "Apache-2.0" ]
null
null
null
evosuite/runtime/src/main/java/org/evosuite/runtime/mock/java/util/zip/MockZipFile.java
racoq/TESRAC
75a33741bd7a0c27a5fcd183fb4418d7b7146e80
[ "Apache-2.0" ]
null
null
null
evosuite/runtime/src/main/java/org/evosuite/runtime/mock/java/util/zip/MockZipFile.java
racoq/TESRAC
75a33741bd7a0c27a5fcd183fb4418d7b7146e80
[ "Apache-2.0" ]
null
null
null
33.685121
91
0.507191
2,289
/** * Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3.0 of the License, or * (at your option) any later version. * * EvoSuite is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ package org.evosuite.runtime.mock.java.util.zip; /* import java.io.Closeable; import java.io.InputStream; import java.io.IOException; import java.io.EOFException; import java.io.File; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayDeque; import java.util.Deque; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.WeakHashMap; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipError; import java.util.zip.ZipException; import java.util.zip.ZipFile; import java.security.AccessController; import sun.security.action.GetPropertyAction; import static org.evosuite.runtime.mock.java.util.zip.EvoZipConstants64.*; */ //ZipFile implements ZipConstants, but it is package level access /* * TODO */ public class MockZipFile { //extends ZipFile implements Closeable { /* private long jzfile; // address of jzfile data private final String name; // zip file name private final int total; // total number of entries private final boolean locsig; // if zip file starts with LOCSIG (usually true) private volatile boolean closeRequested = false; private static final int STORED = ZipEntry.STORED; private static final int DEFLATED = ZipEntry.DEFLATED; public static final int OPEN_READ = 0x1; public static final int OPEN_DELETE = 0x4; static { // Zip library is loaded from System.initializeSystemClass initIDs(); } private static native void initIDs(); private static final boolean usemmap; static { // A system prpperty to disable mmap use to avoid vm crash when // in-use zip file is accidently overwritten by others. String prop = sun.misc.VM.getSavedProperty("sun.zip.disableMemoryMapping"); usemmap = (prop == null || !(prop.length() == 0 || prop.equalsIgnoreCase("true"))); } private ZipCoder zc; // the outstanding inputstreams that need to be closed, // mapped to the inflater objects they use. private final Map<InputStream, Inflater> streams = new WeakHashMap<>(); //----- constructors ---------------------- public MockZipFile(String name) throws IOException { this(new File(name), OPEN_READ); } public MockZipFile(File file, int mode) throws IOException { this(file, mode, StandardCharsets.UTF_8); } public MockZipFile(File file) throws ZipException, IOException { this(file, OPEN_READ); } public MockZipFile(File file, int mode, Charset charset) throws IOException { if (((mode & OPEN_READ) == 0) || ((mode & ~(OPEN_READ | OPEN_DELETE)) != 0)) { throw new IllegalArgumentException("Illegal mode: 0x"+ Integer.toHexString(mode)); } String name = file.getPath(); SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkRead(name); if ((mode & OPEN_DELETE) != 0) { sm.checkDelete(name); } } if (charset == null) throw new NullPointerException("charset is null"); this.zc = ZipCoder.get(charset); long t0 = System.nanoTime(); jzfile = open(name, mode, file.lastModified(), usemmap); sun.misc.PerfCounter.getZipFileOpenTime().addElapsedTimeFrom(t0); sun.misc.PerfCounter.getZipFileCount().increment(); this.name = name; this.total = getTotal(jzfile); this.locsig = startsWithLOC(jzfile); } public MockZipFile(String name, Charset charset) throws IOException { this(new File(name), OPEN_READ, charset); } public MockZipFile(File file, Charset charset) throws IOException { this(file, OPEN_READ, charset); } //------- methods ----------------------- public String getComment() { synchronized (this) { ensureOpen(); byte[] bcomm = getCommentBytes(jzfile); if (bcomm == null) return null; return zc.toString(bcomm, bcomm.length); } } public ZipEntry getEntry(String name) { if (name == null) { throw new NullPointerException("name"); } long jzentry = 0; synchronized (this) { ensureOpen(); jzentry = getEntry(jzfile, zc.getBytes(name), true); if (jzentry != 0) { ZipEntry ze = getZipEntry(name, jzentry); freeEntry(jzfile, jzentry); return ze; } } return null; } private static native long getEntry(long jzfile, byte[] name, boolean addSlash); // freeEntry releases the C jzentry struct. private static native void freeEntry(long jzfile, long jzentry); public InputStream getInputStream(ZipEntry entry) throws IOException { if (entry == null) { throw new NullPointerException("entry"); } long jzentry = 0; ZipFileInputStream in = null; synchronized (this) { ensureOpen(); if (!zc.isUTF8() && (entry.flag & EFS) != 0) { jzentry = getEntry(jzfile, zc.getBytesUTF8(entry.name), false); } else { jzentry = getEntry(jzfile, zc.getBytes(entry.name), false); } if (jzentry == 0) { return null; } in = new ZipFileInputStream(jzentry); switch (getEntryMethod(jzentry)) { case STORED: synchronized (streams) { streams.put(in, null); } return in; case DEFLATED: // MORE: Compute good size for inflater stream: long size = getEntrySize(jzentry) + 2; // Inflater likes a bit of slack if (size > 65536) size = 8192; if (size <= 0) size = 4096; Inflater inf = getInflater(); InputStream is = new ZipFileInflaterInputStream(in, inf, (int)size); synchronized (streams) { streams.put(is, inf); } return is; default: throw new ZipException("invalid compression method"); } } } // ------- internal class ---------- private class ZipFileInflaterInputStream extends InflaterInputStream { private volatile boolean closeRequested = false; private boolean eof = false; private final ZipFileInputStream zfin; ZipFileInflaterInputStream(ZipFileInputStream zfin, Inflater inf, int size) { super(zfin, inf, size); this.zfin = zfin; } public void close() throws IOException { if (closeRequested) return; closeRequested = true; super.close(); Inflater inf; synchronized (streams) { inf = streams.remove(this); } if (inf != null) { releaseInflater(inf); } } // Override fill() method to provide an extra "dummy" byte // at the end of the input stream. This is required when // using the "nowrap" Inflater option. protected void fill() throws IOException { if (eof) { throw new EOFException("Unexpected end of ZLIB input stream"); } len = in.read(buf, 0, buf.length); if (len == -1) { buf[0] = 0; len = 1; eof = true; } inf.setInput(buf, 0, len); } public int available() throws IOException { if (closeRequested) return 0; long avail = zfin.size() - inf.getBytesWritten(); return (avail > (long) Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) avail); } protected void finalize() throws Throwable { close(); } } private Inflater getInflater() { Inflater inf; synchronized (inflaterCache) { while (null != (inf = inflaterCache.poll())) { if (false == inf.ended()) { return inf; } } } return new Inflater(true); } private void releaseInflater(Inflater inf) { if (false == inf.ended()) { inf.reset(); synchronized (inflaterCache) { inflaterCache.add(inf); } } } // List of available Inflater objects for decompression private Deque<Inflater> inflaterCache = new ArrayDeque<>(); public String getName() { return name; } public Enumeration<? extends ZipEntry> entries() { ensureOpen(); return new Enumeration<ZipEntry>() { private int i = 0; public boolean hasMoreElements() { synchronized (MockZipFile.this) { ensureOpen(); return i < total; } } public ZipEntry nextElement() throws NoSuchElementException { synchronized (MockZipFile.this) { ensureOpen(); if (i >= total) { throw new NoSuchElementException(); } long jzentry = getNextEntry(jzfile, i++); if (jzentry == 0) { String message; if (closeRequested) { message = "ZipFile concurrently closed"; } else { message = getZipMessage(MockZipFile.this.jzfile); } throw new ZipError("jzentry == 0" + ",\n jzfile = " + MockZipFile.this.jzfile + ",\n total = " + MockZipFile.this.total + ",\n name = " + MockZipFile.this.name + ",\n i = " + i + ",\n message = " + message ); } ZipEntry ze = getZipEntry(null, jzentry); freeEntry(jzfile, jzentry); return ze; } } }; } private ZipEntry getZipEntry(String name, long jzentry) { ZipEntry e = new ZipEntry(); e.flag = getEntryFlag(jzentry); // get the flag first if (name != null) { e.name = name; } else { byte[] bname = getEntryBytes(jzentry, JZENTRY_NAME); if (!zc.isUTF8() && (e.flag & EFS) != 0) { e.name = zc.toStringUTF8(bname, bname.length); } else { e.name = zc.toString(bname, bname.length); } } e.time = getEntryTime(jzentry); e.crc = getEntryCrc(jzentry); e.size = getEntrySize(jzentry); e. csize = getEntryCSize(jzentry); e.method = getEntryMethod(jzentry); e.extra = getEntryBytes(jzentry, JZENTRY_EXTRA); byte[] bcomm = getEntryBytes(jzentry, JZENTRY_COMMENT); if (bcomm == null) { e.comment = null; } else { if (!zc.isUTF8() && (e.flag & EFS) != 0) { e.comment = zc.toStringUTF8(bcomm, bcomm.length); } else { e.comment = zc.toString(bcomm, bcomm.length); } } return e; } private static native long getNextEntry(long jzfile, int i); public int size() { ensureOpen(); return total; } public void close() throws IOException { if (closeRequested) return; closeRequested = true; synchronized (this) { // Close streams, release their inflaters synchronized (streams) { if (false == streams.isEmpty()) { Map<InputStream, Inflater> copy = new HashMap<>(streams); streams.clear(); for (Map.Entry<InputStream, Inflater> e : copy.entrySet()) { e.getKey().close(); Inflater inf = e.getValue(); if (inf != null) { inf.end(); } } } } // Release cached inflaters Inflater inf; synchronized (inflaterCache) { while (null != (inf = inflaterCache.poll())) { inf.end(); } } if (jzfile != 0) { // Close the zip file long zf = this.jzfile; jzfile = 0; close(zf); } } } protected void finalize() throws IOException { close(); } private static native void close(long jzfile); private void ensureOpen() { if (closeRequested) { throw new IllegalStateException("zip file closed"); } if (jzfile == 0) { throw new IllegalStateException("The object is not initialized."); } } private void ensureOpenOrZipException() throws IOException { if (closeRequested) { throw new ZipException("ZipFile closed"); } } private class ZipFileInputStream extends InputStream { private volatile boolean closeRequested = false; protected long jzentry; // address of jzentry data private long pos; // current position within entry data protected long rem; // number of remaining bytes within entry protected long size; // uncompressed size of this entry ZipFileInputStream(long jzentry) { pos = 0; rem = getEntryCSize(jzentry); size = getEntrySize(jzentry); this.jzentry = jzentry; } public int read(byte b[], int off, int len) throws IOException { if (rem == 0) { return -1; } if (len <= 0) { return 0; } if (len > rem) { len = (int) rem; } synchronized (MockZipFile.this) { ensureOpenOrZipException(); len = MockZipFile.read(MockZipFile.this.jzfile, jzentry, pos, b, off, len); } if (len > 0) { pos += len; rem -= len; } if (rem == 0) { close(); } return len; } public int read() throws IOException { byte[] b = new byte[1]; if (read(b, 0, 1) == 1) { return b[0] & 0xff; } else { return -1; } } public long skip(long n) { if (n > rem) n = rem; pos += n; rem -= n; if (rem == 0) { close(); } return n; } public int available() { return rem > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) rem; } public long size() { return size; } public void close() { if (closeRequested) return; closeRequested = true; rem = 0; synchronized (MockZipFile.this) { if (jzentry != 0 && MockZipFile.this.jzfile != 0) { freeEntry(MockZipFile.this.jzfile, jzentry); jzentry = 0; } } synchronized (streams) { streams.remove(this); } } protected void finalize() { close(); } } static { sun.misc.SharedSecrets.setJavaUtilZipFileAccess( new sun.misc.JavaUtilZipFileAccess() { public boolean startsWithLocHeader(ZipFile zip) { return zip.startsWithLocHeader(); } } ); } // Returns {@code true} if, and only if, the zip file begins with {@code //LOCSIG}. private boolean startsWithLocHeader() { return locsig; } private static native long open(String name, int mode, long lastModified, boolean usemmap) throws IOException; private static native int getTotal(long jzfile); private static native boolean startsWithLOC(long jzfile); private static native int read(long jzfile, long jzentry, long pos, byte[] b, int off, int len); // access to the native zentry object private static native long getEntryTime(long jzentry); private static native long getEntryCrc(long jzentry); private static native long getEntryCSize(long jzentry); private static native long getEntrySize(long jzentry); private static native int getEntryMethod(long jzentry); private static native int getEntryFlag(long jzentry); private static native byte[] getCommentBytes(long jzfile); private static final int JZENTRY_NAME = 0; private static final int JZENTRY_EXTRA = 1; private static final int JZENTRY_COMMENT = 2; private static native byte[] getEntryBytes(long jzentry, int type); private static native String getZipMessage(long jzfile); */ }
3e057960c1e90f85f612d9a0d3c4a5fc96058968
1,889
java
Java
Yeokku/src/main/java/com/kh/yeokku/model/dto/TransResultBusDto.java
KH-FINAL-2TEAM/Final_Project_Yeokku
4976d76876484cb7634b7fa9dc95d8123defd8ea
[ "MIT" ]
1
2021-09-27T11:34:50.000Z
2021-09-27T11:34:50.000Z
Yeokku/src/main/java/com/kh/yeokku/model/dto/TransResultBusDto.java
KH-FINAL-2TEAM/Final_Project_Yeokku
4976d76876484cb7634b7fa9dc95d8123defd8ea
[ "MIT" ]
null
null
null
Yeokku/src/main/java/com/kh/yeokku/model/dto/TransResultBusDto.java
KH-FINAL-2TEAM/Final_Project_Yeokku
4976d76876484cb7634b7fa9dc95d8123defd8ea
[ "MIT" ]
null
null
null
23.6125
103
0.721016
2,290
package com.kh.yeokku.model.dto; public class TransResultBusDto { private String gradeNm; private String depPlandTime; private String arrPlandTime; private String depPlaceNm; private String arrPlaceNm; private String charge; private String type; public TransResultBusDto() { super(); } public TransResultBusDto(String gradeNm, String depPlandTime, String arrPlandTime, String depPlaceNm, String arrPlaceNm, String charge, String type) { super(); this.gradeNm = gradeNm; this.depPlandTime = depPlandTime; this.arrPlandTime = arrPlandTime; this.depPlaceNm = depPlaceNm; this.arrPlaceNm = arrPlaceNm; this.charge = charge; this.type = type; } public String getGradeNm() { return gradeNm; } public void setGradeNm(String gradeNm) { this.gradeNm = gradeNm; } public String getDepPlandTime() { return depPlandTime; } public void setDepPlandTime(String depPlandTime) { this.depPlandTime = depPlandTime; } public String getArrPlandTime() { return arrPlandTime; } public void setArrPlandTime(String arrPlandTime) { this.arrPlandTime = arrPlandTime; } public String getDepPlaceNm() { return depPlaceNm; } public void setDepPlaceNm(String depPlaceNm) { this.depPlaceNm = depPlaceNm; } public String getArrPlaceNm() { return arrPlaceNm; } public void setArrPlaceNm(String arrPlaceNm) { this.arrPlaceNm = arrPlaceNm; } public String getCharge() { return charge; } public void setCharge(String charge) { this.charge = charge; } public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public String toString() { return "TransResultBusDto [gradeNm=" + gradeNm + ", depPlandTime=" + depPlandTime + ", arrPlandTime=" + arrPlandTime + ", depPlaceNm=" + depPlaceNm + ", arrPlaceNm=" + arrPlaceNm + ", charge=" + charge + ", type=" + type + "]"; } }
3e057a79c6f7e5fc5ab654c7eaaab4c4b2efed81
4,443
java
Java
src/main/java/org/asciicerebrum/neocortexengine/services/statistics/DefaultAbilityCalculationService.java
asciiCerebrum/neocortexEngine
dda27f24ed1dbd4010523124f5fe11e5e8dee4cf
[ "MIT" ]
3
2016-05-24T03:34:31.000Z
2021-04-09T18:38:11.000Z
src/main/java/org/asciicerebrum/neocortexengine/services/statistics/DefaultAbilityCalculationService.java
asciiCerebrum/neocortexEngine
dda27f24ed1dbd4010523124f5fe11e5e8dee4cf
[ "MIT" ]
null
null
null
src/main/java/org/asciicerebrum/neocortexengine/services/statistics/DefaultAbilityCalculationService.java
asciiCerebrum/neocortexEngine
dda27f24ed1dbd4010523124f5fe11e5e8dee4cf
[ "MIT" ]
2
2016-03-09T07:50:20.000Z
2020-07-05T02:05:54.000Z
36.121951
90
0.696601
2,291
package org.asciicerebrum.neocortexengine.services.statistics; import org.asciicerebrum.neocortexengine.domain.core.particles.AbilityScore; import org.asciicerebrum.neocortexengine.domain.core.particles.BonusRank; import org.asciicerebrum.neocortexengine.domain.core.particles.BonusValue; import org.asciicerebrum.neocortexengine.domain.core.particles.BonusValueTuple; import org.asciicerebrum.neocortexengine.domain.game.DndCharacter; import org.asciicerebrum.neocortexengine.domain.mechanics.BonusTargets; import org.asciicerebrum.neocortexengine.domain.mechanics.ObserverHook; import org.asciicerebrum.neocortexengine.domain.mechanics.ObserverHooks; import org.asciicerebrum.neocortexengine.domain.mechanics.bonus.source.BonusSources; import org.asciicerebrum.neocortexengine.domain.mechanics.observer.source.ObserverSources; import org.asciicerebrum.neocortexengine.domain.ruleentities.Ability; import org.asciicerebrum.neocortexengine.services.core.BonusCalculationService; /** * * @author species8472 */ public class DefaultAbilityCalculationService implements AbilityCalculationService { /** * These are constants for calculating the ability mod from the ability * score. This whole class is d20-specific. So if you ever want to implement * another rule system, this class has to be replaced anyway. So these * values were not put into the spring xml. */ private static final double ABILITY_BONUS_OFFSET = 10.0; /** * Constant for calculating the ability mod from the ability score. */ private static final double ABILITY_BONUS_FRACTION = 2.0; /** * The bonus calculation service needed for dynamic bonus value calculation. */ private BonusCalculationService bonusService; @Override public final AbilityScore calcAbilityScore(final DndCharacter dndCharacter, final Ability ability) { final AbilityScore baseValue = dndCharacter.getBaseAbilities().getValueForAbility(ability); // adding the advancements in that special ability. baseValue.add(dndCharacter.getLevelAdvancements() .countAbility(ability)); return baseValue; } @Override public final AbilityScore calcCurrentAbilityScore( final DndCharacter dndCharacter, final Ability ability) { final AbilityScore baseValue = this.calcAbilityScore( dndCharacter, ability); final BonusValueTuple abilityTuple = this.getBonusService().calculateBonusValues( new BonusSources(dndCharacter), new BonusTargets(ability), dndCharacter, new ObserverSources(dndCharacter), new ObserverHooks(ObserverHook.ABILITY, ability.getAssociatedHook()), dndCharacter); // adding all dynamic boni to the ability score. baseValue.add(abilityTuple.getBonusValueByRank(BonusRank.RANK_0)); return baseValue; } @Override public final BonusValue calcAbilityMod(final DndCharacter dndCharacter, final Ability ability) { final AbilityScore score = this.calcAbilityScore( dndCharacter, ability); return this.calcAbilityMod(score); } @Override public final BonusValue calcCurrentAbilityMod( final DndCharacter dndCharacter, final Ability ability) { final AbilityScore score = this.calcCurrentAbilityScore( dndCharacter, ability); return this.calcAbilityMod(score); } /** * Basic calculation method from the ability score to the mod. * * @param score the ability score. * @return the corresponding ability mod. */ final BonusValue calcAbilityMod(final AbilityScore score) { long mod = Math.round(Math.floor((score.getValue() - ABILITY_BONUS_OFFSET) / ABILITY_BONUS_FRACTION)); return new BonusValue(mod); } /** * @param bonusServiceInput the bonusService to set */ public final void setBonusService( final BonusCalculationService bonusServiceInput) { this.bonusService = bonusServiceInput; } /** * @return the bonusService */ public final BonusCalculationService getBonusService() { return bonusService; } }
3e057a9b698ec2bfa239446fe9ee544d026e06c5
220
java
Java
src/test/java/com/os94/dutchpay/DutchpayApplicationTests.java
os94/DutchPay
00b2fbc24f9df382ea1a18ad2a8de2bd0431a636
[ "MIT" ]
null
null
null
src/test/java/com/os94/dutchpay/DutchpayApplicationTests.java
os94/DutchPay
00b2fbc24f9df382ea1a18ad2a8de2bd0431a636
[ "MIT" ]
null
null
null
src/test/java/com/os94/dutchpay/DutchpayApplicationTests.java
os94/DutchPay
00b2fbc24f9df382ea1a18ad2a8de2bd0431a636
[ "MIT" ]
null
null
null
15.714286
60
0.754545
2,292
package com.os94.dutchpay; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class DutchpayApplicationTests { @Test void contextLoads() { } }
3e057b260ff79d0d54c06c05fa6ecb56f6e5decd
4,269
java
Java
core/src/main/java/org/apache/oozie/command/StatusTransitXCommand.java
martin-g/oozie
b6575162a7979ee655c2397b8a5ba3153fc03ae9
[ "Apache-2.0" ]
589
2015-01-12T09:17:08.000Z
2022-03-31T03:05:40.000Z
core/src/main/java/org/apache/oozie/command/StatusTransitXCommand.java
martin-g/oozie
b6575162a7979ee655c2397b8a5ba3153fc03ae9
[ "Apache-2.0" ]
35
2015-01-20T12:22:36.000Z
2018-07-26T05:22:20.000Z
core/src/main/java/org/apache/oozie/command/StatusTransitXCommand.java
martin-g/oozie
b6575162a7979ee655c2397b8a5ba3153fc03ae9
[ "Apache-2.0" ]
495
2015-01-07T04:29:58.000Z
2022-03-23T02:50:16.000Z
26.515528
117
0.636683
2,293
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.oozie.command; import org.apache.oozie.client.Job; import org.apache.oozie.executor.jpa.JPAExecutorException; /** * StatusTransitXCommand is super class for Status Transit Command, it defines layout for Status Transit Commands. It * tries change job status change after acquiring lock with zero timeout. StatusTransit Commands are not requeued. */ abstract public class StatusTransitXCommand extends XCommand<Void> { /** * Instantiates a new status transit x command. * * @param name the name * @param type the type * @param priority the priority */ public StatusTransitXCommand(String name, String type, int priority) { super(name, type, priority); } @Override final protected long getLockTimeOut() { return 0L; } @Override final protected boolean isReQueueRequired() { return false; } @Override final protected boolean isLockRequired() { return true; } @Override protected Void execute() throws CommandException { final Job.Status jobStatus = getJobStatus(); try { if (jobStatus != null) { updateJobStatus(jobStatus); } } catch (JPAExecutorException e) { throw new CommandException(e); } return null; } /** * Gets the job status. * * @return the job status * @throws CommandException the command exception */ protected Job.Status getJobStatus() throws CommandException { if (isTerminalState()) { return getTerminalStatus(); } if (isPausedState()) { return getPausedState(); } if (isSuspendedState()) { return getSuspendedStatus(); } if (isRunningState()) { return getRunningState(); } return null; } /** * Checks if job is in terminal state. * * @return true, if is terminal state */ protected abstract boolean isTerminalState(); /** * Gets the job terminal status. * * @return the terminal status */ protected abstract Job.Status getTerminalStatus(); /** * Checks if job is in paused state. * * @return true, if job is in paused state */ protected abstract boolean isPausedState(); /** * Gets the job pause state. * * @return the paused state */ protected abstract Job.Status getPausedState(); /** * Checks if is in suspended state. * * @return true, if job is in suspended state */ protected abstract boolean isSuspendedState(); /** * Gets the suspended status. * * @return the suspended status */ protected abstract Job.Status getSuspendedStatus(); /** * Checks if job is in running state. * * @return true, if job is in running state */ protected abstract boolean isRunningState(); /** * Gets the job running state. * * @return the running state */ protected abstract Job.Status getRunningState(); /** * Update job status. * * @param status the status * @throws JPAExecutorException the JPA executor exception * @throws CommandException the command exception */ protected abstract void updateJobStatus(Job.Status status) throws JPAExecutorException, CommandException; }
3e057bcc5eddda66bfa3f447ae7e49cd33c6706f
16,633
java
Java
PluginsAndFeatures/azure-toolkit-for-intellij/src/com/microsoft/azuretools/ijidea/ui/SignInWindow.java
SummerSun/azure-tools-for-java
809ee45ef4dad06666cbe485c057143d80b0d826
[ "MIT" ]
null
null
null
PluginsAndFeatures/azure-toolkit-for-intellij/src/com/microsoft/azuretools/ijidea/ui/SignInWindow.java
SummerSun/azure-tools-for-java
809ee45ef4dad06666cbe485c057143d80b0d826
[ "MIT" ]
1
2018-11-13T07:11:46.000Z
2018-11-13T07:11:46.000Z
PluginsAndFeatures/azure-toolkit-for-intellij/src/com/microsoft/azuretools/ijidea/ui/SignInWindow.java
SummerSun/azure-tools-for-java
809ee45ef4dad06666cbe485c057143d80b0d826
[ "MIT" ]
null
null
null
38.681395
126
0.61889
2,294
/* * Copyright (c) Microsoft Corporation * <p/> * All rights reserved. * <p/> * MIT License * <p/> * 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: * <p/> * The above copyright notice and this permission notice shall be included in all copies or substantial portions of * the Software. * <p/> * 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.microsoft.azuretools.ijidea.ui; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.microsoft.azuretools.adauth.AuthCanceledException; import com.microsoft.azuretools.adauth.StringUtils; import com.microsoft.azuretools.authmanage.AdAuthManager; import com.microsoft.azuretools.authmanage.CommonSettings; import com.microsoft.azuretools.authmanage.DCAuthManager; import com.microsoft.azuretools.authmanage.SubscriptionManager; import com.microsoft.azuretools.authmanage.interact.AuthMethod; import com.microsoft.azuretools.authmanage.models.AuthMethodDetails; import com.microsoft.azuretools.authmanage.models.SubscriptionDetail; import com.microsoft.azuretools.sdkmanage.AccessTokenAzureManager; import com.microsoft.intellij.ui.components.AzureDialogWrapper; import org.jdesktop.swingx.JXHyperlink; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URI; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class SignInWindow extends AzureDialogWrapper { private static final Logger LOGGER = Logger.getInstance(SignInWindow.class); private static final String SIGN_IN_ERROR = "Sign In Error"; private JPanel contentPane; private JRadioButton interactiveRadioButton; private JRadioButton deviceLoginRadioButton; private JRadioButton automatedRadioButton; private JLabel authFileLabel; private JTextField authFileTextField; private JButton browseButton; private JButton createNewAuthenticationFileButton; private JLabel automatedCommentLabel; private JLabel interactiveCommentLabel; private JLabel deviceLoginCommentLabel; private AuthMethodDetails authMethodDetails; private AuthMethodDetails authMethodDetailsResult; private String accountEmail; private Project project; public AuthMethodDetails getAuthMethodDetails() { return authMethodDetailsResult; } public static SignInWindow go(AuthMethodDetails authMethodDetails, Project project) { SignInWindow d = new SignInWindow(authMethodDetails, project); d.show(); if (d.getExitCode() == DialogWrapper.OK_EXIT_CODE) { return d; } return null; } private SignInWindow(AuthMethodDetails authMethodDetails, Project project) { super(project, true, IdeModalityType.PROJECT); this.project = project; setModal(true); setTitle("Azure Sign In"); setOKButtonText("Sign in"); this.authMethodDetails = authMethodDetails; authFileTextField.setText(authMethodDetails.getCredFilePath()); interactiveRadioButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { refreshAuthControlElements(); } }); automatedRadioButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { refreshAuthControlElements(); } }); deviceLoginRadioButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { refreshAuthControlElements(); } }); browseButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doSelectCredFilepath(); } }); createNewAuthenticationFileButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doCreateServicePrincipal(); } }); Font labelFont = UIManager.getFont("Label.font"); deviceLoginRadioButton.setVisible(CommonSettings.getDeviceLoginEnabled()); deviceLoginCommentLabel.setVisible(CommonSettings.getDeviceLoginEnabled()); interactiveRadioButton.setSelected(true); refreshAuthControlElements(); init(); } private void refreshAuthControlElements() { refreshAutomateLoginElements(); refreshDeviceLoginElements(); refreshInteractiveLoginElements(); } private void refreshAutomateLoginElements() { automatedCommentLabel.setEnabled(automatedRadioButton.isSelected()); authFileLabel.setEnabled(automatedRadioButton.isSelected()); authFileTextField.setEnabled(automatedRadioButton.isSelected()); browseButton.setEnabled(automatedRadioButton.isSelected()); createNewAuthenticationFileButton.setEnabled(automatedRadioButton.isSelected()); } private void refreshDeviceLoginElements() { deviceLoginCommentLabel.setEnabled(deviceLoginRadioButton.isSelected()); } private void refreshInteractiveLoginElements() { interactiveCommentLabel.setEnabled(interactiveRadioButton.isSelected()); } private void doSelectCredFilepath() { FileChooserDescriptor fileDescriptor = FileChooserDescriptorFactory.createSingleFileDescriptor("azureauth"); fileDescriptor.setTitle("Select Authentication File"); final VirtualFile file = FileChooser.chooseFile( fileDescriptor, this.project, LocalFileSystem.getInstance().findFileByPath(System.getProperty("user.home")) ); if (file != null) { authFileTextField.setText(file.getPath()); } } private void doDeviceLogin() { try { final DCAuthManager dcAuthManager = DCAuthManager.getInstance(); if (dcAuthManager.isSignedIn()) { doSignOut(); } deviceLoginAsync(dcAuthManager); accountEmail = dcAuthManager.getAccountEmail(); } catch (Exception ex) { ex.printStackTrace(); ErrorWindow.show(project, ex.getMessage(), SIGN_IN_ERROR); } } private void deviceLoginAsync(@NotNull final DCAuthManager dcAuthManager) { ProgressManager.getInstance().run( new Task.Modal(project, "Sign In Progress", false) { @Override public void run(ProgressIndicator indicator) { try { dcAuthManager.deviceLogin(null); } catch (AuthCanceledException ex) { System.out.println(ex.getMessage()); } catch (Exception ex) { ApplicationManager.getApplication().invokeLater( () -> ErrorWindow.show(project, ex.getMessage(), SIGN_IN_ERROR)); } } }); } private void doInteractiveLogin() { try { AdAuthManager adAuthManager = AdAuthManager.getInstance(); if (adAuthManager.isSignedIn()) { doSignOut(); } signInAsync(); accountEmail = adAuthManager.getAccountEmail(); } catch (Exception ex) { ex.printStackTrace(); //LOGGER.error("doSignIn", ex); ErrorWindow.show(project, ex.getMessage(), SIGN_IN_ERROR); } } private void signInAsync() { ProgressManager.getInstance().run( new Task.Modal(project, "Sign In Progress", false) { @Override public void run(ProgressIndicator indicator) { indicator.setIndeterminate(true); indicator.setText("Signing In..."); try { AdAuthManager.getInstance().signIn(); } catch (AuthCanceledException ex) { System.out.println(ex.getMessage()); } catch (Exception ex) { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { ErrorWindow.show(project, ex.getMessage(), SIGN_IN_ERROR); } }); } } } ); } private void doSignOut() { try { accountEmail = null; AdAuthManager.getInstance().signOut(); } catch (Exception ex) { ex.printStackTrace(); ErrorWindow.show(project, ex.getMessage(), "Sign Out Error"); } } private void doCreateServicePrincipal() { AdAuthManager adAuthManager = null; try { adAuthManager = AdAuthManager.getInstance(); if (adAuthManager.isSignedIn()) { adAuthManager.signOut(); } signInAsync(); if (!adAuthManager.isSignedIn()) { // canceled by the user System.out.println(">> Canceled by the user"); return; } AccessTokenAzureManager accessTokenAzureManager = new AccessTokenAzureManager(); SubscriptionManager subscriptionManager = accessTokenAzureManager.getSubscriptionManager(); ProgressManager.getInstance().run(new Task.Modal(project, "Load Subscriptions Progress", true) { @Override public void run(ProgressIndicator progressIndicator) { progressIndicator.setText("Loading subscriptions..."); try { progressIndicator.setIndeterminate(true); subscriptionManager.getSubscriptionDetails(); } catch (Exception ex) { ex.printStackTrace(); //LOGGER.error("doCreateServicePrincipal::Task.Modal", ex); ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { ErrorWindow.show(project, ex.getMessage(), "Load Subscription Error"); } }); } } }); SrvPriSettingsDialog d = SrvPriSettingsDialog.go(subscriptionManager.getSubscriptionDetails(), project); List<SubscriptionDetail> subscriptionDetailsUpdated; String destinationFolder; if (d != null) { subscriptionDetailsUpdated = d.getSubscriptionDetails(); destinationFolder = d.getDestinationFolder(); } else { System.out.println(">> Canceled by the user"); return; } Map<String, List<String>> tidSidsMap = new HashMap<>(); for (SubscriptionDetail sd : subscriptionDetailsUpdated) { if (sd.isSelected()) { System.out.format(">> %s\n", sd.getSubscriptionName()); String tid = sd.getTenantId(); List<String> sidList; if (!tidSidsMap.containsKey(tid)) { sidList = new LinkedList<>(); } else { sidList = tidSidsMap.get(tid); } sidList.add(sd.getSubscriptionId()); tidSidsMap.put(tid, sidList); } } SrvPriCreationStatusDialog d1 = SrvPriCreationStatusDialog.go(tidSidsMap, destinationFolder, project); if (d1 == null) { System.out.println(">> Canceled by the user"); return; } String path = d1.getSelectedAuthFilePath(); if (path == null) { System.out.println(">> No file was created"); return; } authFileTextField.setText(path); } catch (Exception ex) { ex.printStackTrace(); //LOGGER.error("doCreateServicePrincipal", ex); ErrorWindow.show(project, ex.getMessage(), "Get Subscription Error"); } finally { if (adAuthManager != null) { try { System.out.println(">> Signing out..."); adAuthManager.signOut(); } catch (Exception e) { e.printStackTrace(); } } } } @Nullable @Override protected JComponent createCenterPanel() { return contentPane; } @Override protected void doOKAction() { authMethodDetailsResult = new AuthMethodDetails(); if (interactiveRadioButton.isSelected()) { doInteractiveLogin(); if (StringUtils.isNullOrEmpty(accountEmail)) { System.out.println("Canceled by the user."); return; } authMethodDetailsResult.setAuthMethod(AuthMethod.AD); authMethodDetailsResult.setAccountEmail(accountEmail); authMethodDetailsResult.setAzureEnv(CommonSettings.getEnvironment().getName()); } else if (automatedRadioButton.isSelected()) { // automated String authPath = authFileTextField.getText(); if (StringUtils.isNullOrWhiteSpace(authPath)) { JOptionPane.showMessageDialog( contentPane, "Select authentication file", "Sign in dialog info", JOptionPane.INFORMATION_MESSAGE); return; } authMethodDetailsResult.setAuthMethod(AuthMethod.SP); // TODO: check field is empty, check file is valid authMethodDetailsResult.setCredFilePath(authPath); } else if (deviceLoginRadioButton.isSelected()) { doDeviceLogin(); if (StringUtils.isNullOrEmpty(accountEmail)) { System.out.println("Canceled by the user."); return; } authMethodDetailsResult.setAuthMethod(AuthMethod.DC); authMethodDetailsResult.setAccountEmail(accountEmail); authMethodDetailsResult.setAzureEnv(CommonSettings.getEnvironment().getName()); } super.doOKAction(); } @Override public void doCancelAction() { authMethodDetailsResult = authMethodDetails; super.doCancelAction(); } @Override public void doHelpAction() { JXHyperlink helpLink = new JXHyperlink(); helpLink.setURI(URI.create("https://docs.microsoft.com/en-us/azure/azure-toolkit-for-intellij-sign-in-instructions")); helpLink.doClick(); } @Nullable @Override protected String getDimensionServiceKey() { return "SignInWindow"; } }
3e057cebe3f4d93d387725342689ef8516373b6b
992
java
Java
commons-util/src/main/java/com/alanbuttars/commons/util/functions/Function.java
alanbuttars/commons-java
2b9f48bf2e7e5ab2903776b637e8c6f9f68909dd
[ "Apache-2.0" ]
null
null
null
commons-util/src/main/java/com/alanbuttars/commons/util/functions/Function.java
alanbuttars/commons-java
2b9f48bf2e7e5ab2903776b637e8c6f9f68909dd
[ "Apache-2.0" ]
null
null
null
commons-util/src/main/java/com/alanbuttars/commons/util/functions/Function.java
alanbuttars/commons-java
2b9f48bf2e7e5ab2903776b637e8c6f9f68909dd
[ "Apache-2.0" ]
null
null
null
26.105263
75
0.679435
2,295
/* * Copyright (C) Alan Buttars * * 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.alanbuttars.commons.util.functions; /** * A general interface intended for lambdas. For Java 1.7 and below. * * @author Alan Buttars * * @param <A> * Input type * @param <B> * Output type */ public abstract class Function<A, B> { /** * Applies the function. * * @param input * Nullable input */ public abstract B apply(A input); }
3e057e232175f42b5f5338155e0918734d42e4ad
6,163
java
Java
javax.servlet-api-4.0.1-sources/javax/servlet/http/HttpServletMapping.java
creepyCaller/servlet-src
be353316ea4f47171a0c7595603cb66c66aeba08
[ "MIT" ]
6
2020-12-24T19:36:47.000Z
2021-12-27T16:11:41.000Z
javax.servlet-api-4.0.1-sources/javax/servlet/http/HttpServletMapping.java
creepyCaller/servlet-src
be353316ea4f47171a0c7595603cb66c66aeba08
[ "MIT" ]
2
2020-12-19T13:16:55.000Z
2021-01-31T17:45:45.000Z
javax.servlet-api-4.0.1-sources/javax/servlet/http/HttpServletMapping.java
creepyCaller/servlet-src
be353316ea4f47171a0c7595603cb66c66aeba08
[ "MIT" ]
2
2020-12-24T01:24:54.000Z
2020-12-26T16:16:47.000Z
35.217143
78
0.650495
2,296
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2017 Oracle and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can * obtain a copy of the License at * https://oss.oracle.com/licenses/CDDL+GPL-1.1 * or LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at LICENSE.txt. * * GPL Classpath Exception: * Oracle designates this particular file as subject to the "Classpath" * exception as provided by Oracle in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package javax.servlet.http; /** * <p>Allows runtime discovery of the manner in which the {@link * HttpServlet} for the current {@link HttpServletRequest} was invoked. * Invoking any of the methods must not block the caller. The * implementation must be thread safe. Instances are immutable and are * returned from {@link HttpServletRequest#getHttpServletMapping}.</p> * * <p>Following are some illustrative examples for various combinations * of mappings. Consider the following Servlet declaration:</p> * * <pre><code> * &lt;servlet&gt; * &lt;servlet-name&gt;MyServlet&lt;/servlet-name&gt; * &lt;servlet-class&gt;MyServlet&lt;/servlet-class&gt; * &lt;/servlet&gt; * &lt;servlet-mapping&gt; * &lt;servlet-name&gt;MyServlet&lt;/servlet-name&gt; * &lt;url-pattern&gt;/MyServlet&lt;/url-pattern&gt; * &lt;url-pattern&gt;""&lt;/url-pattern&gt; * &lt;url-pattern&gt;*.extension&lt;/url-pattern&gt; * &lt;url-pattern&gt;/path/*&lt;/url-pattern&gt; * &lt;/servlet-mapping&gt; * </code></pre> * * <p>The expected values of the properties for various incoming URI * path values are as shown in this table. The {@code servletName} * column is omitted as its value is always {@code MyServlet}.</p> * * <table border="1"> * <caption>Expected values of properties for various URI paths</caption> * <tr> * <th>URI Path (in quotes)</th> * <th>matchValue</th> * <th>pattern</th> * <th>mappingMatch</th> * </tr> * <tr> * <td>""</td> * <td>""</td> * <td>""</td> * <td>CONTEXT_ROOT</td> * </tr> * <tr> * <td>"/index.html"</td> * <td>""</td> * <td>/</td> * <td>DEFAULT</td> * </tr> * <tr> * <td>"/MyServlet"</td> * <td>MyServlet</td> * <td>/MyServlet</td> * <td>EXACT</td> * </tr> * <tr> * <td>"/foo.extension"</td> * <td>foo</td> * <td>*.extension</td> * <td>EXTENSION</td> * </tr> * <tr> * <td>"/path/foo"</td> * <td>foo</td> * <td>/path/*</td> * <td>PATH</td> * </tr> * * </table> * * @since 4.0 */ public interface HttpServletMapping { /** * <p>Return the portion of the URI path that caused this request to * be matched. If the {@link getMappingMatch} value is {@code * CONTEXT_ROOT} or {@code DEFAULT}, this method must return the * empty string. If the {@link getMappingMatch} value is {@code * EXACT}, this method must return the portion of the path that * matched the servlet, omitting any leading slash. If the {@link * getMappingMatch} value is {@code EXTENSION} or {@code PATH}, this * method must return the value that matched the '*'. See the class * javadoc for examples. </p> * * @return the match. * * @since 4.0 */ public String getMatchValue(); /** * <p>Return the String representation for the {@code url-pattern} * for this mapping. If the {@link getMappingMatch} value is {@code * CONTEXT_ROOT} or {@code DEFAULT}, this method must return the * empty string. If the {@link getMappingMatch} value is {@code * EXTENSION}, this method must return the pattern, without any * leading slash. Otherwise, this method returns the pattern * exactly as specified in the descriptor or Java configuration.</p> * * @return the String representation for the * {@code url-pattern} for this mapping. * * @since 4.0 */ public String getPattern(); /** * <p>Return the String representation for the {@code servlet-name} * for this mapping. If the Servlet providing the response is the * default servlet, the return from this method is the name of the * defautl servlet, which is container specific.</p> * * @return the String representation for the {@code servlet-name} * for this mapping. * * @since 4.0 */ public String getServletName(); /** * <p>Return the {@link MappingMatch} for this * instance</p> * * @return the {@code MappingMatch} for this instance. * * @since 4.0 */ public MappingMatch getMappingMatch(); }
3e057e5a9daf29e068ca533abeab52b095944be6
3,354
java
Java
app/src/main/java/com/dopesatan/cemkian/jobs/DailyChecker.java
utsanjan/Cemkian
b029be155abdf8e0009df6d29c77356daf4fece7
[ "MIT" ]
1
2022-03-09T13:34:26.000Z
2022-03-09T13:34:26.000Z
app/src/main/java/com/dopesatan/cemkian/jobs/DailyChecker.java
utsanjan/Cemkian
b029be155abdf8e0009df6d29c77356daf4fece7
[ "MIT" ]
null
null
null
app/src/main/java/com/dopesatan/cemkian/jobs/DailyChecker.java
utsanjan/Cemkian
b029be155abdf8e0009df6d29c77356daf4fece7
[ "MIT" ]
1
2022-03-13T05:54:08.000Z
2022-03-13T05:54:08.000Z
38.113636
138
0.515802
2,297
package com.dopesatan.cemkian.jobs; import android.content.Context; import androidx.annotation.NonNull; import com.evernote.android.job.DailyJob; import com.evernote.android.job.JobRequest; import java.util.Locale; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import com.dopesatan.cemkian.attendance_objs.AttendanceData; import com.dopesatan.cemkian.workers.DTM; import com.dopesatan.cemkian.workers.LocalNotificationManager; import com.dopesatan.cemkian.workers.Runner; import com.dopesatan.cemkian.workers.WebParser; import com.google.firebase.crashlytics.internal.common.CrashlyticsCore; public class DailyChecker extends DailyJob { static final String TAG = "daily_"; private static final StringBuilder builder = new StringBuilder(); private CrashlyticsCore Crashlytics; public static void schedule(Context context) { long start = TimeUnit.HOURS.toMillis(DTM.getInstance(context).getCycleT_Hour()) + TimeUnit.MINUTES.toMillis(DTM.getInstance(context).getCycleT_Min()); long end = start + TimeUnit.HOURS.toMillis(1); DailyJob.schedule(new JobRequest.Builder(TAG) .setUpdateCurrent(true), start, end); } @NonNull @Override protected DailyJobResult onRunDailyJob(@NonNull Params params) { try { new WebParser().start( DTM.getInstance(getContext()).getUname(), DTM.getInstance(getContext()).getPWD(), new Runner() { @Override public void onComplete(AttendanceData data) { AttendanceData old = DTM.getInstance(getContext()).getLastSavedATD(); if (old != null) { for (int i = 0; i < data.getSubLen(); i++) { builder.append(data.getSub(i)) .append(" : ") .append(String.format(Locale.US, "%.2f", data.getPercentInPoint(i) - old.getPercentInPoint(i)) ) .append("%") .append( i != data.getSubLen() - 1 ? " | " : "" ); } Logger.getLogger(builder.toString()); giveNotification(); } DTM.getInstance(getContext()).updateAttendanceData(data); } @Override public void onCheckComplete(boolean isNull) { } @Override public void onError() { } }); } catch (Exception e) { e.printStackTrace(); Crashlytics.logException(e); } return DailyJobResult.SUCCESS; } private void giveNotification() { LocalNotificationManager.getInstance(getContext()) .setTitle("Percentage Change :") .setBody(builder.toString()) .show(); } }
3e057f50d0764c3b46f3c24f2058668137ba2186
1,753
java
Java
lab_3/SinglyLinkedList.java
almsdy/almasdy.github.io
4110a9fdaa0dc4c8572b5f7df725ecbbbd409dac
[ "MIT" ]
null
null
null
lab_3/SinglyLinkedList.java
almsdy/almasdy.github.io
4110a9fdaa0dc4c8572b5f7df725ecbbbd409dac
[ "MIT" ]
null
null
null
lab_3/SinglyLinkedList.java
almsdy/almasdy.github.io
4110a9fdaa0dc4c8572b5f7df725ecbbbd409dac
[ "MIT" ]
null
null
null
18.452632
47
0.458072
2,298
package lab_3; /** * Created by Ahmed Al masadi on 25/01/2022. */ public class SinglyLinkedList<E> { private Node<E> head=null; private Node<E> tail=null; private int size=0; public SinglyLinkedList(){ } public boolean isEmpty(){ return size==0; } public int size(){ return size; } public E first() { if (isEmpty())return null; return head.getElement(); } public E last() { if (isEmpty())return null; return tail.getElement(); } public void addFrist(E e) { head=new Node<E>(e,head); if (size==0) tail=head; size++; } public void addLast(E e) { Node<E>newest=new Node<E>(e,null); if (isEmpty()) head=newest; else tail.setNext(newest); tail=newest; size++; } public E removeFirst(){ if (isEmpty())return null; E x=head.getElement(); head=head.getNext(); size--; if (size==0) tail=null; return x; } public static class Node<E>{ private E element; private Node<E>next; public Node(E element, Node<E> next) { this.element = element; this.next = next; } public E getElement() { return element; } // public void setElement(E element) { // this.element = element; // } public Node<E> getNext() { return next; } public void setNext(Node<E> next) { this.next = next; } } }
3e057f525907ecf182ad875fdc8b39ba05529f71
17,624
java
Java
orion-server/src/test/java/com/pinterest/orion/core/actions/kafka/TestConcurrentKafkaAction.java
ambud/orion
40fde451c074b973b96ffe839359a3ea808cd3f8
[ "Apache-2.0" ]
64
2020-11-18T21:02:54.000Z
2022-03-24T01:38:40.000Z
orion-server/src/test/java/com/pinterest/orion/core/actions/kafka/TestConcurrentKafkaAction.java
ambud/orion
40fde451c074b973b96ffe839359a3ea808cd3f8
[ "Apache-2.0" ]
17
2021-11-12T01:07:50.000Z
2022-03-20T15:00:26.000Z
orion-server/src/test/java/com/pinterest/orion/core/actions/kafka/TestConcurrentKafkaAction.java
ambud/orion
40fde451c074b973b96ffe839359a3ea808cd3f8
[ "Apache-2.0" ]
20
2020-11-18T21:02:15.000Z
2022-01-27T01:09:00.000Z
37.577825
144
0.681003
2,299
/******************************************************************************* * Copyright 2020 Pinterest, 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 com.pinterest.orion.core.actions.kafka; import static org.junit.Assert.*; import com.pinterest.orion.common.NodeInfo; import com.pinterest.orion.core.Cluster; import com.pinterest.orion.core.Node; import com.pinterest.orion.core.actions.Action; import com.pinterest.orion.core.actions.ActionEngine; import com.pinterest.orion.core.kafka.KafkaBroker; import com.pinterest.orion.core.kafka.KafkaCluster; import com.pinterest.orion.core.kafka.KafkaTopicDescription; import com.pinterest.orion.core.kafka.KafkaTopicPartitionInfo; import com.pinterest.orion.utils.OrionConstants; import com.google.common.collect.Sets; import org.apache.kafka.common.TopicPartitionInfo; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; /** * Testing Concurrent Kafka Actions */ @RunWith(MockitoJUnitRunner.StrictStubs.class) public class TestConcurrentKafkaAction { private static final String[] TEST_TOPICS = new String[]{"testTopic1", "testTopic2"}; private static int MAX_NODE_COUNT = 6; /* A simple 6 broker topology with a single topic with 3 partitions Topic Partition assignment: P0: 0, 1, 3 0 - 1 - 2 P1: 1, 2, 4 \ / \ / P2: 3, 4, 5 3 - 4 (the dependency graph) \ / 5 */ private static int[][] simpleAssignment = new int[][]{ new int[]{0, 1, 3}, new int[]{1, 2, 4}, new int[]{3, 4, 5} }; /* A 6 broker topology with a single topic with 3 partitions, leaving broker 0 with 0 assignments Topic Partition assignment: P0: 1, 3, 4 0 1 - 2 P1: 1, 2, 4 / \ / P2: 3, 4, 5 3 - 4 (the dependency graph) \ / 5 */ private static int[][] isolatedNodeAssignment = new int[][] { new int[]{1, 2, 4}, new int[]{1, 3, 4}, new int[]{3, 4, 5} }; /* A topology similar to the above one, but leaving broker 2, and when used together with the above one, should form a dependency graph same as the simpleAssignment case */ private static int[][] multiTopicAdditionalAssignment = new int[][] { new int[]{0, 1, 3}, new int[]{1, 3, 4}, new int[]{3, 4, 5} }; @Mock KafkaCluster cluster; ActionEngine engine; org.apache.kafka.common.Node[] kafkaNodes = new org.apache.kafka.common.Node[MAX_NODE_COUNT]; @Before public void init() throws ExecutionException, InterruptedException { Map<String, Node> nodeMap = new HashMap<>(); for (int i = 0; i < MAX_NODE_COUNT; i++) { String idString = Integer.toString(i); NodeInfo nodeInfo = new NodeInfo(); kafkaNodes[i] = new org.apache.kafka.common.Node(i, idString, 9092); nodeInfo.setNodeId(idString); KafkaBroker broker = new KafkaBroker(cluster, nodeInfo, null); nodeMap.put(idString, broker); } Mockito.when(cluster.getNodeMap()).thenReturn(nodeMap); assertNotNull(cluster); engine = new TestActionEngine(cluster); } private KafkaTopicDescription getTopicAssignments(String topic, int[][] assignments){ Map<Integer, KafkaTopicPartitionInfo> topicPartitionInfoMap = new HashMap<>(); for (int i = 0; i < assignments.length; i++) { int[] partitionAssignment = assignments[i]; int leader = partitionAssignment[0]; List<org.apache.kafka.common.Node> nodeList = Arrays.stream(partitionAssignment).mapToObj(id -> kafkaNodes[id]).collect( Collectors.toList()); KafkaTopicPartitionInfo ktpi = new KafkaTopicPartitionInfo(new TopicPartitionInfo(i, kafkaNodes[leader], nodeList, nodeList)); topicPartitionInfoMap.put(i, ktpi); } return new KafkaTopicDescription(topic, false, topicPartitionInfoMap); } private void setSingleTopic() throws Exception { Map<String, KafkaTopicDescription> descriptions = new HashMap<>(); descriptions.put(TEST_TOPICS[0], getTopicAssignments(TEST_TOPICS[0], simpleAssignment)); Mockito.when(cluster.getTopicDescriptionFromKafka()).thenReturn(descriptions); } private void setIsolatedNodeSingleTopic() throws Exception { Map<String, KafkaTopicDescription> descriptions = new HashMap<>(); descriptions.put(TEST_TOPICS[0], getTopicAssignments(TEST_TOPICS[0], isolatedNodeAssignment)); Mockito.when(cluster.getTopicDescriptionFromKafka()).thenReturn(descriptions); } private void setMultiTopics() throws Exception { Map<String, KafkaTopicDescription> descriptions = new HashMap<>(); descriptions.put(TEST_TOPICS[0], getTopicAssignments(TEST_TOPICS[0], isolatedNodeAssignment)); descriptions.put(TEST_TOPICS[1], getTopicAssignments(TEST_TOPICS[1], multiTopicAdditionalAssignment)); Mockito.when(cluster.getTopicDescriptionFromKafka()).thenReturn(descriptions); } @Test public void testSimpleGenerateDependencyGraph() throws Exception { setSingleTopic(); ConcurrentKafkaAction action = new TestConcurrentNoOpAction(); Map<String, Set<String>> dependencyGraph = action.generateDependencyGraph(cluster, cluster.getNodeMap().keySet()); assertEquals(Sets.newHashSet("0", "1", "3"), dependencyGraph.get("0")); assertEquals(Sets.newHashSet("0", "1", "2", "3", "4"), dependencyGraph.get("1")); assertEquals(Sets.newHashSet("1", "2", "4"), dependencyGraph.get("2")); assertEquals(Sets.newHashSet("0", "1", "3", "4", "5"), dependencyGraph.get("3")); assertEquals(Sets.newHashSet("1", "2", "3", "4", "5"), dependencyGraph.get("4")); assertEquals(Sets.newHashSet("3", "4", "5"), dependencyGraph.get("5")); } @Test public void testIsolatedNodeGenerateDependencyGraph() throws Exception { setIsolatedNodeSingleTopic(); ConcurrentKafkaAction action = new TestConcurrentNoOpAction(); Map<String, Set<String>> dependencyGraph = action.generateDependencyGraph(cluster, cluster.getNodeMap().keySet()); assertEquals(Sets.newHashSet("0"), dependencyGraph.get("0")); assertEquals(Sets.newHashSet("1", "2", "3", "4"), dependencyGraph.get("1")); assertEquals(Sets.newHashSet("1", "2", "4"), dependencyGraph.get("2")); assertEquals(Sets.newHashSet("1", "3", "4", "5"), dependencyGraph.get("3")); assertEquals(Sets.newHashSet("1", "2", "3", "4", "5"), dependencyGraph.get("4")); assertEquals(Sets.newHashSet("3", "4", "5"), dependencyGraph.get("5")); } @Test public void testMultiTopicGenerateDependencyGraph() throws Exception { setMultiTopics(); ConcurrentKafkaAction action = new TestConcurrentNoOpAction(); Map<String, Set<String>> dependencyGraph = action.generateDependencyGraph(cluster, cluster.getNodeMap().keySet()); assertEquals(Sets.newHashSet("0", "1", "3"), dependencyGraph.get("0")); assertEquals(Sets.newHashSet("0", "1", "2", "3", "4"), dependencyGraph.get("1")); assertEquals(Sets.newHashSet("1", "2", "4"), dependencyGraph.get("2")); assertEquals(Sets.newHashSet("0", "1", "3", "4", "5"), dependencyGraph.get("3")); assertEquals(Sets.newHashSet("1", "2", "3", "4", "5"), dependencyGraph.get("4")); assertEquals(Sets.newHashSet("3", "4", "5"), dependencyGraph.get("5")); } @Test public void testSimpleAction() throws Exception { setSingleTopic(); ConcurrentKafkaAction action = new TestConcurrentNoOpAction(); Map<String, Set<String>> dependencyGraph = action.generateDependencyGraph(cluster, cluster.getNodeMap().keySet()); action.initialize(Collections.singletonMap("checkingIntervalMs", 10_000)); engine.dispatch(action); long startTs = System.currentTimeMillis(); while(System.currentTimeMillis() - startTs < 41_000) { checkIfActionsAreDependent(action.getChildren(), dependencyGraph); Thread.sleep(1000); } assertEquals(Action.Status.SUCCEEDED, action.getStatus()); for(Action child : action.getChildren()) { assertEquals(Action.Status.SUCCEEDED, child.getStatus()); } } @Test public void testIsolatedNodeAction() throws Exception { setIsolatedNodeSingleTopic(); ConcurrentKafkaAction action = new TestConcurrentNoOpAction(); Map<String, Set<String>> dependencyGraph = action.generateDependencyGraph(cluster, cluster.getNodeMap().keySet()); action.initialize(Collections.singletonMap("checkingIntervalMs", 10_000)); engine.dispatch(action); long startTs = System.currentTimeMillis(); while(System.currentTimeMillis() - startTs < 41_000) { checkIfActionsAreDependent(action.getChildren(), dependencyGraph); Thread.sleep(1000); } assertEquals(Action.Status.SUCCEEDED, action.getStatus()); for(Action child : action.getChildren()) { assertEquals(Action.Status.SUCCEEDED, child.getStatus()); } } @Test public void testMultiTopicAction() throws Exception { setMultiTopics(); ConcurrentKafkaAction action = new TestConcurrentNoOpAction(); Map<String, Set<String>> dependencyGraph = action.generateDependencyGraph(cluster, cluster.getNodeMap().keySet()); action.initialize(Collections.singletonMap("checkingIntervalMs", 10_000)); engine.dispatch(action); long startTs = System.currentTimeMillis(); while(System.currentTimeMillis() - startTs < 41_000) { checkIfActionsAreDependent(action.getChildren(), dependencyGraph); Thread.sleep(1000); } assertEquals(Action.Status.SUCCEEDED, action.getStatus()); for(Action child : action.getChildren()) { assertEquals(Action.Status.SUCCEEDED, child.getStatus()); } } @Test public void testFailedActionWithNoDraining() throws Exception { setSingleTopic(); Set<String> failIds = Sets.newHashSet("1"); Set<String> remainingIds = Sets.newHashSet("3", "4"); ConcurrentKafkaAction action = new TestConcurrentFailableNoOpAction(); action.setAttribute("failIds", failIds); Map<String, Set<String>> dependencyGraph = action.generateDependencyGraph(cluster, cluster.getNodeMap().keySet()); action.initialize(Collections.singletonMap("checkingIntervalMs", 10_000)); engine.dispatch(action); long startTs = System.currentTimeMillis(); while(System.currentTimeMillis() - startTs < 21_000) { // will fail on the second iteration checkIfActionsAreDependent(action.getChildren(), dependencyGraph); Thread.sleep(1000); } assertEquals(Action.Status.FAILED, action.getStatus()); for(Action child : action.getChildren()) { String nodeId = child.getAttribute(OrionConstants.NODE_ID).getValue(); if (failIds.contains(nodeId)) { assertEquals(Action.Status.FAILED, child.getStatus()); } else if (remainingIds.contains(nodeId)){ fail("node " + nodeId + " should not have started action since it is in remaining nodes: " + failIds); } else { assertEquals(Action.Status.SUCCEEDED, child.getStatus()); } } } @Test public void testFailedActionWithDraining() throws Exception { setSingleTopic(); Set<String> drainIds = Sets.newHashSet("2", "5"); Set<String> failIds = Sets.newHashSet("0"); // 2, 5 should succeed after draining Set<String> remainingIds = Sets.newHashSet("1", "3", "4"); TestConcurrentFailableNoOpAction action = new TestConcurrentFailableNoOpAction(); action.setAttribute("failIds", failIds); Map<String, Set<String>> dependencyGraph = action.generateDependencyGraph(cluster, cluster.getNodeMap().keySet()); action.initialize(Collections.singletonMap("checkingIntervalMs", 5_000)); // shortening for draining to happen engine.dispatch(action); long startTs = System.currentTimeMillis(); while(System.currentTimeMillis() - startTs < 21_000) { // will fail on the first iteration, but will be draining checkIfActionsAreDependent(action.getChildren(), dependencyGraph); Thread.sleep(1000); } assertEquals(drainIds, action.currentNodes); assertEquals(Action.Status.FAILED, action.getStatus()); for(Action child : action.getChildren()) { String nodeId = child.getAttribute(OrionConstants.NODE_ID).getValue(); if (failIds.contains(nodeId)) { assertEquals(Action.Status.FAILED, child.getStatus()); } else if (remainingIds.contains(nodeId)){ fail("node " + nodeId + " should not have started action since it is in remaining nodes: " + failIds); } else { assertEquals(Action.Status.SUCCEEDED, child.getStatus()); } } } @Test public void testMultipleTopic() throws Exception { setMultiTopics(); } private boolean checkIfActionsAreDependent(List<Action> actions, Map<String, Set<String>> dependencyGraph) { Set<String> currentActiveNodes = new HashSet<>(); for (Action action : actions) { if (action.getStatus().equals(Action.Status.RUNNING)) { String nodeId = action.getAttribute(OrionConstants.NODE_ID).getValue(); currentActiveNodes.add(nodeId); } } if (currentActiveNodes.isEmpty()) { return false; } Set<String> cover = new HashSet<>(); for (String node : currentActiveNodes) { if (cover.contains(node)) { return true; } else { cover.addAll(dependencyGraph.get(node)); } } return false; } private static class TestNoOpAction extends Action { @Override public void runAction() throws Exception { Thread.sleep(9_000); markSucceeded(); } @Override public String getName() { return null; } } private static class TestFailableNoOpAction extends Action { @Override public void runAction() throws Exception { if (containsAttribute("failIds")) { Set<String> failIds = getAttribute("failIds").getValue(); String nodeId = getAttribute(OrionConstants.NODE_ID).getValue(); if (failIds.contains(nodeId)) { Thread.sleep(4_000); markFailed("Failed"); return; } } Thread.sleep(9_000); markSucceeded(); } @Override public String getName() { return null; } } private static class TestConcurrentNoOpAction extends ConcurrentKafkaAction { TestConcurrentNoOpAction() { super("noop"); } @Override protected Action getChildAction() { return new TestNoOpAction(); } @Override public boolean failIfNoNodeIds() { return false; } } private static class TestConcurrentFailableNoOpAction extends ConcurrentKafkaAction { private Set<String> currentNodes = new HashSet<>(); TestConcurrentFailableNoOpAction() { super("failable-noop"); } @Override protected boolean handleFailure(Action failedAction, List<Action> currentActions, Set<String> remainingNodes) { currentNodes = currentActions.stream().map(a -> a.getAttribute(OrionConstants.NODE_ID).getValue().toString()).collect(Collectors.toSet()); return super.handleFailure(failedAction, currentActions, remainingNodes); } @Override protected Action getChildAction() { Action action = new TestFailableNoOpAction(); action.copyAttributeFrom(this, "failIds"); return action; } @Override public boolean failIfNoNodeIds() { return false; } } private static class TestActionEngine extends ActionEngine { TestActionEngine(Cluster cluster) { super(cluster, null, null, null); actionExecutors = new ThreadPoolExecutor(1, 1, 0, TimeUnit.NANOSECONDS, new LinkedBlockingQueue<>()); childActionExecutors = new ThreadPoolExecutor(8, 8, 0, TimeUnit.NANOSECONDS, new LinkedBlockingQueue<>()); } @Override public void dispatch(Action action) { action.setParent(true); action.setEngine(this); Future<?> future = actionExecutors.submit(action); action.setInternalFuture(future); } // skips config initialization since there won't be any for tests public void dispatchChild(Action parent, Action child) throws Exception { child.setOwner(parent.getOwner()); child.setEngine(this); child.setParent(false); Future<?> future = childActionExecutors.submit(child); child.setInternalFuture(future); } } }
3e058008348802c113ea336411c2cb51e88de935
1,018
java
Java
helium/src/main/groovy/com/stanfy/helium/handler/codegen/objectivec/ObjcEntitiesOptions.java
nolia/helium
bd9a5157b2ec7c0fac0ca1c081db94628d850143
[ "Apache-2.0" ]
null
null
null
helium/src/main/groovy/com/stanfy/helium/handler/codegen/objectivec/ObjcEntitiesOptions.java
nolia/helium
bd9a5157b2ec7c0fac0ca1c081db94628d850143
[ "Apache-2.0" ]
null
null
null
helium/src/main/groovy/com/stanfy/helium/handler/codegen/objectivec/ObjcEntitiesOptions.java
nolia/helium
bd9a5157b2ec7c0fac0ca1c081db94628d850143
[ "Apache-2.0" ]
null
null
null
25.45
85
0.727898
2,300
package com.stanfy.helium.handler.codegen.objectivec; import com.stanfy.helium.handler.codegen.GeneratorOptions; import java.util.HashMap; import java.util.Map; /** * Options for a handler that generated Obj-C entities. */ public class ObjcEntitiesOptions extends GeneratorOptions { /** Class names prefix. */ private String prefix = "HE"; /** * Map that contains mappings for custom Helium Types. i.e. timestamp -> NSDate. * It is used for generating custom(complex) types. */ private Map<String, String> customTypesMappings = new HashMap<String, String>(); public void setPrefix(final String prefix) { this.prefix = prefix; } /** Returns prefix for all files those would be generated */ public String getPrefix() { return prefix; } public void setCustomTypesMappings(final Map<String, String> customTypesMappings) { this.customTypesMappings = customTypesMappings; } public Map<String, String> getCustomTypesMappings() { return customTypesMappings; } }
3e0580302f56d58d3b9610da6bc44f6ed448e42d
3,284
java
Java
dhis-2/dhis-api/src/main/java/org/hisp/dhis/sqlview/ResourceTableNameMap.java
hispindia/MAHARASHTRA-2.13
f50ec5b3ca2c5fabb43058166fd0c0fbbaa946a9
[ "BSD-3-Clause" ]
null
null
null
dhis-2/dhis-api/src/main/java/org/hisp/dhis/sqlview/ResourceTableNameMap.java
hispindia/MAHARASHTRA-2.13
f50ec5b3ca2c5fabb43058166fd0c0fbbaa946a9
[ "BSD-3-Clause" ]
null
null
null
dhis-2/dhis-api/src/main/java/org/hisp/dhis/sqlview/ResourceTableNameMap.java
hispindia/MAHARASHTRA-2.13
f50ec5b3ca2c5fabb43058166fd0c0fbbaa946a9
[ "BSD-3-Clause" ]
null
null
null
40.54321
82
0.721985
2,301
package org.hisp.dhis.sqlview; /* * Copyright (c) 2004-2013, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project 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 OWNER 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. */ import java.util.HashMap; import java.util.Map; /** * @author Dang Duy Hieu * @version $Id ResourceTableNameMap.java Aug 10, 2010$ */ public class ResourceTableNameMap { private static Map<String, String> resourceNameMap; private static Map<String, String> ignoredNameMap; static { resourceNameMap = new HashMap<String, String>(); ignoredNameMap = new HashMap<String, String>(); resourceNameMap.put( "_cocn", "_categoryoptioncomboname" ); resourceNameMap.put( "_cs", "_categorystructure" ); resourceNameMap.put( "_degss", "_dataelementgroupsetstructure" ); resourceNameMap.put( "_icgss", "_indicatorgroupsetstructure" ); resourceNameMap.put( "_ous", "_orgunitstructure" ); resourceNameMap.put( "_ougss", "_orgunitgroupsetstructure" ); resourceNameMap.put( "_oustgss", "_organisationunitgroupsetstructure" ); ignoredNameMap.put( "_users", "users" ); ignoredNameMap.put( "_uinfo", "userinfo" ); ignoredNameMap.put( "_patient", "patient" ); ignoredNameMap.put( "_patientid", "patientidentifier" ); ignoredNameMap.put( "_patientattr", "patientattribute" ); ignoredNameMap.put( "_relationship", "relationship.*" ); ignoredNameMap.put( "_caseaggrcondition", "caseaggregationcondition" ); } public static String getResourceNameByAlias( String alias ) { return resourceNameMap.get( alias ); } public static String getIgnoredNameByAlias( String alias ) { return ignoredNameMap.get( alias ); } public static Map<String, String> getIgnoredNameMap() { return ignoredNameMap; } }
3e05815f32973d7e706b95fc426e683de873544c
1,529
java
Java
src/test/java/com/kaczmarczyks/twotowers/TwoTowersApplicationTests.java
kaczmarczyks/two-towers
a06822a757e8aee2c8e269e7fe9e3287bc522dd2
[ "MIT" ]
null
null
null
src/test/java/com/kaczmarczyks/twotowers/TwoTowersApplicationTests.java
kaczmarczyks/two-towers
a06822a757e8aee2c8e269e7fe9e3287bc522dd2
[ "MIT" ]
1
2022-01-21T23:25:50.000Z
2022-01-21T23:25:50.000Z
src/test/java/com/kaczmarczyks/twotowers/TwoTowersApplicationTests.java
kaczmarczyks/two-towers
a06822a757e8aee2c8e269e7fe9e3287bc522dd2
[ "MIT" ]
null
null
null
26.824561
66
0.739699
2,302
package com.kaczmarczyks.twotowers; import com.kaczmarczyks.twotowers.first.EntityOne; import com.kaczmarczyks.twotowers.first.EntityOneRepository; import com.kaczmarczyks.twotowers.second.EntityTwo; import com.kaczmarczyks.twotowers.second.EntityTwoRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @SpringBootTest public class TwoTowersApplicationTests { @Autowired private EntityOneRepository entityOneRepository; @Autowired private EntityTwoRepository entityTwoRepository; @Test public void contextLoads() { } @Test @Transactional("firstTransactionManager") public void entityOneIsSaved() { //given EntityOne entityOne = new EntityOne(null, "propertyOne1"); //when entityOneRepository.save(entityOne); //then assertThat(entityOne.getId()).isNotNull(); } @Test @Transactional("secondTransactionManager") public void entityTwoIsSaved() { //given EntityTwo entityTwo = new EntityTwo(null, "propertyTwo1"); //when entityTwoRepository.save(entityTwo); //then assertThat(entityTwo.getId()).isNotNull(); } }
3e058210fd66fa197fab1a3c40c2dcc53d06db6e
2,671
java
Java
business/oauth2-service/src/main/java/com/study/shop/business/configure/WebSecurityConfiguration.java
yhuihu/shop_api
890320848cf5a1334a1679308579844923069611
[ "Apache-2.0" ]
1
2020-12-03T14:42:52.000Z
2020-12-03T14:42:52.000Z
business/oauth2-service/src/main/java/com/study/shop/business/configure/WebSecurityConfiguration.java
yhuihu/shop_api
890320848cf5a1334a1679308579844923069611
[ "Apache-2.0" ]
null
null
null
business/oauth2-service/src/main/java/com/study/shop/business/configure/WebSecurityConfiguration.java
yhuihu/shop_api
890320848cf5a1334a1679308579844923069611
[ "Apache-2.0" ]
1
2020-12-03T14:42:59.000Z
2020-12-03T14:42:59.000Z
35.144737
107
0.766005
2,303
package com.study.shop.business.configure; import com.study.shop.business.service.UserDetailsServiceImpl; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; /** * @author Tiger * @date 2019-09-11 * @see com.study.shop.business.configure **/ @Configuration @EnableWebSecurity @EnableResourceServer @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true) public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean @Override public UserDetailsService userDetailsServiceBean() throws Exception { return new UserDetailsServiceImpl(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsServiceBean()); } /** * 用于支持 password 模式 * * @return AuthenticationManager * @throws Exception */ @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override public void configure(WebSecurity web) throws Exception { //不拦截登录接口 web.ignoring() .antMatchers("/user/login"); } /** * 将授权访问配置改为注解方式 @PreAuthorize * * @see */ @Override protected void configure(HttpSecurity http) throws Exception { http.exceptionHandling() .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); } }
3e058237dcf98f979523fb6516c048e2309dd344
152
java
Java
app/src/main/java/net/arvin/wanandroid/entities/events/ChangeNightMode.java
arvinljw/WanAndroid
ca6aeedf0d14cb9ab7cb97c1eda4bed409d6602a
[ "Apache-2.0" ]
53
2018-12-07T05:34:58.000Z
2022-01-08T00:44:55.000Z
app/src/main/java/net/arvin/wanandroid/entities/events/ChangeNightMode.java
arvinljw/WanAndroid
ca6aeedf0d14cb9ab7cb97c1eda4bed409d6602a
[ "Apache-2.0" ]
3
2019-01-05T03:46:44.000Z
2019-03-25T03:07:32.000Z
app/src/main/java/net/arvin/wanandroid/entities/events/ChangeNightMode.java
arvinljw/WanAndroid
ca6aeedf0d14cb9ab7cb97c1eda4bed409d6602a
[ "Apache-2.0" ]
14
2019-01-04T07:51:50.000Z
2020-12-10T16:51:58.000Z
15.2
45
0.703947
2,304
package net.arvin.wanandroid.entities.events; /** * Created by arvinljw on 2018/12/4 18:15 * Function: * Desc: */ public class ChangeNightMode { }
3e05825d016fac09bc55f73c0d1761429d5e013e
5,103
java
Java
6357_Code/src/main/scala/chapter2/DataUtilities.java
PacktPublishing/Deep-Learning-with-Apache-Spark
ef8cab4f6d3e26ea8edea26d814f4d338e6dbb11
[ "MIT" ]
2
2019-02-24T02:02:30.000Z
2021-10-02T03:20:02.000Z
6357_Code/src/main/scala/chapter2/DataUtilities.java
PacktPublishing/Deep-Learning-with-Apache-Spark
ef8cab4f6d3e26ea8edea26d814f4d338e6dbb11
[ "MIT" ]
null
null
null
6357_Code/src/main/scala/chapter2/DataUtilities.java
PacktPublishing/Deep-Learning-with-Apache-Spark
ef8cab4f6d3e26ea8edea26d814f4d338e6dbb11
[ "MIT" ]
null
null
null
37.522059
115
0.676857
2,305
package chapter2; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import org.apache.commons.io.FilenameUtils; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; public class DataUtilities { private static Logger log = LoggerFactory.getLogger(DataUtilities.class); /** Data URL for downloading */ public static final String DATA_URL = "http://github.com/myleott/mnist_png/raw/master/mnist_png.tar.gz"; /** Location to save and extract the training/testing data */ public static final String DATA_PATH = FilenameUtils.concat(System.getProperty("java.io.tmpdir"), "dl4j_Mnist/"); protected static void downloadData() throws Exception { // Create directory if required File directory = new File(DATA_PATH); if (!directory.exists()) directory.mkdir(); // Download file: String archizePath = DATA_PATH + "/mnist_png.tar.gz"; File archiveFile = new File(archizePath); String extractedPath = DATA_PATH + "mnist_png"; File extractedFile = new File(extractedPath); if (!archiveFile.exists()) { log.info("Starting data download (15MB)..."); getMnistPNG(); //Extract tar.gz file to output directory DataUtilities.extractTarGz(archizePath, DATA_PATH); } else { //Assume if archive (.tar.gz) exists, then data has already been extracted log.info("Data (.tar.gz file) already exists at {}", archiveFile.getAbsolutePath()); if (!extractedFile.exists()) { //Extract tar.gz file to output directory DataUtilities.extractTarGz(archizePath, DATA_PATH); } else { log.info("Data (extracted) already exists at {}", extractedFile.getAbsolutePath()); } } } public static void getMnistPNG() throws IOException { String tmpDirStr = System.getProperty("java.io.tmpdir"); String archizePath = DATA_PATH + "/mnist_png.tar.gz"; if (tmpDirStr == null) { throw new IOException("System property 'java.io.tmpdir' does specify a tmp dir"); } File f = new File(archizePath); if (!f.exists()) { DataUtilities.downloadFile(DATA_URL, archizePath); log.info("Data downloaded to ", archizePath); } else { log.info("Using existing directory at ", f.getAbsolutePath()); } } /** * Download a remote file if it doesn't exist. * @param remoteUrl URL of the remote file. * @param localPath Where to download the file. * @return True if and only if the file has been downloaded. * @throws Exception IO error. */ public static boolean downloadFile(String remoteUrl, String localPath) throws IOException { boolean downloaded = false; if (remoteUrl == null || localPath == null) return downloaded; File file = new File(localPath); if (!file.exists()) { file.getParentFile().mkdirs(); HttpClientBuilder builder = HttpClientBuilder.create(); CloseableHttpClient client = builder.build(); try (CloseableHttpResponse response = client.execute(new HttpGet(remoteUrl))) { HttpEntity entity = response.getEntity(); if (entity != null) { try (FileOutputStream outstream = new FileOutputStream(file)) { entity.writeTo(outstream); outstream.flush(); } } } downloaded = true; } if (!file.exists()) throw new IOException("File doesn't exist: " + localPath); return downloaded; } /** * Extract a "tar.gz" file into a local folder. * @param inputPath Input file path. * @param outputPath Output directory path. * @throws IOException IO error. */ public static void extractTarGz(String inputPath, String outputPath) throws IOException { if (inputPath == null || outputPath == null) return; final int bufferSize = 4096; if (!outputPath.endsWith("" + File.separatorChar)) outputPath = outputPath + File.separatorChar; try (TarArchiveInputStream tais = new TarArchiveInputStream( new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(inputPath))))) { TarArchiveEntry entry; while ((entry = (TarArchiveEntry) tais.getNextEntry()) != null) { if (entry.isDirectory()) { new File(outputPath + entry.getName()).mkdirs(); } else { int count; byte data[] = new byte[bufferSize]; FileOutputStream fos = new FileOutputStream(outputPath + entry.getName()); BufferedOutputStream dest = new BufferedOutputStream(fos, bufferSize); while ((count = tais.read(data, 0, bufferSize)) != -1) { dest.write(data, 0, count); } dest.close(); } } } } }
3e0582e298f411b5528985015ef1c0d409fb7896
4,294
java
Java
cosky-discovery/src/test/java/me/ahoo/cosky/discovery/RedisServiceRegistryTest.java
Ahoo-Wang/CoSky
32c1d787be161d1fa242f76cec9003d3f39b77a5
[ "Apache-2.0" ]
32
2021-05-31T01:55:10.000Z
2022-03-17T06:10:12.000Z
cosky-discovery/src/test/java/me/ahoo/cosky/discovery/RedisServiceRegistryTest.java
Ahoo-Wang/CoSky
32c1d787be161d1fa242f76cec9003d3f39b77a5
[ "Apache-2.0" ]
12
2021-05-31T09:44:00.000Z
2022-03-09T14:08:26.000Z
cosky-discovery/src/test/java/me/ahoo/cosky/discovery/RedisServiceRegistryTest.java
Ahoo-Wang/CoSky
32c1d787be161d1fa242f76cec9003d3f39b77a5
[ "Apache-2.0" ]
10
2021-06-03T01:10:33.000Z
2022-03-18T06:09:57.000Z
32.515152
104
0.667288
2,306
/* * Copyright [2021-present] [ahoo wang <[email protected]> (https://github.com/Ahoo-Wang)]. * 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 me.ahoo.cosky.discovery; import lombok.SneakyThrows; import lombok.var; import me.ahoo.cosky.discovery.redis.RedisServiceRegistry; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; /** * @author ahoo wang */ public class RedisServiceRegistryTest extends BaseOnRedisClientTest { private final static String namespace = "test_svc_csy"; private ServiceInstance testInstance; private ServiceInstance testFixedInstance; private RedisServiceRegistry redisServiceRegistry; @BeforeAll private void init() { testInstance = TestServiceInstance.TEST_INSTANCE; testFixedInstance = TestServiceInstance.TEST_FIXED_INSTANCE; var registryProperties = new RegistryProperties(); registryProperties.setInstanceTtl(10); redisServiceRegistry = new RedisServiceRegistry(registryProperties, redisConnection.reactive()); } @Test public void register() { clearTestData(namespace); var result = redisServiceRegistry.register(namespace, testInstance).block(); Assertions.assertTrue(result); } @Test public void renew() { var result = redisServiceRegistry.renew(namespace, testInstance).block(); Assertions.assertTrue(result); } @Test public void renewFixed() { var result = redisServiceRegistry.renew(namespace, testFixedInstance).block(); Assertions.assertFalse(result); } @Test public void registerFixed() { var result = redisServiceRegistry.register(namespace, testFixedInstance).block(); Assertions.assertTrue(result); } @Test public void deregister() { redisServiceRegistry.deregister(namespace, testInstance).block(); } private final static int REPEATED_SIZE = 60000; @Test public void registerRepeatedSync() { for (int i = 0; i < 20; i++) { redisServiceRegistry.register(namespace, testInstance).block(); } } @SneakyThrows // @Test public void registerRepeatedAsync() { var futures = new Mono[REPEATED_SIZE]; for (int i = 0; i < REPEATED_SIZE; i++) { var future = redisServiceRegistry.register(testInstance); futures[i] = future; } Mono.when(futures).block(); } private final static int THREAD_COUNT = 5; // @Test public void registerRepeatedMultiple() throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(THREAD_COUNT); for (int thNum = 0; thNum < THREAD_COUNT; thNum++) { new Thread(() -> { registerRepeatedAsync(); countDownLatch.countDown(); }).start(); } countDownLatch.await(); } // @Test public void deregisterRepeatedAsync() { var futures = new Mono[REPEATED_SIZE]; for (int i = 0; i < REPEATED_SIZE; i++) { futures[i] = redisServiceRegistry.deregister(testInstance); } Mono.when(futures).block(); } // @Test public void deregisterRepeatedMultiple() throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(THREAD_COUNT); for (int thNum = 0; thNum < THREAD_COUNT; thNum++) { new Thread(() -> { deregisterRepeatedAsync(); countDownLatch.countDown(); }).start(); } countDownLatch.await(); } }
3e0583bde7edd6ee37cfd1e22246230d90cef4c7
633
java
Java
lib/src/main/java/processorworkflow/AbstractComposer.java
matfax/processor-workflow
da43966acdf9d5d7177b180fc8d9e0e22cf694f4
[ "MIT" ]
null
null
null
lib/src/main/java/processorworkflow/AbstractComposer.java
matfax/processor-workflow
da43966acdf9d5d7177b180fc8d9e0e22cf694f4
[ "MIT" ]
103
2018-09-26T11:38:04.000Z
2021-07-29T08:13:52.000Z
lib/src/main/java/processorworkflow/AbstractComposer.java
matfax/processor-workflow
da43966acdf9d5d7177b180fc8d9e0e22cf694f4
[ "MIT" ]
null
null
null
20.548387
65
0.66248
2,307
package processorworkflow; import com.squareup.javapoet.JavaFile; import java.util.ArrayList; import java.util.List; /** * @author Lukasz Piliszczuk - [email protected] */ public abstract class AbstractComposer<T_Model> { private List<T_Model> specs; public AbstractComposer(List<T_Model> specs) { this.specs = specs; } public List<JavaFile> compose() { List<JavaFile> javaFiles = new ArrayList<>(specs.size()); for (T_Model spec : specs) { javaFiles.add(compose(spec)); } return javaFiles; } protected abstract JavaFile compose(T_Model spec); }
3e05855d7cb0ae6c9ff37fd68a4479572bc3c4e9
3,907
java
Java
src/main/java/org/mitre/taxii/query/PythonTextOutput.java
w6030a/java-taxii
64bde3731ab4ec5c7fd923e4db7cf7c595ffd135
[ "BSD-3-Clause" ]
18
2015-01-06T21:35:36.000Z
2020-10-19T09:07:05.000Z
src/main/java/org/mitre/taxii/query/PythonTextOutput.java
w6030a/java-taxii
64bde3731ab4ec5c7fd923e4db7cf7c595ffd135
[ "BSD-3-Clause" ]
8
2015-02-06T15:16:54.000Z
2017-12-21T22:43:54.000Z
src/main/java/org/mitre/taxii/query/PythonTextOutput.java
w6030a/java-taxii
64bde3731ab4ec5c7fd923e4db7cf7c595ffd135
[ "BSD-3-Clause" ]
13
2015-03-26T17:36:26.000Z
2020-07-31T20:39:49.000Z
38.683168
119
0.541848
2,308
/* * 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 org.mitre.taxii.query; /** * * @author jasenj1 */ public class PythonTextOutput { private static final String STD_INDENT = " "; // A "Standard Indent" to use for to_text() methods public static String toText(Object obj) { return toText(obj,""); } public static String toText(Object obj, String line_prepend) { String s = new String(); if (null == line_prepend) { line_prepend = ""; } if (obj instanceof DefaultQuery) { DefaultQuery self = (DefaultQuery)obj; // The opening line is rendered by taxii.messages.xml11's PythonOutputText. // s = super(DefaultQuery, self).to_text(line_prepend) s += line_prepend + String.format(" Targeting Expression ID: %s\n", self.getTargetingExpressionId()); s += toText(self.getCriteria(), line_prepend); return s; } if (obj instanceof CriteriaType) { CriteriaType self = (CriteriaType)obj; s = line_prepend + "=== Criteria ===\n"; s += line_prepend + String.format(" Operator: %s\n", self.getOperator()); for (CriteriaType criteria : self.getCriterias()) { s += toText(criteria, line_prepend + STD_INDENT); } for (CriterionType criterion : self.getCriterions()) { s += toText(criterion, line_prepend + STD_INDENT); } return s; } if (obj instanceof CriterionType) { CriterionType self = (CriterionType)obj; s = line_prepend + "=== Criterion ===\n"; s += line_prepend + String.format(" Negate: %s\n", booleanString(self.isNegate())); s += line_prepend + String.format(" Target: %s\n", self.getTarget()); s += toText(self.getTest(), line_prepend + STD_INDENT); return s; } if (obj instanceof TestType) { TestType self = (TestType)obj; s = line_prepend + "=== Test ==\n"; s += line_prepend + String.format(" Capability ID: %s\n", self.getCapabilityId()); s += line_prepend + String.format(" Relationship: %s\n", self.getRelationship()); for (ParameterType parameter : self.getParameters()) { s += line_prepend + String.format(" Parameter: %s = %s\n", parameter.getName(), parameter.getValue()); } return s; } if (obj instanceof TargetingExpressionInfoType) { TargetingExpressionInfoType self = (TargetingExpressionInfoType)obj; s = line_prepend + "=== Targeting Expression Info ===\n"; s += line_prepend + String.format(" Targeting Expression ID: %s\n", self.getTargetingExpressionId()); for (String scope : self.getPreferredScopes()) { s += line_prepend + String.format(" Preferred Scope: %s\n",scope); } for (String scope : self.getAllowedScopes()) { s += line_prepend + String.format(" Allowed Scope: %s\n",scope); } return s; } if (s.isEmpty()) { s = "Sorry, I do not know how to render a " + obj.getClass().getName(); } return s; } /** * Turn a Boolean into a Python string representation. * * @ return "None", "True", or "False". */ private static String booleanString(Boolean value) { if (null == value) return "None"; return value ? "True" : "False"; } }
3e058586ac9b0e006fe341525604a31bc4fdbed3
2,539
java
Java
lib/src/main/xtend-gen/processingModule/SDFActorProcessingModule.java
Rojods/CInTSyDe
b026d7e59b7707b0d43032a74a085875b43dd281
[ "MIT" ]
1
2022-03-29T13:16:25.000Z
2022-03-29T13:16:25.000Z
lib/src/main/xtend-gen/processingModule/SDFActorProcessingModule.java
Rojods/CInTSyDe
b026d7e59b7707b0d43032a74a085875b43dd281
[ "MIT" ]
null
null
null
lib/src/main/xtend-gen/processingModule/SDFActorProcessingModule.java
Rojods/CInTSyDe
b026d7e59b7707b0d43032a74a085875b43dd281
[ "MIT" ]
null
null
null
32.139241
98
0.659709
2,309
package processingModule; import forsyde.io.java.core.ForSyDeSystemGraph; import forsyde.io.java.core.Vertex; import forsyde.io.java.typed.viewers.moc.sdf.SDFActor; import generator.Generator; import java.util.HashSet; import java.util.Set; import java.util.function.Consumer; import java.util.function.Predicate; import template.templateInterface.ActorTemplate; import utils.Query; import utils.Save; @SuppressWarnings("all") public class SDFActorProcessingModule implements ModuleInterface { private Set<ActorTemplate> templates; public SDFActorProcessingModule() { HashSet<ActorTemplate> _hashSet = new HashSet<ActorTemplate>(); this.templates = _hashSet; } @Override public void create() { final Predicate<Vertex> _function = (Vertex v) -> { return (SDFActor.conforms(v)).booleanValue(); }; final Consumer<Vertex> _function_1 = (Vertex v) -> { this.process(v); }; Generator.model.vertexSet().stream().filter(_function).forEach(_function_1); } public void process(final Vertex v) { final Consumer<ActorTemplate> _function = (ActorTemplate t) -> { this.save(Generator.model, v, t); }; this.templates.stream().forEach(_function); } public void add(final ActorTemplate t) { this.templates.add(t); } public boolean save(final ForSyDeSystemGraph model, final Vertex actor, final ActorTemplate t) { boolean _xblockexpression = false; { if ((Generator.platform == 1)) { String _create = t.create(actor); String _savePath = t.savePath(); String _plus = ((Generator.root + "/tile/") + _savePath); Save.save(_create, _plus); } if ((Generator.platform == 2)) { Vertex tile = Query.findTile(Generator.model, actor); if ((tile != null)) { String _create_1 = t.create(actor); String _identifier = tile.getIdentifier(); String _plus_1 = ((Generator.root + "/") + _identifier); String _plus_2 = (_plus_1 + "/"); String _savePath_1 = t.savePath(); String _plus_3 = (_plus_2 + _savePath_1); Save.save(_create_1, _plus_3); } } boolean _xifexpression = false; if ((Generator.platform == 3)) { String _create_2 = t.create(actor); String _savePath_2 = t.savePath(); String _plus_4 = (Generator.root + _savePath_2); _xifexpression = Save.save(_create_2, _plus_4); } _xblockexpression = _xifexpression; } return _xblockexpression; } }
3e0585a064006e6bc0e1b0b773d988ada4232d5a
4,051
java
Java
aws-java-sdk-codebuild/src/main/java/com/amazonaws/services/codebuild/model/transform/TestCaseMarshaller.java
pedrolauro/aws-sdk-java
f66f01bd1eed08a1ed12d8fe5460628a65a1acc6
[ "Apache-2.0" ]
null
null
null
aws-java-sdk-codebuild/src/main/java/com/amazonaws/services/codebuild/model/transform/TestCaseMarshaller.java
pedrolauro/aws-sdk-java
f66f01bd1eed08a1ed12d8fe5460628a65a1acc6
[ "Apache-2.0" ]
1
2020-02-12T01:54:01.000Z
2020-02-12T01:54:11.000Z
aws-java-sdk-codebuild/src/main/java/com/amazonaws/services/codebuild/model/transform/TestCaseMarshaller.java
pedrolauro/aws-sdk-java
f66f01bd1eed08a1ed12d8fe5460628a65a1acc6
[ "Apache-2.0" ]
1
2020-02-12T01:46:54.000Z
2020-02-12T01:46:54.000Z
52.61039
159
0.754135
2,310
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.codebuild.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.codebuild.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * TestCaseMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class TestCaseMarshaller { private static final MarshallingInfo<String> REPORTARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("reportArn").build(); private static final MarshallingInfo<String> TESTRAWDATAPATH_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("testRawDataPath").build(); private static final MarshallingInfo<String> PREFIX_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("prefix").build(); private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("name").build(); private static final MarshallingInfo<String> STATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("status").build(); private static final MarshallingInfo<Long> DURATIONINNANOSECONDS_BINDING = MarshallingInfo.builder(MarshallingType.LONG) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("durationInNanoSeconds").build(); private static final MarshallingInfo<String> MESSAGE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("message").build(); private static final MarshallingInfo<java.util.Date> EXPIRED_BINDING = MarshallingInfo.builder(MarshallingType.DATE) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("expired").timestampFormat("unixTimestamp").build(); private static final TestCaseMarshaller instance = new TestCaseMarshaller(); public static TestCaseMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(TestCase testCase, ProtocolMarshaller protocolMarshaller) { if (testCase == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(testCase.getReportArn(), REPORTARN_BINDING); protocolMarshaller.marshall(testCase.getTestRawDataPath(), TESTRAWDATAPATH_BINDING); protocolMarshaller.marshall(testCase.getPrefix(), PREFIX_BINDING); protocolMarshaller.marshall(testCase.getName(), NAME_BINDING); protocolMarshaller.marshall(testCase.getStatus(), STATUS_BINDING); protocolMarshaller.marshall(testCase.getDurationInNanoSeconds(), DURATIONINNANOSECONDS_BINDING); protocolMarshaller.marshall(testCase.getMessage(), MESSAGE_BINDING); protocolMarshaller.marshall(testCase.getExpired(), EXPIRED_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
3e0586270ce1b2ed5ab3e8ff524543a68aaa15f1
9,384
java
Java
functional/SyntheticGCWorkload/src/net/adoptopenjdk/casa/workload_sessions/Event.java
hangshao0/openjdk-tests
7e0b74c8931e957c68c953ad798fdd7cc96f329b
[ "Apache-2.0" ]
96
2017-05-23T15:47:36.000Z
2021-04-25T17:26:02.000Z
functional/SyntheticGCWorkload/src/net/adoptopenjdk/casa/workload_sessions/Event.java
hangshao0/openjdk-tests
7e0b74c8931e957c68c953ad798fdd7cc96f329b
[ "Apache-2.0" ]
2,005
2017-04-25T13:25:57.000Z
2021-04-29T07:21:36.000Z
functional/SyntheticGCWorkload/src/net/adoptopenjdk/casa/workload_sessions/Event.java
hangshao0/openjdk-tests
7e0b74c8931e957c68c953ad798fdd7cc96f329b
[ "Apache-2.0" ]
173
2017-04-21T15:33:50.000Z
2021-04-28T22:39:50.000Z
23.577889
121
0.624467
2,311
/******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package net.adoptopenjdk.casa.workload_sessions; import java.io.PrintStream; import net.adoptopenjdk.casa.event.EventHandler; import net.adoptopenjdk.casa.util.Utilities; import net.adoptopenjdk.casa.verbose_gc_parser.VerboseUtil; /** * Error handling enum used for reporting errors to the user in the benchmark. * * * */ enum Event implements EventHandler { BAD_ARGUMENTS (10, null, Action.CLEAN_SHUTDOWN), INTERRUPT (1 , "INTERRUPTED: ", Action.CLEAN_SHUTDOWN), NOTICE (0 , "NOTICE: ", Action.MESSAGE), WARNING (0 , "WARNING: ", Action.MESSAGE), SUCCESS (0 , null, Action.CLEAN_SHUTDOWN), // Thrown in fatal situations where execution of java code required to shutdown is likely to succeed. FATAL_ERROR (-1, "FATAL ERROR: ", Action.IMMEDIATE_SHUTDOWN), // Thrown in emergencies when the VM must shutdown immediately. Will perform an orderly shutdown if possible. (eg: OOM) RUNTIME_EXCEPTION (-2, "RUNTIME EXCEPTION: ", Action.RUNTIME_EXCEPTION), // ASSERTION (-3, "FAILED ASSERTION: ", Action.IMMEDIATE_SHUTDOWN), PARSE_ERROR (-4, "PARSE ERROR: ", Action.CLEAN_SHUTDOWN); private final int FAILED_ISSUE_CODE = -128; public final int USER_EXCEPTION_CODE = -64; // The code upon which to exit, should the action call for it. private final int code; // A prefix to describe the type of event. private final String messagePrefix; // All information printed is sent to this stream. private final PrintStream errorStream; // A formatted message that may include the prefix and information from the throwable. private String message; // The event may have been issued due to something being thrown. private Throwable associatedThrowable; // Informs on the action which should be taken when this event is issued. private Action action; // Set the debug flag to see stack traces on any event. private static final boolean DEBUG = false; /** * Describes the nature of the event and informs on * the type of action that should be taken. * * */ private enum Action { /** * Just print something. */ MESSAGE (), /** * Shutdown cleanly, allowing threads to join, etc... */ CLEAN_SHUTDOWN (), /** * Shutdown without joining threads or waiting for anything to finish. */ IMMEDIATE_SHUTDOWN (), /** * Throw a runtime exception to get out fast. May attempt to shutdown gracefully first. */ RUNTIME_EXCEPTION (); /** * Does this event entail a shutdown? * * @return */ public boolean isFatal() { return equals(Action.IMMEDIATE_SHUTDOWN) || equals(Action.RUNTIME_EXCEPTION) || equals(Action.CLEAN_SHUTDOWN); } /** * Should the name of the associated Throwable be printed? * * @return */ public boolean printExceptionName() { return printStackTrace(); } /** * Should a stack trace be printed? * * @return */ public boolean printStackTrace() { return equals(Action.IMMEDIATE_SHUTDOWN) || DEBUG; } /** * Should this event cause a quick shutdown due to exceptional circumstances? * * @return */ public boolean isRuntimeException() { return equals(Action.RUNTIME_EXCEPTION); } } private Event(int code, String messagePrefix, Action action) { this.code = code; this.messagePrefix = messagePrefix; this.message = null; this.action = action; this.associatedThrowable = null; errorStream = Main.err; } /** * Lets the main thread know if the shutdown can be * graceful or not. This avoids long join() times * in situations where the VM is overloaded or out * of memory. * * @return true if it is OK to do a graceful shutdown. */ public boolean doCleanShutdown() { return action.equals(Action.CLEAN_SHUTDOWN); } /** * Prints the encapsulated message to standard out and nullifies it. Also * prints a stack trace if the action calls for it. * * Suppresses output from the status thread during printing. */ private void printMessage() { try { // Stop the status thread from printing. try { Main.getWorkloads().suppressStatusOutput(); } catch (NullPointerException e) {} if (message != null) { // Output the message and nullify it. Main.err.println(message); message = null; } // Look to the action type to see if we should print a trace. if (action.printStackTrace()) { // If we have a Throwable, print its stack trace if (associatedThrowable != null) associatedThrowable.printStackTrace(errorStream); // Otherwise, fabricate one. else new Throwable().printStackTrace(errorStream); } associatedThrowable = null; // Allow the status thread to continue printing if the event isn't fatal if (!action.isFatal()) { try { Main.getWorkloads().resumeStatusOutput(); } catch (NullPointerException e) {} } } catch (Throwable t) { System.exit(FAILED_ISSUE_CODE); } } /** * Performs a shutdown, if possible. * * @return */ private boolean shutdown() throws Throwable { // Try to perform shutdown. if (Main.shutdown(this)) { printMessage(); // The main thread exits, others interrupt the main thread and return true. if (Main.isMainThread()) { System.exit(code); } else { Main.interruptMainThread(); } return true; } // Thread did not perform the shutdown else { return false; } } public boolean issue(String message) { try { setMessage(message); // Throw a RuntimeException? if (action.isRuntimeException()) { boolean performedShutdown = shutdown(); System.exit(code); return performedShutdown; } // Shutdown? else if (action.isFatal()) { return shutdown(); } // Just print a message else { printMessage(); return true; } } catch (RuntimeException e) { throw e; } // Issue failed. catch (Throwable e) { System.exit(FAILED_ISSUE_CODE); return false; } } public boolean issue(Throwable e, String message) { try { associatedThrowable = e; // Append information about the throwable to the message. if (e != null) { if (message == null) message = formatException(e); else message = formatException(e) + ": " + message; } return issue(message); } catch (RuntimeException f) { throw f; } catch (Throwable t) { System.exit(FAILED_ISSUE_CODE); return false; } } public boolean issue() { return issue((String)null); } public boolean issue(Throwable e) { return issue(e, null); } public boolean issue(boolean condition, String message) { if (condition) return issue(message); else return false; } public boolean issue(boolean condition, Throwable e) { if (condition) return issue(e); else return false; } public boolean issue(boolean condition, Throwable e, String message) { if (condition) return issue(e, message); else return false; } /** * Gets a string representation of the exception. * * @param e * @return */ private String formatException(Throwable e) { try { StringBuilder builder = new StringBuilder(); // If there is a message in the throwable, we want to add it to the output. if (e.getMessage() != null) { // Append the name if called for. if (action.printExceptionName()) builder.append(e.getClass().getName() + ": "); // Append the message builder.append(e.getMessage()); } else { // Append the name if there is no message, regardless of the action. builder.append(e.getClass().getName()); } return builder.toString(); } catch (Throwable t) { System.exit(FAILED_ISSUE_CODE); return ""; } } /** * Sets the message, possibly adding a prefix. * * @param message */ private void setMessage(String message) { if (message == null) { this.message = null; } // Format the message to include the prefix. else { this.message = VerboseUtil.formatTimestamp(0, Utilities.getAbsoluteTime()) + ": "; if (this.messagePrefix != null) this.message += this.messagePrefix; this.message += message; } } }
3e058638c87031162027dc95167efc89080a67c6
6,462
java
Java
app/src/main/java/ru/gsench/passwordmanager/presentation/view/activity/SettingsActivity.java
GSench/PasswordManager
08a4b52e4f44ce6ff3616ecc63661455eabd2231
[ "Apache-2.0" ]
null
null
null
app/src/main/java/ru/gsench/passwordmanager/presentation/view/activity/SettingsActivity.java
GSench/PasswordManager
08a4b52e4f44ce6ff3616ecc63661455eabd2231
[ "Apache-2.0" ]
null
null
null
app/src/main/java/ru/gsench/passwordmanager/presentation/view/activity/SettingsActivity.java
GSench/PasswordManager
08a4b52e4f44ce6ff3616ecc63661455eabd2231
[ "Apache-2.0" ]
null
null
null
36.100559
110
0.629681
2,312
package ru.gsench.passwordmanager.presentation.view.activity; import android.content.DialogInterface; import android.inputmethodservice.KeyboardView; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.widget.Toast; import ru.gsench.passwordmanager.R; import ru.gsench.passwordmanager.domain.utils.function; import ru.gsench.passwordmanager.presentation.AndroidInterface; import ru.gsench.passwordmanager.presentation.presenter.KeyInputPresenter; import ru.gsench.passwordmanager.presentation.presenter.NewKeyPresenter; import ru.gsench.passwordmanager.presentation.presenter.NewPINPresenter; import ru.gsench.passwordmanager.presentation.presenter.PINInputPresenter; import ru.gsench.passwordmanager.presentation.presenter.SettingsPresenter; import ru.gsench.passwordmanager.presentation.utils.AViewContainer; import ru.gsench.passwordmanager.presentation.utils.KeyboardPref; import ru.gsench.passwordmanager.presentation.view.SettingsView; import ru.gsench.passwordmanager.presentation.view.aview.KeyInputAView; import ru.gsench.passwordmanager.presentation.view.aview.NewKeyAView; import ru.gsench.passwordmanager.presentation.view.aview.NewPINAView; import ru.gsench.passwordmanager.presentation.view.aview.PINInputAView; import ru.gsench.passwordmanager.presentation.view.view_etc.SettingsFragment; import ru.gsench.passwordmanager.presentation.viewholder.SettingsViewHolder; /** * Created by grish on 08.04.2017. */ public class SettingsActivity extends AppCompatActivity implements SettingsView { public static final int SETTINGS = 1; private SettingsViewHolder viewHolder; private AViewContainer container; private SettingsFragment settingsFragment; private SettingsPresenter presenter; private KeyboardPref keyboard; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.settings_layout); viewHolder = new SettingsViewHolder(this); presenter = new SettingsPresenter(new AndroidInterface(this)); presenter.setView(this); presenter.start(); } @Override public void init() { settingsFragment = new SettingsFragment(); settingsFragment.init( new function() { @Override public void run(String... params) { KeyboardPref.saveKeyboardPref(Boolean.parseBoolean(params[0]), SettingsActivity.this); } }, new function() { @Override public void run(String... params) { presenter.onBasePrefBtn(); } }, new function() { @Override public void run(String... params) { presenter.onKeyPrefBtn(); } }, new function() { @Override public void run(String... params) { presenter.onPINPrefBtn(); } } ); getFragmentManager().beginTransaction().replace(R.id.settings_list, settingsFragment).commit(); keyboard = new KeyboardPref(this, (KeyboardView) findViewById(R.id.keyboard_view), true); keyboard.enableHapticFeedback(true); container = new AViewContainer(viewHolder.dialogContent) .setOnCloseListener(new function() { @Override public void run(String... params) { keyboard.hideCustomKeyboard(); keyboard.closeSoftKeyboard(); } }); } @Override public void exit() { finish(); } @Override public void newKeyView(NewKeyPresenter presenter) { NewKeyAView aView = new NewKeyAView(container, presenter, keyboard); keyboard.registerEditText(aView.viewHolder.keyEdit, true); aView.open(); } @Override public void newPINView(NewPINPresenter presenter) { new NewPINAView(container, presenter).open(); } @Override public void openPINInputView(PINInputPresenter presenter) { new PINInputAView(container, presenter).open(); } @Override public void keyInputView(KeyInputPresenter presenter) { KeyInputAView aView = new KeyInputAView(container, presenter, keyboard); keyboard.registerEditText(aView.viewHolder.keyEdit, true); aView.open(); } @Override public boolean isViewOpened() { return container.viewOpened(); } @Override public void closeCurrentView() { container.closeView(); } @Override public void onSaveBaseErrorMsg() { Toast.makeText(this, R.string.unable_to_edit_file, Toast.LENGTH_SHORT).show(); } @Override public void changeKeyConfirmDialog() { new AlertDialog.Builder(this) .setTitle(R.string.change_key_title) .setMessage(R.string.change_base_key) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.cancel(); presenter.onChangeKeyConfirm(); } }) .setNeutralButton(R.string.cancel, null) .create() .show(); } @Override public void changeBaseConfirmDialog() { new AlertDialog.Builder(this) .setTitle(R.string.new_base_title) .setMessage(R.string.change_base_msg) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.cancel(); presenter.onChangeBaseConfirm(); } }) .setNeutralButton(R.string.cancel, null) .create() .show(); } @Override public void onBackPressed() { if(keyboard.onBackHandle()) return; presenter.onBackPressed(); } }