blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
a5548e9566e1dfbaa96d08b7b07a0fcddecfd0be
Java
InfinityRaider/NinjaGear
/src/main/java/com/infinityraider/ninjagear/item/ItemShuriken.java
UTF-8
2,806
1.984375
2
[ "MIT" ]
permissive
package com.infinityraider.ninjagear.item; import com.infinityraider.ninjagear.NinjaGear; import com.infinityraider.ninjagear.api.v1.IHiddenItem; import com.infinityraider.ninjagear.entity.EntityShuriken; import com.infinityraider.ninjagear.handler.NinjaAuraHandler; import com.infinityraider.ninjagear.reference.Reference; import com.infinityraider.ninjagear.registry.EffectRegistry; import com.infinityraider.infinitylib.item.ItemBase; import com.infinityraider.ninjagear.registry.ItemRegistry; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.Level; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import java.util.List; @MethodsReturnNonnullByDefault public class ItemShuriken extends ItemBase implements IHiddenItem { public ItemShuriken() { super("shuriken", new Properties().tab(ItemRegistry.CREATIVE_TAB)); } @Override @ParametersAreNonnullByDefault public InteractionResultHolder<ItemStack> use(Level world, Player player, InteractionHand hand) { if(!world.isClientSide()) { boolean crit = player.hasEffect(EffectRegistry.getInstance().getNinjaHiddenEffect()); EntityShuriken shuriken = new EntityShuriken(player, crit); world.addFreshEntity(shuriken); if (!player.isCreative()) { player.getInventory().removeItem(player.getInventory().selected, 1); } NinjaAuraHandler.getInstance().revealEntity(player, NinjaGear.instance.getConfig().getHidingCooldown(), true); } return new InteractionResultHolder<>(InteractionResult.CONSUME, player.getItemInHand(hand)); } @Override @OnlyIn(Dist.CLIENT) public void appendHoverText(ItemStack stack, @Nullable Level world, List<Component> tooltip, TooltipFlag advanced) { tooltip.add(new TranslatableComponent(Reference.MOD_ID + ".tooltip:" + this.getInternalName() + "_L1")); tooltip.add(new TranslatableComponent(Reference.MOD_ID + ".tooltip:" + this.getInternalName() + "_L2")); tooltip.add(new TranslatableComponent(Reference.MOD_ID + ".tooltip:" + this.getInternalName() + "_L3")); } @Override public boolean shouldRevealPlayerWhenEquipped(Player entity, ItemStack stack) { return false; } }
true
ab02ea62f6c63172041b07d33145401c412a88c5
Java
wwmengtao/AndroidTest_AS
/rxjava-android-sample/src/main/java/com/example/rxjava_android_sample/utils/ThrObserverInfo.java
UTF-8
2,351
2.46875
2
[]
no_license
package com.example.rxjava_android_sample.utils; import android.os.SystemClock; import com.example.rxjava_android_sample.ALog; import java.util.List; import rx.Observable; import static com.example.rxjava_android_sample.utils.ObserverInfo.BaseObserver; /** * Created by mengtao1 on 2017/12/20. */ public class ThrObserverInfo { private static final String TAG_TOP = "ThrObserverInfo "; public static void setTagTop(){ ObserverInfo.setTagTop(TAG_TOP); } public static class ObSample extends BaseObserver<Long> { public static ObSample get() { return new ObSample(); } @Override public void onNext(Long i) { SystemClock.sleep(1000); ALog.Log(TAG + "onNext " + "sample#" + "<--------" + i + "--------->"); } } public static class ObThrFirst extends BaseObserver<Long> { public static ObThrFirst get() { return new ObThrFirst(); } @Override public void onNext(Long i) { SystemClock.sleep(1000); ALog.Log(TAG + "onNext " + "trottleFirst#" + "<--------" + i + "--------->"); } } public static class ObDebounce extends BaseObserver<Long> { public static ObDebounce get() { return new ObDebounce(); } @Override public void onNext(Long i) { SystemClock.sleep(1000); ALog.Log(TAG + "onNext " + "debounce#" + "<--------" + i + "--------->"); } } public static class ObBuffer extends BaseObserver<List<Long>> { public static ObBuffer get() { return new ObBuffer(); } @Override public void onNext(List<Long> i) { SystemClock.sleep(100);//如果睡眠时间大于ThrObsFetcher.getBufferObs中的buffer的timespan,那么将报错 ALog.Log(TAG + "onNext " + "buffer#\n" + "<--" + i.toString() + "-->"); } } public static class ObWindow extends BaseObserver<Observable<String>> { public static ObWindow get() { return new ObWindow(); } @Override public void onNext(Observable<String> i) { ALog.sleep(1000); ALog.Log(TAG + "onNext " + "window#\n"); i.subscribe(ObserverInfo.ObString.get()); } } }
true
ebfda6f9bfe0ce6c2be630a2d9f1e22f0255fbad
Java
gellmr/Consultant-Tool
/src/consultanttool3/ConsultantDateInput.java
UTF-8
3,525
3.53125
4
[]
no_license
/** * Title: Consultant Tool * * Author: Michael Gell (Student 30276096) * * Date: 11 May 2012 * * File Name: ConsultantDateInput.java * * Purpose: A DateInput which is associated with a particular Consultant. * * * Assumptions / Conditions * * Form of Input: * * When you create an instance of ConsultantDateInput, you pass some * * listeners to its constructor, which are fired by the various inputs. * * - DAY_OF_MONTH input uses a JTextField and fires a MyDocumentListener. * * - MONTH input uses a JComboBox and fires an ActionListener. * * - YEAR input uses a JTextField and fires a MyDocumentListener. * * After creating this object, you can call setMyConsultant(c) to set the * * consultant for all the listeners you have just specified. * * * * Expected Output: * * In your event handler code for the MyDocumentListeners and ActionListener above, * * you can call getMyConsultant() to gain access to the consultant object, * * and perform some work on it. */ package consultanttool3; import java.util.GregorianCalendar; public class ConsultantDateInput extends DateInput { /** * Project to be manipulated by the handler of this input. */ private Consultant m_myConsultant; /** * Event Listeners associated with this input. */ private ConsultantDocumentListener m_dayOfMonthListener; private ConsultantActionListener m_monthListener; private ConsultantDocumentListener m_yearListener; /** * Default Constructor. */ public ConsultantDateInput() { super(); } /** * Constructor with arguments. * * @param calendar GregorianCalendar with the desired DAY_OF_MONTH / MONTH / YEAR values. * * @param dayOfMonthListener ConsultantDocumentListener, to be called when the DAY_OF_MONTH input is fired. * * @param monthListener ConsultantActionListener, to be called when the MONTH input is fired. * * @param yearListener ConsultantDocumentListener, to be called when the YEAR input is fired. */ public ConsultantDateInput( GregorianCalendar calendar, ConsultantDocumentListener dayOfMonthListener, ConsultantActionListener monthListener, ConsultantDocumentListener yearListener ) { super(calendar, dayOfMonthListener, monthListener, yearListener); m_dayOfMonthListener = dayOfMonthListener; m_monthListener = monthListener; m_yearListener = yearListener; } /** * Mutator method. Set the Consultant that is linked to this GUI input. * * @param c Consultant object to manipulate. */ public void setMyConsultant(Consultant c) { m_myConsultant = c; m_dayOfMonthListener.setConsultant(m_myConsultant); m_monthListener.setMyConsultant(m_myConsultant); m_yearListener.setConsultant(m_myConsultant); } /** * Accessor method. Get the Consultant that is linked to this GUI input. * * @return Consultant object, to manipulate. */ public Consultant getMyConsultant() { return m_myConsultant; } }
true
dc10f6846db410adbff0edb36e9ddd2af0a2a40b
Java
TencentCloud/tencentcloud-sdk-java
/src/main/java/com/tencentcloudapi/bda/v20200324/BdaClient.java
UTF-8
21,226
2.296875
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.bda.v20200324; import java.lang.reflect.Type; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; import com.tencentcloudapi.common.exception.TencentCloudSDKException; import com.tencentcloudapi.common.AbstractClient; import com.tencentcloudapi.common.profile.ClientProfile; import com.tencentcloudapi.common.JsonResponseModel; import com.tencentcloudapi.common.Credential; import com.tencentcloudapi.bda.v20200324.models.*; public class BdaClient extends AbstractClient{ private static String endpoint = "bda.tencentcloudapi.com"; private static String service = "bda"; private static String version = "2020-03-24"; public BdaClient(Credential credential, String region) { this(credential, region, new ClientProfile()); } public BdaClient(Credential credential, String region, ClientProfile profile) { super(BdaClient.endpoint, BdaClient.version, credential, region, profile); } /** *用于创建一个空的人体库,如果人体库已存在返回错误。 1个APPID下最多有2000W个人体动作轨迹(Trace),最多1W个人体库(Group)。 单个人体库(Group)最多10W个人体动作轨迹(Trace)。 单个人员(Person)最多添加 5 个人体动作轨迹(Trace)。 * @param req CreateGroupRequest * @return CreateGroupResponse * @throws TencentCloudSDKException */ public CreateGroupResponse CreateGroup(CreateGroupRequest req) throws TencentCloudSDKException{ JsonResponseModel<CreateGroupResponse> rsp = null; String rspStr = ""; req.setSkipSign(false); try { Type type = new TypeToken<JsonResponseModel<CreateGroupResponse>>() { }.getType(); rspStr = this.internalRequest(req, "CreateGroup"); rsp = gson.fromJson(rspStr, type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException("response message: " + rspStr + ".\n Error message: " + e.getMessage()); } return rsp.response; } /** *创建人员,添加对应人员的人体动作轨迹信息。 请注意: - 我们希望您的输入为 严格符合动作轨迹图片 要求的图片。如果您输入的图片不符合动作轨迹图片要求,会对最终效果产生较大负面影响。请您尽量保证一个Trace中的图片人体清晰、无遮挡、连贯; - 一个人体动作轨迹(Trace)可以包含1-5张人体图片。提供越多质量高的人体图片有助于提升最终识别结果; - 无论您在单个Trace中提供了多少张人体图片,我们都将生成一个对应的动作轨迹(Trace)信息。即,Trace仅和本次输入的图片序列相关,和图片的个数无关; - 输入的图片组中,若有部分图片输入不合法(如图片大小过大、分辨率过大、无法解码等),我们将舍弃这部分图片,确保合法图片被正确搜索。即,我们将尽可能保证请求成功,去除不合法的输入; - 构成人体动作轨迹单张图片大小不得超过2M,分辨率不得超过1920*1080。 * @param req CreatePersonRequest * @return CreatePersonResponse * @throws TencentCloudSDKException */ public CreatePersonResponse CreatePerson(CreatePersonRequest req) throws TencentCloudSDKException{ JsonResponseModel<CreatePersonResponse> rsp = null; String rspStr = ""; req.setSkipSign(false); try { Type type = new TypeToken<JsonResponseModel<CreatePersonResponse>>() { }.getType(); rspStr = this.internalRequest(req, "CreatePerson"); rsp = gson.fromJson(rspStr, type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException("response message: " + rspStr + ".\n Error message: " + e.getMessage()); } return rsp.response; } /** *本接口为人像分割在线处理接口组中的提交任务接口,可以对提交的资源进行处理视频流/图片流识别视频作品中的人像区域,进行一键抠像、背景替换、人像虚化等后期处理。 * @param req CreateSegmentationTaskRequest * @return CreateSegmentationTaskResponse * @throws TencentCloudSDKException */ public CreateSegmentationTaskResponse CreateSegmentationTask(CreateSegmentationTaskRequest req) throws TencentCloudSDKException{ JsonResponseModel<CreateSegmentationTaskResponse> rsp = null; String rspStr = ""; req.setSkipSign(false); try { Type type = new TypeToken<JsonResponseModel<CreateSegmentationTaskResponse>>() { }.getType(); rspStr = this.internalRequest(req, "CreateSegmentationTask"); rsp = gson.fromJson(rspStr, type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException("response message: " + rspStr + ".\n Error message: " + e.getMessage()); } return rsp.response; } /** *将一个人体动作轨迹添加到一个人员中。一个人员最多允许包含 5 个人体动作轨迹。同一人的人体动作轨迹越多,搜索识别效果越好。 >请注意: - 我们希望您的输入为 严格符合动作轨迹图片 要求的图片。如果您输入的图片不符合动作轨迹图片要求,会对最终效果产生较大负面影响。请您尽量保证一个Trace中的图片人体清晰、无遮挡、连贯。 - 一个人体动作轨迹(Trace)可以包含1-5张人体图片。提供越多质量高的人体图片有助于提升最终识别结果。 - 无论您在单个Trace中提供了多少张人体图片,我们都将生成一个对应的动作轨迹(Trace)信息。即,Trace仅和本次输入的图片序列相关,和图片的个数无关。 - 输入的图片组中,若有部分图片输入不合法(如图片大小过大、分辨率过大、无法解码等),我们将舍弃这部分图片,确保合法图片被正确搜索。即,我们将尽可能保证请求成功,去除不合法的输入; - 构成人体动作轨迹单张图片大小限制为2M,分辨率限制为1920*1080。 * @param req CreateTraceRequest * @return CreateTraceResponse * @throws TencentCloudSDKException */ public CreateTraceResponse CreateTrace(CreateTraceRequest req) throws TencentCloudSDKException{ JsonResponseModel<CreateTraceResponse> rsp = null; String rspStr = ""; req.setSkipSign(false); try { Type type = new TypeToken<JsonResponseModel<CreateTraceResponse>>() { }.getType(); rspStr = this.internalRequest(req, "CreateTrace"); rsp = gson.fromJson(rspStr, type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException("response message: " + rspStr + ".\n Error message: " + e.getMessage()); } return rsp.response; } /** *删除该人体库及包含的所有的人员。 * @param req DeleteGroupRequest * @return DeleteGroupResponse * @throws TencentCloudSDKException */ public DeleteGroupResponse DeleteGroup(DeleteGroupRequest req) throws TencentCloudSDKException{ JsonResponseModel<DeleteGroupResponse> rsp = null; String rspStr = ""; req.setSkipSign(false); try { Type type = new TypeToken<JsonResponseModel<DeleteGroupResponse>>() { }.getType(); rspStr = this.internalRequest(req, "DeleteGroup"); rsp = gson.fromJson(rspStr, type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException("response message: " + rspStr + ".\n Error message: " + e.getMessage()); } return rsp.response; } /** *删除人员。 * @param req DeletePersonRequest * @return DeletePersonResponse * @throws TencentCloudSDKException */ public DeletePersonResponse DeletePerson(DeletePersonRequest req) throws TencentCloudSDKException{ JsonResponseModel<DeletePersonResponse> rsp = null; String rspStr = ""; req.setSkipSign(false); try { Type type = new TypeToken<JsonResponseModel<DeletePersonResponse>>() { }.getType(); rspStr = this.internalRequest(req, "DeletePerson"); rsp = gson.fromJson(rspStr, type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException("response message: " + rspStr + ".\n Error message: " + e.getMessage()); } return rsp.response; } /** *可以查看单条任务的处理情况,包括处理状态,处理结果。 * @param req DescribeSegmentationTaskRequest * @return DescribeSegmentationTaskResponse * @throws TencentCloudSDKException */ public DescribeSegmentationTaskResponse DescribeSegmentationTask(DescribeSegmentationTaskRequest req) throws TencentCloudSDKException{ JsonResponseModel<DescribeSegmentationTaskResponse> rsp = null; String rspStr = ""; req.setSkipSign(false); try { Type type = new TypeToken<JsonResponseModel<DescribeSegmentationTaskResponse>>() { }.getType(); rspStr = this.internalRequest(req, "DescribeSegmentationTask"); rsp = gson.fromJson(rspStr, type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException("response message: " + rspStr + ".\n Error message: " + e.getMessage()); } return rsp.response; } /** *检测给定图片中的人体(Body)的位置信息及属性信息。 * @param req DetectBodyRequest * @return DetectBodyResponse * @throws TencentCloudSDKException */ public DetectBodyResponse DetectBody(DetectBodyRequest req) throws TencentCloudSDKException{ JsonResponseModel<DetectBodyResponse> rsp = null; String rspStr = ""; req.setSkipSign(false); try { Type type = new TypeToken<JsonResponseModel<DetectBodyResponse>>() { }.getType(); rspStr = this.internalRequest(req, "DetectBody"); rsp = gson.fromJson(rspStr, type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException("response message: " + rspStr + ".\n Error message: " + e.getMessage()); } return rsp.response; } /** *检测图片中人体的14个关键点。建议用于人体图像清晰、无遮挡的场景。支持一张图片中存在多个人体的识别。 * @param req DetectBodyJointsRequest * @return DetectBodyJointsResponse * @throws TencentCloudSDKException */ public DetectBodyJointsResponse DetectBodyJoints(DetectBodyJointsRequest req) throws TencentCloudSDKException{ JsonResponseModel<DetectBodyJointsResponse> rsp = null; String rspStr = ""; req.setSkipSign(false); try { Type type = new TypeToken<JsonResponseModel<DetectBodyJointsResponse>>() { }.getType(); rspStr = this.internalRequest(req, "DetectBodyJoints"); rsp = gson.fromJson(rspStr, type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException("response message: " + rspStr + ".\n Error message: " + e.getMessage()); } return rsp.response; } /** *获取人体库列表。 * @param req GetGroupListRequest * @return GetGroupListResponse * @throws TencentCloudSDKException */ public GetGroupListResponse GetGroupList(GetGroupListRequest req) throws TencentCloudSDKException{ JsonResponseModel<GetGroupListResponse> rsp = null; String rspStr = ""; req.setSkipSign(false); try { Type type = new TypeToken<JsonResponseModel<GetGroupListResponse>>() { }.getType(); rspStr = this.internalRequest(req, "GetGroupList"); rsp = gson.fromJson(rspStr, type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException("response message: " + rspStr + ".\n Error message: " + e.getMessage()); } return rsp.response; } /** *获取指定人体库中的人员列表。 * @param req GetPersonListRequest * @return GetPersonListResponse * @throws TencentCloudSDKException */ public GetPersonListResponse GetPersonList(GetPersonListRequest req) throws TencentCloudSDKException{ JsonResponseModel<GetPersonListResponse> rsp = null; String rspStr = ""; req.setSkipSign(false); try { Type type = new TypeToken<JsonResponseModel<GetPersonListResponse>>() { }.getType(); rspStr = this.internalRequest(req, "GetPersonList"); rsp = gson.fromJson(rspStr, type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException("response message: " + rspStr + ".\n Error message: " + e.getMessage()); } return rsp.response; } /** *获取人体库汇总信息。 * @param req GetSummaryInfoRequest * @return GetSummaryInfoResponse * @throws TencentCloudSDKException */ public GetSummaryInfoResponse GetSummaryInfo(GetSummaryInfoRequest req) throws TencentCloudSDKException{ JsonResponseModel<GetSummaryInfoResponse> rsp = null; String rspStr = ""; req.setSkipSign(false); try { Type type = new TypeToken<JsonResponseModel<GetSummaryInfoResponse>>() { }.getType(); rspStr = this.internalRequest(req, "GetSummaryInfo"); rsp = gson.fromJson(rspStr, type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException("response message: " + rspStr + ".\n Error message: " + e.getMessage()); } return rsp.response; } /** *修改人体库名称、备注。 * @param req ModifyGroupRequest * @return ModifyGroupResponse * @throws TencentCloudSDKException */ public ModifyGroupResponse ModifyGroup(ModifyGroupRequest req) throws TencentCloudSDKException{ JsonResponseModel<ModifyGroupResponse> rsp = null; String rspStr = ""; req.setSkipSign(false); try { Type type = new TypeToken<JsonResponseModel<ModifyGroupResponse>>() { }.getType(); rspStr = this.internalRequest(req, "ModifyGroup"); rsp = gson.fromJson(rspStr, type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException("response message: " + rspStr + ".\n Error message: " + e.getMessage()); } return rsp.response; } /** *修改人员信息。 * @param req ModifyPersonInfoRequest * @return ModifyPersonInfoResponse * @throws TencentCloudSDKException */ public ModifyPersonInfoResponse ModifyPersonInfo(ModifyPersonInfoRequest req) throws TencentCloudSDKException{ JsonResponseModel<ModifyPersonInfoResponse> rsp = null; String rspStr = ""; req.setSkipSign(false); try { Type type = new TypeToken<JsonResponseModel<ModifyPersonInfoResponse>>() { }.getType(); rspStr = this.internalRequest(req, "ModifyPersonInfo"); rsp = gson.fromJson(rspStr, type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException("response message: " + rspStr + ".\n Error message: " + e.getMessage()); } return rsp.response; } /** *本接口用于对一组待识别的人体动作轨迹(Trace)图片,在人体库中识别出最相似的 TopK 人体,按照相似度从大到小排列。 人体动作轨迹(Trace)图片要求:图片中当且仅包含一个人体。人体完整、无遮挡。 > 请注意: - 我们希望您的输入为严格符合动作轨迹图片要求的图片。如果您输入的图片不符合动作轨迹图片要求,会对最终效果产生较大负面影响; - 人体动作轨迹,是一个包含1-5张图片的图片序列。您可以输入1张图片作为动作轨迹,也可以输入多张。单个动作轨迹中包含越多符合质量的图片,搜索效果越好。 - 构成人体动作轨迹单张图片大小不得超过2M,分辨率不得超过1920*1080。 * @param req SearchTraceRequest * @return SearchTraceResponse * @throws TencentCloudSDKException */ public SearchTraceResponse SearchTrace(SearchTraceRequest req) throws TencentCloudSDKException{ JsonResponseModel<SearchTraceResponse> rsp = null; String rspStr = ""; req.setSkipSign(false); try { Type type = new TypeToken<JsonResponseModel<SearchTraceResponse>>() { }.getType(); rspStr = this.internalRequest(req, "SearchTrace"); rsp = gson.fromJson(rspStr, type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException("response message: " + rspStr + ".\n Error message: " + e.getMessage()); } return rsp.response; } /** *在前后景分割的基础上优化多分类分割,支持对头发、五官等的分割,既作为换发型、挂件等底层技术,也可用于抠人头、抠人脸等玩法 * @param req SegmentCustomizedPortraitPicRequest * @return SegmentCustomizedPortraitPicResponse * @throws TencentCloudSDKException */ public SegmentCustomizedPortraitPicResponse SegmentCustomizedPortraitPic(SegmentCustomizedPortraitPicRequest req) throws TencentCloudSDKException{ JsonResponseModel<SegmentCustomizedPortraitPicResponse> rsp = null; String rspStr = ""; req.setSkipSign(false); try { Type type = new TypeToken<JsonResponseModel<SegmentCustomizedPortraitPicResponse>>() { }.getType(); rspStr = this.internalRequest(req, "SegmentCustomizedPortraitPic"); rsp = gson.fromJson(rspStr, type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException("response message: " + rspStr + ".\n Error message: " + e.getMessage()); } return rsp.response; } /** *即二分类人像分割,识别传入图片中人体的完整轮廓,进行抠像。 * @param req SegmentPortraitPicRequest * @return SegmentPortraitPicResponse * @throws TencentCloudSDKException */ public SegmentPortraitPicResponse SegmentPortraitPic(SegmentPortraitPicRequest req) throws TencentCloudSDKException{ JsonResponseModel<SegmentPortraitPicResponse> rsp = null; String rspStr = ""; req.setSkipSign(false); try { Type type = new TypeToken<JsonResponseModel<SegmentPortraitPicResponse>>() { }.getType(); rspStr = this.internalRequest(req, "SegmentPortraitPic"); rsp = gson.fromJson(rspStr, type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException("response message: " + rspStr + ".\n Error message: " + e.getMessage()); } return rsp.response; } /** *终止指定视频人像分割处理任务 * @param req TerminateSegmentationTaskRequest * @return TerminateSegmentationTaskResponse * @throws TencentCloudSDKException */ public TerminateSegmentationTaskResponse TerminateSegmentationTask(TerminateSegmentationTaskRequest req) throws TencentCloudSDKException{ JsonResponseModel<TerminateSegmentationTaskResponse> rsp = null; String rspStr = ""; req.setSkipSign(false); try { Type type = new TypeToken<JsonResponseModel<TerminateSegmentationTaskResponse>>() { }.getType(); rspStr = this.internalRequest(req, "TerminateSegmentationTask"); rsp = gson.fromJson(rspStr, type); } catch (JsonSyntaxException e) { throw new TencentCloudSDKException("response message: " + rspStr + ".\n Error message: " + e.getMessage()); } return rsp.response; } }
true
8567b5b999d22fa0f2c909bcf10b3000dfaa0b22
Java
lenkalee814089/domain
/insight-domain-security/src/main/java/com/dataexa/insight/domain/security/spark/dataset/model/RailwayRecord.java
UTF-8
2,831
1.914063
2
[]
no_license
package com.dataexa.insight.domain.security.spark.dataset.model; import com.alibaba.fastjson.JSONObject; import java.io.Serializable; public class RailwayRecord implements Serializable { private String GMSFHM; private String SFD; private String MDD; private String CC; private String CXH; private String ZWH; private String FCSJ; private JSONObject diffFieldJsonObject; private JSONObject sameFieldJsonObject; public RailwayRecord(){ } @Override public String toString() { return "RailwayRecord{" + "GMSFHM='" + GMSFHM + '\'' + ", SFD='" + SFD + '\'' + ", MDD='" + MDD + '\'' + ", CC='" + CC + '\'' + ", CXH='" + CXH + '\'' + ", ZWH='" + ZWH + '\'' + ", FCSJ='" + FCSJ + '\'' + ", diffFieldJsonObject=" + diffFieldJsonObject + ", sameFieldJsonObject=" + sameFieldJsonObject + '}'; } public RailwayRecord(String GMSFHM, String SFD, String MDD, String CC, String CXH, String ZWH, String FCSJ, JSONObject diffFieldJsonObject, JSONObject sameFieldJsonObject) { this.GMSFHM = GMSFHM; this.SFD = SFD; this.MDD = MDD; this.CC = CC; this.CXH = CXH; this.ZWH = ZWH; this.FCSJ = FCSJ; this.diffFieldJsonObject = diffFieldJsonObject; this.sameFieldJsonObject = sameFieldJsonObject; } public JSONObject getDiffFieldJsonObject() { return diffFieldJsonObject; } public void setDiffFieldJsonObject(JSONObject diffFieldJsonObject) { this.diffFieldJsonObject = diffFieldJsonObject; } public JSONObject getSameFieldJsonObject() { return sameFieldJsonObject; } public void setSameFieldJsonObject(JSONObject sameFieldJsonObject) { this.sameFieldJsonObject = sameFieldJsonObject; } public String getFCSJ() { return FCSJ; } public void setFCSJ(String FCSJ) { this.FCSJ = FCSJ; } public String getGMSFHM() { return GMSFHM; } public void setGMSFHM(String GMSFHM) { this.GMSFHM = GMSFHM; } public String getSFD() { return SFD; } public void setSFD(String SFD) { this.SFD = SFD; } public String getMDD() { return MDD; } public void setMDD(String MDD) { this.MDD = MDD; } public String getCC() { return CC; } public void setCC(String CC) { this.CC = CC; } public String getCXH() { return CXH; } public void setCXH(String CXH) { this.CXH = CXH; } public String getZWH() { return ZWH; } public void setZWH(String ZWH) { this.ZWH = ZWH; } }
true
f67cb8b72b98ae7d246119f0c4d1396f6c2ee1e0
Java
wyczol/gra_Test_Spostrzegawczosci
/PracaSemestralna/src/controller/MainWindowController.java
WINDOWS-1250
2,411
2.71875
3
[]
no_license
package controller; import java.io.IOException; import controller.Main; import javafx.scene.control.*; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Cell; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.Modality; import javafx.stage.Stage; public class MainWindowController { private Main main; private Stage primaryStage; @FXML Button przycisk; @FXML TextField txtUserName; @FXML TextField txtPassword; @FXML Label wyjasnienie; public void setMain(Main main, Stage primaryStage) { this.main = main; this.primaryStage = primaryStage; } @FXML public void closeMainWindow(){ primaryStage.close(); } @FXML public void GridClicked(MouseEvent evt){ // int num; // double x, y; // int col, row; // // x = evt.getX(); // y = evt.getY(); // // col = (int) (x/40.0); // row = (int) (y/30.0); // // num = 3*row+col+1; System.out.println("wybrana cyfra: "); } @FXML public void ButtonClicked() { //if (txtUserName.getText().matches("user") && txtPassword.getText().matches("pass")) { try { FXMLLoader loader= new FXMLLoader( Main.class.getResource("/view/WyborWindowView.fxml")); AnchorPane wyborPane=loader.load(); Stage wyborWindowStage = new Stage(); wyborWindowStage.setTitle("Wstp"); wyborWindowStage.initModality(Modality.WINDOW_MODAL); wyborWindowStage.initOwner(primaryStage); wyborWindowStage.setMinWidth(500.0); wyborWindowStage.setMinHeight(500.0); Scene scene=new Scene(wyborPane); wyborWindowStage.setScene(scene); WyborWindowController wyborWindowController= loader.getController(); wyborWindowController.setWyborWindowStage(wyborWindowStage); wyborWindowStage.showAndWait(); } catch (IOException e) { e.printStackTrace(); } } } @FXML public void gridClicked(MouseEvent evt){ int num; double x, y; int col, row; x = evt.getX(); y = evt.getY(); col = (int) (x/40.0); row = (int) (y/30.0); num = 3*row+col+1; System.out.println("wybrana cyfra: "+num); }}
true
e7590dbe5bfb25593de8a685acf9b81c1a5f044e
Java
793753509/InterviewIForJob
/Arithmetic/src/main/java/com/zcprog/arithmetic/LeetCode_0031_NextPermutation.java
UTF-8
2,109
4.15625
4
[ "Apache-2.0" ]
permissive
package com.zcprog.arithmetic; import java.util.Arrays; /** * @Description 下一个排列 * @Author zhaochao * @Date 2020/12/21 17:38 * @Email zcprog@foxmail.com * @Version V1.0 */ public class LeetCode_0031_NextPermutation { /** * LeetCode地址:https://leetcode-cn.com/problems/next-permutation/ * 实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。 * 如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。 * 必须原地修改,只允许使用额外常数空间。 * <p> * 以下是一些例子,输入位于左侧列,其相应输出位于右侧列。 * 1,2,3 → 1,3,2 * 3,2,1 → 1,2,3 * 1,1,5 → 1,5,1 */ public static void main(String[] args) { int[][] heaps = {{1, 2, 3}, {3, 2, 1}, {1, 1, 5}, {1, 3, 2}, {4, 2, 0, 2, 3, 2, 0}}; for (int[] heap : heaps) { solve(heap); System.out.println(Arrays.toString(heap)); } } /** * 时间复杂度:O(n) * 空间复杂度:O(1) */ private static void solve(int[] nums) { if (nums == null || nums.length < 2) { return; } // 从后往前找到第一个不是升序的数,记为nums[i] int i = nums.length - 2; while (i >= 0 && nums[i] >= nums[i + 1]) { i--; } // 从后往前找到第一个大于nums[i]的数,并交换 if (i >= 0) { int j = nums.length - 1; while (j >= 0 && nums[i] >= nums[j]) { j--; } swap(nums, i, j); } // 将nums[i]后(不包含nums[i])的数按照降序排列 int left = i + 1; int right = nums.length - 1; while (left < right) { swap(nums, left, right); left++; right--; } } public static void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } }
true
e4b0f81b0cb8c6f7a5848b0d8309d7b56d558968
Java
vicchiam/AppFichas
/AppFichas/src/pcs/interfacesDAO/LanguageDAO.java
UTF-8
619
2.140625
2
[]
no_license
package pcs.interfacesDAO; import java.sql.SQLException; import java.util.Collection; import pcs.language.Language; public interface LanguageDAO { public Collection<Language> listLanguages(String name, int state) throws SQLException; public Language getLanguage(int id) throws SQLException; public Language insertLanguage(Language language) throws SQLException; public Language updateLanguage(Language language) throws SQLException; public boolean changeStateLanguage(int id) throws SQLException; public boolean updatePathLanguage(int id, String path) throws SQLException; }
true
f3df704aa8a4adfd79b57968c07e5af487dba29d
Java
luseek/house
/src/main/java/com/jzfq/house/swagger/model/amp/ProjectReq.java
UTF-8
483
1.648438
2
[]
no_license
package com.jzfq.house.swagger.model.amp; import lombok.Data; /** * 项目入参 * * @author Garen Gosling * @create 2018-04-21 14:11 * @since v1.0 */ @Data public class ProjectReq { private Integer projectId; private String houseName; private String name; private String leader;//person表username private Integer leaderId;//person表id private String leaderTel; private Integer status; private String projectStart; private String projectEnd; }
true
7577ae237651460080f15261eea67e73b6c5f1a0
Java
gcomte/zeus
/backend/src/main/java/ch/puzzle/ln/zeus/web/rest/BitcoinResource.java
UTF-8
3,290
2.09375
2
[ "MIT" ]
permissive
package ch.puzzle.ln.zeus.web.rest; import ch.puzzle.ln.zeus.config.ApplicationProperties; import ch.puzzle.ln.zeus.service.BitcoinService; import io.micrometer.core.annotation.Timed; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.actuate.health.AbstractHealthIndicator; import org.springframework.boot.actuate.health.Health; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Collections; import java.util.List; import java.util.Map; import static ch.puzzle.ln.zeus.service.BitcoinService.FIELD_BUY; import static org.springframework.http.ResponseEntity.ok; @RestController @RequestMapping("/api/bitcoin") @Timed public class BitcoinResource extends AbstractHealthIndicator { private static final Logger LOGGER = LoggerFactory.getLogger(BitcoinResource.class); private final ApplicationProperties applicationProperties; private final BitcoinService bitcoinService; public BitcoinResource(ApplicationProperties applicationProperties, BitcoinService bitcoinService) { this.applicationProperties = applicationProperties; this.bitcoinService = bitcoinService; } @GetMapping(value = "") public ResponseEntity<Map<String, Object>> getInfo() throws Exception { return ok(bitcoinService.chainInfo()); } @GetMapping("/price/{ticker}") public ResponseEntity<Object> getPrice(@PathVariable String ticker) { LOGGER.debug("REST request to get bitcoin price in {}", ticker); return ok(Collections.singletonMap(FIELD_BUY, bitcoinService.buyPricePerBitcoinIn(ticker))); } @GetMapping("/prices/stale") public ResponseEntity<List<String>> getStalePrices() { LOGGER.debug("REST request to get stale bitcoin prices"); return ok(bitcoinService.getStalePrices()); } @GetMapping("/prices/age") public ResponseEntity<Map<String, Long>> getPricesAge() { LOGGER.debug("REST request to get bitcoin prices age"); return ok(bitcoinService.getPricesAge()); } @Override protected void doHealthCheck(Health.Builder builder) { try { Map<String, Object> info = bitcoinService.chainInfo(); Double price = bitcoinService.buyPricePerBitcoinIn(applicationProperties.getCurrencyTicker()); List<String> stalePrices = bitcoinService.getStalePrices(); Map<String, Long> pricesAges = bitcoinService.getPricesAge(); if (info == null || !stalePrices.isEmpty()) { builder.down(); return; } builder .withDetail("price", price) .withDetail("stalePrices", stalePrices) .withDetail("pricesAge", pricesAges) .withDetail("blockHeight", info.get("blocks")) .withDetail("blockHash", info.get("bestblockhash")) .up(); } catch (Exception e) { LOGGER.error("Error in bitcoin health check.", e); builder.down(e); } } }
true
ae3cfbc51c24d894515663b07845682669d8d005
Java
yuananye/fcoin-java-api
/src/main/java/com/fcoin/api/client/domain/Depth.java
UTF-8
392
1.726563
2
[ "MIT" ]
permissive
package com.fcoin.api.client.domain; import lombok.Getter; import lombok.Setter; import java.math.BigDecimal; import java.util.List; /** * created by jacky. 2018/7/21 2:28 PM */ @Getter @Setter public class Depth { private String type; private String seq; private long ts; //[price,vol,price1,vol1] private List<BigDecimal> bids; private List<BigDecimal> asks; }
true
9cdca151a88635c686f0bfd2dab4b34ce0746a5b
Java
appirio-tech/direct-app
/services/catalog_services/src/java/main/com/topcoder/catalog/service/CatalogServiceImpl.java
UTF-8
89,011
1.734375
2
[]
no_license
/* * Copyright (C) 2009 TopCoder Inc., All Rights Reserved. */ package com.topcoder.catalog.service; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Collection; import javax.annotation.Resource; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.persistence.EntityExistsException; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.persistence.TransactionRequiredException; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import com.topcoder.catalog.entity.Category; import com.topcoder.catalog.entity.CompClient; import com.topcoder.catalog.entity.CompDocumentation; import com.topcoder.catalog.entity.CompForum; import com.topcoder.catalog.entity.CompLink; import com.topcoder.catalog.entity.CompUploadedFile; import com.topcoder.catalog.entity.CompUser; import com.topcoder.catalog.entity.CompVersion; import com.topcoder.catalog.entity.CompVersionDates; import com.topcoder.catalog.entity.Component; import com.topcoder.catalog.entity.Phase; import com.topcoder.catalog.entity.Status; import com.topcoder.catalog.entity.Technology; /** * <p>This class implements the contract for the catalog services.</p> * <p>It provides facilities to retrieve <code>Components</code>, <code>Categories</code>, <code>Technologies</code> * and <code>Phases</code> from and to modify <code>Components</code> in the persistence.</p> * <p><strong>Thread safety: </strong></p> * <p> * version 1.1 add method <code>getAllAssetVersions(long)</code> which get all versions with same asset id. * </p> * * <p> * Changes in v1.2 (Cockpit Upload Attachment): * - Added entity manager to checkAssetDocumentation to be able to delete removed documents from persistence. * - Fixed multiple file upload logic in checkAssetDocumentation. * - Removed unnecessary document type inference from storeUploadedFile and convertUploadedFileToCompDocumentation. * - Removed getAllDocumentTypes method and calls, it's not used anymore. * - Added asset.documentation refresh after create/update asset. * </p> * * <p>this class is thread safe because all operations are transactions in the EJB environment.</p> * * @author caru, Retunsky, pulky * @version 1.2 * @since 1.0 */ @Stateless public class CatalogServiceImpl implements CatalogServiceLocal, CatalogServiceRemote { /** * <p>CompVersionDates level ID.</p> */ private static final long LEVEL_ID = 100L; /** * <p>Collaboration phase ID.</p> */ /** * <p>This field represents the entity manager which is used to communicate with the persistence.</p> * <p>It's automatically injected by EJB container.</p> */ @PersistenceContext private EntityManager entityManager; /** * This is the root directory of uploaded files. * @since BUGR-1600 */ @Resource(name = "uploadedFilesRootDir") private String uploadedFilesRootDir; /** * <p>Default constructor.</p> <p><em>Does nothing.</em></p> */ public CatalogServiceImpl() { } /** * <p>Returns a list containing all active <code>Categories</code>.</p> * * @return a list containing all active <code>Categories</code>. It can be empty if no objects found. * @throws PersistenceException if an error occurs when interacting with the persistence store, * including invalid named query configuration */ @TransactionAttribute(TransactionAttributeType.REQUIRED) public List<Category> getActiveCategories() throws PersistenceException { return retrieveList(Category.class, "getActiveCategories"); } /** * <p>Returns a list containing all active <code>Technologies</code>.</p> * * @return a list containing all active <code>Categories</code>. It can be empty if no objects found. * @throws PersistenceException if an error occurs when interacting with the persistence store, * including invalid named query configuration */ @TransactionAttribute(TransactionAttributeType.REQUIRED) public List<Technology> getActiveTechnologies() throws PersistenceException { return retrieveList(Technology.class, "getActiveTechnologies"); } /** * <p>Returns a list containing all <code>Phases</code>.</p> * * @return a list containing all active <code>Categories</code>. It can be empty if no objects found. * @throws PersistenceException if an error occurs when interacting with the persistence store, * including invalid named query configuration */ @TransactionAttribute(TransactionAttributeType.REQUIRED) public List<Phase> getPhases() throws PersistenceException { return retrieveList(Phase.class, "getAllPhases"); } /** * <p>Returns a <code>AssetDTO</code> instance describing the asset with specified id, * with an option of retrieving whether the current or the latest version.</p> * * @param id the id of the asset * @param currentVersion if <code>true</code>, retrieve the current version, otherwise retrieve the latest one * @return a <code>AssetDTO</code> instance describing the asset (cannot be <code>null</code>) * @throws EntityNotFoundException if the asset is not found in persistence * @throws PersistenceException if an error occurs when interacting with the persistence store. */ @TransactionAttribute(TransactionAttributeType.REQUIRED) public AssetDTO getAssetById(long id, boolean currentVersion) throws PersistenceException, EntityNotFoundException { try { // get the Component entity Component component = findComponentById(id); // get the latest and the current versions final CompVersion theLatestVersion = getLatestVersion(component); final CompVersion theCurrentVersion = component.getCurrentVersion(); // assign to component version the current or the last, depending on the passed flag final CompVersion compVersion = currentVersion ? theCurrentVersion : theLatestVersion; // create AssetDTO from the component and appropriate version return createAssetDTO(component, compVersion); } catch (javax.persistence.PersistenceException e) { // any other errors, e.g. on JDBC level are wrapped to it throw new PersistenceException("Unexpected persistence error occurred: " + e.getMessage(), e); } catch (IllegalStateException e) { throw new PersistenceException("Unexpected error: " + e.getMessage(), e); } catch (IllegalArgumentException e) { throw new PersistenceException("Unexpected error: " + e.getMessage(), e); } } /** * <p>Returns a <code>AssetDTO</code> instance describing the asset containing * the version with specified id.</p> * * @param id the id of the asset's version * @return a <code>AssetDTO</code> instance describing the asset (cannot be <code>null</code>) * @throws EntityNotFoundException if the asset is not found in persistence * @throws PersistenceException if an error occurs when interacting with the persistence store */ @TransactionAttribute(TransactionAttributeType.REQUIRED) public AssetDTO getAssetByVersionId(long id) throws PersistenceException, EntityNotFoundException { try { // get the CompVersion entity CompVersion compVersion = getEntityManager().find(CompVersion.class, id); if (compVersion == null) { throw new EntityNotFoundException("CompVersion with id=" + id + " not found"); } if (compVersion.getComponent() == null) { throw new PersistenceException("CompVersion with id=" + id + " doesn't have a Component entity."); } // build assetDTO from the version's Component and itself return createAssetDTO(compVersion.getComponent(), compVersion); } catch (javax.persistence.PersistenceException e) { // any other errors, e.g. on JDBC level are wrapped to it throw new PersistenceException("Unexpected persistence error occurred: " + e.getMessage(), e); } catch (IllegalStateException e) { throw new PersistenceException("Unexpected error: " + e.getMessage(), e); } catch (IllegalArgumentException e) { throw new PersistenceException("Unexpected error: " + e.getMessage(), e); } } /** * <p>Creates a new <code>AssetDTO</code> in the persistence.</p> * * @param asset a <code>AssetDTO</code> instance describing the asset * @return created asset with populated <code>asset.id</code> and <code>asset.versionId</code> fields. * @throws IllegalArgumentException if any of the following conditions met: * <ul> * <li>if the parameter is <code>null</code></li> * <li>if the <code>asset.id</code> has non-null value</li> * <li>if the <code>asset.versionId</code> has non-null value</li> * <li>if the <code>asset.name</code> is <code>null</code> or empty</li> * <li>if the <code>asset.versionText</code> is <code>null</code> or empty</li> * <li>if the <code>asset.shortDescription</code> is <code>null</code> or empty</li> * <li>if the <code>asset.detailedDescription</code> is <code>null</code> or empty</li> * <li>if the <code>asset.rootCategory</code> is <code>null</code></li> * <li>if the <code>asset.functionalDescription</code> is <code>null</code> or empty</li> * <li>if the <code>asset.categories</code> is <code>null</code>, empty or contains <code>null</code> item</li> * <li>if the <code>asset.technologies</code> is <code>null</code>, * empty or contains <code>null</code> item</li> * <li>if the <code>asset.documentation</code> is <code>null</code>, * contains <code>null</code> item</li> * </ul> * @throws PersistenceException if an error occurs when interacting with the persistence store. */ @TransactionAttribute(TransactionAttributeType.REQUIRED) public AssetDTO createAsset(AssetDTO asset) throws PersistenceException { checkNotNull("asset", asset); if (asset.getId() != null) { throw new IllegalArgumentException("Component already has id=" + asset.getId() + " and cannot be created."); } checkNullVersionId(asset); // create a new asset entity final Component entityComponent = new Component(); entityComponent.setStatus(Status.APPROVED); // update the new asset entity and create a new version final CompVersion compVersion = updateAssetCreateVersion(asset, entityComponent); // set the created version as current entityComponent.setCurrentVersion(compVersion); final EntityManager em = getEntityManager(); // save the asset entity finally persistEntity(em, entityComponent); // save version persistEntity(em, compVersion); populateVersionDocumentation(asset, em, compVersion); // BUGR-1600.2 for(CompDocumentation doc : compVersion.getDocumentation()) { // BUGR-1600.2 mergeEntity(em, doc); } // Refresh documentation collection in asset. asset.setDocumentation(new ArrayList<CompDocumentation>(compVersion.getDocumentation())); // populate with ids of just stored entities asset.setId(entityComponent.getId()); asset.setCompVersionId(compVersion.getId()); asset.setVersionNumber(compVersion.getId()); asset.setVersionText(compVersion.getVersionText()); asset.setVersion(compVersion.getVersion()); // and return it return asset; } /** * <p> * Creates a new version for the given <code>AssetDTO</code> and update it in the persistence. * </p> * * @param asset * a <code>AssetDTO</code> instance describing the asset * @return updated asset with populated <code>asset.versionId</code> field. * * @throws IllegalArgumentException * if any of the following conditions met: * <ul> * <li>if the parameter is <code>null</code></li> * <li>if the <code>asset.id</code> has <code>null</code> value</li> * <li>if the <code>asset.versionId</code> has non-null value</li> * <li>if the <code>asset.name</code> is <code>null</code> or empty</li> * <li>if the <code>asset.versionText</code> is <code>null</code> or empty</li> * <li>if the <code>asset.shortDescription</code> is <code>null</code> or empty</li> * <li>if the <code>asset.detailedDescription</code> is <code>null</code> or * empty</li> * <li>if the <code>asset.functionalDescription</code> is <code>null</code> or * empty</li> * <li>if the <code>asset.rootCategory</code> is <code>null</code></li> * <li>if the <code>asset.categories</code> is <code>null</code>, empty or * contains <code>null</code> item</li> * <li>if the <code>asset.technologies</code> is <code>null</code>, empty or * contains <code>null</code> item</li> * <li>if the <code>asset.documentation</code> is <code>null</code>, or * contains <code>null</code> item</li> * </ul> * @throws EntityNotFoundException * if the asset is not found in persistence * @throws PersistenceException * if an error occurs when interacting with the persistence store. */ @TransactionAttribute(TransactionAttributeType.REQUIRED) public AssetDTO createVersion(AssetDTO asset) throws EntityNotFoundException, PersistenceException { checkNotNull("asset", asset); checkComponentIdNotNull(asset); checkNullVersionId(asset); final EntityManager em = getEntityManager(); // retrieve the asset entity final Component entityComponent = findComponentById(asset.getId()); // update the asset entity and create a new version final CompVersion compVersion = updateAssetCreateVersion(asset, entityComponent); // persist the new version persistEntity(em, compVersion); // update the asset entity finally mergeEntity(em, entityComponent); // populate with ids of just stored entities asset.setId(entityComponent.getId()); asset.setCompVersionId(compVersion.getId()); asset.setVersionNumber(compVersion.getId()); asset.setVersionText(compVersion.getVersionText()); asset.setVersion(compVersion.getVersion()); return asset; } /** * <p>Updates an <code>AssetDTO</code> in the persistence (without its version properties).</p> * * @param asset a <code>AssetDTO</code> instance describing the asset * * @throws IllegalArgumentException if any of the following conditions met: * <ul> * <li>if the parameter is <code>null</code></li> * <li>if the <code>asset.id</code> has <code>null</code> value</li> * <li>if the <code>asset.name</code> is <code>null</code> or empty</li> * <li>if the <code>asset.shortDescription</code> is <code>null</code> or empty</li> * <li>if the <code>asset.detailedDescription</code> is <code>null</code> or empty</li> * <li>if the <code>asset.functionalDescription</code> is <code>null</code> or empty</li> * <li>if the <code>asset.rootCategory</code> is <code>null</code></li> * <li>if the <code>asset.categories</code> is <code>null</code>, empty or contains <code>null</code> item</li> * </ul> * @throws EntityNotFoundException if the asset is not found in persistence, or version not found (if specified) * @throws PersistenceException if an error occurs when interacting with the persistence store. */ @TransactionAttribute(TransactionAttributeType.REQUIRED) public AssetDTO updateAsset(AssetDTO asset) throws PersistenceException, EntityNotFoundException { checkNotNull("asset", asset); checkComponentIdNotNull(asset); final EntityManager em = getEntityManager(); // retrieve the asset entity final Component entityComponent = findComponentById(asset.getId()); CompVersion versionToUpdate = null; if (asset.getCompVersionId() != null) { // if there is a version to update for (CompVersion compVersion : entityComponent.getVersions()) { if (compVersion.getId().equals(asset.getCompVersionId())) { versionToUpdate = compVersion; break; } } if (versionToUpdate == null) { throw new EntityNotFoundException("CompVersion with id=" + asset.getCompVersionId() + " not found"); } } else { throw new EntityNotFoundException("Asset Version Id is null"); } entityComponent.setCurrentVersion(versionToUpdate); // if phase is complted, udpate comp version and comp version dates if (asset.getPhase().equals("Completed")) { Phase phase = getEntityManager().find(Phase.class, Phase.COMPLETED_PHASE_ID); versionToUpdate.setPhase(phase); if (versionToUpdate.getVersionDates().get(Phase.COMPLETED_PHASE_ID) == null) { final Date zeroPointDate = buildDate(1976, 5, 5); final Date stubDate = buildDate(2000, 1, 1); final CompVersionDates compVersionDates = createInitialCompVersionDates(asset, zeroPointDate, stubDate); compVersionDates.setPhase(phase); compVersionDates.setCompVersion(versionToUpdate); compVersionDates.setProductionDate(getDate(asset.getProductionDate())); versionToUpdate.getVersionDates().put(Phase.COMPLETED_PHASE_ID, compVersionDates); } } // update the asset entity updateAsset(asset, entityComponent, versionToUpdate); // BUGR-1600 update the compVersion with uploaded /removed docs and persist it again. // Note that we need component entity to be existing for this, so persist twice here populateVersionDocumentation(asset, em, versionToUpdate); // update documentation collection for(CompDocumentation doc : versionToUpdate.getDocumentation()) { mergeEntity(em, doc); } // update the asset entity finally mergeEntity(em, entityComponent); // Refresh documentation collection in asset. asset.setDocumentation(new ArrayList<CompDocumentation>(versionToUpdate.getDocumentation())); return asset; } /** * By a given criteria returns a list of <code>AssetDTOs</code> containing only the following information: * <ul> * <li>Id</li> * <li>VersionId</li> * <li>Name</li> * <li>Version (text)</li> * <li>Root Category</li> * <li>Short Description</li> * <li>component create after date</li> * <li>component create before date</li> * <li>component version create after date</li> * <li>component version create before date</li> * </ul> * <p>It is indicated in the DTO that the information is not complete * (by property {@link AssetDTO#informationComplete}).</p> * <p>It is possible to choose whether to retrieve the current version or the last one.</p> * The search criteria is: * <ul> * <li><tt>userId</tt>: If a <code>userId</code> is specified, the asset must meet one or of these conditions: * <ol> * <li>In the AssetDTO, users list must contain a user with that user id</li> * <li>In the AssetDTO, clients list must contain a client id which is associated with the user id * (via <code>CompUser</code> entity)</li> * </ol> * </li> * <li><tt>clientId</tt>: in the AssetDTO, clients list must contain the client id.</li> * <li>List of <tt>categories</tt>: given a list of category ids, the root category of the asset must be * one of those.</li> * <li>the AssetDTO <tt>name</tt>: seeks for partial case insensitive matches.</li> * <li><tt>descriptions</tt>: it must search in all the description fields, * seeks for partial case insensitive matches</li> * <li>compCreateAfterDate seeks for component create after this date(include)</li> * <li>compCreateBeforeDate seeks for component version create before this date(include)</li> * <li>compVersionCreateAfterDate seeks for component version create after this date(include)</li> * <li>compVersionCreateBeforeDate seeks for component version create before this date(include)</li> * </ul> * For the algorithm details look at the CS 1.3.3. * @param criteria the search criteria * @param currentVersion if <code>true</code>, retrieve the current version, otherwise retrieve the latest one * * @return a list of <code>AssetDTO</code> partially describing the asset (can be empty if none is found) * * @throws IllegalArgumentException if criteria is <code>null</code> * @throws PersistenceException if an error occurs when interacting with the persistence store. */ @SuppressWarnings("unchecked") @TransactionAttribute(TransactionAttributeType.REQUIRED) public List<AssetDTO> findAssets(SearchCriteria criteria, boolean currentVersion) throws PersistenceException { checkNotNull("criteria", criteria); // create a native query, as maximum four tables can be joined, and it's much faster // that query all then boot off records // create initial query and add 'where', as there couldn't be an empty criteria final StringBuilder subQueryString = new StringBuilder("SELECT DISTINCT C.component_id FROM comp_catalog C\n"); // build query and get parameters map for it final Map<String, Object> parameters = buildSubQuery(criteria, subQueryString); final EntityManager em = getEntityManager(); // create a single query to retrieve the data // JOIN approach can be by 'current_version' if the currentVersion parameter is true // or from versions to components by 'component_id' otherwise // in latter case we select only the version with maximum number String queryString = "SELECT A.component_id, A.component_name, A.short_desc," + " A.root_category_id, B.version_text, B.comp_vers_id FROM comp_catalog A\n" + "JOIN comp_versions B ON " + (currentVersion ? "A.current_version=B.version and A.component_id = B.component_id" : "A.component_id=B.component_id") // join type + "\n where A.component_id IN (" + subQueryString + ")\n" // only in eligible components' ids + (currentVersion ? "" : "AND version=(SELECT MAX(version) FROM comp_versions WHERE component_id=A.component_id)"); // latest one try { em.clear(); // clear caches, as commenting this line leads to a hibernate bug final Query query = em.createNativeQuery(queryString, AssetDTO.class); for (Map.Entry<String, Object> parameter : parameters.entrySet()) { query.setParameter(parameter.getKey(), parameter.getValue()); } // this is read-only entities query.setHint("org.hibernate.readOnly", true); return (List<AssetDTO>) query.getResultList(); } catch (javax.persistence.PersistenceException e) { // any other errors, e.g. on JDBC level are wrapped to it throw new PersistenceException("Unexpected error occurred on underlying persistence level:" + e.getMessage(), e); } catch (IllegalStateException e) { throw new PersistenceException("Unexpected error: " + e.getMessage(), e); } catch (IllegalArgumentException e) { throw new PersistenceException("Unexpected error: " + e.getMessage(), e); } } /** * <p>Assigns a specified user to a specified <code>assetDTO</code>.</p> * <p>If a user already assigned to the asset, this method simply does nothing.</p> * * @param userId the id of the user * @param assetId the id of the assetDTO * * @throws EntityNotFoundException if the assetDTO is not found in persistence * @throws PersistenceException if an error occurs when interacting with the persistence store. */ @TransactionAttribute(TransactionAttributeType.REQUIRED) public void assignUserToAsset(long userId, long assetId) throws PersistenceException, EntityNotFoundException { final EntityManager em = getEntityManager(); // retrieve the component entity final Component entityComponent = findComponentById(assetId); // update the component entity Set<CompUser> compUserSet = entityComponent.getUsers(); if (compUserSet == null) { compUserSet = new HashSet<CompUser>(); entityComponent.setUsers(compUserSet); } else { for (CompUser compUser : compUserSet) { if (compUser.getUserId() == userId) { return; // do nothing if association already exists } } } final CompUser compUser = new CompUser(); compUser.setComponent(entityComponent); compUser.setUserId(userId); compUserSet.add(compUser); // update the component entity finally persistEntity(em, compUser); mergeEntity(em, entityComponent); } /** * <p>create comp forum</p> * * @param compVersId * @param jiveCategoryId * * @throws PersistenceException if an error occurs when interacting with the persistence store. */ @TransactionAttribute(TransactionAttributeType.REQUIRED) public void addCompForum(long compVersId, long jiveCategoryId) throws PersistenceException { // we have to create component and version first so that we can // create the forum, then we need to create compForum, since // pk is forumId + compVersionsId, we have to use native query here final EntityManager em = getEntityManager(); Query query = em.createNamedQuery("addCompForum"); query.setParameter(1, compVersId); query.setParameter(2, jiveCategoryId); query.executeUpdate(); } /** * <p>Removes a specified user from a specified <code>assetDTO</code>.</p> * * @param userId the id of the user * @param assetId the id of the asset * * @throws EntityNotFoundException * if the assetDTO is not found in persistence, or the user is not assigned to the asset * @throws PersistenceException * if an error occurs when interacting with the persistence store */ @TransactionAttribute(TransactionAttributeType.REQUIRED) public void removeUserFromAsset(long userId, long assetId) throws PersistenceException, EntityNotFoundException { final EntityManager em = getEntityManager(); // retrieve the component entity final Component entityComponent = findComponentById(assetId); // update the component entity Set<CompUser> compUserSet = entityComponent.getUsers(); boolean removed = false; if (compUserSet != null) { for (Iterator<CompUser> iterator = compUserSet.iterator(); iterator.hasNext();) { CompUser compUser = iterator.next(); if (compUser.getUserId() == userId) { iterator.remove(); removed = true; break; } } } // if there were no association then report with exception if (!removed) { throw new EntityNotFoundException("User with id=" + userId + " was not assigned to" + " assetDTO with id=" + assetId); } // update the component entity finally mergeEntity(em, entityComponent); } /** * <p>retrieve all the versions of an <code>assetDTO</code> using given assetId.</p> * * @param assetId the assetId * @return a list where each element is a version of the asset, ordered by CompVersion.version * @throws EntityNotFoundException if the assetDTO is not found in persistence * @throws PersistenceException if an error occurs when interacting with the persistence store. * @since version 1.1 */ @TransactionAttribute(TransactionAttributeType.REQUIRED) public List<AssetDTO> getAllAssetVersions(long assetId) throws PersistenceException, EntityNotFoundException{ Component component = findComponentById(assetId); List<CompVersion> versions = component.getVersions(); // sort version Collections.sort(versions, new Comparator<CompVersion>() { public int compare(CompVersion o1, CompVersion o2) { long sub = o1.getId() - o2.getId(); return (sub == 0) ? 0 : (sub > 0 ? 1 : -1); } }); List<AssetDTO> resDTO =new ArrayList<AssetDTO>(); // translate to DTO for (CompVersion version : versions) { resDTO.add(createAssetDTO(component, version)); } return resDTO; } /** * <p>create dev component, basically insert a new row in CompVersionsDates</p> * * @param asset a <code>AssetDTO</code> instance describing the asset * * @throws EntityNotFoundException if the asset is not found in persistence, or version not found (if specified) * @throws PersistenceException if an error occurs when interacting with the persistence store. */ @TransactionAttribute(TransactionAttributeType.REQUIRED) public AssetDTO createDevComponent(AssetDTO asset) throws PersistenceException, EntityNotFoundException { checkNotNull("asset", asset); checkComponentIdNotNull(asset); final EntityManager em = getEntityManager(); // retrieve the asset entity final Component entityComponent = findComponentById(asset.getId()); CompVersion versionToUpdate = null; if (asset.getCompVersionId() != null) { // if there is a version to update for (CompVersion compVersion : entityComponent.getVersions()) { if (compVersion.getId().equals(asset.getCompVersionId())) { versionToUpdate = compVersion; break; } } if (versionToUpdate == null) { throw new EntityNotFoundException("CompVersion with id=" + asset.getCompVersionId() + " not found"); } } else { throw new EntityNotFoundException("Asset Version Id is null"); } final Date zeroPointDate = buildDate(1976, 5, 5); //final Phase collaborationPhase = getEntityManager().find(Phase.class, COLLABORATION_PHASE_ID); Phase phase = getEntityManager().find(Phase.class, Phase.DEVELOPMENT_PHASE_ID); // populate with CompVersionDates final Date stubDate = buildDate(2000, 1, 1); final CompVersionDates compVersionDates = createInitialCompVersionDates(asset, zeroPointDate, stubDate); compVersionDates.setPhase(phase); compVersionDates.setCompVersion(versionToUpdate); versionToUpdate.getVersionDates().put(Phase.DEVELOPMENT_PHASE_ID, compVersionDates); persistEntity(em, versionToUpdate); asset.setVersionNumber(versionToUpdate.getId()); asset.setVersionText(versionToUpdate.getVersionText()); asset.setVersion(versionToUpdate.getVersion()); return asset; } /** * <p> * Retrieves the entity manager injected by EJB container for persistence operations. * </p> * * @return the entity manager injected by EJB container for persistence operations * @throws PersistenceException * if the entity manager is <code>null</code> */ private EntityManager getEntityManager() throws PersistenceException { if (entityManager == null) { throw new PersistenceException("No EntityManager injected to the bean."); } return entityManager; } /** * <p>Creates <code>AssetDTO</code> instance by a given <code>Component</code> entity instance, which has * been retrieved from the persistence.</p> * <p>Marks returned object as completed and populates <code>isCurrentVersionAlsoLatestVersion</code> flag with * appropriate value (<code>true</code>, if the last version is current one).</p> * * @param component the original component entity from which to create DTO representation * @param compVersion the version of the component entity * @return * a <code>AssetDTO</code> corresponding the given <code>Component</code> and <code>CompVersion</code> entities * @throws PersistenceException if versions list is empty (which means error on persistence level, as there always * should be non-empty list of versions in a component entity). */ private AssetDTO createAssetDTO(Component component, CompVersion compVersion) throws PersistenceException { final AssetDTO assetDTO = new AssetDTO(); // and set current-also-latest flag with a proper value assetDTO.setCurrentVersionAlsoLatestVersion( component.getCurrentVersion().getVersion().equals(getLatestVersion(component).getVersion())); // force hibernate to retrieve lazy collection List<Category> categories = new ArrayList<Category>(); if (component.getCategories() != null) { for (Category category : component.getCategories()) { categories.add(category); } } org.hibernate.Hibernate.initialize(component.getRootCategory()); assetDTO.setCategories(categories); populateClientAndUsersIds(component, assetDTO); // fill flat properties assetDTO.setDetailedDescription(component.getDescription()); assetDTO.setForum(compVersion.getForum()); assetDTO.setFunctionalDescription(component.getFunctionalDesc()); assetDTO.setId(component.getId()); assetDTO.setInformationComplete(true); assetDTO.setLink(compVersion.getLink()); assetDTO.setName(component.getName()); assetDTO.setRootCategory(component.getRootCategory()); assetDTO.setShortDescription(component.getShortDesc()); //force hibernate to retrieve lazy collection List<Technology> technologies = new ArrayList<Technology>(); if (compVersion.getTechnologies() != null) { // actually, getTechnologies will not be null // just to make code more robust for (Technology tech : compVersion.getTechnologies()) { technologies.add(tech); } } assetDTO.setTechnologies(technologies); // here is the new lines add in bug fix. // start here List<Long> dependencies = new ArrayList<Long>(); if (compVersion.getDependencies() != null) { // actually, getDependencies will not be null // just to make code more robust for (CompVersion com : compVersion.getDependencies()) { dependencies.add(com.getId()); } } assetDTO.setDependencies(dependencies); assetDTO.setCompComments(compVersion.getComments()); assetDTO.setPhase(compVersion.getPhase().getDescription()); // end here. // extract production date, if it's available final CompVersionDates versionDates = compVersion.getVersionDates().get(compVersion.getPhase().getId()); if (versionDates != null) { assetDTO.setProductionDate(getXMLGregorianCalendar(versionDates.getProductionDate())); } // set version properties assetDTO.setCompVersionId(compVersion.getId()); assetDTO.setVersionText(compVersion.getVersionText()); assetDTO.setVersionNumber(compVersion.getId()); // force lazy collection List<CompDocumentation> documentation = new ArrayList<CompDocumentation>(); if (compVersion.getDocumentation() != null) { for (CompDocumentation doc : compVersion.getDocumentation()) { documentation.add(entityManager.find(CompDocumentation.class, doc.getId())); } } assetDTO.setDocumentation(documentation); return assetDTO; } /** * Populates clients' ids from <code>CompClients</code> and user's ids from <code>CompUsers</code> * of <code>Component</code> entity to the given <code>AssetDTO</code>. * @param component the component entity * @param assetDTO the assetDTO to populate with data */ private void populateClientAndUsersIds(Component component, AssetDTO assetDTO) { // extract clientIds final List<Long> clientIds = new ArrayList<Long>(); final Set<CompClient> compClients = component.getClients(); if (compClients != null && !compClients.isEmpty()) { for (CompClient compClient : compClients) { clientIds.add(compClient.getClientId()); } assetDTO.setClientIds(clientIds); } // extract userIds final Set<CompUser> compUsers = component.getUsers(); if (compUsers != null && !compUsers.isEmpty()) { final List<Long> userIds = new ArrayList<Long>(); for (CompUser compUser : compUsers) { userIds.add(compUser.getUserId()); } assetDTO.setUserIds(userIds); } } /** * <p>Updates a <code>Component</code> entity by populating fields with given <code>AssetDTO</code> instance, * creates a new <code>CompVersion</code>, which fields are also populated from the given <code>AssetDTO</code>.</p> * * @param assetDTO the original assetDTO from which to create an entity * @param component component entity to update with * @return a <code>Component</code> entity which fields populated form the given <code>AssetDTO</code> * @throws IllegalArgumentException if any of the following conditions met: * <ul> * <li>if the <code>assetDTO.name</code> is <code>null</code> or empty</li> * <li>if the <code>assetDTO.versionText</code> is <code>null</code> or empty</li> * <li>if the <code>assetDTO.shortDescription</code> is <code>null</code> or empty</li> * <li>if the <code>assetDTO.detailedDescription</code> is <code>null</code> or empty</li> * <li>if the <code>assetDTO.functionalDescription</code> is <code>null</code> or empty</li> * <li>if the <code>assetDTO.rootCategory</code> is <code>null</code></li> * <li>if the <code>assetDTO.categories</code> is <code>null</code>, empty or contains <code>null</code> item</li> * <li>if the <code>assetDTO.technologies</code> is <code>null</code>, * empty or contains <code>null</code> item</li> * <li>if the <code>assetDTO.documentation</code> is <code>null</code>, * or contains <code>null</code> item</li> * </ul> * @throws javax.persistence.PersistenceException * re-thrown from underlying persistence level * @throws PersistenceException if any passed entity cannot be found in the database, or the EntityManager * cannot be obtained */ private CompVersion updateAssetCreateVersion(AssetDTO assetDTO, Component component) throws PersistenceException { // check the version text and the technologies are valid checkString("versionText", assetDTO.getVersionText()); // techonogies can be null for conceptualization and specification //checkList("technologies", assetDTO.getTechnologies()); List<CompDocumentation> documentation = assetDTO.getDocumentation(); checkNotNull("documentation", documentation); if (documentation.contains(null)) { throw new IllegalArgumentException("List 'documentation' cannot contain a null value"); } // update component attributes updateAsset(assetDTO, component, null); final EntityManager em = getEntityManager(); // create version CompVersion compVersion = new CompVersion(); compVersion.setPhase(new Phase()); populateVersionTechnologies(assetDTO, em, compVersion); // here is the new code line add in bug fix. // start here. populateVersionDependencies(assetDTO, em, compVersion); compVersion.setComments(assetDTO.getCompComments()); compVersion.getPhase().setDescription(assetDTO.getPhase()); // end compVersion.setVersionText(assetDTO.getVersionText()); populateForumAndLink(assetDTO, compVersion); // create CompVersionDates // get latest version, if component was saved final CompVersion latestVersion = component.getId() == null ? null : getLatestVersion(component); // if one exists, then increase the version, otherwise set to the first compVersion.setVersion(latestVersion == null ? 1L : latestVersion.getVersion() + 1); if (latestVersion == null) { compVersion.setVersionText(compVersion.getVersion()+".0"); } else { String lastVersionText = latestVersion.getVersionText(); String[] versions = lastVersionText.split("\\."); // should not happen, if (versions.length < 2) { compVersion.setVersionText(compVersion.getVersion()+".0"); } else { int major = Integer.parseInt(versions[0].trim()); int minor = Integer.parseInt(versions[1].trim()); if (assetDTO.getToCreateMinorVersion() == null || (!assetDTO.getToCreateMinorVersion().booleanValue())) { major++; minor = 0; } else { minor++; } compVersion.setVersionText(major+"."+minor); } } compVersion.setComponent(component); List<CompVersion> versions = component.getVersions(); if (versions == null) { versions = new ArrayList<CompVersion>(); } populateCompVersionDates(assetDTO, compVersion); versions.add(compVersion); component.setVersions(versions); return compVersion; } /** * * @param file * @since BUGR-1600 */ private void deleteFileTree(File file) { if(file.isDirectory()) { for(File f : file.listFiles()) { deleteFileTree(f); } } file.delete(); } /** * Updates the documentation. * On the front-end, user has 2 options: * - delete existing doc (if the documentation is associated, but is no longer in assetDTO.documentation) * - upload new doc (which means item in assetDTO.uploadedFiles) * * Note: the logic in this method was wrong and was not working with multiple files. It was fixed in v1.2. * * @param assetDTO * @param compVersion * @param em the entity manager used to delete removed documentation * @throws PersistenceException * @throws PersistenceException * @throws InterruptedException * @throws IOException * @since BUGR-1600 */ private void checkAssetDocumentation(AssetDTO assetDTO, EntityManager em, CompVersion compVersion) throws PersistenceException { // BUGR-1600.2 do not return value System.out.println("Enter checkAssetDocumentation"); System.out.println("docs from asset=" + assetDTO.getCompUploadedFiles().size()); List<CompDocumentation> docs = new ArrayList<CompDocumentation>(); for(CompUploadedFile uf : assetDTO.getCompUploadedFiles()) { if(uf == null) continue; docs.add(convertUploadedFileToCompDocumentation(compVersion.getComponent(), uf.getUploadedFileDesc(), uf.getUploadedFileType())); } // we need to see which existing files we need to remove if (compVersion.getDocumentation() != null && compVersion.getDocumentation().size() > 0) { Set<CompDocumentation> removeDocs = new HashSet<CompDocumentation>(); for(CompDocumentation existingDoc: compVersion.getDocumentation()) { // just make sure, as in facade we set to null existingDoc.setCompVersion(compVersion); // if an existing document is found in uploaded collection, it means it was updated (removed, // then added) on front-end. In this case it needs to be removed. boolean remove = false; for(CompDocumentation newDoc : docs) { if(existingDoc.getDocumentName().equals(newDoc.getDocumentName()) && existingDoc.getDocumentTypeId().equals(newDoc.getDocumentTypeId())) { remove = true; System.out.println("found: " + existingDoc.getUrl()); } } if (!remove) { // if an existing document is not in asset, it means it was removed on front-end. // In this case it also needs to be removed. boolean foundInAssetDTO = false; for(int i = 0; i < assetDTO.getDocumentation().size() && !foundInAssetDTO; i++) { CompDocumentation assetDoc = assetDTO.getDocumentation().get(i); if(existingDoc.getDocumentName().equals(assetDoc.getDocumentName()) && existingDoc.getDocumentTypeId().equals(assetDoc.getDocumentTypeId())) { foundInAssetDTO = true; } } remove = !foundInAssetDTO; } if(remove) { // remove from persistence em.remove(existingDoc); removeDocs.add(existingDoc); // delete from file system String rootDir = uploadedFilesRootDir; if (!rootDir.endsWith("/")) { rootDir += "/"; } rootDir += existingDoc.getUrl(); System.out.println("deleting: " + rootDir); deleteFileTree(new File(rootDir)); } } compVersion.getDocumentation().removeAll(removeDocs); } // add uploaded docs for(int i = 0; i < docs.size(); i++) { System.out.println("adding: " + docs.get(i).getDocumentName()); try { compVersion.getDocumentation().addAll(storeUploadedFile(compVersion, assetDTO.getCompUploadedFiles().get(i))); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("Exit checkAssetDocumentation"); } /** * <p>Populates <code>CompVersion</code>'s documentation collection from the * given <code>assetDTO.documentation</code>.</p> * @param assetDTO the original assetDTO to take data from * @param em the entity manager to verify documentation exist in the persistence and to take them from it * @param compVersion the CompVersion to populate * @throws PersistenceException if a document is not found in the persistence * @since 1.1 */ private void populateVersionDocumentation(AssetDTO assetDTO, EntityManager em, CompVersion compVersion)throws PersistenceException { System.out.println("Enter populateVersionDocumentation"); //final List<CompDocumentation> documentation = new ArrayList<CompDocumentation>(); try { // check if front-end added any compDocumentations, which means error for (CompDocumentation compDocumentation : assetDTO.getDocumentation()) { // try to find each one final CompDocumentation foundCompDocumentation = em.find(CompDocumentation.class, compDocumentation.getId()); if (foundCompDocumentation == null) { // invalid technology passed throw new PersistenceException("Invalid parameter passed: there is no document with id=" + foundCompDocumentation.getId()); } //documentation.add(foundCompDocumentation); BUGR-1600 } // BUGR-1600.2 checkAssetDocumentation(assetDTO, em, compVersion); System.out.println("doc count=" + compVersion.getDocumentation().size()); System.out.println("Exit populateVersionDocumentation"); } catch (javax.persistence.PersistenceException e) { // any other errors, e.g. on JDBC level are wrapped to it throw new PersistenceException("Unexpected error: " + e.getMessage(), e); } catch (IllegalStateException e) { throw new PersistenceException("Unexpected error: " + e.getMessage(), e); } catch (IllegalArgumentException e) { throw new PersistenceException("Unexpected error: " + e.getMessage(), e); } } /** * Stores uploaded file in the file system. * * Note: unnecessary document type inference was removed. Also removed archive processing. (v1.2) * * @param file uploaded file * @throws IOException * @throws InterruptedException * @since BUGR-1600 */ private List<CompDocumentation> storeUploadedFile(CompVersion version, CompUploadedFile uf) throws PersistenceException, IOException, InterruptedException { System.out.println("Enter storeUploadedFile with filename=" + uf.getUploadedFileName()); System.out.println("ROOTDIR = " + uploadedFilesRootDir); Component component = version.getComponent(); Long lngComponent = component.getId(); Long lngVersion = version.getId(); List<CompDocumentation> result = new ArrayList<CompDocumentation>(); String remoteFileName = uf.getUploadedFileName(); String rootDir = uploadedFilesRootDir; if (!rootDir.endsWith("/")) { rootDir += "/"; } String dir = lngComponent + "/" + lngVersion + "/"; if (uf.getFileData().length > 0) { CompDocumentation parsedDoc = this.convertUploadedFileToCompDocumentation(component, uf.getUploadedFileDesc(), uf.getUploadedFileType()); long lngType = parsedDoc.getDocumentTypeId(); // Upload file String url = dir + remoteFileName; System.out.println("url=" + url); ByteArrayInputStream is = new ByteArrayInputStream(uf.getFileData()); new File(rootDir, dir).mkdirs(); System.out.println("path=" + new File(rootDir, dir).getAbsolutePath()); File f = new File(rootDir, url); if (!f.exists()) { FileOutputStream fos = new FileOutputStream(f); int b = is.read(); while (b != -1) { fos.write(b); b = is.read(); } fos.close(); is.close(); // Extract the Javadocs if (lngType == CompDocumentation.JAVADOCS) { File jDocDir = new File(f.getParent(), "javadoc"); jDocDir.mkdir(); System.out.println("Executing: jar -xf " + f.getAbsolutePath() + " in " + jDocDir.getAbsolutePath()); Runtime.getRuntime().exec("jar -xf " + f.getAbsolutePath(), new String[0], jDocDir); } // Add document to component parsedDoc.setUrl(url); result.add(parsedDoc); } else { //TEMP IGNORE //throw new PersistenceException("The file " + f.getName() + " already exists"); } } System.out.println("Exit storeUploadedFile"); return result; } /** * Simple conversion between * * Note: this method was simplified and document type inference was removed. (v1.2) * * @param component component for which the uploaded doc belongs * @param documentDesc the description of the file being converted * @param documentTypeId the document type id of the file being converted * * @return the CompDocumentation instance * * @since BUGR-1600 */ private CompDocumentation convertUploadedFileToCompDocumentation(Component component, String documentDesc, long documentTypeId) { CompDocumentation doc = new CompDocumentation(); doc.setCompVersion(component.getCurrentVersion()); doc.setDocumentName(documentDesc); doc.setDocumentTypeId(documentTypeId); return doc; } /** * <p>Populates <code>CompVersion</code>'s <code>CompVersionDates</code> map from the * given <code>assetDTO</code>.</p> * @param assetDTO the original assetDTO to take data from * @param compVersion the CompVersion to populate * @throws PersistenceException if a collaboration phase (<tt>111L</tt>) is not found in the persistence * * @throws javax.persistence.PersistenceException * re-thrown from underlying persistence level */ private void populateCompVersionDates(AssetDTO assetDTO, CompVersion compVersion) throws PersistenceException { // populate phase properties final Date zeroPointDate = buildDate(1976, 5, 5); //final Phase collaborationPhase = getEntityManager().find(Phase.class, COLLABORATION_PHASE_ID); Phase phase = getEntityManager().find(Phase.class, Phase.COLLABORATION_PHASE_ID); if (assetDTO.getPhase().equals("Development")) { phase = getEntityManager().find(Phase.class, Phase.DEVELOPMENT_PHASE_ID); } else if (assetDTO.getPhase().equals("Design")) { phase = getEntityManager().find(Phase.class, Phase.DESIGN_PHASE_ID); } compVersion.setPhase(phase); compVersion.setPhasePrice(0d); compVersion.setPhaseTime(zeroPointDate); // populate with CompVersionDates final Date stubDate = buildDate(2000, 1, 1); final Map<Long, CompVersionDates> versionDates = new HashMap<Long, CompVersionDates>(); compVersion.setVersionDates(versionDates); final CompVersionDates compVersionDates = createInitialCompVersionDates(assetDTO, zeroPointDate, stubDate); compVersionDates.setPhase(phase); compVersionDates.setCompVersion(compVersion); if (assetDTO.getPhase().equals("Development")) { versionDates.put(Phase.DEVELOPMENT_PHASE_ID, compVersionDates); } else if (assetDTO.getPhase().equals("Design")) { versionDates.put(Phase.DESIGN_PHASE_ID, compVersionDates); } else { versionDates.put(Phase.COLLABORATION_PHASE_ID, compVersionDates); } } /** * <p>Populates <code>CompVersion</code>'s <code>CompForum</code> and <code>CompLink</code> from the * given <code>assetDTO</code>.</p> * @param assetDTO the original assetDTO to take data from * @param compVersion the CompVersion to populate */ private void populateForumAndLink(AssetDTO assetDTO, CompVersion compVersion) { CompForum compForum = assetDTO.getForum(); if (compForum != null && compVersion.getForum() == null) { compVersion.setForum(compForum); compForum.setCompVersion(compVersion); } CompLink link = assetDTO.getLink(); if (link != null && compVersion.getLink() == null) { compVersion.setLink(link); link.setCompVersion(compVersion); } } /** * <p>Populates <code>CompVersion</code>'s technologies collection from the * given <code>assetDTO.technologies</code>.</p> * @param assetDTO the original assetDTO to take data from * @param em the entity manager to verify technologies exist in the persistence and to take them from it * @param compVersion the CompVersion to populate * @throws PersistenceException if a technology is not found in the persistence */ private void populateVersionTechnologies(AssetDTO assetDTO, EntityManager em, CompVersion compVersion) throws PersistenceException { final List<Technology> technologies = new ArrayList<Technology>(); try { for (Technology technology : assetDTO.getTechnologies()) { // try to find each one final Technology foundTechnology = em.find(Technology.class, technology.getId()); if (foundTechnology == null) { // invalid technology passed throw new PersistenceException("Invalid parameter passed: there is no technology with id=" + technology.getId()); } technologies.add(foundTechnology); } compVersion.setTechnologies(technologies); } catch (javax.persistence.PersistenceException e) { // any other errors, e.g. on JDBC level are wrapped to it throw new PersistenceException("Unexpected error: " + e.getMessage(), e); } catch (IllegalStateException e) { throw new PersistenceException("Unexpected error: " + e.getMessage(), e); } catch (IllegalArgumentException e) { throw new PersistenceException("Unexpected error: " + e.getMessage(), e); } } /** * <p> * Populates <code>CompVersion</code>'s dependencies collection from the * given <code>assetDTO.dependencies</code>. * </p> * * @param assetDTO the original assetDTO to take data from * @param em the entity manager to verify dependencies exist in the persistence and to take them from it * @param compVersion the CompVersion to populate * * <p> * <strong>Changes:</strong> * A new field add in bug fix. * </p> * * @throws PersistenceException if a technology is not found in the persistence */ private void populateVersionDependencies(AssetDTO assetDTO, EntityManager em, CompVersion compVersion) throws PersistenceException { final List<CompVersion> dependencies = new ArrayList<CompVersion>(); try { for (Long compId : assetDTO.getDependencies()) { // try to find each one final CompVersion foundCompVersion = em.find(CompVersion.class, compId); if (foundCompVersion == null) { // invalid compVersion passed throw new PersistenceException("Invalid parameter passed: there is no compVersion with id=" + compId); } dependencies.add(foundCompVersion); } compVersion.setDependencies(dependencies); } catch (javax.persistence.PersistenceException e) { // any other errors, e.g. on JDBC level are wrapped to it throw new PersistenceException("Unexpected error: " + e.getMessage(), e); } catch (IllegalStateException e) { throw new PersistenceException("Unexpected error: " + e.getMessage(), e); } catch (IllegalArgumentException e) { throw new PersistenceException("Unexpected error: " + e.getMessage(), e); } } /** * <p>Updates <code>Component</code> entity by populating fields with given <code>AssetDTO</code> instance.</p> * * @param assetDTO the original assetDTO from which take values to update the entity * @param component component to update with * @param versionToUpdate version to update (can be null, means no update of comp version) * @throws IllegalArgumentException if any of the following conditions met: * <ul> * <li>if the <code>assetDTO.name</code> is <code>null</code> or empty</li> * <li>if the <code>assetDTO.shortDescription</code> is <code>null</code> or empty</li> * <li>if the <code>assetDTO.detailedDescription</code> is <code>null</code> or empty</li> * <li>if the <code>assetDTO.functionalDescription</code> is <code>null</code> or empty</li> * <li>if the <code>assetDTO.rootCategory</code> is <code>null</code></li> * <li>if the <code>assetDTO.categories</code> is <code>null</code>, empty or contains <code>null</code> item</li> * empty or contains <code>null</code> item</li> * <li>if the <code>versionToUpdate</code> is not <code>null</code> * and <code>assetDTO.versionText</code> is <code>null</code> or empty</li> * <li>if the <code>versionToUpdate</code> is not <code>null</code> * and the <code>assetDTO.technologies</code> is <code>null</code>, * </ul> * @throws javax.persistence.PersistenceException * re-thrown from underlying persistence level * @throws PersistenceException if any passed entity cannot be found in the database, or the EntityManager * cannot be obtained */ private void updateAsset(AssetDTO assetDTO, Component component, CompVersion versionToUpdate) throws PersistenceException { checkString("name", assetDTO.getName()); checkString("shortDescription", assetDTO.getShortDescription()); checkString("detailedDescription", assetDTO.getDetailedDescription()); //checkString("functionalDescription", assetDTO.getFunctionalDescription()); checkNotNull("rootCategory", assetDTO.getRootCategory()); checkList("categories", assetDTO.getCategories()); if (versionToUpdate != null) { checkString("versionText", assetDTO.getVersionText()); //checkList("technologies", assetDTO.getTechnologies()); populateVersionTechnologies(assetDTO, getEntityManager(), versionToUpdate); /*if (versionToUpdate.getDocumentation() != null) { populateVersionDocumentation(assetDTO, getEntityManager(), versionToUpdate, component); // BUGR-1600 }*/ versionToUpdate.setVersionText(assetDTO.getVersionText()); populateForumAndLink(assetDTO, versionToUpdate); } // update component with categories, but get actual ones from the persistence by their id final List<Category> categories = new ArrayList<Category>(); for (Category category : assetDTO.getCategories()) { categories.add(retrieveActualCategory(category)); } component.setCategories(categories); // the same for the root one component.setRootCategory(retrieveActualCategory(assetDTO.getRootCategory())); // build lists of CompUser and CompClient entities buildClientsAndUsers(assetDTO, component); // populate flat fields component.setName(assetDTO.getName()); component.setDescription(assetDTO.getDetailedDescription()); component.setFunctionalDesc(assetDTO.getFunctionalDescription()); component.setShortDesc(assetDTO.getShortDescription()); } /** * <p>Builds lists of CompClients and CompUsers (if the corresponding ones of ids contain data).</p> * * @param assetDTO the assetDTO to get data from * @param component the component entity instance to provide data with */ private void buildClientsAndUsers(AssetDTO assetDTO, Component component) { // build clients final List<Long> clientIds = assetDTO.getClientIds(); if (clientIds != null && !clientIds.isEmpty()) { final Set<CompClient> clients = new HashSet<CompClient>(); for (Long clientId : clientIds) { CompClient compClient = new CompClient(); compClient.setClientId(clientId); compClient.setComponent(component); clients.add(compClient); } component.setClients(clients); } // extract userIds final List<Long> userIds = assetDTO.getUserIds(); if (userIds != null && !userIds.isEmpty()) { final Set<CompUser> users = new HashSet<CompUser>(); for (Long userId : userIds) { CompUser compUser = new CompUser(); compUser.setUserId(userId); compUser.setComponent(component); users.add(compUser); } component.setUsers(users); } } /** * <p>Retrieves actual category from database by given one.</p> * <p>If no such a category then <code>PersistenceException</code> is thrown.</p> * * @param category passed category parameter (from client application) * @return entity retrieved from the persistence * @throws javax.persistence.PersistenceException * re-thrown from underlying persistence level * @throws PersistenceException if any passed entity cannot be found in the database, or the EntityManager cannot be * obtained */ private Category retrieveActualCategory(Category category) throws PersistenceException { final Long categoryId = category.getId(); try { final Category entity = getEntityManager().find(Category.class, categoryId); if (entity == null) { throw new PersistenceException("Invalid category passed with ID=" + categoryId); } return entity; } catch (javax.persistence.PersistenceException e) { // any other errors, e.g. on JDBC level are wrapped to it throw new PersistenceException("Unexpected error: " + e.getMessage(), e); } catch (IllegalStateException e) { throw new PersistenceException("Unexpected error: " + e.getMessage(), e); } catch (IllegalArgumentException e) { throw new PersistenceException("Unexpected error: " + e.getMessage(), e); } } /** * <p>Retrieves the latest version of a given component entity.</p> * * @param component component entity whose latest version is being obtained * @return the latest version of the component * @throws PersistenceException if versions list is empty (which means error on persistence level, as there always * should be non-empty list of versions in a component). */ private CompVersion getLatestVersion(Component component) throws PersistenceException { final List<CompVersion> versions = component.getVersions(); if (versions == null || versions.isEmpty()) { throw new PersistenceException("Component doesn't have any versions"); } // there is always at least one version CompVersion latestVersion = versions.get(0); for (CompVersion version : versions) { if (version.getVersion() > latestVersion.getVersion()) { latestVersion = version; } } return latestVersion; } /** * <p>Creates a date by given year, month, day of month.</p> * * @param year the date's year * @param month the date's month * @param day the date's day of month * @return Date object corresponding to given string representation */ private Date buildDate(int year, int month, int day) { final Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(0L); // reset value calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, day); return calendar.getTime(); } /** * <p>Checks if an <code>Object</code> is not <code>null</code>.</p> * * @param name a name of a parameter (used to build an error message). * @param value an <code>Object</code> to check. * @throws IllegalArgumentException if the parameter is null */ private void checkNotNull(String name, Object value) { if (value == null) { throw new IllegalArgumentException("Argument '" + name + "' cannot be null"); } } /** * <p>Checks if a <code>String</code> not <code>null</code> or empty after trimming.</p> * * @param name a name of a parameter (used to build an error message). * @param value a <code>String</code> to check. * @throws IllegalArgumentException if the parameter is null or an empty String after trimming */ private void checkString(String name, String value) { checkNotNull(name, value); if (value.trim().length() == 0) { throw new IllegalArgumentException("Argument '" + name + "' cannot be empty"); } } /** * <p>Checks if a <code>List</code> is not null or empty and doesn't contain <code>null</code> values.</p> * * @param name a name of a parameter (used to build an error message). * @param value a <code>Collection</code> to check. * @throws IllegalArgumentException if the collection contains null value, or <code>emptyIsIllegal</code> is * <code>true</code> and the collection is <code>null</code> or empty */ private void checkList(String name, List<?> value) { checkNotNull(name, value); if (value.isEmpty()) { throw new IllegalArgumentException("List '" + name + "' cannot be null or empty"); } for (Object next : value) { if (next == null) { throw new IllegalArgumentException("List '" + name + "' cannot contain a null value"); } } } /** * <p>Creates a new <code>CompVersionDates</code> instance with default values, and production date * taken from passed AssetDTO instance.</p> * * @param asset an assetDTO instance * @param postingDate a value for posting date * @param otherDates a value for all other dates * @return <code>CompVersionDates</code> instance populated with default parameters and production date taken * from passed asset. */ private CompVersionDates createInitialCompVersionDates(AssetDTO asset, Date postingDate, Date otherDates) { // populate with default data final CompVersionDates compVersionDates = new CompVersionDates(); compVersionDates.setTotalSubmissions(0); compVersionDates.setPrice(0L); compVersionDates.setPostingDate(postingDate); compVersionDates.setAggregationCompleteDate(otherDates); compVersionDates.setEstimatedDevDate(otherDates); compVersionDates.setFinalSubmissionDate(otherDates); compVersionDates.setInitialSubmissionDate(otherDates); compVersionDates.setPhaseCompleteDate(otherDates); compVersionDates.setReviewCompleteDate(otherDates); compVersionDates.setScreeningCompleteDate(otherDates); compVersionDates.setWinnerAnnouncedDate(otherDates); compVersionDates.setLevelId(LEVEL_ID); compVersionDates.setStatus(Status.NEW_POST); // populate production date from the asset compVersionDates.setProductionDate(getDate(asset.getProductionDate())); return compVersionDates; } /** * <p>Returns canonized string parameter for database search (case insensitive, with doubled '\'' symbols).</p> * <p>This method introduced as Informix doesn't like JDBC queries like <tt>'%' || :param || '%'</tt>, * for unknown reason. So setting the parameter manually is a sad necessity.</p> * * @param parameter string parameter * @return canonized string parameter */ private String canonize(String parameter) { return parameter.toLowerCase().replaceAll("'", "''"); } /** * <p>Checks that <code>asset.versionId</code> is null (otherwise a version cannot be created).</p> * @param asset asset to check * @throws IllegalArgumentException if <code>asset.versionId</code> is not <code>null</code> */ private void checkNullVersionId(AssetDTO asset) { if (asset.getCompVersionId() != null) { throw new IllegalArgumentException("CompVersion already has id=" + asset.getId() + " and cannot be created."); } } /** * <p>Checks that <code>asset.id</code> is not null (otherwise an asset cannot be updated).</p> * @param asset asset to check * @throws IllegalArgumentException if <code>asset.id</code> is <code>null</code> */ private void checkComponentIdNotNull(AssetDTO asset) { if (asset.getId() == null) { throw new IllegalArgumentException("Component doesn't have id and cannot be updated."); } } /** * <p>Build joins and where clause for selecting componentIds of the Component entities which * satisfy the given criteria.</p> * @param criteria the search criteria to filter Component entities * @param subQueryString original query to append with joins and the where clause * @return map of parameters to set the query */ private Map<String, Object> buildSubQuery(SearchCriteria criteria, StringBuilder subQueryString) { final List<String> condition = new ArrayList<String>(); // map of named parameters for the query final Map<String, Object> parameters = new HashMap<String, Object>(); // add joins and parameters with tables for user_id filtering, if the criteria is set appendUserId(criteria, subQueryString, condition, parameters); // add join and parameter with tables for client_id filtering, if the criteria is set appendClientId(criteria, subQueryString, condition, parameters); // add component_name and descriptions filtering, if the corresponding criteria is set appendNameAndDescription(criteria, condition); // add root category filtering, if the criteria is set appendCategories(criteria, condition, parameters); // add component and compVersion create date criteria appendCreateDateCriteria(criteria, condition, parameters); // build 'where' clause string subQueryString.append(" WHERE "); final int conditionsCount = condition.size(); for (int i = 0; i < conditionsCount; i++) { String next = condition.get(i); if (i > 0) { subQueryString.append("\n AND "); } subQueryString.append(next); } return parameters; } /** * <p>Appends component and compVersion create date filtering</p> * @param criteria the search criteria * @param condition the list of conditions (an element for the 'where' clause can be added) * @param parameters the parameters for the query */ private void appendCreateDateCriteria(SearchCriteria criteria, List<String> condition, Map<String, Object> parameters) { final Date before = criteria.getCompCreateBeforeDate(); final Date after = criteria.getCompCreateAfterDate(); final Date versionBefore = criteria.getCompVersionCreateBeforeDate(); final Date versionAfter = criteria.getCompVersionCreateAfterDate(); if (before != null) { condition.add("(C.create_time<='"+new Timestamp(before.getTime())+"')"); } if (after != null) { condition.add("(C.create_time>='"+new Timestamp(after.getTime())+"')"); } if (versionBefore != null) { condition.add("(B.create_time<='"+new Timestamp(versionBefore.getTime())+"')"); } if (versionAfter != null) { condition.add("(B.create_time>='"+new Timestamp(versionAfter.getTime())+"')"); } } /** * <p>Appends clause for <code>Component.rootCategory</code> filtering * (if <code>criteria.categories</code> is not null).</p> * @param criteria the search criteria * @param condition the list of conditions (an element for the 'where' clause can be added) * @param parameters the parameters for the query (categoryIds are being added to it) */ private void appendCategories(SearchCriteria criteria, List<String> condition, Map<String, Object> parameters) { final List<Category> categoryList = criteria.getCategories(); if (categoryList != null) { StringBuilder categoryIds = new StringBuilder(); final int categoriesCount = categoryList.size(); // build clause like (:c0, :c1, :c2, ...) for the list of categories // and put each one to the parameters map for (int i = 0; i < categoriesCount; i++) { Category category = categoryList.get(i); final String paramName = "c" + i; if (i > 0) { categoryIds.append(","); } categoryIds.append(':').append(paramName); parameters.put(paramName, category.getId()); } condition.add("(C.root_category_id IN (" + categoryIds + "))\n"); } } /** * <p>Appends clause for <code>Component.name</code> filtering * (if <code>criteria.name</code> is not null).</p> * @param criteria the search criteria * @param condition the list of conditions (elements for the 'where' clause can be added) */ private void appendNameAndDescription(SearchCriteria criteria, List<String> condition) { // add name filtering, if the criteria is set final String name = criteria.getName(); if (name != null && name.trim().length() != 0) { condition.add("(LOWER(C.component_name) LIKE '%" + canonize(name) + "%')"); } // add description filtering, if the criteria is set final String description = criteria.getDescription(); if (description != null && description.trim().length() != 0) { String likeCondition = "LIKE '%" + canonize(description) + "%')"; condition.add( "(LOWER(C.description) " + likeCondition + " OR (LOWER(C.short_desc) " + likeCondition + " OR (LOWER(C.function_desc) " + likeCondition ); } } /** * <p>Appends clause for <code>Component.clientId</code> filtering * (if <code>criteria.clientId</code> is not null).</p> * @param criteria the search criteria * @param subQueryString original query to append with joins * @param condition the list of conditions (an element for the 'where' clause can be added) * @param parameters the parameters for the query (clientId is being added to it, if it's not null) */ private void appendClientId(SearchCriteria criteria, StringBuilder subQueryString, List<String> condition, Map<String, Object> parameters) { final Long clientId = criteria.getClientId(); if (clientId != null) { if (criteria.getUserId() == null) { // otherwise the table was already joined subQueryString.append("JOIN comp_client CL ON CL.component_id=C.component_id\n"); } condition.add("(CL.client_id=:client_id)"); parameters.put("client_id", clientId); } } /** * <p>Appends clause for <code>Component.userId</code> filtering * (if <code>criteria.userId</code> is not null).</p> * @param criteria the search criteria * @param subQueryString original query to append with joins * @param condition the list of conditions (an element for the 'where' clause can be added) * @param parameters the parameters for the query (userId is being added to it, if it's not null) */ private void appendUserId(SearchCriteria criteria, StringBuilder subQueryString, List<String> condition, Map<String, Object> parameters) { final Long userId = criteria.getUserId(); if (userId != null) { subQueryString .append("LEFT OUTER JOIN comp_user U ON C.component_id=U.component_id\n") .append("LEFT OUTER JOIN comp_client CL ON CL.component_id=C.component_id\n") .append("LEFT OUTER JOIN user_client UC ON UC.client_id=CL.client_id\n"); condition.add("(U.user_id=:user_id OR UC.user_id=:user_id)\n"); parameters.put("user_id", userId); } } /** * Get a <code>Component</code> by its ID. * * @param id the id of the Component * @return Component entity found * @throws PersistenceException on any error on the underlying persistence level * @throws EntityNotFoundException if not found an entity with the given ID */ private Component findComponentById(long id) throws PersistenceException, EntityNotFoundException { try { Component component = getEntityManager().find(Component.class, id); if (component == null) { throw new EntityNotFoundException("Component with id=" + id + " not found"); } return component; } catch (IllegalStateException e) { throw new PersistenceException("Unexpected error: " + e.getMessage(), e); } catch (IllegalArgumentException e) { throw new PersistenceException("Unexpected error: " + e.getMessage(), e); } catch (javax.persistence.PersistenceException e) { // any other errors, e.g. on JDBC level are wrapped to it throw new PersistenceException("Unexpected persistence error occurred: " + e.getMessage(), e); } } /** * <p>Retrieves list of entities by the given named query and the excpected type of entities.</p> * * @param cls expected type of entities * @param queryName the named query's name * @return list of entities returned by the query (empty list if none) * @throws PersistenceException if any error occurs on the underlying persistence level or query returned * list of invalid type */ @SuppressWarnings("unchecked") private <T> List<T> retrieveList(Class<T> cls, String queryName) throws PersistenceException { try { // simply execute the named query Query query = getEntityManager().createNamedQuery(queryName); final List resultList = query.getResultList(); if (!resultList.isEmpty()) { if (!cls.isInstance(resultList.get(0))) { throw new PersistenceException("Returned invalid collection. Elements expected as <" + cls.getName() + "> but was <" + resultList.get(0).getClass().getName() + ">"); } } return (List<T>) resultList; } catch (javax.persistence.PersistenceException e) { // any other errors, e.g. on JDBC level are wrapped to it throw new PersistenceException("Unexpected persistence error occurred: " + e.getMessage(), e); } catch (IllegalStateException e) { throw new PersistenceException("Unexpected error: " + e.getMessage(), e); } catch (IllegalArgumentException e) { throw new PersistenceException("Unexpected error: " + e.getMessage(), e); } } /** * Persist an entity, handles all possible exceptions. * * @param em the entity manger to perform operation * @param entity the entity to persist * @throws PersistenceException if any error occurs on the persistence level */ private void persistEntity(EntityManager em, Object entity) throws PersistenceException { try { em.persist(entity); } catch (IllegalStateException e) { throw new PersistenceException("The entity manager has been closed.", e); } catch (IllegalArgumentException e) { throw new PersistenceException("Object of [" + entity.getClass() + "] is not an entity.", e); } catch (EntityExistsException e) { throw new PersistenceException("The entity already exists.", e); } catch (TransactionRequiredException e) { throw new PersistenceException("Not in transaction.", e); } catch (javax.persistence.PersistenceException e) { // any other errors, e.g. on JDBC level are wrapped to it throw new PersistenceException("Unexpected error occurred on underlying persistence level:" + e.getMessage(), e); } } /** * Merges an entity, handles all possible exceptions. * * @param em the entity manger to perform operation * @param entity the entity to persist * @throws PersistenceException if any error occurs on the persistence level */ private void mergeEntity(EntityManager em, Object entity) throws PersistenceException { try { em.persist(entity); } catch (IllegalStateException e) { throw new PersistenceException("The entity manager has been closed.", e); } catch (IllegalArgumentException e) { throw new PersistenceException("Object of [" + entity.getClass() + "] is not an entity," + " or has been removed.", e); } catch (TransactionRequiredException e) { throw new PersistenceException("Not in transaction.", e); } catch (javax.persistence.PersistenceException e) { // any other errors, e.g. on JDBC level are wrapped to it throw new PersistenceException("Unexpected error occurred on underlying persistence level:" + e.getMessage(), e); } } /** * Converts standard java Date object into XMLGregorianCalendar instance. * Returns null if parameter is null. * * @param date * Date object to convert * @return converted calendar instance */ private XMLGregorianCalendar getXMLGregorianCalendar(Date date) { if (date == null) { return null; } GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); try { return DatatypeFactory.newInstance().newXMLGregorianCalendar(cal); } catch (DatatypeConfigurationException ex) { // can't create calendar, return null return null; } } /** * Converts XMLGregorianCalendar date into standard java Date object. * Returns null if argument is null. * * @param calendar * calendar instance to convert * @return converted Date instance */ private Date getDate(XMLGregorianCalendar calendar) { if (calendar == null) { return null; } return calendar.toGregorianCalendar().getTime(); } }
true
ffa34d4b10333d11056887853534a96968a0f66d
Java
azzdinemj/edu-crmclub
/educrm-api/src/main/java/com/wuxue/api/controller/junhua/TrophicAnalysisController.java
UTF-8
1,708
2.140625
2
[ "Apache-2.0" ]
permissive
package com.wuxue.api.controller.junhua; import com.wuxue.api.service.junhwa.StudentNutritionAnalysisService; import com.wuxue.api.service.junhwa.TrophicAnalysisService; import com.wuxue.model.ParentOrder; import com.wuxue.model.junhwa.StudentNutritionAnalysis; import com.wuxue.utils.contract.Request; import com.wuxue.utils.contract.Response; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * 营养分析 */ @RestController @RequestMapping(value = "api/junhua/analysis") public class TrophicAnalysisController { @Autowired private TrophicAnalysisService trophicAnalysisService; @Autowired private StudentNutritionAnalysisService studentNutritionAnalysisService; @RequestMapping(value = "/getStudentNutritionList", method = RequestMethod.POST) public Response getStudentNutritionList(@RequestBody Request<ParentOrder> request) { return trophicAnalysisService.getStudentNutritionList(request.getData()); } @RequestMapping(value = "selectMealStatistics" ,method = RequestMethod.POST) public Response selectMealStatistics(@RequestBody Request<String> request){ return trophicAnalysisService.selectMealStatistics(request); } /** * 查询学生营养元素 * @return */ @RequestMapping(value = "/getnutritionanalysis") public Response getNutritionAnalysis(@RequestBody Request<StudentNutritionAnalysis> request){ return studentNutritionAnalysisService.getNutritionAnalysisByPeriodType(request.getData()); } }
true
7c044498557e9b8ef2b22dc36cd03b5558c1856a
Java
zhongxingyu/Seer
/Diff-Raw-Data/31/31_5a6498dd14c1fbeec9581df62b66e0686918ed99/RequisitionServiceTest/31_5a6498dd14c1fbeec9581df62b66e0686918ed99_RequisitionServiceTest_s.java
UTF-8
65,345
1.617188
2
[]
no_license
/* * * * Copyright © 2013 VillageReach. All Rights Reserved. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. * * * * If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ package org.openlmis.rnr.service; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.openlmis.core.builder.FacilityBuilder; import org.openlmis.core.builder.ProcessingPeriodBuilder; import org.openlmis.core.builder.SupervisoryNodeBuilder; import org.openlmis.core.builder.UserBuilder; import org.openlmis.core.domain.*; import org.openlmis.core.exception.DataException; import org.openlmis.core.message.OpenLmisMessage; import org.openlmis.core.service.*; import org.openlmis.db.categories.UnitTests; import org.openlmis.rnr.builder.RequisitionBuilder; import org.openlmis.rnr.domain.*; import org.openlmis.rnr.repository.RequisitionRepository; import org.openlmis.rnr.search.criteria.RequisitionSearchCriteria; import org.openlmis.rnr.search.factory.RequisitionSearchStrategyFactory; import org.openlmis.rnr.search.strategy.RequisitionSearchStrategy; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import static com.natpryce.makeiteasy.MakeItEasy.*; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; import static org.openlmis.core.builder.ProcessingPeriodBuilder.defaultProcessingPeriod; import static org.openlmis.core.builder.ProcessingPeriodBuilder.numberOfMonths; import static org.openlmis.core.builder.ProductBuilder.code; import static org.openlmis.core.builder.ProductBuilder.defaultProduct; import static org.openlmis.core.builder.SupplyLineBuilder.defaultSupplyLine; import static org.openlmis.core.domain.Right.*; import static org.openlmis.rnr.builder.RequisitionBuilder.*; import static org.openlmis.rnr.builder.RnrColumnBuilder.*; import static org.openlmis.rnr.domain.ProgramRnrTemplate.*; import static org.openlmis.rnr.domain.RegimenLineItem.*; import static org.openlmis.rnr.domain.RnrStatus.*; import static org.openlmis.rnr.service.RequisitionService.*; import static org.powermock.api.mockito.PowerMockito.doNothing; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.spy; import static org.powermock.api.mockito.PowerMockito.when; import static org.powermock.api.mockito.PowerMockito.*; @Category(UnitTests.class) @RunWith(PowerMockRunner.class) @PrepareForTest(RequisitionService.class) public class RequisitionServiceTest { private static final Long HIV = 1L; private static final Facility FACILITY = new Facility(1L); private static final Program PROGRAM = new Program(3L); private static final ProcessingPeriod PERIOD = make(a(defaultProcessingPeriod, with(ProcessingPeriodBuilder.id, 10L), with(numberOfMonths, 1))); private static final Long USER_ID = 1L; @Rule public ExpectedException expectedException = ExpectedException.none(); @Mock private FacilityApprovedProductService facilityApprovedProductService; @Mock private RequisitionRepository requisitionRepository; @Mock private RnrTemplateService rnrTemplateService; @Mock private SupervisoryNodeService supervisoryNodeService; @Mock private RoleAssignmentService roleAssignmentService; @Mock private ProgramService programService; @Mock private ProcessingScheduleService processingScheduleService; @Mock private FacilityService facilityService; @Mock private SupplyLineService supplyLineService; @Mock private RegimenService regimenService; @Mock private RegimenColumnService regimenColumnService; @Mock private RequisitionEventService requisitionEventService; @Mock private RequisitionPermissionService requisitionPermissionService; @Mock private UserService userService; @InjectMocks private RequisitionSearchStrategyFactory requisitionSearchStrategyFactory; @InjectMocks private RequisitionService requisitionService; private Rnr submittedRnr; private Rnr initiatedRnr; private Rnr authorizedRnr; private Rnr inApprovalRnr; private ArrayList<RnrColumn> rnrColumns; private List<LossesAndAdjustmentsType> lossesAndAdjustmentsTypes; @Before public void setup() { requisitionService.setRequisitionSearchStrategyFactory(requisitionSearchStrategyFactory); submittedRnr = make(a(RequisitionBuilder.defaultRnr, with(status, SUBMITTED), with(modifiedBy, USER_ID))); initiatedRnr = make(a(RequisitionBuilder.defaultRnr, with(status, INITIATED), with(modifiedBy, USER_ID))); authorizedRnr = make(a(RequisitionBuilder.defaultRnr, with(status, AUTHORIZED), with(modifiedBy, USER_ID))); inApprovalRnr = make(a(defaultRnr, with(status, IN_APPROVAL), with(modifiedBy, USER_ID))); rnrColumns = new ArrayList<RnrColumn>() {{ add(new RnrColumn()); }}; lossesAndAdjustmentsTypes = mock(ArrayList.class); when(requisitionService.getLossesAndAdjustmentsTypes()).thenReturn(lossesAndAdjustmentsTypes); } @Test public void shouldInitRequisitionAndSetFieldValuesAccordingToTemplate() throws Exception { Date date = new Date(); Rnr requisition = createRequisition(PERIOD.getId(), null); setupForInitRnr(date, requisition, PERIOD); List<FacilityTypeApprovedProduct> facilityTypeApprovedProducts = new ArrayList<>(); ProgramProduct programProduct = new ProgramProduct(null, make(a(defaultProduct)), 10, true); facilityTypeApprovedProducts.add(new FacilityTypeApprovedProduct("warehouse", programProduct, 30)); when(facilityApprovedProductService.getFullSupplyFacilityApprovedProductByFacilityAndProgram(FACILITY.getId(), PROGRAM.getId())).thenReturn(facilityTypeApprovedProducts); List<Regimen> regimens = new ArrayList<>(); regimens.add(new Regimen("name", "code", 1L, true, new RegimenCategory("code", "name", 1), 1)); List<RegimenLineItem> regimenLineItems = new ArrayList<>(); regimenLineItems.add(new RegimenLineItem(null, null, 1L, 1L)); requisition.setRegimenLineItems(regimenLineItems); Rnr spyRequisition = spy(requisition); Mockito.doNothing().when(spyRequisition).setFieldsAccordingToTemplate(any(ProgramRnrTemplate.class), any(RegimenTemplate.class)); when(regimenService.getByProgram(PROGRAM.getId())).thenReturn(regimens); List<RegimenColumn> regimenColumns = new ArrayList<>(); regimenColumns.add(new RegimenColumn(PROGRAM.getId(), INITIATED_TREATMENT, "label", TYPE_NUMERIC, Boolean.TRUE, 1L)); regimenColumns.add(new RegimenColumn(PROGRAM.getId(), ON_TREATMENT, "label", TYPE_NUMERIC, Boolean.FALSE, 1L)); when(regimenColumnService.getRegimenTemplateByProgramId(PROGRAM.getId())).thenReturn(new RegimenTemplate()); whenNew(Rnr.class).withArguments(FACILITY.getId(), PROGRAM.getId(), PERIOD.getId(), false, facilityTypeApprovedProducts, regimens, USER_ID, USER_ID).thenReturn(spyRequisition); RequisitionService spyRequisitionService = spy(requisitionService); when(requisitionRepository.getById(requisition.getId())).thenReturn(spyRequisition); when(facilityService.getById(FACILITY.getId())).thenReturn(FACILITY); when(processingScheduleService.getPeriodById(PERIOD.getId())).thenReturn(PERIOD); when(programService.getById(PROGRAM.getId())).thenReturn(PROGRAM); Rnr rnr = spyRequisitionService.initiate(FACILITY.getId(), PROGRAM.getId(), PERIOD.getId(), 1L, false); verify(facilityApprovedProductService).getFullSupplyFacilityApprovedProductByFacilityAndProgram(FACILITY.getId(), PROGRAM.getId()); verify(requisitionRepository).insert(any(Rnr.class)); verify(requisitionRepository).logStatusChange(any(Rnr.class)); verify(regimenColumnService).getRegimenTemplateByProgramId(PROGRAM.getId()); assertThat(rnr, is(spyRequisition)); } @Test public void shouldInitRequisitionAndSetBeginningBalanceToZeroIfNotVisibleAndPreviousStockInHandNotAvailable() throws Exception { Date date = new Date(); Rnr requisition = spy(createRequisition(PERIOD.getId(), null)); setupForInitRnr(date, requisition, PERIOD); List<FacilityTypeApprovedProduct> facilityTypeApprovedProducts = new ArrayList<>(); ProgramProduct programProduct = new ProgramProduct(null, make(a(defaultProduct)), 10, true); facilityTypeApprovedProducts.add(new FacilityTypeApprovedProduct("warehouse", programProduct, 30)); when(facilityApprovedProductService.getFullSupplyFacilityApprovedProductByFacilityAndProgram(FACILITY.getId(), PROGRAM.getId())).thenReturn(facilityTypeApprovedProducts); ArrayList<RnrColumn> rnrColumns = getRnrColumns(); rnrColumns.add(make(a(defaultRnrColumn, with(columnName, BEGINNING_BALANCE), with(visible, false)))); when(rnrTemplateService.fetchProgramTemplateForRequisition(PROGRAM.getId())).thenReturn(new ProgramRnrTemplate(rnrColumns)); when(requisitionRepository.getRequisitionWithLineItems(FACILITY, PROGRAM, PERIOD)).thenReturn(requisition); List<Regimen> regimens = new ArrayList<>(); when(regimenService.getByProgram(PROGRAM.getId())).thenReturn(regimens); whenNew(Rnr.class).withArguments(FACILITY.getId(), PROGRAM.getId(), PERIOD.getId(), false, facilityTypeApprovedProducts, regimens, USER_ID, USER_ID).thenReturn(requisition); Mockito.doNothing().when(requisition).setFieldsAccordingToTemplate(any(ProgramRnrTemplate.class), any(RegimenTemplate.class)); requisitionService.initiate(FACILITY.getId(), PROGRAM.getId(), PERIOD.getId(), 1L, false); assertThat(requisition.getFullSupplyLineItems().get(0).getBeginningBalance(), is(0)); } @Test public void shouldInitRequisitionAndNotSetBeginningBalanceToZeroIfVisibleAndPreviousStockInHandNotAvailable() throws Exception { Date date = new Date(); Rnr requisition = spy(createRequisition(PERIOD.getId(), null)); requisition.getFullSupplyLineItems().get(0).setBeginningBalance(null); setupForInitRnr(date, requisition, PERIOD); List<FacilityTypeApprovedProduct> facilityTypeApprovedProducts = new ArrayList<>(); ProgramProduct programProduct = new ProgramProduct(null, make(a(defaultProduct)), 10, true); facilityTypeApprovedProducts.add(new FacilityTypeApprovedProduct("warehouse", programProduct, 30)); when(facilityApprovedProductService.getFullSupplyFacilityApprovedProductByFacilityAndProgram(FACILITY.getId(), PROGRAM.getId())).thenReturn(facilityTypeApprovedProducts); ArrayList<RnrColumn> rnrColumns = getRnrColumns(); rnrColumns.add(make(a(defaultRnrColumn, with(columnName, BEGINNING_BALANCE), with(visible, true)))); when(rnrTemplateService.fetchProgramTemplateForRequisition(PROGRAM.getId())).thenReturn(new ProgramRnrTemplate(rnrColumns)); List<Regimen> regimens = new ArrayList<>(); when(regimenService.getByProgram(PROGRAM.getId())).thenReturn(regimens); whenNew(Rnr.class).withArguments(FACILITY.getId(), PROGRAM.getId(), PERIOD.getId(), false, facilityTypeApprovedProducts, regimens, USER_ID, USER_ID).thenReturn(requisition); Mockito.doNothing().when(requisition).setFieldsAccordingToTemplate(any(ProgramRnrTemplate.class), any(RegimenTemplate.class)); requisitionService.initiate(FACILITY.getId(), PROGRAM.getId(), PERIOD.getId(), 1L, false); assertThat(requisition.getFullSupplyLineItems().get(0).getBeginningBalance(), is(nullValue())); } private ArrayList<RnrColumn> getRnrColumns() { return new ArrayList<RnrColumn>() {{ add(make(a(defaultRnrColumn, with(columnName, QUANTITY_RECEIVED), with(visible, false)))); add(make(a(defaultRnrColumn, with(columnName, QUANTITY_DISPENSED), with(visible, false)))); add(make(a(defaultRnrColumn, with(columnName, LOSSES_AND_ADJUSTMENTS), with(visible, false)))); add(make(a(defaultRnrColumn, with(columnName, NEW_PATIENT_COUNT), with(visible, true)))); add(make(a(defaultRnrColumn, with(columnName, STOCK_OUT_DAYS), with(visible, true)))); add(make(a(defaultRnrColumn, with(columnName, STOCK_IN_HAND), with(visible, false)))); add(make(a(defaultRnrColumn, with(columnName, BEGINNING_BALANCE), with(visible, true)))); }}; } @Test public void shouldGetRequisition() throws Exception { Rnr requisition = spy(new Rnr()); requisition.setFacility(FACILITY); requisition.setProgram(PROGRAM); requisition.setPeriod(PERIOD); when(requisitionRepository.getRequisitionWithLineItems(FACILITY, PROGRAM, new ProcessingPeriod(PERIOD.getId()))).thenReturn(requisition); when(programService.getById(PROGRAM.getId())).thenReturn(PROGRAM); when(facilityService.getById(FACILITY.getId())).thenReturn(FACILITY); when(processingScheduleService.getPeriodById(PERIOD.getId())).thenReturn(PERIOD); RequisitionSearchCriteria criteria = new RequisitionSearchCriteria(FACILITY.getId(), PROGRAM.getId(), PERIOD.getId()); Rnr actualRequisition = requisitionService.get(criteria).get(0); assertThat(actualRequisition, is(requisition)); verify(requisition).fillBasicInformation(FACILITY, PROGRAM, PERIOD); } @Test public void shouldGetPreviousTwoRequisitionsNormalizedConsumptionsWhileGettingRequisition() throws Exception { final Long lastPeriodId = 2L; final Long secondLastPeriodsId = 3L; ProcessingPeriod lastPeriod = make(a(ProcessingPeriodBuilder.defaultProcessingPeriod, with(ProcessingPeriodBuilder.id, lastPeriodId))); Rnr rnr = new Rnr(FACILITY, PROGRAM, PERIOD); final Rnr spyRnr = spy(rnr); when(requisitionRepository.getRequisitionWithLineItems(new Facility(FACILITY.getId()), new Program(PROGRAM.getId()), new ProcessingPeriod(PERIOD.getId()))).thenReturn(spyRnr); ProcessingPeriod period = new ProcessingPeriod(PERIOD.getId(), PERIOD.getStartDate(), PERIOD.getEndDate(), PERIOD.getNumberOfMonths(), PERIOD.getName()); when(processingScheduleService.getPeriodById(10L)).thenReturn(period); when(processingScheduleService.getImmediatePreviousPeriod(period)).thenReturn(lastPeriod); ProcessingPeriod secondLastPeriod = make(a(ProcessingPeriodBuilder.defaultProcessingPeriod, with(ProcessingPeriodBuilder.id, secondLastPeriodsId))); when(processingScheduleService.getImmediatePreviousPeriod(lastPeriod)).thenReturn(secondLastPeriod); Rnr lastPeriodsRnr = new Rnr(FACILITY, PROGRAM, lastPeriod); when(requisitionRepository.getRequisitionWithLineItems(FACILITY, PROGRAM, lastPeriod)).thenReturn(lastPeriodsRnr); Rnr secondLastPeriodsRnr = new Rnr(FACILITY, PROGRAM, secondLastPeriod); when(requisitionRepository.getRequisitionWithLineItems(FACILITY, PROGRAM, secondLastPeriod)).thenReturn(secondLastPeriodsRnr); when(programService.getById(PROGRAM.getId())).thenReturn(PROGRAM); when(facilityService.getById(FACILITY.getId())).thenReturn(FACILITY); when(processingScheduleService.getPeriodById(PERIOD.getId())).thenReturn(PERIOD); RequisitionSearchCriteria criteria = new RequisitionSearchCriteria(FACILITY.getId(), PROGRAM.getId(), PERIOD.getId()); final Rnr actual = requisitionService.get(criteria).get(0); assertThat(actual, is(spyRnr)); verify(spyRnr).fillLastTwoPeriodsNormalizedConsumptions(lastPeriodsRnr, secondLastPeriodsRnr); } @Test public void shouldGetAllPeriodsForInitiatingRequisitionWhenThereIsAtLeastOneExistingRequisitionInThePostSubmitFlow() throws Exception { DateTime date1 = new DateTime(); DateTime date2 = date1.minusMonths(1); DateTime date3 = date1.minusMonths(2); DateTime date4 = date1.minusMonths(3); ProcessingPeriod processingPeriod1 = createProcessingPeriod(10L, date1); ProcessingPeriod processingPeriod2 = createProcessingPeriod(20L, date2); ProcessingPeriod processingPeriod3 = createProcessingPeriod(30L, date3); ProcessingPeriod processingPeriod4 = createProcessingPeriod(40L, date4); createRequisition(processingPeriod1.getId(), AUTHORIZED); Rnr rnr2 = createRequisition(processingPeriod2.getId(), APPROVED); createRequisition(processingPeriod3.getId(), INITIATED); when(programService.getProgramStartDate(FACILITY.getId(), PROGRAM.getId())).thenReturn(date1.toDate()); when(requisitionRepository.getLastRequisitionToEnterThePostSubmitFlow(FACILITY.getId(), PROGRAM.getId())).thenReturn(rnr2); when(processingScheduleService.getAllPeriodsAfterDateAndPeriod(FACILITY.getId(), PROGRAM.getId(), date1.toDate(), processingPeriod2.getId())). thenReturn(Arrays.asList(processingPeriod3, processingPeriod4)); List<ProcessingPeriod> periods = requisitionService.getAllPeriodsForInitiatingRequisition(new RequisitionSearchCriteria(FACILITY.getId(), PROGRAM.getId())); assertThat(periods.size(), is(2)); assertThat(periods.get(0), is(processingPeriod3)); assertThat(periods.get(1), is(processingPeriod4)); } @Test public void shouldGetAllPeriodsForInitiatingRequisitionWhenThereIsNoRequisitionInThePostSubmitFlow() throws Exception { DateTime date1 = new DateTime(); DateTime date2 = date1.minusMonths(1); ProcessingPeriod processingPeriod1 = createProcessingPeriod(10L, date1); ProcessingPeriod processingPeriod2 = createProcessingPeriod(20L, date2); when(programService.getProgramStartDate(FACILITY.getId(), PROGRAM.getId())).thenReturn(date1.toDate()); when(requisitionRepository.getLastRequisitionToEnterThePostSubmitFlow(FACILITY.getId(), PROGRAM.getId())).thenReturn(null); when(processingScheduleService.getAllPeriodsAfterDateAndPeriod(FACILITY.getId(), PROGRAM.getId(), date1.toDate(), null)). thenReturn(Arrays.asList(processingPeriod1, processingPeriod2)); List<ProcessingPeriod> periods = requisitionService.getAllPeriodsForInitiatingRequisition(new RequisitionSearchCriteria(FACILITY.getId(), PROGRAM.getId())); assertThat(periods.size(), is(2)); assertThat(periods.get(0), is(processingPeriod1)); assertThat(periods.get(1), is(processingPeriod2)); } private Rnr createRequisition(Long periodId, RnrStatus status) { Facility defaultFacility = make(a(FacilityBuilder.defaultFacility)); defaultFacility.setId(1L); return make(a(RequisitionBuilder.defaultRnr, with(RequisitionBuilder.facility, defaultFacility), with(RequisitionBuilder.periodId, periodId), with(RequisitionBuilder.status, status))); } private ProcessingPeriod createProcessingPeriod(Long id, DateTime startDate) { ProcessingPeriod processingPeriod = make(a(defaultProcessingPeriod, with(ProcessingPeriodBuilder.startDate, startDate.toDate()))); processingPeriod.setId(id); return processingPeriod; } @Test public void shouldNotInitRequisitionIfTemplateNotDefined() { when(requisitionPermissionService.hasPermission(USER_ID, FACILITY, PROGRAM, CREATE_REQUISITION)).thenReturn(true); when(rnrTemplateService.fetchProgramTemplateForRequisition(PROGRAM.getId())).thenReturn(new ProgramRnrTemplate(new ArrayList<RnrColumn>())); expectedException.expect(DataException.class); expectedException.expectMessage("error.rnr.template.not.defined"); Rnr rnr = requisitionService.initiate(FACILITY.getId(), PROGRAM.getId(), PERIOD.getId(), USER_ID, false); verify(facilityApprovedProductService, never()).getFullSupplyFacilityApprovedProductByFacilityAndProgram(FACILITY.getId(), HIV); verify(requisitionRepository, never()).insert(rnr); } @Test public void shouldNotInitRequisitionIfPeriodDoesNotAllowInitiation() throws Exception { Date date = new Date(); Rnr requisition = createRequisition(PERIOD.getId(), null); ProcessingPeriod validPeriod = new ProcessingPeriod(1L); setupForInitRnr(date, requisition, validPeriod); expectedException.expect(DataException.class); expectedException.expectMessage("error.rnr.previous.not.filled"); requisitionService.initiate(FACILITY.getId(), PROGRAM.getId(), PERIOD.getId(), USER_ID, false); verify(programService).getProgramStartDate(FACILITY.getId(), PROGRAM.getId()); verify(requisitionRepository).getLastRequisitionToEnterThePostSubmitFlow(FACILITY.getId(), PROGRAM.getId()); verify(processingScheduleService).getAllPeriodsAfterDateAndPeriod(FACILITY.getId(), PROGRAM.getId(), date, validPeriod.getId()); } @Test public void shouldInitEmergencyRequisitionEvenIfPreviousPeriodRnrNotFilled() throws Exception { Date date = new Date(); Rnr requisition = createRequisition(PERIOD.getId(), null); ProcessingPeriod validPeriod = new ProcessingPeriod(1L); setupForInitRnr(date, requisition, validPeriod); List<FacilityTypeApprovedProduct> facilityTypeApprovedProducts = new ArrayList<>(); ProgramProduct programProduct = new ProgramProduct(null, make(a(defaultProduct)), 10, true); facilityTypeApprovedProducts.add(new FacilityTypeApprovedProduct("warehouse", programProduct, 30)); when(facilityApprovedProductService.getFullSupplyFacilityApprovedProductByFacilityAndProgram(FACILITY.getId(), PROGRAM.getId())).thenReturn(facilityTypeApprovedProducts); List<Regimen> regimens = new ArrayList<>(); regimens.add(new Regimen("name", "code", 1L, true, new RegimenCategory("code", "name", 1), 1)); List<RegimenLineItem> regimenLineItems = new ArrayList<>(); regimenLineItems.add(new RegimenLineItem(null, null, 1L, 1L)); requisition.setRegimenLineItems(regimenLineItems); Rnr spyRequisition = spy(requisition); Mockito.doNothing().when(spyRequisition).setFieldsAccordingToTemplate(any(ProgramRnrTemplate.class), any(RegimenTemplate.class)); when(regimenService.getByProgram(PROGRAM.getId())).thenReturn(regimens); List<RegimenColumn> regimenColumns = new ArrayList<>(); regimenColumns.add(new RegimenColumn(PROGRAM.getId(), INITIATED_TREATMENT, "label", TYPE_NUMERIC, Boolean.TRUE, 1L)); regimenColumns.add(new RegimenColumn(PROGRAM.getId(), ON_TREATMENT, "label", TYPE_NUMERIC, Boolean.FALSE, 1L)); when(regimenColumnService.getRegimenTemplateByProgramId(PROGRAM.getId())).thenReturn(new RegimenTemplate()); whenNew(Rnr.class).withArguments(FACILITY.getId(), PROGRAM.getId(), PERIOD.getId(), true, facilityTypeApprovedProducts, regimens, USER_ID, USER_ID).thenReturn(spyRequisition); RequisitionService spyRequisitionService = spy(requisitionService); when(requisitionRepository.getById(requisition.getId())).thenReturn(spyRequisition); when(facilityService.getById(FACILITY.getId())).thenReturn(FACILITY); when(processingScheduleService.getPeriodById(PERIOD.getId())).thenReturn(PERIOD); when(programService.getById(PROGRAM.getId())).thenReturn(PROGRAM); Rnr rnr = spyRequisitionService.initiate(FACILITY.getId(), PROGRAM.getId(), PERIOD.getId(), 1L, true); verify(facilityApprovedProductService).getFullSupplyFacilityApprovedProductByFacilityAndProgram(FACILITY.getId(), PROGRAM.getId()); verify(requisitionRepository).insert(any(Rnr.class)); verify(requisitionRepository).logStatusChange(any(Rnr.class)); verify(regimenColumnService).getRegimenTemplateByProgramId(PROGRAM.getId()); assertThat(rnr, is(spyRequisition)); } private void setupForInitRnr(Date date, Rnr requisition, ProcessingPeriod validPeriod) { when(requisitionPermissionService.hasPermission(USER_ID, FACILITY, PROGRAM, CREATE_REQUISITION)).thenReturn(true); when(rnrTemplateService.fetchProgramTemplateForRequisition(PROGRAM.getId())).thenReturn(new ProgramRnrTemplate(getRnrColumns())); when(programService.getProgramStartDate(FACILITY.getId(), PROGRAM.getId())).thenReturn(date); when(requisitionRepository.getLastRequisitionToEnterThePostSubmitFlow(FACILITY.getId(), PROGRAM.getId())).thenReturn(requisition); when(processingScheduleService.getAllPeriodsAfterDateAndPeriod(FACILITY.getId(), PROGRAM.getId(), date, PERIOD.getId())). thenReturn(Arrays.asList(validPeriod)); } private void setupForInitRnr(Rnr requisition) { Date date = new Date(); when(requisitionPermissionService.hasPermission(USER_ID, FACILITY, PROGRAM, CREATE_REQUISITION)).thenReturn(true); when(rnrTemplateService.fetchProgramTemplateForRequisition(PROGRAM.getId())).thenReturn(new ProgramRnrTemplate(getRnrColumns())); when(programService.getProgramStartDate(FACILITY.getId(), PROGRAM.getId())).thenReturn(date); when(requisitionRepository.getLastRequisitionToEnterThePostSubmitFlow(FACILITY.getId(), PROGRAM.getId())).thenReturn(requisition); when(processingScheduleService.getAllPeriodsAfterDateAndPeriod(FACILITY.getId(), PROGRAM.getId(), date, PERIOD.getId())). thenReturn(asList(PERIOD)); } @Test public void shouldReturnMessageIfSupervisingNodeNotPresent() throws Exception { when(supervisoryNodeService.getFor(FACILITY, PROGRAM)).thenReturn(null); OpenLmisMessage message = requisitionService.getSubmitMessageBasedOnSupervisoryNode(FACILITY, PROGRAM); assertThat(message.getCode(), is("msg.rnr.submitted.without.supervisor")); } @Test public void shouldSubmitValidRnrWithSubmittedDate() { Rnr savedRnr = getFilledSavedRequisitionWithDefaultFacilityProgramPeriod(initiatedRnr, CREATE_REQUISITION); ProgramRnrTemplate template = new ProgramRnrTemplate(rnrColumns); when(rnrTemplateService.fetchProgramTemplate(PROGRAM.getId())).thenReturn(template); doNothing().when(savedRnr).calculate(template, lossesAndAdjustmentsTypes); when(supervisoryNodeService.getFor(FACILITY, PROGRAM)).thenReturn(new SupervisoryNode()); Rnr submittedRnr = requisitionService.submit(initiatedRnr); verify(requisitionRepository).update(savedRnr); verify(requisitionRepository).logStatusChange(savedRnr); // assertThat(submittedRnr.getSubmittedDate(), is(notNullValue())); assertThat(submittedRnr.getStatus(), is(SUBMITTED)); } @Test public void shouldAuthorizeAValidRnrAndTagWithSupervisoryNode() throws Exception { Rnr savedRnr = getFilledSavedRequisitionWithDefaultFacilityProgramPeriod(submittedRnr, AUTHORIZE_REQUISITION); ProgramRnrTemplate template = new ProgramRnrTemplate(rnrColumns); when(rnrTemplateService.fetchProgramTemplate(PROGRAM.getId())).thenReturn(template); doNothing().when(savedRnr).calculate(template, lossesAndAdjustmentsTypes); SupervisoryNode approverNode = new SupervisoryNode(); when(supervisoryNodeService.getFor(FACILITY, PROGRAM)).thenReturn(approverNode); Rnr authorizedRnr = requisitionService.authorize(submittedRnr); verify(rnrTemplateService).fetchProgramTemplate(PROGRAM.getId()); verify(requisitionRepository).update(savedRnr); verify(requisitionRepository).logStatusChange(savedRnr); assertThat(authorizedRnr.getStatus(), is(AUTHORIZED)); assertThat(authorizedRnr.getSupervisoryNodeId(), is(approverNode.getId())); } @Test public void shouldAuthorizeAValidRnr() throws Exception { Rnr savedRnr = getFilledSavedRequisitionWithDefaultFacilityProgramPeriod(submittedRnr, AUTHORIZE_REQUISITION); ProgramRnrTemplate template = new ProgramRnrTemplate(rnrColumns); when(rnrTemplateService.fetchProgramTemplate(PROGRAM.getId())).thenReturn(template); doNothing().when(savedRnr).calculate(template, lossesAndAdjustmentsTypes); SupervisoryNode node = make(a(SupervisoryNodeBuilder.defaultSupervisoryNode)); when(supervisoryNodeService.getFor(savedRnr.getFacility(), savedRnr.getProgram())).thenReturn(node); doNothing().when(savedRnr).fillBasicInformation(FACILITY, PROGRAM, PERIOD); Rnr authorizedRnr = requisitionService.authorize(submittedRnr); verify(rnrTemplateService).fetchProgramTemplate(savedRnr.getProgram().getId()); verify(requisitionRepository).update(savedRnr); assertThat(authorizedRnr.getStatus(), is(AUTHORIZED)); } @Test public void shouldNotAuthorizeRnrIfNotSubmitted() throws Exception { Rnr savedRnr = getFilledSavedRequisitionWithDefaultFacilityProgramPeriod(initiatedRnr, AUTHORIZE_REQUISITION); doNothing().when(savedRnr).fillBasicInformation(FACILITY, PROGRAM, PERIOD); expectedException.expect(DataException.class); expectedException.expectMessage(RNR_AUTHORIZATION_ERROR); requisitionService.authorize(initiatedRnr); } @Test public void shouldGiveSuccessMessageIfApproverExist() throws Exception { when(supervisoryNodeService.getApproverFor(FACILITY, PROGRAM)).thenReturn(new User()); OpenLmisMessage message = requisitionService.getAuthorizeMessageBasedOnSupervisoryNode(FACILITY, PROGRAM); assertThat(message.getCode(), is(RNR_AUTHORIZED_SUCCESSFULLY)); } @Test public void shouldGiveAuthorizedSuccessWithoutApproverMessageIfApproverDoesNotExist() throws Exception { when(supervisoryNodeService.getApproverFor(FACILITY, PROGRAM)).thenReturn(null); OpenLmisMessage message = requisitionService.getAuthorizeMessageBasedOnSupervisoryNode(FACILITY, PROGRAM); assertThat(message.getCode(), is(RNR_AUTHORIZED_SUCCESSFULLY_WITHOUT_SUPERVISOR)); } @Test public void shouldGiveApprovedSuccessIfParentDoesNotExist() throws Exception { Rnr rnr = make(a(defaultRnr)); when(supervisoryNodeService.getParent(rnr.getSupervisoryNodeId())).thenReturn(null); OpenLmisMessage message = requisitionService.getApproveMessageBasedOnParentNode(rnr); assertThat(message.getCode(), is(RNR_APPROVED_SUCCESSFULLY)); } @Test public void shouldGiveApprovedSuccessIfParentExistWtihSupervisor() throws Exception { Rnr rnr = make(a(defaultRnr)); SupervisoryNode parent = new SupervisoryNode(); when(supervisoryNodeService.getParent(rnr.getSupervisoryNodeId())).thenReturn(parent); when(supervisoryNodeService.getApproverForGivenSupervisoryNodeAndProgram(parent, rnr.getProgram())).thenReturn(new User()); OpenLmisMessage message = requisitionService.getApproveMessageBasedOnParentNode(rnr); assertThat(message.getCode(), is(RNR_APPROVED_SUCCESSFULLY)); } @Test public void shouldGiveApprovedSuccessWithoutSupervisorIfApproverDoesNotExitAtParentNode() throws Exception { Rnr rnr = make(a(defaultRnr)); SupervisoryNode parent = new SupervisoryNode(); when(supervisoryNodeService.getParent(rnr.getSupervisoryNodeId())).thenReturn(parent); when(supervisoryNodeService.getApproverForGivenSupervisoryNodeAndProgram(parent, rnr.getProgram())).thenReturn(null); OpenLmisMessage message = requisitionService.getApproveMessageBasedOnParentNode(rnr); assertThat(message.getCode(), is(RNR_APPROVED_SUCCESSFULLY_WITHOUT_SUPERVISOR)); } @Test public void shouldSaveRnrIfUserHasAppropriatePermission() { Rnr savedRnr = spy(getFilledSavedRequisitionWithDefaultFacilityProgramPeriod(initiatedRnr, CREATE_REQUISITION)); ProgramRnrTemplate template = new ProgramRnrTemplate(rnrColumns); RegimenTemplate regimenTemplate = new RegimenTemplate(savedRnr.getProgram().getId(), new ArrayList<RegimenColumn>()); Mockito.when(requisitionRepository.getById(savedRnr.getId())).thenReturn(savedRnr); when(rnrTemplateService.fetchProgramTemplate(initiatedRnr.getProgram().getId())).thenReturn(template); Mockito.when(regimenColumnService.getRegimenTemplateByProgramId(initiatedRnr.getProgram().getId())).thenReturn(regimenTemplate); Mockito.doNothing().when(savedRnr).copyCreatorEditableFields(initiatedRnr, template, regimenTemplate); Mockito.doNothing().when(savedRnr).fillBasicInformation(FACILITY, PROGRAM, PERIOD); when(requisitionPermissionService.hasPermissionToSave(USER_ID, savedRnr)).thenReturn(true); initiatedRnr.setModifiedBy(USER_ID); requisitionService.save(initiatedRnr); verify(requisitionRepository).update(savedRnr); } @Test public void shouldNotSaveUserDoesNotHaveAppropriatePermission() { Rnr savedRnr = spy(submittedRnr); savedRnr.setModifiedBy(USER_ID); savedRnr.setFacility(FACILITY); savedRnr.setProgram(PROGRAM); savedRnr.setPeriod(PERIOD); when(programService.getById(PROGRAM.getId())).thenReturn(PROGRAM); when(facilityService.getById(FACILITY.getId())).thenReturn(FACILITY); when(processingScheduleService.getPeriodById(PERIOD.getId())).thenReturn(PERIOD); when(requisitionRepository.getById(submittedRnr.getId())).thenReturn(savedRnr); when(requisitionPermissionService.hasPermissionToSave(USER_ID, savedRnr)).thenReturn(false); expectedException.expect(DataException.class); expectedException.expectMessage(RNR_OPERATION_UNAUTHORIZED); requisitionService.save(submittedRnr); } @Test public void shouldFetchAllRequisitionsForFacilitiesAndProgramSupervisedByUserForApproval() throws Exception { final RoleAssignment firstAssignment = new RoleAssignment(1L, 1L, 1L, new SupervisoryNode()); final RoleAssignment secondAssignment = new RoleAssignment(2L, 2L, 2L, new SupervisoryNode()); final Rnr requisition = make(a(RequisitionBuilder.defaultRnr)); final List<Rnr> requisitionsForFirstAssignment = new ArrayList<Rnr>() {{ add(requisition); }}; final List<Rnr> requisitionsForSecondAssignment = new ArrayList<>(); List<RoleAssignment> roleAssignments = new ArrayList<RoleAssignment>() {{ add(firstAssignment); add(secondAssignment); }}; when(roleAssignmentService.getRoleAssignments(APPROVE_REQUISITION, USER_ID)).thenReturn(roleAssignments); when(requisitionRepository.getAuthorizedRequisitions(firstAssignment)).thenReturn(requisitionsForFirstAssignment); when(requisitionRepository.getAuthorizedRequisitions(secondAssignment)).thenReturn(requisitionsForSecondAssignment); Program expectedProgram = new Program(); Facility expectedFacility = new Facility(); ProcessingPeriod expectedPeriod = new ProcessingPeriod(); when(programService.getById(3L)).thenReturn(expectedProgram); when(facilityService.getById(3L)).thenReturn(expectedFacility); when(processingScheduleService.getPeriodById(3L)).thenReturn(expectedPeriod); List<Rnr> requisitions = requisitionService.listForApproval(USER_ID); List<Rnr> expectedRequisitions = new ArrayList<Rnr>() {{ addAll(requisitionsForFirstAssignment); addAll(requisitionsForSecondAssignment); }}; assertThat(requisitions, is(expectedRequisitions)); assertThat(requisition.getProgram(), is(expectedProgram)); assertThat(requisition.getFacility(), is(expectedFacility)); assertThat(requisition.getPeriod(), is(expectedPeriod)); verify(requisitionRepository, times(1)).getAuthorizedRequisitions(firstAssignment); verify(requisitionRepository, times(1)).getAuthorizedRequisitions(secondAssignment); } @Test public void shouldNotApproveAnRnrIfStatusIsNotAuthorized() throws Exception { Rnr savedRnr = spy(submittedRnr); savedRnr.setFacility(FACILITY); savedRnr.setProgram(PROGRAM); savedRnr.setPeriod(PERIOD); when(requisitionPermissionService.hasPermission(USER_ID, savedRnr, APPROVE_REQUISITION)).thenReturn(true); when(programService.getById(PROGRAM.getId())).thenReturn(PROGRAM); when(facilityService.getById(FACILITY.getId())).thenReturn(FACILITY); when(processingScheduleService.getPeriodById(PERIOD.getId())).thenReturn(PERIOD); when(requisitionRepository.getById(submittedRnr.getId())).thenReturn(savedRnr); expectedException.expect(DataException.class); expectedException.expectMessage(RNR_OPERATION_UNAUTHORIZED); requisitionService.approve(submittedRnr); } @Test public void shouldApproveAnRnrAndChangeStatusToApprovedIfThereIsNoFurtherApprovalNeeded() throws Exception { Long supervisoryNodeId = 1L; Rnr savedRnr = getFilledSavedRequisitionWithDefaultFacilityProgramPeriod(authorizedRnr, APPROVE_REQUISITION); savedRnr.setSupervisoryNodeId(supervisoryNodeId); SupervisoryNode supervisoryNode = new SupervisoryNode(); supervisoryNode.setId(supervisoryNodeId); SupplyLine supplyLine = mock(SupplyLine.class); savedRnr.setStatus(IN_APPROVAL); when(supplyLineService.getSupplyLineBy(supervisoryNode, PROGRAM)).thenReturn(supplyLine); Facility supplyingDepot = new Facility(); when(supplyLine.getSupplyingFacility()).thenReturn(supplyingDepot); requisitionService.approve(authorizedRnr); verify(requisitionRepository).approve(savedRnr); verify(requisitionRepository).logStatusChange(savedRnr); assertThat(savedRnr.getStatus(), is(APPROVED)); assertThat(savedRnr.getSupervisoryNodeId(), is(supervisoryNodeId)); assertThat(savedRnr.getModifiedBy(), is(USER_ID)); } @Test public void shouldDoFinalApprovalOfAnRnrAndTagWithSupplyLine() throws Exception { Long supervisoryNodeId = 1L; Rnr savedRnr = getFilledSavedRequisitionWithDefaultFacilityProgramPeriod(authorizedRnr, APPROVE_REQUISITION); savedRnr.setSupervisoryNodeId(supervisoryNodeId); SupervisoryNode supervisoryNode = new SupervisoryNode(); supervisoryNode.setId(supervisoryNodeId); SupplyLine supplyLine = new SupplyLine(); when(supplyLineService.getSupplyLineBy(supervisoryNode, PROGRAM)).thenReturn(supplyLine); Rnr rnr = requisitionService.approve(authorizedRnr); } @Test public void shouldValidateRnrForApproval() throws Exception { Rnr spyRnr = spy(authorizedRnr); spyRnr.setFacility(FACILITY); spyRnr.setProgram(PROGRAM); spyRnr.setPeriod(PERIOD); when(programService.getById(PROGRAM.getId())).thenReturn(PROGRAM); when(facilityService.getById(FACILITY.getId())).thenReturn(FACILITY); when(processingScheduleService.getPeriodById(PERIOD.getId())).thenReturn(PERIOD); when(requisitionRepository.getById(authorizedRnr.getId())).thenReturn(spyRnr); Mockito.doThrow(new DataException("some error")).when(spyRnr).validateForApproval(); expectedException.expect(DataException.class); expectedException.expectMessage("some error"); requisitionService.approve(spyRnr); } @Test public void shouldApproveAnRnrAndKeepStatusInApprovalIfFurtherApprovalNeeded() throws Exception { Rnr savedRnr = getFilledSavedRequisitionWithDefaultFacilityProgramPeriod(authorizedRnr, APPROVE_REQUISITION); savedRnr.setSupervisoryNodeId(1L); SupervisoryNode parentNode = new SupervisoryNode() {{ setId(2L); }}; when(supervisoryNodeService.getParent(1L)).thenReturn(parentNode); when(supervisoryNodeService.getApproverForGivenSupervisoryNodeAndProgram(parentNode, PROGRAM)).thenReturn(new User()); savedRnr.setSupervisoryNodeId(1l); SupervisoryNode supervisoryNode = new SupervisoryNode(); supervisoryNode.setId(1l); SupplyLine supplyLine = mock(SupplyLine.class); when(supplyLineService.getSupplyLineBy(supervisoryNode, PROGRAM)).thenReturn(supplyLine); Facility supplyingDepot = new Facility(); when(supplyLine.getSupplyingFacility()).thenReturn(supplyingDepot); requisitionService.approve(authorizedRnr); verify(requisitionRepository).approve(savedRnr); verify(requisitionRepository).logStatusChange(savedRnr); verify(requisitionEventService).notifyForStatusChange(savedRnr); assertThat(savedRnr.getStatus(), is(IN_APPROVAL)); assertThat(savedRnr.getSupervisoryNodeId(), is(2L)); assertThat(savedRnr.getModifiedBy(), is(USER_ID)); } @Test public void shouldApproveAnRnrAndKeepStatusInApprovalIfFurtherApprovalNeededAndShouldGiveMessageIfThereIsNoSupervisorAssigned() throws Exception { Rnr savedRnr = getFilledSavedRequisitionWithDefaultFacilityProgramPeriod(authorizedRnr, APPROVE_REQUISITION); savedRnr.setSupervisoryNodeId(1L); SupervisoryNode parentNode = new SupervisoryNode() {{ setId(2L); }}; when(supervisoryNodeService.getParent(1L)).thenReturn(parentNode); when(supervisoryNodeService.getApproverForGivenSupervisoryNodeAndProgram(parentNode, authorizedRnr.getProgram())).thenReturn(null); savedRnr.setSupervisoryNodeId(1l); SupervisoryNode supervisoryNode = new SupervisoryNode(); supervisoryNode.setId(1l); SupplyLine supplyLine = mock(SupplyLine.class); when(supplyLineService.getSupplyLineBy(supervisoryNode, PROGRAM)).thenReturn(supplyLine); Facility supplyingDepot = new Facility(); when(supplyLine.getSupplyingFacility()).thenReturn(supplyingDepot); requisitionService.approve(authorizedRnr); verify(requisitionRepository).approve(savedRnr); assertThat(savedRnr.getStatus(), is(IN_APPROVAL)); assertThat(savedRnr.getSupervisoryNodeId(), is(2L)); assertThat(savedRnr.getModifiedBy(), is(USER_ID)); } @Test public void shouldFillBeginningBalanceOfLineItemsFromPreviousRequisitionIfAvailableDuringInitialize() throws Exception { Date date = new Date(); ProcessingPeriod period = new ProcessingPeriod(10L); Rnr someRequisition = createRequisition(period.getId(), null); Rnr previousRnr = make(a(defaultRnr)); ProcessingPeriod previousPeriod = make(a(defaultProcessingPeriod, with(ProcessingPeriodBuilder.id, period.getId() - 1))); setupForInitRnr(date, someRequisition, period); Rnr spyRequisition = spy(someRequisition); List<FacilityTypeApprovedProduct> facilityTypeApprovedProducts = new ArrayList<>(); ProgramProduct programProduct = new ProgramProduct(null, make(a(defaultProduct)), 10, true); facilityTypeApprovedProducts.add(new FacilityTypeApprovedProduct("warehouse", programProduct, 30)); ProgramProduct programProduct2 = new ProgramProduct(null, make(a(defaultProduct, with(code, "testCode"))), 10, true); facilityTypeApprovedProducts.add(new FacilityTypeApprovedProduct("warehouse", programProduct2, 30)); when(facilityApprovedProductService.getFullSupplyFacilityApprovedProductByFacilityAndProgram(FACILITY.getId(), PROGRAM.getId())).thenReturn(facilityTypeApprovedProducts); when(processingScheduleService.getImmediatePreviousPeriod(spyRequisition.getPeriod())).thenReturn(previousPeriod); when(requisitionRepository.getRequisitionWithLineItems(spyRequisition.getFacility(), spyRequisition.getProgram(), previousPeriod)).thenReturn(previousRnr); List<Regimen> regimens = new ArrayList<>(); when(regimenService.getByProgram(PROGRAM.getId())).thenReturn(regimens); whenNew(Rnr.class).withArguments(FACILITY.getId(), PROGRAM.getId(), period.getId(), false, facilityTypeApprovedProducts, regimens, USER_ID, USER_ID).thenReturn(spyRequisition); Mockito.doNothing().when(spyRequisition).setFieldsAccordingToTemplate(any(ProgramRnrTemplate.class), any(RegimenTemplate.class)); requisitionService.initiate(FACILITY.getId(), PROGRAM.getId(), period.getId(), USER_ID, false); verify(spyRequisition).setBeginningBalances(previousRnr, true); } @Test public void shouldNotFillBeginningBalanceIfPreviousRnrNotDefinedDuringInitiate() throws Exception { Date date = new Date(); Rnr someRequisition = createRequisition(PERIOD.getId(), null); setupForInitRnr(date, someRequisition, PERIOD); List<FacilityTypeApprovedProduct> facilityTypeApprovedProducts = new ArrayList<>(); ProgramProduct programProduct = new ProgramProduct(null, make(a(defaultProduct)), 10, true); facilityTypeApprovedProducts.add(new FacilityTypeApprovedProduct("warehouse", programProduct, 30)); when(facilityApprovedProductService.getFullSupplyFacilityApprovedProductByFacilityAndProgram(FACILITY.getId(), PROGRAM.getId())).thenReturn(facilityTypeApprovedProducts); Rnr spyRequisition = spy(someRequisition); List<Regimen> regimens = new ArrayList<>(); when(regimenService.getByProgram(PROGRAM.getId())).thenReturn(regimens); whenNew(Rnr.class).withArguments(FACILITY.getId(), PROGRAM.getId(), PERIOD.getId(), false, facilityTypeApprovedProducts, regimens, USER_ID, USER_ID).thenReturn(spyRequisition); Mockito.doNothing().when(spyRequisition).setFieldsAccordingToTemplate(any(ProgramRnrTemplate.class), any(RegimenTemplate.class)); Long previousPeriodId = PERIOD.getId() - 1L; ProcessingPeriod previousPeriod = make(a(defaultProcessingPeriod, with(ProcessingPeriodBuilder.id, previousPeriodId))); when(processingScheduleService.getPeriodById(PERIOD.getId())).thenReturn(PERIOD); when(processingScheduleService.getImmediatePreviousPeriod(PERIOD)).thenReturn(previousPeriod); when(requisitionRepository.getRequisitionWithLineItems(FACILITY, PROGRAM, previousPeriod)).thenReturn(null); when(processingScheduleService.getPeriodById(PERIOD.getId())).thenReturn(PERIOD); requisitionService.initiate(FACILITY.getId(), PROGRAM.getId(), PERIOD.getId(), USER_ID, false); verify(spyRequisition).setBeginningBalances(null, true); } @Test public void shouldFillBeginningBalanceFromPreviousRequisitionEvenIfStockInHandIsNotDisplayed() throws Exception { Date date = new Date(); ProcessingPeriod period = new ProcessingPeriod(10L); Rnr someRequisition = createRequisition(period.getId(), null); Rnr previousRnr = make(a(defaultRnr)); ProcessingPeriod previousPeriod = make(a(defaultProcessingPeriod, with(ProcessingPeriodBuilder.id, period.getId() - 1))); setupForInitRnr(date, someRequisition, period); when(rnrTemplateService.fetchProgramTemplateForRequisition(PROGRAM.getId())).thenReturn(new ProgramRnrTemplate(getRnrColumns())); Rnr spyRequisition = spy(someRequisition); List<FacilityTypeApprovedProduct> facilityTypeApprovedProducts = new ArrayList<>(); ProgramProduct programProduct = new ProgramProduct(null, make(a(defaultProduct)), 10, true); facilityTypeApprovedProducts.add(new FacilityTypeApprovedProduct("warehouse", programProduct, 30)); ProgramProduct programProduct2 = new ProgramProduct(null, make(a(defaultProduct, with(code, "testCode"))), 10, true); facilityTypeApprovedProducts.add(new FacilityTypeApprovedProduct("warehouse", programProduct2, 30)); when(facilityApprovedProductService.getFullSupplyFacilityApprovedProductByFacilityAndProgram(FACILITY.getId(), PROGRAM.getId())).thenReturn(facilityTypeApprovedProducts); when(processingScheduleService.getImmediatePreviousPeriod(spyRequisition.getPeriod())).thenReturn(previousPeriod); when(requisitionRepository.getRequisitionWithLineItems(spyRequisition.getFacility(), spyRequisition.getProgram(), previousPeriod)).thenReturn(previousRnr); List<Regimen> regimens = new ArrayList<>(); when(regimenService.getByProgram(PROGRAM.getId())).thenReturn(regimens); whenNew(Rnr.class).withArguments(FACILITY.getId(), PROGRAM.getId(), period.getId(), false, facilityTypeApprovedProducts, regimens, USER_ID, USER_ID).thenReturn(spyRequisition); Mockito.doNothing().when(spyRequisition).setFieldsAccordingToTemplate(any(ProgramRnrTemplate.class), any(RegimenTemplate.class)); requisitionService.initiate(FACILITY.getId(), PROGRAM.getId(), period.getId(), USER_ID, false); verify(spyRequisition).setBeginningBalances(previousRnr, true); } @Test public void shouldDoCalculatePacksToShipAndCostOnApprove() throws Exception { Rnr spyRnr = getFilledSavedRequisitionWithDefaultFacilityProgramPeriod(authorizedRnr, APPROVE_REQUISITION); doNothing().when(spyRnr).calculateForApproval(); requisitionService.approve(spyRnr); verify(spyRnr).calculateForApproval(); } @Test public void shouldGetRequisitionsForViewForGivenFacilityProgramsAndPeriodRange() throws Exception { final Rnr requisition = make(a(RequisitionBuilder.defaultRnr)); final List<Rnr> expected = new ArrayList<Rnr>() {{ add(requisition); }}; Program expectedProgram = requisition.getProgram(); Facility expectedFacility = requisition.getFacility(); ProcessingPeriod expectedPeriod = requisition.getPeriod(); when(programService.getById(3L)).thenReturn(expectedProgram); when(facilityService.getById(3L)).thenReturn(expectedFacility); when(processingScheduleService.getPeriodById(3L)).thenReturn(expectedPeriod); Facility facility = new Facility(1L); Program program = new Program(2L); Date dateRangeStart = DateTime.parse("2013-02-01").toDate(); Date dateRangeEnd = DateTime.parse("2013-02-14").toDate(); RequisitionSearchCriteria criteria = new RequisitionSearchCriteria(facility.getId(), program.getId(), dateRangeStart, dateRangeEnd); RequisitionSearchStrategy searchStrategy = mock(RequisitionSearchStrategy.class); RequisitionSearchStrategyFactory spyFactory = spy(requisitionSearchStrategyFactory); requisitionService.setRequisitionSearchStrategyFactory(spyFactory); when(spyFactory.getSearchStrategy(criteria)).thenReturn(searchStrategy); when(searchStrategy.search()).thenReturn(expected); List<Rnr> actual = requisitionService.get(criteria); assertThat(actual, is(expected)); verify(spyFactory).getSearchStrategy(criteria); verify(programService).getById(3L); verify(facilityService).getById(3L); verify(processingScheduleService).getPeriodById(3L); } @Test public void shouldGetFullRequisitionById() { Long requisitionId = 1L; Rnr requisition = spy(new Rnr()); requisition.setFacility(FACILITY); requisition.setProgram(PROGRAM); requisition.setPeriod(PERIOD); requisition.setId(requisitionId); requisition.setStatus(RnrStatus.APPROVED); when(programService.getById(PROGRAM.getId())).thenReturn(PROGRAM); when(facilityService.getById(FACILITY.getId())).thenReturn(FACILITY); when(processingScheduleService.getPeriodById(PERIOD.getId())).thenReturn(PERIOD); when(requisitionRepository.getById(requisitionId)).thenReturn(requisition); requisition.setSupervisoryNodeId(1l); SupervisoryNode supervisoryNode = new SupervisoryNode(); supervisoryNode.setId(1l); SupplyLine supplyLine = mock(SupplyLine.class); when(supplyLineService.getSupplyLineBy(supervisoryNode, PROGRAM)).thenReturn(supplyLine); Facility supplyingDepot = new Facility(); when(supplyLine.getSupplyingFacility()).thenReturn(supplyingDepot); Rnr fullRequisition = requisitionService.getFullRequisitionById(requisitionId); verify(requisitionRepository).getById(requisitionId); verify(facilityService).getById(FACILITY.getId()); verify(programService).getById(PROGRAM.getId()); verify(processingScheduleService).getPeriodById(PERIOD.getId()); assertThat(fullRequisition.getSupplyingDepot(), is(supplyingDepot)); } @Test public void shouldGetRequisitionFilledWithSupplyLine() { Long requisitionId = 1L; Rnr requisition = spy(new Rnr()); SupplyLine supplyLine = new SupplyLine(); supplyLine.setId(3L); SupplyLine filledSupplyLine = make(a(defaultSupplyLine)); requisition.setFacility(FACILITY); requisition.setProgram(PROGRAM); requisition.setPeriod(PERIOD); requisition.setId(requisitionId); when(supplyLineService.getById(3L)).thenReturn(filledSupplyLine); when(requisitionRepository.getById(requisitionId)).thenReturn(requisition); Mockito.doNothing().when(requisition).fillBasicInformation(any(Facility.class), any(Program.class), any(ProcessingPeriod.class)); Rnr returnedRnr = requisitionService.getFullRequisitionById(requisitionId); } @Test public void shouldNotFillSupplyLineIfRequisitionNotTagged() { Long requisitionId = 1L; Rnr requisition = spy(new Rnr()); requisition.setFacility(FACILITY); requisition.setProgram(PROGRAM); requisition.setPeriod(PERIOD); requisition.setId(requisitionId); when(requisitionRepository.getById(requisitionId)).thenReturn(requisition); Mockito.doNothing().when(requisition).fillBasicInformation(any(Facility.class), any(Program.class), any(ProcessingPeriod.class)); requisitionService.getFullRequisitionById(requisitionId); verify(supplyLineService, never()).getById(anyLong()); } @Test public void shouldCheckForPermissionBeforeInitiatingRnr() throws Exception { when(requisitionPermissionService.hasPermission(USER_ID, FACILITY, PROGRAM, CREATE_REQUISITION)).thenReturn(false); expectedException.expect(DataException.class); expectedException.expectMessage(RNR_OPERATION_UNAUTHORIZED); requisitionService.initiate(FACILITY.getId(), PROGRAM.getId(), PERIOD.getId(), USER_ID, false); } @Test public void shouldCheckForPermissionBeforeSubmittingRnr() throws Exception { Rnr savedRnr = getFilledSavedRequisitionWithDefaultFacilityProgramPeriod(initiatedRnr, CREATE_REQUISITION); when(requisitionPermissionService.hasPermission(USER_ID, savedRnr, CREATE_REQUISITION)).thenReturn(false); expectedException.expect(DataException.class); expectedException.expectMessage(RNR_OPERATION_UNAUTHORIZED); requisitionService.submit(initiatedRnr); } @Test public void shouldCheckForPermissionBeforeAuthorizingRnr() throws Exception { Rnr savedRnr = getFilledSavedRequisitionWithDefaultFacilityProgramPeriod(submittedRnr, CREATE_REQUISITION); when(requisitionPermissionService.hasPermission(USER_ID, savedRnr, AUTHORIZE_REQUISITION)).thenReturn(false); expectedException.expect(DataException.class); expectedException.expectMessage(RNR_OPERATION_UNAUTHORIZED); requisitionService.authorize(submittedRnr); } @Test public void shouldCheckForPermissionBeforeApprovingRnr() throws Exception { Rnr savedRnr = getFilledSavedRequisitionWithDefaultFacilityProgramPeriod(authorizedRnr, CREATE_REQUISITION); when(requisitionPermissionService.hasPermission(USER_ID, savedRnr, APPROVE_REQUISITION)).thenReturn(false); expectedException.expect(DataException.class); expectedException.expectMessage(RNR_ALREADY_APPROVED); requisitionService.approve(authorizedRnr); } @Test public void shouldGetCategoryCount() { Rnr requisition = new Rnr(); boolean fullSupply = true; when(requisitionRepository.getCategoryCount(requisition, fullSupply)).thenReturn(10); Integer categoryCount = requisitionService.getCategoryCount(requisition, fullSupply); assertThat(categoryCount, is(10)); verify(requisitionRepository).getCategoryCount(requisition, fullSupply); } @Test public void shouldInsertComment() throws Exception { Comment comment = new Comment(); requisitionService.insertComment(comment); verify(requisitionRepository).insertComment(comment); } @Test public void shouldNotifyStatusChangeEvent() throws Exception { Rnr requisition = spy(createRequisition(PERIOD.getId(), INITIATED)); setupForInitRnr(requisition); whenNew(Rnr.class).withAnyArguments().thenReturn(requisition); Mockito.doNothing().when(requisition).setFieldsAccordingToTemplate(any(ProgramRnrTemplate.class), any(RegimenTemplate.class)); requisitionService.initiate(FACILITY.getId(), PROGRAM.getId(), PERIOD.getId(), 1L, false); verify(requisitionEventService).notifyForStatusChange(requisition); } @Test public void shouldNotifyStatusChangeOnAuthorize() throws Exception { Rnr savedRnr = getFilledSavedRequisitionWithDefaultFacilityProgramPeriod(submittedRnr, AUTHORIZE_REQUISITION); ProgramRnrTemplate template = new ProgramRnrTemplate(rnrColumns); when(rnrTemplateService.fetchProgramTemplate(PROGRAM.getId())).thenReturn(template); doNothing().when(savedRnr).calculate(template, lossesAndAdjustmentsTypes); when(supervisoryNodeService.getApproverFor(FACILITY, PROGRAM)).thenReturn(new User()); SupervisoryNode approverNode = new SupervisoryNode(); when(supervisoryNodeService.getFor(FACILITY, PROGRAM)).thenReturn(approverNode); requisitionService.authorize(submittedRnr); verify(requisitionEventService).notifyForStatusChange(savedRnr); } @Test public void shouldSetDefaultApprovedQuantityOnAuthorization() throws Exception { Rnr savedRnr = getFilledSavedRequisitionWithDefaultFacilityProgramPeriod(submittedRnr, AUTHORIZE_REQUISITION); ProgramRnrTemplate template = new ProgramRnrTemplate(rnrColumns); when(rnrTemplateService.fetchProgramTemplate(PROGRAM.getId())).thenReturn(template); doNothing().when(savedRnr).calculate(template, lossesAndAdjustmentsTypes); when(supervisoryNodeService.getApproverFor(FACILITY, PROGRAM)).thenReturn(new User()); SupervisoryNode approverNode = new SupervisoryNode(); when(supervisoryNodeService.getFor(FACILITY, PROGRAM)).thenReturn(approverNode); doNothing().when(savedRnr).setDefaultApprovedQuantity(); requisitionService.authorize(submittedRnr); verify(savedRnr).setDefaultApprovedQuantity(); } @Test public void shouldNotifyStatusChangeOnSubmit() throws Exception { Rnr savedRnr = getFilledSavedRequisitionWithDefaultFacilityProgramPeriod(initiatedRnr, CREATE_REQUISITION); ProgramRnrTemplate template = new ProgramRnrTemplate(rnrColumns); when(rnrTemplateService.fetchProgramTemplate(PROGRAM.getId())).thenReturn(template); doNothing().when(savedRnr).calculate(template, lossesAndAdjustmentsTypes); when(rnrTemplateService.fetchAllRnRColumns(PROGRAM.getId())).thenReturn(rnrColumns); requisitionService.submit(initiatedRnr); verify(requisitionEventService).notifyForStatusChange(savedRnr); } @Test public void shouldGetAllCommentsForARnrWithUsername() throws Exception { User user = make(a(UserBuilder.defaultUser)); ArrayList<Comment> comments = new ArrayList<>(); Comment comment = new Comment(); User author = new User(); author.setId(USER_ID); comment.setAuthor(author); comments.add(comment); when(requisitionRepository.getCommentsByRnrID(1L)).thenReturn(comments); User spyUser = spy(user); User userReturned = new User(); userReturned.setId(1L); userReturned.setUserName(user.getUserName()); when(spyUser.basicInformation()).thenReturn(userReturned); when(userService.getById(USER_ID)).thenReturn(spyUser); List<Comment> returnedComments = requisitionService.getCommentsByRnrId(1L); verify(requisitionRepository).getCommentsByRnrID(1L); User commentUser = comments.get(0).getAuthor(); verify(spyUser).basicInformation(); assertThat(commentUser.getUserName(), is(user.getUserName())); assertThat(comments, is(returnedComments)); } @Test public void shouldReleaseRequisitionAsOrder() throws Exception { when(requisitionPermissionService.hasPermission(USER_ID, CONVERT_TO_ORDER)).thenReturn(true); final Rnr rnr = spy(authorizedRnr); when(requisitionRepository.getById(authorizedRnr.getId())).thenReturn(rnr); List<Rnr> rnrList = new ArrayList<Rnr>() {{ add(rnr); }}; requisitionService.releaseRequisitionsAsOrder(rnrList, USER_ID); verify(rnr).convertToOrder(USER_ID); } @Test public void shouldNotifyStatusChangeToReleased() throws Exception { when(requisitionPermissionService.hasPermission(USER_ID, CONVERT_TO_ORDER)).thenReturn(true); final Rnr rnr = spy(authorizedRnr); when(requisitionRepository.getById(authorizedRnr.getId())).thenReturn(rnr); List<Rnr> rnrList = new ArrayList<Rnr>() {{ add(rnr); }}; requisitionService.releaseRequisitionsAsOrder(rnrList, USER_ID); verify(requisitionEventService).notifyForStatusChange(rnr); } @Test public void shouldSaveRnrWithOnlyThoseFieldsWhichAreCreatorEditableBasedOnRnrStatus() throws Exception { Rnr savedRequisition = getFilledSavedRequisitionWithDefaultFacilityProgramPeriod(initiatedRnr, CREATE_REQUISITION); ProgramRnrTemplate template = new ProgramRnrTemplate(new ArrayList<RnrColumn>()); RegimenTemplate regimenTemplate = new RegimenTemplate(savedRequisition.getProgram().getId(), new ArrayList<RegimenColumn>()); doNothing().when(savedRequisition).copyCreatorEditableFields(initiatedRnr, template, regimenTemplate); when(rnrTemplateService.fetchProgramTemplate(savedRequisition.getProgram().getId())).thenReturn(template); Mockito.when(regimenColumnService.getRegimenTemplateByProgramId(initiatedRnr.getProgram().getId())).thenReturn(regimenTemplate); requisitionService.save(initiatedRnr); verify(savedRequisition).copyCreatorEditableFields(initiatedRnr, template, regimenTemplate); verify(requisitionRepository).update(savedRequisition); } @Test public void shouldSaveRnrWithOnlyThoseFieldsWhichAreApproverEditableBasedOnRnrStatus() throws Exception { Rnr savedRequisition = getFilledSavedRequisitionWithDefaultFacilityProgramPeriod(authorizedRnr, APPROVE_REQUISITION); ProgramRnrTemplate template = new ProgramRnrTemplate(new ArrayList<RnrColumn>()); when(rnrTemplateService.fetchProgramTemplate(savedRequisition.getProgram().getId())).thenReturn(template); doNothing().when(savedRequisition).copyApproverEditableFields(authorizedRnr, template); requisitionService.save(authorizedRnr); verify(savedRequisition).copyApproverEditableFields(authorizedRnr, template); verify(requisitionRepository).update(savedRequisition); } @Test public void shouldSaveRnrWithOnlyThoseFieldsWhichAreApproverEditableBasedInApprovalStatus() throws Exception { Rnr savedRequisition = getFilledSavedRequisitionWithDefaultFacilityProgramPeriod(inApprovalRnr, APPROVE_REQUISITION); ProgramRnrTemplate template = new ProgramRnrTemplate(new ArrayList<RnrColumn>()); when(rnrTemplateService.fetchProgramTemplate(savedRequisition.getProgram().getId())).thenReturn(template); doNothing().when(savedRequisition).copyApproverEditableFields(inApprovalRnr, template); requisitionService.save(inApprovalRnr); verify(savedRequisition).copyApproverEditableFields(inApprovalRnr, template); verify(requisitionRepository).update(savedRequisition); } @Test public void shouldGetLWRnrById() throws Exception { Rnr expectedRnr = new Rnr(); Long rnrId = 1L; Mockito.when(requisitionRepository.getLWById(rnrId)).thenReturn(expectedRnr); Rnr returnedRnr = requisitionService.getLWById(rnrId); assertThat(returnedRnr, is(expectedRnr)); } @Test public void shouldNotSubmittedIfRnrAlreadySubmitted() throws Exception { Rnr submittedRnr = getFilledSavedRequisitionWithDefaultFacilityProgramPeriod(this.submittedRnr, CREATE_REQUISITION); expectedException.expect(DataException.class); expectedException.expectMessage(RNR_SUBMISSION_ERROR); requisitionService.submit(submittedRnr); } @Test public void shouldNotAuthorizeIfRnrAlreadyAuthorized() throws Exception { Rnr authorizedRnr = getFilledSavedRequisitionWithDefaultFacilityProgramPeriod(this.authorizedRnr, AUTHORIZE_REQUISITION); expectedException.expect(DataException.class); expectedException.expectMessage(RNR_AUTHORIZATION_ERROR); requisitionService.authorize(authorizedRnr); } @Test public void shouldGetCurrentPeriodForFacilityAndProgram() { Date programStartDate = new Date(); when(programService.getProgramStartDate(1L, 2L)).thenReturn(programStartDate); requisitionService.getCurrentPeriod(new RequisitionSearchCriteria(1L, 2L)); verify(processingScheduleService).getCurrentPeriod(1L, 2L, programStartDate); } private Rnr getFilledSavedRequisitionWithDefaultFacilityProgramPeriod(Rnr rnr, Right right) { Rnr savedRnr = spy(rnr); when(requisitionPermissionService.hasPermissionToSave(USER_ID, savedRnr)).thenReturn(true); when(requisitionPermissionService.hasPermission(USER_ID, savedRnr, right)).thenReturn(true); when(programService.getById(savedRnr.getProgram().getId())).thenReturn(PROGRAM); when(facilityService.getById(savedRnr.getFacility().getId())).thenReturn(FACILITY); when(processingScheduleService.getPeriodById(savedRnr.getProgram().getId())).thenReturn(PERIOD); when(requisitionRepository.getById(rnr.getId())).thenReturn(savedRnr); return savedRnr; } }
true
7fe6ce83ddfa6deb03846d53252716de000e6fe1
Java
dmifed/JavaRush
/2.JavaCore/src/tests/CharArrayToString.java
UTF-8
429
3.109375
3
[]
no_license
package tests; /** * Created by dima on 01.03.2017. */ public class CharArrayToString { public static void main(String[] args) { String s= "abcdef"; char[] chars = s.toCharArray(); StringBuilder stringBuilder = new StringBuilder(); for(int i = chars.length-1; i>=0; i--){ stringBuilder.append(chars[i]); } System.out.println(stringBuilder.toString()); } }
true
67f322933c51012a1880bbd2960cd808c2a7223a
Java
maomengya/eclipseremeto
/2.1 第二章1—顺序表/src/第二章_顺序表/Student.java
GB18030
1,092
3.640625
4
[]
no_license
package ڶ_˳; public class Student extends Object implements Comparable<Student> //ѧ { String name; // int score; //ijſγ̳ɼ public Student (String name,int score) //췽 { this.name = name; this.score = score; } public String toString() //ضַʽΪ(,) { return "("+this.name+"<"+this.score+")"; } public boolean equals(Object obj) //Ƚ϶ǷȣȽname { //Stringequals(Object)ȽǷ return this == obj||(obj instanceof Student)&&this.name.equals(((Student)obj).name); } public int compareTo(Student stu) //Ƚ϶СʵComparable<T>ӿ { return this.score-stu.score; //ɼȽ϶С } }
true
23870d81a2f6ffe9bebc3b2ede783a90e2e28b31
Java
voxwivas/lab-inventory
/src/main/java/com/labfolder/labexperimentinventory/devices/store/FakeDeviceStore.java
UTF-8
2,190
3.015625
3
[]
no_license
package com.labfolder.labexperimentinventory.devices.store; import com.labfolder.labexperimentinventory.devices.models.Device; import com.labfolder.labexperimentinventory.exceptions.DeviceExistsException; import com.labfolder.labexperimentinventory.exceptions.DeviceNotFoundException; import java.util.*; public class FakeDeviceStore implements DeviceStore { private final Map<Long, Device> devices = new HashMap<>(); @Override public Long saveDevice(Device device) { if (checkDeviceExists(device)) { throw new DeviceExistsException(String.format("Device with element name %s already exixts", device.getElement())); } else { Long id = (long) nextDeviceId(); var deviceToSave = new Device( id, device.getElement(), device.getMassInKg(), device.getLengthInMeters(), device.getDiameterInMeters(), device.getRemarks() ); devices.put(id, deviceToSave); return id; } } @Override public Device updateDevice(Device device) { var device1 = devices.get(device.getId()); if (device1 == null) { throw new DeviceNotFoundException(String.format("Device with id %n for update does not exist", device.getId())); } else { devices.put(device.getId(), device); } return device; } @Override public Optional<Device> getDeviceById(Long deviceId) { var device1 = devices.get(deviceId); if (device1 == null) { throw new DeviceNotFoundException(String.format("Device with id %n for update does not exist", deviceId)); } else { return Optional.of(devices.get(deviceId)); } } @Override public Optional<List<Device>> getAllDevices() { return Optional.of(new ArrayList<>(devices.values())); } private boolean checkDeviceExists(Device device) { return devices.values().stream().anyMatch(c -> c.isSameDevice(device)); } private int nextDeviceId() { return devices.size() + 1; } }
true
609d91f7ad5dc893991896f2aa1e5455e82f36a5
Java
marssong123/FrameApp
/ioc/src/main/java/com/ssjj/ioc/http/PutTask.java
UTF-8
915
2.265625
2
[]
no_license
package com.ssjj.ioc.http; import com.android.volley.AuthFailureError; import com.android.volley.Request; import java.util.Map; /** * Created by GZ1581 on 2016/5/30 */ public class PutTask extends HttpTask { private String mBodyContentType; private Map<String, String> mBodyParams; private byte[] mBody; public PutTask(String url, RequestParams params, HttpClient.ResultHandler handler) { super(Request.Method.PUT, url, params, handler); } @Override public byte[] getBody() throws AuthFailureError { return null == mBody ? super.getBody() : mBody; } @Override protected Map<String, String> getParams() throws AuthFailureError { return mBodyParams; } @Override public String getBodyContentType() { return null == mBodyContentType ? super.getBodyContentType() : mBodyContentType; } }
true
c29adc29205ac88cf447029d7994ca4838275419
Java
ducpm8/CloudinaryUploadTool
/src/main/java/cloudinary/repositories/ImageObject.java
UTF-8
2,563
2.46875
2
[]
no_license
package cloudinary.repositories; public class ImageObject { public String sku = ""; public String image1; public String image2; public String image3; public String image4; public String newImage1; public String newImage2; public String newImage3; public String newImage4; public String reason = ""; public String line = ""; /** * @return the newImage1 */ public String getNewImage1() { return newImage1; } /** * @param newImage1 the newImage1 to set */ public void setNewImage1(String newImage1) { this.newImage1 = newImage1; } /** * @return the newImage2 */ public String getNewImage2() { return newImage2; } /** * @param newImage2 the newImage2 to set */ public void setNewImage2(String newImage2) { this.newImage2 = newImage2; } /** * @return the newImage3 */ public String getNewImage3() { return newImage3; } /** * @param newImage3 the newImage3 to set */ public void setNewImage3(String newImage3) { this.newImage3 = newImage3; } /** * @return the newImage4 */ public String getNewImage4() { return newImage4; } /** * @param newImage4 the newImage4 to set */ public void setNewImage4(String newImage4) { this.newImage4 = newImage4; } /** * @return the setReason */ public String getReason() { return reason; } /** * @param setReason the setReason to set */ public void setReason(String reason) { this.reason = reason; } /** * @return the line */ public String getLine() { return line; } /** * @param line the line to set */ public void setLine(String line) { this.line = line; } /** * @return the sku */ public String getSku() { return sku; } /** * @param sku the sku to set */ public void setSku(String sku) { this.sku = sku; } /** * @return the image1 */ public String getImage1() { return image1; } /** * @param image1 the image1 to set */ public void setImage1(String image1) { this.image1 = image1; } /** * @return the image2 */ public String getImage2() { return image2; } /** * @param image2 the image2 to set */ public void setImage2(String image2) { this.image2 = image2; } /** * @return the image3 */ public String getImage3() { return image3; } /** * @param image3 the image3 to set */ public void setImage3(String image3) { this.image3 = image3; } /** * @return the image4 */ public String getImage4() { return image4; } /** * @param image4 the image4 to set */ public void setImage4(String image4) { this.image4 = image4; } }
true
d4ea1484ce6d0c13e45b702ae81064aea95549ac
Java
sudcea/openjsfshop
/src/main/java/com/openshop/beans/UserSearchBean.java
UTF-8
972
2.21875
2
[]
no_license
package com.openshop.beans; /** * User: Patrick Trautmann * Date: 13.05.11 * Time: 18:15 * Contact & Support: http://sharea.de */ public class UserSearchBean { private String eMail; private String prename; private String surname; public UserSearchBean() { } private boolean isNotNullOrEmpty(Object obj) { return (obj != null && !obj.equals("")); } public String geteMail() { return (isNotNullOrEmpty(eMail)) ? eMail : null; } public void seteMail(String eMail) { this.eMail = eMail; } public String getPrename() { return (isNotNullOrEmpty(prename)) ? prename : null; } public void setPrename(String prename) { this.prename = prename; } public String getSurname() { return (isNotNullOrEmpty(surname)) ? surname : null; } public void setSurname(String surname) { this.surname = surname; } }
true
1949fc8d596cb1c1d39cf569dad255938570c0fb
Java
ReadingGroup534/DailyReading
/server/reading/reading-web/src/main/java/com/aiteu/reading/web/api/ApiDealer.java
UTF-8
1,425
2.140625
2
[ "Apache-2.0" ]
permissive
package com.aiteu.reading.web.api; import java.util.List; import java.util.Map; import org.springframework.ui.ModelMap; import com.aiteu.reading.api.model.Browse; import com.aiteu.reading.api.service.ArticleService; import com.aiteu.reading.api.service.BrowseService; /** * 主要是处理api的核心事物 * @author liwei * */ public class ApiDealer { private static final int LIMIT = 5; public ApiDealer(){ } public void doGetBrowses(ModelMap modelMap, Map<String, String> form, BrowseService service){ List<Browse> browseList = service.getBrowses(); modelMap.put("browses", browseList); } public void doGetList(ModelMap modelMap, Map<String, String> form, ArticleService service){ if(null == form.get("start")){ form.put("start", "0"); } if(null == form.get("limit")){ form.put("limit", String.valueOf(LIMIT)); } if(null == form.get("browseId")){ form.put("browseId", "0");// 默认加载全部 } modelMap.put("total", service.getCount(form)); modelMap.put("list", service.getList(form)); } public void doGetTodayList(ModelMap modelMap, Map<String, String> form, ArticleService service){ if(null == form.get("offset")){ form.put("offset", "0"); } if(null == form.get("prevd")){ form.put("prevd", "1"); } modelMap.put("offset", form.get("offset")); modelMap.put("prevd", form.get("prevd")); modelMap.put("list", service.getTodayList(form)); } }
true
3bb520798e0c8ec5ee8d3dd03d2ddacdefc743ea
Java
lwj278455/frame
/src/main/java/com/xxx/frame/Entity/AdminUser.java
UTF-8
4,399
2.25
2
[]
no_license
package com.xxx.frame.Entity; import java.io.Serializable; import java.util.List; public class AdminUser implements Serializable { private Integer id; private String name; private String username; private String password; private String adminlevel; private String qrcodeurl; private List<UserInfo> userInfoList; public List<UserInfo> getUserInfoList() { return userInfoList; } public void setUserInfoList(List<UserInfo> userInfoList) { this.userInfoList = userInfoList; } private static final long serialVersionUID = 1L; public AdminUser(Integer id) { this.id = id; } public AdminUser(Integer id, String name, String username, String password, String adminlevel, String qrcodeurl) { this.id = id; this.name = name; this.username = username; this.password = password; this.adminlevel = adminlevel; this.qrcodeurl = qrcodeurl; } public AdminUser() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getUsername() { return username; } public void setUsername(String username) { this.username = username == null ? null : username.trim(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } public String getAdminlevel() { return adminlevel; } public void setAdminlevel(String adminlevel) { this.adminlevel = adminlevel == null ? null : adminlevel.trim(); } public String getQrcodeurl() { return qrcodeurl; } public void setQrcodeurl(String qrcodeurl) { this.qrcodeurl = qrcodeurl == null ? null : qrcodeurl.trim(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } AdminUser other = (AdminUser) that; return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())) && (this.getUsername() == null ? other.getUsername() == null : this.getUsername().equals(other.getUsername())) && (this.getPassword() == null ? other.getPassword() == null : this.getPassword().equals(other.getPassword())) && (this.getAdminlevel() == null ? other.getAdminlevel() == null : this.getAdminlevel().equals(other.getAdminlevel())) && (this.getQrcodeurl() == null ? other.getQrcodeurl() == null : this.getQrcodeurl().equals(other.getQrcodeurl())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); result = prime * result + ((getUsername() == null) ? 0 : getUsername().hashCode()); result = prime * result + ((getPassword() == null) ? 0 : getPassword().hashCode()); result = prime * result + ((getAdminlevel() == null) ? 0 : getAdminlevel().hashCode()); result = prime * result + ((getQrcodeurl() == null) ? 0 : getQrcodeurl().hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", name=").append(name); sb.append(", username=").append(username); sb.append(", password=").append(password); sb.append(", adminlevel=").append(adminlevel); sb.append(", qrcodeurl=").append(qrcodeurl); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
true
17fd46e2ac3baf7aaaac7c74fae4ea80d430d349
Java
AnilSrinivasMuddineni/testingWorks
/SingletonExample.java
UTF-8
947
3.15625
3
[]
no_license
package testing1; class SingletonExample { private static SingletonExample singletonExample; public String s = null; private SingletonExample() { s = "this is what singleton class is pppp :)"; } public static SingletonExample SingletonExampleMethod() { if(singletonExample ==null) singletonExample = new SingletonExample(); return singletonExample; } public String inSingleton(int value) { return "why SingletonExample ... ?"+s; } /*public String getS() { return s; } public void setS(String s) { this.s = s; }*/ @Override public String toString() { return "SingletonExample [inSingleton()=" + inSingleton(0) + "]"; } } class ForSingletonObjCreation { public static void main(String [] args) { SingletonExample singletonExample = SingletonExample.SingletonExampleMethod(); } }
true
69e9042605b472e293f45e49f8c085ef4f57260d
Java
jenniferpetersen/INTE-Projekt
/HedgeFund.java
UTF-8
463
2.609375
3
[]
no_license
package netrunner; public class HedgeFund extends Operation{ public HedgeFund(){ super("HedgeFund", "Transaction", "Gain 9 credits", 5, "neutral", "0", false); } protected void playCard(Corporation corp){ if (corp.getCredits() >= this.getCost()) { corp.gainCredits(9); corp.removeCardFromHQ(this); corp.addCardToArchives(this); } else { throw new IllegalArgumentException("You don't have enough money to play that card!"); } } }
true
a586386610d3bf6295224f6f7d4663fef645300c
Java
suxpro/YA801G3
/src/back/employee/controller/LoginHandler.java
UTF-8
2,762
2.65625
3
[]
no_license
package back.employee.controller; import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import back.employee.model.EmployeeDAO; import back.employee.model.EmployeeVO; public class LoginHandler extends HttpServlet { // 【檢查使用者輸入的帳號(account) 密碼(password)是否有效】 // 【實際上應至資料庫搜尋比對】 protected String allowUser(String account, String password) { EmployeeVO getEmpVo = new EmployeeDAO().findPwdByEmpId(account); // System.out.println("LoginHandler.16."+getEmpVo.getEmp_pwd()); // System.out.println("LoginHandler.17."+getEmpVo.getEmp_pwd().equals(password)); if (getEmpVo.getEmp_pwd().equals(password)) return getEmpVo.getEmp_job(); else return "false"; } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // req.setCharacterEncoding("UTF-8"); // //已由filters.SetCharacterEncodingFilter處理 res.setContentType("text/html; charset=UTF-8"); PrintWriter out = res.getWriter(); // 【取得使用者 帳號(account) 密碼(password)】 String accountBack = req.getParameter("accountBack"); String passwordBack = req.getParameter("passwordBack"); String allowUser = allowUser(accountBack, passwordBack); // System.out.println("LoginHandler.34."+accountBack); // System.out.println("LoginHandler.35."+passwordBack); System.out.println("LoginHandler.39.後端登入"+accountBack); // 【檢查該帳號 , 密碼是否有效】 if ("false".equals(allowUser)) { // 【帳號 , 密碼無效時】 req.setAttribute("dashboard_login_error", "帳號或密碼錯誤,請重新登入!"); RequestDispatcher failureView = req .getRequestDispatcher("/back/dashboard_login.jsp"); failureView.forward(req, res); // res.sendRedirect(req.getContextPath()+"/back/dashboard_login.jsp"); return; } else { // 【帳號 , 密碼有效時, 才做以下工作】 HttpSession session = req.getSession(); session.setAttribute("accountBack", accountBack); // *工作1: session.setAttribute("accountBackJob", allowUser); // *工作1: // 才在session內做已經登入過的標識 try { // *工作2: 看看有無來源網頁 (-如有:則重導之) String location = (String) session.getAttribute("location"); if (location != null) { session.removeAttribute("location"); res.sendRedirect(location); return; } } catch (Exception ignored) { } res.sendRedirect(req.getContextPath()+"/back/dashboard.jsp"); // *工作3: (-如無: 無來源網頁, // 則重導至index.jsp網頁) } } }
true
f1e59998a720aa59a10a02ddbdbdff179e9665da
Java
ppazos/hapi-testpanel
/hunit/hunit-impl/src/main/java/ca/uhn/hunit/compare/hl7v2/bulk/BulkHl7V2Comparison.java
UTF-8
6,171
2.1875
2
[]
no_license
package ca.uhn.hunit.compare.hl7v2.bulk; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.logging.Logger; import ca.uhn.hl7v2.HL7Exception; import ca.uhn.hl7v2.model.Message; import ca.uhn.hl7v2.parser.EncodingNotSupportedException; import ca.uhn.hl7v2.parser.PipeParser; import ca.uhn.hl7v2.util.Terser; import ca.uhn.hunit.api.IMessageTransformer; import ca.uhn.hunit.compare.hl7v2.Hl7V2MessageCompare; import ca.uhn.hunit.ex.UnexpectedTestFailureException; import ca.uhn.hunit.util.Hl7FileUtil; public class BulkHl7V2Comparison { private static final Logger ourLog = Logger.getLogger(BulkHl7V2Comparison.class.getName()); private Iterator<Message> myActualMessages; private List<IMessageTransformer<Message>> myActualMessageTransformers = new ArrayList<IMessageTransformer<Message>>(); private Iterator<Message> myExpectedMessages; private List<IMessageTransformer<Message>> myExpectedMessageTransformers = new ArrayList<IMessageTransformer<Message>>(); private List<Hl7V2MessageCompare> myFailedComparisons = new ArrayList<Hl7V2MessageCompare>(); private Set<String> myFieldsToIgnore = new HashSet<String>(); private PipeParser myParser; private boolean myStopOnFirstFailure; private int myTotalMessages = -1; public BulkHl7V2Comparison() { myParser = PipeParser.getInstanceWithNoValidation(); } public void addActualMessageTransformer(IMessageTransformer<Message> theTransformer) { myActualMessageTransformers.add(theTransformer); } public void addExpectedMessageTransformer(IMessageTransformer<Message> theTransformer) { myExpectedMessageTransformers.add(theTransformer); } /** * @param theFieldToIgnore * the terserPathsToIgnore to set */ public void addFieldToIgnore(String theFieldToIgnore) { myFieldsToIgnore.add(theFieldToIgnore); } public void compare() throws UnexpectedTestFailureException { int actualIndex = 0; int expectedIndex = 0; while (myActualMessages.hasNext() && myExpectedMessages.hasNext()) { Message actualMessage = myActualMessages.next(); Message expectedMessage = myExpectedMessages.next(); for (IMessageTransformer<Message> next : myExpectedMessageTransformers) { expectedMessage = next.transform(expectedMessage); } for (IMessageTransformer<Message> next : myActualMessageTransformers) { actualMessage = next.transform(actualMessage); } Terser aTerser = new Terser(actualMessage); Terser eTerser = new Terser(expectedMessage); StringBuilder msg = new StringBuilder(); msg.append("Comparing message " + (actualIndex + 1)); if (myTotalMessages != -1) { msg.append((actualIndex + 1) + "/" + myTotalMessages); } try { msg.append(" - MSH-10 Expected[" + eTerser.get("/.MSH-10") + "] Actual[" + aTerser.get("/.MSH-10") + "]"); } catch (HL7Exception e) { // ignore, just for logging } ourLog.info(msg.toString()); Hl7V2MessageCompare comparison = new Hl7V2MessageCompare(myParser); comparison.setFieldsToIgnore(myFieldsToIgnore); comparison.compare(expectedMessage, actualMessage); if (!comparison.isSame()) { myFailedComparisons.add(comparison); if (myStopOnFirstFailure) { break; } } actualIndex++; expectedIndex++; } } public String describeDifferences() throws HL7Exception { StringBuilder retVal = new StringBuilder(); for (Hl7V2MessageCompare next : myFailedComparisons) { retVal.append("Expected Message:\n"); retVal.append(next.getExpectedMessage().encode().replace("\r", "\n")); retVal.append("\n\nActual Message:\n"); retVal.append(next.getActualMessage().encode().replace("\r", "\n")); retVal.append("\n\nDifferences:\n"); retVal.append(next.describeDifference()); retVal.append("\n\n"); } return retVal.toString(); } /** * @return the failedComparisons */ public List<Hl7V2MessageCompare> getFailedComparisons() { return myFailedComparisons; } /** * @return the stopOnFirstFailure */ public boolean isStopOnFirstFailure() { return myStopOnFirstFailure; } /** * @param theActualMessages * the actualMessages to set */ public void setActualMessages(Iterator<Message> theActualMessages) { myTotalMessages = -1; myActualMessages = theActualMessages; } /** * @param theActualMessages * the actualMessages to set */ public void setActualMessages(List<Message> theActualMessages) { myTotalMessages = theActualMessages.size(); myActualMessages = theActualMessages.iterator(); } /** * @param theExpectedMessages * the expectedMessages to set */ public void setExpectedMessages(Iterator<Message> theExpectedMessages) { myExpectedMessages = theExpectedMessages; } /** * @param theExpectedMessages * the expectedMessages to set */ public void setExpectedMessages(List<Message> theExpectedMessages) { myExpectedMessages = theExpectedMessages.iterator(); } /** * @param theStopOnFirstFailure * the stopOnFirstFailure to set */ public void setStopOnFirstFailure(boolean theStopOnFirstFailure) { myStopOnFirstFailure = theStopOnFirstFailure; } public static void main(String[] theArgs) throws EncodingNotSupportedException, IOException, HL7Exception, UnexpectedTestFailureException { String expectedFile = "../../prj_Map_ADT_SIMS_EPR_ADT_UHN_RxTFC_Pojo/test/expected.txt"; String actualFile = "../../prj_Map_ADT_SIMS_EPR_ADT_UHN_RxTFC_Pojo/test/actual.txt"; BulkHl7V2Comparison tester = new BulkHl7V2Comparison(); tester.setExpectedMessages(Hl7FileUtil.loadFileAndParseIntoMessages(expectedFile)); tester.setActualMessages(Hl7FileUtil.loadFileAndParseIntoMessages(actualFile)); tester.setStopOnFirstFailure(true); tester.addFieldToIgnore("MSH-2"); tester.addFieldToIgnore("MSH-10"); tester.compare(); System.out.println(); System.out.println(); System.out.println(); System.out.println(tester.describeDifferences()); } }
true
f33e2283d84bd64c4dd2d3e7fe013f30adc10b3c
Java
PMKCHOWDARY/Java-Programs
/48.java
UTF-8
343
2.96875
3
[]
no_license
import java.util.*; public class Main { public static void main(String args[]) { Scanner s=new Scanner(System.in); int n=s.nextInt(); int[] arr=new int[n]; for(int i=0;i<n;i++) arr[i]=s.nextInt(); int k=0; for(int j=0;j<n;j++) { arr[k]=Math.abs(arr[j]*arr[j]); k++; } Arrays.sort(arr); for(int i=0;i<n;i++) System.out.print(arr[i]+" "); } }
true
a4d33809c801fcc8521c3beabdea7a85114b195a
Java
ChikaKanu/fashionApp
/fashion/src/main/java/com/example/codeclan/fashion/repository/fabricSuppliers/FabricSupplierRepository.java
UTF-8
506
1.742188
2
[]
no_license
package com.example.codeclan.fashion.repository.fabricSuppliers; import com.example.codeclan.fashion.models.FabricSupplier; import com.example.codeclan.fashion.projections.FabricSupplierProjection; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; @RepositoryRestResource(excerptProjection = FabricSupplierProjection.class) public interface FabricSupplierRepository extends JpaRepository<FabricSupplier, Long> { }
true
30709bdb4394313a2676d0fbb140d78e9c67865d
Java
entropy64/JiraRESTClient
/src/main/java/com/softwareleaf/jira/jql/JQLOrder.java
UTF-8
855
2.90625
3
[ "Apache-2.0" ]
permissive
package com.softwareleaf.jira.jql; /** * Provides an API for handling {@literal "ORDER BY"} JQL Keyword * grammar rules. * * @author Jonathon Hope */ public class JQLOrder { /** * This enum provides the types of JQL ordering. * * @author Jonathon Hope */ public enum OrderType { /** * Ascending. */ ASC, /** * Descending. */ DESC } private JQL jql; public JQLOrder(JQL jql) { this.jql = jql; } private JQLKeyword addOrderType(String field) { jql.add(field); return new JQLKeyword(jql); } public JQLKeyword asc() { return addOrderType(" " + OrderType.ASC); } public JQLKeyword desc() { return addOrderType(" " + OrderType.DESC); } }
true
0581abe20038bc27d7964ce7cc3c2d55e84262e7
Java
yiner233/Age-of-Exile
/src/main/java/com/robertx22/age_of_exile/vanilla_mc/items/gearitems/weapons/MaceWeapon.java
UTF-8
850
2.296875
2
[]
no_license
package com.robertx22.age_of_exile.vanilla_mc.items.gearitems.weapons; import com.robertx22.age_of_exile.uncommon.enumclasses.WeaponTypes; import com.robertx22.library_of_exile.utils.RandomUtils; import com.robertx22.library_of_exile.utils.SoundUtils; import net.minecraft.entity.LivingEntity; import net.minecraft.item.ItemStack; import net.minecraft.sound.SoundEvent; import net.minecraft.sound.SoundEvents; public class MaceWeapon extends ModWeapon { public MaceWeapon() { super(WeaponTypes.mace); } @Override public boolean postHit(ItemStack stack, LivingEntity target, LivingEntity attacker) { SoundEvent sound = SoundEvents.BLOCK_ANVIL_LAND; SoundUtils.playSound(attacker, sound, 0.2F, RandomUtils.RandomRange(0F, 1F)); return super. postHit(stack, target, attacker); } }
true
a902e0b3c1bed33f4990ed265660b346a5f811fd
Java
TinyEaves/webflux-samples
/webflux-spring-security/src/test/java/org/javaboy/webflux/springsecurity/WebfluxSpringSecurityApplicationTests.java
UTF-8
250
1.515625
2
[ "Apache-2.0" ]
permissive
package org.javaboy.webflux.springsecurity; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class WebfluxSpringSecurityApplicationTests { @Test void contextLoads() { } }
true
54acfe60213dc4d7953c9a08232a1917200fb2d0
Java
smitdetroja96/RCTMP
/app/src/main/java/com/example/rctmp/SuggestionsBookCount.java
UTF-8
829
2.828125
3
[]
no_license
package com.example.rctmp; import java.util.Comparator; public class SuggestionsBookCount { BooksClass book; int cnt; public SuggestionsBookCount() { } public SuggestionsBookCount(BooksClass book, int cnt) { this.book = book; this.cnt = cnt; } public BooksClass getBook() { return book; } public void setBook(BooksClass book) { this.book = book; } public int getCnt() { return cnt; } public void setCnt(int cnt) { this.cnt = cnt; } public static Comparator<SuggestionsBookCount> CountComparator = new Comparator<SuggestionsBookCount>() { @Override public int compare(SuggestionsBookCount o1,SuggestionsBookCount o2) { return (o1.getCnt() > o2.getCnt()) ? 1 : -1; } }; }
true
3facebc153beeb7721e77ff1de4e6b78b7b6b01b
Java
jsbradley523/LeetCode
/src/test/java/jamison/bradley/leet/code/questions/algorithms/PopulatingNextRightPointersInEachNodeTest.java
UTF-8
2,592
2.8125
3
[]
no_license
package jamison.bradley.leet.code.questions.algorithms; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; public class PopulatingNextRightPointersInEachNodeTest { private PopulatingNextRightPointersInEachNode connector; @Before public void before(){ connector = new PopulatingNextRightPointersInEachNode(); } @Test public void oneLevelTreeIsCorrect(){ final TreeLinkNode one = new TreeLinkNode(1); final TreeLinkNode expectedOne = new TreeLinkNode(1); connector.connect(one); MatcherAssert.assertThat(one, Matchers.is(expectedOne)); } @Test public void twoLevelTreeIsCorrect(){ final TreeLinkNode one = new TreeLinkNode(1); final TreeLinkNode two = new TreeLinkNode(2); final TreeLinkNode three = new TreeLinkNode(3); one.left = two; one.right = three; final TreeLinkNode expectedOne = new TreeLinkNode(1); final TreeLinkNode expectedTwo = new TreeLinkNode(2); final TreeLinkNode expectedThree = new TreeLinkNode(3); expectedOne.left = expectedTwo; expectedOne.right = expectedThree; expectedTwo.next = expectedThree; connector.connect(one); MatcherAssert.assertThat(one, Matchers.is(expectedOne)); } @Test public void threeLevelTreeIsCorrect(){ final TreeLinkNode one = new TreeLinkNode(1); final TreeLinkNode two = new TreeLinkNode(2); final TreeLinkNode three = new TreeLinkNode(3); final TreeLinkNode four = new TreeLinkNode(4); final TreeLinkNode five = new TreeLinkNode(5); final TreeLinkNode six = new TreeLinkNode(6); final TreeLinkNode seven = new TreeLinkNode(7); one.left = two; one.right = three; two.left = four; two.right = five; three.left = six; three.right = seven; final TreeLinkNode expectedOne = new TreeLinkNode(1); final TreeLinkNode expectedTwo = new TreeLinkNode(2); final TreeLinkNode expectedThree = new TreeLinkNode(3); final TreeLinkNode expectedFour = new TreeLinkNode(4); final TreeLinkNode expectedFive = new TreeLinkNode(5); final TreeLinkNode expectedSix = new TreeLinkNode(6); final TreeLinkNode expectedSeven = new TreeLinkNode(7); expectedOne.left = expectedTwo; expectedOne.right = expectedThree; expectedTwo.next = expectedThree; expectedTwo.left = expectedFour; expectedTwo.right = expectedFive; expectedThree.left = expectedSix; expectedThree.right = expectedSeven; expectedFour.next = expectedFive; expectedFive.next = expectedSix; expectedSix.next = expectedSeven; connector.connect(one); MatcherAssert.assertThat(one, Matchers.is(expectedOne)); } }
true
f654ddd938705d44fdbcaa4e277640b859d8224f
Java
b96705008/te_matrix_system
/src/paper/semantic/matrix/LSI.java
UTF-8
5,821
3.25
3
[]
no_license
package paper.semantic.matrix; import weka.core.matrix.Matrix; import weka.core.matrix.SingularValueDecomposition; /** * This class implements the Latent Semantic Indexing technique. <br/> * LSI generalises a sparse matrix of indexed terms using term co-occurrences. * The approximation uses a given lower rank of the matrix or a ratio of the S values gotten from the SVD. * <p> It should be noted that the number of S values is NOT always equal to the Rank of the matrix. * <p>It uses a third party Java package called Jama for Singular Value Decomposition. * @author Ibrahim Adeyanju * assisted by Stewart Massie * @version 1.0 */ public class LSI { /** * @param args * A = original * D = document * S = singular * T = term */ public static void main(String[] args) { double[][] cb = {{1,0,0,1,0,0,0,0,0}, {1,0,1,0,0,0,0,0,0}, {1,1,0,0,0,0,0,0,0}, {0,1,1,0,1,0,0,0,0}, {0,1,1,2,0,0,0,0,0}, {0,1,0,0,1,0,0,0,0}, {0,1,0,0,1,0,0,0,0}, {0,0,1,1,0,0,0,0,0}, {0,1,0,0,0,0,0,0,1}, {0,0,0,0,0,1,1,1,0}, {0,0,0,0,0,0,1,1,1}, {0,0,0,0,0,0,0,1,1}}; LSI lsi = new LSI(cb, 2); lsi.getAk(); lsi.getD_D(); lsi.getT_T(); } //property private Matrix A; private Matrix Ak; private Matrix D_D; private Matrix T_T; private Matrix S; private int k; /** * Constructor to instantiate a new LSI class. * The default number of terms used for approximation is half of the matrix Rank * @param cb A 2-dimensional array intended to be generalised */ public LSI(double[][] cb){ this.A = new Matrix(cb); this.k = (int)(A.rank() * 0.5); } /** * Constructor to instantiate a new LSI class * @param cb A 2-dimensional array intended to be generalised * @param k An integer representing the rank of approximation */ public LSI(double[][] cb, int k){ this.A = new Matrix(cb); this.k = k; } /** * Constructor to instantiate a new LSI class * @param cb A 2-dimensional array intended to be generalised * @param ratio A fraction representing a ratio of the number of S values used for approximation */ public LSI(double[][] cb, double ratio){ this.A = new Matrix(cb); int row = this.A.getRowDimension(); int col = this.A.getColumnDimension(); if(row < col) this.k = (int)(ratio * row); else this.k = (int)(ratio * col); } /** * Gets the Generalised matrix * @return Generalised matrix */ public double[][] getAk(){ boolean transpose = false; //if rows < cols then transpose A if(this.A.getRowDimension() < this.A.getColumnDimension()){ this.A = this.A.transpose(); transpose = true; } //get S V D matrices SingularValueDecomposition svd = new SingularValueDecomposition(this.A); Matrix U = svd.getU(); this.S = svd.getS(); Matrix V = svd.getV(); // trim the matrices according to k Matrix Uk = U.getMatrix(0, U.getRowDimension() - 1, 0, this.k - 1); Matrix Sk = this.S.getMatrix(0, this.k - 1, 0, this.k - 1); Matrix Vk = V.getMatrix(0, V.getRowDimension() - 1, 0, this.k - 1); //reconstruct matrix at lower rank if(transpose) this.Ak = (Uk.times(Sk)).times(Vk.transpose()).transpose(); else this.Ak = (Uk.times(Sk)).times(Vk.transpose()); return this.Ak.getArrayCopy(); } /** * Gets the similarity between elements in the rows of the given matrix * @return Matrix of similarity between row elements */ public double[][] getD_D(){ if(this.Ak == null) this.getAk(); //doc/doc cosine similarity - normalised dot product // The given matrix is assumed to be a document by term matrix this.D_D = this.Ak.times(this.Ak.transpose()); //set normalise factor for each row vector i.e. 2norm Matrix norms = new Matrix(this.Ak.getRowDimension(), 1); for(int i=0; i<this.Ak.getRowDimension(); i++){ double val1 = Math.sqrt(this.D_D.get(i,i)); if(val1 == 0) val1 = 0.000001; norms.set(i, 0, val1); } //set cosine similarity dot prod/norm factor for each element for (int i = 0; i < this.D_D.getRowDimension(); i++){ for (int a = 0; a < this.D_D.getColumnDimension(); a++){ double val = this.D_D.get(i,a) / (norms.get(i,0)*norms.get(a,0)); this.D_D.set(i,a,val); } } this.D_D.print(5, 2); return this.D_D.getArray(); } /** * Gets the similarity between elements in the columns of the given matrix * @return Matrix of similarity between column elements */ public double[][] getT_T(){ if(this.Ak==null) this.getAk(); //term/term cosine similarity - normalised dot product //The given matrix is assumed to be a document by term matrix Matrix AkT = this.Ak.transpose(); this.T_T=AkT.times(this.Ak); //set normalise factor for each row vector i.e. 2norm Matrix norms = new Matrix(AkT.getRowDimension(),1); for (int i = 0; i < AkT.getRowDimension(); i++) { double val1 = Math.sqrt(this.T_T.get(i,i)); if(val1 == 0) val1 = 0.000001; norms.set(i,0,val1); } //set cosine similarity dot prod/norm factor for each element for (int i = 0; i < this.T_T.getRowDimension(); i++) { for (int a = 0; a < this.T_T.getColumnDimension(); a++) { double val = this.T_T.get(i,a)/(norms.get(i,0)*norms.get(a,0)); this.T_T.set(i,a,val); } } this.T_T.print(5, 2); return this.T_T.getArrayCopy(); } /** * Gets the diagonal matrix of S values after SVD * @return Diagonal matrix of S values */ public double[][] getS(){ if(this.Ak == null) this.getAk(); return this.S.getArrayCopy(); } /** * Gets the rank of the Original Matrix * @return Rank of the original matrix */ public int getRank(){ return this.A.rank(); } }
true
a886a8ae17cfc48fb4342b5be4801d29a69c6bb8
Java
lukacsd/aws-scheme
/src/org/lukacsd/aws/scheme/ui/SchemeFragment.java
UTF-8
7,413
1.835938
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2014 David Lukacs * * 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.lukacsd.aws.scheme.ui; import java.io.Serializable; import java.util.Map; import org.lukacsd.aws.scheme.Constants; import org.lukacsd.aws.scheme.R; import org.lukacsd.aws.scheme.ec2.model.ClusterScheme; import org.lukacsd.aws.scheme.ec2.model.ClusterSnapshot; import org.lukacsd.aws.scheme.ec2.model.InstanceResource; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.content.LocalBroadcastManager; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.LinearLayout; import android.widget.Switch; public class SchemeFragment extends Fragment implements Nameable { private String name; private ClusterScheme scheme; private Switch activateSwitch; private ClusterSnapshotUpdateListener clusterSnapshotUpdateListener; private ActivateSwitchClickListener activateSwitchClickListener; private ActivateSwitchCheckedChangeListener activateSwitchCheckedChangeListener; public SchemeFragment( ) { } public SchemeFragment( ClusterScheme scheme ) { this.name = scheme.getName( ); this.scheme = scheme; } @Override public String getTitle() { return name; } @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) { View retval = inflater.inflate( R.layout.fragment_scheme, container, false ); clusterSnapshotUpdateListener = new ClusterSnapshotUpdateListener( ); activateSwitchClickListener = new ActivateSwitchClickListener( ); activateSwitchCheckedChangeListener = new ActivateSwitchCheckedChangeListener( ); if ( savedInstanceState != null ) { name = savedInstanceState.getString( "name" ); scheme = ( ClusterScheme ) savedInstanceState.getSerializable( "scheme" ); } activateSwitch = ( Switch ) retval.findViewById( R.id.activateSchemeSwitch ); activateSwitch.setLongClickable( false ); activateSwitch.setOnClickListener( activateSwitchClickListener ); activateSwitch.setOnCheckedChangeListener( activateSwitchCheckedChangeListener ); updateUi( getActivity( ), retval ); return retval; } @Override public void onResume() { super.onResume( ); LocalBroadcastManager.getInstance( getActivity( ) ).registerReceiver( clusterSnapshotUpdateListener, new IntentFilter( Constants.CLUSTER_SNAPSHOT_UPDATE_BROADCAST ) ); } @Override public void onPause() { super.onPause( ); LocalBroadcastManager.getInstance( getActivity( ) ).unregisterReceiver( clusterSnapshotUpdateListener ); } @Override public void onSaveInstanceState( Bundle outState ) { super.onSaveInstanceState( outState ); outState.putString( "name", name ); outState.putSerializable( "scheme", ( Serializable ) scheme ); } public ClusterScheme getScheme() { return scheme; } private boolean isSchemeActive() { boolean retval = false; if ( scheme != null ) { retval = scheme.isActive( ); } return retval; } private void silentlyAdjustSwitchToSchemeState() { activateSwitch.setOnCheckedChangeListener( null ); activateSwitch.setChecked( isSchemeActive( ) ); activateSwitch.setOnCheckedChangeListener( activateSwitchCheckedChangeListener ); } private void updateUi( Context context, View view ) { LinearLayout layout = ( LinearLayout ) view.findViewById( R.id.instanceLayout ); layout.removeAllViews( ); if ( scheme != null ) { Map<String, String> designatedPublicIps = scheme.getDesignatedPublicIpsWithResolvedHostnames( ); for ( InstanceResource instance : scheme.getInstances( ) ) { for ( String designatedPublicIp : instance.getDesignatedPublicIps( ) ) { layout.addView( new HostView( context, designatedPublicIp, designatedPublicIps.get( designatedPublicIp ), instance .isIpOwned( designatedPublicIp ) ) ); } layout.addView( new InstanceView( context, instance ) ); } } silentlyAdjustSwitchToSchemeState( ); } public class ClusterSnapshotUpdateListener extends BroadcastReceiver { @Override public void onReceive( Context context, Intent intent ) { ClusterSnapshot updatedSnapshot = ( ClusterSnapshot ) intent .getSerializableExtra( Constants.CLUSTER_SNAPSHOT_UPDATE_SNAPSHOT_ARG ); if ( updatedSnapshot == null ) { scheme = null; } else { scheme = updatedSnapshot.getScheme( name ); } updateUi( getActivity( ), getView( ) ); } } public class ActivateSwitchClickListener implements OnClickListener { @Override public void onClick( View v ) { silentlyAdjustSwitchToSchemeState( ); if ( !isSchemeActive( ) ) { AlertDialog.Builder builder = new AlertDialog.Builder( getActivity( ) ); builder.setMessage( getString( R.string.activateSchemeMessage, scheme.getName( ) ) ); builder.setPositiveButton( R.string.buttonOK, new DialogInterface.OnClickListener( ) { @Override public void onClick( DialogInterface dialog, int id ) { Intent intent = new Intent( Constants.ACTIVATE_SCHEME_BROADCAST ); intent.putExtra( Constants.ACTIVATE_SCHEME_BROADCAST_ARG, scheme.getName( ) ); LocalBroadcastManager.getInstance( getActivity( ) ).sendBroadcast( intent ); } } ); builder.setNegativeButton( R.string.buttonCancel, new DialogInterface.OnClickListener( ) { @Override public void onClick( DialogInterface dialog, int id ) { } } ); builder.show( ); } } } public class ActivateSwitchCheckedChangeListener implements OnCheckedChangeListener { @Override public void onCheckedChanged( CompoundButton buttonView, boolean isChecked ) { silentlyAdjustSwitchToSchemeState( ); } } }
true
6aee2d8f8ffa12defd8cad331ac917184e2f34ed
Java
mycom-int/jersey-guice-aop
/src/test/java/com/mycom/samples/aop/application/TestMusicianFinderApp.java
UTF-8
973
2.21875
2
[]
no_license
package com.mycom.samples.aop.application; import static org.fest.assertions.Assertions.assertThat; import javax.inject.Inject; import org.jukito.JukitoRunner; import org.jukito.TestModule; import org.junit.Test; import org.junit.runner.RunWith; import com.mycom.samples.aop.domain.model.Instrument.Category; import com.mycom.samples.aop.inject.guice.DomainModule; @RunWith(JukitoRunner.class) public class TestMusicianFinderApp { public static class Module extends TestModule { @Override protected void configureTest() { install(new DomainModule()); } } @Inject MusicianFinderApp app; @Test public void testList() { assertThat(app.listMusicians()).isNotNull().isNotEmpty().hasSize(2); } @Test public void testFind() { assertThat(app.findMusician(Category.Brass)).isNotNull().isNotEmpty().hasSize(2); assertThat(app.findMusician(Category.Chords)).isNotNull().isEmpty(); } }
true
534e84fdf0d6e9674ee8e6def4f04c03b69544a2
Java
HelixOW/UHC-Spigot
/UHC-Remake/src/main/java/de/alphahelix/uhc/inventories/TeamInventory.java
UTF-8
1,317
2.4375
2
[]
no_license
package de.alphahelix.uhc.inventories; import de.alphahelix.alphalibary.item.ItemBuilder; import de.alphahelix.uhc.instances.UHCTeam; import de.alphahelix.uhc.register.UHCFileRegister; import de.alphahelix.uhc.util.TeamManagerUtil; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; public class TeamInventory { private Inventory i; public TeamInventory() { setInventory(Bukkit.createInventory(null, ((TeamManagerUtil.getTeamAmount() / 9) + 1) * 9, UHCFileRegister.getTeamFile().getInventoryName())); } public void fillInventory() { for (int slot = 0; slot < getInventory().getSize(); slot++) { getInventory().setItem(slot, new ItemBuilder(Material.STAINED_GLASS_PANE).setName(" ").setDamage((short) 7).build()); } for (UHCTeam t : TeamManagerUtil.getTeams()) { getInventory().setItem(t.getInvSlot(), t.getIcon(UHCFileRegister.getTeamFile().getContentMaterial())); } } public void openInventory(Player p) { p.openInventory(getInventory()); } public Inventory getInventory() { return i; } public void setInventory(Inventory i) { this.i = i; } }
true
fd57199084bd9c166dac2a0683f97c4d6d772d37
Java
IsoyaKureno/QueteSimpleUI
/app/src/main/java/com/example/apprenti/quetesimpleui/MainActivity.java
UTF-8
2,391
2.3125
2
[]
no_license
package com.example.apprenti.quetesimpleui; import android.app.Activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); CheckBox maCheckBox = (CheckBox)findViewById(R.id.CheckBox); maCheckBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText edit4 = (EditText)findViewById(R.id.editText4); EditText edit5 = (EditText)findViewById(R.id.editText5); Button button = (Button)findViewById(R.id.button); if (((CheckBox) v).isChecked()) { edit4.setEnabled(true); edit5.setEnabled(true); button.setEnabled(true); } else { edit4.setEnabled(false); edit5.setEnabled(false); button.setEnabled(false); } } }); Button monBouton = (Button)findViewById(R.id.button); monBouton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText edit4 = (EditText)findViewById(R.id.editText4); EditText edit5 = (EditText)findViewById(R.id.editText5); if(edit4.getText().toString().trim().length() == 0 || edit5.getText().toString().trim().length() == 0) { Toast.makeText(MainActivity.this,"Tu dois renseigner le nom et le prénom !",Toast.LENGTH_SHORT).show(); } else { TextView textView = (TextView)findViewById(R.id.textView); textView.setVisibility(View.VISIBLE); textView.setText("Félicitations, " + edit4.getText() + " " + edit5.getText() + "!"); } } }); } }
true
4e8b13c1973f3a01547237425f4036f795ed45f2
Java
priyankvex/Mobile-applications
/Label The Diagram/source-code/LabeltheDiagram/src/com/buildmlearn/labeldiagram/DiagramMenuMicroogranisms.java
UTF-8
2,563
2.328125
2
[ "BSD-3-Clause" ]
permissive
package com.buildmlearn.labeldiagram; import com.buildmlearn.labeldiagram.resources.BacteriaFragment; import com.buildmlearn.labeldiagram.resources.VirusFragment; import com.example.labelthediagram.R; import android.app.ActionBar; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; public class DiagramMenuMicroogranisms extends FragmentActivity { FragmentPagerAdapter adapterViewPager; static float bacteria=0; static float virus=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.diagram_menu); ViewPager vpPager = (ViewPager) findViewById(R.id.diagrampager); adapterViewPager = new BacteriaAdapter( getSupportFragmentManager()); vpPager.setAdapter(adapterViewPager); vpPager.setClipToPadding(false); vpPager.setPageMargin(20); ActionBar actionBar = getActionBar(); actionBar.setTitle("Diagram Menu"); actionBar.setDisplayShowTitleEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.show(); SharedPreferences pref = getApplicationContext().getSharedPreferences( "com.buildmlearn.labeldiagram.PREFERENCE_FILE_KEY", Context.MODE_PRIVATE); bacteria = pref.getFloat("Bacteria", 0); virus = pref.getFloat("Virus", 0); } public static class BacteriaAdapter extends FragmentPagerAdapter { private String[] pageTitles = new String[] { "Bacteria", "Virus" }; public static int NUM_ITEMS = 2; public BacteriaAdapter(FragmentManager fragmentManager) { super(fragmentManager); } @Override public int getCount() { return NUM_ITEMS; } @Override public Fragment getItem(int position) { Bundle bundle = new Bundle(); switch (position) { case 0: BacteriaFragment bacteriaFrag = new BacteriaFragment(); bundle.putFloat("SCORE_SAVED", bacteria); bacteriaFrag.setArguments(bundle); return bacteriaFrag; case 1: VirusFragment virusFrag = new VirusFragment(); bundle.putFloat("SCORE_SAVED", virus); virusFrag.setArguments(bundle); return virusFrag; default: return null; } } public CharSequence getPageTitle(int position) { return pageTitles[position]; } @Override public float getPageWidth(int position) { return 1.0f; } } }
true
fd96814bc009d077387488c00f7cb7a9fb36902f
Java
0is2/GDmarket-Premium
/GDmarket-premium/alarm/src/main/java/gdmarketpremium/Alerted.java
UTF-8
252
2.09375
2
[]
no_license
package gdmarketpremium; public class Alerted extends AbstractEvent { private Long id; public Alerted(){ super(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } }
true
c132582208aac627c6954f1bdb82a194fe07664b
Java
1145087558/flightServer
/src/main/java/com/example/flight/exception/GlobalExceptionHandler.java
UTF-8
1,487
2.203125
2
[]
no_license
package com.example.flight.exception; import com.example.flight.model.error.ErrorInfo;; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; @ControllerAdvice public class GlobalExceptionHandler { private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(value = MyException.class) @ResponseBody public ErrorInfo jsonErrorHandler(HttpServletRequest req, MyException e) throws Exception { log.info("执行jsonErrorHandler"); ErrorInfo r = new ErrorInfo(); r.setMessage(e.getMessage()); r.setCode(ErrorInfo.ERROR); r.setData("自定义MyException异常"); r.setUrl(req.getRequestURL().toString()); log.error(e.getMessage()); return r; } @ExceptionHandler(value = Exception.class) @ResponseBody public ErrorInfo exceptionHandler(HttpServletRequest req, Exception e){ log.info("执行exceptionHandler"); ErrorInfo r = new ErrorInfo(); r.setMessage(e.getMessage()); r.setCode(ErrorInfo.ERROR); r.setData("Exception异常"); r.setUrl(req.getRequestURL().toString()); e.printStackTrace(); log.error(e.getMessage()); return r; } }
true
d7360507eaa075f858c7f3ab9cd2e7290a11ab16
Java
callMeZJ/wondeful
/src/main/java/com/wonderful/service/MasterCardPurchaseDetailsSummaryService.java
UTF-8
349
1.625
2
[]
no_license
package com.wonderful.service; import com.baomidou.mybatisplus.core.metadata.IPage; import com.wonderful.bean.dto.MasterCardPurchaseDetailsSummaryDTO; public interface MasterCardPurchaseDetailsSummaryService { IPage<MasterCardPurchaseDetailsSummaryDTO> pageSummary(MasterCardPurchaseDetailsSummaryDTO masterCardPurchaseDetailsSummaryDTO); }
true
16433d414df3ab2fe22559803bf59528b9489178
Java
markdathorne/geektastic
/src/main/java/com/fsbtech/interviews/entities/MarketRefType.java
UTF-8
713
2.71875
3
[]
no_license
package com.fsbtech.interviews.entities; import java.io.Serializable; public class MarketRefType implements Serializable { private final Integer marketRefId; private final String marketRefName; public String toString() { StringBuilder sb = new StringBuilder(); sb.append(marketRefId).append(",").append(marketRefName); return sb.toString(); } public MarketRefType(Integer marketRefId, String marketRefName) { this.marketRefId = marketRefId; this.marketRefName = marketRefName; } public Integer getMarketRefId() { return marketRefId; } public String getMarketRefName() { return marketRefName; } }
true
c369ec9c998afa3429e81c9fb7ded17043ce4f97
Java
capitalhumain/homepage
/java/lab/springboot/junit5-playground/src/test/java/playground/simple/SimpleTest.java
UTF-8
784
2.921875
3
[]
no_license
package playground.simple; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class SimpleTest { @Test public void testAllMatch() { List<Integer> integers = Arrays.asList(1, 2, 3, 4); assertTrue(integers.stream().allMatch(i -> { if(i>0) { return true; } else { return false; } })); integers = Arrays.asList(1, 2, -3, 4); assertFalse(integers.stream().allMatch(i -> { if(i>0) { return true; } else { return false; } })); } }
true
334a1d99da9edc156eb03c1e0210bda033a8126c
Java
rforshaw/MalletEngine
/src/com/linxonline/mallet/input/InputEvent.java
UTF-8
2,845
2.65625
3
[ "Zlib" ]
permissive
package com.linxonline.mallet.input ; import com.linxonline.mallet.util.caches.Cacheable ; public final class InputEvent implements Cacheable { public InputID id ; public InputType inputType ; public KeyCode keycode ; public int mouseX = 0 ; public int mouseY = 0 ; public boolean isActionKey = false ; public long when = 0L ; public InputEvent() { this( InputType.NONE, KeyCode.NONE, InputID.NONE ) ; } public InputEvent( final InputType _type, final int _x, final int _y, final long _when ) { setID( InputID.NONE ) ; setInput( _type, _x, _y, _when ) ; } public InputEvent( final InputType _type, final KeyCode _keycode, final InputID _id ) { id = _id ; inputType = _type ; keycode = _keycode ; } public InputEvent( final InputEvent _toCopy ) { super() ; clone( _toCopy ) ; } public void setID( final InputID _id ) { id = _id ; } public void setInput( final InputType _type, final KeyCode _keycode, final long _when ) { inputType = _type ; keycode = _keycode ; when = _when ; } public void setInput( final InputType _type, final int _x, final int _y ) { setInput( _type, _x, _y, when ) ; } public void setInput( final InputType _type, final int _x, final int _y, final long _when ) { inputType = _type ; mouseX = _x ; mouseY = _y ; when = _when ; } public final InputID getID() { return id ; } public final InputType getInputType() { return inputType ; } public final KeyCode getKeyCode() { return keycode ; } public final char getKeyCharacter() { return keycode.character ; } public final boolean isActionKey() { return isActionKey ; } public final int getMouseX() { return mouseX ; } public final int getMouseY() { return mouseY ; } public long getWhen() { return when ; } public final void clone( final InputEvent _input ) { inputType = _input.inputType ; mouseX = _input.mouseX ; mouseY = _input.mouseY ; keycode = _input.keycode ; isActionKey = _input.isActionKey ; when = _input.when ; } public final void reset() { id = InputID.NONE ; inputType = InputType.NONE ; keycode = KeyCode.NONE ; mouseX = 0 ; mouseY = 0 ; isActionKey = false ; when = 0L ; } public String toString() { final StringBuffer buffer = new StringBuffer() ; buffer.append( '[' ) ; buffer.append( inputType ) ; switch( inputType ) { case KEYBOARD_RELEASED : case KEYBOARD_PRESSED : { buffer.append( " KeyCode: " + keycode ) ; break ; } default : { buffer.append( " X: " + mouseX ) ; buffer.append( " Y: " + mouseY ) ; break ; } } buffer.append( ']' ) ; return buffer.toString() ; } public enum Action { PROPAGATE, // Continue passing the InputEvent to the next IInputHandler CONSUME // Do not propagate the InputEvent any further } }
true
d2a1d28ec001a437777427fae3ba5644978b319b
Java
situjun/order-management
/src/main/java/com/flyingwillow/restaurant/web/waiter/controller/WaiterOrderRestController.java
UTF-8
8,085
2.140625
2
[]
no_license
package com.flyingwillow.restaurant.web.waiter.controller; import com.flyingwillow.restaurant.domain.CustomOrder; import com.flyingwillow.restaurant.domain.CustomOrderDetail; import com.flyingwillow.restaurant.domain.FoodCategory; import com.flyingwillow.restaurant.domain.Menu; import com.flyingwillow.restaurant.service.ICustomOrderDetailService; import com.flyingwillow.restaurant.service.ICustomOrderService; import com.flyingwillow.restaurant.service.IFoodCategoryService; import com.flyingwillow.restaurant.service.IMenuService; import com.flyingwillow.restaurant.service.ITxCustomOrderService; import com.flyingwillow.restaurant.util.web.DataTableResponse; import com.flyingwillow.restaurant.util.web.TableNumberUtil; import com.flyingwillow.restaurant.web.admin.dto.CheckoutDTO; import com.flyingwillow.restaurant.web.admin.vo.JsonResponseStatus; import com.flyingwillow.restaurant.web.waiter.dto.DetailDTO; import com.flyingwillow.restaurant.web.waiter.dto.OrderDTO; import com.flyingwillow.restaurant.web.waiter.vo.MenuGroup; import com.flyingwillow.restaurant.web.waiter.vo.MenuItem; import com.flyingwillow.restaurant.web.waiter.vo.OrderVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by liuxuhui on 2017/9/22. */ @CrossOrigin(origins = "*", maxAge = 3600) @RestController @RequestMapping("/waiter/api") public class WaiterOrderRestController { @Autowired private IMenuService menuService; @Autowired private ICustomOrderService customOrderService; @Autowired private ICustomOrderDetailService customOrderDetailService; @Autowired private IFoodCategoryService foodCategoryService; @Autowired private ITxCustomOrderService txCustomOrderService; // "/order/{orderId}" get @RequestMapping(value = "/order/table/{tableNo}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8") public ResponseEntity getOrderByTableNo(@PathVariable Integer tableNo){ CustomOrder order = customOrderService.getCustomOrderByTableNo(tableNo); if(null==order){ return new ResponseEntity(JsonResponseStatus.buildFailResponse(404,"此桌未点餐"), HttpStatus.BAD_REQUEST); } List<CustomOrderDetail> list = customOrderDetailService.getCustomOrderDetailsByOrder(order.getId().intValue()); OrderVO orderVO = new OrderVO(order,list); return new ResponseEntity(orderVO,HttpStatus.OK); } // "/order" create request body {tableNo:n, details:[]} @RequestMapping(value = "/order", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") public ResponseEntity createOrder(@RequestBody OrderDTO orderDTO){ if(customOrderService.getCustomOrderCountByTableNo(orderDTO.getTableNo())>0){ return new ResponseEntity(JsonResponseStatus.buildFailResponse(500,"此桌重复点餐"),HttpStatus.CONFLICT); } txCustomOrderService.txCreateOrder(orderDTO); return new ResponseEntity(JsonResponseStatus.buildSuccessResponse(),HttpStatus.OK); } // "/order/detail/{detailId}/" 增加量 put @RequestMapping(value = "/order/detail/{detailId}", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8") public ResponseEntity updateOrderDetail(@PathVariable Integer detailId, @RequestParam Float mount){ customOrderDetailService.updateCustomOrderDetailMount(detailId, mount); return new ResponseEntity(JsonResponseStatus.buildSuccessResponse(),HttpStatus.OK); } // "/order/{orderId}/" 增加菜品 post @RequestMapping(value = "/order/{orderId}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") public ResponseEntity addOrderDetail(@PathVariable Integer orderId, @RequestBody DetailDTO detailDTO){ txCustomOrderService.saveOrderDetail(orderId, detailDTO); return new ResponseEntity(JsonResponseStatus.buildSuccessResponse(),HttpStatus.OK); } // "/order/detail/{detailId}" delete @RequestMapping(value = "/order/detail/{detailId}", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8") public ResponseEntity deleteOrderDetail(@PathVariable Integer detailId){ customOrderDetailService.deleteCustomOrderDetail(detailId); return new ResponseEntity(JsonResponseStatus.buildSuccessResponse(),HttpStatus.OK); } // "/order/deliver" 上菜 put @RequestMapping(value = "/order/detail/{detailId}/delivered", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8") public ResponseEntity deliveredOrderDetail(@PathVariable Integer detailId){ customOrderDetailService.deleteCustomOrderDetail(detailId); return new ResponseEntity(JsonResponseStatus.buildSuccessResponse(),HttpStatus.OK); } // "/order/{orderId}/check" put @RequestMapping(value = "/order/{orderId}/checkout", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8") public ResponseEntity checkoutOrder(@PathVariable Integer orderId, @RequestBody CheckoutDTO checkoutDTO){ txCustomOrderService.checkoutOrder(orderId, checkoutDTO); return new ResponseEntity(JsonResponseStatus.buildSuccessResponse(),HttpStatus.OK); } // get menu list @RequestMapping(value = "/menu/grouped", method = RequestMethod.GET, produces = "application/json;charset=UTF-8") public ResponseEntity getGroupedMenus(){ Map<String,Object> result = new HashMap<>(2); List<FoodCategory> categories = foodCategoryService.getFoodCategoryList(null,0,100); if(null!=categories&&categories.size()>0){ List<MenuGroup> groups = new ArrayList<>(categories.size()); for(FoodCategory category : categories){ List<Menu> list = menuService.getMenuListByCategory(category.getId()); MenuGroup group = new MenuGroup(category,list); groups.add(group); } result.put("groups",groups); } return new ResponseEntity(result, HttpStatus.OK); } // get menu list @RequestMapping(value = "/menu/search", method = RequestMethod.GET, produces = "application/json;charset=UTF-8") public ResponseEntity searchMenus(@RequestParam String name){ Map<String,Object> result = new HashMap<>(2); List<Menu> list = menuService.searchMenuByKeywords(name,0,20); if(null==list||list.isEmpty()){ return new ResponseEntity(JsonResponseStatus.buildSuccessResponse(),HttpStatus.OK); }else{ List<MenuItem> results = new ArrayList<>(list.size()); for(Menu menu : list){ results.add(new MenuItem(menu)); } result.put("list",results); } return new ResponseEntity(result, HttpStatus.OK); } //获取桌号列表 @RequestMapping(value = "/tableNo", method = RequestMethod.GET, produces = "application/json;charset=UTF-8") public ResponseEntity getTableNumbers(@RequestParam Integer type){ type = null==type?0:type; List<Integer> listAll = TableNumberUtil.getAllTableNumberList(); List<Integer> listOrdered = customOrderService.getOrderedTableNumbers(); if(1==type){ return new ResponseEntity(listOrdered,HttpStatus.OK); }else { return new ResponseEntity(listAll.removeAll(listOrdered),HttpStatus.OK); } } }
true
2150c1ce86325dd14a3c6849a84699b0daf209da
Java
stormning/platform
/catering-service/src/main/java/com/le07/catering/model/BoardItem.java
UTF-8
1,751
2.171875
2
[]
no_license
package com.le07.catering.model; import org.hibernate.annotations.*; import java.io.Serializable; import javax.persistence.*; import javax.persistence.Entity; import javax.persistence.Table; import java.util.Date; /** * Model * * Created with IDEA * User: 虎 * Date: 13-7-21 * Time: 下午10:39 */ @Entity @Table(name="board_item") @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class BoardItem implements Serializable { private static final long serialVersionUID = 1818895690904242667L; @Id @GeneratedValue(strategy=GenerationType.AUTO) private long id; @Temporal(TemporalType.TIMESTAMP) @Column(name="begin_time") private Date beginTime; @Temporal(TemporalType.TIMESTAMP) @Column(name="end_time") private Date endTime; private int galleryful; private String remark; //bi-directional many-to-one association to Board @ManyToOne @JoinColumn(name = "board_id") private Board board; public BoardItem() { } public long getId() { return this.id; } public int getGalleryful() { return galleryful; } public void setGalleryful(int galleryful) { this.galleryful = galleryful; } public void setId(long id) { this.id = id; } public Date getBeginTime() { return this.beginTime; } public void setBeginTime(Date beginTime) { this.beginTime = beginTime; } public Date getEndTime() { return this.endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public String getRemark() { return this.remark; } public void setRemark(String remark) { this.remark = remark; } public Board getBoard() { return this.board; } public void setBoard(Board board) { this.board = board; } }
true
0351c14d1734f574f673c0e745f7ff423fc3a5f8
Java
satelite54/BUSAN_IT_ACADEMY
/Spring_Infearn/Web_RTC_Sgnaling_Spring_Server/src/main/java/org/nextrtc/signalingserver/domain/EventContext.java
UTF-8
4,159
2.3125
2
[ "MIT" ]
permissive
package org.nextrtc.signalingserver.domain; import com.google.common.collect.Maps; import org.nextrtc.signalingserver.api.NextRTCEvents; import org.nextrtc.signalingserver.api.dto.NextRTCConversation; import org.nextrtc.signalingserver.api.dto.NextRTCEvent; import org.nextrtc.signalingserver.api.dto.NextRTCMember; import org.nextrtc.signalingserver.exception.SignalingException; import java.time.ZonedDateTime; import java.util.Map; import java.util.Optional; import static java.util.Collections.unmodifiableMap; import static java.util.Optional.ofNullable; import static org.apache.commons.lang3.StringUtils.defaultString; public class EventContext implements NextRTCEvent { private final NextRTCEvents type; private final ZonedDateTime published = ZonedDateTime.now(); private final Map<String, String> custom = Maps.newHashMap(); private final NextRTCMember from; private final NextRTCMember to; private final NextRTCConversation conversation; private final SignalingException exception; private final String content; private EventContext(NextRTCEvents type, NextRTCMember from, NextRTCMember to, NextRTCConversation conversation, SignalingException exception, String content) { this.type = type; this.from = from; this.to = to; this.conversation = conversation; this.exception = exception; this.content = content; } @Override public NextRTCEvents type() { return type; } @Override public ZonedDateTime published() { return published; } @Override public Optional<NextRTCMember> from() { return ofNullable(from); } @Override public Optional<NextRTCMember> to() { return ofNullable(to); } @Override public Optional<NextRTCConversation> conversation() { return ofNullable(conversation); } @Override public Optional<SignalingException> exception() { return ofNullable(exception); } @Override public Map<String, String> custom() { return unmodifiableMap(custom); } @Override public String content() { return defaultString(content); } @Override public String toString() { return String.format("%s (%s -> %s) | conv: %s | %s", type, from, to, conversation, custom); } public static EventContextBuilder builder() { return new EventContextBuilder(); } public static class EventContextBuilder { private Map<String, String> custom; private NextRTCEvents type; private NextRTCMember from; private NextRTCMember to; private NextRTCConversation conversation; private SignalingException exception; private String content; public EventContextBuilder content(String content) { this.content = content; return this; } public EventContextBuilder type(NextRTCEvents type) { this.type = type; return this; } public EventContextBuilder custom(Map<String, String> custom) { this.custom = custom; return this; } public EventContextBuilder from(NextRTCMember from) { this.from = from; return this; } public EventContextBuilder to(NextRTCMember to) { this.to = to; return this; } public EventContextBuilder conversation(NextRTCConversation conversation) { this.conversation = conversation; return this; } public EventContextBuilder exception(SignalingException exception) { this.exception = exception; return this; } public NextRTCEvent build() { if (type == null) { throw new IllegalArgumentException("Type is required"); } EventContext eventContext = new EventContext(type, from, to, conversation, exception, content); if (custom != null) { eventContext.custom.putAll(custom); } return eventContext; } } }
true
65a47bb1bb32bd0a01d0b33a486ca9313e5c5f09
Java
liuandhisgithub/myblog
/blog/src/main/java/com/liu/myblog/action/CommentAction.java
UTF-8
907
1.984375
2
[]
no_license
package com.liu.myblog.action; import com.liu.myblog.entity.Comment; import com.liu.myblog.service.CommentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import sun.plugin.com.event.COMEventHandler; @Controller(CommentAction.CODE) @RequestMapping("/comment") public class CommentAction { public static final String CODE = "com.liu.myblog.action.CommentAction"; @Autowired @Qualifier(CommentService.CODE) private CommentService commentService; @RequestMapping("submitComment") public String save(Comment comment){ commentService.save(comment); return "redirect:../blog/find/one?id="+comment.getBlogId(); } }
true
547a65803de9fa882fec05b09c57091ec81af67b
Java
reverseengineeringer/fr.dvilleneuve.lockito
/src/io/fabric/sdk/android/services/persistence/PersistenceStrategy.java
UTF-8
378
1.835938
2
[]
no_license
package io.fabric.sdk.android.services.persistence; public abstract interface PersistenceStrategy<T> { public abstract void clear(); public abstract T restore(); public abstract void save(T paramT); } /* Location: * Qualified Name: io.fabric.sdk.android.services.persistence.PersistenceStrategy * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
fe6aeb1315330d19954d57922a1fcbc976bf59c7
Java
18731218717/jewelry_manager
/src/main/java/org/bdyy/jewelry/pojo/FinishedProductSubclassExample.java
UTF-8
14,227
2.328125
2
[]
no_license
package org.bdyy.jewelry.pojo; import java.util.ArrayList; import java.util.List; public class FinishedProductSubclassExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public FinishedProductSubclassExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andFinishedProductSubclassIdIsNull() { addCriterion("finished_product_subclass_id is null"); return (Criteria) this; } public Criteria andFinishedProductSubclassIdIsNotNull() { addCriterion("finished_product_subclass_id is not null"); return (Criteria) this; } public Criteria andFinishedProductSubclassIdEqualTo(Integer value) { addCriterion("finished_product_subclass_id =", value, "finishedProductSubclassId"); return (Criteria) this; } public Criteria andFinishedProductSubclassIdNotEqualTo(Integer value) { addCriterion("finished_product_subclass_id <>", value, "finishedProductSubclassId"); return (Criteria) this; } public Criteria andFinishedProductSubclassIdGreaterThan(Integer value) { addCriterion("finished_product_subclass_id >", value, "finishedProductSubclassId"); return (Criteria) this; } public Criteria andFinishedProductSubclassIdGreaterThanOrEqualTo(Integer value) { addCriterion("finished_product_subclass_id >=", value, "finishedProductSubclassId"); return (Criteria) this; } public Criteria andFinishedProductSubclassIdLessThan(Integer value) { addCriterion("finished_product_subclass_id <", value, "finishedProductSubclassId"); return (Criteria) this; } public Criteria andFinishedProductSubclassIdLessThanOrEqualTo(Integer value) { addCriterion("finished_product_subclass_id <=", value, "finishedProductSubclassId"); return (Criteria) this; } public Criteria andFinishedProductSubclassIdIn(List<Integer> values) { addCriterion("finished_product_subclass_id in", values, "finishedProductSubclassId"); return (Criteria) this; } public Criteria andFinishedProductSubclassIdNotIn(List<Integer> values) { addCriterion("finished_product_subclass_id not in", values, "finishedProductSubclassId"); return (Criteria) this; } public Criteria andFinishedProductSubclassIdBetween(Integer value1, Integer value2) { addCriterion("finished_product_subclass_id between", value1, value2, "finishedProductSubclassId"); return (Criteria) this; } public Criteria andFinishedProductSubclassIdNotBetween(Integer value1, Integer value2) { addCriterion("finished_product_subclass_id not between", value1, value2, "finishedProductSubclassId"); return (Criteria) this; } public Criteria andFinishedProductSubclassNameIsNull() { addCriterion("finished_product_subclass_name is null"); return (Criteria) this; } public Criteria andFinishedProductSubclassNameIsNotNull() { addCriterion("finished_product_subclass_name is not null"); return (Criteria) this; } public Criteria andFinishedProductSubclassNameEqualTo(String value) { addCriterion("finished_product_subclass_name =", value, "finishedProductSubclassName"); return (Criteria) this; } public Criteria andFinishedProductSubclassNameNotEqualTo(String value) { addCriterion("finished_product_subclass_name <>", value, "finishedProductSubclassName"); return (Criteria) this; } public Criteria andFinishedProductSubclassNameGreaterThan(String value) { addCriterion("finished_product_subclass_name >", value, "finishedProductSubclassName"); return (Criteria) this; } public Criteria andFinishedProductSubclassNameGreaterThanOrEqualTo(String value) { addCriterion("finished_product_subclass_name >=", value, "finishedProductSubclassName"); return (Criteria) this; } public Criteria andFinishedProductSubclassNameLessThan(String value) { addCriterion("finished_product_subclass_name <", value, "finishedProductSubclassName"); return (Criteria) this; } public Criteria andFinishedProductSubclassNameLessThanOrEqualTo(String value) { addCriterion("finished_product_subclass_name <=", value, "finishedProductSubclassName"); return (Criteria) this; } public Criteria andFinishedProductSubclassNameLike(String value) { addCriterion("finished_product_subclass_name like", value, "finishedProductSubclassName"); return (Criteria) this; } public Criteria andFinishedProductSubclassNameNotLike(String value) { addCriterion("finished_product_subclass_name not like", value, "finishedProductSubclassName"); return (Criteria) this; } public Criteria andFinishedProductSubclassNameIn(List<String> values) { addCriterion("finished_product_subclass_name in", values, "finishedProductSubclassName"); return (Criteria) this; } public Criteria andFinishedProductSubclassNameNotIn(List<String> values) { addCriterion("finished_product_subclass_name not in", values, "finishedProductSubclassName"); return (Criteria) this; } public Criteria andFinishedProductSubclassNameBetween(String value1, String value2) { addCriterion("finished_product_subclass_name between", value1, value2, "finishedProductSubclassName"); return (Criteria) this; } public Criteria andFinishedProductSubclassNameNotBetween(String value1, String value2) { addCriterion("finished_product_subclass_name not between", value1, value2, "finishedProductSubclassName"); return (Criteria) this; } public Criteria andFinishedProductSubclassTokenIsNull() { addCriterion("finished_product_subclass_token is null"); return (Criteria) this; } public Criteria andFinishedProductSubclassTokenIsNotNull() { addCriterion("finished_product_subclass_token is not null"); return (Criteria) this; } public Criteria andFinishedProductSubclassTokenEqualTo(String value) { addCriterion("finished_product_subclass_token =", value, "finishedProductSubclassToken"); return (Criteria) this; } public Criteria andFinishedProductSubclassTokenNotEqualTo(String value) { addCriterion("finished_product_subclass_token <>", value, "finishedProductSubclassToken"); return (Criteria) this; } public Criteria andFinishedProductSubclassTokenGreaterThan(String value) { addCriterion("finished_product_subclass_token >", value, "finishedProductSubclassToken"); return (Criteria) this; } public Criteria andFinishedProductSubclassTokenGreaterThanOrEqualTo(String value) { addCriterion("finished_product_subclass_token >=", value, "finishedProductSubclassToken"); return (Criteria) this; } public Criteria andFinishedProductSubclassTokenLessThan(String value) { addCriterion("finished_product_subclass_token <", value, "finishedProductSubclassToken"); return (Criteria) this; } public Criteria andFinishedProductSubclassTokenLessThanOrEqualTo(String value) { addCriterion("finished_product_subclass_token <=", value, "finishedProductSubclassToken"); return (Criteria) this; } public Criteria andFinishedProductSubclassTokenLike(String value) { addCriterion("finished_product_subclass_token like", value, "finishedProductSubclassToken"); return (Criteria) this; } public Criteria andFinishedProductSubclassTokenNotLike(String value) { addCriterion("finished_product_subclass_token not like", value, "finishedProductSubclassToken"); return (Criteria) this; } public Criteria andFinishedProductSubclassTokenIn(List<String> values) { addCriterion("finished_product_subclass_token in", values, "finishedProductSubclassToken"); return (Criteria) this; } public Criteria andFinishedProductSubclassTokenNotIn(List<String> values) { addCriterion("finished_product_subclass_token not in", values, "finishedProductSubclassToken"); return (Criteria) this; } public Criteria andFinishedProductSubclassTokenBetween(String value1, String value2) { addCriterion("finished_product_subclass_token between", value1, value2, "finishedProductSubclassToken"); return (Criteria) this; } public Criteria andFinishedProductSubclassTokenNotBetween(String value1, String value2) { addCriterion("finished_product_subclass_token not between", value1, value2, "finishedProductSubclassToken"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
true
3c8cc8a2ff469b051c47abac193d3c230d44f414
Java
Mararsh/MyBox
/alpha/MyBox/src/main/java/mara/mybox/controller/JsonAddElementController.java
UTF-8
2,578
2.1875
2
[ "Apache-2.0" ]
permissive
package mara.mybox.controller; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import javafx.fxml.FXML; import javafx.scene.control.TreeItem; import mara.mybox.data.JsonTreeNode; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2023-5-20 * @License Apache License Version 2.0 */ public class JsonAddElementController extends ControlJsonNodeBase { public void setParameters(ControlJsonTree treeController, TreeItem<JsonTreeNode> item) { try { this.treeController = treeController; this.treeItem = item; setTitle(treeController.getMyStage().getTitle()); checkValue(); } catch (Exception e) { MyBoxLog.error(e); } } @FXML @Override public void okAction() { try { if (treeItem == null) { close(); return; } JsonTreeNode treeNode = treeItem.getValue(); if (treeNode == null || !treeNode.isArray()) { close(); return; } JsonNode newNode = pickValue(); if (newNode == null) { popError(message("InvalidParameter") + ": " + message("Value")); return; } ArrayNode arrayNode = (ArrayNode) treeNode.getJsonNode(); arrayNode.add(newNode); treeItem.getValue().setJsonNode(arrayNode); treeController.updateTreeItem(treeItem); treeController.jsonEditor.domChanged(true); treeController.jsonEditor.popInformation(message("CreatedSuccessfully")); close(); } catch (Exception e) { MyBoxLog.error(e); } } @FXML @Override public void cancelAction() { close(); } @Override public boolean keyESC() { close(); return false; } /* static methods */ public static JsonAddElementController open(ControlJsonTree treeController, TreeItem<JsonTreeNode> item) { JsonAddElementController controller = (JsonAddElementController) WindowTools.openChildStage( treeController.getMyWindow(), Fxmls.JsonAddElementFxml); if (controller != null) { controller.setParameters(treeController, item); controller.requestMouse(); } return controller; } }
true
71317ce30a07857bfe532f0bd265431c0e22ce2f
Java
mictra/ooprojekt2015
/calendarplusplus/src/test/java/edu/chl/calendarplusplus/model/NotificationManagerTest.java
UTF-8
1,551
2.65625
3
[]
no_license
/* * 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 edu.chl.calendarplusplus.model; import java.util.Calendar; import org.junit.Test; import org.junit.Assert; /** * * @author Johan */ public class NotificationManagerTest { Calendar time_1 = Calendar.getInstance(); Calendar time_2 = Calendar.getInstance(); IActivity a1; INotification n1; INotificationManager n; public NotificationManagerTest(){ n = new NotificationManager(); time_2.add(Calendar.MINUTE, 5); time_2.add(Calendar.MINUTE, 10); } @Test public void getNotification(){ a1 = new Activity(time_1, time_2, "An Activity", "", "", null); n1 = new Notification(time_1, "A Notification", "A Description", a1); n.setNotification(a1, n1); Assert.assertEquals(n1, n.getNotification(a1)); } //@Test public void editNotification(){ a1 = new Activity(time_1, time_2, "An Activity", "", "", null); n1 = new Notification(time_1, "Old Notification", "A Description",a1); n.setNotification(a1, n1); Assert.assertEquals(n1, n.getNotification(a1)); Notification n2 = new Notification(time_1, "New Notification", "A Description", a1); n.setNotification(a1, n2); Assert.assertEquals(n2, n.getNotification(a1)); } }
true
76bcce655109d30a7056c8ae6c845d1a51fe4f0a
Java
marcoeilers/pcsd
/assignment-3/master/src/dk/diku/pcsd/assignment3/master/impl/KeyValueBaseMasterImplService.java
UTF-8
2,931
2.109375
2
[]
no_license
package dk.diku.pcsd.assignment3.master.impl; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; import javax.jws.WebMethod; import javax.jws.WebService; import dk.diku.pcsd.assignment3.impl.KeyImpl; import dk.diku.pcsd.assignment3.impl.ValueListImpl; import dk.diku.pcsd.keyvaluebase.exceptions.BeginGreaterThanEndException; import dk.diku.pcsd.keyvaluebase.exceptions.KeyAlreadyPresentException; import dk.diku.pcsd.keyvaluebase.exceptions.KeyNotFoundException; import dk.diku.pcsd.keyvaluebase.exceptions.ServiceAlreadyConfiguredException; import dk.diku.pcsd.keyvaluebase.exceptions.ServiceAlreadyInitializedException; import dk.diku.pcsd.keyvaluebase.exceptions.ServiceInitializingException; import dk.diku.pcsd.keyvaluebase.exceptions.ServiceNotInitializedException; import dk.diku.pcsd.keyvaluebase.interfaces.Configuration; import dk.diku.pcsd.keyvaluebase.interfaces.Pair; import dk.diku.pcsd.keyvaluebase.interfaces.Predicate; import dk.diku.pcsd.keyvaluebase.interfaces.TimestampLog; @WebService public class KeyValueBaseMasterImplService extends KeyValueBaseMasterImpl{ public KeyValueBaseMasterImplService() { super(); } @Override @WebMethod public void init(String serverFilename) throws ServiceAlreadyInitializedException, ServiceInitializingException, FileNotFoundException { super.init(serverFilename); } @Override @WebMethod public Pair<TimestampLog, ValueListImpl> read(KeyImpl k) throws KeyNotFoundException, IOException, ServiceNotInitializedException { return super.read(k); } @Override @WebMethod public void insert(KeyImpl k, ValueListImpl v) throws KeyAlreadyPresentException, IOException, ServiceNotInitializedException { super.insert(k, v); } @Override @WebMethod public void update(KeyImpl k, ValueListImpl newV) throws KeyNotFoundException, IOException, ServiceNotInitializedException { super.update(k, newV); } @Override @WebMethod public void delete(KeyImpl k) throws KeyNotFoundException, ServiceNotInitializedException { super.delete(k); } @Override @WebMethod public Pair<TimestampLog, List<ValueListImpl>> scan(KeyImpl begin, KeyImpl end, Predicate<ValueListImpl> p) throws IOException, BeginGreaterThanEndException, ServiceNotInitializedException { return super.scan(begin, end, p); } @Override @WebMethod public Pair<TimestampLog, List<ValueListImpl>> atomicScan(KeyImpl begin, KeyImpl end, Predicate<ValueListImpl> p) throws IOException, BeginGreaterThanEndException, ServiceNotInitializedException { return super.atomicScan(begin, end, p); } @Override @WebMethod public void bulkPut(List<Pair<KeyImpl, ValueListImpl>> mappings) throws IOException, ServiceNotInitializedException { super.bulkPut(mappings); } @Override @WebMethod public void config(Configuration conf) throws ServiceAlreadyConfiguredException { super.config(conf); } }
true
348aba1fb10a6d711ee5c8ff31515a48801e8179
Java
Park-SooYeon/Coding-Test-Practice
/bruteForce/permutation/Baekjoon1339.java
UTF-8
2,107
3.390625
3
[]
no_license
package bruteForce.permutation; /* 문제 출처 : https://www.acmicpc.net/problem/1339 단어 수학 푼 날짜 : 2021-03-07 */ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Baekjoon1339 { private static int n, max; private static char[][] words; private static boolean[] selected; private static List<Character> alphabet; private static Map<Character, Integer> map; private static int calc() { int sum = 0; for(int i = 0 ; i < n ; i++) { int temp = 0; for(char c : words[i]) { temp *= 10; // 자리수를 하나씩 올려줌 temp += map.get(c); } sum += temp; } return sum; } private static void permutation(int depth) { if(depth == alphabet.size()) { int temp = calc(); max = Math.max(max, temp); return; } for(int i = 0 ; i < 10 ; i++) { if(selected[i]) continue; selected[i] = true; map.put(alphabet.get(depth), i); permutation(depth + 1); selected[i] = false; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); n = Integer.parseInt(br.readLine()); max = Integer.MIN_VALUE; words = new char[n][]; selected = new boolean[10]; alphabet = new ArrayList<Character>(); map = new HashMap<Character, Integer>(); for(int i = 0 ; i < n ; i++) { char[] inputChar = br.readLine().toCharArray(); words[i] = inputChar; // 입력받은 문자열을 character 배열에 저장 // 알파벳 중복 제거 for(char c : inputChar) { if(alphabet.contains(c)) continue; alphabet.add(c); } } permutation(0); bw.write(max + ""); bw.flush(); bw.close(); br.close(); } }
true
ff65fb97826de92e7d096aac67a5bc9c1d493cb0
Java
seycileli/TimBuchalkaJavaMasterClass
/ClassesConstructorsInheritance/point/entities/Point.java
UTF-8
2,128
4.4375
4
[]
no_license
package entities; public class Point { /* You have to represent a Point in 2D space. The class needs two fields (instance variables) with name x and y, of type int */ private int x, y; /* The class needs to have two constructors. The first constructor does not have any parameters (no-arg constructor) The second constructor has parameters x and y of type int and it needs to initialize the fields. Write the following fields; Create Getters & Setters Empty Constructor & Constructor that has 2 parameters x and y of type int */ /* Method named distance without any parameters, It needs to return the distance between this Point and Point 0, 0 as double. */ public double distance() { return Math.sqrt((this.x * this.x) + (this.y * this.y)); } /* Method named distance with 2 parameters, x, y both of type int. It needs to return the distance between this Point and Point x, y as double */ public double distance(int x, int y) { return Math.sqrt((this.x - x) * (this.x - x) + (this.y - y) * (this.y - y)); } /* Method named distance with parameter another of type Point, it needs to return the distance between this Point and another Point as double How to find the distance between two points? To find a distance between points A(xA,yA) and B(xB,yB), we use the formula: d(A,B)=√ (xB − xA) * (xB - xA) + (yB − yA) * (yB - yA) Where √ represents square root. */ public double distance(Point point) { return Math.sqrt( (point.getX() - x) * (point.getX() - x) + (point.getY() - y) * (point.getY() - y)); } public Point() { } public Point(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } }
true
3a1a3713f7179a0568cc0aba2c42f30a93807925
Java
duketeaches/ds_algo
/src/main/java/duke/learn/stacks/StackOps.java
UTF-8
2,080
3.46875
3
[ "Apache-2.0" ]
permissive
package duke.learn.stacks; import java.io.File; import java.io.IOException; import java.nio.file.Files; public class StackOps { public static String reverseWord(String word) { Stack<Character> charStack = new Stack<>(word.length()); for (int i = 0; i < word.length(); i++) charStack.push(word.charAt(i)); StringBuilder builder = new StringBuilder(); while (!charStack.isEmpty()) builder.append(charStack.pop()); return builder.toString(); } public static boolean validateDelimeters(String brackets) { return validateDelimeters(brackets, false); } public static boolean validateDelimeters(String brackets, boolean debug) { Stack<Character> bracketStack = new Stack<>(brackets.length()); brackets.chars().anyMatch(c -> { boolean doNoContinue = false; char ch = (char) c; switch (ch) { case '{': case '(': case '[': if (debug) System.out.println("checking " + ch); bracketStack.push((char) ch); break; case '}': case ')': case ']': if (debug) System.out.println("checking " + ch); if (!bracketStack.isEmpty()) { char chx = bracketStack.pop(); if ((ch == ')' && chx != '(') || (ch == '}' && chx != '{') || (ch == ']' && chx != '[')) { doNoContinue = true; bracketStack.push(ch); break; } } else { bracketStack.push(ch); doNoContinue = true; break; } break; } if (doNoContinue) { return true; } return false; }); if (bracketStack.isEmpty()) return true; return false; } public static void main(String[] args) throws IOException { // System.out.println(reverseWord("WHAT")); File file = new File( "D:\\works\\workspaces\\EclipseWorkspaces\\POC\\data-structures\\src\\main\\java\\duke\\learn\\sort\\InsertionSort.java"); String javaCode = new String(Files.readAllBytes(file.toPath())); // System.out.println(javaCode); System.out.println(validateDelimeters(javaCode, true)); } }
true
9e757174901633bc4ee571f9d0948879c1dffa5b
Java
believe6998/hocjava
/Game/src/entity/Game.java
UTF-8
1,559
2.859375
3
[]
no_license
package entity; public class Game { private String name; private String description; private double price; private String releaseAt; private String website; public Game() { } public Game(String name, String description, double price, String releaseAt, String website) { this.name = name; this.description = description; this.price = price; this.releaseAt = releaseAt; this.website = website; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getReleaseAt() { return releaseAt; } public void setReleaseAt(String releaseAt) { this.releaseAt = releaseAt; } public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } @Override public String toString() { return "Game{" + "name='" + name + '\'' + ", description='" + description + '\'' + ", price=" + price + ", releaseAt='" + releaseAt + '\'' + ", website='" + website + '\'' + '}'; } }
true
35f5e180b94f5bd5c4bbec44c602b8108a981aaf
Java
mcparkournet/anfodis
/anfodis-paper/src/main/java/net/mcparkour/anfodis/channel/registry/PaperChannelListenerRegistry.java
UTF-8
4,995
1.664063
2
[ "MIT" ]
permissive
/* * MIT License * * Copyright (c) 2020 MCParkour * * 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 net.mcparkour.anfodis.channel.registry; import java.util.Set; import net.mcparkour.anfodis.channel.ChannelMessage; import net.mcparkour.anfodis.channel.handler.ChannelListenerContext; import net.mcparkour.anfodis.channel.handler.PaperChannelListenerHandler; import net.mcparkour.anfodis.channel.mapper.PaperChannelListener; import net.mcparkour.anfodis.channel.mapper.PaperChannelListenerMapper; import net.mcparkour.anfodis.channel.mapper.properties.PaperChannelListenerProperties; import net.mcparkour.anfodis.codec.context.TransformCodec; import net.mcparkour.anfodis.codec.registry.CodecRegistry; import net.mcparkour.anfodis.codec.injection.InjectionCodec; import net.mcparkour.anfodis.handler.ContextHandler; import net.mcparkour.anfodis.registry.AbstractRegistry; import org.bukkit.Server; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.messaging.Messenger; import org.bukkit.plugin.messaging.PluginMessageListener; public class PaperChannelListenerRegistry extends AbstractRegistry<PaperChannelListener, ChannelListenerContext> { private static final PaperChannelListenerMapper CHANNEL_LISTENER_MAPPER = new PaperChannelListenerMapper(); private final Plugin plugin; private final Messenger messenger; public PaperChannelListenerRegistry( final CodecRegistry<InjectionCodec<?>> injectionCodecRegistry, final CodecRegistry<TransformCodec<ChannelListenerContext, ?>> transformCodecRegistry, final Plugin plugin ) { super( net.mcparkour.anfodis.channel.annotation.properties.ChannelListener.class, CHANNEL_LISTENER_MAPPER, injectionCodecRegistry, transformCodecRegistry ); this.plugin = plugin; Server server = plugin.getServer(); this.messenger = server.getMessenger(); } @Override public void register(final PaperChannelListener root) { CodecRegistry<InjectionCodec<?>> injectionCodecRegistry = getInjectionCodecRegistry(); CodecRegistry<TransformCodec<ChannelListenerContext, ?>> transformCodecRegistry = getTransformCodecRegistry(); PaperChannelListenerHandler handler = new PaperChannelListenerHandler(root, injectionCodecRegistry, transformCodecRegistry); register(root, handler); } @Override public void register(final PaperChannelListener root, final ContextHandler<ChannelListenerContext> handler) { PaperChannelListenerProperties properties = root.getProperties(); Set<String> channels = properties.getChannels(); for (final String channel : channels) { register(root, channel, handler); } } private void register(final PaperChannelListener channelListener, final String channel, final ContextHandler<ChannelListenerContext> handler) { ChannelListener listener = (source, message) -> { ChannelListenerContext context = new ChannelListenerContext(source, message); Object channelListenerInstance = channelListener.createInstance(); handler.handle(context, channelListenerInstance); }; register(channel, listener); } public void register(final String channel, final ChannelListener channelListener) { PluginMessageListener messageListener = createPluginMessageListener(channel, channelListener); this.messenger.registerIncomingPluginChannel(this.plugin, channel, messageListener); } private PluginMessageListener createPluginMessageListener(final String channel, final ChannelListener channelListener) { return (incomingChannel, player, message) -> { if (channel.equals(incomingChannel)) { ChannelMessage channelMessage = new ChannelMessage(message); channelListener.listen(player, channelMessage); } }; } }
true
bf5145dd88bec090607e299d6c8e5426c7131176
Java
seshasaisrivatsav/data-structures-java
/src/main/java/arraysAndStrings/MajorityElement.java
UTF-8
4,253
4.4375
4
[]
no_license
package arraysAndStrings; import java.util.Arrays; /* Given an array nums of size n, return the majority element. The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. Try to solve the problem in linear time and O(1) space */ public class MajorityElement { public static void main(String[] args) { System.out.println(majorityElementUsingBoyerMoore(new int[]{1, 1, 2, 2, 2})); System.out.println(majorityElementUsingBoyerMoore(new int[]{3, 2, 3}));// 3 System.out.println(majorityElementUsingSortingSmartCode(new int[]{1, 1, 2, 2, 2})); System.out.println(majorityElementUsingSortingSmartCode(new int[]{3, 2, 3}));// 3 System.out.println(majorityElementUsingSorting(new int[]{1, 1, 2, 2, 2})); } /* Time Complexity: O(n) Space Complexity: O(1) Intuition: If we had some way of counting instances of the majority element as +1 and instances of any other element as −1, summing them would make it obvious that the majority element is indeed the majority element. Algorithm: - Essentially, what Boyer-Moore does is look for a suffix suf of nums where suf[0] is the majority element in that suffix. - To do this, we maintain a count, which is incremented whenever we see an instance of our current candidate for majority element and decremented whenever we see anything else. - Whenever count equals 0, we effectively forget about everything in nums up to the current index and consider the current number as the candidate for majority element. - It is not immediately obvious why we can get away with forgetting prefixes of nums - consider the following examples (pipes are inserted to separate runs of nonzero count). [7, 7, 5, 7, 5, 1 | 5, 7 | 5, 5, 7, 7 | 7, 7, 7, 7] - Here, the 7 at index 0 is selected to be the first candidate for majority element. - count will eventually reach 0 after index 5 is processed, so the 5 at index 6 will be the next candidate. - In this case, 7 is the true majority element, so by disregarding this prefix, we are ignoring an equal number of majority and minority elements - therefore, 7 will still be the majority element in the suffix formed by throwing away the first prefix. [7, 7, 5, 7, 5, 1 | 5, 7 | 5, 5, 7, 7 | 5, 5, 5, 5] - Now, the majority element is 5 (we changed the last run of the array from 7s to 5s), but our first candidate is still 7. In this case, our candidate is not the true majority element, but we still cannot discard more majority elements than minority elements (this would imply that count could reach -1 before we reassign candidate, which is obviously false). - Therefore, given that it is impossible (in both cases) to discard more majority elements than minority elements, we are safe in discarding the prefix and attempting to recursively solve the majority element problem for the suffix. - Eventually, a suffix will be found for which count does not hit 0, and the majority element of that suffix will necessarily be the same as the majority element of the overall array. */ public static int majorityElementUsingBoyerMoore(int[] nums) { int count = 0; Integer candidate = null; for (int num : nums) { if (count == 0) { candidate = num; } count += (num == candidate) ? 1 : -1; } return candidate; } public static int majorityElementUsingSortingSmartCode(int[] nums) { Arrays.sort(nums); return nums[nums.length/2]; } /** * Using sorting * TC: O(n log n) * SC: O(1) * @param nums * @return */ public static int majorityElementUsingSorting(int[] nums) { int length = nums.length/2; Arrays.sort(nums); int count = 1; for (int i=1; i<nums.length; i++) { if (nums[i]==nums[i-1]) { count ++; } else { count = 1; } if (count > length) { return nums[i]; } } return nums[0]; } }
true
72bc44587ac4101ec882d59c74a9198083bc6176
Java
colbymorrison/chord-app-v2
/src/main/java/backend/Resty.java
UTF-8
577
2.859375
3
[ "Apache-2.0" ]
permissive
package backend; import org.jfugue.theory.Note; public class Resty extends Note implements Useable{ private Duration duration; public Resty(Duration duration) { super("R"+duration.getDur()); this.duration = duration; } public boolean isRest(){ return true; } public String[] getRow() { return new String[]{ "R", "", duration.toString() // this was originally giving back a double, now it gives back the string }; } public void setDur(Duration dur) { this.duration = dur; } }
true
337d0017276504cf6df53e9f3dcbe38a7fc92837
Java
xwhPanda/MyToolsProject
/NoteBook/src/main/java/com/lanshu/fragment/BaseFragment.java
UTF-8
1,180
2.140625
2
[]
no_license
package com.lanshu.fragment; import android.databinding.DataBindingUtil; import android.databinding.ViewDataBinding; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * Author xwh * Email 1152046774@qq.com * CreateTime 2017/1/10 20:18 */ public abstract class BaseFragment extends Fragment { protected View view; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { ViewDataBinding binding = DataBindingUtil.inflate(inflater,getLayoutViewId(),container,false); Log.e("TAG",binding + " : id"); view = binding.getRoot(); createView(); return view; } @Override public void onDestroyView() { super.onDestroyView(); } protected abstract void createView(); protected abstract int getLayoutViewId(); }
true
13aedce99bf49e8ef44714a7f2391133e24bded7
Java
Jonol3/retoLogin-Android
/app/src/main/java/com/example/reto1/LogOut.java
UTF-8
1,447
2.515625
3
[]
no_license
package com.example.reto1; import androidx.appcompat.app.AppCompatActivity; import retoLogin.User; import android.content.Intent; import android.media.MediaPlayer; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; /** * Class for the LogOut activity * @author Jon Calvo Gaminde */ public class LogOut extends AppCompatActivity implements View.OnClickListener { private User user = new User(); private TextView tvGreeting; private Button btnLogOut; private MediaPlayer mp; /* * Initializes the Activity */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_out); Intent intent = getIntent(); user = (User) intent.getSerializableExtra("USER"); tvGreeting = (TextView) findViewById(R.id.tvGreeting); btnLogOut = (Button) findViewById(R.id.btnLogOut); tvGreeting.setText(getResources().getString(R.string.greeting) + " " + user.getFullName()); btnLogOut.setOnClickListener(this); mp = MediaPlayer.create(this, R.raw.button); } /** * Checks if the LogOut button has been clicked, and finishes the Activity * @param view The current view */ @Override public void onClick(View view) { mp.start(); finish(); } }
true
bff857b13fc6cfa52845e963c815a8f3876715be
Java
kylelee0617/SpringBootSample
/ModuleWeb/src/main/java/com/fg/web/zbean/LoginBean.java
UTF-8
596
2.015625
2
[]
no_license
package com.fg.web.zbean; import com.fg.service.vo.Result; public class LoginBean { private String useracc = ""; private String userpwd = ""; private Result result = null; //登入結果 public String getUseracc() { return useracc; } public void setUseracc(String useracc) { this.useracc = useracc; } public String getUserpwd() { return userpwd; } public void setUserpwd(String userpwd) { this.userpwd = userpwd; } public Result getResult() { return result; } public void setResult(Result result) { this.result = result; } }
true
2aca1ef993206e60cd81f9a543a94e98396b923e
Java
Yatharth0045/ProgrammingStuff
/javaPrograms/AlternateElementProduct.java
UTF-8
1,093
3.890625
4
[]
no_license
/* Given an array of integers, find the pair of adjacent elements that has the largest product and return that product. Example For inputArray = [3, 6, -2, -5, 7, 3], the output should be adjacentElementsProduct(inputArray) = 21. 7 and 3 produce the largest product. */ class AlternateElementProduct{ public static void main(String[] args) { int arr[]={3,6,-2,-5,7,3}; System.out.println(alternateElements(arr)); } static int alternateElements(int[] inputArray) { int i=0,mul1=Integer.MIN_VALUE,mul2=Integer.MIN_VALUE; while(i<inputArray.length) { if(i%2==0) { if(inputArray[i]>0) { mul1=mul1*inputArray[i]; } } else{ if(inputArray[i]>0) { mul2=mul2*inputArray[i]; } } i++; } if(mul1>mul2) return mul1; else return mul2; } }
true
f9b7fc56cb59aaa4060bee9197b8d4bae0756a91
Java
pombredanne/maven-verifier
/src/main/java/org/apache/maven/it/launcher/ForkedLauncher.java
UTF-8
5,791
1.890625
2
[]
no_license
package org.apache.maven.it.launcher; /* * 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. */ import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.maven.shared.utils.StringUtils; import org.apache.maven.shared.utils.cli.CommandLineException; import org.apache.maven.shared.utils.cli.CommandLineUtils; import org.apache.maven.shared.utils.cli.Commandline; import org.apache.maven.shared.utils.cli.StreamConsumer; import org.apache.maven.shared.utils.cli.WriterStreamConsumer; import org.apache.maven.shared.utils.io.FileUtils; /** * @author Benjamin Bentmann */ public class ForkedLauncher implements MavenLauncher { private final String mavenHome; private final Map<String, String> envVars; private final String executable; public ForkedLauncher(String mavenHome) { this(mavenHome, Collections.<String, String> emptyMap(), false); } public ForkedLauncher(String mavenHome, Map<String, String> envVars, boolean debugJvm) { this.mavenHome = mavenHome; this.envVars = Collections.unmodifiableMap(new LinkedHashMap<String, String>(envVars)); String script = debugJvm ? "mvnDebug" : "mvn"; if (mavenHome != null) { executable = new File(mavenHome, "bin/" + script).getPath(); } else { executable = script; } } public int run(String[] cliArgs, Map<String, String> envVars, String workingDirectory, File logFile) throws IOException, LauncherException { Commandline cmd = new Commandline(); cmd.setExecutable(executable); if (mavenHome != null) { cmd.addEnvironment("M2_HOME", mavenHome); } if (envVars != null) { for (Object o : envVars.keySet()) { String key = (String) o; cmd.addEnvironment(key, (String) envVars.get(key)); } } if (envVars == null || envVars.get("JAVA_HOME") == null) { cmd.addEnvironment("JAVA_HOME", System.getProperty("java.home")); } cmd.addEnvironment("MAVEN_TERMINATE_CMD", "on"); cmd.setWorkingDirectory(workingDirectory); for (String cliArg : cliArgs) { cmd.createArg().setValue(cliArg); } Writer logWriter = new FileWriter(logFile); StreamConsumer out = new WriterStreamConsumer(logWriter); StreamConsumer err = new WriterStreamConsumer(logWriter); try { return CommandLineUtils.executeCommandLine(cmd, out, err); } catch (CommandLineException e) { throw new LauncherException("Failed to run Maven: " + e.getMessage() + "\n" + cmd, e); } finally { logWriter.close(); } } public int run(String[] cliArgs, String workingDirectory, File logFile) throws IOException, LauncherException { return run(cliArgs, envVars, workingDirectory, logFile); } public String getMavenVersion() throws IOException, LauncherException { File logFile; try { logFile = File.createTempFile("maven", "log"); } catch (IOException e) { throw new LauncherException("Error creating temp file", e); } try { // disable EMMA runtime controller port allocation, should be harmless if EMMA is not used Map<String, String> envVars = Collections.singletonMap("MAVEN_OPTS", "-Demma.rt.control=false"); run(new String[] { "--version" }, envVars, null, logFile); } catch (IOException e) { throw new LauncherException("IO Error communicating with commandline " + e.toString(), e); } List<String> logLines = FileUtils.loadFile(logFile); //noinspection ResultOfMethodCallIgnored logFile.delete(); String version = extractMavenVersion(logLines); if (version == null) { version = extractTeslaVersion(logLines); } if (version == null) { throw new LauncherException("Illegal maven output: String 'Maven version: ' not found in the following output:\n" + StringUtils.join(logLines.iterator(), "\n")); } else { return version; } } private static final Pattern MAVEN_VERSION = Pattern.compile("(?i).*Maven [^0-9]*([0-9]\\S*).*"); static String extractMavenVersion(List<String> logLines) { String version = null; for (Iterator<String> it = logLines.iterator(); version == null && it.hasNext();) { String line = (String) it.next(); Matcher m = MAVEN_VERSION.matcher(line); if (m.matches()) { version = m.group(1); } } return version; } static String extractTeslaVersion(List<String> logLines) { String version = null; final Pattern MAVEN_VERSION = Pattern.compile("(?i).*Tesla [^0-9]*([0-9]\\S*).*"); for (Iterator<String> it = logLines.iterator(); version == null && it.hasNext();) { String line = (String) it.next(); Matcher m = MAVEN_VERSION.matcher(line); if (m.matches()) { version = m.group(1); } } return version; } }
true
752110be39617ad3d09dcfe7905e61206574d4c7
Java
kan86197/pa1
/src/converter/Length.java
UTF-8
453
3.265625
3
[]
no_license
package converter; public enum Length implements Unit{ METER("Meter", 1), KILOMETER("Kilometer", 1000.0), CENTIMETER("Centimeter", 0.01), MILE("Mile", 1609.344), FOOT("Foot", 0.3048), WA("Wa", 2) ; private String name; private double value; private Length(String name, double value){ this.name = name; this.value = value; } public double getValue(){ return value; } public String toString(){ return name; } }
true
cf7d44f3f4f62ad0a9cf783786007da450a3cd4d
Java
krizzikuse/MTe
/app-core/src/main/java/com/mercury/platform/core/utils/interceptor/plain/FrenchIncLocalizationMatcher.java
UTF-8
495
2.078125
2
[ "MIT" ]
permissive
package com.mercury.platform.core.utils.interceptor.plain; import org.apache.commons.lang3.StringUtils; public class FrenchIncLocalizationMatcher extends LocalizationMatcher { @Override public boolean isSuitableFor(String message) { return message.contains("@De"); } @Override public boolean isIncoming() { return true; } @Override public String trimString(String message) { return StringUtils.substringAfter(message, "@De "); } }
true
016c7d6e65cee5d44790f9911e902afcf580894b
Java
jskd/ProtIntTP1
/documentation/TP/TP3/Serveur.java
UTF-8
1,099
3.546875
4
[]
no_license
import java.net.*; import java.io.*; import java.util.Random; public class Serveur{ public static void main(String args[]){ try{ ServerSocket serv = new ServerSocket(3434); Random rand = new Random(); int number = rand.nextInt(100)+1; Socket socket = serv.accept(); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream())); pw.print("Entrez un nombre entre 1-100 :\n"); pw.flush(); while(true){ String mess = br.readLine(); if(mess == null) break; try{ int test = Integer.parseInt(mess); if(test > number){ pw.print("-\n"); pw.flush(); } else if(test < number){ pw.print("+\n"); pw.flush(); } else{ pw.print("=\n"); pw.flush(); break; } }catch (Exception e){ pw.print("Ce n'est pas un nombre.\n"); pw.flush(); } } br.close(); pw.close(); socket.close(); }catch (Exception e){ System.out.println(e); } } }
true
e256e6cc37bef09b9d6919721e5bd0d57bbb5356
Java
avirupdutta/30-days-of-Java
/src/LeetCode/Solution.java
UTF-8
5,120
3.375
3
[]
no_license
package LeetCode; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Solution{ public int fib(int N){ if (N == 1) return 1; else if (N == 2) return 1; else if (N <= 0) return 0; return fib(N-1)+fib(N-2); } public int numJewelsInStones ( String jewels, String stones ) { int counter = 0; for (int i = 0; i < jewels.length(); i++){ for (int j = 0; j < stones.length(); j++){ if (stones.charAt(j) == jewels.charAt(i)) counter++; } } return counter; } public String longestWord(String[] words) { String output = ""; for (String word: words){ if (word.length() > output.length()) output = word; } return output; } private int[] reverseArray(int arr[]){ int newArr[] = new int[arr.length]; for (int i=arr.length-1, j=0; i>=0; i--, j++) newArr[j] = arr[i]; return newArr; } public int[][] flipAndInvertImage(int[][] A) { // flipping horizontally for (int i = 0; i < A.length; i++) A[i] = reverseArray(A[i]); // Inverting it for (int i = 0; i < A.length; i++){ for (int j = 0; j < A[i].length; j++){ if (A[i][j] == 1) A[i][j] = 0; else A[i][j] = 1; } } return A; } public int[] sortArrayByParity(int[] A) { int output[] = new int[A.length]; int lastIndex = 0; // pushing all the even elements first for (int i = 0; i < A.length; i++){ if (A[i] % 2 == 0) output[lastIndex++] = A[i]; } // finally pushing all the odd elements for (int i = 0; i < A.length; i++){ if (A[i] % 2 != 0) output[lastIndex++] = A[i]; } return output; } public int repeatedNTimes(int[] A) { ArrayList<Integer> arr = new ArrayList<Integer>(); for (int num: A){ if (arr.contains(num)) return num; arr.add(num); } return -1; } public String defangIPaddr(String address) { String output = ""; for (int i = 0; i < address.length(); i++){ char currChar = address.charAt(i); if ( currChar == '.'){ output += "[.]"; }else{ output += currChar; } } return output; } private int countDigits(int num){ int counter = 0; while (num > 0){ num = num / 10; counter++; } return counter; } private boolean checkSelfDivision(int num){ boolean output = false; int numCopy = num; while (num > 0){ int lastDigit = num % 10; if (lastDigit == 0 || numCopy % lastDigit != 0){ output = false; break; } else{ output = true; } num = num / 10; } return output; } public List<Integer> selfDividingNumbers( int left, int right) { List<Integer> output = new ArrayList<Integer>(); for (int i = left; i <= right ; i++){ if (checkSelfDivision(i)) output.add(i); } return output; } public boolean checkPerfectNumber(int num) { int counter = 0; if (num == counter) return true; for (int i = 1; i <= num / 2; i++){ if ( num % i == 0 ) counter += i; } System.out.println(counter); return num == counter; } public int integerReplacement(int n) { // Buggy method // Link to the problem - https://leetcode.com/problems/integer-replacement/ int counter = 0; while (n > 1){ System.out.print(n+" "); if (n % 2 == 0) n /= 2; else n = (n + 1); counter++; } return counter; } public int hammingDistance(int x, int y) { int counter = 0; String binX = Integer.toBinaryString(x); String binY = Integer.toBinaryString(y); int binXlen = binX.length(); int binYlen = binY.length(); if (binXlen > binYlen){ int diff = binXlen - binYlen; for (int i = 0; i < diff; i++){ binY = "0" + binY; } binYlen = binY.length(); } else if (binYlen > binXlen){ int diff = binYlen - binXlen; for (int i = 0; i < diff; i++){ binX = "0" + binX; } binXlen = binX.length(); } for (int i = 0; i < binXlen; i++){ if (binX.charAt(i) != binY.charAt(i)){ counter++; } } return counter; } }
true
32934c6889e9d4c1db83d1ac1ccf22318753a615
Java
0Zix0/PixelEngine
/PixelEngine/src/com/engine/Colors.java
UTF-8
698
2.46875
2
[]
no_license
package com.engine; public class Colors { public static final int BLACK = 0x000000; public static final int WHITE = 0xFFFFFF; public static final int RED = 0xFF0000; public static final int GREEN = 0x00FF00; public static final int BLUE = 0x0000FF; public static final int YELLOW = 0xFFFF00; public static final int CYAN = 0x00FFFF; public static final int PINK = 0xFF00FF; public static final int DARK_RED = 0x7F0000; public static final int DARK_GREEN = 0x00FF00; public static final int DARK_BLUE = 0x00007F; public static final int DARK_YELLOW = 0x7F7F00; public static final int DARK_CYAN = 0x007F7F; public static final int DARK_PINK = 0x7F007F; }
true
c26f4d7d0189c29d871aaf0b67195eabb83bdec6
Java
rathoreamrsingh/InventoryManagementSystem
/src/com/inventory/core/ApparelCategory.java
UTF-8
1,519
2.75
3
[]
no_license
/** * */ package com.inventory.core; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Enumeration; import java.util.Properties; /** * @author amar * */ public abstract class ApparelCategory extends ApparelImpl { private Apparel apparel; /** * @param name * @param code */ public ApparelCategory(String name, String code) { super(name, code); } /** * @return the apparel */ public Apparel getApparel() { return apparel; } /** * @param apparel * the apparel to set */ public void setApparel(Apparel apparel) { this.apparel = apparel; } @Override public float getDiscount() { float discount = 0.0f; try { File file = new File("discountList.properties"); FileInputStream fileInput = new FileInputStream(file); Properties properties = new Properties(); properties.load(fileInput); fileInput.close(); Enumeration enuKeys = properties.keys(); while (enuKeys.hasMoreElements()) { String key = (String) enuKeys.nextElement(); String value = properties.getProperty(key); if (key.equalsIgnoreCase(getCode())) { discount = Float.parseFloat(value); break; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } return getApparel().getDiscount() > discount ? getApparel().getDiscount() : discount; } }
true
9b8f7ad860a395a4eaa3673ab9883af34169db04
Java
Diba15/TugasPerpustakaan
/src/Main.java
UTF-8
14,414
2.9375
3
[]
no_license
import java.util.*; public class Main { static OpenLibrary openLibrary = new OpenLibrary(); static Scanner scanner = new Scanner(System.in); static int pilih; public static void add() { String jenis, status, namaKoleksi, penerbit, tangter; int noKoleksi, pilihStatus; System.out.println("Data Apa yang ingin anda tambahkan : "); System.out.println("1.Buku\t2.Majalah\n3.Koran\t4.Cakram Digital"); pilih = scanner.nextInt(); switch (pilih) { case 1: jenis = "Buku"; System.out.print("Masukkan Nomor Koleksi : "); noKoleksi = scanner.nextInt(); System.out.print("Masukkan Judul : "); namaKoleksi = scanner.next(); System.out.print("Masukkan Pihak Penerbit : "); penerbit = scanner.next(); System.out.print("Masukkan Tanggal Terbit : "); tangter = scanner.next(); System.out.println("Status[1.Ada\t2.Rusak\t3.Hilang]"); System.out.print("Pilih : "); pilihStatus = scanner.nextInt(); switch (pilihStatus) { case 1: status = "Ada"; break; case 2: status = "Rusak"; break; case 3: status = "Hilang"; break; default: status = "Koleksi"; break; } System.out.print("Masukkan Pengarang : "); String pengarang = scanner.next(); System.out.print("Masukkan ISSN : "); String issn = scanner.next(); System.out.print("Masukkan ISBN : "); String isbn = scanner.next(); System.out.print("Masukkan DOI : "); String doi = scanner.next(); System.out.print("Masukkan Arxiv ID : "); String arxivId = scanner.next(); System.out.print("Masukkan Tahun Masuk : "); int tahunMasuk = scanner.nextInt(); openLibrary.addKoleksi(new Buku(noKoleksi, namaKoleksi, penerbit, tangter, jenis, status, pengarang, issn, isbn, doi, arxivId, tahunMasuk)); break; case 2: jenis = "Majalah"; System.out.print("Masukkan Nomor Koleksi : "); noKoleksi = scanner.nextInt(); System.out.print("Masukkan Judul : "); namaKoleksi = scanner.next(); System.out.print("Masukkan Pihak Penerbit : "); penerbit = scanner.next(); System.out.print("Masukkan Tanggal Terbit : "); tangter = scanner.next(); System.out.println("Status[1.Ada\t2.Rusak\t3.Hilang]"); System.out.print("Pilih : "); pilihStatus = scanner.nextInt(); switch (pilihStatus) { case 1: status = "Ada"; break; case 2: status = "Rusak"; break; case 3: status = "Hilang"; break; default: status = "Koleksi"; break; } System.out.print("Masukkan No Edisi : "); int noEdisi = scanner.nextInt(); System.out.println("Jenis Terbit[1.Mingguan\t2.Bulanan]"); System.out.print("Pilih : "); int jenisTerbit = scanner.nextInt(); String jenisMajalah; switch (jenisTerbit) { case 1: jenisMajalah = "Mingguan"; break; case 2: jenisMajalah = "Bulanan"; break; default: jenisMajalah = ""; break; } openLibrary.addKoleksi(new Majalah(noKoleksi, namaKoleksi, penerbit, tangter, jenis, status, noEdisi, jenisMajalah)); break; case 3: jenis = "Koran"; System.out.print("Masukkan Nomor Koleksi : "); noKoleksi = scanner.nextInt(); System.out.print("Masukkan Judul : "); namaKoleksi = scanner.next(); System.out.print("Masukkan Pihak Penerbit : "); penerbit = scanner.next(); System.out.print("Masukkan Tanggal Terbit : "); tangter = scanner.next(); System.out.println("Status[1.Ada\t2.Rusak\t3.Hilang]"); System.out.print("Pilih : "); pilihStatus = scanner.nextInt(); switch (pilihStatus) { case 1: status = "Ada"; break; case 2: status = "Rusak"; break; case 3: status = "Hilang"; break; default: status = "Koleksi"; break; } System.out.println("Jenis Terbit[1.Harian\t2.Mingguan]"); System.out.print("Pilih : "); int pilihJenis = scanner.nextInt(); String jenisKoran = "Harian"; switch (pilihJenis) { case 1: jenisKoran = "Harian"; break; case 2: jenisKoran = "Mingguan"; break; } openLibrary.addKoleksi(new Koran(noKoleksi, namaKoleksi, penerbit, tangter, jenis, status, jenisKoran)); break; case 4: jenis = "Cakram Digital"; System.out.print("Masukkan Nomor Koleksi : "); noKoleksi = scanner.nextInt(); System.out.print("Masukkan Judul : "); namaKoleksi = scanner.next(); System.out.print("Masukkan Pihak Penerbit : "); penerbit = scanner.next(); System.out.print("Masukkan Tanggal Terbit : "); tangter = scanner.next(); System.out.println("Status[1.Ada\t2.Rusak\t3.Hilang]"); System.out.print("Pilih : "); pilihStatus = scanner.nextInt(); switch (pilihStatus) { case 1: status = "Ada"; break; case 2: status = "Rusak"; break; case 3: status = "Hilang"; break; default: status = "Koleksi"; break; } System.out.println("Jenis Media[1.Biasa\t2.Bluray\t3.CD RIP]"); System.out.print("Pilih : "); int pilihMedia = scanner.nextInt(); String jenisMedia = "Biasa"; switch (pilihMedia) { case 1: jenisMedia = "Biasa"; break; case 2: jenisMedia = "Bluray"; break; case 3: jenisMedia = "CD RIP"; break; } openLibrary.addKoleksi(new CakramDigital(noKoleksi, namaKoleksi, penerbit, tangter, jenis, status, jenisMedia)); break; } } public static void displayKoleksi() { char urut; int pilihUrut; System.out.println("Tampilkan"); System.out.println("1.Buku\t2.Majalah\n3.Koran\t4.Cakram Digital"); System.out.print("Pilih : "); pilih = scanner.nextInt(); switch (pilih) { case 1: System.out.print("Apakah Ingin diurutkan?[y/t] : "); urut = scanner.next().charAt(0); if (urut == 'y' || urut == 'Y') { System.out.println("Ingin diurutkan Berdasarkan?\n1.Title\t2.No Koleksi"); System.out.print("Pilih : "); pilihUrut = scanner.nextInt(); switch (pilihUrut) { case 1: openLibrary.compare(1); openLibrary.displayBuku(); break; case 2: openLibrary.compare(2); openLibrary.displayBuku(); break; } } else if (urut == 't' || urut == 'T') { openLibrary.displayBuku(); } break; case 2: System.out.print("Apakah Ingin diurutkan?[y/t] : "); urut = scanner.next().charAt(0); if (urut == 'y' || urut == 'Y') { System.out.println("Ingin diurutkan Berdasarkan?\n1.Title\t2.No Koleksi"); System.out.print("Pilih : "); pilihUrut = scanner.nextInt(); switch (pilihUrut) { case 1: openLibrary.compare(1); openLibrary.displayMajalah(); break; case 2: openLibrary.compare(2); openLibrary.displayMajalah(); break; } } else if (urut == 't' || urut == 'T') { openLibrary.displayMajalah(); } break; case 3: System.out.print("Apakah Ingin diurutkan?[y/t] : "); urut = scanner.next().charAt(0); if (urut == 'y' || urut == 'Y') { System.out.println("Ingin diurutkan Berdasarkan?\n1.Title\t2.No Koleksi"); System.out.print("Pilih : "); pilihUrut = scanner.nextInt(); switch (pilihUrut) { case 1: openLibrary.compare(1); openLibrary.displayKoran(); break; case 2: openLibrary.compare(2); openLibrary.displayKoran(); break; } } else if (urut == 't' || urut == 'T') { openLibrary.displayKoran(); } break; case 4: System.out.print("Apakah Ingin diurutkan?[y/t] : "); urut = scanner.next().charAt(0); if (urut == 'y' || urut == 'Y') { System.out.println("Ingin diurutkan Berdasarkan?\n1.Title\t2.No Koleksi"); System.out.print("Pilih : "); pilihUrut = scanner.nextInt(); switch (pilihUrut) { case 1: openLibrary.compare(1); openLibrary.displayCakram(); break; case 2: openLibrary.compare(2); openLibrary.displayCakram(); break; } } else if (urut == 't' || urut == 'T') { openLibrary.displayCakram(); } break; default: System.out.println("Pilih yang ada Pada Pilihan"); break; } System.out.println(); } public static void runThis() { do { System.out.println("===== Open Library ====="); System.out.println("1.Tambah Koleksi\n2.Display Koleksi\n3.Exit"); System.out.print("Pilih : "); pilih = scanner.nextInt(); switch (pilih) { case 1: add(); break; case 2: displayKoleksi(); break; case 3: System.out.println("Terima Kasih!"); System.exit(1); break; default: System.out.println("Pilih yang ada pada pilihan!"); break; } } while (true); } public static void dummy() { openLibrary.addKoleksi(new Buku(1, "Petualangan Dimas", "BIN", "10 Maret 2001", "Buku", "Ada", "Dimas", "A0192", "A1029", "A82828", "PQO102", 2001)); openLibrary.addKoleksi(new Buku(5, "Mau Hidup Sehat", "BIN", "10 Maret 2001", "Buku", "Ada", "Dimas", "A0192", "A1029", "A82828", "PQO102", 2001)); openLibrary.addKoleksi(new Majalah(2,"Baju Baru", "SoKrenz","20 Maret 2020","Majalah","Ada", 10,"Mingguan")); openLibrary.addKoleksi(new Majalah(6,"Celana Baru", "SoKrenz","20 Maret 2020","Majalah","Ada", 10,"Mingguan")); openLibrary.addKoleksi(new Koran(3, "Kelakuan Tikus", "Bang Alex", "28 Maret 2020", "Koran", "Ada", "Harian")); openLibrary.addKoleksi(new Koran(7, "Corona Musnah", "Bang Alex", "28 Maret 2021", "Koran", "Ada", "Harian")); openLibrary.addKoleksi(new CakramDigital(4, "Si Bolang", "Trens 9", "30 Maret 2020", "Cakram Digital", "Rusak", "Bluray")); openLibrary.addKoleksi(new CakramDigital(8, "Narto", "Gloubal", "30 Maret 2020", "Cakram Digital", "Ada", "Bluray")); } public static void main(String[] args) { dummy(); runThis(); } }
true
e176f08323182c37ff8b65831a79632b578b3a99
Java
ChizhikovAlexey/LightUtilitiesBot
/src/main/java/chizhikov/utilitiesbot/bot/commands/Help.java
UTF-8
2,472
2.484375
2
[]
no_license
package chizhikov.utilitiesbot.bot.commands; import chizhikov.utilitiesbot.bot.KeyboardResolver; import chizhikov.utilitiesbot.bot.userdata.ChatState; import chizhikov.utilitiesbot.bot.userdata.ChatsManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.objects.Chat; import org.telegram.telegrambots.meta.api.objects.User; import org.telegram.telegrambots.meta.bots.AbsSender; @Component public class Help extends AbstractCommand { private final KeyboardResolver keyboardResolver; @Autowired public Help(ChatsManager chatsManager, KeyboardResolver keyboardResolver) { super("help", "начало работы", chatsManager); this.keyboardResolver = keyboardResolver; } @Override public void execute(AbsSender absSender, User user, Chat chat, String[] strings) { if (chatsManager.getState(chat) == ChatState.MAIN) { String help = """ Бот предназначен для ввода показаний счётчиков и генерации отчётов. Используйте кнопки для работы с ботом. Также доступны команды: /cancel – отменяет текущую команду.\ Например, если вы по ошибке начали вводить новые данные счётчиков или тарифа.\ Также возвращает к главному меню. /help – вызывает этот текст с помощью. /start – начать работу с ботом, если она ещё не начата. """; sendMessage( absSender, SendMessage. builder(). text(help). chatId(chat.getId().toString()). replyMarkup(keyboardResolver.getKeyboard(ChatState.MAIN)). build() ); } else { sendWrongStateAnswer(absSender, chat); } } }
true
edbdfbef9155bf66997373d6a8063751e07685a7
Java
DevSnox/SmoothTimber
/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Reflections.java
UTF-8
1,224
3.0625
3
[]
no_license
package com.syntaxphoenix.syntaxapi.utils.java; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Reflections { public static boolean hasSameArguments(Class<?>[] compare1, Class<?>[] compare2) { if (compare1.length == 0 && compare2.length == 0) { return true; } else if (compare1.length != compare2.length) { return false; } for(Class<?> arg1 : compare1) { boolean found = false; for(Class<?> arg2 : compare2) { if(arg2.isAssignableFrom(arg1)) { found = true; break; } } if(!found) { return false; } } return true; } /* * */ public static Object execute(Object source, Method method, Object... arguments) { if (method != null) { boolean access; if (!(access = method.isAccessible())) { method.setAccessible(true); } try { return method.invoke(source, arguments); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { if (!access) { method.setAccessible(access); } e.printStackTrace(); } if (!access) { method.setAccessible(access); } } return null; } }
true
dffc2c924c9b5e0c6f6771e949d70e13643510e2
Java
braveyly/fangdongliqi
/code/src/main/java/com/tvt/fdlq/domain/Property.java
UTF-8
3,546
2.296875
2
[]
no_license
package com.tvt.fdlq.domain; public class Property extends PropertyKey { /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column property.name * * @mbg.generated */ private String name; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column property.address * * @mbg.generated */ private String address; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column property.type * * @mbg.generated */ private Integer type; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column property.bankAccount * * @mbg.generated */ private String bankaccount; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column property.name * * @return the value of property.name * * @mbg.generated */ public String getName() { return name; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column property.name * * @param name the value for property.name * * @mbg.generated */ public void setName(String name) { this.name = name == null ? null : name.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column property.address * * @return the value of property.address * * @mbg.generated */ public String getAddress() { return address; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column property.address * * @param address the value for property.address * * @mbg.generated */ public void setAddress(String address) { this.address = address == null ? null : address.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column property.type * * @return the value of property.type * * @mbg.generated */ public Integer getType() { return type; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column property.type * * @param type the value for property.type * * @mbg.generated */ public void setType(Integer type) { this.type = type; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column property.bankAccount * * @return the value of property.bankAccount * * @mbg.generated */ public String getBankaccount() { return bankaccount; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column property.bankAccount * * @param bankaccount the value for property.bankAccount * * @mbg.generated */ public void setBankaccount(String bankaccount) { this.bankaccount = bankaccount == null ? null : bankaccount.trim(); } }
true
2f40659a3f21e1b8cdbcf7384d5ef0a560eb530c
Java
Aksh12/Learningconcepts
/testprojectAutomationTool/fittrapplication/src/test/java/utilities/CommonUtils.java
UTF-8
2,801
1.9375
2
[]
no_license
package utilities; import java.io.FileInputStream; import java.io.IOException; import java.net.URL; import java.util.Properties; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.openqa.selenium.remote.DesiredCapabilities; import io.appium.java_client.remote.AndroidMobileCapabilityType; import io.appium.java_client.remote.MobileCapabilityType; import io.appium.java_client.remote.MobilePlatform; import io.testproject.sdk.drivers.TestProjectCapabilityType; import io.testproject.sdk.drivers.android.AndroidDriver; import io.testproject.sdk.internal.exceptions.AgentConnectException; import io.testproject.sdk.internal.exceptions.InvalidTokenException; import io.testproject.sdk.internal.exceptions.ObsoleteVersionException; public class CommonUtils { private static AndroidDriver driver; private static int IMPLICIT_WAIT; private static int EXPLICIT_WAIT; private static String PLATFORM_NAME; private static String PLATFORM_VERSION; private static String APPIUM_PORT_NUMBER; private static String DUT_UDID; private static String APP_PACKAGE; private static String APP_ACTIVITY; private static URL serverUrl; private static DesiredCapabilities capabilities = new DesiredCapabilities(); public static void loadConfig(String loadConfigFile) throws IOException { FileInputStream fis = new FileInputStream( System.getProperty("user.dir") + "\\src\\test\\resources\\properties\\" + loadConfigFile); Properties pro = new Properties(); pro.load(fis); IMPLICIT_WAIT = Integer.parseInt(pro.getProperty("implicit.wait")); EXPLICIT_WAIT = Integer.parseInt(pro.getProperty("explicit.wait")); DUT_UDID = pro.getProperty("DUT_UDID"); PLATFORM_NAME = pro.getProperty("platform.name"); PLATFORM_VERSION = pro.getProperty("platform.version"); APPIUM_PORT_NUMBER = pro.getProperty("appium.port"); APP_PACKAGE = pro.getProperty("base.package"); APP_ACTIVITY = pro.getProperty("activity.package"); } public static void loadCapabilities() { capabilities.setCapability(MobileCapabilityType.UDID, DUT_UDID); capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, MobilePlatform.ANDROID); capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, PLATFORM_VERSION); capabilities.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, APP_PACKAGE); capabilities.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, APP_ACTIVITY); // capabilities.setCapability(TestProjectCapabilityType., value); } public static AndroidDriver getDriver() throws IOException, AgentConnectException, InvalidTokenException, ObsoleteVersionException { driver = new AndroidDriver("cqLuXpjEAm_qFruu2dEXQl7WEQi6A80XbiAc5Zaesis1", capabilities, "Fittr Application"); driver.report().disableReports(true); return driver; } }
true
9f9f51188f17edbf3db8a1439cbc2d3c08a580ca
Java
wuwushijunru/snack-app
/app/src/main/java/com/shuyue/snack/ui/snack/SnackViewModel.java
UTF-8
436
1.890625
2
[]
no_license
package com.shuyue.snack.ui.snack; import androidx.lifecycle.LiveData; import androidx.lifecycle.MediatorLiveData; import androidx.lifecycle.ViewModel; public class SnackViewModel extends ViewModel { private MediatorLiveData<String> mText; public SnackViewModel() { mText = new MediatorLiveData<>(); mText.setValue("点单页面"); } public LiveData<String> getText() { return mText; } }
true
6b1fb2cc199bfd787ea080362bf65d0ff5fca591
Java
dmzadorin/clientService
/src/main/java/ru/dmzadorin/clientservice/net/request/RequestDispatcher.java
UTF-8
500
2.234375
2
[]
no_license
package ru.dmzadorin.clientservice.net.request; import ru.dmzadorin.clientservice.model.response.ResponseType; import java.io.InputStream; /** * Created by Dmitry Zadorin on 07.03.2018 */ public interface RequestDispatcher { /** * Parses request body into xml RequestType and dispatches that request to appropriate controller * * @param requestBody body of the request * @return response generated by controller */ ResponseType handleRequest(InputStream requestBody); }
true
1b6ac3cf2254403fd72ab517e897a8f37f1deef6
Java
OlBiMaCooJam/heaven-games
/src/main/java/com/olbimacoojam/heaven/mafia/MafiaResult.java
UTF-8
95
1.5625
2
[]
no_license
package com.olbimacoojam.heaven.mafia; public enum MafiaResult { MAFIA_WIN, CITIZEN_WIN }
true
d58d8f855427f392b33edca4a5283d9ebfcbdb4e
Java
adrics97/api-rest-miyofuturo
/src/main/java/es/uv/api/miyofuturo/services/TestUsuarioService.java
UTF-8
829
1.921875
2
[]
no_license
package es.uv.api.miyofuturo.services; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import es.uv.api.miyofuturo.entities.TestUsuario; import es.uv.api.miyofuturo.entities.Usuario; import es.uv.api.miyofuturo.repositories.TestUsuarioRepository; import es.uv.api.miyofuturo.repositories.UsuariosRepository; @Service public class TestUsuarioService { @Autowired private TestUsuarioRepository testUsuRepo; @Autowired private UsuariosRepository usuariosRepo; public TestUsuario createTestUsuario(TestUsuario testUsu) { return testUsuRepo.save(testUsu); } public List<TestUsuario> getTestByIdusuario(int idusuario) { Usuario u = usuariosRepo.findById(idusuario).orElse(null); return testUsuRepo.findByIdusuario(u); } }
true
40591c03a5561f5fddf43fcc572d361d574f0afb
Java
korinneramcharitar/Ramcharitar-cop3330-ex05
/src/main/java/base/base.java
UTF-8
1,482
4.09375
4
[]
no_license
/* * UCF COP3330 Summer 2021 Assignment 1 Solution * Copyright 2021 Korinne Ramcharitar */ package base; //You’ll often write programs that deal with numbers. And depending on the programming language you use, you’ll have to convert the inputs you get to numerical data types. //Write a program that prompts for two numbers. Print the sum, difference, product, and quotient of those numbers as shown in the example output: //What is the first number? 10 //What is the second number? 5 //10 + 5 = 15 //10 - 5 = 5 //10 * 5 = 50 //10 / 5 = 2 //Values coming from users will be strings. Ensure that you convert these values to numbers before doing the math. //Keep the inputs and outputs separate from the numerical conversions and other processing. //Generate a single output statement with line breaks in the appropriate spots. import java.util.Scanner; public class base { public static void main (String[] args) { Scanner input = new Scanner(System.in); System.out.println("What is the first number?"); String num1 = input.nextLine(); System.out.println("What is the second number?"); String num2 = input.nextLine(); int a = Integer.parseInt(num1); int b = Integer.parseInt(num2); System.out.println( +a+ " + " +b+ " = " + (a + b)); System.out.println(+a+ " - " +b+ " = " + (a - b)); System.out.println(+a+ " * " +b+ " = " + (a * b)); System.out.println(+a+ " / " +b+ " = " + (a / b)); } }
true
2949dbf48c61b80cd1f2e7fefab29c4b3a40a03f
Java
Zajaczekk/ProjektIO
/app/src/main/java/com/trener/activity/DodajCwiczenieActivity.java
UTF-8
4,569
2.015625
2
[]
no_license
package com.trener.activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.android.volley.Request.Method; import com.android.volley.RequestQueue; import com.android.volley.toolbox.StringRequest; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.Volley; import com.trener.app.AppConfig; import java.util.HashMap; import java.util.Map; import info.androidhive.loginandregistration.R; public class DodajCwiczenieActivity extends AppCompatActivity { Button btnDodaj; EditText etNazwaCwiczenia, etOpis; Spinner spPartia; CheckBox ciezar, czas, dystans, powt, serie; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dodaj_cwiczenie); btnDodaj = (Button)findViewById(R.id.btnDodaj); etNazwaCwiczenia = (EditText)findViewById(R.id.etNazwaCwiczeniaE); etOpis = (EditText)findViewById(R.id.etOpisE); spPartia = (Spinner)findViewById(R.id.spPartiaE); ciezar = (CheckBox) findViewById(R.id.chbCiezarE); czas = (CheckBox) findViewById(R.id.chbCzasE); dystans = (CheckBox)findViewById(R.id.chbDystansE); powt = (CheckBox) findViewById(R.id.chbPowtorzeniaE); serie = (CheckBox) findViewById(R.id.chbSerieE); btnDodaj.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { RequestQueue queue = Volley.newRequestQueue(getApplicationContext()); StringRequest stringRequest = new StringRequest(Method.POST, AppConfig.URL_ADD_EXERCISE, new Response.Listener<String>() { @Override public void onResponse(String response) { } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), "Błąd.", Toast.LENGTH_SHORT).show(); } }){ @Override protected Map<String, String> getParams() { // Posting params to register url Map<String, String> params = new HashMap<String, String>(); params.put("nazwa_c", etNazwaCwiczenia.getText().toString()); params.put("nazwa_p_fk", spPartia.getSelectedItem().toString()); params.put("informacja", etOpis.getText().toString()); params.put("id_cwiczenia_pk",String.valueOf(AppConfig.id_c)); AppConfig.id_c++; if (serie.isChecked()) { params.put("ilosc_serii", "1"); } else { params.put("ilosc_serii", "0"); } if (powt.isChecked()) { params.put("ilosc_pow", "1"); } else { params.put("ilosc_pow", "0"); } if (dystans.isChecked()) { params.put("dystans", "1"); } else { params.put("dystans", "0"); } if (ciezar.isChecked()) { params.put("ciezar", "1"); } else { params.put("ciezar", "0"); } if (czas.isChecked()) { params.put("czas", "1"); } else { params.put("czas", "0"); } params.put("id_uzytkownika_fk", "1"); return params; }}; queue.add(stringRequest); Intent i = new Intent(getApplicationContext(), CwiczeniaActivity.class); startActivity(i); finish(); } }); } @Override public void onBackPressed() { Intent i = new Intent(getApplicationContext(), CwiczeniaActivity.class); startActivity(i); finish(); } }
true
84c820b728d24efbda199c6d52c90b67cda8570a
Java
abhimaniac4/BLRS
/BRLS/testCases/library/entities/CalendarTest.java
UTF-8
1,162
2.34375
2
[]
no_license
package library.entities; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; import java.util.List; import java.util.Date; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import library.entities.ICalendar; @ExtendWith(MockitoExtension.class) class CalendarTest { @Mock IBook mockBook; @InjectMocks Calendar mockCalendar; @BeforeAll static void setUpBeforeClass() throws Exception { } @AfterAll static void tearDownAfterClass() throws Exception { } @BeforeEach void setUp() throws Exception { } @AfterEach void tearDown() throws Exception { } @Test void testGetDaysDifference() { //arrange mockCalendar.getDate(); //act mockCalendar.incrementDate(3); Date targetDate = mockCalendar.getDate(); //assert assertEquals(3,mockCalendar.getDaysDifference(targetDate)); } }
true
58384d603216af6badee1c2ab72485d8de569db5
Java
HafizullahQambari/MyBasicJavaProject
/src/com/synax/class26/PropertiesFileReading.java
UTF-8
1,233
3.421875
3
[]
no_license
package com.synax.class26; import java.io.FileInputStream; import java.io.IOException; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; public class PropertiesFileReading { public static void main(String[] args) throws IOException { //1. to read the file we need to have file String filePath="C:\\Users\\baria\\eclipse-workspace\\JavaBasics\\configs\\Examples.properties"; //2. bring object of fileInputStream FileInputStream fileInput=new FileInputStream(filePath); // to handle data from .properties file we need property class Properties prop=new Properties(); prop.load(fileInput); String name=prop.getProperty("name"); System.out.println(name); String lastName=prop.getProperty("lastName"); System.out.println(lastName); String city=prop.getProperty("city"); System.out.println(city); System.out.println("---------------------------------------------------"); // getting all keys from property file Set<Object> key=prop.keySet(); for(Object k:key) { System.out.println(k); } Set<Entry<Object, Object>> ob=prop.entrySet(); for(Entry<Object, Object> obj:ob) { System.out.println(obj.getKey()+" : "+obj.getValue()); } } }
true
0f684b2fa4b48e61bf32a821e4953c73d99f7f2c
Java
hugopte/ProjetJava
/model/src/main/java/element/mobile/Monster2.java
UTF-8
519
2.640625
3
[]
no_license
package element.mobile; import element.Permeability; /** * Element type Monster2 class * @author RICOUARTTANGUY * */ public class Monster2 extends Mobile { /** * Define permeability type, the sprite and the position of the element. * @param Y * define positionY of the element * @param X * define positionX of the element */ public Monster2(int Y, int X) { super("C:/Users/Hugo PETTE/git/ProjetJava/Sprite/monster_2.png" , Permeability.KILL, Y, X); } }
true
08c954116770d2d9e31c916a22221f0288e4325e
Java
ZoneMo/com.tencent.mm
/src/com/tencent/mm/plugin/sight/encode/a/b.java
UTF-8
1,143
1.5
2
[]
no_license
package com.tencent.mm.plugin.sight.encode.a; import android.hardware.Camera.PreviewCallback; public abstract interface b { public abstract void SA(); public abstract void a(a parama); public abstract void a(b paramb); public abstract void aI(String paramString1, String paramString2); public abstract boolean ajI(); public abstract long ajJ(); public abstract b ajK(); public abstract void ajL(); public abstract float ajM(); public abstract Camera.PreviewCallback ajN(); public abstract void b(a parama); public abstract void cancel(); public abstract int getDuration(); public abstract String getRecordPath(); public abstract void h(Runnable paramRunnable); public abstract void reset(); public static abstract interface a { public abstract void ajO(); public abstract void onError(); public abstract void onStart(); public abstract void onStop(); } public static enum b {} } /* Location: * Qualified Name: com.tencent.mm.plugin.sight.encode.a.b * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
9dc40032465307c926e3b9ca56abefc31eac0668
Java
megamott/Notes
/app/src/main/java/com/megamott/notes/view/adapter/NumberAdapter.java
UTF-8
4,527
2.59375
3
[]
no_license
package com.megamott.notes.view.adapter; import android.app.Activity; import android.graphics.Paint; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.SortedList; import com.megamott.notes.App; import com.megamott.notes.R; import com.megamott.notes.model.Note; import com.megamott.notes.view.screens.details.NoteDetailsActivity; import java.util.List; public class NumberAdapter extends RecyclerView.Adapter<NumberAdapter.NoteViewHolder> { private final SortedList<Note> content; public NumberAdapter() { this.content = new SortedList<>(Note.class, new SortedList.Callback<Note>() { @Override public int compare(Note o1, Note o2) { if (!o2.isDone() && o1.isDone()) { return 1; } if (o2.isDone() && !o1.isDone()) { return -1; } return (int) (o2.getTimestamp() - o1.getTimestamp()); } @Override public void onChanged(int position, int count) { notifyItemChanged(position, count); } @Override public boolean areContentsTheSame(Note oldItem, Note newItem) { return oldItem.equals(newItem); } @Override public boolean areItemsTheSame(Note item1, Note item2) { return item1.getUid() == item2.getUid(); } @Override public void onInserted(int position, int count) { notifyItemRangeInserted(position, count); } @Override public void onRemoved(int position, int count) { notifyItemRangeRemoved(position, count); } @Override public void onMoved(int fromPosition, int toPosition) { notifyItemMoved(fromPosition, toPosition); } }); } @NonNull @Override public NoteViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new NoteViewHolder( LayoutInflater.from(parent.getContext()).inflate(R.layout.number_in_sheet_layout, parent, false) ); } @Override public void onBindViewHolder(@NonNull NoteViewHolder holder, int position) { holder.bind(content.get(position)); } @Override public int getItemCount() { return content.size(); } public void setItems(List<Note> notes){ content.replaceAll(notes); } public static class NoteViewHolder extends RecyclerView.ViewHolder { private final TextView noteText; private final CheckBox completed; private Note note; boolean silentUpdate; public NoteViewHolder(@NonNull View itemView) { super(itemView); noteText = itemView.findViewById(R.id.number_element_text); completed = itemView.findViewById(R.id.number_element_completed); View delete = itemView.findViewById(R.id.number_element_delete); delete.setOnClickListener(v -> App.getInstance().getNoteDao().delete(note)); completed.setOnCheckedChangeListener((buttonView, isChecked) -> { if (!silentUpdate) { note.setDone(isChecked); App.getInstance().getNoteDao().update(note); } updateStrokeOut(); }); itemView.setOnClickListener(v -> NoteDetailsActivity.startActivity((Activity) itemView.getContext(), note)); } public void bind(Note note) { this.note = note; noteText.setText(note.getText()); updateStrokeOut(); silentUpdate = true; completed.setChecked(note.isDone()); silentUpdate = false; } private void updateStrokeOut() { if (note.isDone()) { // Set Flag to true. The text is crossed out. noteText.setPaintFlags(noteText.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); } else { // Set Flag to false. The text is not crossed out. noteText.setPaintFlags(noteText.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG); } } } }
true
9e56df6bdcc485ab0bd27a373bee0dedf545f498
Java
uweerakoon/managedisaster
/managedisaster-service/src/main/java/edu/usu/cs/mas/managedisaster/model/AgentModel.java
UTF-8
7,240
2.34375
2
[]
no_license
package edu.usu.cs.mas.managedisaster.model; import java.awt.Color; import java.util.List; import org.pojomatic.Pojomatic; import org.pojomatic.annotations.AutoProperty; import org.pojomatic.annotations.PojomaticPolicy; import org.pojomatic.annotations.Property; import edu.usu.cs.mas.managedisaster.common.AgentRole; import edu.usu.cs.mas.managedisaster.common.AgentStatus; import edu.usu.cs.mas.managedisaster.common.Chemical; import edu.usu.cs.mas.managedisaster.entity.CoalitionEntity; import edu.usu.cs.mas.managedisaster.entity.FireEntity; import edu.usu.cs.mas.managedisaster.entity.FireStationEntity; import sim.util.MutableInt2D; @AutoProperty public class AgentModel{ private Long id; private Integer x; private Integer y; private String name; private AgentStatus status; private AgentStatus initialStatus; private AgentRole role; private Color color; private double speed; private Long vicinity; private Chemical chemical; private Double chemicalAmount; private Double initialChemicalAmount; private Long minimumFireProximity; private Integer squirtPressure; private Integer fillingUpPressure; private MutableInt2D waterImpactCenter; private int waterImpactRadius; @Property(policy=PojomaticPolicy.NONE) private FireEntity fire; @Property(policy=PojomaticPolicy.NONE) private List<FireEntity> closeFires; @Property(policy=PojomaticPolicy.NONE) private CoalitionEntity coalition; @Property(policy=PojomaticPolicy.NONE) private FireStationEntity fireStation; public AgentModel(){ } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getX() { return x; } public void setX(Integer x) { this.x = x; } public Integer getY() { return y; } public void setY(Integer y) { this.y = y; } public String getName() { return name; } public void setName(String name) { this.name = name; } public AgentStatus getStatus() { return status; } public void setStatus(AgentStatus status) { this.status = status; } public AgentStatus getInitialStatus() { return initialStatus; } public void setInitialStatus(AgentStatus initialStatus) { this.initialStatus = initialStatus; } public AgentRole getRole() { return role; } public void setRole(AgentRole role) { this.role = role; } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } public double getSpeed() { return speed; } public void setSpeed(double speed) { this.speed = speed; } public AgentModel withId(Long id){ this.setId(id); return this; } public AgentModel withX(Integer x){ this.setX(x); return this; } public AgentModel withY(Integer y){ this.setY(y); return this; } public AgentModel withName(String name){ this.setName(name);; return this; } public AgentModel withStatus(AgentStatus status){ this.setStatus(status); return this; } public AgentModel withRole(AgentRole role){ this.setRole(role); return this; } public AgentModel with(Color color){ this.setColor(color); return this; } public AgentModel withSpeed(Double speed){ this.setSpeed(speed); return this; } public Long getVicinity() { return vicinity; } public void setVicinity(Long vicinity) { this.vicinity = vicinity; } public AgentModel withVicinity(Long vicinity) { setVicinity(vicinity); return this; } public Chemical getChemical() { return chemical; } public void setChemical(Chemical chemical) { this.chemical = chemical; } public AgentModel withChemical(Chemical chemical) { setChemical(chemical); return this; } public Double getChemicalAmount() { return chemicalAmount; } public void setChemicalAmount(Double chemicalAmount) { this.chemicalAmount = chemicalAmount; } public AgentModel withChemicalAmount(Double chemicalAmount) { setChemicalAmount(chemicalAmount); return this; } public Double getInitialChemicalAmount() { return initialChemicalAmount; } public void setInitialChemicalAmount(Double initialChemicalAmount) { this.initialChemicalAmount = initialChemicalAmount; } public AgentModel withInitialChemicalAmount(Double initialChemicalAmount) { setInitialChemicalAmount(initialChemicalAmount); return this; } public Long getMinimumFireProximity() { return minimumFireProximity; } public void setMinimumFireProximity(Long minimumFireProximity) { this.minimumFireProximity = minimumFireProximity; } public AgentModel withMinimumFireProximity(Long minimumFireProximity) { setMinimumFireProximity(minimumFireProximity); return this; } public Integer getSquirtPressure() { return squirtPressure; } public void setSquirtPressure(Integer squirtPressure) { this.squirtPressure = squirtPressure; } public AgentModel withSquirtPressure(Integer squirtPressure) { setSquirtPressure(squirtPressure); return this; } public Integer getFillingUpPressure() { return fillingUpPressure; } public void setFillingUpPressure(Integer fillingUpPressure) { this.fillingUpPressure = fillingUpPressure; } public AgentModel withFillingUpPressure(Integer fillingUpPressure) { setFillingUpPressure(fillingUpPressure); return this; } public MutableInt2D getWaterImpactCenter() { return waterImpactCenter; } public void setWaterImpactCenter(MutableInt2D waterImpactCenter) { this.waterImpactCenter = waterImpactCenter; } public int getWaterImpactRadius() { return waterImpactRadius; } public void setWaterImpactRadius(int waterImpactRadius) { this.waterImpactRadius = waterImpactRadius; } public FireEntity getFire() { return fire; } public void setFire(FireEntity fire) { this.fire = fire; } public AgentModel withFire(FireEntity fire) { setFire(fire); return this; } public List<FireEntity> getCloseFires() { return closeFires; } public void setCloseFires(List<FireEntity> closeFires) { this.closeFires = closeFires; } public AgentModel withCloseFires(List<FireEntity> closeFires) { setCloseFires(closeFires); return this; } public CoalitionEntity getCoalition() { return coalition; } public void setCoalition(CoalitionEntity coalition) { this.coalition = coalition; } public AgentModel withCoalition(CoalitionEntity coalition) { setCoalition(coalition); return this; } public FireStationEntity getFireStation() { return fireStation; } public void setFireStation(FireStationEntity fireStation) { this.fireStation = fireStation; } public AgentModel withFireStation(FireStationEntity fireStation) { setFireStation(fireStation); return this; } @Override public boolean equals(Object other){ return Pojomatic.equals(this, other); } @Override public String toString(){ return Pojomatic.toString(this); } @Override public int hashCode(){ return Pojomatic.hashCode(this); } }
true
bcf1e252c777990587fbd7dadc9516a81dbc3f77
Java
2010USFJava/CarlsonA
/Training Project 0/CarlsonJDBCBank/src/main/java/com/revature/driver/Main.java
UTF-8
494
2
2
[ "MIT" ]
permissive
package com.revature.driver; import java.sql.SQLException; import com.revature.Meta.DatabaseIO; import com.revature.ui.BankUI; public class Main { public static void main(String[] args) throws SQLException { // // CustAcctRelDaoImple custAct = new CustAcctRelDaoImple(); // ArrayList<Employee> emps =custAct.getEmployeeList(); // System.out.println(emps); BankUI bank=new BankUI(); DatabaseIO.loadDatabaseInfo(); // bank.addTestData(); bank.startPage(); System.exit(0); } }
true
a5f5a036bb3e268b81cfd38ea519870e1b93aa95
Java
futurexv2016/url-shortener
/url-shortener-backend/src/main/java/com/bondle/shortenurl/repository/ShortenUrlRepository.java
UTF-8
368
1.90625
2
[]
no_license
package com.bondle.shortenurl.repository; import com.bondle.shortenurl.entity.*; import org.springframework.data.jpa.repository.*; import org.springframework.stereotype.*; import java.util.*; @Repository public interface ShortenUrlRepository extends JpaRepository<Url, UUID>, JpaSpecificationExecutor<Url> { List<Url> findByShortenedUrl(String shortenedUrl); }
true
01f218c815c5a1ba794e19ff6bcb6a878bb50e9a
Java
rammaina01/urlshortener
/src/main/java/com/url/service/IUrlShortenerService.java
UTF-8
267
1.898438
2
[]
no_license
package com.url.service; import com.url.entity.UrlDetails; import com.url.model.Url; import java.util.List; public interface IUrlShortenerService { Url createShortenUrl(Url url); Url getShortenUrl(String url); List<UrlDetails> getAllShortenUrls(); }
true
73dca8ef1b58eae72b51533ab914701dc2a5eadb
Java
fahmi54321/ExpandableListView
/app/src/main/java/com/android/a33expandablelistview/MainActivity.java
UTF-8
1,878
2.546875
3
[]
no_license
package com.android.a33expandablelistview; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class MainActivity extends AppCompatActivity { private ExpandableListView listView; private ExpandableListAdapter listAdapter; private List<String> list; private HashMap<String,List<String>> hashMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ExpandableListView) findViewById(R.id.listview); initData(); listAdapter = new Adapter(this,list,hashMap); listView.setAdapter(listAdapter); } private void initData() { list = new ArrayList<>(); hashMap = new HashMap<>(); list.add("Kotlin"); list.add("Java"); list.add("Flutter"); list.add("Xamarin"); List<String> peminatKotlin = new ArrayList<>(); peminatKotlin.add("Fahmi Abdul Aziz"); List<String> peminatJava = new ArrayList<>(); peminatJava.add("Fahmi"); peminatJava.add("Abdul"); peminatJava.add("Aziz"); List<String> peminatFlutter = new ArrayList<>(); peminatFlutter.add("Fitria"); peminatFlutter.add("Alya"); peminatFlutter.add("Putri"); List<String> peminatXamarin = new ArrayList<>(); peminatXamarin.add("Muhammad"); peminatXamarin.add("Ega"); peminatXamarin.add("Dermawan"); hashMap.put(list.get(0),peminatKotlin); hashMap.put(list.get(1),peminatJava); hashMap.put(list.get(2),peminatFlutter); hashMap.put(list.get(3),peminatXamarin); } }
true
30c4a55a0adc64b4c5d60c915468502c856adc4a
Java
chessnerd/GoPass
/src/gopass/engine/Board.java
UTF-8
2,024
3.953125
4
[ "MIT" ]
permissive
package gopass.engine; import gopass.GoBoard; /** * The logic of a Go board * * @author Jason Mey * @version 1.0 */ public class Board implements GoBoard { /** Denotes an empty space on the board */ public static final int EMPTY = 0; /** Denotes a space with a black piece */ public static final int BLACK = 1; /** Denotes a space with a white piece */ public static final int WHITE = 2; /** The board */ private int[][] board; /** * Creates a standard 19x19 board */ public Board() { this(19, 19); } /** * Creates a board with x rows and y columns * * @param x the number of rows * @param y the number of columns */ public Board(int x, int y) { if (x <= 1) { x = 2; } if (y <= 1) { y = 2; } board = new int[x][y]; } /** * Places a piece on the board * * @param x the x-coordinate of the piece * @param y the y-coordinate of the piece * @param color the color of the piece */ public void place(int x, int y, int color) { board[x][y] = color; } /** * Gets the number of rows * * @return the number of rows */ public int getRowNum() { return board.length; } /** * Gets the number of columns * * @return the number of columns */ public int getColNum() { return board[0].length; } /** * Gets the color of the stone at the given coordinates * * @param x the x-coordinate of the stone * @param y the y-coordinate of the stone * @return the color of the stone */ public int getStoneAt(int x, int y) { return board[x][y]; } /** * Prints the board in its current state */ public void printBoard() { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { System.out.print(board[i][j] + " "); } System.out.println(); } System.out.println(); } }
true
c532e83d8b1e9641e8e780cafce8ceeae9bd8725
Java
PriNova/talos
/editor/src/com/talosvfx/talos/editor/nodes/widgets/ButtonWidget.java
UTF-8
990
2.359375
2
[ "Apache-2.0" ]
permissive
package com.talosvfx.talos.editor.nodes.widgets; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.JsonValue; import com.badlogic.gdx.utils.XmlReader; import com.talosvfx.talos.editor.widgets.ui.common.RoundedFlatButton; public class ButtonWidget extends AbstractWidget<Object> { private Label label; @Override public void init(Skin skin) { super.init(skin); label = new Label("", skin); RoundedFlatButton button = new RoundedFlatButton(skin, label); content.add(button).growX(); } @Override public void loadFromXML(XmlReader.Element element) { label.setText(element.getText()); } @Override public Object getValue() { return null; } @Override public void read(Json json, JsonValue jsonValue) { } @Override public void write(Json json, String name) { } }
true
5c9057d81478b70ea8ca85a2774865a4e003ca4f
Java
zacscoding/web-tracer
/tracer-agent/src/test/java/StringInvokeUtilTest.java
UTF-8
870
2
2
[]
no_license
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.zaccoding.tracer.util.StringInvokeUtil; import org.junit.Test; /** * @author zacconding * @Date 2018-01-21 * @GitHub : https://github.com/zacscoding */ public class StringInvokeUtilTest { @Test public void check() { assertTrue(StringInvokeUtil.isMatches("org.zaccoding", "org.zaccoding.test", StringInvokeUtil.InvokeType.startsWith, false)); assertFalse(StringInvokeUtil.isMatches(null, "org.zaccoding.test", StringInvokeUtil.InvokeType.startsWith, true)); assertFalse(StringInvokeUtil.isMatches( "org.zaccoding.test", null, StringInvokeUtil.InvokeType.startsWith, false)); assertTrue(StringInvokeUtil.isMatches("org.zaccoding.test", "test.org.zaccoding.test.app", StringInvokeUtil.InvokeType.contains, false)); } }
true
47735d225764f8b2e341b8a8da2dc666e734f290
Java
myFuckFuture/film
/ssmFilmTest/src/org/gec/service/UserService.java
UTF-8
257
1.84375
2
[]
no_license
package org.gec.service; import org.gec.pojo.Users; /** * @Description 用户类Service * @Author 余永浩 * @Date 21:17 2020/6/20 **/ public interface UserService { // 1.登陆 Users login(String username, String password); }
true
79cb1e23f878e2027448f9cd5d560ce1148e458d
Java
drew21/Spring-Hibernate-login
/src/main/java/net/drew/dao/LoginDAO.java
UTF-8
153
1.898438
2
[]
no_license
package net.drew.dao; import net.drew.model.*; public interface LoginDAO{ public boolean checkLogin(String userName, String userPassword); }
true
bbba1f46568c2aa5d7c09b9aa5f62618a8937345
Java
retrogamer500/no-idea-engine
/src/main/java/net/loganford/noideaengine/graphics/RenderBatcher.java
UTF-8
5,930
2.453125
2
[ "BSD-2-Clause" ]
permissive
package net.loganford.noideaengine.graphics; import net.loganford.noideaengine.graphics.shader.ShaderProgram; import net.loganford.noideaengine.graphics.shader.ShaderUniform; import net.loganford.noideaengine.utils.memory.UnsafeMemory; import net.loganford.noideaengine.utils.memory.UnsafeMemoryTracker; import org.joml.Matrix4f; import org.joml.Vector3f; import org.lwjgl.opengl.GL33; import org.lwjgl.system.MemoryStack; import java.nio.IntBuffer; public class RenderBatcher implements UnsafeMemory { private static Vector3f v3 = new Vector3f(); private static Matrix4f identity = new Matrix4f(); public static final int MAX_QUADS = 512; public static final int MAX_VERTICES = 4 * MAX_QUADS; //512 quads public static final int INDEX_SIZE = 6 * MAX_QUADS; private int quads = 0; private VertexArrayObject vao; private VertexArrayObject.VertexBufferObject positionVbo; private VertexArrayObject.VertexBufferObject normalVbo; private VertexArrayObject.VertexBufferObject uvVbo; private VertexArrayObject.VertexBufferObject colorVbo; private int indicesVbo; private Texture currentTexture; @SuppressWarnings("PointlessArithmeticExpression") public RenderBatcher() { vao = new VertexArrayObject(); positionVbo = vao.addVertexBufferObject(3, MAX_VERTICES, GL33.GL_STREAM_DRAW); normalVbo = vao.addVertexBufferObject(3, MAX_VERTICES, GL33.GL_STREAM_DRAW); uvVbo = vao.addVertexBufferObject(2, MAX_VERTICES, GL33.GL_STREAM_DRAW); colorVbo = vao.addVertexBufferObject(4, MAX_VERTICES, GL33.GL_STREAM_DRAW); vao.buffer(); //Create index arrays try (MemoryStack stack = MemoryStack.stackPush()) { IntBuffer indices = stack.mallocInt(INDEX_SIZE); int index = 0; for (int i = 0; i < MAX_QUADS; i++) { indices.put(index + 0); indices.put(index + 2); indices.put(index + 1); indices.put(index + 1); indices.put(index + 2); indices.put(index + 3); index += 4; } indices.flip(); GL33.glBindVertexArray(vao.getId()); indicesVbo = GL33.glGenBuffers(); GL33.glBindBuffer(GL33.GL_ELEMENT_ARRAY_BUFFER, indicesVbo); GL33.glBufferData(GL33.GL_ELEMENT_ARRAY_BUFFER, indices, GL33.GL_STATIC_DRAW); GL33.glBindBuffer(GL33.GL_ELEMENT_ARRAY_BUFFER, 0); } UnsafeMemoryTracker.track(this); } public void put(Renderer renderer, Image image, float x, float y, float width, float height, float u0, float v0, float u1, float v1) { //Flush if buffer is full if(quads >= MAX_QUADS) { flush(renderer); } //flush if texture has changed Texture texture = image.getTexture(); if(currentTexture == null) { currentTexture = texture; } else { if(texture.getTextureId() != currentTexture.getTextureId()) { flush(renderer); currentTexture = texture; } } put(renderer, image, v3.set(0, 0, 0), x, y, u0, v0); put(renderer, image, v3.set(width, 0, 0), x, y, u1, v0); put(renderer, image, v3.set(0, height, 0), x, y, u0, v1); put(renderer, image, v3.set(width, height, 0), x, y, u1, v1); quads++; } private void put(Renderer renderer, Image image, Vector3f pos, float x, float y, float u, float v) { pos.rotateZ(-image.getAngle()); pos.mul(image.getScaleX(), image.getScaleY(), 1f); pos.add(x, y, 0); positionVbo.put(pos); normalVbo.put(0); normalVbo.put(0); normalVbo.put(1); uvVbo.put(u); uvVbo.put(v); colorVbo.put(image.getColor()); } public void flush(Renderer renderer) { if(quads != 0) { if(renderer.getShader() == null) { if(renderer.shaderProgramId != renderer.getImageShader().getProgramId()) { GL33.glUseProgram(renderer.getImageShader().getProgramId()); renderer.shaderProgramId = renderer.getImageShader().getProgramId(); } } boolean cullingBackface = renderer.isCullingBackface(); renderer.setCullingBackface(false); vao.flipAndUpdate(0); //Populate uniforms ShaderProgram shader = renderer.getShader(); shader.setUniform(ShaderUniform.COLOR, ShaderProgram.DEFAULT_COLOR); shader.setUniform(ShaderUniform.MODEL, identity); shader.setUniform(ShaderUniform.VIEW, renderer.getView().getViewMatrix()); shader.setUniform(ShaderUniform.PROJECTION, renderer.getView().getProjectionMatrix()); shader.setUniform(ShaderUniform.TEX_DIFFUSE, currentTexture); shader.setUniform(ShaderUniform.LIGHT_COLOR, renderer.getLightColor()); shader.setUniform(ShaderUniform.LIGHT_DIRECTION, renderer.getLightDirection()); shader.setUniform(ShaderUniform.AMBIENT_LIGHT_COLOR, renderer.getAmbientLightColor()); //Bind vertex array GL33.glBindVertexArray(vao.getId()); //Bind indices GL33.glBindBuffer(GL33.GL_ELEMENT_ARRAY_BUFFER, indicesVbo); //Render GL33.glDrawElements(GL33.GL_TRIANGLES, quads * 6, GL33.GL_UNSIGNED_INT, 0); shader.resetBoundTextures(renderer); quads = 0; vao.clear(); currentTexture = null; renderer.setCullingBackface(cullingBackface); } } @Override public void freeMemory() { vao.freeMemory(); GL33.glBindBuffer(GL33.GL_ELEMENT_ARRAY_BUFFER, 0); GL33.glDeleteBuffers(indicesVbo); UnsafeMemoryTracker.untrack(this); } }
true
0606727991daaea43dc4563fd4f0b53e265775a8
Java
awesomedavid/RobotWarsRepoV1
/eclipse-workspace/Robot Wars/src/animations/beam/AnimBeamBurst.java
UTF-8
708
2.3125
2
[]
no_license
package animations.beam; import org.newdawn.slick.Color; import org.newdawn.slick.Graphics; import animations.Animation; import objects.GameObject; import objects.Point; import objects.Unit; import values.CoreValues; public abstract class AnimBeamBurst extends AnimBeam { int width; public AnimBeamBurst(Point origin, Unit actor, GameObject target, int width, int duration, boolean hit) { super(origin, actor, target, duration, hit); this.width = width; } public Color getColor() { Color c = actor.getTeam().getColor(); return new Color(c.getRed(), c.getGreen(), c.getBlue(), getFadeAlphaValue()); } public int getWidth() { return (int) (width * (1.0 - percentComplete())); } }
true