hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e17188661791c4c407fdf456550d8824aaa60ac
2,131
java
Java
handler-transformer/src/main/java/com/spldeolin/allison1875/handlertransformer/HandlerTransformerConfig.java
spldeolin/Allison-1875
9ae048be529f586213db0d8eaac138de74e1d483
[ "Apache-2.0" ]
9
2020-02-18T09:10:37.000Z
2022-03-02T03:05:38.000Z
handler-transformer/src/main/java/com/spldeolin/allison1875/handlertransformer/HandlerTransformerConfig.java
spldeolin/Allison-1875
9ae048be529f586213db0d8eaac138de74e1d483
[ "Apache-2.0" ]
5
2021-01-28T06:06:20.000Z
2022-01-24T02:50:09.000Z
handler-transformer/src/main/java/com/spldeolin/allison1875/handlertransformer/HandlerTransformerConfig.java
spldeolin/Allison-1875
9ae048be529f586213db0d8eaac138de74e1d483
[ "Apache-2.0" ]
3
2020-05-26T16:25:10.000Z
2021-04-07T10:12:11.000Z
24.77907
92
0.63679
9,839
package com.spldeolin.allison1875.handlertransformer; import javax.validation.constraints.NotEmpty; import lombok.Data; /** * Allison1875[handler-transformer]的配置 * * @author Deolin 2020-08-25 */ @Data public final class HandlerTransformerConfig { /** * 控制层 @RequestBody类型所在包的包名 */ @NotEmpty private String reqDtoPackage; /** * 控制层 @ResponseBody业务数据部分类型所在包的包名 */ @NotEmpty private String respDtoPackage; /** * 业务层 Service接口所在包的包名 */ @NotEmpty private String servicePackage; /** * 业务 ServiceImpl类所在包的包名 */ @NotEmpty private String serviceImplPackage; /** * 为生成的代码指定作者 */ @NotEmpty private String author; /** * 分页对象的全限定名 */ @NotEmpty private String pageTypeQualifier; /** * 使用通配符的方式设置所有包名,通配符是<code>.-</code> * * <pre> * e.g.1: * input: * com.company.orginization.project.- * * output: * com.company.orginization.project.javabean.req * com.company.orginization.project.javabean.resp * com.company.orginization.project.service * com.company.orginization.project.serviceimpl * * * e.g.2: * input: * com.company.orginization.project.-.module.sub * * output: * com.company.orginization.project.javabean.req.module.sub * com.company.orginization.project.javabean.resp.module.sub * com.company.orginization.project.service.module.sub * com.company.orginization.project.serviceimpl.module.sub * * </pre> */ public void batchSetAllPackagesByWildcard(String packageNameWithWildcard) { if (packageNameWithWildcard != null && packageNameWithWildcard.contains(".-")) { this.reqDtoPackage = packageNameWithWildcard.replace(".-", ".javabean.req"); this.respDtoPackage = packageNameWithWildcard.replace(".-", ".javabean.resp"); this.servicePackage = packageNameWithWildcard.replace(".-", ".service"); this.serviceImplPackage = packageNameWithWildcard.replace(".-", ".serviceimpl"); } } }
3e1718e8005825bc9bd2cd5be9aabcdbe730b9d1
1,870
java
Java
micro-services/workflow/service-surety-workflow-apilist/src/main/java/yhao/micro/service/workflow/apilist/model/flow/FlowNodeWarnModel.java
fourierjoe/ql-wt
8f20294a9ce28a299e8761b8e5ec67ff2cb1b4dd
[ "Apache-2.0" ]
null
null
null
micro-services/workflow/service-surety-workflow-apilist/src/main/java/yhao/micro/service/workflow/apilist/model/flow/FlowNodeWarnModel.java
fourierjoe/ql-wt
8f20294a9ce28a299e8761b8e5ec67ff2cb1b4dd
[ "Apache-2.0" ]
null
null
null
micro-services/workflow/service-surety-workflow-apilist/src/main/java/yhao/micro/service/workflow/apilist/model/flow/FlowNodeWarnModel.java
fourierjoe/ql-wt
8f20294a9ce28a299e8761b8e5ec67ff2cb1b4dd
[ "Apache-2.0" ]
1
2022-01-24T14:41:22.000Z
2022-01-24T14:41:22.000Z
22.261905
59
0.66631
9,840
package yhao.micro.service.workflow.apilist.model.flow; import io.swagger.annotations.ApiModelProperty; import yhao.infra.common.model.Entity; public class FlowNodeWarnModel extends Entity<String> { @ApiModelProperty("节点Id") private String nodeId; @ApiModelProperty(value = "规定时限") private Integer limit; @ApiModelProperty(value = "提前未完成提醒") private Integer limitWarn; @ApiModelProperty(value = "延期,1级预警") private Integer levelOneWarn; @ApiModelProperty(value = "延期,2级预警") private Integer levelTwoWarn; @ApiModelProperty(value = "延期,3级预警") private Integer levelThreeWarn; @ApiModelProperty(value = "预警通知对象(只预警客户经理)") private String warnPerson; public String getNodeId() { return nodeId; } public void setNodeId(String nodeId) { this.nodeId = nodeId; } public Integer getLimit() { return limit; } public void setLimit(Integer limit) { this.limit = limit; } public Integer getLimitWarn() { return limitWarn; } public void setLimitWarn(Integer limitWarn) { this.limitWarn = limitWarn; } public Integer getLevelOneWarn() { return levelOneWarn; } public void setLevelOneWarn(Integer levelOneWarn) { this.levelOneWarn = levelOneWarn; } public Integer getLevelTwoWarn() { return levelTwoWarn; } public void setLevelTwoWarn(Integer levelTwoWarn) { this.levelTwoWarn = levelTwoWarn; } public Integer getLevelThreeWarn() { return levelThreeWarn; } public void setLevelThreeWarn(Integer levelThreeWarn) { this.levelThreeWarn = levelThreeWarn; } public String getWarnPerson() { return warnPerson; } public void setWarnPerson(String warnPerson) { this.warnPerson = warnPerson; } }
3e17196cada7f1f9f65b194b5fe80169011cc311
5,136
java
Java
commons-jcs-core/src/main/java/org/apache/commons/jcs3/utils/discovery/UDPDiscoveryManager.java
nhojpatrick/apache_commons-jcs
f18c11d604f8a830766edb76edd47ae8dcc44f7b
[ "Apache-2.0" ]
87
2015-02-25T02:27:08.000Z
2021-12-06T10:25:15.000Z
commons-jcs-core/src/main/java/org/apache/commons/jcs3/utils/discovery/UDPDiscoveryManager.java
nhojpatrick/apache_commons-jcs
f18c11d604f8a830766edb76edd47ae8dcc44f7b
[ "Apache-2.0" ]
47
2021-05-13T06:53:34.000Z
2022-03-28T22:12:15.000Z
commons-jcs-core/src/main/java/org/apache/commons/jcs3/utils/discovery/UDPDiscoveryManager.java
nhojpatrick/apache_commons-jcs
f18c11d604f8a830766edb76edd47ae8dcc44f7b
[ "Apache-2.0" ]
61
2015-03-29T03:29:08.000Z
2021-11-07T12:08:36.000Z
36.685714
122
0.686916
9,841
package org.apache.commons.jcs3.utils.discovery; /* * 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.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.commons.jcs3.engine.behavior.ICompositeCacheManager; import org.apache.commons.jcs3.engine.behavior.IElementSerializer; import org.apache.commons.jcs3.engine.behavior.IProvideScheduler; import org.apache.commons.jcs3.log.Log; import org.apache.commons.jcs3.log.LogManager; import org.apache.commons.jcs3.utils.serialization.StandardSerializer; /** * This manages UDPDiscovery Services. We should end up with one service per Lateral Cache Manager * Instance. One service works for multiple regions. We don't want a connection for each region. * <p> * @author Aaron Smuts */ public class UDPDiscoveryManager { /** The logger */ private static final Log log = LogManager.getLog( UDPDiscoveryManager.class ); /** Singleton instance */ private static final UDPDiscoveryManager INSTANCE = new UDPDiscoveryManager(); /** Known services */ private final ConcurrentMap<String, UDPDiscoveryService> services = new ConcurrentHashMap<>(); /** private for singleton */ private UDPDiscoveryManager() { // noopt } /** * Singleton * <p> * @return UDPDiscoveryManager */ public static UDPDiscoveryManager getInstance() { return INSTANCE; } /** * Creates a service for the address and port if one doesn't exist already. * <p> * We need to key this using the listener port too. * TODO think of making one discovery service work for multiple types of clients. * <p> * @param discoveryAddress * @param discoveryPort * @param servicePort * @param cacheMgr * @return UDPDiscoveryService * @deprecated Specify serializer implementation explicitly, allow to specify udpTTL */ @Deprecated public UDPDiscoveryService getService( final String discoveryAddress, final int discoveryPort, final int servicePort, final ICompositeCacheManager cacheMgr ) { return getService(discoveryAddress, discoveryPort, null, servicePort, 0, cacheMgr, new StandardSerializer()); } /** * Creates a service for the address and port if one doesn't exist already. * <p> * We need to key this using the listener port too. * TODO think of making one discovery service work for multiple types of clients. * <p> * @param discoveryAddress * @param discoveryPort * @param serviceAddress * @param servicePort * @param updTTL * @param cacheMgr * @param serializer * * @return UDPDiscoveryService */ public UDPDiscoveryService getService( final String discoveryAddress, final int discoveryPort, final String serviceAddress, final int servicePort, final int updTTL, final ICompositeCacheManager cacheMgr, final IElementSerializer serializer ) { final String key = String.join(":", discoveryAddress, String.valueOf(discoveryPort), String.valueOf(servicePort)); final UDPDiscoveryService service = services.computeIfAbsent(key, k -> { log.info( "Creating service for address:port:servicePort [{0}]", key ); final UDPDiscoveryAttributes attributes = new UDPDiscoveryAttributes(); attributes.setUdpDiscoveryAddr(discoveryAddress); attributes.setUdpDiscoveryPort(discoveryPort); attributes.setServiceAddress(serviceAddress); attributes.setServicePort(servicePort); attributes.setUdpTTL(updTTL); final UDPDiscoveryService newService = new UDPDiscoveryService(attributes, serializer); // register for shutdown notification cacheMgr.registerShutdownObserver( newService ); // inject scheduler if ( cacheMgr instanceof IProvideScheduler) { newService.setScheduledExecutorService(((IProvideScheduler)cacheMgr) .getScheduledExecutorService()); } newService.startup(); return newService; }); log.debug( "Returning service [{0}] for key [{1}]", service, key ); return service; } }
3e17196d9556df81bb1525ee77b1b997b819a1a0
2,082
java
Java
platform/platform-impl/src/com/intellij/terminal/actions/TerminalActionUtil.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
2
2019-04-28T07:48:50.000Z
2020-12-11T14:18:08.000Z
platform/platform-impl/src/com/intellij/terminal/actions/TerminalActionUtil.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
null
null
null
platform/platform-impl/src/com/intellij/terminal/actions/TerminalActionUtil.java
nvartolomei/intellij-community
1aac326dadacf65d45decc25cef21f94f7b80d69
[ "Apache-2.0" ]
1
2020-10-15T05:56:42.000Z
2020-10-15T05:56:42.000Z
47.318182
140
0.735351
9,842
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.terminal.actions; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ActionUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.terminal.JBTerminalSystemSettingsProviderBase; import com.intellij.terminal.JBTerminalWidget; import com.jediterm.terminal.ui.TerminalAction; import com.jediterm.terminal.ui.TerminalActionPresentation; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.List; public class TerminalActionUtil { private TerminalActionUtil() {} public static @Nullable TerminalAction createTerminalAction(@NotNull JBTerminalWidget widget, @NonNls @NotNull String actionId, boolean hiddenAction) { List<KeyStroke> keyStrokes = JBTerminalSystemSettingsProviderBase.getKeyStrokesByActionId(actionId); if (keyStrokes.isEmpty() && hiddenAction) return null; AnAction action = ActionManager.getInstance().getAction(actionId); if (action == null) { throw new AssertionError("Cannot find action " + actionId); } String name = action.getTemplateText(); if (name != null && !hiddenAction) { throw new AssertionError("Action has unknown name: " + actionId); } TerminalActionPresentation presentation = new TerminalActionPresentation(StringUtil.notNullize(name, "unknown"), keyStrokes); return new TerminalAction(presentation, (keyEvent) -> { DataContext dataContext = DataManager.getInstance().getDataContext(widget.getTerminalPanel()); ActionUtil.performActionDumbAware(action, AnActionEvent.createFromInputEvent(keyEvent, "Terminal", null, dataContext)); return true; }).withHidden(hiddenAction); } }
3e171973f7f82989f4728fb9fe8cad25a4541e50
1,946
java
Java
detour/src/main/java/org/recast4j/detour/MeshData.java
Caojunqi/recast4j
8ba5b08dc5395b6b606eddccf40c976cb74ff059
[ "Zlib" ]
166
2016-01-05T06:38:41.000Z
2022-03-31T12:26:15.000Z
detour/src/main/java/org/recast4j/detour/MeshData.java
Caojunqi/recast4j
8ba5b08dc5395b6b606eddccf40c976cb74ff059
[ "Zlib" ]
52
2016-11-04T09:50:20.000Z
2022-03-27T12:16:15.000Z
detour/src/main/java/org/recast4j/detour/MeshData.java
Caojunqi/recast4j
8ba5b08dc5395b6b606eddccf40c976cb74ff059
[ "Zlib" ]
74
2016-01-02T08:34:50.000Z
2022-03-31T12:26:13.000Z
43.2
119
0.730967
9,843
/* Copyright (c) 2009-2010 Mikko Mononen hzdkv@example.com recast4j copyright (c) 2015-2019 Piotr Piastucki hzdkv@example.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ package org.recast4j.detour; public class MeshData { /** The tile header. */ public MeshHeader header; /** The tile vertices. [Size: MeshHeader::vertCount] */ public float[] verts; /** The tile polygons. [Size: MeshHeader::polyCount] */ public Poly[] polys; /** The tile's detail sub-meshes. [Size: MeshHeader::detailMeshCount] */ public PolyDetail[] detailMeshes; /** The detail mesh's unique vertices. [(x, y, z) * MeshHeader::detailVertCount] */ public float[] detailVerts; /** * The detail mesh's triangles. [(vertA, vertB, vertC) * MeshHeader::detailTriCount] See DetailTriEdgeFlags and * NavMesh::getDetailTriEdgeFlags. */ public int[] detailTris; /** * The tile bounding volume nodes. [Size: MeshHeader::bvNodeCount] (Will be null if bounding volumes are disabled.) */ public BVNode[] bvTree; /** The tile off-mesh connections. [Size: MeshHeader::offMeshConCount] */ public OffMeshConnection[] offMeshCons; }
3e171998c1a6d39b2690485f2cafeb6503eccd90
1,362
java
Java
joolun-wx/joolun-weixin/src/main/java/com/joolun/weixin/mapper/WxAutoReplyMapper.java
supermanvv/JooLun-wx
aeaaa4678a55b48bb3db7c851cb0d4def4f4a39d
[ "MIT" ]
1,544
2020-03-21T12:31:07.000Z
2022-03-29T10:27:06.000Z
joolun-wx/joolun-weixin/src/main/java/com/joolun/weixin/mapper/WxAutoReplyMapper.java
coolman200/WeChatManagementSystem
ba529b25f21b77741274465ecfc01b6f71d1cd1b
[ "MIT" ]
2
2021-03-09T14:24:14.000Z
2021-03-22T06:09:51.000Z
joolun-wx/joolun-weixin/src/main/java/com/joolun/weixin/mapper/WxAutoReplyMapper.java
coolman200/WeChatManagementSystem
ba529b25f21b77741274465ecfc01b6f71d1cd1b
[ "MIT" ]
83
2020-04-19T11:37:35.000Z
2022-03-31T03:01:03.000Z
35.842105
78
0.791483
9,844
/* MIT License Copyright (c) 2020 www.joolun.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.joolun.weixin.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.joolun.weixin.entity.WxAutoReply; /** * 消息自动回复 * * @author www.joolun.com * @date 2019-04-18 15:40:39 */ public interface WxAutoReplyMapper extends BaseMapper<WxAutoReply> { }
3e1719f4d14c8dda506b36bd0008244f963788e4
1,551
java
Java
src/main/java/br/com/zupacademy/natalia/transacao/controller/TransacoesCartaoController.java
natyff/orange-talents-05-template-transacao
cab0068a2f1526e22f75aaa3f124d48c244f2c37
[ "Apache-2.0" ]
null
null
null
src/main/java/br/com/zupacademy/natalia/transacao/controller/TransacoesCartaoController.java
natyff/orange-talents-05-template-transacao
cab0068a2f1526e22f75aaa3f124d48c244f2c37
[ "Apache-2.0" ]
null
null
null
src/main/java/br/com/zupacademy/natalia/transacao/controller/TransacoesCartaoController.java
natyff/orange-talents-05-template-transacao
cab0068a2f1526e22f75aaa3f124d48c244f2c37
[ "Apache-2.0" ]
null
null
null
39.769231
102
0.789813
9,845
package br.com.zupacademy.natalia.transacao.controller; import br.com.zupacademy.natalia.transacao.entities.CartaoEntity; import br.com.zupacademy.natalia.transacao.entities.TransacaoEntity; import br.com.zupacademy.natalia.transacao.repositories.CartaoRepository; import br.com.zupacademy.natalia.transacao.repositories.TransacoesRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; 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.RestController; import java.util.Optional; @RestController public class TransacoesCartaoController { @Autowired TransacoesRepository transacoesRepository; @Autowired CartaoRepository cartaoRepository; @GetMapping("/cartoes/{id}/transacoes") public ResponseEntity<?> transacoes(@PathVariable String id, @PageableDefault(page = 0, size = 10) Pageable paginacao) { Optional<CartaoEntity> encontrandoCartao = cartaoRepository.findById(id); if (encontrandoCartao.isPresent()) { Page<TransacaoEntity> transacaoEntities = transacoesRepository.findAll(paginacao); return ResponseEntity.ok().body(transacaoEntities); } return ResponseEntity.badRequest().body("Cartão não encontrado"); } }
3e171a0c4c7e6d1569d3c252eb0f7006a60b07ca
1,422
java
Java
presto-main/src/main/java/com/facebook/presto/sql/planner/iterative/Rule.java
outcoldman/presto
285aa96af1ab36cf14945238ccf28bcd550aaa32
[ "Apache-2.0" ]
null
null
null
presto-main/src/main/java/com/facebook/presto/sql/planner/iterative/Rule.java
outcoldman/presto
285aa96af1ab36cf14945238ccf28bcd550aaa32
[ "Apache-2.0" ]
null
null
null
presto-main/src/main/java/com/facebook/presto/sql/planner/iterative/Rule.java
outcoldman/presto
285aa96af1ab36cf14945238ccf28bcd550aaa32
[ "Apache-2.0" ]
1
2019-08-16T00:08:51.000Z
2019-08-16T00:08:51.000Z
28.44
75
0.727145
9,846
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.sql.planner.iterative; import com.facebook.presto.Session; import com.facebook.presto.matching.Captures; import com.facebook.presto.matching.Pattern; import com.facebook.presto.sql.planner.PlanNodeIdAllocator; import com.facebook.presto.sql.planner.SymbolAllocator; import com.facebook.presto.sql.planner.plan.PlanNode; import java.util.Optional; public interface Rule<T> { /** * Returns a pattern to which plan nodes this rule applies. */ Pattern<T> getPattern(); default boolean isEnabled(Session session) { return true; } Optional<PlanNode> apply(T node, Captures captures, Context context); interface Context { Lookup getLookup(); PlanNodeIdAllocator getIdAllocator(); SymbolAllocator getSymbolAllocator(); Session getSession(); } }
3e171a667f6052ef49b847faef86b35847e89fd2
920
java
Java
dao/StudentDaoImpl.java
VedangJoshi/Java-Design-Patterns
53486464f29f93b384097ac82e220b57805d4365
[ "MIT" ]
1
2017-01-11T07:48:50.000Z
2017-01-11T07:48:50.000Z
dao/StudentDaoImpl.java
VedangJoshi/Java-Design-Patterns
53486464f29f93b384097ac82e220b57805d4365
[ "MIT" ]
null
null
null
dao/StudentDaoImpl.java
VedangJoshi/Java-Design-Patterns
53486464f29f93b384097ac82e220b57805d4365
[ "MIT" ]
null
null
null
19.166667
67
0.728261
9,847
package dao; import java.util.HashMap; import java.util.Map; public class StudentDaoImpl implements StudentDAO{ Map<Long, String> studentMap = new HashMap<>(); @Override public Map<Long, String> getStudents() { return studentMap; } @Override public int insertStudent(long studentID, String studentName) { System.out.println("Inserted: " + studentID + " " + studentName); studentMap.put(studentID, studentName); return 0; } @Override public int deleteStudentByID(long studentID) { studentMap.remove(studentID); return 0; } @Override public int updateStudent(Student student, long studentID) { // TODO Auto-generated method stub return 0; } @Override public Student getStudentByID(long studentID) { // TODO Auto-generated method stub return null; } @Override public Student getStudentByName(String studentName) { // TODO Auto-generated method stub return null; } }
3e171ae79bb9c829b79acd6ab4b567352762e7ec
8,806
java
Java
backend/de.metas.adempiere.adempiere/base/src/main/java-gen/org/compiere/model/X_CM_ChatEntry.java
dram/metasfresh
a1b881a5b7df8b108d4c4ac03082b72c323873eb
[ "RSA-MD" ]
1,144
2016-02-14T10:29:35.000Z
2022-03-30T09:50:41.000Z
backend/de.metas.adempiere.adempiere/base/src/main/java-gen/org/compiere/model/X_CM_ChatEntry.java
dram/metasfresh
a1b881a5b7df8b108d4c4ac03082b72c323873eb
[ "RSA-MD" ]
8,283
2016-04-28T17:41:34.000Z
2022-03-30T13:30:12.000Z
backend/de.metas.adempiere.adempiere/base/src/main/java-gen/org/compiere/model/X_CM_ChatEntry.java
dram/metasfresh
a1b881a5b7df8b108d4c4ac03082b72c323873eb
[ "RSA-MD" ]
441
2016-04-29T08:06:07.000Z
2022-03-28T06:09:56.000Z
25.673469
123
0.734613
9,848
/** Generated Model - DO NOT CHANGE */ package org.compiere.model; import java.sql.ResultSet; import java.util.Properties; /** Generated Model for CM_ChatEntry * @author Adempiere (generated) */ @SuppressWarnings("javadoc") public class X_CM_ChatEntry extends org.compiere.model.PO implements I_CM_ChatEntry, org.compiere.model.I_Persistent { /** * */ private static final long serialVersionUID = -1128109696L; /** Standard Constructor */ public X_CM_ChatEntry (Properties ctx, int CM_ChatEntry_ID, String trxName) { super (ctx, CM_ChatEntry_ID, trxName); /** if (CM_ChatEntry_ID == 0) { setCharacterData (null); setChatEntryType (null); // N setCM_ChatEntry_ID (0); setCM_Chat_ID (0); setConfidentialType (null); } */ } /** Load Constructor */ public X_CM_ChatEntry (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } /** Set Ansprechpartner. @param AD_User_ID User within the system - Internal or Business Partner Contact */ @Override public void setAD_User_ID (int AD_User_ID) { if (AD_User_ID < 0) set_Value (COLUMNNAME_AD_User_ID, null); else set_Value (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID)); } /** Get Ansprechpartner. @return User within the system - Internal or Business Partner Contact */ @Override public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Character Data. @param CharacterData Long Character Field */ @Override public void setCharacterData (java.lang.String CharacterData) { set_ValueNoCheck (COLUMNNAME_CharacterData, CharacterData); } /** Get Character Data. @return Long Character Field */ @Override public java.lang.String getCharacterData () { return (java.lang.String)get_Value(COLUMNNAME_CharacterData); } /** * ChatEntryType AD_Reference_ID=398 * Reference name: CM_Chat EntryType */ public static final int CHATENTRYTYPE_AD_Reference_ID=398; /** Wiki = W */ public static final String CHATENTRYTYPE_Wiki = "W"; /** Note (flat) = N */ public static final String CHATENTRYTYPE_NoteFlat = "N"; /** Forum (threaded) = F */ public static final String CHATENTRYTYPE_ForumThreaded = "F"; /** Set Chat Entry Type. @param ChatEntryType Type of Chat/Forum Entry */ @Override public void setChatEntryType (java.lang.String ChatEntryType) { set_Value (COLUMNNAME_ChatEntryType, ChatEntryType); } /** Get Chat Entry Type. @return Type of Chat/Forum Entry */ @Override public java.lang.String getChatEntryType () { return (java.lang.String)get_Value(COLUMNNAME_ChatEntryType); } @Override public org.compiere.model.I_CM_ChatEntry getCM_ChatEntryGrandParent() { return get_ValueAsPO(COLUMNNAME_CM_ChatEntryGrandParent_ID, org.compiere.model.I_CM_ChatEntry.class); } @Override public void setCM_ChatEntryGrandParent(org.compiere.model.I_CM_ChatEntry CM_ChatEntryGrandParent) { set_ValueFromPO(COLUMNNAME_CM_ChatEntryGrandParent_ID, org.compiere.model.I_CM_ChatEntry.class, CM_ChatEntryGrandParent); } /** Set Chat Entry Grandparent. @param CM_ChatEntryGrandParent_ID Link to Grand Parent (root level) */ @Override public void setCM_ChatEntryGrandParent_ID (int CM_ChatEntryGrandParent_ID) { if (CM_ChatEntryGrandParent_ID < 1) set_Value (COLUMNNAME_CM_ChatEntryGrandParent_ID, null); else set_Value (COLUMNNAME_CM_ChatEntryGrandParent_ID, Integer.valueOf(CM_ChatEntryGrandParent_ID)); } /** Get Chat Entry Grandparent. @return Link to Grand Parent (root level) */ @Override public int getCM_ChatEntryGrandParent_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_ChatEntryGrandParent_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Chat-Eintrag. @param CM_ChatEntry_ID Individual Chat / Discussion Entry */ @Override public void setCM_ChatEntry_ID (int CM_ChatEntry_ID) { if (CM_ChatEntry_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_ChatEntry_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_ChatEntry_ID, Integer.valueOf(CM_ChatEntry_ID)); } /** Get Chat-Eintrag. @return Individual Chat / Discussion Entry */ @Override public int getCM_ChatEntry_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_ChatEntry_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_CM_ChatEntry getCM_ChatEntryParent() { return get_ValueAsPO(COLUMNNAME_CM_ChatEntryParent_ID, org.compiere.model.I_CM_ChatEntry.class); } @Override public void setCM_ChatEntryParent(org.compiere.model.I_CM_ChatEntry CM_ChatEntryParent) { set_ValueFromPO(COLUMNNAME_CM_ChatEntryParent_ID, org.compiere.model.I_CM_ChatEntry.class, CM_ChatEntryParent); } /** Set Chat Entry Parent. @param CM_ChatEntryParent_ID Link to direct Parent */ @Override public void setCM_ChatEntryParent_ID (int CM_ChatEntryParent_ID) { if (CM_ChatEntryParent_ID < 1) set_Value (COLUMNNAME_CM_ChatEntryParent_ID, null); else set_Value (COLUMNNAME_CM_ChatEntryParent_ID, Integer.valueOf(CM_ChatEntryParent_ID)); } /** Get Chat Entry Parent. @return Link to direct Parent */ @Override public int getCM_ChatEntryParent_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_ChatEntryParent_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_CM_Chat getCM_Chat() { return get_ValueAsPO(COLUMNNAME_CM_Chat_ID, org.compiere.model.I_CM_Chat.class); } @Override public void setCM_Chat(org.compiere.model.I_CM_Chat CM_Chat) { set_ValueFromPO(COLUMNNAME_CM_Chat_ID, org.compiere.model.I_CM_Chat.class, CM_Chat); } /** Set Chat. @param CM_Chat_ID Chat or discussion thread */ @Override public void setCM_Chat_ID (int CM_Chat_ID) { if (CM_Chat_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_Chat_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_Chat_ID, Integer.valueOf(CM_Chat_ID)); } /** Get Chat. @return Chat or discussion thread */ @Override public int getCM_Chat_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Chat_ID); if (ii == null) return 0; return ii.intValue(); } /** * ConfidentialType AD_Reference_ID=340 * Reference name: R_Request Confidential */ public static final int CONFIDENTIALTYPE_AD_Reference_ID=340; /** Public Information = A */ public static final String CONFIDENTIALTYPE_PublicInformation = "A"; /** Partner Confidential = C */ public static final String CONFIDENTIALTYPE_PartnerConfidential = "C"; /** Internal = I */ public static final String CONFIDENTIALTYPE_Internal = "I"; /** Private Information = P */ public static final String CONFIDENTIALTYPE_PrivateInformation = "P"; /** Set Vertraulichkeit. @param ConfidentialType Type of Confidentiality */ @Override public void setConfidentialType (java.lang.String ConfidentialType) { set_Value (COLUMNNAME_ConfidentialType, ConfidentialType); } /** Get Vertraulichkeit. @return Type of Confidentiality */ @Override public java.lang.String getConfidentialType () { return (java.lang.String)get_Value(COLUMNNAME_ConfidentialType); } /** * ModeratorStatus AD_Reference_ID=396 * Reference name: CM_ChatEntry ModeratorStatus */ public static final int MODERATORSTATUS_AD_Reference_ID=396; /** Nicht angezeigt = N */ public static final String MODERATORSTATUS_NichtAngezeigt = "N"; /** Veröffentlicht = P */ public static final String MODERATORSTATUS_Veroeffentlicht = "P"; /** To be reviewed = R */ public static final String MODERATORSTATUS_ToBeReviewed = "R"; /** Verdächtig = S */ public static final String MODERATORSTATUS_Verdaechtig = "S"; /** Set Moderation Status. @param ModeratorStatus Status of Moderation */ @Override public void setModeratorStatus (java.lang.String ModeratorStatus) { set_Value (COLUMNNAME_ModeratorStatus, ModeratorStatus); } /** Get Moderation Status. @return Status of Moderation */ @Override public java.lang.String getModeratorStatus () { return (java.lang.String)get_Value(COLUMNNAME_ModeratorStatus); } /** Set Betreff. @param Subject Mail Betreff */ @Override public void setSubject (java.lang.String Subject) { set_Value (COLUMNNAME_Subject, Subject); } /** Get Betreff. @return Mail Betreff */ @Override public java.lang.String getSubject () { return (java.lang.String)get_Value(COLUMNNAME_Subject); } }
3e171b311a1e38cd13379db60415654461c3a491
3,920
java
Java
controllersvc/src/main/java/com/emc/storageos/volumecontroller/impl/plugins/metering/vnxfile/processor/VNXFileSystemUnmountProcessor.java
CoprHD/sds-controller
a575ec96928b1e9258313efe92c930bfe9d6753a
[ "Apache-2.0" ]
91
2015-06-06T01:40:34.000Z
2020-11-24T07:26:40.000Z
controllersvc/src/main/java/com/emc/storageos/volumecontroller/impl/plugins/metering/vnxfile/processor/VNXFileSystemUnmountProcessor.java
CoprHD/sds-controller
a575ec96928b1e9258313efe92c930bfe9d6753a
[ "Apache-2.0" ]
3
2015-07-14T18:47:53.000Z
2015-07-14T18:50:16.000Z
controllersvc/src/main/java/com/emc/storageos/volumecontroller/impl/plugins/metering/vnxfile/processor/VNXFileSystemUnmountProcessor.java
CoprHD/sds-controller
a575ec96928b1e9258313efe92c930bfe9d6753a
[ "Apache-2.0" ]
71
2015-06-05T21:35:31.000Z
2021-11-07T16:32:46.000Z
42.150538
105
0.625255
9,849
/* * Copyright (c) 2008-2013 EMC Corporation * All Rights Reserved */ package com.emc.storageos.volumecontroller.impl.plugins.metering.vnxfile.processor; import com.emc.nas.vnxfile.xmlapi.Severity; import com.emc.nas.vnxfile.xmlapi.TaskResponse; import com.emc.nas.vnxfile.xmlapi.ResponsePacket; import com.emc.nas.vnxfile.xmlapi.Status; import com.emc.storageos.plugins.BaseCollectionException; import com.emc.storageos.plugins.common.domainmodel.Operation; import com.emc.storageos.plugins.metering.vnxfile.VNXFileConstants; import com.emc.storageos.volumecontroller.impl.plugins.metering.vnxfile.VNXFileProcessor; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.methods.PostMethod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Responsible for unmounting file systems on the VNX. */ public class VNXFileSystemUnmountProcessor extends VNXFileProcessor { private final Logger _logger = LoggerFactory.getLogger(VNXFileSystemUnmountProcessor.class); @Override public void processResult(Operation operation, Object resultObj, Map<String, Object> keyMap) throws BaseCollectionException { _logger.info("Processing VNX File System Unmount response: {}", resultObj); final PostMethod result = (PostMethod) resultObj; try { ResponsePacket responsePacket = (ResponsePacket) _unmarshaller .unmarshal(result.getResponseBodyAsStream()); Status status = null; if (null != responsePacket.getPacketFault()) { status = responsePacket.getPacketFault(); processErrorStatus(status, keyMap); } else { List<Object> queryResponse = getTaskResponse(responsePacket); Iterator<Object> queryRespItr = queryResponse.iterator(); while (queryRespItr.hasNext()) { Object responseObj = queryRespItr.next(); if (responseObj instanceof TaskResponse) { TaskResponse system = (TaskResponse) responseObj; status = system.getStatus(); _logger.info("Unmount task response status: {}", status.getMaxSeverity().name()); if (status.getMaxSeverity() == Severity.OK) { keyMap.put(VNXFileConstants.CMD_RESULT, VNXFileConstants.CMD_SUCCESS); } else { processErrorStatus(status, keyMap); } break; } else { _logger.info("Response not TaskResponse: {}", responseObj.getClass().getName()); } } // Extract session information from the response header. Header[] headers = result .getResponseHeaders(VNXFileConstants.CELERRA_SESSION); if (null != headers && headers.length > 0) { keyMap.put(VNXFileConstants.CELERRA_SESSION, headers[0].getValue()); _logger.info("Recieved celerra session information from the Server."); } } } catch (final Exception ex) { _logger.error( "Exception occurred while processing the vnx prov response due to ", ex); keyMap.put(VNXFileConstants.FAULT_DESC, ex.getMessage()); keyMap.put(VNXFileConstants.CMD_RESULT, VNXFileConstants.CMD_FAILURE); } finally { result.releaseConnection(); } } @Override protected void setPrerequisiteObjects(List<Object> inputArgs) throws BaseCollectionException { // TODO Is this method needed? Not used in other processors. } }
3e171ca3cf0b40ea55b6e1f70fb4860accf9f271
2,399
java
Java
gulimall-order/src/main/java/com/zhoushucheng/gulimall/order/controller/OrderReturnApplyController.java
ZhouShucheng/gulimall
44c2065d1ed968835bd99ca2c06e82c1d9a88d48
[ "Apache-2.0" ]
null
null
null
gulimall-order/src/main/java/com/zhoushucheng/gulimall/order/controller/OrderReturnApplyController.java
ZhouShucheng/gulimall
44c2065d1ed968835bd99ca2c06e82c1d9a88d48
[ "Apache-2.0" ]
null
null
null
gulimall-order/src/main/java/com/zhoushucheng/gulimall/order/controller/OrderReturnApplyController.java
ZhouShucheng/gulimall
44c2065d1ed968835bd99ca2c06e82c1d9a88d48
[ "Apache-2.0" ]
null
null
null
26.472527
80
0.719801
9,850
package com.zhoushucheng.gulimall.order.controller; import java.util.Arrays; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; 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.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.zhoushucheng.gulimall.order.entity.OrderReturnApplyEntity; import com.zhoushucheng.gulimall.order.service.OrderReturnApplyService; import com.zhoushucheng.common.utils.PageUtils; import com.zhoushucheng.common.utils.R; /** * 订单退货申请 * * @author zhoushucheng * @email anpch@example.com * @date 2021-08-16 17:49:45 */ @RestController @RequestMapping("order/orderreturnapply") public class OrderReturnApplyController { @Autowired private OrderReturnApplyService orderReturnApplyService; /** * 列表 */ @RequestMapping("/list") //@RequiresPermissions("order:orderreturnapply:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = orderReturnApplyService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") //@RequiresPermissions("order:orderreturnapply:info") public R info(@PathVariable("id") Long id){ OrderReturnApplyEntity orderReturnApply = orderReturnApplyService.getById(id); return R.ok().put("orderReturnApply", orderReturnApply); } /** * 保存 */ @RequestMapping("/save") //@RequiresPermissions("order:orderreturnapply:save") public R save(@RequestBody OrderReturnApplyEntity orderReturnApply){ orderReturnApplyService.save(orderReturnApply); return R.ok(); } /** * 修改 */ @RequestMapping("/update") //@RequiresPermissions("order:orderreturnapply:update") public R update(@RequestBody OrderReturnApplyEntity orderReturnApply){ orderReturnApplyService.updateById(orderReturnApply); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") //@RequiresPermissions("order:orderreturnapply:delete") public R delete(@RequestBody Long[] ids){ orderReturnApplyService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
3e171e0347a3b6f98d67cf923f6ba244882d0105
1,613
java
Java
food-tracker-api/src/main/java/com/foodtracker/foodtrackerapi/resources/RecipeResource.java
JaninaMattes/spring-boot-inventory-backend
917f59b431da04dc8a070e3069141cb5243b2a47
[ "MIT" ]
1
2022-01-12T08:57:09.000Z
2022-01-12T08:57:09.000Z
food-tracker-api/src/main/java/com/foodtracker/foodtrackerapi/resources/RecipeResource.java
JaninaMattes/spring-boot-inventory-backend
917f59b431da04dc8a070e3069141cb5243b2a47
[ "MIT" ]
null
null
null
food-tracker-api/src/main/java/com/foodtracker/foodtrackerapi/resources/RecipeResource.java
JaninaMattes/spring-boot-inventory-backend
917f59b431da04dc8a070e3069141cb5243b2a47
[ "MIT" ]
null
null
null
32.26
90
0.742715
9,851
package com.foodtracker.foodtrackerapi.resources; import com.foodtracker.foodtrackerapi.models.Recipe; import com.foodtracker.foodtrackerapi.services.RecipeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Map; import java.util.Optional; @RestController @RequestMapping("api/recipe") public class RecipeResource { @Autowired RecipeService recipeService; @GetMapping("/type") public Optional<Recipe> getRecipeByType(@RequestBody Map<String, Object> recipeMap){ String type = (String) recipeMap.get("TYPE"); return recipeService.getRecipeByType(type); } @GetMapping("/id") public Optional<Recipe> getRecipeByID(@RequestBody Map<String, Integer> recipeMap){ int id = (Integer) recipeMap.get("ID"); return recipeService.getRecipeByID(id); } @GetMapping("/rating") public Optional<Recipe> getRecipeByRating(@RequestBody Map<String, Object> recipeMap){ Double rating = (Double) recipeMap.get("RATING"); return recipeService.getRecipeByRating(rating); } @GetMapping("/popular") public Optional<Recipe> getMostPopularRecipe(){ return recipeService.getMostPopularRecipe(); } @GetMapping("/all") public List<Recipe> getAllRecipes(){ return recipeService.getAllRecipes(); } }
3e171ec2c35bfaa44f6ad2e1bf2ca018e42738bd
594
java
Java
src/RegexCheck.java
ishamibrahim/LearningJava
ff474d168ec197737c918711b0985379d84d44c3
[ "Apache-2.0" ]
null
null
null
src/RegexCheck.java
ishamibrahim/LearningJava
ff474d168ec197737c918711b0985379d84d44c3
[ "Apache-2.0" ]
null
null
null
src/RegexCheck.java
ishamibrahim/LearningJava
ff474d168ec197737c918711b0985379d84d44c3
[ "Apache-2.0" ]
null
null
null
28.285714
84
0.614478
9,852
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexCheck { public static void main(String[] args){ System.out.println("Testing regex \n"); String pattern = "[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}"; String sentence = "The second world war ended in 14-06-1945 and 14-06-1845"; Pattern patternRgx = Pattern.compile(pattern); Matcher matching = patternRgx.matcher(sentence); while (matching.find()){ System.out.println("Found the date"); System.out.println(matching.group()); } } }
3e171f33fb535ab2702aa76f5afb1478e9362dd8
4,728
java
Java
src/main/java/org/elasticsearch/action/deletebyquery/IndexDeleteByQueryRequest.java
liatrio/elasticsearch
d04aa68bf5ff78fbf764c2a6586604de2af9c79b
[ "Apache-2.0" ]
24
2015-06-22T01:12:12.000Z
2021-02-21T21:58:27.000Z
src/main/java/org/elasticsearch/action/deletebyquery/IndexDeleteByQueryRequest.java
dlyoungerman/elasticsearch
0e6e6f97dcae2cd1ba1f08b65f07a99940de401f
[ "Apache-2.0" ]
1
2019-09-27T07:46:34.000Z
2019-09-27T07:46:34.000Z
src/main/java/org/elasticsearch/action/deletebyquery/IndexDeleteByQueryRequest.java
dlyoungerman/elasticsearch
0e6e6f97dcae2cd1ba1f08b65f07a99940de401f
[ "Apache-2.0" ]
9
2015-05-28T22:33:01.000Z
2022-01-11T03:28:40.000Z
32.833333
143
0.651015
9,853
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.deletebyquery; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.support.replication.IndexReplicationOperationRequest; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.unit.TimeValue; import java.io.IOException; import java.util.HashSet; import java.util.Set; import static org.elasticsearch.action.ValidateActions.addValidationError; /** * Delete by query request to execute on a specific index. */ public class IndexDeleteByQueryRequest extends IndexReplicationOperationRequest<IndexDeleteByQueryRequest> { private BytesReference querySource; private String[] types = Strings.EMPTY_ARRAY; @Nullable private Set<String> routing; @Nullable private String[] filteringAliases; IndexDeleteByQueryRequest(DeleteByQueryRequest request, String index, @Nullable Set<String> routing, @Nullable String[] filteringAliases) { this.index = index; this.timeout = request.timeout(); this.querySource = request.querySource(); this.types = request.types(); this.replicationType = request.replicationType(); this.consistencyLevel = request.consistencyLevel(); this.routing = routing; this.filteringAliases = filteringAliases; } IndexDeleteByQueryRequest() { } BytesReference querySource() { return querySource; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = super.validate(); if (querySource == null) { validationException = addValidationError("querySource is missing", validationException); } return validationException; } Set<String> routing() { return this.routing; } String[] types() { return this.types; } String[] filteringAliases() { return filteringAliases; } public IndexDeleteByQueryRequest timeout(TimeValue timeout) { this.timeout = timeout; return this; } public void readFrom(StreamInput in) throws IOException { super.readFrom(in); querySource = in.readBytesReference(); int typesSize = in.readVInt(); if (typesSize > 0) { types = new String[typesSize]; for (int i = 0; i < typesSize; i++) { types[i] = in.readString(); } } int routingSize = in.readVInt(); if (routingSize > 0) { routing = new HashSet<String>(routingSize); for (int i = 0; i < routingSize; i++) { routing.add(in.readString()); } } int aliasesSize = in.readVInt(); if (aliasesSize > 0) { filteringAliases = new String[aliasesSize]; for (int i = 0; i < aliasesSize; i++) { filteringAliases[i] = in.readString(); } } } public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeBytesReference(querySource); out.writeVInt(types.length); for (String type : types) { out.writeString(type); } if (routing != null) { out.writeVInt(routing.size()); for (String r : routing) { out.writeString(r); } } else { out.writeVInt(0); } if (filteringAliases != null) { out.writeVInt(filteringAliases.length); for (String alias : filteringAliases) { out.writeString(alias); } } else { out.writeVInt(0); } } }
3e171f72d73b7df3859b28d12c15460d44838360
282
java
Java
src/main/java/backend/nomad/domain/review/ReviewRepository.java
ajou-nomad/nomad-backend
0ad11a2f8604fa89928100ef6e537ba3d7ce1abb
[ "MIT" ]
null
null
null
src/main/java/backend/nomad/domain/review/ReviewRepository.java
ajou-nomad/nomad-backend
0ad11a2f8604fa89928100ef6e537ba3d7ce1abb
[ "MIT" ]
null
null
null
src/main/java/backend/nomad/domain/review/ReviewRepository.java
ajou-nomad/nomad-backend
0ad11a2f8604fa89928100ef6e537ba3d7ce1abb
[ "MIT" ]
null
null
null
23.5
71
0.794326
9,854
package backend.nomad.domain.review; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface ReviewRepository extends JpaRepository<Review, Long> { List<Review> findByUid(String uid); Review findByReviewId(Long reviewId); }
3e171f84daebb8d9089296aba11ffa66ed851558
3,243
java
Java
languages/baseLanguage/collections/source_gen/jetbrains/mps/baseLanguage/collections/typesystem/check_AbstractSetOperation_NonTypesystemRule.java
trespasserw/MPS
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
[ "Apache-2.0" ]
null
null
null
languages/baseLanguage/collections/source_gen/jetbrains/mps/baseLanguage/collections/typesystem/check_AbstractSetOperation_NonTypesystemRule.java
trespasserw/MPS
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
[ "Apache-2.0" ]
null
null
null
languages/baseLanguage/collections/source_gen/jetbrains/mps/baseLanguage/collections/typesystem/check_AbstractSetOperation_NonTypesystemRule.java
trespasserw/MPS
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
[ "Apache-2.0" ]
null
null
null
64.86
363
0.831637
9,855
package jetbrains.mps.baseLanguage.collections.typesystem; /*Generated by MPS */ import jetbrains.mps.lang.typesystem.runtime.AbstractNonTypesystemRule_Runtime; import jetbrains.mps.lang.typesystem.runtime.NonTypesystemRule_Runtime; import org.jetbrains.mps.openapi.model.SNode; import jetbrains.mps.typesystem.inference.TypeCheckingContext; import jetbrains.mps.lang.typesystem.runtime.IsApplicableStatus; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations; import jetbrains.mps.typechecking.TypecheckingFacade; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations; import jetbrains.mps.errors.messageTargets.MessageTarget; import jetbrains.mps.errors.messageTargets.NodeMessageTarget; import jetbrains.mps.errors.IErrorReporter; import org.jetbrains.mps.openapi.language.SAbstractConcept; import org.jetbrains.mps.openapi.language.SConcept; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; import org.jetbrains.mps.openapi.language.SContainmentLink; public class check_AbstractSetOperation_NonTypesystemRule extends AbstractNonTypesystemRule_Runtime implements NonTypesystemRule_Runtime { public check_AbstractSetOperation_NonTypesystemRule() { } public void applyRule(final SNode aso, final TypeCheckingContext typeCheckingContext, IsApplicableStatus status) { if (!(SNodeOperations.isInstanceOf(SNodeOperations.getParent(aso), CONCEPTS.DotExpression$yW) && (TypecheckingFacade.getFromContext().strongCoerceType(TypecheckingFacade.getFromContext().getTypeOf(SLinkOperations.getTarget(SNodeOperations.cast(SNodeOperations.getParent(aso), CONCEPTS.DotExpression$yW), LINKS.operand$w6IR)), CONCEPTS.SetType$g6) != null))) { final MessageTarget errorTarget = new NodeMessageTarget(); IErrorReporter _reporter_2309309498 = typeCheckingContext.reportTypeError(aso, "not available here", "r:00000000-0000-4000-0000-011c8959032b(jetbrains.mps.baseLanguage.collections.typesystem)", "4998595809121278530", null, errorTarget); } } public SAbstractConcept getApplicableConcept() { return CONCEPTS.AbstractSetOperation$rD; } public IsApplicableStatus isApplicableAndPattern(SNode argument) { return new IsApplicableStatus(argument.getConcept().isSubConceptOf(getApplicableConcept()), null); } public boolean overrides() { return false; } private static final class CONCEPTS { /*package*/ static final SConcept DotExpression$yW = MetaAdapterFactory.getConcept(0xf3061a5392264cc5L, 0xa443f952ceaf5816L, 0x116b46a08c4L, "jetbrains.mps.baseLanguage.structure.DotExpression"); /*package*/ static final SConcept SetType$g6 = MetaAdapterFactory.getConcept(0x8388864671ce4f1cL, 0x9c53c54016f6ad4fL, 0x11d91cbbcd0L, "jetbrains.mps.baseLanguage.collections.structure.SetType"); /*package*/ static final SConcept AbstractSetOperation$rD = MetaAdapterFactory.getConcept(0x8388864671ce4f1cL, 0x9c53c54016f6ad4fL, 0x11d95148c3eL, "jetbrains.mps.baseLanguage.collections.structure.AbstractSetOperation"); } private static final class LINKS { /*package*/ static final SContainmentLink operand$w6IR = MetaAdapterFactory.getContainmentLink(0xf3061a5392264cc5L, 0xa443f952ceaf5816L, 0x116b46a08c4L, 0x116b46a4416L, "operand"); } }
3e171fc41f09a82e218f88698c949f6b136585a8
1,297
java
Java
metadata-jobs/mae-consumer-job/src/main/java/com/linkedin/metadata/kafka/hydrator/HydratorFactory.java
sunkickr/datahub
5ed410635d033a6dbbab1cd19c24a83ce3c9262c
[ "Apache-2.0" ]
null
null
null
metadata-jobs/mae-consumer-job/src/main/java/com/linkedin/metadata/kafka/hydrator/HydratorFactory.java
sunkickr/datahub
5ed410635d033a6dbbab1cd19c24a83ce3c9262c
[ "Apache-2.0" ]
3
2022-02-14T13:39:45.000Z
2022-02-27T17:32:49.000Z
metadata-jobs/mae-consumer-job/src/main/java/com/linkedin/metadata/kafka/hydrator/HydratorFactory.java
sunkickr/datahub
5ed410635d033a6dbbab1cd19c24a83ce3c9262c
[ "Apache-2.0" ]
null
null
null
37.057143
84
0.784888
9,856
package com.linkedin.metadata.kafka.hydrator; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.linkedin.restli.client.Client; import java.util.HashMap; import java.util.Map; import java.util.Optional; public class HydratorFactory { private final Client _restliClient; private final Map<EntityType, Hydrator> _hydratorMap; public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); public HydratorFactory(Client restliClient) { _restliClient = restliClient; _hydratorMap = new HashMap<>(); _hydratorMap.put(EntityType.DATASET, new DatasetHydrator()); _hydratorMap.put(EntityType.CHART, new ChartHydrator(_restliClient)); _hydratorMap.put(EntityType.DASHBOARD, new DashboardHydrator(_restliClient)); _hydratorMap.put(EntityType.DATA_JOB, new DataJobHydrator(_restliClient)); _hydratorMap.put(EntityType.DATA_FLOW, new DataFlowHydrator(_restliClient)); _hydratorMap.put(EntityType.CORP_USER, new CorpUserHydrator(_restliClient)); } public Optional<ObjectNode> getHydratedEntity(EntityType entityType, String urn) { if (!_hydratorMap.containsKey(entityType)) { return Optional.empty(); } return _hydratorMap.get(entityType).getHydratedEntity(urn); } }
3e1720769f00e551a974a33041b53737830bfd54
3,534
java
Java
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/filesystem/stream/PartitionCommitPredicate.java
wgzhao/flink
6af0b9965293cb732a540b9364b6aae76a9b356a
[ "Apache-2.0" ]
9
2016-09-22T22:53:13.000Z
2019-11-30T03:07:29.000Z
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/filesystem/stream/PartitionCommitPredicate.java
wgzhao/flink
6af0b9965293cb732a540b9364b6aae76a9b356a
[ "Apache-2.0" ]
5
2021-12-14T22:02:04.000Z
2022-03-14T11:49:24.000Z
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/filesystem/stream/PartitionCommitPredicate.java
wgzhao/flink
6af0b9965293cb732a540b9364b6aae76a9b356a
[ "Apache-2.0" ]
1
2022-01-12T17:13:55.000Z
2022-01-12T17:13:55.000Z
34.990099
105
0.677702
9,857
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.table.filesystem.stream; import org.apache.flink.configuration.Configuration; import org.apache.flink.table.filesystem.FileSystemConnectorOptions.PartitionCommitTriggerType; import java.util.List; import static org.apache.flink.table.filesystem.FileSystemConnectorOptions.SINK_PARTITION_COMMIT_TRIGGER; /** * Partition commit predicate. See {@link PartitionTimeCommitPredicate}. See {@link * ProcTimeCommitPredicate} */ public interface PartitionCommitPredicate { boolean isPartitionCommittable(PredicateContext predicateContext); /** * Context that {@link PartitionCommitPredicate} can use for getting context about a partition. */ interface PredicateContext { /** Return the partition. */ String partition(); /** Return the creation time of the partition. */ long createProcTime(); /** Return the current process time. */ long currentProcTime(); /** Returns the current event-time watermark. */ long currentWatermark(); } static PredicateContext createPredicateContext( String partition, long createProcTime, long currentProcTime, long currentWatermark) { return new PredicateContext() { @Override public String partition() { return partition; } @Override public long createProcTime() { return createProcTime; } @Override public long currentProcTime() { return currentProcTime; } @Override public long currentWatermark() { return currentWatermark; } }; } static PartitionCommitPredicate createPartitionTimeCommitPredicate( Configuration conf, ClassLoader cl, List<String> partitionKeys) { return new PartitionTimeCommitPredicate(conf, cl, partitionKeys); } static PartitionCommitPredicate createProcTimeCommitPredicate(Configuration conf) { return new ProcTimeCommitPredicate(conf); } static PartitionCommitPredicate create( Configuration conf, ClassLoader cl, List<String> partitionKeys) { PartitionCommitTriggerType trigger = conf.get(SINK_PARTITION_COMMIT_TRIGGER); switch (trigger) { case PARTITION_TIME: return createPartitionTimeCommitPredicate(conf, cl, partitionKeys); case PROCESS_TIME: return createProcTimeCommitPredicate(conf); default: throw new UnsupportedOperationException( "Unsupported partition commit predicate: " + trigger); } } }
3e1720be3836cd108b64e72ff7b8520c7b9ccdde
2,053
java
Java
SurveyorCore/src/main/java/org/wwarn/surveyor/client/event/DataUpdatedEvent.java
WorldwideAntimalarialResistanceNetwork/WWARN-Maps-Surveyor
506651a5ef54a9e4a7511d5e80d301de4a4ac919
[ "BSD-3-Clause" ]
5
2015-01-20T13:53:53.000Z
2018-03-22T12:02:35.000Z
SurveyorCore/src/main/java/org/wwarn/surveyor/client/event/DataUpdatedEvent.java
WorldwideAntimalarialResistanceNetwork/WWARN-Maps-Surveyor
506651a5ef54a9e4a7511d5e80d301de4a4ac919
[ "BSD-3-Clause" ]
5
2015-05-26T14:28:53.000Z
2021-07-31T18:37:30.000Z
SurveyorCore/src/main/java/org/wwarn/surveyor/client/event/DataUpdatedEvent.java
WorldwideAntimalarialResistanceNetwork/WWARN-Maps-Surveyor
506651a5ef54a9e4a7511d5e80d301de4a4ac919
[ "BSD-3-Clause" ]
5
2015-05-26T13:53:25.000Z
2017-06-08T07:55:42.000Z
41.897959
93
0.758889
9,858
package org.wwarn.surveyor.client.event; /* * #%L * SurveyorCore * %% * Copyright (C) 2013 - 2014 University of Oxford * %% * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the University of Oxford nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * #L% */ import com.google.web.bindery.event.shared.binder.GenericEvent; import org.wwarn.surveyor.client.core.QueryResult; /** * An event to capture that the underlying data has been updated on the server * This can be used to inform end users that the browser needs reloading to show updated data */ public class DataUpdatedEvent extends GenericEvent { public DataUpdatedEvent() { } }
3e17212afe730e9c74a6c08085ee23694849bf21
1,891
java
Java
sdk/network/mgmt-v2019_09_01/src/main/java/com/microsoft/azure/management/network/v2019_09_01/ManagedRuleOverride.java
yiliuTo/azure-sdk-for-java
4536b6e99ded1b2b77f79bc2c31f42566c97b704
[ "MIT" ]
3
2021-09-15T16:25:19.000Z
2021-12-17T05:41:00.000Z
sdk/network/mgmt-v2019_09_01/src/main/java/com/microsoft/azure/management/network/v2019_09_01/ManagedRuleOverride.java
yiliuTo/azure-sdk-for-java
4536b6e99ded1b2b77f79bc2c31f42566c97b704
[ "MIT" ]
306
2019-09-27T06:41:56.000Z
2019-10-14T08:19:57.000Z
sdk/network/mgmt-v2019_09_01/src/main/java/com/microsoft/azure/management/network/v2019_09_01/ManagedRuleOverride.java
yiliuTo/azure-sdk-for-java
4536b6e99ded1b2b77f79bc2c31f42566c97b704
[ "MIT" ]
1
2022-01-31T19:22:33.000Z
2022-01-31T19:22:33.000Z
26.633803
127
0.656795
9,859
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2019_09_01; import com.fasterxml.jackson.annotation.JsonProperty; /** * Defines a managed rule group override setting. */ public class ManagedRuleOverride { /** * Identifier for the managed rule. */ @JsonProperty(value = "ruleId", required = true) private String ruleId; /** * Describes the state of the managed rule. Defaults to Disabled if not * specified. Possible values include: 'Disabled'. */ @JsonProperty(value = "state") private ManagedRuleEnabledState state; /** * Get identifier for the managed rule. * * @return the ruleId value */ public String ruleId() { return this.ruleId; } /** * Set identifier for the managed rule. * * @param ruleId the ruleId value to set * @return the ManagedRuleOverride object itself. */ public ManagedRuleOverride withRuleId(String ruleId) { this.ruleId = ruleId; return this; } /** * Get describes the state of the managed rule. Defaults to Disabled if not specified. Possible values include: 'Disabled'. * * @return the state value */ public ManagedRuleEnabledState state() { return this.state; } /** * Set describes the state of the managed rule. Defaults to Disabled if not specified. Possible values include: 'Disabled'. * * @param state the state value to set * @return the ManagedRuleOverride object itself. */ public ManagedRuleOverride withState(ManagedRuleEnabledState state) { this.state = state; return this; } }
3e17212e219161ad9bebfe52078f475565054ad4
1,548
java
Java
reference-services/order-service/src/main/java/net/safedata/microservices/training/order/adapters/MessageProducer.java
ovidel78/microservices-training
18c7d93aec0436634d0d6114bfdde791be7b2911
[ "Apache-2.0" ]
null
null
null
reference-services/order-service/src/main/java/net/safedata/microservices/training/order/adapters/MessageProducer.java
ovidel78/microservices-training
18c7d93aec0436634d0d6114bfdde791be7b2911
[ "Apache-2.0" ]
null
null
null
reference-services/order-service/src/main/java/net/safedata/microservices/training/order/adapters/MessageProducer.java
ovidel78/microservices-training
18c7d93aec0436634d0d6114bfdde791be7b2911
[ "Apache-2.0" ]
null
null
null
41.837838
100
0.786822
9,860
package net.safedata.microservices.training.order.adapters; import net.safedata.microservices.training.order.channels.OutboundChannels; import net.safedata.microservices.training.order.events.OrderCreatedEvent; import net.safedata.microservices.training.order.marker.OutboundAdapter; import net.safedata.microservices.training.order.ports.MessagingOutboundPort; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.support.MessageBuilder; import org.springframework.stereotype.Component; import org.springframework.util.MimeTypeUtils; @Component @EnableBinding(OutboundChannels.class) public class MessageProducer implements MessagingOutboundPort, OutboundAdapter { private final OutboundChannels outboundChannels; @Autowired public MessageProducer(final OutboundChannels outboundChannels) { this.outboundChannels = outboundChannels; } public void publishEvent(final OrderCreatedEvent orderCreatedEvent) { outboundChannels.orders() .send(createMessage(orderCreatedEvent)); } private Message<?> createMessage(final OrderCreatedEvent orderCreatedEvent) { return MessageBuilder.withPayload(orderCreatedEvent) .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON) .build(); } }
3e1721dfa622453fc4136f6f28931e9521f1b254
1,587
java
Java
modules/core/src/main/java/org/apache/ignite/internal/binary/streams/BinaryStream.java
liyuj/gridgain
9505c0cfd7235210993b2871b17f15acf7d3dcd4
[ "CC0-1.0" ]
218
2015-01-04T13:20:55.000Z
2022-03-28T05:28:55.000Z
modules/core/src/main/java/org/apache/ignite/internal/binary/streams/BinaryStream.java
liyuj/gridgain
9505c0cfd7235210993b2871b17f15acf7d3dcd4
[ "CC0-1.0" ]
175
2015-02-04T23:16:56.000Z
2022-03-28T18:34:24.000Z
modules/core/src/main/java/org/apache/ignite/internal/binary/streams/BinaryStream.java
liyuj/gridgain
9505c0cfd7235210993b2871b17f15acf7d3dcd4
[ "CC0-1.0" ]
93
2015-01-06T20:54:23.000Z
2022-03-31T08:09:00.000Z
25.190476
111
0.650914
9,861
/* * Copyright 2019 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.binary.streams; /** * Binary stream. */ public interface BinaryStream { /** * @return Position. */ public int position(); /** * @param pos Position. */ public void position(int pos); /** * @return Underlying array. */ public byte[] array(); /** * @return Copy of data in the stream. */ public byte[] arrayCopy(); /** * @return Offheap pointer if stream is offheap based and "forceHeap" flag is not set; otherwise {@code 0}. */ public long offheapPointer(); /** * @return Offheap pointer if stream is offheap based; otherwise {@code 0}. */ public long rawOffheapPointer(); /** * @return {@code True} is stream is array based. */ public boolean hasArray(); /** * @return Total capacity. */ public int capacity(); }
3e17223d67c06212868fe5046f5f47e93e111db8
866
java
Java
src/main/java/com/bosssoft/pay/sdk/core/internal/validation/ValidationResult.java
chenchaolei/sdk-core
31713f625cc9eb7e430a84c7db250e50aeb18b62
[ "Apache-2.0" ]
2
2020-02-05T03:49:02.000Z
2020-02-05T03:49:06.000Z
src/main/java/com/bosssoft/pay/sdk/core/internal/validation/ValidationResult.java
chenchaolei/sdk-core
31713f625cc9eb7e430a84c7db250e50aeb18b62
[ "Apache-2.0" ]
4
2020-04-23T20:30:17.000Z
2021-12-09T21:59:00.000Z
src/main/java/com/bosssoft/pay/sdk/core/internal/validation/ValidationResult.java
chenchaolei/sdk-core
31713f625cc9eb7e430a84c7db250e50aeb18b62
[ "Apache-2.0" ]
null
null
null
19.818182
92
0.581422
9,862
package com.bosssoft.pay.sdk.core.internal.validation; import java.util.Map; /** * @Title 校验结果 * @Description * @Author 陈超雷(ychag@example.com) * @Date 2019/01/05 */ public class ValidationResult { /** * 是否有错误 */ private boolean hasErrors; /** * 校验错误信息 */ private Map<String, String> errorMsg; public boolean hasErrors() { return hasErrors; } public void setHasErrors(boolean hasErrors) { this.hasErrors = hasErrors; } public Map<String, String> getErrorMsg() { return errorMsg; } public void setErrorMsg(Map<String, String> errorMsg) { this.errorMsg = errorMsg; } @Override public String toString() { return "ValidationResult [hasErrors=" + hasErrors + ", errorMsg=" + errorMsg + "]"; } }
3e1722d8d8a6593f957a62a50117a43b518c668d
3,511
java
Java
aliyun-java-sdk-ahas-openapi/src/main/java/com/aliyuncs/ahas_openapi/transform/v20190901/CreateHotParamRuleResponseUnmarshaller.java
cctvzd7/aliyun-openapi-java-sdk
b8e4dce2a61ca968615c9b910bedebaea71781ae
[ "Apache-2.0" ]
1
2022-02-12T06:01:36.000Z
2022-02-12T06:01:36.000Z
aliyun-java-sdk-ahas-openapi/src/main/java/com/aliyuncs/ahas_openapi/transform/v20190901/CreateHotParamRuleResponseUnmarshaller.java
cctvzd7/aliyun-openapi-java-sdk
b8e4dce2a61ca968615c9b910bedebaea71781ae
[ "Apache-2.0" ]
27
2021-06-11T21:08:40.000Z
2022-03-11T21:25:09.000Z
aliyun-java-sdk-ahas-openapi/src/main/java/com/aliyuncs/ahas_openapi/transform/v20190901/CreateHotParamRuleResponseUnmarshaller.java
cctvzd7/aliyun-openapi-java-sdk
b8e4dce2a61ca968615c9b910bedebaea71781ae
[ "Apache-2.0" ]
1
2020-03-05T07:30:16.000Z
2020-03-05T07:30:16.000Z
55.730159
135
0.813159
9,863
/* * 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.aliyuncs.ahas_openapi.transform.v20190901; import java.util.ArrayList; import java.util.List; import com.aliyuncs.ahas_openapi.model.v20190901.CreateHotParamRuleResponse; import com.aliyuncs.ahas_openapi.model.v20190901.CreateHotParamRuleResponse.Data; import com.aliyuncs.ahas_openapi.model.v20190901.CreateHotParamRuleResponse.Data.ParamFlowItemListItem; import com.aliyuncs.transform.UnmarshallerContext; public class CreateHotParamRuleResponseUnmarshaller { public static CreateHotParamRuleResponse unmarshall(CreateHotParamRuleResponse createHotParamRuleResponse, UnmarshallerContext _ctx) { createHotParamRuleResponse.setRequestId(_ctx.stringValue("CreateHotParamRuleResponse.RequestId")); createHotParamRuleResponse.setCode(_ctx.stringValue("CreateHotParamRuleResponse.Code")); createHotParamRuleResponse.setMessage(_ctx.stringValue("CreateHotParamRuleResponse.Message")); createHotParamRuleResponse.setSuccess(_ctx.booleanValue("CreateHotParamRuleResponse.Success")); Data data = new Data(); data.setAppName(_ctx.stringValue("CreateHotParamRuleResponse.Data.AppName")); data.setBurstCount(_ctx.integerValue("CreateHotParamRuleResponse.Data.BurstCount")); data.setControlBehavior(_ctx.integerValue("CreateHotParamRuleResponse.Data.ControlBehavior")); data.setThreshold(_ctx.floatValue("CreateHotParamRuleResponse.Data.Threshold")); data.setStatDurationSec(_ctx.longValue("CreateHotParamRuleResponse.Data.StatDurationSec")); data.setEnable(_ctx.booleanValue("CreateHotParamRuleResponse.Data.Enable")); data.setMetricType(_ctx.integerValue("CreateHotParamRuleResponse.Data.MetricType")); data.setRuleId(_ctx.longValue("CreateHotParamRuleResponse.Data.RuleId")); data.setMaxQueueingTimeMs(_ctx.integerValue("CreateHotParamRuleResponse.Data.MaxQueueingTimeMs")); data.setNamespace(_ctx.stringValue("CreateHotParamRuleResponse.Data.Namespace")); data.setParamIdx(_ctx.integerValue("CreateHotParamRuleResponse.Data.ParamIdx")); data.setResource(_ctx.stringValue("CreateHotParamRuleResponse.Data.Resource")); List<ParamFlowItemListItem> paramFlowItemList = new ArrayList<ParamFlowItemListItem>(); for (int i = 0; i < _ctx.lengthValue("CreateHotParamRuleResponse.Data.ParamFlowItemList.Length"); i++) { ParamFlowItemListItem paramFlowItemListItem = new ParamFlowItemListItem(); paramFlowItemListItem.setItemType(_ctx.stringValue("CreateHotParamRuleResponse.Data.ParamFlowItemList["+ i +"].ItemType")); paramFlowItemListItem.setThreshold(_ctx.floatValue("CreateHotParamRuleResponse.Data.ParamFlowItemList["+ i +"].Threshold")); paramFlowItemListItem.setItemValue(_ctx.stringValue("CreateHotParamRuleResponse.Data.ParamFlowItemList["+ i +"].ItemValue")); paramFlowItemList.add(paramFlowItemListItem); } data.setParamFlowItemList(paramFlowItemList); createHotParamRuleResponse.setData(data); return createHotParamRuleResponse; } }
3e17254e0bc2b94f27dc1eb91ecbc82f46c3d7f4
720
java
Java
latest/src/test/java8/br/com/objectos/latest/processor/CompilationHelperJava8.java
objectos/incubator
881fa1c0eb364be98a627d5072b473d334279027
[ "Apache-2.0" ]
null
null
null
latest/src/test/java8/br/com/objectos/latest/processor/CompilationHelperJava8.java
objectos/incubator
881fa1c0eb364be98a627d5072b473d334279027
[ "Apache-2.0" ]
null
null
null
latest/src/test/java8/br/com/objectos/latest/processor/CompilationHelperJava8.java
objectos/incubator
881fa1c0eb364be98a627d5072b473d334279027
[ "Apache-2.0" ]
null
null
null
34.285714
75
0.756944
9,864
/* * Copyright (C) 2020-2022 Objectos Software LTDA. * * 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 br.com.objectos.latest.processor; class CompilationHelperJava8 extends CompilationHelperJava7 { }
3e172551c024e858f1267f6dc539a3f5e7a5ef64
2,793
java
Java
easybatch-xml/src/test/java/org/easybatch/xml/MultiXmlFileRecordReaderTest.java
raulgomis/easy-batch
66f35966683f7cf2c54ce7c3dd3efa4db102241e
[ "MIT" ]
1
2019-04-19T08:03:14.000Z
2019-04-19T08:03:14.000Z
easybatch-xml/src/test/java/org/easybatch/xml/MultiXmlFileRecordReaderTest.java
liujiaqiang/easy-batch
46286e1091dae1206674e2a30e0609c31feae36c
[ "MIT" ]
null
null
null
easybatch-xml/src/test/java/org/easybatch/xml/MultiXmlFileRecordReaderTest.java
liujiaqiang/easy-batch
46286e1091dae1206674e2a30e0609c31feae36c
[ "MIT" ]
null
null
null
37.905405
119
0.707665
9,865
/** * The MIT License * * Copyright (c) 2019, Mahmoud Ben Hassine (efpyi@example.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.easybatch.xml; import org.easybatch.core.job.Job; import org.easybatch.core.job.JobBuilder; import org.easybatch.core.job.JobExecutor; import org.easybatch.core.processor.RecordCollector; import org.easybatch.core.record.Record; import org.junit.Test; import java.io.File; import java.io.FilenameFilter; import java.util.Arrays; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class MultiXmlFileRecordReaderTest { @Test public void allResourcesShouldBeReadInOneShot() throws Exception { // given File dir = new File("src/test/resources"); File[] files = dir.listFiles(new XmlFileFilter()); MultiXmlFileRecordReader multiFileRecordReader = new MultiXmlFileRecordReader(Arrays.asList(files), "website"); RecordCollector recordCollector = new RecordCollector(); Job job = JobBuilder.aNewJob() .reader(multiFileRecordReader) .processor(recordCollector) .build(); // when JobExecutor jobExecutor = new JobExecutor(); jobExecutor.execute(job); jobExecutor.shutdown(); List<Record> records = recordCollector.getRecords(); // then // there are 6 records in xml files starting with "web" inside "src/test/resources" assertThat(records).hasSize(6); } private class XmlFileFilter implements FilenameFilter { @Override public boolean accept(File dir, String name) { return name.startsWith("web") && name.endsWith("xml"); } } }
3e1725588ea246039a285d8dbfa3e07a477dce08
2,514
java
Java
SpringMVC_06_Book/src/main/java/com/veryoo/controller/LoginController.java
oubijie/SpringMVC
704ea13ddd8002baa9fc3611eb3370d42bdda9c9
[ "Apache-2.0" ]
null
null
null
SpringMVC_06_Book/src/main/java/com/veryoo/controller/LoginController.java
oubijie/SpringMVC
704ea13ddd8002baa9fc3611eb3370d42bdda9c9
[ "Apache-2.0" ]
5
2020-03-04T22:40:34.000Z
2021-01-21T00:14:56.000Z
SpringMVC_06_Book/src/main/java/com/veryoo/controller/LoginController.java
oubijie/SpringMVC
704ea13ddd8002baa9fc3611eb3370d42bdda9c9
[ "Apache-2.0" ]
null
null
null
27.626374
91
0.6965
9,866
package com.veryoo.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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.ResponseBody; import com.veryoo.entity.User; import com.veryoo.service.UserService; @Controller public class LoginController { @Autowired private UserService userService; @RequestMapping(value = "/login", method = RequestMethod.GET) public String login() { return "login"; } @RequestMapping(value = "/login", method = RequestMethod.POST) public String login(String username, String password, Model model, HttpSession session) { User user = userService.getUserByUsername(username); if(user == null) { model.addAttribute("errMsg", "用户不存在!"); return "login"; }else if(!user.getPassword().equals(password)) { model.addAttribute("errMsg", "密码不正确!"); return "login"; }else { session.setAttribute("loginUser", user); return "redirect:/book/list"; } } @RequestMapping(value = "/register", method = RequestMethod.GET) public String register() { return "register"; } @RequestMapping(value = "/register", method = RequestMethod.POST) public String register(User user, String password2) { System.out.println("============注册用户"); return "register"; } @RequestMapping(value = "/exists") @ResponseBody public Map<String, Boolean> exists(String username) { System.out.println("正在检查用户名是否存在:" + username); User user = userService.getUserByUsername(username); Map<String, Boolean> result = new HashMap<String, Boolean>(); if(user == null) { result.put("exists", false); }else { result.put("exists", true); } return result; } @RequestMapping(value = "/exists2") @ResponseBody public Map<String, Boolean> exists2(@RequestBody String username) { System.out.println("正在检查用户名是否存在:" + username); User user = userService.getUserByUsername(username); Map<String, Boolean> result = new HashMap<String, Boolean>(); if(user == null) { result.put("exists", false); }else { result.put("exists", true); } return result; } }
3e1726bc0dc9ed91c54ef5c80a6393293efe4c5e
1,540
java
Java
engine/src/main/java/com/msopentech/odatajclient/engine/data/ODataError.java
mkostin/ODataJClient
90d9ce3b2fa35575961b7d0b30605eb855f6557a
[ "Apache-2.0" ]
6
2017-02-17T09:41:12.000Z
2021-03-01T23:23:44.000Z
sdk/office365-mail-calendar-contact-sdk/odata/engine/src/main/java/com/msopentech/odatajclient/engine/data/ODataError.java
sunsun1988/Office-365-SDK-for-Android
b97be3450c76cafc5d1d00d37ae5b2271e6925cc
[ "Apache-2.0" ]
null
null
null
sdk/office365-mail-calendar-contact-sdk/odata/engine/src/main/java/com/msopentech/odatajclient/engine/data/ODataError.java
sunsun1988/Office-365-SDK-for-Android
b97be3450c76cafc5d1d00d37ae5b2271e6925cc
[ "Apache-2.0" ]
10
2016-07-20T01:37:02.000Z
2020-12-09T20:55:54.000Z
22.318841
72
0.637662
9,867
/** * Copyright © Microsoft Open Technologies, Inc. * * 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 * * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. * * See the Apache License, Version 2.0 for the specific language * governing permissions and limitations under the License. */ package com.msopentech.odatajclient.engine.data; /** * OData error. */ public interface ODataError { /** * Gets error code. * * @return error code. */ String getCode(); /** * Gets error message language. * * @return error message language. */ String getMessageLang(); /** * Gets error message. * * @return error message. */ String getMessageValue(); /** * Gets inner error message. * * @return inner error message. */ String getInnerErrorMessage(); /** * Gets inner error type. * * @return inner error type. */ String getInnerErrorType(); /** * Gets inner error stack-trace. * * @return inner error stack-trace */ String getInnerErrorStacktrace(); }
3e172731662b0262f2a5708b01387f77d0a995f8
557
java
Java
discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/constant/StrategyConstant.java
shenzlly/Discovery
809c92177a1cea3652ccd06c4d09f53691e95df6
[ "Apache-2.0" ]
1
2018-09-14T08:05:58.000Z
2018-09-14T08:05:58.000Z
discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/constant/StrategyConstant.java
zsjzero/Discovery
ee0f5ad095df79e24ff5bc0eff1240d3af514d17
[ "Apache-2.0" ]
null
null
null
discovery-plugin-strategy/src/main/java/com/nepxion/discovery/plugin/strategy/constant/StrategyConstant.java
zsjzero/Discovery
ee0f5ad095df79e24ff5bc0eff1240d3af514d17
[ "Apache-2.0" ]
1
2018-09-21T15:35:37.000Z
2018-09-21T15:35:37.000Z
37.133333
147
0.768402
9,868
package com.nepxion.discovery.plugin.strategy.constant; /** * <p>Title: Nepxion Discovery</p> * <p>Description: Nepxion Discovery</p> * <p>Copyright: Copyright (c) 2017-2050</p> * <p>Company: Nepxion</p> * @author Haojun Ren * @version 1.0 */ public class StrategyConstant { public static final String SPRING_APPLICATION_STRATEGY_CONTROL_ENABLED = "spring.application.strategy.control.enabled"; public static final String SPRING_APPLICATION_STRATEGY_ZONE_AVOIDANCE_RULE_ENABLED = "spring.application.strategy.zone.avoidance.rule.enabled"; }
3e1727c0e1b1a3bb8d0080c8724ef50603daed2f
2,313
java
Java
Learning/Thinking_in_Java_4th_Edition/Help/AntVersionSkip.java
banbao990/Java
e2bb57951f1f00c95b91d1ad8910e83434e42e01
[ "MIT" ]
1
2020-05-31T03:00:15.000Z
2020-05-31T03:00:15.000Z
Learning/Thinking_in_Java_4th_Edition/Help/AntVersionSkip.java
banbao990/Java
e2bb57951f1f00c95b91d1ad8910e83434e42e01
[ "MIT" ]
null
null
null
Learning/Thinking_in_Java_4th_Edition/Help/AntVersionSkip.java
banbao990/Java
e2bb57951f1f00c95b91d1ad8910e83434e42e01
[ "MIT" ]
null
null
null
25.417582
71
0.431042
9,869
/** * @author banbao * @comment 修改自示例代码 */ import java.io.*; import java.util.ArrayList; import java.util.List; public class AntVersionSkip { private static String regex; public static final String detect = "<fail message=\"J2SE5 required\" unless=\"version1.5\"/>"; public static void main(String...args) { // default String strPath = ".." + File.separator; regex = ".*\\.xml"; // walk File path = new File(strPath); walk(path); } public static void walk(File dir) { // 不加入文件夹 File[] files = dir.listFiles(); if(files == null) return; // 空文件夹 for(File now : files) { if(now.isDirectory()) { walk(now); } else { String simpleName = now.getName(); if(simpleName.matches(regex)) { // deal skip(now.getAbsolutePath()); } } } } private static void skip(String now) { List<String> list = new ArrayList<>(); // file File file = new File(now); // input BufferedReader br = null; try { br = new BufferedReader( new FileReader(now)); String line; while((line = br.readLine()) != null) { if(detect.equals(line.trim())){ line = "<!--" + line + "-->"; } list.add(line); } } catch(IOException e) { e.printStackTrace(); } finally { try{ br.close(); } catch(IOException e) { e.printStackTrace(); } } // delete file.delete(); // output BufferedWriter bw = null; try { bw = new BufferedWriter( new FileWriter(now)); for(String line : list) { bw.write(line); bw.write("\n"); } } catch(IOException e) { e.printStackTrace(); } finally { try{ bw.close(); } catch(IOException e) { e.printStackTrace(); } } } } /* Output */
3e172845440312502b63b9cabd0758522ca014fb
1,027
java
Java
src/main/java/excel/util/Utils.java
CPyeah/algorithms-and-data-structures
6f4ac2374c6fda87a8fb3da53acd1fdcaa843856
[ "Apache-2.0" ]
null
null
null
src/main/java/excel/util/Utils.java
CPyeah/algorithms-and-data-structures
6f4ac2374c6fda87a8fb3da53acd1fdcaa843856
[ "Apache-2.0" ]
null
null
null
src/main/java/excel/util/Utils.java
CPyeah/algorithms-and-data-structures
6f4ac2374c6fda87a8fb3da53acd1fdcaa843856
[ "Apache-2.0" ]
null
null
null
20.137255
80
0.472249
9,870
package excel.util; public class Utils { public static float getSimilarityRatio(String str, String target) { if (str.equals(target)) { return 100; } int d[][]; // 矩阵 int n = str.length(); int m = target.length(); int i; // 遍历str的 int j; // 遍历target的 char ch1; // str的 char ch2; // target的 int temp; // 记录相同字符,在某个矩阵位置值的增量,不是0就是1 if (n == 0 || m == 0) { return 0; } d = new int[n + 1][m + 1]; for (i = 0; i <= n; i++) { // 初始化第一列 d[i][0] = i; } for (j = 0; j <= m; j++) { // 初始化第一行 d[0][j] = j; } for (i = 1; i <= n; i++) { // 遍历str ch1 = str.charAt(i - 1); // 去匹配target for (j = 1; j <= m; j++) { ch2 = target.charAt(j - 1); if (ch1 == ch2 || ch1 == ch2 + 32 || ch1 + 32 == ch2) { temp = 0; } else { temp = 1; } // 左边+1,上边+1, 左上角+temp取最小 d[i][j] = Math .min(Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1), d[i - 1][j - 1] + temp); } } return (1 - (float) d[n][m] / Math.max(str.length(), target.length())) * 100F; } }
3e17286e9644193b6fe0de7f54fd349982438c22
434
java
Java
spring-boot-2-test-by-howtodoinjava/1_test-springboot/src/test/java/spring/boot/_2/test/by/howtodoinjava/springboot/_2_unit_test_with_springboottest/MyTestConfiguration.java
shijiansu/spring-boot
6d7821f65e9a59f4d621e69385dbf152a86fc102
[ "MIT" ]
null
null
null
spring-boot-2-test-by-howtodoinjava/1_test-springboot/src/test/java/spring/boot/_2/test/by/howtodoinjava/springboot/_2_unit_test_with_springboottest/MyTestConfiguration.java
shijiansu/spring-boot
6d7821f65e9a59f4d621e69385dbf152a86fc102
[ "MIT" ]
2
2020-07-31T02:30:18.000Z
2020-10-06T17:11:06.000Z
spring-boot-2-test-by-howtodoinjava/1_test-springboot/src/test/java/spring/boot/_2/test/by/howtodoinjava/springboot/_2_unit_test_with_springboottest/MyTestConfiguration.java
shijiansu/spring-boot
6d7821f65e9a59f4d621e69385dbf152a86fc102
[ "MIT" ]
null
null
null
28.933333
89
0.81106
9,871
package spring.boot._2.test.by.howtodoinjava.springboot._2_unit_test_with_springboottest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import spring.boot._2.test.by.howtodoinjava.springboot.EmployeeHelper; @TestConfiguration public class MyTestConfiguration { @Bean // bean name is "helper" EmployeeHelper helper() { return new EmployeeHelper(); } }
3e1728888c904b026feac55a2da962d1bf6d0122
2,288
java
Java
src/main/java/net/jforum/dao/sqlserver/SqlServerModerationLogDAO.java
f450/jforum2
7cd29754e0b4a462a1d14115d181a55636e7aacb
[ "BSD-3-Clause" ]
null
null
null
src/main/java/net/jforum/dao/sqlserver/SqlServerModerationLogDAO.java
f450/jforum2
7cd29754e0b4a462a1d14115d181a55636e7aacb
[ "BSD-3-Clause" ]
68
2020-07-05T22:46:49.000Z
2022-02-16T01:12:19.000Z
src/main/java/net/jforum/dao/sqlserver/SqlServerModerationLogDAO.java
honglouleiyan/jfoum2
9c621cc406213edeaf286f60b7dd6d28075a87b5
[ "BSD-3-Clause" ]
null
null
null
35.75
86
0.716783
9,872
/* * Copyright (c) JForum Team * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * 1) Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * 2) Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or * other materials provided with the distribution. * 3) Neither the name of "Rafael Steil" nor * the names of its contributors may be used to endorse * or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE * * Created on 2009/7/29 10:04:03 AM * The JForum Project * http://www.jforum.net */ package net.jforum.dao.sqlserver; import java.util.List; import net.jforum.dao.generic.GenericModerationLogDAO; import net.jforum.entities.ModerationLog; /** * @author Andowson Chang * @version $Id$ */ public class SqlServerModerationLogDAO extends GenericModerationLogDAO { /** * @see net.jforum.dao.generic.GenericModerationLogDAO#selectAll(int, int) */ @Override public List<ModerationLog> selectAll(final int start, final int count) { return super.selectAll(start, start + count); } }
3e1729ca913dbb17d3fbb02baba52aeee6d1afdb
557
java
Java
src/main/Java/com/czj/service/PersonService.java
czonesoft/JTestWeb
780338b814ed86e10f29db417665864045194f03
[ "Apache-2.0" ]
null
null
null
src/main/Java/com/czj/service/PersonService.java
czonesoft/JTestWeb
780338b814ed86e10f29db417665864045194f03
[ "Apache-2.0" ]
null
null
null
src/main/Java/com/czj/service/PersonService.java
czonesoft/JTestWeb
780338b814ed86e10f29db417665864045194f03
[ "Apache-2.0" ]
null
null
null
21.423077
79
0.648115
9,873
package com.czj.service; import com.czj.model.Person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class PersonService { @Autowired Person person; public PersonService(){ System.out.println("PersonService Constructor...\n\n\n\n\n\n"); } public void save(){ System.out.println("save"); } /** * 自我介绍 */ public void introduce(){ System.out.println("您好,我叫"+person.getName()+"今年"+person.getAge()+"岁!"); } }
3e172aa0c64779c0569620a70e0e6a660d9b736c
5,706
java
Java
module/nuls-transaction/src/test/java/io/nuls/transaction/sort/TestSorter.java
LaudateCorpus1/nerve-2
4980c66ae7fc66b21399e374c778fd84273dd7de
[ "MIT" ]
103
2020-02-07T03:55:21.000Z
2022-01-21T16:13:48.000Z
module/nuls-transaction/src/test/java/io/nuls/transaction/sort/TestSorter.java
LaudateCorpus1/nerve-2
4980c66ae7fc66b21399e374c778fd84273dd7de
[ "MIT" ]
59
2020-04-07T10:14:29.000Z
2021-07-29T04:08:23.000Z
module/nuls-transaction/src/test/java/io/nuls/transaction/sort/TestSorter.java
LaudateCorpus1/nerve-2
4980c66ae7fc66b21399e374c778fd84273dd7de
[ "MIT" ]
30
2020-04-13T10:08:36.000Z
2022-03-22T10:33:42.000Z
34.803681
107
0.585228
9,874
package io.nuls.transaction.sort; import io.nuls.transaction.tx.OrphanTxSortTest; import io.nuls.transaction.utils.NewSorter; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * @author Eva */ public class TestSorter { private List<TestSortData> getData0() { List<TestSortData> dataList = new ArrayList<>(); dataList.add(new TestSortData("4", "3")); dataList.add(new TestSortData("1", "0")); dataList.add(new TestSortData("3", "2")); dataList.add(new TestSortData("2", "1")); return dataList; } private List<TestSortData> getData1() { List<TestSortData> dataList = new ArrayList<>(); dataList.add(new TestSortData("1", "0")); dataList.add(new TestSortData("2", "1", "0")); dataList.add(new TestSortData("3", "2", "1")); dataList.add(new TestSortData("4", "30")); dataList.add(new TestSortData("5", "3")); dataList.add(new TestSortData("6", "4", "5")); return dataList; } private List<TestSortData> getData2() { List<TestSortData> dataList = new ArrayList<>(); dataList.add(new TestSortData("1", "0")); dataList.add(new TestSortData("2", "1")); dataList.add(new TestSortData("3", "2", "1")); dataList.add(new TestSortData("4", "3", "2", "1")); dataList.add(new TestSortData("5", "3", "2", "1")); dataList.add(new TestSortData("6", "3", "2", "1")); dataList.add(new TestSortData("7", "5", "6", "4")); return dataList; } private List<TestSortData> getData3() { List<TestSortData> dataList = new ArrayList<>(); dataList.add(new TestSortData("1")); dataList.add(new TestSortData("2")); dataList.add(new TestSortData("3")); dataList.add(new TestSortData("4", "1", "3")); dataList.add(new TestSortData("5", "2")); dataList.add(new TestSortData("6", "4", "5")); dataList.add(new TestSortData("x", "1", "3","z")); dataList.add(new TestSortData("y", "2","x")); dataList.add(new TestSortData("z", "4", "y")); dataList.add(new TestSortData("7")); dataList.add(new TestSortData("8")); dataList.add(new TestSortData("9")); dataList.add(new TestSortData("a")); dataList.add(new TestSortData("b")); dataList.add(new TestSortData("c")); dataList.add(new TestSortData("d", "6", "7")); return dataList; } private List<TestSortData> getData4() { List<TestSortData> dataList = new ArrayList<>(); dataList.add(new TestSortData("a", "9")); dataList.add(new TestSortData("c", "b")); dataList.add(new TestSortData("d", "c")); dataList.add(new TestSortData("2", "1")); dataList.add(new TestSortData("5", "4")); dataList.add(new TestSortData("f", "e")); dataList.add(new TestSortData("6", "5")); dataList.add(new TestSortData("b", "a")); dataList.add(new TestSortData("3", "2")); dataList.add(new TestSortData("4", "3")); dataList.add(new TestSortData("7", "6")); dataList.add(new TestSortData("8", "7")); dataList.add(new TestSortData("1")); dataList.add(new TestSortData("9", "8")); dataList.add(new TestSortData("e", "d")); return dataList; } @Test public void test0() { List<TestSortData> dataList = getData0(); dataList = NewSorter.sort(dataList); String result = getResult(dataList); assertEquals(result, "1234"); } @Test public void test1() { List<TestSortData> dataList = getData1(); dataList = NewSorter.sort(dataList); String result = getResult(dataList); assertTrue(result.equals("123456") || result.equals("123546")); } @Test public void test2() { List<TestSortData> dataList = getData2(); dataList = NewSorter.sort(dataList); String result = getResult(dataList); assertTrue(result.startsWith("123") && result.endsWith("7")); } @Test public void test3() { List<TestSortData> dataList = getData3(); dataList = NewSorter.sort(dataList); String result = getResult(dataList); System.out.println(result); // 1/3 在4之前 assertTrue(result.indexOf("1") < result.indexOf("4") && result.indexOf("3") < result.indexOf("4")); // 2 在5之前 assertTrue(result.indexOf("2") < result.indexOf("5")); // 4,5 在6之前 assertTrue(result.indexOf("4") < result.indexOf("6") && result.indexOf("5") < result.indexOf("6")); // 6,7在d之前 assertTrue(result.indexOf("6") < result.indexOf("d") && result.indexOf("7") < result.indexOf("d")); } @Test public void test4() { List<TestSortData> dataList = getData4(); List<TestSortData> txList = new ArrayList<>(); List<Integer> ide = OrphanTxSortTest.randomIde(dataList.size()); for (int i = 0; i < dataList.size(); i++) { txList.add(dataList.get(ide.get(i))); } System.out.println(getResult(txList)); dataList = NewSorter.sort(txList); String result = getResult(dataList); System.out.println("fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b: " + result); assertTrue(result.equals("123456789abcdef")); } public String getResult(List<TestSortData> list) { StringBuilder ss = new StringBuilder(); for (TestSortData data : list) { ss.append(data.getId()); } return ss.toString(); } }
3e172b1c53d2a6f0dc3bd25d0873488ef728ea2b
1,472
java
Java
game-service/src/main/java/com/sparkystudios/traklibrary/game/service/impl/GameBarcodeServiceImpl.java
TheLordBritish/trak-api
3e36df67f9c8de942a13a5e2065855ef3c5e4e05
[ "Apache-2.0" ]
null
null
null
game-service/src/main/java/com/sparkystudios/traklibrary/game/service/impl/GameBarcodeServiceImpl.java
TheLordBritish/trak-api
3e36df67f9c8de942a13a5e2065855ef3c5e4e05
[ "Apache-2.0" ]
35
2020-08-25T11:46:11.000Z
2021-08-22T20:45:48.000Z
game-service/src/main/java/com/sparkystudios/traklibrary/game/service/impl/GameBarcodeServiceImpl.java
TheLordBritish/trak-api
3e36df67f9c8de942a13a5e2065855ef3c5e4e05
[ "Apache-2.0" ]
null
null
null
42.057143
106
0.813859
9,875
package com.sparkystudios.traklibrary.game.service.impl; import com.sparkystudios.traklibrary.game.repository.GameBarcodeRepository; import com.sparkystudios.traklibrary.game.service.GameBarcodeService; import com.sparkystudios.traklibrary.game.service.dto.GameBarcodeDto; import com.sparkystudios.traklibrary.game.service.mapper.GameBarcodeMapper; import lombok.RequiredArgsConstructor; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityNotFoundException; @RequiredArgsConstructor @Service public class GameBarcodeServiceImpl implements GameBarcodeService { private static final String NOT_FOUND_MESSAGE = "game-barcode.exception.barcode-not-found"; private final GameBarcodeRepository gameBarcodeRepository; private final MessageSource messageSource; private final GameBarcodeMapper gameBarcodeMapper; @Override @Transactional(readOnly = true) public GameBarcodeDto findByBarcode(String barcode) { String errorMessage = messageSource .getMessage(NOT_FOUND_MESSAGE, new Object[] { barcode }, LocaleContextHolder.getLocale()); return gameBarcodeMapper.fromGameBarcode(gameBarcodeRepository.findByBarcode(barcode) .orElseThrow(() -> new EntityNotFoundException(errorMessage))); } }
3e172bf601da7da431880991c94aabdc017c5f9e
1,834
java
Java
src/main/java/com/sematext/rq/searches/output/AbstractOutputWriter.java
sematext/related-searches
afd7a6c07df29f821d61b1de01afbb9d5e7128d9
[ "Apache-2.0" ]
7
2017-02-14T15:34:44.000Z
2022-01-10T19:20:29.000Z
src/main/java/com/sematext/rq/searches/output/AbstractOutputWriter.java
sematext/related-searches
afd7a6c07df29f821d61b1de01afbb9d5e7128d9
[ "Apache-2.0" ]
null
null
null
src/main/java/com/sematext/rq/searches/output/AbstractOutputWriter.java
sematext/related-searches
afd7a6c07df29f821d61b1de01afbb9d5e7128d9
[ "Apache-2.0" ]
3
2018-01-15T08:53:33.000Z
2019-05-10T07:30:10.000Z
26.57971
111
0.664122
9,876
/* * Copyright (c) Sematext International * All Rights Reserved * * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF Sematext International * The copyright notice above does not evidence any * actual or intended publication of such source code. */ package com.sematext.rq.searches.output; import java.io.BufferedWriter; import java.io.IOException; import java.util.Set; import redis.clients.jedis.JedisPool; import com.sematext.rq.searches.eval.SegmentProcessorQueriesEvaluator; /** * Abstract base class for {@link OutputWriter} implementations. * * @author sematext, http://www.sematext.com/ */ public abstract class AbstractOutputWriter implements OutputWriter { private String prefix; /** * Constructor called by children classes. * * @param prefix * prefix */ protected AbstractOutputWriter(String prefix) { this.prefix = prefix; } /** * Writes queries to given writer. * * @param writer * writer * @param dym * evaluation * @throws IOException * thrown when I/O error occurs */ protected void writeQueries(BufferedWriter writer, SegmentProcessorQueriesEvaluator dym) throws IOException { // hack // get all keys that are related to query // and run suggest method with that query writing it to file JedisPool pool = dym.getSeqDym().getPool(); Set<String> keys = pool.getResource().keys(prefix + "*"); for (String key : keys) { String query = key.substring(prefix.length()); String suggestion = dym.suggest(query); if (suggestion != null && !suggestion.isEmpty()) { writer.write(query); writer.write(" -> "); writer.write(suggestion); writer.newLine(); } } } public String getPrefix() { return prefix; } }
3e172c062dce1a27a59c3e9cd755a953d86edaae
4,870
java
Java
src/main/java/com/mmall/controller/common/interceptor/AuthorityInterceptor.java
gongfukangEE/MMAIL
1f65a2e89b5c144643859216b5a38f5673a20e9b
[ "MIT" ]
5
2019-04-21T08:38:51.000Z
2020-11-08T04:48:14.000Z
src/main/java/com/mmall/controller/common/interceptor/AuthorityInterceptor.java
gongfukangEE/MMAIL
1f65a2e89b5c144643859216b5a38f5673a20e9b
[ "MIT" ]
null
null
null
src/main/java/com/mmall/controller/common/interceptor/AuthorityInterceptor.java
gongfukangEE/MMAIL
1f65a2e89b5c144643859216b5a38f5673a20e9b
[ "MIT" ]
7
2019-07-03T08:19:27.000Z
2020-12-29T06:41:29.000Z
39.918033
146
0.634292
9,877
package com.mmall.controller.common.interceptor; import com.google.common.collect.Maps; import com.mmall.common.Const; import com.mmall.common.ServerResponse; import com.mmall.pojo.User; import com.mmall.util.CookieUtil; import com.mmall.util.JsonUtil; import com.mmall.util.RedisShardedPoolUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import java.util.Arrays; import java.util.Iterator; import java.util.Map; /** * @Auther gongfukang * @Date 7/8 16:02 * 拦截器 */ @Slf4j public class AuthorityInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.info("preHandle"); // 请求中的方法名字 HandlerMethod handlerMethod = (HandlerMethod) handler; // 解析 HandlerMethod String methodName = handlerMethod.getMethod().getName(); String className = handlerMethod.getBean().getClass().getSimpleName(); // 解析参数,具体的参数 key value 是什么,日志打印 StringBuffer requestParamBuffer = new StringBuffer(); Map paramMap = request.getParameterMap(); Iterator it = paramMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); String mapKey = (String) entry.getKey(); String mapValue = StringUtils.EMPTY; // request 这个参数的 map 里面的 value 返回的是一个 String[] Object obj = entry.getValue(); if (obj instanceof String[]) { String[] strs = (String[]) obj; mapValue = Arrays.toString(strs); } requestParamBuffer.append(mapKey).append("=").append(mapValue); } if (StringUtils.equals(className, "UserManagerController") && StringUtils.equals(methodName, "login")) { log.info("权限拦截器拦截的请求,className:{}, methodName:{}", className, methodName); // 如果是拦截的登陆请求,不打印参数,参数中的密码会打印到日志中,不安全 return true; } log.info("权限拦截器拦截到请求,className: {}, methodName: {}, param: {}", className, methodName, requestParamBuffer.toString()); // 获取用户 User user = null; String loginToken = CookieUtil.readLoginToken(request); if (StringUtils.isNotEmpty(loginToken)) { String userJsonStr = RedisShardedPoolUtil.get(loginToken); user = JsonUtil.string2Obj(userJsonStr, User.class); } // response 托管到 拦截器当中,将 dispatcher-servlet 中与 json 相关的配置全部重写 if (user == null || (user.getRole().intValue() != Const.Role.ROLE_ADMIN)) { // 返回 false,即不会调用 Controller 中的方法 response.reset(); // 这里要添加 reset,否则要报异常 response.setCharacterEncoding("UTF-8"); //这里要设置编码,否则乱码 response.setContentType("application/json;charset=UTF-8"); //设置返回值的类型,因为全部是 json 接口 PrintWriter out = response.getWriter(); // 上传由于富文本的控件要去,要特殊处理返回值,这里面区分登陆和权限 if (user == null) { if (StringUtils.equals(className, "ProductManageController") && StringUtils.equals(methodName, "richtextImgUpload")) { Map resultMap = Maps.newHashMap(); resultMap.put("success", false); resultMap.put("msg", "请登陆管理员"); out.print(JsonUtil.obj2String(resultMap)); } else { out.print(JsonUtil.obj2String(ServerResponse.createByErrorMessage("拦截器拦截,用户未登录"))); } } else { if (StringUtils.equals(className, "ProductManageController") && StringUtils.equals(methodName, "richtextImgUpload")) { Map resultMap = Maps.newHashMap(); resultMap.put("success", false); resultMap.put("msg", "无权限操作"); out.print(JsonUtil.obj2String(resultMap)); } else { out.print(JsonUtil.obj2String(ServerResponse.createByErrorMessage("拦截器拦截,用户无权限操作"))); } } out.flush(); out.close(); return false; } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { log.info("postHandle"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { log.info("afterCompletion"); } }
3e172d847ae208972f285a0f884ab074d5bc97bf
1,688
java
Java
logback-android/src/main/java/ch/qos/logback/classic/net/server/RemoteAppenderServerRunner.java
someweardev/logback-android
ebd3088603c6ea4a3e835273dc821bd0a5f00735
[ "Apache-2.0" ]
880
2015-01-02T05:41:10.000Z
2022-03-31T05:56:36.000Z
logback-android/src/main/java/ch/qos/logback/classic/net/server/RemoteAppenderServerRunner.java
someweardev/logback-android
ebd3088603c6ea4a3e835273dc821bd0a5f00735
[ "Apache-2.0" ]
234
2015-01-11T05:19:16.000Z
2022-02-23T10:05:31.000Z
logback-android/src/main/java/ch/qos/logback/classic/net/server/RemoteAppenderServerRunner.java
someweardev/logback-android
ebd3088603c6ea4a3e835273dc821bd0a5f00735
[ "Apache-2.0" ]
129
2015-01-06T06:22:36.000Z
2022-03-24T07:06:36.000Z
30.142857
75
0.741114
9,878
/** * Copyright 2019 Anthony Trinh * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.qos.logback.classic.net.server; import java.util.concurrent.Executor; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.core.net.server.ConcurrentServerRunner; import ch.qos.logback.core.net.server.ServerListener; import ch.qos.logback.core.net.server.ServerRunner; /** * A {@link ServerRunner} that receives logging events from remote appender * clients. * * @author Carl Harris */ class RemoteAppenderServerRunner extends ConcurrentServerRunner<RemoteAppenderClient> { /** * Constructs a new server runner. * @param listener the listener from which the server will accept new * clients * @param executor that will be used to execute asynchronous tasks * on behalf of the runner. */ public RemoteAppenderServerRunner( ServerListener<RemoteAppenderClient> listener, Executor executor) { super(listener, executor); } /** * {@inheritDoc} */ @Override protected boolean configureClient(RemoteAppenderClient client) { client.setLoggerContext((LoggerContext) getContext()); return true; } }
3e172e0b79db9ad2ed86ad9f2fd51ea0e0068dc3
616
java
Java
src/main/java/br/com/server/northwind/batch/TableJobListener.java
thennull/Java_Store_Backend
68f1d6d77b920578746f417fada01e9fa775f8d9
[ "MIT" ]
null
null
null
src/main/java/br/com/server/northwind/batch/TableJobListener.java
thennull/Java_Store_Backend
68f1d6d77b920578746f417fada01e9fa775f8d9
[ "MIT" ]
null
null
null
src/main/java/br/com/server/northwind/batch/TableJobListener.java
thennull/Java_Store_Backend
68f1d6d77b920578746f417fada01e9fa775f8d9
[ "MIT" ]
null
null
null
32.421053
81
0.720779
9,879
package br.com.server.northwind.batch; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobExecutionListener; public class TableJobListener implements JobExecutionListener { @Override public void beforeJob ( JobExecution jobExecution ) { System.out.println( "Job started..." ); System.out.println( jobExecution.getJobInstance().getJobName() ); } @Override public void afterJob ( JobExecution jobExecution ) { System.out.println( "Job ended..." ); System.out.println( "Job status: " + jobExecution.getStatus().toString() ); } }
3e1730903dd22943435170e99643435475c73af0
3,065
java
Java
elza/elza-core/src/main/java/cz/tacr/elza/print/UnitDate.java
elzasw/elza
5c9751f8b7366e8090b709bbcea3d085848125b6
[ "Apache-2.0" ]
null
null
null
elza/elza-core/src/main/java/cz/tacr/elza/print/UnitDate.java
elzasw/elza
5c9751f8b7366e8090b709bbcea3d085848125b6
[ "Apache-2.0" ]
null
null
null
elza/elza-core/src/main/java/cz/tacr/elza/print/UnitDate.java
elzasw/elza
5c9751f8b7366e8090b709bbcea3d085848125b6
[ "Apache-2.0" ]
1
2022-01-09T12:21:31.000Z
2022-01-09T12:21:31.000Z
24.133858
99
0.672431
9,880
package cz.tacr.elza.print; import java.util.Objects; import cz.tacr.elza.api.IUnitdate; import cz.tacr.elza.core.data.CalendarType; import cz.tacr.elza.domain.ArrCalendarType; import cz.tacr.elza.domain.convertor.UnitDateConvertor; /** * Rozšiřuje {@link UnitDateText} o strukturovaný zápis datumu. * */ public class UnitDate implements IUnitdate { private final String valueFrom; private final String valueTo; private final Boolean valueFromEstimated; private final Boolean valueToEstimated; private final CalendarType calendarType; private String format; private String valueText; public UnitDate(IUnitdate srcItemData) { this.valueFrom = srcItemData.getValueFrom(); this.valueTo = srcItemData.getValueTo(); this.valueFromEstimated = srcItemData.getValueFromEstimated(); this.valueToEstimated = srcItemData.getValueToEstimated(); this.format = srcItemData.getFormat(); // id without fetch -> access type property this.calendarType = CalendarType.fromId(srcItemData.getCalendarType().getCalendarTypeId()); } public String getValueText() { if (valueText == null) { valueText = UnitDateConvertor.convertToString(this); } return valueText; } public String getCalendar() { return calendarType.getName(); } public String getCalendarCode() { return calendarType.getCode(); } @Override public String getFormat() { return format; } @Override public void setFormat(final String format) { if (!Objects.equals(this.format, format)) { resetValueText(); } this.format = format; } @Override public void formatAppend(final String format) { throw new UnsupportedOperationException(); } @Override public String getValueFrom() { return valueFrom; } @Override public void setValueFrom(final String valueFrom) { throw new UnsupportedOperationException(); } @Override public Boolean getValueFromEstimated() { return valueFromEstimated; } @Override public void setValueFromEstimated(final Boolean valueFromEstimated) { throw new UnsupportedOperationException(); } @Override public String getValueTo() { return valueTo; } @Override public void setValueTo(final String valueTo) { throw new UnsupportedOperationException(); } @Override public Boolean getValueToEstimated() { return valueToEstimated; } @Override public void setValueToEstimated(final Boolean valueToEstimated) { throw new UnsupportedOperationException(); } @Override public ArrCalendarType getCalendarType() { return calendarType.getEntity(); } @Override public void setCalendarType(ArrCalendarType calendarType) { throw new UnsupportedOperationException(); } private void resetValueText() { this.valueText = null; } }
3e173226378771bd18b9fafae80bc25beed5e828
550
java
Java
serverless-search-api/src/main/java/au/qut/edu/eresearch/serverlesssearch/handler/InvalidIndexNameExceptionHandler.java
eresearchqut/serverless-search
e131e27907834b9679dfd49890be7b217070c410
[ "MIT" ]
null
null
null
serverless-search-api/src/main/java/au/qut/edu/eresearch/serverlesssearch/handler/InvalidIndexNameExceptionHandler.java
eresearchqut/serverless-search
e131e27907834b9679dfd49890be7b217070c410
[ "MIT" ]
null
null
null
serverless-search-api/src/main/java/au/qut/edu/eresearch/serverlesssearch/handler/InvalidIndexNameExceptionHandler.java
eresearchqut/serverless-search
e131e27907834b9679dfd49890be7b217070c410
[ "MIT" ]
null
null
null
32.352941
101
0.810909
9,881
package au.qut.edu.eresearch.serverlesssearch.handler; import au.qut.edu.eresearch.serverlesssearch.service.InvalidIndexNameException; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; @Provider public class InvalidIndexNameExceptionHandler implements ExceptionMapper<InvalidIndexNameException> { @Override public Response toResponse(InvalidIndexNameException exception) { return Response.status(Response.Status.BAD_REQUEST).entity(exception.getMessage()).build(); } }
3e1732611bbb998bb3495d3fa6a5621cab2bdb1a
2,182
java
Java
activiti-cloud-services-query/activiti-cloud-services-query-repo/src/main/java/org/activiti/cloud/services/query/app/repository/BPMNSequenceFlowRepository.java
AlfrescoArchive/activiti-cloud-query-service
7e8323d0b5a77a9b4a4707a349589df16c4615ed
[ "Apache-2.0" ]
14
2018-01-20T13:00:26.000Z
2021-03-18T07:20:17.000Z
activiti-cloud-services-query/activiti-cloud-services-query-repo/src/main/java/org/activiti/cloud/services/query/app/repository/BPMNSequenceFlowRepository.java
AlfrescoArchive/activiti-cloud-query-service
7e8323d0b5a77a9b4a4707a349589df16c4615ed
[ "Apache-2.0" ]
368
2017-10-19T15:02:23.000Z
2020-02-26T11:16:05.000Z
activiti-cloud-services-query/activiti-cloud-services-query-repo/src/main/java/org/activiti/cloud/services/query/app/repository/BPMNSequenceFlowRepository.java
Activiti/activiti-cloud-query-service
7e8323d0b5a77a9b4a4707a349589df16c4615ed
[ "Apache-2.0" ]
28
2018-02-07T19:52:45.000Z
2021-03-18T07:20:19.000Z
43.64
111
0.731897
9,882
/* * Copyright 2018 Alfresco, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.cloud.services.query.app.repository; import java.util.List; import com.querydsl.core.types.dsl.StringPath; import org.activiti.cloud.services.query.model.BPMNSequenceFlowEntity; import org.activiti.cloud.services.query.model.QBPMNSequenceFlowEntity; import org.springframework.data.querydsl.QuerydslPredicateExecutor; import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer; import org.springframework.data.querydsl.binding.QuerydslBindings; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; @RepositoryRestResource(exported = false) public interface BPMNSequenceFlowRepository extends PagingAndSortingRepository<BPMNSequenceFlowEntity, String>, QuerydslPredicateExecutor<BPMNSequenceFlowEntity>, QuerydslBinderCustomizer<QBPMNSequenceFlowEntity> { @Override default void customize(QuerydslBindings bindings, QBPMNSequenceFlowEntity root) { bindings.bind(String.class).first( (StringPath path, String value) -> path.eq(value)); } List<BPMNSequenceFlowEntity> findByProcessInstanceId(String processInstanceId); BPMNSequenceFlowEntity findByProcessInstanceIdAndElementId(String processInstanceId, String elementId); BPMNSequenceFlowEntity findByEventId(String eventId); }
3e1732d99be873d16fb662de3e56f7538d13867a
2,971
java
Java
app/src/main/java/com/per/epx/easytrain/models/wrapper/RouteWrapper.java
kobayashikanata/EasyTrain
a51e4cd7087b21b66470c1fc7aab00454c09f4e2
[ "MIT" ]
null
null
null
app/src/main/java/com/per/epx/easytrain/models/wrapper/RouteWrapper.java
kobayashikanata/EasyTrain
a51e4cd7087b21b66470c1fc7aab00454c09f4e2
[ "MIT" ]
null
null
null
app/src/main/java/com/per/epx/easytrain/models/wrapper/RouteWrapper.java
kobayashikanata/EasyTrain
a51e4cd7087b21b66470c1fc7aab00454c09f4e2
[ "MIT" ]
null
null
null
32.293478
127
0.696062
9,883
package com.per.epx.easytrain.models.wrapper; import android.content.Context; import com.per.epx.easytrain.R; import com.per.epx.easytrain.helpers.DateFormatter; import com.per.epx.easytrain.helpers.DurationFormatter; import com.per.epx.easytrain.models.sln.LineRoute; import java.io.Serializable; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Calendar; public class RouteWrapper implements Serializable{ private static NumberFormat formatNumber = new DecimalFormat("#####.##"); private LineRoute raw; private long timeUsage; private int dayDiffer; private String tripMonthDayHourMinute; private String beginHourMinuteText; private String terminalHourMinuteText; private String timeUsageText; private String transferText; public RouteWrapper(LineRoute raw, Context context) { setup(raw, context); this.timeUsageText = DurationFormatter.totalMillsToHourMinute(timeUsage, context.getString(R.string.label_hour), context.getString(R.string.label_minutes)); } private void setup(LineRoute raw, Context context){ this.raw = raw; long firstDriveTime = raw.getBeginning().getDriveTime(); long lastArriveTime = raw.getTerminal().getArrivalTime(); this.timeUsage = lastArriveTime - firstDriveTime; this.tripMonthDayHourMinute = DateFormatter.formatDefault(firstDriveTime, "MM/dd\nHH:mm"); this.beginHourMinuteText = DateFormatter.formatDefault(firstDriveTime, "HH:mm"); this.terminalHourMinuteText = DateFormatter.formatDefault(lastArriveTime, "HH:mm"); this.dayDiffer = DateFormatter.differ(lastArriveTime, firstDriveTime, Calendar.DAY_OF_YEAR); if(raw.getRunLines().size() <= 1){ this.transferText = context.getString(R.string.label_nonstop); }else{ this.transferText = String.format(context.getString(R.string.format_transfer_times), raw.getRunLines().size() - 1); } } public LineRoute raw(){ return this.raw; } public String getTransferText(){ return transferText; } public String getPayment(){ return formatNumber.format(raw().getPayment()); } public String getCrossSize(){ return String.valueOf(raw().getRunLines().size()); } public String getBeginName(){ return String.valueOf(raw().getBeginning().getName()); } public String getTerminalName(){ return String.valueOf(raw().getTerminal().getName()); } public int getDayDiffer() { return dayDiffer; } public String getTimeUsageText() { return timeUsageText; } public String getTripMonthDayHourMinute() { return tripMonthDayHourMinute; } public String getBeginHourMinuteText() { return beginHourMinuteText; } public String getTerminalHourMinuteText() { return terminalHourMinuteText; } }
3e1732ee6732b40ae657da145d7625139d592ebf
1,028
java
Java
src/main/java/net/nullspace_mc/tapestry/mixin/feature/fillorientationfix/SetBlockCommandMixin.java
Copetan/Tapestry
4cfa3434113e96cf0d72284cacb5daafe732a9c0
[ "MIT" ]
1
2021-12-01T10:13:58.000Z
2021-12-01T10:13:58.000Z
src/main/java/net/nullspace_mc/tapestry/mixin/feature/fillorientationfix/SetBlockCommandMixin.java
Copetan/Tapestry
4cfa3434113e96cf0d72284cacb5daafe732a9c0
[ "MIT" ]
null
null
null
src/main/java/net/nullspace_mc/tapestry/mixin/feature/fillorientationfix/SetBlockCommandMixin.java
Copetan/Tapestry
4cfa3434113e96cf0d72284cacb5daafe732a9c0
[ "MIT" ]
2
2021-12-04T00:42:50.000Z
2022-01-12T13:35:56.000Z
38.074074
113
0.749027
9,884
package net.nullspace_mc.tapestry.mixin.feature.fillorientationfix; import net.minecraft.command.AbstractCommand; import net.minecraft.command.CommandSource; import net.minecraft.server.command.SetBlockCommand; import net.nullspace_mc.tapestry.helpers.SetBlockHelper; import net.nullspace_mc.tapestry.settings.Settings; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(SetBlockCommand.class) public abstract class SetBlockCommandMixin extends AbstractCommand { @Inject( method = "execute", at = @At( value = "INVOKE", target = "Lnet/minecraft/world/World;setBlockWithMetadata(IIILnet/minecraft/block/Block;II)Z" ) ) private void fixOrientation(CommandSource source, String[] args, CallbackInfo ci) { SetBlockHelper.applyFillOrientationFixRule = true; } }
3e17334fef54f341bbe2027aa8e9cf464a549c4e
2,569
java
Java
src/java/us/temerity/pipeline/ui/JListCellRenderer.java
JimCallahan/Pipeline
948ea80b84e13de69f049210b63e1d58f7a8f9de
[ "Apache-2.0" ]
9
2019-10-23T19:35:16.000Z
2021-09-21T22:03:42.000Z
src/java/us/temerity/pipeline/ui/JListCellRenderer.java
JimCallahan/Pipeline
948ea80b84e13de69f049210b63e1d58f7a8f9de
[ "Apache-2.0" ]
null
null
null
src/java/us/temerity/pipeline/ui/JListCellRenderer.java
JimCallahan/Pipeline
948ea80b84e13de69f049210b63e1d58f7a8f9de
[ "Apache-2.0" ]
2
2019-07-02T08:34:37.000Z
2019-10-26T23:13:55.000Z
29.193182
94
0.401323
9,885
// $Id: JListCellRenderer.java,v 1.5 2009/08/19 23:49:53 jim Exp $ package us.temerity.pipeline.ui; import us.temerity.pipeline.laf.LookAndFeelLoader; import java.awt.*; import java.awt.event.*; import java.text.*; import javax.swing.*; import javax.swing.border.*; /*------------------------------------------------------------------------------------------*/ /* L I S T C E L L R E N D E R E R */ /*------------------------------------------------------------------------------------------*/ /** * The renderer used for the {@link JList JList} cells. */ public class JListCellRenderer extends DefaultListCellRenderer { /*----------------------------------------------------------------------------------------*/ /* C O N S T R U C T O R */ /*----------------------------------------------------------------------------------------*/ /** * Construct a new renderer. */ public JListCellRenderer() { setOpaque(true); setBackground(new Color(0.45f, 0.45f, 0.45f)); } /*----------------------------------------------------------------------------------------*/ /* R E N D E R I N G */ /*----------------------------------------------------------------------------------------*/ /** * Generates the component to be displayed for JList cells. */ public Component getListCellRendererComponent ( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus ) { assert(value != null); setText(value.toString()); setHorizontalAlignment(JLabel.LEFT); if(isSelected) { setForeground(Color.yellow); setIcon(sSelectedIcon); } else { setForeground(Color.white); setIcon(sNormalIcon); } return this; } /*----------------------------------------------------------------------------------------*/ /* S T A T I C I N T E R N A L S */ /*----------------------------------------------------------------------------------------*/ private static final long serialVersionUID = 9144374790563937303L; private static final Icon sNormalIcon = new ImageIcon(LookAndFeelLoader.class.getResource("ListCellNormalIcon.png")); private static final Icon sSelectedIcon = new ImageIcon(LookAndFeelLoader.class.getResource("ListCellSelectedIcon.png")); }
3e17349a529821ac4049d1ec93be1e31d805db25
321
java
Java
erp_parent/erp_dao/src/main/java/cn/xlr/erp/dao/IStoredetailDao.java
ggb2312/Erp
df258d73e32c8442e72729a4f9adefe71cb843ee
[ "Apache-2.0" ]
10
2019-05-19T15:36:22.000Z
2020-04-06T03:09:38.000Z
erp_parent/erp_dao/src/main/java/cn/xlr/erp/dao/IStoredetailDao.java
ggb2312/Erp
df258d73e32c8442e72729a4f9adefe71cb843ee
[ "Apache-2.0" ]
6
2021-04-22T16:49:38.000Z
2022-02-09T22:57:48.000Z
erp_parent/erp_dao/src/main/java/cn/xlr/erp/dao/IStoredetailDao.java
ggb2312/Erp
df258d73e32c8442e72729a4f9adefe71cb843ee
[ "Apache-2.0" ]
7
2019-05-30T21:34:49.000Z
2019-12-21T16:46:19.000Z
16.894737
63
0.725857
9,886
package cn.xlr.erp.dao; import java.util.List; import cn.xlr.erp.entity.Storealert; import cn.xlr.erp.entity.Storedetail; /** * 仓库库存数据访问接口 * @author Administrator * */ public interface IStoredetailDao extends IBaseDao<Storedetail>{ /** * 获取库存预警列表 * @return */ public List<Storealert> getStorealertList(); }
3e1734ec58657c7044e29ee39f6ef42d5c3e8b64
2,082
java
Java
jena-arq/src/main/java/org/apache/jena/sparql/function/library/FN_StrNormalizeUnicode.java
costas80/jena
7d146c5c265196c9c2740948fd1cd22b21aca033
[ "Apache-2.0" ]
null
null
null
jena-arq/src/main/java/org/apache/jena/sparql/function/library/FN_StrNormalizeUnicode.java
costas80/jena
7d146c5c265196c9c2740948fd1cd22b21aca033
[ "Apache-2.0" ]
1
2022-02-05T16:08:39.000Z
2022-02-05T16:08:41.000Z
jena-arq/src/main/java/org/apache/jena/sparql/function/library/FN_StrNormalizeUnicode.java
costas80/jena
7d146c5c265196c9c2740948fd1cd22b21aca033
[ "Apache-2.0" ]
null
null
null
36.526316
129
0.699808
9,887
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.sparql.function.library; import org.apache.jena.atlas.lib.Lib; import org.apache.jena.query.QueryBuildException; import org.apache.jena.sparql.expr.ExprEvalException; import org.apache.jena.sparql.expr.ExprList; import org.apache.jena.sparql.expr.NodeValue; import org.apache.jena.sparql.expr.nodevalue.XSDFuncOp; import org.apache.jena.sparql.function.FunctionBase; import java.util.List; public class FN_StrNormalizeUnicode extends FunctionBase { public FN_StrNormalizeUnicode() { super() ; } @Override public void checkBuild(String uri, ExprList args) { if ( args.size() != 1 && args.size() != 2 ) throw new QueryBuildException("Function '"+ Lib.className(this)+"' takes one or two arguments") ; } @Override public NodeValue exec(List<NodeValue> args) { if ( args.size() != 1 && args.size() != 2 ) throw new ExprEvalException("FN_StrNormalizeUnicode: Wrong number of arguments: "+args.size()+" : [wanted 1 or 2]") ; NodeValue v1 = args.get(0) ; if ( args.size() == 2 ) { NodeValue v2 = args.get(1) ; return XSDFuncOp.strNormalizeUnicode(v1, v2) ; } return XSDFuncOp.strNormalizeUnicode(v1, null) ; } }
3e17363c80806819ced9727b94ba3b58c0e0f73c
17,889
java
Java
support/cas-server-support-hazelcast-core/src/main/java/org/apereo/cas/hz/HazelcastConfigurationFactory.java
JasonEverling/cas
9d5eb3e7dbf34a29f5f69141602b3f83b48353c8
[ "Apache-2.0" ]
4
2015-10-31T14:57:03.000Z
2020-11-16T01:39:42.000Z
support/cas-server-support-hazelcast-core/src/main/java/org/apereo/cas/hz/HazelcastConfigurationFactory.java
Nurran/cas
43392ae8eefeb36d44a2b06fdedba589d726f4ae
[ "Apache-2.0" ]
12
2020-07-03T06:06:14.000Z
2022-01-27T00:37:19.000Z
support/cas-server-support-hazelcast-core/src/main/java/org/apereo/cas/hz/HazelcastConfigurationFactory.java
isabella232/cas
fc570ef1f0aa6b18817a955c5158e84d35aa201d
[ "Apache-2.0" ]
1
2016-06-22T00:54:09.000Z
2016-06-22T00:54:09.000Z
51.852174
141
0.697691
9,888
package org.apereo.cas.hz; import org.apereo.cas.configuration.model.support.hazelcast.BaseHazelcastProperties; import org.apereo.cas.configuration.model.support.hazelcast.HazelcastClusterProperties; import org.apereo.cas.util.CollectionUtils; import org.apereo.cas.util.function.FunctionUtils; import org.apereo.cas.util.spring.SpringExpressionLanguageValueResolver; import com.hazelcast.config.Config; import com.hazelcast.config.ConsistencyCheckStrategy; import com.hazelcast.config.DiscoveryConfig; import com.hazelcast.config.DiscoveryStrategyConfig; import com.hazelcast.config.EvictionConfig; import com.hazelcast.config.EvictionPolicy; import com.hazelcast.config.InMemoryFormat; import com.hazelcast.config.JoinConfig; import com.hazelcast.config.ManagementCenterConfig; import com.hazelcast.config.MapConfig; import com.hazelcast.config.MaxSizePolicy; import com.hazelcast.config.MergePolicyConfig; import com.hazelcast.config.MulticastConfig; import com.hazelcast.config.NamedConfig; import com.hazelcast.config.NetworkConfig; import com.hazelcast.config.PartitionGroupConfig; import com.hazelcast.config.ReplicatedMapConfig; import com.hazelcast.config.SSLConfig; import com.hazelcast.config.TcpIpConfig; import com.hazelcast.config.WanAcknowledgeType; import com.hazelcast.config.WanBatchPublisherConfig; import com.hazelcast.config.WanQueueFullBehavior; import com.hazelcast.config.WanReplicationConfig; import com.hazelcast.config.WanSyncConfig; import com.hazelcast.nio.ssl.BasicSSLContextFactory; import com.hazelcast.spi.merge.DiscardMergePolicy; import com.hazelcast.spi.merge.ExpirationTimeMergePolicy; import com.hazelcast.spi.merge.HigherHitsMergePolicy; import com.hazelcast.spi.merge.LatestAccessMergePolicy; import com.hazelcast.spi.merge.LatestUpdateMergePolicy; import com.hazelcast.spi.merge.PassThroughMergePolicy; import com.hazelcast.spi.merge.PutIfAbsentMergePolicy; import com.hazelcast.wan.WanPublisherState; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.commons.lang3.BooleanUtils; import org.springframework.util.StringUtils; import java.util.ServiceLoader; import java.util.UUID; /** * This is {@link HazelcastConfigurationFactory}. * * @author Misagh Moayyed * @since 5.2.0 */ @Slf4j public class HazelcastConfigurationFactory { /** * Sets config map. * * @param mapConfig the map config * @param config the config */ public static void setConfigMap(final NamedConfig mapConfig, final Config config) { if (mapConfig instanceof MapConfig) { config.addMapConfig((MapConfig) mapConfig); } else if (mapConfig instanceof ReplicatedMapConfig) { config.addReplicatedMapConfig((ReplicatedMapConfig) mapConfig); } } /** * Build config. * * @param hz the hz * @param mapConfig the map config * @return the config */ public static Config build(final BaseHazelcastProperties hz, final NamedConfig mapConfig) { val config = build(hz); setConfigMap(mapConfig, config); return finalizeConfig(config, hz); } /** * Build config. * * @param hz the hz * @return the config */ public static Config build(final BaseHazelcastProperties hz) { val cluster = hz.getCluster(); val config = new Config(); config.setLicenseKey(hz.getCore().getLicenseKey()); if (cluster.getCore().getCpMemberCount() > 0) { config.getCPSubsystemConfig().setCPMemberCount(cluster.getCore().getCpMemberCount()); } buildManagementCenterConfig(hz, config); val networkConfig = new NetworkConfig() .setPort(cluster.getNetwork().getPort()) .setPortAutoIncrement(cluster.getNetwork().isPortAutoIncrement()); buildNetworkSslConfig(networkConfig, hz); if (StringUtils.hasText(cluster.getNetwork().getNetworkInterfaces())) { networkConfig.getInterfaces().setEnabled(true); StringUtils.commaDelimitedListToSet(cluster.getNetwork().getNetworkInterfaces()) .forEach(faceIp -> networkConfig.getInterfaces().addInterface(faceIp)); } if (StringUtils.hasText(cluster.getNetwork().getLocalAddress())) { config.setProperty(BaseHazelcastProperties.HAZELCAST_LOCAL_ADDRESS_PROP, cluster.getNetwork().getLocalAddress()); } if (StringUtils.hasText(cluster.getNetwork().getPublicAddress())) { config.setProperty(BaseHazelcastProperties.HAZELCAST_PUBLIC_ADDRESS_PROP, cluster.getNetwork().getPublicAddress()); networkConfig.setPublicAddress(cluster.getNetwork().getPublicAddress()); } cluster.getNetwork().getOutboundPorts().forEach(networkConfig::addOutboundPortDefinition); if (cluster.getWanReplication().isEnabled()) { if (!StringUtils.hasText(hz.getCore().getLicenseKey())) { throw new IllegalArgumentException("Cannot activate WAN replication, a Hazelcast enterprise feature, without a license key"); } LOGGER.warn("Using Hazelcast WAN Replication requires a Hazelcast Enterprise subscription. Make sure you " + "have acquired the proper license, SDK and tooling from Hazelcast before activating this feature."); buildWanReplicationSettingsForConfig(hz, config); } val joinConfig = cluster.getDiscovery().isEnabled() ? createDiscoveryJoinConfig(config, cluster, networkConfig) : createDefaultJoinConfig(cluster); LOGGER.trace("Created Hazelcast join configuration [{}]", joinConfig); networkConfig.setJoin(joinConfig); LOGGER.trace("Created Hazelcast network configuration [{}]", networkConfig); config.setNetworkConfig(networkConfig); config.getSerializationConfig().setEnableCompression(hz.getCore().isEnableCompression()); val instanceName = StringUtils.hasText(cluster.getCore().getInstanceName()) ? SpringExpressionLanguageValueResolver.getInstance().resolve(cluster.getCore().getInstanceName()) : UUID.randomUUID().toString(); LOGGER.trace("Configuring Hazelcast instance name [{}]", instanceName); return config.setInstanceName(instanceName) .setProperty(BaseHazelcastProperties.HAZELCAST_DISCOVERY_ENABLED_PROP, BooleanUtils.toStringTrueFalse(cluster.getDiscovery().isEnabled())) .setProperty(BaseHazelcastProperties.IPV4_STACK_PROP, String.valueOf(cluster.getNetwork().isIpv4Enabled())) .setProperty(BaseHazelcastProperties.LOGGING_TYPE_PROP, cluster.getCore().getLoggingType()) .setProperty(BaseHazelcastProperties.MAX_HEARTBEAT_SECONDS_PROP, String.valueOf(cluster.getCore().getMaxNoHeartbeatSeconds())); } private static void buildNetworkSslConfig(final NetworkConfig networkConfig, final BaseHazelcastProperties hz) { val ssl = hz.getCluster().getNetwork().getSsl(); val sslConfig = new SSLConfig(); sslConfig.setFactoryClassName(BasicSSLContextFactory.class.getName()); FunctionUtils.doIfNotNull(ssl.getKeystore(), value -> sslConfig.setProperty("keystore", value)); FunctionUtils.doIfNotNull(ssl.getProtocol(), value -> sslConfig.setProperty("protocol", value)); FunctionUtils.doIfNotNull(ssl.getKeystorePassword(), value -> sslConfig.setProperty("keystorePassword", value)); FunctionUtils.doIfNotNull(ssl.getKeyStoreType(), value -> sslConfig.setProperty("keyStoreType", value)); FunctionUtils.doIfNotNull(ssl.getTrustStore(), value -> sslConfig.setProperty("trustStore", value)); FunctionUtils.doIfNotNull(ssl.getTrustStoreType(), value -> sslConfig.setProperty("trustStoreType", value)); FunctionUtils.doIfNotNull(ssl.getTrustStorePassword(), value -> sslConfig.setProperty("trustStorePassword", value)); FunctionUtils.doIfNotNull(ssl.getMutualAuthentication(), value -> sslConfig.setProperty("mutualAuthentication", value)); FunctionUtils.doIfNotNull(ssl.getCipherSuites(), value -> sslConfig.setProperty("cipherSuites", value)); FunctionUtils.doIfNotNull(ssl.getTrustManagerAlgorithm(), value -> sslConfig.setProperty("trustManagerAlgorithm", value)); FunctionUtils.doIfNotNull(ssl.getKeyManagerAlgorithm(), value -> sslConfig.setProperty("keyManagerAlgorithm", value)); sslConfig.setProperty("validateIdentity", String.valueOf(ssl.isValidateIdentity())); networkConfig.setSSLConfig(sslConfig); } private static void buildManagementCenterConfig(final BaseHazelcastProperties hz, final Config config) { val managementCenter = new ManagementCenterConfig(); LOGGER.trace("Enables management center scripting: [{}]", hz.getCore().isEnableManagementCenterScripting()); managementCenter.setScriptingEnabled(hz.getCore().isEnableManagementCenterScripting()); config.setManagementCenterConfig(managementCenter); } private static void buildWanReplicationSettingsForConfig(final BaseHazelcastProperties hz, final Config config) { val wan = hz.getCluster().getWanReplication(); val wanReplicationConfig = new WanReplicationConfig(); wanReplicationConfig.setName(wan.getReplicationName()); wan.getTargets().forEach(target -> { val publisherConfig = new WanBatchPublisherConfig(); publisherConfig.setClassName(target.getPublisherClassName()); publisherConfig.setQueueFullBehavior(WanQueueFullBehavior.valueOf(target.getQueueFullBehavior())); publisherConfig.setQueueCapacity(target.getQueueCapacity()); publisherConfig.setAcknowledgeType(WanAcknowledgeType.valueOf(target.getAcknowledgeType())); publisherConfig.setBatchSize(target.getBatchSize()); publisherConfig.setBatchMaxDelayMillis(target.getBatchMaximumDelayMilliseconds()); publisherConfig.setResponseTimeoutMillis(target.getResponseTimeoutMilliseconds()); publisherConfig.setSnapshotEnabled(target.isSnapshotEnabled()); publisherConfig.setTargetEndpoints(target.getEndpoints()); publisherConfig.setClusterName(target.getClusterName()); publisherConfig.setPublisherId(target.getPublisherId()); publisherConfig.setMaxConcurrentInvocations(target.getExecutorThreadCount()); publisherConfig.setInitialPublisherState(WanPublisherState.REPLICATING); publisherConfig.setProperties(target.getProperties()); publisherConfig.setSyncConfig(new WanSyncConfig() .setConsistencyCheckStrategy(ConsistencyCheckStrategy.valueOf(target.getConsistencyCheckStrategy()))); wanReplicationConfig.addBatchReplicationPublisherConfig(publisherConfig); }); config.addWanReplicationConfig(wanReplicationConfig); } private static JoinConfig createDiscoveryJoinConfig(final Config config, final HazelcastClusterProperties cluster, final NetworkConfig networkConfig) { val joinConfig = new JoinConfig(); LOGGER.trace("Disabling multicast and TCP/IP configuration for discovery"); joinConfig.getMulticastConfig().setEnabled(false); joinConfig.getTcpIpConfig().setEnabled(false); val discoveryConfig = new DiscoveryConfig(); val strategyConfig = locateDiscoveryStrategyConfig(cluster, joinConfig, config, networkConfig); LOGGER.trace("Creating discovery strategy configuration as [{}]", strategyConfig); discoveryConfig.setDiscoveryStrategyConfigs(CollectionUtils.wrap(strategyConfig)); joinConfig.setDiscoveryConfig(discoveryConfig); return joinConfig; } private static DiscoveryStrategyConfig locateDiscoveryStrategyConfig(final HazelcastClusterProperties cluster, final JoinConfig joinConfig, final Config config, final NetworkConfig networkConfig) { val serviceLoader = ServiceLoader.load(HazelcastDiscoveryStrategy.class); val it = serviceLoader.iterator(); if (it.hasNext()) { val strategy = it.next(); return strategy.get(cluster, joinConfig, config, networkConfig) .orElseThrow(() -> new IllegalArgumentException("Could not create discovery strategy configuration.")); } throw new IllegalArgumentException("Could not create discovery strategy configuration. No discovery provider is defined"); } private static JoinConfig createDefaultJoinConfig(final HazelcastClusterProperties cluster) { val tcpIpConfig = new TcpIpConfig() .setEnabled(cluster.getNetwork().isTcpipEnabled()) .setMembers(cluster.getNetwork().getMembers()) .setConnectionTimeoutSeconds(cluster.getCore().getTimeout()); LOGGER.trace("Created Hazelcast TCP/IP configuration [{}] for members [{}]", tcpIpConfig, cluster.getNetwork().getMembers()); val multicast = cluster.getDiscovery().getMulticast(); val multicastConfig = new MulticastConfig().setEnabled(multicast.isEnabled()); if (multicast.isEnabled()) { LOGGER.debug("Created Hazelcast Multicast configuration [{}]", multicastConfig); multicastConfig.setMulticastGroup(multicast.getGroup()); multicastConfig.setMulticastPort(multicast.getPort()); val trustedInterfaces = StringUtils.commaDelimitedListToSet(multicast.getTrustedInterfaces()); if (!trustedInterfaces.isEmpty()) { multicastConfig.setTrustedInterfaces(trustedInterfaces); } multicastConfig.setMulticastTimeoutSeconds(multicast.getTimeout()); multicastConfig.setMulticastTimeToLive(multicast.getTimeToLive()); } else { LOGGER.debug("Skipped Hazelcast Multicast configuration since feature is disabled"); } return new JoinConfig() .setMulticastConfig(multicastConfig) .setTcpIpConfig(tcpIpConfig); } private static Config finalizeConfig(final Config config, final BaseHazelcastProperties hz) { if (StringUtils.hasText(hz.getCluster().getCore().getPartitionMemberGroupType())) { val partitionGroupConfig = config.getPartitionGroupConfig(); val type = PartitionGroupConfig.MemberGroupType.valueOf( hz.getCluster().getCore().getPartitionMemberGroupType().toUpperCase()); LOGGER.trace("Using partition member group type [{}]", type); partitionGroupConfig.setEnabled(true).setGroupType(type); } return config; } /** * Build map config map config. * * @param hz the hz * @param mapName the storage name * @param timeoutSeconds the timeoutSeconds * @return the map config */ public static NamedConfig buildMapConfig(final BaseHazelcastProperties hz, final String mapName, final long timeoutSeconds) { val cluster = hz.getCluster(); val evictionPolicy = EvictionPolicy.valueOf(cluster.getCore().getEvictionPolicy()); val evictionConfig = new EvictionConfig(); evictionConfig.setEvictionPolicy(evictionPolicy); evictionConfig.setMaxSizePolicy(MaxSizePolicy.valueOf(cluster.getCore().getMaxSizePolicy())); evictionConfig.setSize(cluster.getCore().getMaxSize()); val mergePolicyConfig = new MergePolicyConfig(); if (StringUtils.hasText(cluster.getCore().getMapMergePolicy())) { switch (cluster.getCore().getMapMergePolicy().trim().toLowerCase()) { case "discard": mergePolicyConfig.setPolicy(DiscardMergePolicy.class.getName()); break; case "pass_through": mergePolicyConfig.setPolicy(PassThroughMergePolicy.class.getName()); break; case "expiration_time": mergePolicyConfig.setPolicy(ExpirationTimeMergePolicy.class.getName()); break; case "higher_hits": mergePolicyConfig.setPolicy(HigherHitsMergePolicy.class.getName()); break; case "latest_update": mergePolicyConfig.setPolicy(LatestUpdateMergePolicy.class.getName()); break; case "latest_access": mergePolicyConfig.setPolicy(LatestAccessMergePolicy.class.getName()); break; case "put_if_absent": default: mergePolicyConfig.setPolicy(PutIfAbsentMergePolicy.class.getName()); break; } } if (cluster.getCore().isReplicated()) { return new ReplicatedMapConfig() .setName(mapName) .setStatisticsEnabled(true) .setAsyncFillup(cluster.getCore().isAsyncFillup()) .setInMemoryFormat(InMemoryFormat.BINARY) .setSplitBrainProtectionName(mapName.concat("-SplitBrainProtection")) .setMergePolicyConfig(mergePolicyConfig); } return new MapConfig() .setName(mapName) .setStatisticsEnabled(true) .setMergePolicyConfig(mergePolicyConfig) .setMaxIdleSeconds((int) timeoutSeconds) .setBackupCount(cluster.getCore().getBackupCount()) .setAsyncBackupCount(cluster.getCore().getAsyncBackupCount()) .setEvictionConfig(evictionConfig); } }
3e1737848c1d69e0484e4e0872884e9e3b75032e
4,560
java
Java
server/src/main/java/com/linecorp/centraldogma/server/internal/command/AbstractCommandExecutor.java
jmostella/centraldogma
9c2c14a6702a77293833a990cac27826c73d59c0
[ "Apache-2.0" ]
null
null
null
server/src/main/java/com/linecorp/centraldogma/server/internal/command/AbstractCommandExecutor.java
jmostella/centraldogma
9c2c14a6702a77293833a990cac27826c73d59c0
[ "Apache-2.0" ]
null
null
null
server/src/main/java/com/linecorp/centraldogma/server/internal/command/AbstractCommandExecutor.java
jmostella/centraldogma
9c2c14a6702a77293833a990cac27826c73d59c0
[ "Apache-2.0" ]
null
null
null
35.076923
110
0.640351
9,889
/* * Copyright 2017 LINE Corporation * * LINE Corporation 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: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.linecorp.centraldogma.server.internal.command; import static java.util.Objects.requireNonNull; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ForkJoinPool; import java.util.function.Consumer; import javax.annotation.Nullable; import com.linecorp.armeria.common.util.StartStopSupport; public abstract class AbstractCommandExecutor implements CommandExecutor { @Nullable private final Consumer<CommandExecutor> onTakeLeadership; @Nullable private final Runnable onReleaseLeadership; private final CommandExecutorStartStop startStop = new CommandExecutorStartStop(); private volatile boolean started; protected AbstractCommandExecutor(@Nullable Consumer<CommandExecutor> onTakeLeadership, @Nullable Runnable onReleaseLeadership) { this.onTakeLeadership = onTakeLeadership; this.onReleaseLeadership = onReleaseLeadership; } @Override public final boolean isStarted() { return started; } @Override public final CompletableFuture<Void> start() { return startStop.start(true).thenRun(() -> started = true); } protected abstract void doStart(@Nullable Runnable onTakeLeadership, @Nullable Runnable onReleaseLeadership); @Override public final CompletableFuture<Void> stop() { started = false; return startStop.stop(); } protected abstract void doStop(@Nullable Runnable onReleaseLeadership); @Override public final <T> CompletableFuture<T> execute(Command<T> command) { return execute(replicaId(), command); } @Override public final <T> CompletableFuture<T> execute(int replicaId, Command<T> command) { requireNonNull(command, "command"); if (!isStarted()) { throw new IllegalStateException("running in read-only mode"); } try { return doExecute(replicaId, command); } catch (Throwable t) { final CompletableFuture<T> f = new CompletableFuture<>(); f.completeExceptionally(t); return f; } } protected abstract <T> CompletableFuture<T> doExecute( int replicaId, Command<T> command) throws Exception; private final class CommandExecutorStartStop extends StartStopSupport<Void, Void> { CommandExecutorStartStop() { super(ForkJoinPool.commonPool()); } @Override protected CompletionStage<Void> doStart() throws Exception { return execute("command-executor", () -> { AbstractCommandExecutor.this.doStart( onTakeLeadership != null ? () -> onTakeLeadership.accept(AbstractCommandExecutor.this) : null, onReleaseLeadership); }); } @Override protected CompletionStage<Void> doStop() throws Exception { return execute("command-executor-shutdown", () -> AbstractCommandExecutor.this.doStop(onReleaseLeadership)); } private CompletionStage<Void> execute(String threadNamePrefix, Runnable task) { final CompletableFuture<Void> future = new CompletableFuture<>(); final String threadName = threadNamePrefix + "-0x" + Long.toHexString(AbstractCommandExecutor.this.hashCode() & 0xFFFFFFFFL); final Thread thread = new Thread(() -> { try { task.run(); future.complete(null); } catch (Throwable cause) { future.completeExceptionally(cause); } }, threadName); thread.start(); return future; } } }
3e17385c604ba52e67d1e75c56b1e8699a417a95
479
java
Java
src/test/java/io/millesabords/zeppelin/eclairjs/EclairjsInterpreterTest.java
bbonnin/zeppelin-eclairjs-interpreter
debb792b428fe338f9bab37c540d1715d568937a
[ "Apache-2.0" ]
null
null
null
src/test/java/io/millesabords/zeppelin/eclairjs/EclairjsInterpreterTest.java
bbonnin/zeppelin-eclairjs-interpreter
debb792b428fe338f9bab37c540d1715d568937a
[ "Apache-2.0" ]
null
null
null
src/test/java/io/millesabords/zeppelin/eclairjs/EclairjsInterpreterTest.java
bbonnin/zeppelin-eclairjs-interpreter
debb792b428fe338f9bab37c540d1715d568937a
[ "Apache-2.0" ]
null
null
null
26.611111
85
0.745303
9,890
package io.millesabords.zeppelin.eclairjs; import static org.junit.Assert.assertEquals; import org.apache.zeppelin.interpreter.InterpreterResult; import org.junit.Test; public class EclairjsInterpreterTest { private final EclairjsInterpreter interpreter = new EclairjsInterpreter(null); @Test public void testSimple() { final InterpreterResult res = interpreter.interpret("print('hello');", null); assertEquals("hello\n", res.message()); } }
3e173aa7b215a80b9eddbc961ef796db13f2148d
474
java
Java
src/iterator/MetallicCoverIterator.java
RKreddy1799/HardDiskCoversIterator
626fd1699f39bf31dc413d06e754e2375b3b8cba
[ "Apache-2.0" ]
null
null
null
src/iterator/MetallicCoverIterator.java
RKreddy1799/HardDiskCoversIterator
626fd1699f39bf31dc413d06e754e2375b3b8cba
[ "Apache-2.0" ]
null
null
null
src/iterator/MetallicCoverIterator.java
RKreddy1799/HardDiskCoversIterator
626fd1699f39bf31dc413d06e754e2375b3b8cba
[ "Apache-2.0" ]
null
null
null
19.75
65
0.691983
9,891
package iterator; public class MetallicCoverIterator implements Iterator{ DiskCover[] diskCovers; int index = 0; public MetallicCoverIterator( DiskCover[] diskCovers ) { this.diskCovers = diskCovers; } public DiskCover next() { DiskCover diskCover = diskCovers[index]; index = index + 1; return diskCover; } public boolean hasNext() { if( index >= diskCovers.length || diskCovers[index] == null ) { return false; } else { return true; } } }
3e173af55637853ad3f9a1716a507c01713abf5f
9,145
java
Java
Data/Juliet-Java/Juliet-Java-v103/000/140/898/CWE566_Authorization_Bypass_Through_SQL_Primary__Servlet_22a.java
b19e93n/PLC-Pyramid
6d5b57be6995a94ef7402144cee965862713b031
[ "MIT" ]
null
null
null
Data/Juliet-Java/Juliet-Java-v103/000/140/898/CWE566_Authorization_Bypass_Through_SQL_Primary__Servlet_22a.java
b19e93n/PLC-Pyramid
6d5b57be6995a94ef7402144cee965862713b031
[ "MIT" ]
null
null
null
Data/Juliet-Java/Juliet-Java-v103/000/140/898/CWE566_Authorization_Bypass_Through_SQL_Primary__Servlet_22a.java
b19e93n/PLC-Pyramid
6d5b57be6995a94ef7402144cee965862713b031
[ "MIT" ]
null
null
null
32.314488
140
0.539967
9,892
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE566_Authorization_Bypass_Through_SQL_Primary__Servlet_22a.java Label Definition File: CWE566_Authorization_Bypass_Through_SQL_Primary__Servlet.label.xml Template File: sources-sink-22a.tmpl.java */ /* * @description * CWE: 566 Authorization Bypass through SQL primary * BadSource: user id taken from url parameter * GoodSource: hardcoded user id * Sinks: writeConsole * BadSink : user authorization not checked * Flow Variant: 22 Control flow: Flow controlled by value of a public static variable. Sink functions are in a separate file from sources. * * */ import javax.servlet.http.*; import java.sql.*; import java.util.logging.Level; public class CWE566_Authorization_Bypass_Through_SQL_Primary__Servlet_22a extends AbstractTestCaseServlet { /* The public static variable below is used to drive control flow in the source function. * The public static variable mimics a global variable in the C/C++ language family. */ public static boolean badPublicStatic = false; public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; badPublicStatic = true; data = (new CWE566_Authorization_Bypass_Through_SQL_Primary__Servlet_22b()).badSource(request, response); Connection dBConnection = IO.getDBConnection(); PreparedStatement preparedStatement = null; ResultSet resultSet = null; int id = 0; try { id = Integer.parseInt(data); } catch ( NumberFormatException nfx ) { id = -1; /* Assuming this id does not exist */ } try { preparedStatement = dBConnection.prepareStatement("select * from invoices where uid=?"); preparedStatement.setInt(1, id); resultSet = preparedStatement.executeQuery(); /* POTENTIAL FLAW: no check to see whether the user has privileges to view the data */ IO.writeString("bad() - result requested: " + data +"\n"); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error executing query", exceptSql); } finally { try { if (resultSet != null) { resultSet.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Could not close ResultSet", exceptSql); } try { if (preparedStatement != null) { preparedStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Could not close PreparedStatement", exceptSql); } try { if (dBConnection != null) { dBConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Could not close Connection", exceptSql); } } } /* The public static variables below are used to drive control flow in the source functions. * The public static variable mimics a global variable in the C/C++ language family. */ public static boolean goodG2B1PublicStatic = false; public static boolean goodG2B2PublicStatic = false; public void good(HttpServletRequest request, HttpServletResponse response) throws Throwable { goodG2B1(request, response); goodG2B2(request, response); } /* goodG2B1() - use goodsource and badsink by setting the static variable to false instead of true */ private void goodG2B1(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; goodG2B1PublicStatic = false; data = (new CWE566_Authorization_Bypass_Through_SQL_Primary__Servlet_22b()).goodG2B1Source(request, response); Connection dBConnection = IO.getDBConnection(); PreparedStatement preparedStatement = null; ResultSet resultSet = null; int id = 0; try { id = Integer.parseInt(data); } catch ( NumberFormatException nfx ) { id = -1; /* Assuming this id does not exist */ } try { preparedStatement = dBConnection.prepareStatement("select * from invoices where uid=?"); preparedStatement.setInt(1, id); resultSet = preparedStatement.executeQuery(); /* POTENTIAL FLAW: no check to see whether the user has privileges to view the data */ IO.writeString("bad() - result requested: " + data +"\n"); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error executing query", exceptSql); } finally { try { if (resultSet != null) { resultSet.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Could not close ResultSet", exceptSql); } try { if (preparedStatement != null) { preparedStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Could not close PreparedStatement", exceptSql); } try { if (dBConnection != null) { dBConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Could not close Connection", exceptSql); } } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if in the sink function */ private void goodG2B2(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; goodG2B2PublicStatic = true; data = (new CWE566_Authorization_Bypass_Through_SQL_Primary__Servlet_22b()).goodG2B2Source(request, response); Connection dBConnection = IO.getDBConnection(); PreparedStatement preparedStatement = null; ResultSet resultSet = null; int id = 0; try { id = Integer.parseInt(data); } catch ( NumberFormatException nfx ) { id = -1; /* Assuming this id does not exist */ } try { preparedStatement = dBConnection.prepareStatement("select * from invoices where uid=?"); preparedStatement.setInt(1, id); resultSet = preparedStatement.executeQuery(); /* POTENTIAL FLAW: no check to see whether the user has privileges to view the data */ IO.writeString("bad() - result requested: " + data +"\n"); } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Error executing query", exceptSql); } finally { try { if (resultSet != null) { resultSet.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Could not close ResultSet", exceptSql); } try { if (preparedStatement != null) { preparedStatement.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Could not close PreparedStatement", exceptSql); } try { if (dBConnection != null) { dBConnection.close(); } } catch (SQLException exceptSql) { IO.logger.log(Level.WARNING, "Could not close Connection", exceptSql); } } } /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { mainFromParent(args); } }
3e173b16febfba1e60d2a415751bb9588937d59f
4,962
java
Java
spigot/nms/1.16.2/src/main/java/io/github/karlatemp/karframework/nms/v1_16_R2/NBTComponent.java
Karlatemp/KarFramework
984f8788cca05ea70542df0856f377a7147e6d6f
[ "MIT" ]
3
2020-08-04T18:49:35.000Z
2020-11-27T05:07:57.000Z
spigot/nms/1.16.2/src/main/java/io/github/karlatemp/karframework/nms/v1_16_R2/NBTComponent.java
Karlatemp/KarFramework
984f8788cca05ea70542df0856f377a7147e6d6f
[ "MIT" ]
null
null
null
spigot/nms/1.16.2/src/main/java/io/github/karlatemp/karframework/nms/v1_16_R2/NBTComponent.java
Karlatemp/KarFramework
984f8788cca05ea70542df0856f377a7147e6d6f
[ "MIT" ]
null
null
null
22.880184
79
0.632024
9,893
/* * Copyright (c) 2018-2020 Karlatemp. All rights reserved. * @author Karlatemp <dycjh@example.com> <https://github.com/Karlatemp> * @create 2020/08/04 19:19:39 * * kar-framework/kar-framework.spigot-nms-1_16_1.main/NBTComponend.java */ package io.github.karlatemp.karframework.nms.v1_16_R2; import io.github.karlatemp.karframework.opennbt.ITag; import io.github.karlatemp.karframework.opennbt.ITagCompound; import io.github.karlatemp.karframework.opennbt.ITagList; import net.minecraft.server.v1_16_R2.NBTBase; import net.minecraft.server.v1_16_R2.NBTTagCompound; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Set; import java.util.UUID; public class NBTComponent extends NBTBaseWrapper<NBTTagCompound> implements ITagCompound { public NBTComponent(NBTTagCompound compound) { super(compound); } @Override public @Nullable ITag get(@NotNull String key) { return of(base.get(key)); } @Override public void put(@NotNull String key, @Nullable ITag tag) { set(key, tag); } @Override public @NotNull Set<@NotNull String> keySet() { return base.getKeys(); } @Override public int size() { return base.e(); } @Override public @Nullable ITag set(String key, ITag value) { NBTBase base = value == null ? null : ((NBTBaseWrapper<?>) value).base; return of(super.base.set(key, base)); } @Override public void setByte(String key, byte value) { base.setByte(key, value); } @Override public void setShort(String key, short value) { base.setShort(key, value); } @Override public void setInt(String key, int value) { base.setInt(key, value); } @Override public void setLong(String key, long value) { base.setLong(key, value); } @Override public void setUUID(String key, UUID value) { base.a(key, value); } @Override public UUID getUUID(String key) { return base.a(key); } @Override public void setFloat(String key, float value) { base.setFloat(key, value); } @Override public void setDouble(String key, double value) { base.setDouble(key, value); } @Override public void setString(String key, String value) { base.setString(key, value); } @Override public void setByteArray(String key, byte[] value) { base.setByteArray(key, value); } @Override public void setIntArray(String key, int[] value) { base.setIntArray(key, value); } @Override public void setIntArray(String key, List<Integer> value) { base.b(key, value); } @Override public void setLongArray(String key, long[] value) { base.a(key, value); } @Override public void setLongArray(String key, List<Long> value) { base.c(key, value); } @Override public void setBoolean(String key, boolean value) { base.setBoolean(key, value); } @Override public boolean hasKey(String key) { return base.hasKey(key); } @Override public byte getByte(String key) { return base.getByte(key); } @Override public short getShort(String key) { return base.getShort(key); } @Override public int getInt(String key) { return base.getInt(key); } @Override public long getLong(String key) { return base.getLong(key); } @Override public float getFloat(String key) { return base.getFloat(key); } @Override public double getDouble(String key) { return base.getDouble(key); } @Override public @NotNull String getString(String key) { return base.getString(key); } @Override public @NotNull byte[] getByteArray(String key) { return base.getByteArray(key); } @Override public @NotNull int[] getIntArray(String key) { return base.getIntArray(key); } @Override public @NotNull long[] getLongArray(String key) { return base.getLongArray(key); } @Override public @NotNull ITagCompound getCompound(String key) { return new NBTComponent(base.getCompound(key)); } @Override public @NotNull ITagList getList(String key, int type) { return (ITagList) of(base.getList(key, type)); } @Override public boolean getBoolean(String key) { return base.getBoolean(key); } @Override public void remove(String key) { base.remove(key); } @Override public @NotNull ITagCompound clone() { return new NBTComponent(base.clone()); } @Override public @NotNull ITagCompound merge(@NotNull ITagCompound compound) { base.a(((NBTComponent) compound).base); return this; } }
3e173c9fcaabc9ad5fe03b0504034c854ade9f26
22,224
java
Java
sshd-core/src/main/java/org/apache/sshd/client/session/ClientSessionImpl.java
platformlayer/mina-sshd
b37403ed73b831f915f3a2da47ca436b46a5e8b9
[ "Apache-2.0" ]
1
2015-05-08T14:54:36.000Z
2015-05-08T14:54:36.000Z
sshd-core/src/main/java/org/apache/sshd/client/session/ClientSessionImpl.java
platformlayer/mina-sshd
b37403ed73b831f915f3a2da47ca436b46a5e8b9
[ "Apache-2.0" ]
null
null
null
sshd-core/src/main/java/org/apache/sshd/client/session/ClientSessionImpl.java
platformlayer/mina-sshd
b37403ed73b831f915f3a2da47ca436b46a5e8b9
[ "Apache-2.0" ]
null
null
null
40.484517
154
0.530055
9,894
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sshd.client.session; import java.io.IOException; import java.net.SocketAddress; import java.security.KeyPair; import java.util.HashMap; import java.util.Map; import org.apache.mina.core.session.IoSession; import org.apache.sshd.ClientChannel; import org.apache.sshd.ClientSession; import org.apache.sshd.client.ClientFactoryManager; import org.apache.sshd.client.ServerKeyVerifier; import org.apache.sshd.client.UserAuth; import org.apache.sshd.client.auth.UserAuthAgent; import org.apache.sshd.client.auth.UserAuthPassword; import org.apache.sshd.client.auth.UserAuthPublicKey; import org.apache.sshd.client.channel.ChannelExec; import org.apache.sshd.client.channel.ChannelShell; import org.apache.sshd.client.channel.ChannelSubsystem; import org.apache.sshd.client.future.AuthFuture; import org.apache.sshd.client.future.DefaultAuthFuture; import org.apache.sshd.client.future.OpenFuture; import org.apache.sshd.common.Channel; import org.apache.sshd.common.FactoryManager; import org.apache.sshd.common.KeyExchange; import org.apache.sshd.common.KeyPairProvider; import org.apache.sshd.common.NamedFactory; import org.apache.sshd.common.SshConstants; import org.apache.sshd.common.SshException; import org.apache.sshd.common.future.CloseFuture; import org.apache.sshd.common.future.SshFutureListener; import org.apache.sshd.common.session.AbstractSession; import org.apache.sshd.common.util.Buffer; import org.apache.sshd.server.channel.OpenChannelException; /** * TODO Add javadoc * * @author <a href="mailto:dycjh@example.com">Apache MINA SSHD Project</a> */ public class ClientSessionImpl extends AbstractSession implements ClientSession { public enum State { ReceiveKexInit, Kex, ReceiveNewKeys, AuthRequestSent, WaitForAuth, UserAuth, Running, Unknown } private State state = State.ReceiveKexInit; private UserAuth userAuth; private AuthFuture authFuture; /** * For clients to store their own metadata */ private Map<Object, Object> metadataMap = new HashMap<Object, Object>(); public ClientSessionImpl(FactoryManager client, IoSession session) throws Exception { super(client, session); log.info("Session created..."); sendClientIdentification(); sendKexInit(); } public ClientFactoryManager getClientFactoryManager() { return (ClientFactoryManager) factoryManager; } public KeyExchange getKex() { return kex; } public AuthFuture authAgent(String username) throws IOException { synchronized (lock) { if (closeFuture.isClosed()) { throw new IllegalStateException("Session is closed"); } if (authed) { throw new IllegalStateException("User authentication has already been performed"); } if (userAuth != null) { throw new IllegalStateException("A user authentication request is already pending"); } if (getFactoryManager().getAgentFactory() == null) { throw new IllegalStateException("No ssh agent factory has been configured"); } waitFor(CLOSED | WAIT_AUTH, 0); if (closeFuture.isClosed()) { throw new IllegalStateException("Session is closed"); } authFuture = new DefaultAuthFuture(lock); userAuth = new UserAuthAgent(this, username); setState(ClientSessionImpl.State.UserAuth); switch (userAuth.next(null)) { case Success: authFuture.setAuthed(true); username = userAuth.getUsername(); authed = true; setState(State.Running); break; case Failure: authFuture.setAuthed(false); userAuth = null; setState(State.WaitForAuth); break; case Continued: break; } return authFuture; } } public AuthFuture authPassword(String username, String password) throws IOException { synchronized (lock) { if (closeFuture.isClosed()) { throw new IllegalStateException("Session is closed"); } if (authed) { throw new IllegalStateException("User authentication has already been performed"); } if (userAuth != null) { throw new IllegalStateException("A user authentication request is already pending"); } waitFor(CLOSED | WAIT_AUTH, 0); if (closeFuture.isClosed()) { throw new IllegalStateException("Session is closed"); } authFuture = new DefaultAuthFuture(lock); userAuth = new UserAuthPassword(this, username, password); setState(ClientSessionImpl.State.UserAuth); switch (userAuth.next(null)) { case Success: authFuture.setAuthed(true); username = userAuth.getUsername(); authed = true; setState(State.Running); break; case Failure: authFuture.setAuthed(false); userAuth = null; setState(State.WaitForAuth); break; case Continued: break; } return authFuture; } } public AuthFuture authPublicKey(String username, KeyPair key) throws IOException { synchronized (lock) { if (closeFuture.isClosed()) { throw new IllegalStateException("Session is closed"); } if (authed) { throw new IllegalStateException("User authentication has already been performed"); } if (userAuth != null) { throw new IllegalStateException("A user authentication request is already pending"); } waitFor(CLOSED | WAIT_AUTH, 0); if (closeFuture.isClosed()) { throw new IllegalStateException("Session is closed"); } authFuture = new DefaultAuthFuture(lock); userAuth = new UserAuthPublicKey(this, username, key); setState(ClientSessionImpl.State.UserAuth); switch (userAuth.next(null)) { case Success: authFuture.setAuthed(true); username = userAuth.getUsername(); authed = true; setState(State.Running); break; case Failure: authFuture.setAuthed(false); userAuth = null; setState(State.WaitForAuth); break; case Continued: break; } return authFuture; } } public ClientChannel createChannel(String type) throws Exception { return createChannel(type, null); } public ClientChannel createChannel(String type, String subType) throws Exception { if (ClientChannel.CHANNEL_SHELL.equals(type)) { return createShellChannel(); } else if (ClientChannel.CHANNEL_EXEC.equals(type)) { return createExecChannel(subType); } else if (ClientChannel.CHANNEL_SUBSYSTEM.equals(type)) { return createSubsystemChannel(subType); } else { throw new IllegalArgumentException("Unsupported channel type " + type); } } public ChannelShell createShellChannel() throws Exception { ChannelShell channel = new ChannelShell(); registerChannel(channel); return channel; } public ChannelExec createExecChannel(String command) throws Exception { ChannelExec channel = new ChannelExec(command); registerChannel(channel); return channel; } public ChannelSubsystem createSubsystemChannel(String subsystem) throws Exception { ChannelSubsystem channel = new ChannelSubsystem(subsystem); registerChannel(channel); return channel; } @Override public CloseFuture close(boolean immediately) { synchronized (lock) { if (authFuture != null && !authFuture.isDone()) { authFuture.setException(new SshException("Session is closed")); } return super.close(immediately); } } protected void handleMessage(Buffer buffer) throws Exception { synchronized (lock) { doHandleMessage(buffer); } } protected void doHandleMessage(Buffer buffer) throws Exception { SshConstants.Message cmd = buffer.getCommand(); log.debug("Received packet {}", cmd); switch (cmd) { case SSH_MSG_DISCONNECT: { int code = buffer.getInt(); String msg = buffer.getString(); log.info("Received SSH_MSG_DISCONNECT (reason={}, msg={})", code, msg); close(false); break; } case SSH_MSG_UNIMPLEMENTED: { int code = buffer.getInt(); log.info("Received SSH_MSG_UNIMPLEMENTED #{}", code); break; } case SSH_MSG_DEBUG: { boolean display = buffer.getBoolean(); String msg = buffer.getString(); log.info("Received SSH_MSG_DEBUG (display={}) '{}'", display, msg); break; } case SSH_MSG_IGNORE: log.info("Received SSH_MSG_IGNORE"); break; default: switch (state) { case ReceiveKexInit: if (cmd != SshConstants.Message.SSH_MSG_KEXINIT) { log.error("Ignoring command " + cmd + " while waiting for " + SshConstants.Message.SSH_MSG_KEXINIT); break; } log.info("Received SSH_MSG_KEXINIT"); receiveKexInit(buffer); negociate(); kex = NamedFactory.Utils.create(factoryManager.getKeyExchangeFactories(), negociated[SshConstants.PROPOSAL_KEX_ALGS]); kex.init(this, serverVersion.getBytes(), clientVersion.getBytes(), I_S, I_C); setState(State.Kex); break; case Kex: buffer.rpos(buffer.rpos() - 1); if (kex.next(buffer)) { checkHost(); sendNewKeys(); setState(State.ReceiveNewKeys); } break; case ReceiveNewKeys: if (cmd != SshConstants.Message.SSH_MSG_NEWKEYS) { disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, "Protocol error: expected packet SSH_MSG_NEWKEYS, got " + cmd); return; } log.info("Received SSH_MSG_NEWKEYS"); receiveNewKeys(false); sendAuthRequest(); setState(State.AuthRequestSent); break; case AuthRequestSent: if (cmd != SshConstants.Message.SSH_MSG_SERVICE_ACCEPT) { disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, "Protocol error: expected packet SSH_MSG_SERVICE_ACCEPT, got " + cmd); return; } setState(State.WaitForAuth); break; case WaitForAuth: // We're waiting for the client to send an authentication request // TODO: handle unexpected incoming packets break; case UserAuth: if (userAuth == null) { throw new IllegalStateException("State is userAuth, but no user auth pending!!!"); } buffer.rpos(buffer.rpos() - 1); switch (userAuth.next(buffer)) { case Success: authFuture.setAuthed(true); username = userAuth.getUsername(); authed = true; setState(State.Running); break; case Failure: authFuture.setAuthed(false); userAuth = null; setState(State.WaitForAuth); break; case Continued: break; } break; case Running: switch (cmd) { case SSH_MSG_CHANNEL_OPEN: channelOpen(buffer); break; case SSH_MSG_CHANNEL_OPEN_CONFIRMATION: channelOpenConfirmation(buffer); break; case SSH_MSG_CHANNEL_OPEN_FAILURE: channelOpenFailure(buffer); break; case SSH_MSG_CHANNEL_REQUEST: channelRequest(buffer); break; case SSH_MSG_CHANNEL_DATA: channelData(buffer); break; case SSH_MSG_CHANNEL_EXTENDED_DATA: channelExtendedData(buffer); break; case SSH_MSG_CHANNEL_FAILURE: channelFailure(buffer); break; case SSH_MSG_CHANNEL_WINDOW_ADJUST: channelWindowAdjust(buffer); break; case SSH_MSG_CHANNEL_EOF: channelEof(buffer); break; case SSH_MSG_CHANNEL_CLOSE: channelClose(buffer); break; default: throw new IllegalStateException("Unsupported command: " + cmd); } break; default: throw new IllegalStateException("Unsupported state: " + state); } } } public int waitFor(int mask, long timeout) { long t = 0; synchronized (lock) { for (;;) { int cond = 0; if (closeFuture.isClosed()) { cond |= CLOSED; } if (authed) { cond |= AUTHED; } if (state == State.WaitForAuth) { cond |= WAIT_AUTH; } if ((cond & mask) != 0) { return cond; } if (timeout > 0) { if (t == 0) { t = System.currentTimeMillis() + timeout; } else { timeout = t - System.currentTimeMillis(); if (timeout <= 0) { cond |= TIMEOUT; return cond; } } } try { if (timeout > 0) { lock.wait(timeout); } else { lock.wait(); } } catch (InterruptedException e) { // Ignore } } } } public void setState(State newState) { synchronized (lock) { this.state = newState; lock.notifyAll(); } } protected boolean readIdentification(Buffer buffer) throws IOException { serverVersion = doReadIdentification(buffer); if (serverVersion == null) { return false; } log.info("Server version string: {}", serverVersion); if (!(serverVersion.startsWith("SSH-2.0-") || serverVersion.startsWith("SSH-1.99-"))) { throw new SshException(SshConstants.SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED, "Unsupported protocol version: " + serverVersion); } return true; } private void sendClientIdentification() { clientVersion = "SSH-2.0-" + getFactoryManager().getVersion(); sendIdentification(clientVersion); } private void sendKexInit() throws Exception { clientProposal = createProposal(KeyPairProvider.SSH_RSA + "," + KeyPairProvider.SSH_DSS); I_C = sendKexInit(clientProposal); } private void receiveKexInit(Buffer buffer) throws Exception { serverProposal = new String[SshConstants.PROPOSAL_MAX]; I_S = receiveKexInit(buffer, serverProposal); } private void checkHost() throws SshException { ServerKeyVerifier serverKeyVerifier = getClientFactoryManager().getServerKeyVerifier(); if (serverKeyVerifier != null) { SocketAddress remoteAddress = ioSession.getRemoteAddress(); if (!serverKeyVerifier.verifyServerKey(this, remoteAddress, kex.getServerKey())) throw new SshException("Server key did not validate"); } } private void sendAuthRequest() throws Exception { log.info("Send SSH_MSG_SERVICE_REQUEST for ssh-userauth"); Buffer buffer = createBuffer(SshConstants.Message.SSH_MSG_SERVICE_REQUEST, 0); buffer.putString("ssh-userauth"); writePacket(buffer); } private void channelOpen(Buffer buffer) throws Exception { String type = buffer.getString(); final int id = buffer.getInt(); final int rwsize = buffer.getInt(); final int rmpsize = buffer.getInt(); log.info("Received SSH_MSG_CHANNEL_OPEN {}", type); if (closing) { Buffer buf = createBuffer(SshConstants.Message.SSH_MSG_CHANNEL_OPEN_FAILURE, 0); buf.putInt(id); buf.putInt(SshConstants.SSH_OPEN_CONNECT_FAILED); buf.putString("SSH server is shutting down: " + type); buf.putString(""); writePacket(buf); return; } final Channel channel = NamedFactory.Utils.create(getFactoryManager().getChannelFactories(), type); if (channel == null) { Buffer buf = createBuffer(SshConstants.Message.SSH_MSG_CHANNEL_OPEN_FAILURE, 0); buf.putInt(id); buf.putInt(SshConstants.SSH_OPEN_UNKNOWN_CHANNEL_TYPE); buf.putString("Unsupported channel type: " + type); buf.putString(""); writePacket(buf); return; } final int channelId = getNextChannelId(); channels.put(channelId, channel); channel.init(this, channelId); channel.open(id, rwsize, rmpsize, buffer).addListener(new SshFutureListener<OpenFuture>() { public void operationComplete(OpenFuture future) { try { if (future.isOpened()) { Buffer buf = createBuffer(SshConstants.Message.SSH_MSG_CHANNEL_OPEN_CONFIRMATION, 0); buf.putInt(id); buf.putInt(channelId); buf.putInt(channel.getLocalWindow().getSize()); buf.putInt(channel.getLocalWindow().getPacketSize()); writePacket(buf); } else if (future.getException() != null) { Buffer buf = createBuffer(SshConstants.Message.SSH_MSG_CHANNEL_OPEN_FAILURE, 0); buf.putInt(id); if (future.getException() instanceof OpenChannelException) { buf.putInt(((OpenChannelException)future.getException()).getReasonCode()); buf.putString(future.getException().getMessage()); } else { buf.putInt(0); buf.putString("Error opening channel: " + future.getException().getMessage()); } buf.putString(""); writePacket(buf); } } catch (IOException e) { exceptionCaught(e); } } }); } public Map<Object, Object> getMetadataMap() { return metadataMap; } }
3e173e3ceffa7216ef1894cef6ca2c1ca7fc16c8
396
java
Java
src/main/java/bftsmart/communication/MacAuthenticationException.java
wujifengcn/bftsmart
8ea1856cad7d68f0bcd2c1e414eac88499158ca1
[ "Apache-2.0" ]
null
null
null
src/main/java/bftsmart/communication/MacAuthenticationException.java
wujifengcn/bftsmart
8ea1856cad7d68f0bcd2c1e414eac88499158ca1
[ "Apache-2.0" ]
null
null
null
src/main/java/bftsmart/communication/MacAuthenticationException.java
wujifengcn/bftsmart
8ea1856cad7d68f0bcd2c1e414eac88499158ca1
[ "Apache-2.0" ]
null
null
null
17.217391
69
0.75
9,895
package bftsmart.communication; /** * 连接认证错误; * <p> * * @author huanghaiquan * */ public class MacAuthenticationException extends Exception { private static final long serialVersionUID = 5898942127123704248L; public MacAuthenticationException(String message) { super(message); } public MacAuthenticationException(String message, Throwable cause) { super(message, cause); } }
3e173f0c7fc90038326db658a2ad4153211e08c4
13,909
java
Java
app/src/main/java/com/kerneladiutormod/reborn/fragments/kernel/GPUFragment.java
Akianonymus/kernel_adiutor
11be0c02b78c632f3e9dd15c1525a454e9693545
[ "Apache-2.0" ]
2
2018-05-19T00:41:00.000Z
2021-09-18T16:26:14.000Z
app/src/main/java/com/kerneladiutormod/reborn/fragments/kernel/GPUFragment.java
vaginessa/KernelAdiutor-Mod-Reborn
b320781add5873d3423216f0b4f4e6f01644297a
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/kerneladiutormod/reborn/fragments/kernel/GPUFragment.java
vaginessa/KernelAdiutor-Mod-Reborn
b320781add5873d3423216f0b4f4e6f01644297a
[ "Apache-2.0" ]
null
null
null
42.405488
122
0.674455
9,896
/* * Copyright (C) 2015 Willi Ye * * 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.kerneladiutormod.reborn.fragments.kernel; import android.os.Bundle; import com.kerneladiutormod.reborn.R; import com.kerneladiutormod.reborn.elements.DDivider; import com.kerneladiutormod.reborn.elements.cards.CardViewItem; import com.kerneladiutormod.reborn.elements.cards.PopupCardView; import com.kerneladiutormod.reborn.elements.cards.SeekBarCardView; import com.kerneladiutormod.reborn.elements.cards.SwitchCardView; import com.kerneladiutormod.reborn.fragments.RecyclerViewFragment; import com.kerneladiutormod.reborn.utils.kernel.GPU; import java.util.ArrayList; import java.util.List; /** * Created by willi on 26.12.14. */ public class GPUFragment extends RecyclerViewFragment implements PopupCardView.DPopupCard.OnDPopupCardListener, SwitchCardView.DSwitchCard.OnDSwitchCardListener, SeekBarCardView.DSeekBarCard.OnDSeekBarCardListener { private CardViewItem.DCardView mCur2dFreqCard, mCurFreqCard; private PopupCardView.DPopupCard mMax2dFreqCard, mMaxFreqCard; private PopupCardView.DPopupCard mMinFreqCard; private PopupCardView.DPopupCard m2dGovernorCard, mGovernorCard; private SwitchCardView.DSwitchCard mGamingModeGpuCard; private SwitchCardView.DSwitchCard mSimpleGpuCard; private SeekBarCardView.DSeekBarCard mSimpleGpuLazinessCard, mSimpleGpuRampThresoldCard; private SwitchCardView.DSwitchCard mAdrenoIdlerCard; private SeekBarCardView.DSeekBarCard mAdrenoIdlerDownDiffCard, mAdrenoIdlerIdleWaitCard, mAdrenoIdlerIdleWorkloadCard; @Override public void init(Bundle savedInstanceState) { super.init(savedInstanceState); curFreqInit(); maxFreqInit(); minFreqInit(); governorInit(); if (GPU.hasGPUMinPowerLevel()) gamingmodeInit(); if (GPU.hasSimpleGpu()) simpleGpuInit(); if (GPU.hasAdrenoIdler()) adrenoIdlerInit(); } private void curFreqInit() { if (GPU.hasGpu2dCurFreq()) { mCur2dFreqCard = new CardViewItem.DCardView(); mCur2dFreqCard.setTitle(getString(R.string.gpu_2d_cur_freq)); addView(mCur2dFreqCard); } if (GPU.hasGpuCurFreq()) { mCurFreqCard = new CardViewItem.DCardView(); mCurFreqCard.setTitle(getString(R.string.gpu_cur_freq)); addView(mCurFreqCard); } } private void maxFreqInit() { if (GPU.hasGpu2dMaxFreq() && GPU.hasGpu2dFreqs()) { List<String> freqs = new ArrayList<>(); for (int freq : GPU.getGpu2dFreqs()) { if ((freq / 1000000) < 1) { freqs.add(freq / 1000 + getString(R.string.mhz)); } else { freqs.add(freq / 1000000 + getString(R.string.mhz)); } } mMax2dFreqCard = new PopupCardView.DPopupCard(freqs); mMax2dFreqCard.setTitle(getString(R.string.gpu_2d_max_freq)); mMax2dFreqCard.setDescription(getString(R.string.gpu_2d_max_freq_summary)); if ((GPU.getGpu2dMaxFreq() / 1000000) < 1) { mMax2dFreqCard.setItem(GPU.getGpu2dMaxFreq() / 1000 + getString(R.string.mhz)); } else { mMax2dFreqCard.setItem(GPU.getGpu2dMaxFreq() / 1000000 + getString(R.string.mhz)); } mMax2dFreqCard.setOnDPopupCardListener(this); addView(mMax2dFreqCard); } if (GPU.hasGpuMaxFreq() && GPU.hasGpuFreqs()) { List<String> freqs = new ArrayList<>(); for (int freq : GPU.getGpuFreqs()) { if ((freq / 1000000) < 1) { freqs.add(freq / 1000 + getString(R.string.mhz)); } else { freqs.add(freq / 1000000 + getString(R.string.mhz)); } } mMaxFreqCard = new PopupCardView.DPopupCard(freqs); mMaxFreqCard.setTitle(getString(R.string.gpu_max_freq)); mMaxFreqCard.setDescription(getString(R.string.gpu_max_freq_summary)); if ((GPU.getGpuMaxFreq() / 1000000) < 1) { mMaxFreqCard.setItem(GPU.getGpuMaxFreq() / 1000 + getString(R.string.mhz)); } else { mMaxFreqCard.setItem(GPU.getGpuMaxFreq() / 1000000 + getString(R.string.mhz)); } mMaxFreqCard.setOnDPopupCardListener(this); addView(mMaxFreqCard); } } private void minFreqInit() { if (GPU.hasGpuMinFreq() && GPU.hasGpuFreqs()) { List<String> freqs = new ArrayList<>(); for (int freq : GPU.getGpuFreqs()) { if ((freq / 1000000) < 1) { freqs.add(freq / 1000 + getString(R.string.mhz)); } else { freqs.add(freq / 1000000 + getString(R.string.mhz)); } } mMinFreqCard = new PopupCardView.DPopupCard(freqs); mMinFreqCard.setTitle(getString(R.string.gpu_min_freq)); mMinFreqCard.setDescription(getString(R.string.gpu_min_freq_summary)); if ((GPU.getGpuMinFreq() / 1000000) < 1) { mMinFreqCard.setItem(GPU.getGpuMinFreq() / 1000 + getString(R.string.mhz)); } else { mMinFreqCard.setItem(GPU.getGpuMinFreq() / 1000000 + getString(R.string.mhz)); } mMinFreqCard.setOnDPopupCardListener(this); addView(mMinFreqCard); } } private void governorInit() { if (GPU.hasGpu2dGovernor()) { m2dGovernorCard = new PopupCardView.DPopupCard(GPU.getGpu2dGovernors()); m2dGovernorCard.setTitle(getString(R.string.gpu_2d_governor)); m2dGovernorCard.setDescription(getString(R.string.gpu_2d_governor_summary)); m2dGovernorCard.setItem(GPU.getGpu2dGovernor()); m2dGovernorCard.setOnDPopupCardListener(this); addView(m2dGovernorCard); } if (GPU.hasGpuGovernor()) { mGovernorCard = new PopupCardView.DPopupCard(GPU.getGpuGovernors()); mGovernorCard.setTitle(getString(R.string.gpu_governor)); mGovernorCard.setDescription(getString(R.string.gpu_governor_summary)); mGovernorCard.setItem(GPU.getGpuGovernor()); mGovernorCard.setOnDPopupCardListener(this); addView(mGovernorCard); } } private void gamingmodeInit() { if (GPU.hasGPUMinPowerLevel()) { mGamingModeGpuCard = new SwitchCardView.DSwitchCard(); mGamingModeGpuCard.setTitle(getString(R.string.gpu_gaming_mode)); mGamingModeGpuCard.setDescription(getString(R.string.gpu_gaming_mode_summary)); mGamingModeGpuCard.setChecked(GPU.isGamingModeActive()); mGamingModeGpuCard.setOnDSwitchCardListener(this); addView(mGamingModeGpuCard); } } private void simpleGpuInit() { DDivider mSimpleGpuDividerCard = new DDivider(); mSimpleGpuDividerCard.setText(getString(R.string.simple_gpu_algorithm)); addView(mSimpleGpuDividerCard); mSimpleGpuCard = new SwitchCardView.DSwitchCard(); mSimpleGpuCard.setTitle(getString(R.string.simple_gpu_algorithm)); mSimpleGpuCard.setDescription(getString(R.string.simple_gpu_algorithm_summary)); mSimpleGpuCard.setChecked(GPU.isSimpleGpuActive()); mSimpleGpuCard.setOnDSwitchCardListener(this); addView(mSimpleGpuCard); List<String> list = new ArrayList<>(); for (int i = 0; i < 11; i++) list.add(String.valueOf(i)); mSimpleGpuLazinessCard = new SeekBarCardView.DSeekBarCard(list); mSimpleGpuLazinessCard.setTitle(getString(R.string.laziness)); mSimpleGpuLazinessCard.setDescription(getString(R.string.laziness_summary)); mSimpleGpuLazinessCard.setProgress(GPU.getSimpleGpuLaziness()); mSimpleGpuLazinessCard.setOnDSeekBarCardListener(this); addView(mSimpleGpuLazinessCard); mSimpleGpuRampThresoldCard = new SeekBarCardView.DSeekBarCard(list); mSimpleGpuRampThresoldCard.setTitle(getString(R.string.ramp_thresold)); mSimpleGpuRampThresoldCard.setDescription(getString(R.string.ramp_thresold_summary)); mSimpleGpuRampThresoldCard.setProgress(GPU.getSimpleGpuRampThreshold()); mSimpleGpuRampThresoldCard.setOnDSeekBarCardListener(this); addView(mSimpleGpuRampThresoldCard); } private void adrenoIdlerInit() { DDivider mAndrenoIdlerDivider = new DDivider(); mAndrenoIdlerDivider.setText(getString(R.string.adreno_idler)); addView(mAndrenoIdlerDivider); mAdrenoIdlerCard = new SwitchCardView.DSwitchCard(); mAdrenoIdlerCard.setTitle(getString(R.string.adreno_idler)); mAdrenoIdlerCard.setDescription(getString(R.string.adreno_idler_summary)); mAdrenoIdlerCard.setChecked(GPU.isAdrenoIdlerActive()); mAdrenoIdlerCard.setOnDSwitchCardListener(this); addView(mAdrenoIdlerCard); { List<String> list = new ArrayList<>(); for (int i = 0; i < 100; i++) list.add(String.valueOf(i)); mAdrenoIdlerDownDiffCard = new SeekBarCardView.DSeekBarCard(list); mAdrenoIdlerDownDiffCard.setTitle(getString(R.string.down_differential)); mAdrenoIdlerDownDiffCard.setDescription(getString(R.string.down_differential_summary)); mAdrenoIdlerDownDiffCard.setProgress(GPU.getAdrenoIdlerDownDiff()); mAdrenoIdlerDownDiffCard.setOnDSeekBarCardListener(this); addView(mAdrenoIdlerDownDiffCard); mAdrenoIdlerIdleWaitCard = new SeekBarCardView.DSeekBarCard(list); mAdrenoIdlerIdleWaitCard.setTitle(getString(R.string.idle_wait)); mAdrenoIdlerIdleWaitCard.setDescription(getString(R.string.idle_wait_summary)); mAdrenoIdlerIdleWaitCard.setProgress(GPU.getAdrenoIdlerIdleWait()); mAdrenoIdlerIdleWaitCard.setOnDSeekBarCardListener(this); addView(mAdrenoIdlerIdleWaitCard); } { List<String> list = new ArrayList<>(); for (int i = 1; i < 11; i++) list.add(String.valueOf(i)); mAdrenoIdlerIdleWorkloadCard = new SeekBarCardView.DSeekBarCard(list); mAdrenoIdlerIdleWorkloadCard.setTitle(getString(R.string.workload)); mAdrenoIdlerIdleWorkloadCard.setDescription(getString(R.string.workload_summary)); mAdrenoIdlerIdleWorkloadCard.setProgress(GPU.getAdrenoIdlerIdleWorkload() - 1); mAdrenoIdlerIdleWorkloadCard.setOnDSeekBarCardListener(this); addView(mAdrenoIdlerIdleWorkloadCard); } } @Override public void onItemSelected(PopupCardView.DPopupCard dPopupCard, int position) { if (dPopupCard == mMax2dFreqCard) GPU.setGpu2dMaxFreq(GPU.getGpu2dFreqs().get(position), getActivity()); else if (dPopupCard == mMaxFreqCard) GPU.setGpuMaxFreq(GPU.getGpuFreqs().get(position), getActivity()); else if (dPopupCard == mMinFreqCard) GPU.setGpuMinFreq(GPU.getGpuFreqs().get(position), getActivity()); else if (dPopupCard == m2dGovernorCard) GPU.setGpu2dGovernor(GPU.getGpu2dGovernors().get(position), getActivity()); else if (dPopupCard == mGovernorCard) GPU.setGpuGovernor(GPU.getGpuGovernors().get(position), getActivity()); } @Override public void onChecked(SwitchCardView.DSwitchCard dSwitchCard, boolean checked) { if (dSwitchCard == mSimpleGpuCard) GPU.activateSimpleGpu(checked, getActivity()); else if (dSwitchCard == mAdrenoIdlerCard) GPU.activateAdrenoIdler(checked, getActivity()); else if (dSwitchCard == mGamingModeGpuCard) GPU.activateGamingMode(checked, getActivity()); } @Override public void onChanged(SeekBarCardView.DSeekBarCard dSeekBarCard, int position) { } @Override public void onStop(SeekBarCardView.DSeekBarCard dSeekBarCard, int position) { if (dSeekBarCard == mSimpleGpuLazinessCard) GPU.setSimpleGpuLaziness(position, getActivity()); else if (dSeekBarCard == mSimpleGpuRampThresoldCard) GPU.setSimpleGpuRampThreshold(position, getActivity()); else if (dSeekBarCard == mAdrenoIdlerDownDiffCard) GPU.setAdrenoIdlerDownDiff(position, getActivity()); else if (dSeekBarCard == mAdrenoIdlerIdleWaitCard) GPU.setAdrenoIdlerIdleWait(position, getActivity()); else if (dSeekBarCard == mAdrenoIdlerIdleWorkloadCard) GPU.setAdrenoIdlerIdleWorkload(position + 1, getActivity()); } @Override public boolean onRefresh() { if (mCur2dFreqCard != null) { if ((GPU.getGpu2dCurFreq() / 1000000) < 1) { mCur2dFreqCard.setDescription((GPU.getGpu2dCurFreq() / 1000) + getString(R.string.mhz)); } else { mCur2dFreqCard.setDescription((GPU.getGpu2dCurFreq() / 1000000) + getString(R.string.mhz)); } } if (mCurFreqCard != null) { if ((GPU.getGpuCurFreq() / 1000000) < 1) { mCurFreqCard.setDescription((GPU.getGpuCurFreq() / 1000) + getString(R.string.mhz)); } else { mCurFreqCard.setDescription((GPU.getGpuCurFreq() / 1000000) + getString(R.string.mhz)); } } return true; } }
3e173f66ad6f2366213655c6339baf3db1d584e8
392
java
Java
src/test/java/com/code/some/games/tegback/TegBackApplicationITests.java
famaridon/teg-back
08dc920d209db1ebcff25100f4e741145059c1d5
[ "MIT" ]
3
2019-09-03T10:53:47.000Z
2019-09-03T10:54:34.000Z
src/test/java/com/code/some/games/tegback/TegBackApplicationITests.java
famaridon/teg-back
08dc920d209db1ebcff25100f4e741145059c1d5
[ "MIT" ]
null
null
null
src/test/java/com/code/some/games/tegback/TegBackApplicationITests.java
famaridon/teg-back
08dc920d209db1ebcff25100f4e741145059c1d5
[ "MIT" ]
null
null
null
23.058824
70
0.818878
9,897
package com.code.some.games.tegback; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) @SpringBootTest public class TegBackApplicationITests { @Test public void contextLoads() { } }
3e174016cdff99e5a099e53a1d3fe78e61bd0546
2,501
java
Java
flink-core/src/main/java/org/apache/flink/api/python/PythonGatewayServer.java
jainanuj07/flink
b92365d442aafec3a42522eb2c7873b7cecc5cef
[ "Apache-2.0" ]
9
2016-09-22T22:53:13.000Z
2019-11-30T03:07:29.000Z
flink-core/src/main/java/org/apache/flink/api/python/PythonGatewayServer.java
jainanuj07/flink
b92365d442aafec3a42522eb2c7873b7cecc5cef
[ "Apache-2.0" ]
null
null
null
flink-core/src/main/java/org/apache/flink/api/python/PythonGatewayServer.java
jainanuj07/flink
b92365d442aafec3a42522eb2c7873b7cecc5cef
[ "Apache-2.0" ]
null
null
null
32.064103
93
0.730908
9,898
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.api.python; import py4j.GatewayServer; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.InetAddress; /** * The Py4j Gateway Server provides RPC service for user's python process. */ public class PythonGatewayServer { /** * <p> * Main method to start a local GatewayServer on a ephemeral port. * It tells python side via a file. * * See: py4j.GatewayServer.main() * </p> */ public static void main(String[] args) throws IOException { InetAddress localhost = InetAddress.getLoopbackAddress(); GatewayServer gatewayServer = new GatewayServer.GatewayServerBuilder() .javaPort(0) .javaAddress(localhost) .build(); gatewayServer.start(); int boundPort = gatewayServer.getListeningPort(); if (boundPort == -1) { System.out.println("GatewayServer failed to bind; exiting"); System.exit(1); } // Tells python side the port of our java rpc server String handshakeFilePath = System.getenv("_PYFLINK_CONN_INFO_PATH"); File handshakeFile = new File(handshakeFilePath); if (handshakeFile.createNewFile()) { FileOutputStream fileOutputStream = new FileOutputStream(handshakeFile); DataOutputStream stream = new DataOutputStream(fileOutputStream); stream.writeInt(boundPort); stream.close(); fileOutputStream.close(); } else { System.out.println("Can't create handshake file: " + handshakeFilePath + ", now exit..."); return; } // Exit on EOF or broken pipe. This ensures that the server dies // if its parent program dies. while (System.in.read() != -1) { // Do nothing } gatewayServer.shutdown(); } }
3e17407c2bc7bce689b77952f0cd21dd5528e34f
3,124
java
Java
sdk/src/main/java/com/jccdex/rpc/core/coretypes/STArray.java
xdjiang/Jcc_Jingtum_java
bf6920be02762c5676538df228fc7e2eb9d42fbd
[ "MIT" ]
null
null
null
sdk/src/main/java/com/jccdex/rpc/core/coretypes/STArray.java
xdjiang/Jcc_Jingtum_java
bf6920be02762c5676538df228fc7e2eb9d42fbd
[ "MIT" ]
null
null
null
sdk/src/main/java/com/jccdex/rpc/core/coretypes/STArray.java
xdjiang/Jcc_Jingtum_java
bf6920be02762c5676538df228fc7e2eb9d42fbd
[ "MIT" ]
1
2021-09-10T10:55:18.000Z
2021-09-10T10:55:18.000Z
29.196262
82
0.629321
9,899
package com.jccdex.rpc.core.coretypes; import java.util.ArrayList; import com.jccdex.core.serialized.BytesSink; import org.json.JSONArray; import org.json.JSONObject; import com.jccdex.rpc.core.fields.Field; import com.jccdex.rpc.core.fields.STArrayField; import com.jccdex.rpc.core.fields.Type; import com.jccdex.rpc.core.serialized.BinaryParser; import com.jccdex.rpc.core.serialized.SerializedType; import com.jccdex.rpc.core.serialized.TypeTranslator; public class STArray extends ArrayList<STObject> implements SerializedType { public JSONArray toJSONArray() { JSONArray array = new JSONArray(); for (STObject so : this) { array.put(so.toJSON()); } return array; } @Override public Object toJSON() { return toJSONArray(); } @Override public byte[] toBytes() { return translate.toBytes(this); } @Override public String toHex() { return translate.toHex(this); } @Override public void toBytesSink(BytesSink to) { for (STObject stObject : this) { stObject.toBytesSink(to); } } @Override public Type type() { return Type.STArray; } public static class Translator extends TypeTranslator<STArray> { @Override public STArray fromParser(BinaryParser parser, Integer hint) { STArray stArray = new STArray(); while (!parser.end()) { Field field = parser.readField(); if (field == Field.ArrayEndMarker) { break; } STObject outer = new STObject(); // assert field.getType() == Type.STObject; outer.put(field, STObject.translate.fromParser(parser)); stArray.add(STObject.formatted(outer)); } return stArray; } @Override public JSONArray toJSONArray(STArray obj) { return obj.toJSONArray(); } @Override public STArray fromJSONArray(JSONArray jsonArray) { STArray arr = new STArray(); for (int i = 0; i < jsonArray.length(); i++) { Object o = jsonArray.get(i); arr.add(STObject.fromJSONObject((JSONObject) o)); } return arr; } } static public Translator translate = new Translator(); public STArray(){} public static STArrayField starrayField(final Field f) { return new STArrayField(){ @Override public Field getField() {return f;}}; } static public STArrayField AffectedNodes = starrayField(Field.AffectedNodes); static public STArrayField SignerEntries = starrayField(Field.SignerEntries); static public STArrayField Signers = starrayField(Field.Signers); static public STArrayField Template = starrayField(Field.Template); static public STArrayField Necessary = starrayField(Field.Necessary); static public STArrayField Sufficient = starrayField(Field.Sufficient); static public STArrayField Memos = starrayField(Field.Memos); }
3e17412ada976c71190449d509a3e8f1a847cc38
5,307
java
Java
app/src/main/java/net/named_data/jndn/encrypt/algo/RsaAlgorithm.java
luckiday/AR-Toolbox
0792b20ec1e741070c9da847f1b91db15d96225a
[ "Apache-2.0" ]
1
2021-06-07T23:46:09.000Z
2021-06-07T23:46:09.000Z
app/src/main/java/net/named_data/jndn/encrypt/algo/RsaAlgorithm.java
luckiday/AR-Toolbox
0792b20ec1e741070c9da847f1b91db15d96225a
[ "Apache-2.0" ]
null
null
null
app/src/main/java/net/named_data/jndn/encrypt/algo/RsaAlgorithm.java
luckiday/AR-Toolbox
0792b20ec1e741070c9da847f1b91db15d96225a
[ "Apache-2.0" ]
null
null
null
37.935714
95
0.730936
9,900
/** * Copyright (C) 2015-2019 Regents of the University of California. * @author: Jeff Thompson <dycjh@example.com> * @author: From ndn-group-encrypt src/algo/rsa https://github.com/named-data/ndn-group-encrypt * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * A copy of the GNU Lesser General Public License is in the file COPYING. */ // (This is ported from ndn::gep::algo::Rsa, and named RsaAlgorithm because // "Rsa" is very short and not all the Common Client Libraries have namespaces.) package net.named_data.jndn.encrypt.algo; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import net.named_data.jndn.encrypt.DecryptKey; import net.named_data.jndn.encrypt.EncryptKey; import net.named_data.jndn.security.RsaKeyParams; import net.named_data.jndn.security.tpm.TpmPrivateKey; import net.named_data.jndn.util.Blob; import net.named_data.jndn.security.SecurityException; import net.named_data.jndn.security.UnrecognizedKeyFormatException; import net.named_data.jndn.security.certificate.PublicKey; /** * The RsaAlgorithm class provides static methods to manipulate keys, encrypt * and decrypt using RSA. * @note This class is an experimental feature. The API may change. */ public class RsaAlgorithm { /** * Generate a new random decrypt key for RSA based on the given params. * @param params The key params with the key size (in bits). * @return The new decrypt key (PKCS8-encoded private key). */ public static DecryptKey generateKey(RsaKeyParams params) throws SecurityException { TpmPrivateKey privateKey; try { privateKey = TpmPrivateKey.generatePrivateKey(params); } catch (IllegalArgumentException ex) { throw new SecurityException("generateKey: Error in generatePrivateKey: " + ex); } catch (TpmPrivateKey.Error ex) { throw new SecurityException("generateKey: Error in generatePrivateKey: " + ex); } try { return new DecryptKey(privateKey.toPkcs8()); } catch (TpmPrivateKey.Error ex) { throw new SecurityException("generateKey: Error in toPkcs8: " + ex); } } /** * Derive a new encrypt key from the given decrypt key value. * @param keyBits The key value of the decrypt key (PKCS8-encoded private * key). * @return The new encrypt key (DER-encoded public key). */ public static EncryptKey deriveEncryptKey(Blob keyBits) throws SecurityException { TpmPrivateKey privateKey = new TpmPrivateKey(); try { privateKey.loadPkcs8(keyBits.buf()); } catch (TpmPrivateKey.Error ex) { throw new SecurityException("deriveEncryptKey: Error in loadPkcs8: " + ex); } try { return new EncryptKey(privateKey.derivePublicKey()); } catch (TpmPrivateKey.Error ex) { throw new SecurityException("deriveEncryptKey: Error in derivePublicKey: " + ex); } } /** * Decrypt the encryptedData using the keyBits according the encrypt params. * @param keyBits The key value (PKCS8-encoded private key). * @param encryptedData The data to decrypt. * @param params This decrypts according to params.getAlgorithmType(). * @return The decrypted data. */ public static Blob decrypt(Blob keyBits, Blob encryptedData, EncryptParams params) throws SecurityException { TpmPrivateKey privateKey = new TpmPrivateKey(); try { privateKey.loadPkcs8(keyBits.buf()); } catch (TpmPrivateKey.Error ex) { throw new SecurityException("decrypt: Error in loadPkcs8: " + ex); } try { return privateKey.decrypt(encryptedData.buf(), params.getAlgorithmType()); } catch (TpmPrivateKey.Error ex) { throw new SecurityException("decrypt: Error in decrypt: " + ex); } } /** * Encrypt the plainData using the keyBits according the encrypt params. * @param keyBits The key value (DER-encoded public key). * @param plainData The data to encrypt. * @param params This encrypts according to params.getAlgorithmType(). * @return The encrypted data. */ public static Blob encrypt(Blob keyBits, Blob plainData, EncryptParams params) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { try { return new PublicKey(keyBits).encrypt (plainData, params.getAlgorithmType()); } catch (UnrecognizedKeyFormatException ex) { throw new InvalidKeyException(ex.getMessage()); } } }
3e17419623672335a832152745e9af6c315c818d
2,222
java
Java
begincode-web/src/main/java/net/begincode/controller/SummernoteImgController.java
litanwei/begincode_wenda
7ac7800d8e250482ee5751f6b3e0f1dd54a24b28
[ "Apache-2.0" ]
1
2017-06-14T13:48:33.000Z
2017-06-14T13:48:33.000Z
begincode-web/src/main/java/net/begincode/controller/SummernoteImgController.java
litanwei/begincode_wenda
7ac7800d8e250482ee5751f6b3e0f1dd54a24b28
[ "Apache-2.0" ]
null
null
null
begincode-web/src/main/java/net/begincode/controller/SummernoteImgController.java
litanwei/begincode_wenda
7ac7800d8e250482ee5751f6b3e0f1dd54a24b28
[ "Apache-2.0" ]
null
null
null
35.83871
164
0.687219
9,901
package net.begincode.controller; import com.qiniu.util.StringMap; import net.begincode.common.BizException; import net.begincode.core.support.AuthPassport; import net.begincode.enums.CommonResponseEnum; import net.begincode.utils.QiniuUtil; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; 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.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.util.UUID; /** * Created by Stay on 2016/11/22 15:40. */ @Controller @RequestMapping(value = "/summernote") public class SummernoteImgController { private Logger logger = LoggerFactory.getLogger(SummernoteImgController.class); /** * summernote 文件上传 controller * * @param file * @param request * @return */ @AuthPassport @RequestMapping(value = "/imgUpload", method = RequestMethod.POST) @ResponseBody public Object uploadImgage(@RequestParam("file") MultipartFile file, HttpServletRequest request) { File destFile = null; if (!file.isEmpty()) { try { String path = request.getSession().getServletContext().getRealPath("/upload"); String fileName = UUID.randomUUID().toString().replace("-", "") + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); destFile = new File(path + "/" + fileName); FileUtils.copyInputStreamToFile(file.getInputStream(), destFile); //复制临时文件到指定目录 StringMap stringMap = QiniuUtil.upload(fileName, path + "/" + fileName); return stringMap.map(); } catch (Exception e) { logger.error(e.getMessage()); throw new BizException(CommonResponseEnum.EXCEPTION); } finally { destFile.delete(); } } return null; } }
3e1742560fc7ad67e3017f34e402b38ab9a54d56
3,062
java
Java
saferoom/src/androidTest/java/com/commonsware/cwac/saferoom/test/room/simple/TypeTransmogrifier.java
antslava/cwac-saferoom
0f8d5d60d969f8508eea8ddab120de1a8d482c70
[ "Apache-2.0" ]
621
2017-07-10T13:51:46.000Z
2022-03-08T15:29:36.000Z
saferoom/src/androidTest/java/com/commonsware/cwac/saferoom/test/room/simple/TypeTransmogrifier.java
antslava/cwac-saferoom
0f8d5d60d969f8508eea8ddab120de1a8d482c70
[ "Apache-2.0" ]
74
2017-09-28T15:15:23.000Z
2021-04-24T15:25:57.000Z
saferoom/src/androidTest/java/com/commonsware/cwac/saferoom/test/room/simple/TypeTransmogrifier.java
antslava/cwac-saferoom
0f8d5d60d969f8508eea8ddab120de1a8d482c70
[ "Apache-2.0" ]
79
2017-07-10T13:51:48.000Z
2022-02-15T07:40:05.000Z
23.921875
78
0.681907
9,902
/*** Copyright (c) 2017 CommonsWare, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 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. Covered in detail in the book _Android's Architecture Components_ https://commonsware.com/AndroidArch */ package com.commonsware.cwac.saferoom.test.room.simple; import android.location.Location; import android.util.JsonReader; import android.util.JsonWriter; import android.util.Log; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.Date; import java.util.HashSet; import java.util.Locale; import java.util.Set; import androidx.room.TypeConverter; public class TypeTransmogrifier { private static final String TAG="TypeTransmogrifier"; @TypeConverter public static Long fromDate(Date date) { if (date==null) { return(null); } return(date.getTime()); } @TypeConverter public static Date toDate(Long millisSinceEpoch) { if (millisSinceEpoch==null) { return(null); } return(new Date(millisSinceEpoch)); } @TypeConverter public static String fromLocation(Location location) { if (location==null) { return(null); } return(String.format(Locale.US, "%f,%f", location.getLatitude(), location.getLongitude())); } @TypeConverter public static Location toLocation(String latlon) { if (latlon==null) { return(null); } String[] pieces=latlon.split(","); Location result=new Location(""); result.setLatitude(Double.parseDouble(pieces[0])); result.setLongitude(Double.parseDouble(pieces[1])); return(result); } @TypeConverter public static String fromStringSet(Set<String> strings) { if (strings==null) { return(null); } StringWriter result=new StringWriter(); JsonWriter json=new JsonWriter(result); try { json.beginArray(); for (String s : strings) { json.value(s); } json.endArray(); json.close(); } catch (IOException e) { Log.e(TAG, "Exception creating JSON", e); } return(result.toString()); } @TypeConverter public static Set<String> toStringSet(String strings) { if (strings==null) { return(null); } StringReader reader=new StringReader(strings); JsonReader json=new JsonReader(reader); HashSet<String> result=new HashSet<>(); try { json.beginArray(); while (json.hasNext()) { result.add(json.nextString()); } json.endArray(); } catch (IOException e) { Log.e(TAG, "Exception parsing JSON", e); } return(result); } }
3e1742b77993104d0eac3c7227bc4fc6c3a1b149
493
java
Java
src/digitalparking/DigitalParking.java
shevanejiwolop/DigitalParking
5eee007a78a2056d138a7397c1badef2012f2fd1
[ "MIT" ]
1
2020-05-15T08:18:52.000Z
2020-05-15T08:18:52.000Z
src/digitalparking/DigitalParking.java
shevanejiwolop/DigitalParking
5eee007a78a2056d138a7397c1badef2012f2fd1
[ "MIT" ]
null
null
null
src/digitalparking/DigitalParking.java
shevanejiwolop/DigitalParking
5eee007a78a2056d138a7397c1badef2012f2fd1
[ "MIT" ]
null
null
null
18.259259
79
0.679513
9,903
/* * 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 digitalparking; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.text.*; /** * * @author HP ProBook */ public class DigitalParking { /** * @param args the command line arguments */ public static void main(String[] args) { } }
3e1742e27ec7b47b8d66e7ecdc52dc9afc066e5f
823
java
Java
src/main/java/edu/msu/nscl/olog/control/TimeWatch.java
css-iter/olog-service
02d3b377e21f330484f8816ad856313885312c71
[ "MIT" ]
2
2019-10-08T02:38:00.000Z
2019-10-08T02:38:03.000Z
src/main/java/edu/msu/nscl/olog/control/TimeWatch.java
css-iter/olog-service
02d3b377e21f330484f8816ad856313885312c71
[ "MIT" ]
15
2015-01-23T21:20:08.000Z
2022-02-16T00:58:10.000Z
src/main/java/edu/msu/nscl/olog/control/TimeWatch.java
css-iter/olog-service
02d3b377e21f330484f8816ad856313885312c71
[ "MIT" ]
4
2017-02-15T17:42:21.000Z
2020-02-12T07:37:50.000Z
21.102564
80
0.599028
9,904
/* * 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.msu.nscl.olog.control; import java.util.concurrent.TimeUnit; /** * * @author berryman */ public class TimeWatch { long starts; public static TimeWatch start() { return new TimeWatch(); } private TimeWatch() { reset(); } public TimeWatch reset() { starts = System.currentTimeMillis(); return this; } public long time() { long ends = System.currentTimeMillis(); return ends - starts; } public long time(TimeUnit unit) { return unit.convert(time(), TimeUnit.MILLISECONDS); } }
3e174327f1a41060c6e139743f6bec7254ac321d
3,876
java
Java
src/main/java/com/simonorj/mc/getmehome/ConfigTool.java
chuushi/ChuuWarp
0ea64f6171c02b78df19b1e98c9bbcfc711beb8a
[ "MIT" ]
5
2019-03-30T08:51:12.000Z
2019-09-07T05:36:46.000Z
src/main/java/com/simonorj/mc/getmehome/ConfigTool.java
chuushi/GetMeHome
0ea64f6171c02b78df19b1e98c9bbcfc711beb8a
[ "MIT" ]
16
2016-11-22T05:37:57.000Z
2019-08-20T01:25:42.000Z
src/main/java/com/simonorj/mc/getmehome/ConfigTool.java
chuushi/GetMeHome
0ea64f6171c02b78df19b1e98c9bbcfc711beb8a
[ "MIT" ]
4
2018-08-10T00:43:39.000Z
2019-08-22T15:28:43.000Z
44.045455
98
0.615067
9,905
package com.simonorj.mc.getmehome; import org.bukkit.configuration.file.FileConfiguration; public class ConfigTool { private static final String STORAGE_ROOT = "storage"; private static final String SAVENAME_CHILD = "savename"; public static final String STORAGE_SAVENAME_NODE = STORAGE_ROOT + "." + SAVENAME_CHILD; private static final String MESSAGE_ROOT = "message"; private static final String PREFIX_CHILD = "prefix"; private static final String CONTENT_COLOR_CHILD = "content-color"; private static final String FOCUS_COLOR_CHILD = "focus-color"; static final String MESSAGE_PREFIX_NODE = MESSAGE_ROOT + "." + PREFIX_CHILD; static final String MESSAGE_CONTENT_COLOR_NODE = MESSAGE_ROOT + "." + CONTENT_COLOR_CHILD; static final String MESSAGE_FOCUS_COLOR_NODE = MESSAGE_ROOT + "." + FOCUS_COLOR_CHILD; static final String WELCOME_HOME_RADIUS_NODE = "welcome-home-radius"; public static final String CONFIG_VERSION_NODE = "config-version"; public static final int version = 3; private static final String HEADER = "# GetMeHome by Simon Chuu\n" + "\n" + "# For help, follow the plugin project link below:\n" + "# https://github.com/SimonOrJ/GetMeHome/\n"; private static final String STORAGE = "# Storage Settings\n"; private static final String STORAGE_SAVENAME = " # should the plugin save player names with their UUID?\n" + " # This is only for your reference when looking through the file.\n"; private static final String MESSAGE = ""; private static final String MESSAGE_PREFIX = " # Prefix for beginning of message. Use & and 0~9, a~f to set colors.\n"; private static final String MESSAGE_CONTENT_COLOR = " # Colors: Accepted values are 0~9, a~f, or named colors.\n" + " # https://minecraft.gamepedia.com/Formatting_codes\n"; private static final String MESSAGE_FOCUS_COLOR = " # Color for the focus points. e.g. home names or player names\n"; private static final String WELCOME_HOME_RADIUS = "# Maximum distance away from home point for \"Welcome home\" message to not show\n" + "# on /home\n" + "# Set to -1 to disable \"Welcome home\" message\n"; private static final String CONFIG_VERSION = "# Keeps track of configuration version -- do not change!\n"; static String saveToString(FileConfiguration config) { boolean storageSavename = config.getBoolean(STORAGE_SAVENAME_NODE, true); String messagePrefix = config.getString(MESSAGE_PREFIX_NODE, "&6[GetMeHome]"); String messageContentColor = config.getString(MESSAGE_CONTENT_COLOR_NODE, "e"); String messageFocusColor = config.getString(MESSAGE_FOCUS_COLOR_NODE, "f"); int welcomeHomeRadius = config.getInt(WELCOME_HOME_RADIUS_NODE, 4); return HEADER + '\n' + STORAGE + STORAGE_ROOT + ":\n" + STORAGE_SAVENAME + " " + SAVENAME_CHILD + ": " + storageSavename + '\n' + '\n' + MESSAGE + MESSAGE_ROOT + ":\n" + MESSAGE_PREFIX + " " + PREFIX_CHILD + ": \"" + messagePrefix + "\"\n" + MESSAGE_CONTENT_COLOR + " " + CONTENT_COLOR_CHILD + ": " + messageContentColor + '\n' + MESSAGE_FOCUS_COLOR + " " + FOCUS_COLOR_CHILD + ": " + messageFocusColor + '\n' + '\n' + WELCOME_HOME_RADIUS + WELCOME_HOME_RADIUS_NODE + ": " + welcomeHomeRadius + '\n' + '\n' + CONFIG_VERSION + CONFIG_VERSION_NODE + ": " + version + '\n'; } }
3e17432b28b7a14e9921d6f95a848652f6390b29
3,443
java
Java
dynamic-config/cli/config-tool/src/main/java/org/terracotta/dynamic_config/cli/config_tool/parsing/deprecated/DeprecatedDetachCommand.java
guptakshit/terracotta-platform
9c2fadb30500fa69ace162a1567cfa6f294db10f
[ "Apache-2.0" ]
28
2015-10-23T05:54:07.000Z
2021-02-26T12:32:47.000Z
dynamic-config/cli/config-tool/src/main/java/org/terracotta/dynamic_config/cli/config_tool/parsing/deprecated/DeprecatedDetachCommand.java
guptakshit/terracotta-platform
9c2fadb30500fa69ace162a1567cfa6f294db10f
[ "Apache-2.0" ]
535
2015-10-14T20:04:07.000Z
2022-03-29T13:12:21.000Z
dynamic-config/cli/config-tool/src/main/java/org/terracotta/dynamic_config/cli/config_tool/parsing/deprecated/DeprecatedDetachCommand.java
guptakshit/terracotta-platform
9c2fadb30500fa69ace162a1567cfa6f294db10f
[ "Apache-2.0" ]
49
2015-10-14T17:16:32.000Z
2021-11-18T07:02:44.000Z
43.0375
146
0.770839
9,906
/* * Copyright Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terracotta.dynamic_config.cli.config_tool.parsing.deprecated; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import org.terracotta.common.struct.Measure; import org.terracotta.common.struct.TimeUnit; import org.terracotta.dynamic_config.api.model.Identifier; import org.terracotta.dynamic_config.cli.api.command.DetachAction; import org.terracotta.dynamic_config.cli.api.command.Injector.Inject; import org.terracotta.dynamic_config.cli.api.converter.OperationType; import org.terracotta.dynamic_config.cli.command.Command; import org.terracotta.dynamic_config.cli.command.Usage; import org.terracotta.dynamic_config.cli.converter.IdentifierConverter; import org.terracotta.dynamic_config.cli.converter.InetSocketAddressConverter; import org.terracotta.dynamic_config.cli.converter.TimeUnitConverter; import org.terracotta.dynamic_config.cli.converter.TypeConverter; import java.net.InetSocketAddress; @Parameters(commandDescription = "Detach a node from a stripe, or a stripe from a cluster") @Usage("[-t node|stripe] -d <hostname[:port]> -s [<hostname[:port]>|uid|name] [-f] [-W <stop-wait-time>] [-D <stop-delay>]") public class DeprecatedDetachCommand extends Command { @Parameter(names = {"-t"}, description = "Determine if the sources are nodes or stripes. Default: node", converter = TypeConverter.class) protected OperationType operationType = OperationType.NODE; @Parameter(required = true, names = {"-d"}, description = "Destination stripe or cluster", converter = InetSocketAddressConverter.class) protected InetSocketAddress destinationAddress; @Parameter(names = {"-f"}, description = "Force the operation") protected boolean force; @Parameter(names = {"-W"}, description = "Maximum time to wait for the nodes to stop. Default: 120s", converter = TimeUnitConverter.class) protected Measure<TimeUnit> stopWaitTime = Measure.of(120, TimeUnit.SECONDS); @Parameter(names = {"-D"}, description = "Delay before the server stops itself. Default: 2s", converter = TimeUnitConverter.class) protected Measure<TimeUnit> stopDelay = Measure.of(2, TimeUnit.SECONDS); @Parameter(required = true, names = {"-s"}, description = "Source node or stripe (address, name or UID)", converter = IdentifierConverter.class) protected Identifier sourceIdentifier; @Inject public final DetachAction action; public DeprecatedDetachCommand() { this(new DetachAction()); } public DeprecatedDetachCommand(DetachAction action) { this.action = action; } @Override public void run() { action.setOperationType(operationType); action.setDestinationAddress(destinationAddress); action.setForce(force); action.setSourceIdentifier(sourceIdentifier); action.setStopWaitTime(stopWaitTime); action.setStopDelay(stopDelay); action.run(); } }
3e17459818921d94edb420717e7289e383140895
1,693
java
Java
src/main/java/run/xuyang/course/service/client/StudentService.java
xuyang9978/course-select-system
d3a6c8e3529e8d9474b7b57982549c351b1f67d7
[ "Apache-2.0" ]
null
null
null
src/main/java/run/xuyang/course/service/client/StudentService.java
xuyang9978/course-select-system
d3a6c8e3529e8d9474b7b57982549c351b1f67d7
[ "Apache-2.0" ]
null
null
null
src/main/java/run/xuyang/course/service/client/StudentService.java
xuyang9978/course-select-system
d3a6c8e3529e8d9474b7b57982549c351b1f67d7
[ "Apache-2.0" ]
null
null
null
22.573333
111
0.634968
9,907
package run.xuyang.course.service.client; import org.springframework.data.domain.Page; import run.xuyang.course.core.ResponseResult; import run.xuyang.course.entity.client.Student; import run.xuyang.course.entity.query.StudentQuery; import run.xuyang.course.web.security.SecurityResponseBody; import java.util.List; /** * @author XuYang * @date 2021/1/31 22:17 */ public interface StudentService { /** * 学生登录 * * @param account 学号/邮箱/手机号 * @param password 密码 * @return 学生信息以及 token 信息 */ SecurityResponseBody<Student> login(String account, String password); /** * 根据学生 id 删除学生信息 * * @param studentIds 学生 id 集合 */ ResponseResult<Object> deleteStudent(List<Long> studentIds); /** * 更新学生信息 * * @param student 学生信息 * @return 更新后的学生信息 */ ResponseResult<Student> updateStudent(Student student); /** * 分页、条件查询学生列表 * * @param page 第几页,从 0 开始 * @param pageSize 每页多少条数据 * @param studentQuery 查询条件 * @return 学生分页数据 */ ResponseResult<Page<Student>> listStudentByPage(Integer page, Integer pageSize, StudentQuery studentQuery); /** * 新增一个学生账号 * * @param student 学生信息 * @return 生成成功的学生对象 */ ResponseResult<Student> addStudent(Student student); /** * 选课 * * @param studentId 学生 id * @param courseIds 选择的课程的 id 集合 */ ResponseResult<Object> courseSelect(Long studentId, List<Long> courseIds); /** * 退课 * * @param studentId 学生 id * @param courseIds 退选的课程的 id 集合 */ ResponseResult<Object> courseUnSelect(Long studentId, List<Long> courseIds); }
3e1745b8a521d873c48dfdd1b28d4c4eb33471ba
2,068
java
Java
src/main/java/com/xuxd/baishun/beans/UserInfoOperationLog.java
xxd763795151/BaiShun
c0eff8301c0745a2527b419e05b2aab638032f8b
[ "MIT" ]
3
2021-11-14T12:09:53.000Z
2022-03-03T02:56:57.000Z
src/main/java/com/xuxd/baishun/beans/UserInfoOperationLog.java
xxd763795151/BaiShun
c0eff8301c0745a2527b419e05b2aab638032f8b
[ "MIT" ]
null
null
null
src/main/java/com/xuxd/baishun/beans/UserInfoOperationLog.java
xxd763795151/BaiShun
c0eff8301c0745a2527b419e05b2aab638032f8b
[ "MIT" ]
null
null
null
20.475248
70
0.545938
9,908
package com.xuxd.baishun.beans; import javax.persistence.*; import java.io.Serializable; /** * @Auther: 许晓东 * @Date: 20-3-29 20:33 * @Description: */ @Entity @Table(name = "t_user_info_updated_log") public class UserInfoOperationLog implements Serializable { private static final long serialVersionUID = -160217880445948477L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String userId; private String name; private String tel; //type ENUM('create', 'recharge', 'deduction', 'update') // 0, 1,2,3 // -> OperationType @Enumerated(EnumType.STRING) private OperationType type; private String updateTime; private String log; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public OperationType getType() { return type; } public void setType(OperationType type) { this.type = type; } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } public String getLog() { return log; } public void setLog(String log) { this.log = log; } @Override public String toString() { return "UserInfoOperationLog{" + "id=" + id + ", userId='" + userId + '\'' + ", name='" + name + '\'' + ", tel='" + tel + '\'' + ", type=" + type + ", updateTime='" + updateTime + '\'' + ", log='" + log + '\'' + '}'; } }
3e1746399bf374d58342278a14288cc59416d0be
1,355
java
Java
FTCDashboard/src/main/java/com/acmerobotics/dashboard/util/ClasspathScanner.java
dansman805/ftc_app
fb9b0d5a4d75d744d33378c3982c4865d939f0e1
[ "MIT" ]
1
2018-08-01T20:18:00.000Z
2018-08-01T20:18:00.000Z
FTCDashboard/src/main/java/com/acmerobotics/dashboard/util/ClasspathScanner.java
dansman805/ftc_app
fb9b0d5a4d75d744d33378c3982c4865d939f0e1
[ "MIT" ]
null
null
null
FTCDashboard/src/main/java/com/acmerobotics/dashboard/util/ClasspathScanner.java
dansman805/ftc_app
fb9b0d5a4d75d744d33378c3982c4865d939f0e1
[ "MIT" ]
null
null
null
28.229167
87
0.62952
9,909
package com.acmerobotics.dashboard.util; import android.content.Context; import android.util.Log; import org.firstinspires.ftc.robotcore.internal.system.AppUtil; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import dalvik.system.DexFile; public class ClasspathScanner { public static final String TAG = "ClasspathScanner"; private DexFile dexFile; private ClassFilter filter; public ClasspathScanner(ClassFilter filter) { Context context = AppUtil.getInstance().getApplication(); try { this.dexFile = new DexFile(context.getPackageCodePath()); } catch (IOException e) { Log.w(TAG, e); } this.filter = filter; } public void scanClasspath() { List<String> classNames = new ArrayList<>(Collections.list(dexFile.entries())); ClassLoader classLoader = ClasspathScanner.class.getClassLoader(); for (String className : classNames) { if (filter.shouldProcessClass(className)) { try { Class klass = Class.forName(className, false, classLoader); filter.processClass(klass); } catch (ClassNotFoundException e) { Log.w(TAG, e); } } } } }
3e17465feff7a1b2e355c894462ddc75645e9165
1,162
java
Java
src/main/java/uk/co/cwspencer/gdb/gdbmi/GdbMiUtil.java
intellij-dlanguage/intellij-gdb
1e42c76d731e1f09070055dadca7553831fb3c96
[ "MIT" ]
null
null
null
src/main/java/uk/co/cwspencer/gdb/gdbmi/GdbMiUtil.java
intellij-dlanguage/intellij-gdb
1e42c76d731e1f09070055dadca7553831fb3c96
[ "MIT" ]
null
null
null
src/main/java/uk/co/cwspencer/gdb/gdbmi/GdbMiUtil.java
intellij-dlanguage/intellij-gdb
1e42c76d731e1f09070055dadca7553831fb3c96
[ "MIT" ]
null
null
null
20.385965
79
0.54475
9,910
package uk.co.cwspencer.gdb.gdbmi; /** * Utility functions relating to the use of GDB/MI. */ public class GdbMiUtil { // Mapping from hexadecimal digits to ASCII characters private static final char[] m_hexAscii = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' }; /** * Formats a string into the format required by GDB/MI. * @param string The string to format. * @return The formatted string. */ public static String formatGdbString(String string) { StringBuilder sb = new StringBuilder(); sb.append("\""); for (int i = 0; i < string.length(); ++i) { char ch = string.charAt(i); // Restrict the use of escape characters to those that are likely to be safe if (ch == '\n') { sb.append("\\n"); } else if (ch == '\r') { sb.append("\\r"); } else if (ch == '"') { sb.append("\\\""); } else if (ch == '\\') { sb.append("\\\\"); } else if (ch <= 0x1f || ch >= 0x7f) { sb.append("\\x"); sb.append(m_hexAscii[ch >> 4]); sb.append(m_hexAscii[ch & 0x0f]); } else { sb.append(ch); } } sb.append("\""); return sb.toString(); } }
3e1746632849961aba52d4cc9c51e49df325a2aa
2,118
java
Java
modules/core/src/main/java/com/jeesite/modules/sys/entity/Area.java
Code4JNothing/jeesite4
8a7846d01e16151d94fe921ef198bbb662c521be
[ "Apache-2.0" ]
1,746
2018-02-25T04:41:12.000Z
2022-03-29T07:51:24.000Z
modules/core/src/main/java/com/jeesite/modules/sys/entity/Area.java
Code4JNothing/jeesite4
8a7846d01e16151d94fe921ef198bbb662c521be
[ "Apache-2.0" ]
17
2018-02-28T03:59:23.000Z
2022-03-31T16:51:17.000Z
modules/core/src/main/java/com/jeesite/modules/sys/entity/Area.java
Code4JNothing/jeesite4
8a7846d01e16151d94fe921ef198bbb662c521be
[ "Apache-2.0" ]
900
2018-02-28T06:15:31.000Z
2022-03-30T03:14:38.000Z
24.627907
107
0.692635
9,911
/** * Copyright (c) 2013-Now http://jeesite.com All rights reserved. */ package com.jeesite.modules.sys.entity; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.NotBlank; import com.jeesite.common.entity.DataEntity; import com.jeesite.common.entity.TreeEntity; import com.jeesite.common.mybatis.annotation.Column; import com.jeesite.common.mybatis.annotation.Table; import com.jeesite.common.mybatis.mapper.query.QueryType; /** * 行政区划Entity * @author ThinkGem * @version 2017-03-22 */ @Table(name="${_prefix}sys_area", alias="a", label="区域信息", columns={ @Column(includeEntity=DataEntity.class), @Column(includeEntity=TreeEntity.class), @Column(name="area_code", attrName="areaCode", label="区域代码", isPK=true), @Column(name="area_name", attrName="areaName", label="区域名称", queryType=QueryType.LIKE, isTreeName=true), @Column(name="area_type", attrName="areaType", label="区域类型"), }, orderBy="a.tree_sorts, a.area_code" ) public class Area extends TreeEntity<Area> { private static final long serialVersionUID = 1L; private String areaCode; // 区域代码 private String areaName; // 区域名称 private String areaType; // 区域类型(1:国家;2:省份、直辖市;3:地市;4:区县) public Area(){ this(null); } public Area(String id){ super(id); } @Override public Area getParent() { return parent; } @Override public void setParent(Area parent) { this.parent = parent; } public String getAreaCode() { return areaCode; } public void setAreaCode(String areaCode) { this.areaCode = areaCode; } @NotBlank(message="名称不能为空") @Length(min=0, max=100, message="名称长度不能超过 100 个字符") public String getAreaName() { return areaName; } public void setAreaName(String areaName) { this.areaName = areaName; } @NotBlank(message="类型不能为空") @Length(min=0, max=1, message="类型长度不能超过 1 个字符") public String getAreaType() { return areaType; } public void setAreaType(String areaType) { this.areaType = areaType; } @Override public String toString() { return areaCode; } }
3e17467932345f7069b60d36322549626470adf9
861
java
Java
src/main/java/uk/gov/hmcts/reform/divorce/transformservice/strategy/reasonfordivorce/UnreasonableBehaviourStrategy.java
hmcts/div-transformation-service
886fbde4726637df8577f4b97fd3b2fb298dd7fe
[ "MIT" ]
2
2018-03-05T16:49:25.000Z
2018-03-06T23:35:36.000Z
src/main/java/uk/gov/hmcts/reform/divorce/transformservice/strategy/reasonfordivorce/UnreasonableBehaviourStrategy.java
hmcts/div-transformation-service
886fbde4726637df8577f4b97fd3b2fb298dd7fe
[ "MIT" ]
50
2018-04-22T09:59:47.000Z
2018-12-07T16:41:42.000Z
src/main/java/uk/gov/hmcts/reform/divorce/transformservice/strategy/reasonfordivorce/UnreasonableBehaviourStrategy.java
hmcts/div-transformation-service
886fbde4726637df8577f4b97fd3b2fb298dd7fe
[ "MIT" ]
2
2018-11-02T12:17:19.000Z
2021-04-10T23:03:07.000Z
34.44
103
0.806039
9,912
package uk.gov.hmcts.reform.divorce.transformservice.strategy.reasonfordivorce; import org.springframework.stereotype.Component; import uk.gov.hmcts.reform.divorce.transformservice.domain.model.divorceapplicationdata.DivorceSession; import static org.apache.commons.lang3.StringUtils.join; @Component public class UnreasonableBehaviourStrategy implements ReasonForDivorceStrategy { private static final String UNREASONABLE_BEHAVIOUR = "unreasonable-behaviour"; private static final String LINE_SEPARATOR = "\n"; @Override public String deriveStatementOfCase(DivorceSession divorceSession) { return join(divorceSession.getReasonForDivorceBehaviourDetails(), LINE_SEPARATOR); } @Override public boolean accepts(String reasonForDivorce) { return UNREASONABLE_BEHAVIOUR.equalsIgnoreCase(reasonForDivorce); } }
3e174680551d941cc3db16f463526d2a233c6d0a
2,421
java
Java
src/main/java/seedu/address/logic/commands/PasswordCommand.java
lekoook/main
632411670b8b9a7d67b300c3c344966c71cac579
[ "MIT" ]
1
2018-10-04T16:56:49.000Z
2018-10-04T16:56:49.000Z
src/main/java/seedu/address/logic/commands/PasswordCommand.java
lekoook/main
632411670b8b9a7d67b300c3c344966c71cac579
[ "MIT" ]
110
2018-09-19T04:00:52.000Z
2018-11-12T14:07:52.000Z
src/main/java/seedu/address/logic/commands/PasswordCommand.java
lekoook/main
632411670b8b9a7d67b300c3c344966c71cac579
[ "MIT" ]
6
2018-08-31T04:14:02.000Z
2018-11-07T07:29:08.000Z
35.602941
110
0.711689
9,913
//@@author lws803 package seedu.address.logic.commands; import static seedu.address.model.Model.PREDICATE_SHOW_ALL_PERSONS; import java.util.Arrays; import java.util.function.Predicate; import seedu.address.commons.exceptions.FileEncryptorException; import seedu.address.commons.util.FileEncryptor; import seedu.address.logic.CommandHistory; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.person.NameContainsKeywordsPredicate; import seedu.address.model.person.Person; /** * Encrypts the XML data using a password and returns a message * Message will be displayed on CommandResult */ public class PasswordCommand extends Command { public static final String COMMAND_WORD = "password"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Hashes file using password.\n" + "Parameter: PASSWORD\n" + "Example: " + COMMAND_WORD + " myPassword"; public static final String MESSAGE_ENCRYPT_SUCCESS = "File encrypted!"; public static final String MESSAGE_DECRYPT_SUCCESS = "File decrypted!"; private String password; private FileEncryptor fe; /** * Executes the FileEncryptor and obtains a message * @param credentials will be obtained from parser */ public PasswordCommand (String credentials, String path) { fe = new FileEncryptor(path); this.password = credentials; } @Override public CommandResult execute (Model model, CommandHistory history) throws CommandException { String message; try { message = fe.process(this.password); } catch (FileEncryptorException fex) { throw new CommandException(fex.getLocalizedMessage()); } if (message.compareTo(FileEncryptor.MESSAGE_DECRYPTED) == 0) { model.reinitAddressbook(); model.reinitialisePrediction(); model.updateFilteredPersonList(PREDICATE_SHOW_ALL_PERSONS); return new CommandResult(MESSAGE_DECRYPT_SUCCESS); } else { String[] approvedList = {}; Predicate<Person> emptyPredicate = new NameContainsKeywordsPredicate(Arrays.asList(approvedList)); model.updateFilteredPersonList(PREDICATE_SHOW_ALL_PERSONS.and(emptyPredicate)); return new CommandResult(MESSAGE_ENCRYPT_SUCCESS); } } }
3e17495272870af6cb00d6beecbe4b42ab660aee
9,322
java
Java
PiaSample/app/src/main/java/eu/nets/pia/sample/ui/fragment/PaymentMethodsFragment.java
antygravity/Netaxept-Android-SDK
659426b2ca44f4803d0a158a3d66b0179d6ed29c
[ "MIT" ]
null
null
null
PiaSample/app/src/main/java/eu/nets/pia/sample/ui/fragment/PaymentMethodsFragment.java
antygravity/Netaxept-Android-SDK
659426b2ca44f4803d0a158a3d66b0179d6ed29c
[ "MIT" ]
null
null
null
PiaSample/app/src/main/java/eu/nets/pia/sample/ui/fragment/PaymentMethodsFragment.java
antygravity/Netaxept-Android-SDK
659426b2ca44f4803d0a158a3d66b0179d6ed29c
[ "MIT" ]
null
null
null
40.181034
136
0.691483
9,914
package eu.nets.pia.sample.ui.fragment; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; import eu.nets.pia.sample.R; import eu.nets.pia.sample.network.model.Method; import eu.nets.pia.sample.network.model.PaymentMethodsResponse; import eu.nets.pia.sample.network.model.Token; import eu.nets.pia.sample.ui.adapter.PaymentMethodsAdapter; import eu.nets.pia.sample.ui.data.DisplayedToken; import eu.nets.pia.sample.ui.data.PaymentMethod; import eu.nets.pia.sample.ui.data.PaymentMethodType; import eu.nets.pia.sample.ui.widget.CustomToolbar; /** * MIT License * <p> * Copyright (c) 2019 Nets Denmark A/S * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ public class PaymentMethodsFragment extends Fragment { public static final String ID_VISA = "Visa"; public static final String ID_MASTERCARD = "MasterCard"; public static final String ID_AMERICAN_EXPRESS = "AmericanExpress"; public static final String ID_DANKORT = "Dankort"; public static final String ID_DINERS = "DinersClubInternational"; public static final String ID_APPLE_PAY = "ApplePay"; public static final String ID_PAY_PAL = "PayPal"; public static final String ID_MOBILE_PAY = "MobilePay"; public static final String ID_KLARNA = "Klarna"; public static final String ID_SWISH = "Swish"; public static final String ID_VIPPS = "Vipps"; public static final String ID_EASY_PAYMENT = "EasyPayment"; public static final String ID_JCB = "JCB"; @BindView(R.id.toolbar) CustomToolbar mToolbar; @BindView(R.id.recycler_view) RecyclerView mRecyclerView; private static String KEY_PAYMENT_METHODS = "KEY_PAYMENT_METHODS"; private FragmentCallback mCallback; private PaymentMethodsResponse mPaymentMethods; private PaymentMethodsAdapter mAdapter; public PaymentMethodsFragment() { // Required empty public constructor } public static PaymentMethodsFragment newInstance(PaymentMethodsResponse paymentMethodsResponse) { PaymentMethodsFragment fragment = new PaymentMethodsFragment(); Bundle args = new Bundle(); args.putParcelable(KEY_PAYMENT_METHODS, paymentMethodsResponse); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { if (getArguments().containsKey(KEY_PAYMENT_METHODS)) { mPaymentMethods = getArguments().getParcelable(KEY_PAYMENT_METHODS); } } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_payment_methods, container, false); ButterKnife.bind(this, view); return view; } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof FragmentCallback) { mCallback = (FragmentCallback) context; } else { throw new RuntimeException(context.toString() + " must implement FragmentCallback"); } } @Override public void onResume() { super.onResume(); mCallback.showActivityToolbar(true); } @Override public void onDetach() { super.onDetach(); mCallback = null; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mCallback.showActivityToolbar(false); mToolbar.setTitle("Payment Methods"); setupRecycler(); } private void setupRecycler() { mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); mAdapter = new PaymentMethodsAdapter(getActivity(), getPaymentMethodsList(), getSupportedCardSchemes(), mCallback); mRecyclerView.setAdapter(mAdapter); } private ArrayList<Method> getSupportedCardSchemes() { ArrayList<Method> supportedMethods = new ArrayList<>(); for (Method method : mPaymentMethods.getMethods()) { if (!method.getId().equals(ID_APPLE_PAY) && !method.getId().equals(ID_EASY_PAYMENT) && !method.getId().equals(ID_PAY_PAL)) { supportedMethods.add(method); } } return supportedMethods; } private ArrayList<PaymentMethod> getPaymentMethodsList() { ArrayList<Token> tokenList; ArrayList<Method> paymentMethodList; /** * Note: * This flag is returned by the Merchant Back-End. The current logic implemented there, is * to have two cases (true and false) based on the customerId being odd or even. This was made only * for Demo purposes. * * For your implementation, check with your acquirer if payment for the specific user can be made without CVV/CVC, * and send this flag accordingly. */ Boolean cardVerificationRequired; if (mPaymentMethods != null) { tokenList = mPaymentMethods.getTokens(); paymentMethodList = mPaymentMethods.getMethods(); cardVerificationRequired = mPaymentMethods.getCardVerificationRequired(); } else { throw new IllegalArgumentException("PaymentMethodsFragment must receive payment method list"); } ArrayList<PaymentMethod> methods = new ArrayList<>(); if (tokenList != null && tokenList.size() > 0) { //The EasyPayment method is the last in the list of payment methods Method easyPayMethod = paymentMethodList.get(paymentMethodList.size() - 1); for (Token token : tokenList) { DisplayedToken savedCard = new DisplayedToken(); savedCard.setType(PaymentMethodType.TOKEN); savedCard.setId(easyPayMethod.getId()); savedCard.setDisplayName(easyPayMethod.getDisplayName()); savedCard.setTokenId(token.getTokenId()); savedCard.setIssuer(token.getIssuer()); savedCard.setExpiryDate(token.getExpiryDate()); savedCard.setCardVerificationRequired(cardVerificationRequired); methods.add(savedCard); } //add header for Other payment methods only if there are saved cards PaymentMethod header = new PaymentMethod(); header.setType(null); // set it to null so that adapter knows that this is a header methods.add(header); } PaymentMethod creditCards = new PaymentMethod(); creditCards.setType(PaymentMethodType.CREDIT_CARDS); creditCards.setDisplayName(getString(R.string.payment_method_credit_cards)); creditCards.setId(getString(R.string.payment_method_credit_cards)); creditCards.setCvcRequired(cardVerificationRequired); methods.add(creditCards); PaymentMethod payPal = new PaymentMethod(); payPal.setType(PaymentMethodType.PAY_PAL); payPal.setId(ID_PAY_PAL); methods.add(payPal); PaymentMethod mobilePay = new PaymentMethod(); mobilePay.setType(PaymentMethodType.MOBILE_PAY); mobilePay.setId(ID_MOBILE_PAY); methods.add(mobilePay); PaymentMethod klarna = new PaymentMethod(); klarna.setType(PaymentMethodType.KLARNA); klarna.setId(ID_KLARNA); methods.add(klarna); PaymentMethod swish = new PaymentMethod(); swish.setType(PaymentMethodType.SWISH); swish.setId(ID_SWISH); methods.add(swish); PaymentMethod vipps = new PaymentMethod(); vipps.setType(PaymentMethodType.VIPPS); vipps.setId(ID_VIPPS); methods.add(vipps); return methods; } }
3e1749a3ceb267946e5f5eb0b821447a66d8ec5a
5,403
java
Java
app/src/main/java/me/devsaki/hentoid/database/DatabaseAccessor.java
herdidi47/GalleryCherry
f26ee7dae37d1d3a33f9ef880627263c3805930c
[ "Apache-2.0" ]
null
null
null
app/src/main/java/me/devsaki/hentoid/database/DatabaseAccessor.java
herdidi47/GalleryCherry
f26ee7dae37d1d3a33f9ef880627263c3805930c
[ "Apache-2.0" ]
null
null
null
app/src/main/java/me/devsaki/hentoid/database/DatabaseAccessor.java
herdidi47/GalleryCherry
f26ee7dae37d1d3a33f9ef880627263c3805930c
[ "Apache-2.0" ]
null
null
null
36.02
174
0.666667
9,915
package me.devsaki.hentoid.database; import android.content.Context; import android.os.AsyncTask; import java.util.ArrayList; import java.util.List; import me.devsaki.hentoid.collection.CollectionAccessor; import me.devsaki.hentoid.database.domains.Attribute; import me.devsaki.hentoid.database.domains.Content; import me.devsaki.hentoid.enums.AttributeType; import me.devsaki.hentoid.enums.Language; import me.devsaki.hentoid.enums.Site; import me.devsaki.hentoid.listener.AttributeListener; import me.devsaki.hentoid.listener.ContentListener; public class DatabaseAccessor implements CollectionAccessor { private static final String contentSynch = ""; private static final String attrSynch = ""; private final HentoidDB db; static class ContentQueryResult { public List<Content> pagedContents; public int totalContent; public int totalSelectedContent; } public DatabaseAccessor(Context ctx) { db = HentoidDB.getInstance(ctx); } @Override public void getRecentBooks(Site site, Language language, int page, int booksPerPage, int orderStyle, boolean favouritesOnly, ContentListener listener) { synchronized (contentSynch) { new ContentFetchTask(db, "", new ArrayList<>(), page, booksPerPage, orderStyle, favouritesOnly, listener).execute(); } } @Override public void getPages(Content content, ContentListener listener) { // Not implemented } @Override public void searchBooks(String query, List<Attribute> metadata, int page, int booksPerPage, int orderStyle, boolean favouritesOnly, ContentListener listener) { synchronized (contentSynch) { new ContentFetchTask(db, query, metadata, page, booksPerPage, orderStyle, favouritesOnly, listener).execute(); } } @Override public void getAttributeMasterData(AttributeType attr, String filter, AttributeListener listener) { synchronized (attrSynch) { new AttributesFetchTask(db, listener, attr, filter).execute(); } } @Override public void dispose() { // Nothing special } // === ASYNC TASKS private static class ContentFetchTask extends AsyncTask<String, String, ContentQueryResult> { private final HentoidDB db; private final ContentListener listener; private final String titleQuery; private final List<Attribute> metadata; private final int currentPage; private final int booksPerPage; private final int orderStyle; private final boolean favouritesOnly; ContentFetchTask(HentoidDB db, String query, List<Attribute> metadata, int page, int booksPerPage, int orderStyle, boolean favouritesOnly, ContentListener listener) { this.db = db; this.titleQuery = query; this.metadata = metadata; this.currentPage = page; this.booksPerPage = booksPerPage; this.orderStyle = orderStyle; this.favouritesOnly = favouritesOnly; this.listener = listener; } @Override protected ContentQueryResult doInBackground(String... params) { ContentQueryResult result = new ContentQueryResult(); result.pagedContents = db.selectContentByQuery(titleQuery, currentPage, booksPerPage, metadata, favouritesOnly, orderStyle); // Fetch total query count (since query are paged, query results count is always <= booksPerPage) result.totalSelectedContent = db.countContentByQuery(titleQuery, metadata, favouritesOnly); // Fetch total book count (useful for displaying and comparing the total number of books) result.totalContent = db.countAllContent(); return result; } @Override protected void onPostExecute(ContentQueryResult response) { if (null == response) { listener.onContentFailed(null, "Content failed to load - Empty response"); return; } listener.onContentReady(response.pagedContents, response.totalSelectedContent, response.totalContent); } } private static class AttributesFetchTask extends AsyncTask<String, String, List<Attribute>> { private final HentoidDB db; private final AttributeListener listener; private final AttributeType attrType; private final String filter; AttributesFetchTask(HentoidDB db, AttributeListener listener, AttributeType attrType, String filter) { this.db = db; this.listener = listener; this.attrType = attrType; this.filter = filter; } @Override protected List<Attribute> doInBackground(String... params) { if (AttributeType.SOURCE == attrType) // Specific case { return db.selectAvailableSources(); } else { return db.selectAllAttributesByType(attrType, filter); } } @Override protected void onPostExecute(List<Attribute> response) { if (null == response) { listener.onAttributesFailed("Attributes failed to load - Empty response"); return; } listener.onAttributesReady(response, response.size()); } } }
3e1749cdcea466ff11a6a555165b5921f56a5ffb
9,291
java
Java
tests/com/nightlycommit/idea/twigextendedplugin/tests/dic/xml/XmlDicCompletionContributorTest.java
ericmorand/idea-twigextendedplugin
2dda5e66b59d831c805509f76d6b185a9c859bf0
[ "MIT" ]
1
2019-06-05T11:59:11.000Z
2019-06-05T11:59:11.000Z
tests/com/nightlycommit/idea/twigextendedplugin/tests/dic/xml/XmlDicCompletionContributorTest.java
ericmorand/idea-twigextendedplugin
2dda5e66b59d831c805509f76d6b185a9c859bf0
[ "MIT" ]
1
2018-03-12T08:00:09.000Z
2018-03-12T08:03:23.000Z
tests/com/nightlycommit/idea/twigextendedplugin/tests/dic/xml/XmlDicCompletionContributorTest.java
ericmorand/idea-twigextendedplugin
2dda5e66b59d831c805509f76d6b185a9c859bf0
[ "MIT" ]
null
null
null
38.413223
154
0.505379
9,916
package com.nightlycommit.idea.twigextendedplugin.tests.dic.xml; import com.intellij.ide.highlighter.XmlFileType; import com.nightlycommit.idea.twigextendedplugin.config.xml.XmlCompletionContributor; import com.nightlycommit.idea.twigextendedplugin.tests.SymfonyLightCodeInsightFixtureTestCase; import java.io.File; /** * @author Daniel Espendiller <nnheo@example.com> * @see com.nightlycommit.idea.twigextendedplugin.config.xml.XmlCompletionContributor */ public class XmlDicCompletionContributorTest extends SymfonyLightCodeInsightFixtureTestCase { public void setUp() throws Exception { super.setUp(); myFixture.copyFileToProject("appDevDebugProjectContainer.xml"); myFixture.configureFromExistingVirtualFile(myFixture.copyFileToProject("classes1.php")); myFixture.copyFileToProject("services.xml"); myFixture.copyFileToProject("XmlDicCompletionContributorTest.env"); myFixture.configureByText("classes.php", "<?php\n" + "namespace Foo\\Name;\n" + "class FooClass {" + " public function foo() " + "}" ); } public String getTestDataPath() { return new File(this.getClass().getResource("fixtures").getFile()).getAbsolutePath(); } /** * @see XmlCompletionContributor */ public void testServiceCompletion() { assertCompletionContains("service.xml", "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<container>\n" + " <services>\n" + " <argument type=\"service\" id=\"<caret>\"/>\n" + " </services>\n" + "</container>" , "data_collector.router" ); assertCompletionContains("service.xml", "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<container>\n" + " <services>\n" + " <service factory-service=\"<caret>\"/>" + " </services>\n" + "</container>" , "data_collector.router" ); assertCompletionContains("service.xml", "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<container>\n" + " <services>\n" + " <service parent=\"<caret>\"/>" + " </services>\n" + "</container>" , "data_collector.router" ); } /** * @see XmlCompletionContributor */ public void testServiceCompletionForArgumentsWithInvalidTypeAttributeBuWithValidParentServiceTag() { assertCompletionContains("service.xml", "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<container>\n" + " <services>\n" + " <service><argument type=\"foobar\" id=\"<caret>\"/></service>\n" + " </services>\n" + "</container>" , "data_collector.router" ); assertCompletionContains("service.xml", "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<container>\n" + " <services>\n" + " <service><argument id=\"<caret>\"/></service>\n" + " </services>\n" + "</container>" , "data_collector.router" ); } public void testClassCompletion() { assertCompletionContains("service.xml", "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<container>\n" + " <services>\n" + " <service id=\"genemu.twig.extension.form\" class=\"<caret>\"/>\n" + " </services>\n" + "</container>" , "FooClass" ); assertCompletionContains("service.xml", "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<container>\n" + " <services>\n" + " <service factory-class=\"<caret>\"/>" + " </services>\n" + "</container>" , "FooClass" ); } public void testAutowiringType() { assertCompletionContains("service.xml", "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<container>\n" + " <services>\n" + " <service>\n" + " <autowiring-type><caret></autowiring-type>" + " </service>\n" + " </services>\n" + "</container>" , "FooClass" ); } public void testClassCompletionResult() { assertCompletionResultEquals("service.xml", "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<container>\n" + " <services>\n" + " <service factory-class=\"FooClass<caret>\"/>" + " </services>\n" + "</container>", "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<container>\n" + " <services>\n" + " <service factory-class=\"Foo\\Name\\FooClass\"/>" + " </services>\n" + "</container>" ); assertCompletionResultEquals("service.xml", "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<container>\n" + " <services>\n" + " <service factory-class=\"Foo\\Name\\<caret>\"/>" + " </services>\n" + "</container>", "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<container>\n" + " <services>\n" + " <service factory-class=\"Foo\\Name\\FooClass\"/>" + " </services>\n" + "</container>" ); } public void testFactoryClassMethodCompletionResult() { assertCompletionContains("service.xml", "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<container>\n" + " <services>\n" + " <factory service=\"<caret>\"/>" + " </services>\n" + "</container>" , "data_collector.router" ); assertCompletionContains("service.xml", "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<container>\n" + " <services>\n" + " <service id=\"foo.factory\" class=\"Foo\\Name\\FooClass\"/>\n" + " <service id=\"foo.manager\">\n" + " <factory service=\"foo.factory\" method=\"<caret>\"/>" + " <service>\n" + " </services>\n" + "</container>" , "foo" ); } /** * @see com.nightlycommit.idea.twigextendedplugin.config.xml.XmlCompletionContributor.ArgumentParameterCompletionProvider */ public void testArgumentParameterCompletion() { assertCompletionContains("service.xml", "<services><service><argument>%<caret></argument></service></services>", "%foo.class%", "%foo_bar%"); assertCompletionContains("service.xml", "<services><service><argument><caret></argument></service></services>", "%foo.class%", "%foo_bar%"); assertCompletionContains("service.xml", "<services><service><argument>%<caret>%</argument></service></services>", "%foo.class%", "%foo_bar%"); assertCompletionResultEquals("service.xml", "<services><service><argument>%foo_bar<caret></argument></service></services>", "<services><service><argument>%foo_bar%</argument></service></services>" ); } /** * @see com.nightlycommit.idea.twigextendedplugin.config.xml.XmlCompletionContributor.ArgumentParameterCompletionProvider */ public void testEnvironmentArgumentParameterCompletion() { assertCompletionContains( "service.xml", "<services><service><argument>%<caret></argument></service></services>", "%env(FOOBAR_ENV)%" ); } public void testServiceInstanceHighlightCompletion() { assertCompletionLookupContainsPresentableItem(XmlFileType.INSTANCE, "" + "<services>" + " <service class=\"Foo\\Bar\\Car\">" + " <argument type=\"service\" id=\"<caret>\"/>" + " </service>" + "</services>", lookupElement -> "foo_bar_apple".equals(lookupElement.getItemText()) && lookupElement.isItemTextBold() && lookupElement.isItemTextUnderlined() ); } public void testThatUppserCaseServiceAreInsideCompletion() { assertCompletionContains(XmlFileType.INSTANCE, "" + "<services>" + " <service class=\"Foo\\Bar\\Car\">" + " <argument type=\"service\" id=\"<caret>\"/>" + " </service>" + "</services>", "foo_bar_car_UPPER_COMPLETION" ); } public void testServiceCompletionOfFactoryService() { assertCompletionContains(XmlFileType.INSTANCE, "" + "<services>\n" + " <service>\n" + " <factory service=\"<caret>\" />\n" + " </service>\n" + "</services>", "foo_bar_apple" ); } }
3e174aa0732a43a76c327f3556f9c9b7ef7ea5b2
988
java
Java
platform/lang-impl/src/com/intellij/codeInsight/lookup/LookupEx.java
teddywest32/intellij-community
e0268d7a1da1d318b441001448cdd3e8929b2f29
[ "Apache-2.0" ]
2
2018-12-29T09:53:39.000Z
2018-12-29T09:53:42.000Z
platform/lang-impl/src/com/intellij/codeInsight/lookup/LookupEx.java
tnorbye/intellij-community
f01cf262fc196bf4dbb99e20cd937dee3705a7b6
[ "Apache-2.0" ]
null
null
null
platform/lang-impl/src/com/intellij/codeInsight/lookup/LookupEx.java
tnorbye/intellij-community
f01cf262fc196bf4dbb99e20cd937dee3705a7b6
[ "Apache-2.0" ]
2
2017-04-24T15:48:40.000Z
2022-03-09T05:48:05.000Z
25.333333
75
0.73583
9,917
/* * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.lookup; import com.intellij.openapi.ui.popup.JBPopup; import java.awt.*; /** * @author peter */ public interface LookupEx extends Lookup { void setCurrentItem(LookupElement item); /** * @deprecated use PopupPositionManager instead */ void showItemPopup(JBPopup hint); Component getComponent(); boolean showElementActions(); }
3e174b2ecdcdeea7c5df85bf1ea8681f5269a50f
6,385
java
Java
ethereum/core/src/test/java/tech/pegasys/teku/core/ForkChoiceUtilTest.java
zilm13/teku
082652d264cf1861d6786bf178f75d9417e6de2b
[ "Apache-2.0" ]
1
2020-05-10T12:17:04.000Z
2020-05-10T12:17:04.000Z
ethereum/core/src/test/java/tech/pegasys/teku/core/ForkChoiceUtilTest.java
zilm13/teku
082652d264cf1861d6786bf178f75d9417e6de2b
[ "Apache-2.0" ]
1
2021-02-26T04:58:18.000Z
2021-03-03T00:31:19.000Z
ethereum/core/src/test/java/tech/pegasys/teku/core/ForkChoiceUtilTest.java
Nashatyrev/artemis
01ebad0c3d1a74dc939aeb6dbdeea1cb196589aa
[ "Apache-2.0" ]
null
null
null
39.658385
118
0.757244
9,918
/* * Copyright 2020 ConsenSys AG. * * 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 tech.pegasys.teku.core; import static org.assertj.core.api.Assertions.assertThat; import static tech.pegasys.teku.util.config.Constants.SECONDS_PER_SLOT; import com.google.common.primitives.UnsignedLong; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.apache.tuweni.bytes.Bytes32; import org.junit.jupiter.api.Test; import tech.pegasys.teku.bls.BLSKeyGenerator; import tech.pegasys.teku.bls.BLSKeyPair; import tech.pegasys.teku.datastructures.blocks.SignedBeaconBlock; import tech.pegasys.teku.datastructures.blocks.SignedBlockAndState; import tech.pegasys.teku.datastructures.forkchoice.PrunableStore; import tech.pegasys.teku.datastructures.forkchoice.TestStoreFactory; import tech.pegasys.teku.protoarray.ProtoArrayForkChoiceStrategy; import tech.pegasys.teku.protoarray.StubProtoArrayStorageChannel; class ForkChoiceUtilTest { private static final UnsignedLong GENESIS_TIME = UnsignedLong.valueOf("1591924193"); static final UnsignedLong SLOT_50 = GENESIS_TIME.plus(UnsignedLong.valueOf(SECONDS_PER_SLOT).times(UnsignedLong.valueOf(50L))); protected static final List<BLSKeyPair> VALIDATOR_KEYS = BLSKeyGenerator.generateKeyPairs(16); private final ChainBuilder chainBuilder = ChainBuilder.create(VALIDATOR_KEYS); private final SignedBlockAndState genesis = chainBuilder.generateGenesis(); private final PrunableStore store = new TestStoreFactory().createGenesisStore(genesis.getState()); private final ProtoArrayForkChoiceStrategy forkChoiceStrategy = ProtoArrayForkChoiceStrategy.initialize(store, new StubProtoArrayStorageChannel()).join(); @Test void getAncestors_shouldGetSimpleSequenceOfAncestors() throws Exception { chainBuilder.generateBlocksUpToSlot(10).forEach(this::addBlock); final NavigableMap<UnsignedLong, Bytes32> rootsBySlot = ForkChoiceUtil.getAncestors( forkChoiceStrategy, chainBuilder.getLatestBlockAndState().getRoot(), UnsignedLong.ONE, UnsignedLong.ONE, UnsignedLong.valueOf(8)); assertThat(rootsBySlot).containsExactlyEntriesOf(getRootsForBlocks(1, 2, 3, 4, 5, 6, 7, 8)); } @Test void getAncestors_shouldGetSequenceOfRootsWhenSkipping() throws Exception { chainBuilder.generateBlocksUpToSlot(10).forEach(this::addBlock); final NavigableMap<UnsignedLong, Bytes32> rootsBySlot = ForkChoiceUtil.getAncestors( forkChoiceStrategy, chainBuilder.getLatestBlockAndState().getRoot(), UnsignedLong.ONE, UnsignedLong.valueOf(2), UnsignedLong.valueOf(4)); assertThat(rootsBySlot).containsExactlyEntriesOf(getRootsForBlocks(1, 3, 5, 7)); } @Test void getAncestors_shouldGetSequenceOfRootsWhenStartIsPriorToFinalizedCheckpoint() throws Exception { chainBuilder.generateBlocksUpToSlot(10).forEach(this::addBlock); forkChoiceStrategy.setPruneThreshold(0); forkChoiceStrategy.maybePrune(chainBuilder.getBlockAtSlot(4).getRoot()); final NavigableMap<UnsignedLong, Bytes32> rootsBySlot = ForkChoiceUtil.getAncestors( forkChoiceStrategy, chainBuilder.getLatestBlockAndState().getRoot(), UnsignedLong.ONE, UnsignedLong.valueOf(2), UnsignedLong.valueOf(4)); assertThat(rootsBySlot).containsExactlyEntriesOf(getRootsForBlocks(5, 7)); } @Test void getAncestors_shouldGetSequenceOfRootsWhenEndIsAfterChainHead() throws Exception { chainBuilder.generateBlocksUpToSlot(10).forEach(this::addBlock); final NavigableMap<UnsignedLong, Bytes32> rootsBySlot = ForkChoiceUtil.getAncestors( forkChoiceStrategy, chainBuilder.getLatestBlockAndState().getRoot(), UnsignedLong.valueOf(6), UnsignedLong.valueOf(2), UnsignedLong.valueOf(20)); assertThat(rootsBySlot).containsExactlyEntriesOf(getRootsForBlocks(6, 8, 10)); } @Test void getAncestors_shouldNotIncludeEntryForEmptySlots() throws Exception { addBlock(chainBuilder.generateBlockAtSlot(3)); addBlock(chainBuilder.generateBlockAtSlot(5)); final NavigableMap<UnsignedLong, Bytes32> rootsBySlot = ForkChoiceUtil.getAncestors( forkChoiceStrategy, chainBuilder.getLatestBlockAndState().getRoot(), UnsignedLong.ZERO, UnsignedLong.ONE, UnsignedLong.valueOf(10)); assertThat(rootsBySlot).containsExactlyEntriesOf(getRootsForBlocks(0, 3, 5)); } @Test public void getCurrentSlot_shouldGetZeroAtGenesis() { assertThat(ForkChoiceUtil.getCurrentSlot(GENESIS_TIME, GENESIS_TIME)) .isEqualTo(UnsignedLong.ZERO); } @Test public void getCurrentSlot_shouldGetNonZeroPastGenesis() { assertThat(ForkChoiceUtil.getCurrentSlot(SLOT_50, GENESIS_TIME)) .isEqualTo(UnsignedLong.valueOf(50L)); } @Test public void getSlotStartTime_shouldGetGenesisTimeForBlockZero() { assertThat(ForkChoiceUtil.getSlotStartTime(UnsignedLong.ZERO, GENESIS_TIME)) .isEqualTo(GENESIS_TIME); } @Test public void getSlotStartTime_shouldGetCorrectTimePastGenesis() { assertThat(ForkChoiceUtil.getSlotStartTime(UnsignedLong.valueOf(50L), GENESIS_TIME)) .isEqualTo(SLOT_50); } private Map<UnsignedLong, Bytes32> getRootsForBlocks(final int... blockNumbers) { return IntStream.of(blockNumbers) .mapToObj(chainBuilder::getBlockAtSlot) .collect(Collectors.toMap(SignedBeaconBlock::getSlot, SignedBeaconBlock::getRoot)); } private void addBlock(final SignedBlockAndState blockAndState) { forkChoiceStrategy.onBlock(blockAndState.getBlock().getMessage(), blockAndState.getState()); } }
3e174b39520e0a60c3b54fbee818ab3908c77ec5
13,067
java
Java
src/main/java/com/wind/web/common/BaseService.java
kejintao558/springboot-seed
313aceed18181dd4eb9b9f225accfbb4eae92c52
[ "MIT" ]
1
2019-09-04T04:12:02.000Z
2019-09-04T04:12:02.000Z
src/main/java/com/wind/web/common/BaseService.java
kejintao558/springboot-seed
313aceed18181dd4eb9b9f225accfbb4eae92c52
[ "MIT" ]
null
null
null
src/main/java/com/wind/web/common/BaseService.java
kejintao558/springboot-seed
313aceed18181dd4eb9b9f225accfbb4eae92c52
[ "MIT" ]
null
null
null
31.335731
122
0.593174
9,919
package com.wind.web.common; import com.github.pagehelper.PageHelper; import com.wind.common.Constant; import com.wind.common.SpringUtil; import com.wind.mybatis.CustomMapper; import org.apache.ibatis.session.RowBounds; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import tk.mybatis.mapper.entity.Example; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import static com.wind.common.Constant.ALL_PAGE; public abstract class BaseService<T> { @Autowired protected CustomMapper<T> mapper; /** * 获取真实反射类型 * * @return 反射类型 */ Class getActualClass() { Type type = getClass().getGenericSuperclass(); // 判断是否泛型 if (type instanceof ParameterizedType) { // 返回表示此类型实际类型参数的Type对象的数组 Type[] types = ((ParameterizedType) type).getActualTypeArguments(); return (Class) types[0]; //将第一个泛型T对应的类返回 } else { return (Class) type;//若没有给定泛型,则返回Object类 } } public Optional<T> selectByID(Long id) { return Optional.ofNullable(mapper.selectByPrimaryKey(id)); } /** * 根据ID列表获取实例列表 * * @param idList ID列表 * @return 实例列表 */ public List<T> selectAll(List<Long> idList) { String ids = ""; for (int index = 0; index < idList.size(); index++) { ids += Long.toString(idList.get(index)); if (index != idList.size() - 1) { ids += ","; } } if ("".equals(ids)) { return new ArrayList<>(); } else { return mapper.selectByIds(ids); } } /** * 根据页数获取实例列表 * * @param page 页数 * @return 实例列表 */ public List<T> selectAll(int page) { Example example = new Example(getActualClass()); example.setOrderByClause("id desc"); PageHelper.startPage(page, Constant.PAGE_SIZE); return mapper.selectByExample(example); } /** * 根据字段(字符型)和页数获取实例列表 * * @param type 字段 * @param value 查询参数(字符型) * @param page 页数 * @return 实例列表 */ public List<T> selectAll(String type, String value, int page) { if (type.toLowerCase().endsWith("id")) { return selectAll(page, new QueryParameter(type, QueryParameterMethod.EQUAL, value, QueryParameterType.LONG)); } else { return selectAll(page, new QueryParameter(type, QueryParameterMethod.LIKE, value, QueryParameterType.STRING)); } } /** * 根据查询参数获取实例列表 * * @param parameters 查询参数 * @return 实例列表 */ public List<T> selectAll(QueryParameter... parameters) { return selectAll(ALL_PAGE, parameters); } /** * 根据查询参数和页数获取实例列表 * * @param parameters 查询参数 * @param page 页数 * @return 实例列表 */ public List<T> selectAll(int page, QueryParameter... parameters) { if (page != ALL_PAGE) { PageHelper.startPage(page, Constant.PAGE_SIZE); } return mapper.selectByExample(createExample(parameters)); } /** * 根据查询参数和页数获取位置最前的多个实例 * * @param count 数量 * @param parameters 查询参数 * @return 实例列表 */ public List<T> selectTop(int count, QueryParameter... parameters) { return mapper.selectByExampleAndRowBounds(createExample(parameters), new RowBounds(0, count)); } /** * 根据查询参数和页数获取实例列表(关联查询) * * @param table 关联表 * @param parameters 查询参数 * @param page 页数 * @return 实例列表 */ @SuppressWarnings("unchecked") public List<T> selectRelatedAll(String table, int page, QueryParameter... parameters) throws Exception { Object relatedService = SpringUtil.getBean(table + "Service"); Method[] s = relatedService.getClass().getDeclaredMethods(); Method selectMethod = relatedService.getClass().getDeclaredMethod("selectAll", QueryParameter[].class); Object selectList = selectMethod.invoke(relatedService, new Object[]{parameters}); Method selectIdsMethod = relatedService.getClass().getDeclaredMethod("getIds", List.class); List<Long> ids = (List<Long>) selectIdsMethod.invoke(relatedService, (List) selectList); return selectAll(table + "Id", ids, page); } /** * 根据字段(字符型)和页数获取实例列表(关联查询) * * @param type 字段 * @param value 查询参数(字符型) * @param page 页数 * @return 实例列表 */ @SuppressWarnings("unchecked") public List<T> selectRelatedAll(String type, String value, String table, int page) throws Exception { Object relatedService = SpringUtil.getBean(table + "Service"); Method selectMethod = relatedService.getClass().getDeclaredMethod("selectAll", String.class, String.class); Object selectList = selectMethod.invoke(relatedService, type, value); Method selectIdsMethod = relatedService.getClass().getDeclaredMethod("getIds", List.class); List<Long> ids = (List<Long>) selectIdsMethod.invoke(relatedService, (List) selectList); return selectAll(table + "Id", ids, page); } /** * 根据字段(字符型)获取实例列表 * * @param type 字段 * @param value 查询参数(字符型) * @return 实例列表 */ public List<T> selectAll(String type, String value) { if (type.toLowerCase().endsWith("id")) { return selectAll(new QueryParameter(type, QueryParameterMethod.EQUAL, value, QueryParameterType.LONG)); } else { return selectAll(new QueryParameter(type, QueryParameterMethod.LIKE, value, QueryParameterType.STRING)); } } /** * 根据字段(ID列表)和页数获取实例列表 * * @param type 字段 * @param ids ID列表 * @param page 页数 * @return 实例列表 */ public List<T> selectAll(String type, List<Long> ids, int page) { if (ids.isEmpty()) { return new ArrayList<>(); } else { Example example = new Example(getActualClass()); example.setOrderByClause("id desc"); Example.Criteria criteria = example.createCriteria(); criteria.andIn(type, ids); PageHelper.startPage(page, Constant.PAGE_SIZE); return mapper.selectByExample(example); } } /** * 根据字段(ID列表)获取实例列表 * * @param type 字段 * @param ids ID列表 * @return 实例列表 */ public List<T> selectAll(String type, List<Long> ids) { if (ids.isEmpty()) { return new ArrayList<>(); } else { Example example = new Example(getActualClass()); example.setOrderByClause("id desc"); Example.Criteria criteria = example.createCriteria(); criteria.andIn(type, ids); return mapper.selectByExample(example); } } /** * 获取实例总数 * * @return 实例总数 * @throws Exception 反射异常 */ public int getCount() throws Exception { Object object = getActualClass().newInstance(); int count = mapper.selectCount((T) object); return count; } /** * 根据查询参数获取实例总数 * * @param parameters 查询参数 * @return 实例总数 */ public int getCount(QueryParameter... parameters) { int count = mapper.selectCountByExample(createExample(parameters)); return count; } public Example createExample(QueryParameter... parameters) { Example example = new Example(getActualClass()); example.setOrderByClause("id desc"); Example.Criteria criteria = example.createCriteria(); for (QueryParameter parameter : parameters) { Object value = null; switch (parameter.getValueType()) { case STRING: value = parameter.getValue(); break; case LONG: value = Long.parseLong(parameter.getValue()); break; case ARRAY: value = parameter.getValue().split(","); break; } switch (parameter.getMethod()) { case LIKE: criteria.andLike(parameter.getType(), "%" + value + "%"); break; case EQUAL: criteria.andEqualTo(parameter.getType(), value); break; case IN: criteria.andIn(parameter.getType(), Arrays.asList((String[])value)); break; case IS_NULL: criteria.andIsNull(parameter.getType()); break; case IS_NOT_NULL: criteria.andIsNotNull(parameter.getType()); break; } } return example; } /** * 根据字段(字符型)获取实例总数 * * @param type 字段 * @param value 查询参数(字符型) * @return 实例总数 */ public int getCount(String type, String value) { if (type.toLowerCase().endsWith("id")) { return getCount(new QueryParameter(type, QueryParameterMethod.EQUAL, value, QueryParameterType.LONG)); } else { return getCount(new QueryParameter(type, QueryParameterMethod.LIKE, value, QueryParameterType.STRING)); } } /** * 根据字段(字符型)获取实例总数(关联查询) * * @param type 字段 * @param value 查询参数(字符型) * @return 实例总数 */ public int getCount(String type, String value, String table) throws Exception { Object relatedService = SpringUtil.getBean(table + "Service"); Method selectMethod = relatedService.getClass().getDeclaredMethod("selectAll", String.class, String.class); Object selectList = selectMethod.invoke(relatedService, type, value); Method selectIdsMethod = relatedService.getClass().getDeclaredMethod("getIds", List.class); List<Long> ids = (List<Long>) selectIdsMethod.invoke(relatedService, selectList); return getCount(table + "Id", ids); } /** * 根据查询参数获取实例总数(关联查询) * * @param table 关联表 * @param parameters 查询参数 * @return 实例总数 */ public int getCount(String table, QueryParameter... parameters) throws Exception { Object relatedService = SpringUtil.getBean(table + "Service"); Method selectMethod = relatedService.getClass().getDeclaredMethod("selectAll", QueryParameter[].class); Object selectList = selectMethod.invoke(relatedService, new Object[]{parameters}); Method selectIdsMethod = relatedService.getClass().getDeclaredMethod("getIds", List.class); List<Long> ids = (List<Long>) selectIdsMethod.invoke(relatedService, selectList); return getCount(table + "Id", ids); } /** * 根据字段(ID列表)获取实例总数 * * @param type 字段 * @param ids ID列表 * @return 实例总数 */ public int getCount(String type, List<Long> ids) { if (ids.isEmpty()) { return 0; } else { Example example = new Example(getActualClass()); Example.Criteria criteria = example.createCriteria(); criteria.andIn(type, ids); int count = mapper.selectCountByExample(example); return count; } } /** * 从实例列表中提取ID列表 * * @param list 实例列表 * @return ID列表 */ public List<Long> getIds(List<T> list) throws Exception { return getRelatedIds(list, "id"); } /** * 提取对象列表中所有特定ID字段列表 * * @param list 对象列表 * @param filed 私有字段名 * @return 所有特定ID字段列表 * @throws Exception 反射异常 */ public List<Long> getRelatedIds(List<T> list, String filed) throws Exception { Class type = getActualClass(); Field field = type.getDeclaredField(filed); field.setAccessible(true); ArrayList<Long> result = new ArrayList<>(); for (T instance : list) { Long e = Long.parseLong(field.get(instance).toString()); if (!result.contains(e)) { result.add(e); } } return result; } @Transactional public boolean add(T t) { return mapper.insertUseGeneratedKeys(t) > 0; } @Transactional public int add(List<T> list) { return mapper.insertList(list); } @Transactional public boolean modifyById(T t) { return mapper.updateByPrimaryKey(t) > 0; } @Transactional public boolean deleteById(Long id) { return mapper.deleteByPrimaryKey(id) > 0; } @Transactional public boolean deleteAll() { Example example = new Example(getActualClass()); return mapper.deleteByExample(example) > 0; } @Transactional public boolean delete(QueryParameter... parameters) { return mapper.deleteByExample(createExample(parameters)) > 0; } }
3e174b54dd3e71d8ba9753a54251382acd4f3ae5
1,931
java
Java
PA2/src/test/DequeTests.java
Gonnnnn/first_step
11c15402922f235a6ea633a54fc64f25bd2bc51d
[ "MIT" ]
null
null
null
PA2/src/test/DequeTests.java
Gonnnnn/first_step
11c15402922f235a6ea633a54fc64f25bd2bc51d
[ "MIT" ]
null
null
null
PA2/src/test/DequeTests.java
Gonnnnn/first_step
11c15402922f235a6ea633a54fc64f25bd2bc51d
[ "MIT" ]
null
null
null
26.452055
72
0.474883
9,920
import java.time.Duration; import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.*; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import testrunner.annotation.Score; class DequeTests { @Test @Score(2) void testInsert() { assertTimeoutPreemptively( Duration.ofSeconds(1), () -> { IDeque<Integer> dq = new Deque<>(); dq.insertFirst(1); assertThat(dq.first(), is(1)); dq.insertLast(2); assertThat(dq.last(), is(2)); }); } @Test @Score(2) void testDelete() { assertTimeoutPreemptively( Duration.ofSeconds(1), () -> { IDeque<Integer> dq = new Deque<>(); dq.insertFirst(1); dq.insertLast(2); dq.deleteLast(); assertThat(dq.last(), is(1)); dq.deleteFirst(); assertThat(dq.isEmpty(), is(true)); }); } @Test @Score(1) void testEmpty() { assertTimeoutPreemptively( Duration.ofSeconds(1), () -> { IDeque<Integer> dq = new Deque<>(); assertThrows( IllegalStateException.class, () -> dq.deleteFirst(), "deleteFirst()"); assertThrows( IllegalStateException.class, () -> dq.deleteLast(), "deleteLast()"); assertThrows( IllegalStateException.class, () -> dq.first(), "first()."); assertThrows( IllegalStateException.class, () -> dq.last(), "last()"); assertThat("Deque size", dq.size(), is(0)); assertThat(dq.isEmpty(), is(true)); }); } }
3e174ba3fc25ac892140e5090ac118d4e903b0dc
127
java
Java
java/other/saas-price/service/src/main/java/com/ly/dubbox/api/UserService.java
liyong299/normal
97d7df786b720bacdba7329c35062aff3e6afb60
[ "MIT" ]
null
null
null
java/other/saas-price/service/src/main/java/com/ly/dubbox/api/UserService.java
liyong299/normal
97d7df786b720bacdba7329c35062aff3e6afb60
[ "MIT" ]
null
null
null
java/other/saas-price/service/src/main/java/com/ly/dubbox/api/UserService.java
liyong299/normal
97d7df786b720bacdba7329c35062aff3e6afb60
[ "MIT" ]
null
null
null
18.142857
36
0.732283
9,921
package com.ly.dubbox.api; import com.ly.dubbox.entities.User; public interface UserService { User getUser(Long id); }
3e174c2247bff81e7996c78d210aaa41c90bf2e6
3,996
java
Java
myupdateapklibrary/src/main/java/com/trycath/myupdateapklibrary/util/IntenetUtil.java
weileng11/MyUpdateApk-master
b0caf42f65175af87b464b068d84a8a1afaff87e
[ "Apache-2.0" ]
1
2019-06-17T16:13:57.000Z
2019-06-17T16:13:57.000Z
myupdateapklibrary/src/main/java/com/trycath/myupdateapklibrary/util/IntenetUtil.java
weileng11/MyUpdateApk-master
b0caf42f65175af87b464b068d84a8a1afaff87e
[ "Apache-2.0" ]
null
null
null
myupdateapklibrary/src/main/java/com/trycath/myupdateapklibrary/util/IntenetUtil.java
weileng11/MyUpdateApk-master
b0caf42f65175af87b464b068d84a8a1afaff87e
[ "Apache-2.0" ]
null
null
null
40.01
169
0.565109
9,922
package com.trycath.myupdateapklibrary.util; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.telephony.TelephonyManager; /** * 在此写用途 * * @author: guoyoujin * @mail: dycjh@example.com * @date: 2016-09-13 18:49 * @version: V1.0 <描述当前版本功能> */ public class IntenetUtil { private static final String TAG = "IntenetUtil"; //没有网络连接 public static final int NETWORN_NONE = 0; //wifi连接 public static final int NETWORN_WIFI = 1; //手机网络数据连接类型 public static final int NETWORN_2G = 2; public static final int NETWORN_3G = 3; public static final int NETWORN_4G = 4; public static final int NETWORN_MOBILE = 5; /** * 获取当前网络连接类型 * @param context * @return */ public static int getNetworkState(Context context) { //获取系统的网络服务 ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); //如果当前没有网络 if (null == connManager) return NETWORN_NONE; //获取当前网络类型,如果为空,返回无网络 NetworkInfo activeNetInfo = connManager.getActiveNetworkInfo(); if (activeNetInfo == null || !activeNetInfo.isAvailable()) { return NETWORN_NONE; } // 判断是不是连接的是不是wifi NetworkInfo wifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (null != wifiInfo) { NetworkInfo.State state = wifiInfo.getState(); if (null != state) if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) { return NETWORN_WIFI; } } // 如果不是wifi,则判断当前连接的是运营商的哪种网络2g、3g、4g等 NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (null != networkInfo) { NetworkInfo.State state = networkInfo.getState(); String strSubTypeName = networkInfo.getSubtypeName(); if (null != state) if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) { switch (activeNetInfo.getSubtype()) { //如果是2g类型 case TelephonyManager.NETWORK_TYPE_GPRS: // 联通2g case TelephonyManager.NETWORK_TYPE_CDMA: // 电信2g case TelephonyManager.NETWORK_TYPE_EDGE: // 移动2g case TelephonyManager.NETWORK_TYPE_1xRTT: case TelephonyManager.NETWORK_TYPE_IDEN: return NETWORN_2G; //如果是3g类型 case TelephonyManager.NETWORK_TYPE_EVDO_A: // 电信3g case TelephonyManager.NETWORK_TYPE_UMTS: case TelephonyManager.NETWORK_TYPE_EVDO_0: case TelephonyManager.NETWORK_TYPE_HSDPA: case TelephonyManager.NETWORK_TYPE_HSUPA: case TelephonyManager.NETWORK_TYPE_HSPA: case TelephonyManager.NETWORK_TYPE_EVDO_B: case TelephonyManager.NETWORK_TYPE_EHRPD: case TelephonyManager.NETWORK_TYPE_HSPAP: return NETWORN_3G; //如果是4g类型 case TelephonyManager.NETWORK_TYPE_LTE: return NETWORN_4G; default: //中国移动 联通 电信 三种3G制式 if (strSubTypeName.equalsIgnoreCase("TD-SCDMA") || strSubTypeName.equalsIgnoreCase("WCDMA") || strSubTypeName.equalsIgnoreCase("CDMA2000")) { return NETWORN_3G; } else { return NETWORN_MOBILE; } } } } return NETWORN_NONE; } }
3e174d5a7126c97393f2ec8c81e5842a0ffc47be
969
java
Java
compiler/core/src/zserio/emit/common/FileUtil.java
0xDEAD/zserio
d72a4f4e1bfcb023886cdc9f05c95d29360d5f03
[ "BSD-3-Clause" ]
2
2019-02-06T17:50:24.000Z
2019-11-20T16:51:34.000Z
compiler/core/src/zserio/emit/common/FileUtil.java
0xDEAD/zserio
d72a4f4e1bfcb023886cdc9f05c95d29360d5f03
[ "BSD-3-Clause" ]
1
2019-11-25T16:25:51.000Z
2019-11-25T18:09:39.000Z
compiler/core/src/zserio/emit/common/FileUtil.java
Klebert-Engineering/zserio-1
fbb4fc42d9ab6f3afa6c040a36267357399180f4
[ "BSD-3-Clause" ]
null
null
null
29.363636
106
0.615067
9,923
package zserio.emit.common; import java.io.File; /** * File utilities for Zserio emitters. */ public class FileUtil { /** * Creates output directory using given file. * * @param outputFile Output file for which to create output directory. * * @throws ZserioEmitException Throws if output directory cannot be created. */ public static void createOutputDirectory(File outputFile) throws ZserioEmitException { final File parentDir = outputFile.getParentFile(); if (parentDir.exists()) { if (!parentDir.isDirectory()) throw new ZserioEmitException("Can't create ouput directory because file with the same " + "name already exists: " + parentDir.toString()); } else { if (!parentDir.mkdirs()) throw new ZserioEmitException("Can't create output directory: " + parentDir.toString()); } } }
3e174e0b229e30df1ceb1a6cf7cb2dccf712b0d1
14,478
java
Java
src/test/java/org/fcrepo/camel/integration/FcrepoTransactionIT.java
dbernstein/fcrepo-camel
7bc35102b56873973d434e3137cf651c2a227283
[ "Apache-2.0" ]
null
null
null
src/test/java/org/fcrepo/camel/integration/FcrepoTransactionIT.java
dbernstein/fcrepo-camel
7bc35102b56873973d434e3137cf651c2a227283
[ "Apache-2.0" ]
null
null
null
src/test/java/org/fcrepo/camel/integration/FcrepoTransactionIT.java
dbernstein/fcrepo-camel
7bc35102b56873973d434e3137cf651c2a227283
[ "Apache-2.0" ]
null
null
null
43.21791
119
0.651678
9,924
/* * Licensed to DuraSpace under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. * * DuraSpace licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fcrepo.camel.integration; import static org.fcrepo.camel.integration.FcrepoTestUtils.FCREPO_USERNAME; import static org.fcrepo.camel.integration.FcrepoTestUtils.FCREPO_PASSWORD; import java.util.HashMap; import java.util.Map; import org.apache.camel.EndpointInject; import org.apache.camel.Exchange; import org.apache.camel.Produce; import org.apache.camel.ProducerTemplate; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.builder.xml.Namespaces; import org.apache.camel.builder.xml.XPathBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.impl.JndiRegistry; import org.apache.camel.spring.spi.SpringTransactionPolicy; import org.apache.camel.test.junit4.CamelTestSupport; import org.apache.jena.vocabulary.RDF; import org.fcrepo.camel.FcrepoHeaders; import org.fcrepo.camel.FcrepoTransactionManager; import org.fcrepo.client.FcrepoOperationFailedException; import org.junit.Test; import org.junit.Before; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionTemplate; /** * Test adding a new resource with POST * @author Aaron Coburn * @since November 7, 2014 */ public class FcrepoTransactionIT extends CamelTestSupport { private static final String REPOSITORY = "http://fedora.info/definitions/v4/repository#"; private TransactionTemplate txTemplate; private FcrepoTransactionManager txMgr; @EndpointInject(uri = "mock:created") protected MockEndpoint createdEndpoint; @EndpointInject(uri = "mock:transactedput") protected MockEndpoint midtransactionEndpoint; @EndpointInject(uri = "mock:notfound") protected MockEndpoint notfoundEndpoint; @EndpointInject(uri = "mock:verified") protected MockEndpoint verifiedEndpoint; @EndpointInject(uri = "mock:transacted") protected MockEndpoint transactedEndpoint; @EndpointInject(uri = "mock:rollback") protected MockEndpoint rollbackEndpoint; @EndpointInject(uri = "mock:deleted") protected MockEndpoint deletedEndpoint; @EndpointInject(uri = "mock:missing") protected MockEndpoint missingEndpoint; @Produce(uri = "direct:create") protected ProducerTemplate template; @Before public void setUp() throws Exception { super.setUp(); txTemplate = new TransactionTemplate(txMgr); txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txTemplate.afterPropertiesSet(); } @Override protected JndiRegistry createRegistry() throws Exception { final JndiRegistry reg = super.createRegistry(); txMgr = new FcrepoTransactionManager(); txMgr.setBaseUrl(FcrepoTestUtils.getFcrepoBaseUrl()); txMgr.setAuthUsername(FCREPO_USERNAME); txMgr.setAuthPassword(FCREPO_PASSWORD); reg.bind("txManager", txMgr); final SpringTransactionPolicy txPolicy = new SpringTransactionPolicy(); txPolicy.setTransactionManager(txMgr); txPolicy.setPropagationBehaviorName("PROPAGATION_REQUIRED"); reg.bind("required", txPolicy); return reg; } @Test public void testTransaction() throws InterruptedException { // Assertions deletedEndpoint.expectedMessageCount(4); deletedEndpoint.expectedHeaderReceived(Exchange.HTTP_RESPONSE_CODE, 204); transactedEndpoint.expectedMessageCount(1); verifiedEndpoint.expectedMessageCount(3); midtransactionEndpoint.expectedMessageCount(3); midtransactionEndpoint.expectedHeaderReceived(Exchange.HTTP_RESPONSE_CODE, 201); notfoundEndpoint.expectedMessageCount(6); notfoundEndpoint.expectedHeaderReceived(Exchange.HTTP_RESPONSE_CODE, 404); // Start the transaction final Map<String, Object> headers = new HashMap<>(); headers.put(Exchange.HTTP_METHOD, "POST"); headers.put(Exchange.CONTENT_TYPE, "text/turtle"); // Create the object final String fullPath = template.requestBodyAndHeaders( "direct:create", FcrepoTestUtils.getTurtleDocument(), headers, String.class); assertNotNull(fullPath); final String identifier = fullPath.replaceAll(FcrepoTestUtils.getFcrepoBaseUrl(), ""); // Test the creation of several objects template.sendBodyAndHeader("direct:transact", null, "TestIdentifierBase", identifier); // Test the object template.sendBodyAndHeader("direct:verify", null, FcrepoHeaders.FCREPO_IDENTIFIER, identifier + "/one"); template.sendBodyAndHeader("direct:verify", null, FcrepoHeaders.FCREPO_IDENTIFIER, identifier + "/two"); template.sendBodyAndHeader("direct:verify", null, FcrepoHeaders.FCREPO_IDENTIFIER, identifier + "/three"); // Teardown template.sendBodyAndHeader("direct:teardown", null, FcrepoHeaders.FCREPO_IDENTIFIER, identifier + "/one"); template.sendBodyAndHeader("direct:teardown", null, FcrepoHeaders.FCREPO_IDENTIFIER, identifier + "/two"); template.sendBodyAndHeader("direct:teardown", null, FcrepoHeaders.FCREPO_IDENTIFIER, identifier + "/three"); template.sendBodyAndHeader("direct:teardown", null, FcrepoHeaders.FCREPO_IDENTIFIER, identifier); // Confirm assertions verifiedEndpoint.assertIsSatisfied(); deletedEndpoint.assertIsSatisfied(); transactedEndpoint.assertIsSatisfied(); notfoundEndpoint.assertIsSatisfied(); midtransactionEndpoint.assertIsSatisfied(); } @Test public void testTransactionWithRollback() throws InterruptedException { // Assertions deletedEndpoint.expectedMessageCount(1); deletedEndpoint.expectedHeaderReceived(Exchange.HTTP_RESPONSE_CODE, 204); transactedEndpoint.expectedMessageCount(0); verifiedEndpoint.expectedMessageCount(0); midtransactionEndpoint.expectedMessageCount(2); midtransactionEndpoint.expectedHeaderReceived(Exchange.HTTP_RESPONSE_CODE, 201); notfoundEndpoint.expectedMessageCount(3); notfoundEndpoint.expectedHeaderReceived(Exchange.HTTP_RESPONSE_CODE, 404); // Start the transaction final Map<String, Object> headers = new HashMap<>(); headers.put(Exchange.HTTP_METHOD, "POST"); headers.put(Exchange.CONTENT_TYPE, "text/turtle"); // Create the object final String fullPath = template.requestBodyAndHeaders( "direct:create", FcrepoTestUtils.getTurtleDocument(), headers, String.class); assertNotNull(fullPath); final String identifier = fullPath.replaceAll(FcrepoTestUtils.getFcrepoBaseUrl(), ""); // Test the creation of several objects template.sendBodyAndHeader("direct:transactWithError", null, "TestIdentifierBase", identifier); // Test the object template.sendBodyAndHeader("direct:verifyMissing", null, FcrepoHeaders.FCREPO_IDENTIFIER, identifier + "/one"); template.sendBodyAndHeader("direct:verifyMissing", null, FcrepoHeaders.FCREPO_IDENTIFIER, identifier + "/two"); // Teardown template.sendBodyAndHeader("direct:teardown", null, FcrepoHeaders.FCREPO_IDENTIFIER, identifier); // Confirm assertions verifiedEndpoint.assertIsSatisfied(); deletedEndpoint.assertIsSatisfied(); transactedEndpoint.assertIsSatisfied(); notfoundEndpoint.assertIsSatisfied(); midtransactionEndpoint.assertIsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { final String fcrepo_uri = FcrepoTestUtils.getFcrepoEndpointUri(); final String http4_uri = fcrepo_uri.replaceAll("fcrepo:", "http4:"); final Namespaces ns = new Namespaces("rdf", RDF.uri); final XPathBuilder titleXpath = new XPathBuilder("/rdf:RDF/rdf:Description/dc:title/text()"); titleXpath.namespaces(ns); titleXpath.namespace("dc", "http://purl.org/dc/elements/1.1/"); onException(FcrepoOperationFailedException.class) .handled(true) .to("mock:missing"); from("direct:create") .to(fcrepo_uri) .to("mock:created"); from("direct:transactWithError") .transacted("required") .setHeader(FcrepoHeaders.FCREPO_IDENTIFIER).simple("${headers.TestIdentifierBase}/one") .setHeader(Exchange.HTTP_METHOD).constant("PUT") .to(fcrepo_uri) .to("mock:transactedput") .setHeader(Exchange.HTTP_PATH).simple("/fcrepo/rest${headers.TestIdentifierBase}/one") .setHeader(Exchange.HTTP_METHOD).constant("GET") .to(http4_uri + "&throwExceptionOnFailure=false") .to("mock:notfound") .setHeader(FcrepoHeaders.FCREPO_IDENTIFIER).simple("${headers.TestIdentifierBase}/two") .setHeader(Exchange.HTTP_METHOD).constant("PUT") .to(fcrepo_uri) .to("mock:transactedput") .setHeader(Exchange.HTTP_PATH).simple("/fcrepo/rest${headers.TestIdentifierBase}/one") .setHeader(Exchange.HTTP_METHOD).constant("GET") .to(http4_uri + "&throwExceptionOnFailure=false") .to("mock:notfound") .setHeader(Exchange.HTTP_PATH).simple("/fcrepo/rest${headers.TestIdentifierBase}/two") .setHeader(Exchange.HTTP_METHOD).constant("GET") .to(http4_uri + "&throwExceptionOnFailure=false") .to("mock:notfound") // this should throw an error .setHeader(FcrepoHeaders.FCREPO_IDENTIFIER).simple("${headers.TestIdentifierBase}/foo/") .setHeader(Exchange.HTTP_METHOD).constant("POST") .to(fcrepo_uri) .to("mock:transactedput") // this should never be reached .to("mock:transacted"); from("direct:transact") .transacted("required") .setHeader(FcrepoHeaders.FCREPO_IDENTIFIER).simple("${headers.TestIdentifierBase}/one") .setHeader(Exchange.HTTP_METHOD).constant("PUT") .to(fcrepo_uri) .to("mock:transactedput") .setHeader(Exchange.HTTP_PATH).simple("/fcrepo/rest${headers.TestIdentifierBase}/one") .setHeader(Exchange.HTTP_METHOD).constant("GET") .to(http4_uri + "&throwExceptionOnFailure=false") .to("mock:notfound") .setHeader(FcrepoHeaders.FCREPO_IDENTIFIER).simple("${headers.TestIdentifierBase}/two") .setHeader(Exchange.HTTP_METHOD).constant("PUT") .to(fcrepo_uri) .to("mock:transactedput") .setHeader(Exchange.HTTP_PATH).simple("/fcrepo/rest${headers.TestIdentifierBase}/one") .setHeader(Exchange.HTTP_METHOD).constant("GET") .to(http4_uri + "&throwExceptionOnFailure=false") .to("mock:notfound") .setHeader(Exchange.HTTP_PATH).simple("/fcrepo/rest${headers.TestIdentifierBase}/two") .setHeader(Exchange.HTTP_METHOD).constant("GET") .to(http4_uri + "&throwExceptionOnFailure=false") .to("mock:notfound") .setHeader(FcrepoHeaders.FCREPO_IDENTIFIER).simple("${headers.TestIdentifierBase}/three") .setHeader(Exchange.HTTP_METHOD).constant("PUT") .to(fcrepo_uri) .to("mock:transactedput") .setHeader(Exchange.HTTP_PATH).simple("/fcrepo/rest${headers.TestIdentifierBase}/one") .setHeader(Exchange.HTTP_METHOD).constant("GET") .to(http4_uri + "&throwExceptionOnFailure=false") .to("mock:notfound") .setHeader(Exchange.HTTP_PATH).simple("/fcrepo/rest${headers.TestIdentifierBase}/two") .setHeader(Exchange.HTTP_METHOD).constant("GET") .to(http4_uri + "&throwExceptionOnFailure=false") .to("mock:notfound") .setHeader(Exchange.HTTP_PATH).simple("/fcrepo/rest${headers.TestIdentifierBase}/three") .setHeader(Exchange.HTTP_METHOD).constant("GET") .to(http4_uri + "&throwExceptionOnFailure=false") .to("mock:notfound") .to("mock:transacted"); from("direct:verify") .to(fcrepo_uri) .filter().xpath( "/rdf:RDF/rdf:Description/rdf:type" + "[@rdf:resource='" + REPOSITORY + "Resource']", ns) .to("mock:verified"); from("direct:verifyMissing") .to(fcrepo_uri + "&throwExceptionOnFailure=false") .filter(header(Exchange.HTTP_RESPONSE_CODE).isEqualTo("404")) .to("mock:notfound"); from("direct:teardown") .setHeader(Exchange.HTTP_METHOD).constant("DELETE") .to(fcrepo_uri) .to("mock:deleted"); } }; } }
3e174e861ddb311f851b8ddcc4997077ad173ffb
3,479
java
Java
java/java-impl/src/com/intellij/psi/impl/JavaDirectoryIconProvider.java
dmeybohm/intellij-community
7fcc441fd5902ec3d237c34ee93f5ed1faf23629
[ "Apache-2.0" ]
2
2018-12-29T09:53:39.000Z
2018-12-29T09:53:42.000Z
java/java-impl/src/com/intellij/psi/impl/JavaDirectoryIconProvider.java
tnorbye/intellij-community
f01cf262fc196bf4dbb99e20cd937dee3705a7b6
[ "Apache-2.0" ]
null
null
null
java/java-impl/src/com/intellij/psi/impl/JavaDirectoryIconProvider.java
tnorbye/intellij-community
f01cf262fc196bf4dbb99e20cd937dee3705a7b6
[ "Apache-2.0" ]
1
2019-07-18T16:50:52.000Z
2019-07-18T16:50:52.000Z
40.453488
133
0.75079
9,925
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.impl; import com.intellij.icons.AllIcons; import com.intellij.ide.IconProvider; import com.intellij.ide.projectView.impl.ProjectRootsUtil; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.roots.SourceFolder; import com.intellij.openapi.roots.ui.configuration.SourceRootPresentation; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.jrt.JrtFileSystem; import com.intellij.openapi.vfs.newvfs.ArchiveFileSystem; import com.intellij.psi.JavaDirectoryService; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.util.PlatformIcons; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; /** * @author yole */ public class JavaDirectoryIconProvider extends IconProvider implements DumbAware { @Override @Nullable public Icon getIcon(@NotNull PsiElement element, int flags) { if (element instanceof PsiDirectory) { final PsiDirectory psiDirectory = (PsiDirectory)element; final VirtualFile vFile = psiDirectory.getVirtualFile(); final Project project = psiDirectory.getProject(); SourceFolder sourceFolder; Icon symbolIcon; if (vFile.getParent() == null && vFile.getFileSystem() instanceof ArchiveFileSystem) { symbolIcon = PlatformIcons.JAR_ICON; } else if (ProjectRootsUtil.isModuleContentRoot(vFile, project)) { Module module = ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(vFile); symbolIcon = module != null ? ModuleType.get(module).getIcon() : PlatformIcons.CONTENT_ROOT_ICON_CLOSED; } else if (ProjectRootsUtil.findUnloadedModuleByContentRoot(vFile, project) != null) { symbolIcon = AllIcons.Modules.UnloadedModule; } else if ((sourceFolder = ProjectRootsUtil.getModuleSourceRoot(vFile, project)) != null) { symbolIcon = SourceRootPresentation.getSourceRootIcon(sourceFolder); } else if (JrtFileSystem.isModuleRoot(vFile)) { symbolIcon = AllIcons.Nodes.JavaModuleRoot; } else if (JavaDirectoryService.getInstance().getPackage(psiDirectory) != null) { symbolIcon = PlatformIcons.PACKAGE_ICON; } else if (!Registry.is("ide.hide.excluded.files") && ProjectRootManager.getInstance(project).getFileIndex().isExcluded(vFile)) { symbolIcon = AllIcons.Modules.ExcludeRoot; } else { symbolIcon = PlatformIcons.DIRECTORY_CLOSED_ICON; } return ElementBase.createLayeredIcon(element, symbolIcon, 0); } return null; } }
3e174ee74133b6c2ef9159c898a50bbff1f488d1
1,886
java
Java
src/main/java/com/learning/springboot/controller/AccountController.java
ApoorvaGupta2/BudgetAnalysisSystem
f8a43a548d34b1d096123ea5611ba64fb77f9245
[ "Apache-2.0" ]
null
null
null
src/main/java/com/learning/springboot/controller/AccountController.java
ApoorvaGupta2/BudgetAnalysisSystem
f8a43a548d34b1d096123ea5611ba64fb77f9245
[ "Apache-2.0" ]
7
2021-06-30T03:12:05.000Z
2021-07-31T11:58:48.000Z
src/main/java/com/learning/springboot/controller/AccountController.java
ApoorvaGupta2/BudgetAnalysisSystem
f8a43a548d34b1d096123ea5611ba64fb77f9245
[ "Apache-2.0" ]
null
null
null
29.46875
64
0.780488
9,926
package com.learning.springboot.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; 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.servlet.ModelAndView; import com.learning.springboot.beans.ae.AccountAE; import com.learning.springboot.service.AccountService; @Controller @RequestMapping("/account") public class AccountController { @Autowired private AccountService accountService; @RequestMapping(path="/", method =RequestMethod.GET) public String getView() { return "account"; } @RequestMapping(path="/", method=RequestMethod.POST) public String createAccount(AccountAE accountAE) { accountService.submitAccount(accountAE); return "account"; } @RequestMapping(path="/showaccount", method= RequestMethod.GET) public ModelAndView showAccount() { ModelAndView mv = new ModelAndView("ShowAccount"); mv.addObject("accounts",accountService.getActiveAccounts()); return mv; } @RequestMapping(path="/update", method=RequestMethod.GET) public ModelAndView getAccount(@RequestParam int id) { ModelAndView mv = new ModelAndView("UpdateAccount"); mv.addObject("accounts", accountService.getAccountById(id)); return mv; } @RequestMapping(path="/update", method=RequestMethod.POST) public String updateAccount(AccountAE accountAE) { accountService.submitAccount(accountAE); return "UpdateAccount"; } @RequestMapping(path = "/delete", method = RequestMethod.POST) public ModelAndView deleteAccount(@RequestParam int id) { accountService.delete(id); ModelAndView mv = new ModelAndView("ShowAccount"); mv.addObject("accounts",accountService.getActiveAccounts()); return mv; } }
3e175023d69e39524c004032518cafbcc53faeff
669
java
Java
backend/src/main/java/com/jitterted/tddgame/domain/User.java
jitterted/tdd-game
57b94eabbfb036ccf15cea4eeaef3c02aadee5c4
[ "Fair" ]
null
null
null
backend/src/main/java/com/jitterted/tddgame/domain/User.java
jitterted/tdd-game
57b94eabbfb036ccf15cea4eeaef3c02aadee5c4
[ "Fair" ]
2
2022-02-14T02:38:01.000Z
2022-02-27T11:49:01.000Z
backend/src/main/java/com/jitterted/tddgame/domain/User.java
jitterted/tdd-game
57b94eabbfb036ccf15cea4eeaef3c02aadee5c4
[ "Fair" ]
null
null
null
16.725
62
0.626308
9,927
package com.jitterted.tddgame.domain; import org.jetbrains.annotations.NotNull; public class User { private String name; public User(@NotNull String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return name.equals(user.name); } @Override public int hashCode() { return name.hashCode(); } @Override public String toString() { return "User: name = " + name; } }
3e1751c3eb136a68217ae52caf6597115efe2f64
1,677
java
Java
java/performance/threaddemo/src/threaddemo/model/PhadhailNameEvent.java
tusharvjoshi/incubator-netbeans
a61bd21f4324f7e73414633712522811cb20ac93
[ "Apache-2.0" ]
1,056
2019-04-25T20:00:35.000Z
2022-03-30T04:46:14.000Z
java/performance/threaddemo/src/threaddemo/model/PhadhailNameEvent.java
Marc382/netbeans
4bee741d24a3fdb05baf135de5e11a7cd95bd64e
[ "Apache-2.0" ]
1,846
2019-04-25T20:50:05.000Z
2022-03-31T23:40:41.000Z
java/performance/threaddemo/src/threaddemo/model/PhadhailNameEvent.java
Marc382/netbeans
4bee741d24a3fdb05baf135de5e11a7cd95bd64e
[ "Apache-2.0" ]
550
2019-04-25T20:04:33.000Z
2022-03-25T17:43:01.000Z
30.490909
93
0.686941
9,928
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package threaddemo.model; /** * Event object for phadhail name change events. * Old and new names may be null. * @author Jesse Glick */ public final class PhadhailNameEvent extends PhadhailEvent { /** factory */ public static PhadhailNameEvent create(Phadhail ph, String oldName, String newName) { return new PhadhailNameEvent(ph, oldName, newName); } private final String oldName, newName; private PhadhailNameEvent(Phadhail ph, String oldName, String newName) { super(ph); this.oldName = oldName; this.newName = newName; } public String getOldName() { return oldName; } public String getNewName() { return newName; } public String toString() { return "PhadhailNameEvent[" + getPhadhail() + ":" + oldName + " -> " + newName + "]"; } }
3e1752b4ddfdb7d3f91a1a51d255c60d1bb89173
5,900
java
Java
hodor-server/src/main/java/org/dromara/hodor/server/manager/ActuatorNodeManager.java
tincopper/hodor
2c4c351cd8ed7ad2352941c77186374f1789eb62
[ "Apache-2.0" ]
55
2020-12-08T16:59:36.000Z
2022-01-11T14:43:11.000Z
hodor-server/src/main/java/org/dromara/hodor/server/manager/ActuatorNodeManager.java
tincopper/hodor
2c4c351cd8ed7ad2352941c77186374f1789eb62
[ "Apache-2.0" ]
6
2021-02-01T02:51:02.000Z
2022-01-21T23:50:57.000Z
hodor-server/src/main/java/org/dromara/hodor/server/manager/ActuatorNodeManager.java
tincopper/hodor
2c4c351cd8ed7ad2352941c77186374f1789eb62
[ "Apache-2.0" ]
35
2021-01-26T13:18:21.000Z
2022-03-12T16:31:00.000Z
36.196319
148
0.695932
9,929
package org.dromara.hodor.server.manager; import cn.hutool.core.lang.Assert; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.dromara.hodor.common.Host; import org.dromara.hodor.common.concurrent.HodorThreadFactory; import org.dromara.hodor.common.loadbalance.LoadBalance; import org.dromara.hodor.common.loadbalance.LoadBalanceEnum; import org.dromara.hodor.common.loadbalance.LoadBalanceFactory; import org.dromara.hodor.model.actuator.ActuatorInfo; import org.dromara.hodor.model.node.NodeInfo; /** * actuator node manager * * @author tomgs * @version 2021/8/1 1.0 */ @Slf4j public class ActuatorNodeManager { private static volatile ActuatorNodeManager INSTANCE; // groupName -> endpoint set private final Map<String, Set<String>> actuatorEndpoints = Maps.newConcurrentMap(); // endpoint -> actuatorNodeInfo private final Map<String, ActuatorInfo> actuatorNodeInfos = Maps.newConcurrentMap(); private static final int HEARTBEAT_THRESHOLD = 30_000; private ScheduledExecutorService cleanSchedule; private ActuatorNodeManager() { } public static ActuatorNodeManager getInstance() { if (INSTANCE == null) { synchronized (ActuatorNodeManager.class) { if (INSTANCE == null) { INSTANCE = new ActuatorNodeManager(); } } } return INSTANCE; } public void startOfflineActuatorClean() { this.cleanSchedule = Executors.newSingleThreadScheduledExecutor(HodorThreadFactory.create("offline-actuator-cleaner", false)); this.cleanSchedule.scheduleWithFixedDelay(this::offlineActuatorClean, 30,60, TimeUnit.SECONDS); } public void offlineActuatorClean() { log.info("offline actuator clean ..."); actuatorNodeInfos.entrySet().removeIf(entry -> { ActuatorInfo actuatorInfo = entry.getValue(); if (heartbeatThresholdExceedCheck(actuatorInfo.getLastHeartbeat())) { String endpoint = entry.getKey(); removeNode(endpoint); return true; } return false; }); } private void removeNode(String endpoint) { actuatorNodeInfos.remove(endpoint); actuatorEndpoints.values().forEach(endpoints -> endpoints.removeIf(e -> e.equals(endpoint))); } public void addActuatorEndpoint(String groupName, String nodeEndpoint) { Set<String> endpoints = actuatorEndpoints.computeIfAbsent(groupName, e -> Sets.newConcurrentHashSet()); endpoints.add(nodeEndpoint); } public void removeActuatorGroup(String groupName, String nodeEndpoint) { Optional.ofNullable(actuatorEndpoints.get(groupName)).ifPresent(endpoints -> endpoints.removeIf(endpoint -> endpoint.equals(nodeEndpoint))); } public Set<String> getActuatorEndpointsByGroupName(final String groupName) { return actuatorEndpoints.getOrDefault(groupName, Sets.newConcurrentHashSet()); } public boolean isOffline(String endpoint) { Long lastHeartbeat = actuatorNodeInfos.get(endpoint).getLastHeartbeat(); return heartbeatThresholdExceedCheck(lastHeartbeat); } private boolean heartbeatThresholdExceedCheck(Long lastHeartbeat) { return System.currentTimeMillis() - lastHeartbeat > HEARTBEAT_THRESHOLD; } public void clearActuatorNodes() { actuatorEndpoints.clear(); actuatorNodeInfos.clear(); } public void stopOfflineActuatorClean() { if (cleanSchedule != null) { cleanSchedule.shutdown(); } } public List<Host> getAvailableHosts(String groupName) { List<String> allWorkNodes = Lists.newArrayList(getActuatorEndpointsByGroupName(groupName)); List<Host> hosts = allWorkNodes.stream() .filter(endpoint -> !isOffline(endpoint)) .map(Host::of) .collect(Collectors.toList()); Assert.notEmpty(hosts, "The group [{}] has no available nodes.", groupName); LoadBalance loadBalance = LoadBalanceFactory.getLoadBalance(LoadBalanceEnum.RANDOM.name()); Host selected = loadBalance.select(hosts); hosts.remove(selected); hosts.add(selected); return hosts; } public void addActuatorNode(String nodeEndpoint, NodeInfo nodeInfo) { ActuatorInfo actuatorInfo = actuatorNodeInfos.computeIfAbsent(nodeEndpoint, k -> ActuatorInfo.builder() .nodeEndpoint(nodeEndpoint) .groupNames(Sets.newHashSet()) .build()); actuatorInfo.setNodeInfo(nodeInfo); } public NodeInfo getActuatorNode(String nodeEndpoint) { ActuatorInfo actuatorNodeInfo = Optional.ofNullable(actuatorNodeInfos.get(nodeEndpoint)) .orElse(ActuatorInfo.builder() .nodeInfo(new NodeInfo()) .build()); return actuatorNodeInfo.getNodeInfo(); } public void removeActuatorNode(String nodeEndpoint) { actuatorNodeInfos.remove(nodeEndpoint); } public void addActuatorNodeInfo(String groupName, String nodeEndpoint, long lastHeartbeat) { ActuatorInfo actuatorInfo = actuatorNodeInfos.computeIfAbsent(nodeEndpoint, k -> ActuatorInfo.builder() .nodeEndpoint(nodeEndpoint) .groupNames(Sets.newHashSet(groupName)) .lastHeartbeat(lastHeartbeat) .build()); actuatorInfo.getGroupNames().add(groupName); actuatorInfo.setLastHeartbeat(lastHeartbeat); } }
3e1752d6eb590968aee6bf5e83707d321b3ce354
2,659
java
Java
happyframe/src/com/game/module/player/model/Player.java
caochuangui/game
ddcac01443eb3bab1ea08e992b8bbb888f9b3935
[ "MIT" ]
null
null
null
happyframe/src/com/game/module/player/model/Player.java
caochuangui/game
ddcac01443eb3bab1ea08e992b8bbb888f9b3935
[ "MIT" ]
null
null
null
happyframe/src/com/game/module/player/model/Player.java
caochuangui/game
ddcac01443eb3bab1ea08e992b8bbb888f9b3935
[ "MIT" ]
null
null
null
15.641176
70
0.614141
9,930
package com.game.module.player.model; import com.frame.async.AsynOperation; import com.frame.bean.BeanManager; import com.game.commom.InstanceMsg; import com.game.module.player.dao.PlayerDao; import com.game.module.player.service.PlayerService; /** * @author liuzhengyi * @date 2014年11月18日 下午5:14:37 */ public class Player extends AsynOperation implements InstanceMsg{ private int playerId; // 玩家Id,唯一标识 private String name = ""; // 玩家姓名 private int level = 1; private short viplevel = 0; // vip等级 private int copper = 0; // 钱币 private int gold = 0; // 金币 private int exp = 0; // 当前经验 private int bagMaxCount = 20; public Player(int playerId) { this.playerId = playerId; } public Player() { } /** * @return the playerId */ public int getPlayerId() { return playerId; } /** * @param playerId * the playerId to set */ public void setPlayerId(int playerId) { this.playerId = playerId; } /** * @return the viplevel */ public short getViplevel() { return viplevel; } /** * @param viplevel * the viplevel to set */ public void setViplevel(short viplevel) { this.viplevel = viplevel; } /** * @return the gold */ public int getGold() { return gold; } /** * @param gold * the gold to set */ public void setGold(int gold) { this.gold = gold; } /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the exp */ public int getExp() { return exp; } /** * @param exp * the exp to set */ public void setExp(int exp) { this.exp = exp; } public int getCopper() { return copper; } public void setCopper(int copper) { this.copper = copper; } /** * @return the level */ public int getLevel() { return level; } /** * @param level * the level to set */ public void setLevel(int level) { this.level = level; } public int getBagMaxCount() { return bagMaxCount; } public void setBagMaxCount(int count) { bagMaxCount = count; } /** * * @see frame.async.AsynObject#save2DB() */ @Override public void save2DB() { PlayerDao bean = BeanManager.getInstance().getBean(PlayerDao.class); bean.updatePlayer(this); } /** * * @see com.gzwabao.frame.async.AsynOperation#getId() */ @Override public Integer getId() { return playerId; } @Override public String toMsg() { String msg = level + " " + viplevel + " " + copper + " " + gold + " " + bagMaxCount + " " + exp; return msg; } }
3e17530c448059d4100da38f41129ca3edbf9748
1,108
java
Java
src/main/java/ch/rasc/s4ws/portfolio/service/Quote.java
ralscha/spring4ws-demos
7af3cf34abaef98a8d9e0954cfdc2d0e41f30289
[ "Apache-2.0" ]
37
2015-02-04T09:43:03.000Z
2019-06-18T15:59:28.000Z
src/main/java/ch/rasc/s4ws/portfolio/service/Quote.java
ralscha/spring4ws-demos
7af3cf34abaef98a8d9e0954cfdc2d0e41f30289
[ "Apache-2.0" ]
1
2021-03-30T22:24:12.000Z
2021-04-01T14:20:37.000Z
src/main/java/ch/rasc/s4ws/portfolio/service/Quote.java
ralscha/spring4ws-demos
7af3cf34abaef98a8d9e0954cfdc2d0e41f30289
[ "Apache-2.0" ]
22
2015-01-16T03:35:22.000Z
2019-04-03T02:42:22.000Z
24.622222
75
0.718412
9,931
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.rasc.s4ws.portfolio.service; import java.math.BigDecimal; public class Quote { private final String ticker; private final BigDecimal price; public Quote(String ticker, BigDecimal price) { this.ticker = ticker; this.price = price; } public String getTicker() { return this.ticker; } public BigDecimal getPrice() { return this.price; } @Override public String toString() { return "Quote [ticker=" + this.ticker + ", price=" + this.price + "]"; } }
3e175314c68dc487d8d3b3e20adc18951a7dc20c
5,029
java
Java
src/main/java/org/overrun/swgl/core/gl/batch/GLBatchCmd.java
Over-Run/vgl-java
ed2d8422e2ab661f5d5e3ac11f39e8d6b3b4cee9
[ "Apache-2.0", "MIT" ]
2
2022-02-12T14:30:46.000Z
2022-03-20T02:36:34.000Z
src/main/java/org/overrun/swgl/core/gl/batch/GLBatchCmd.java
Over-Run/vgl-java
ed2d8422e2ab661f5d5e3ac11f39e8d6b3b4cee9
[ "Apache-2.0", "MIT" ]
3
2022-02-18T05:42:49.000Z
2022-03-20T06:04:43.000Z
src/main/java/org/overrun/swgl/core/gl/batch/GLBatchCmd.java
Over-Run/vgl-java
ed2d8422e2ab661f5d5e3ac11f39e8d6b3b4cee9
[ "Apache-2.0", "MIT" ]
null
null
null
31.236025
95
0.61205
9,932
/* * MIT License * * Copyright (c) 2022 Overrun Organization * * 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 org.overrun.swgl.core.gl.batch; import org.overrun.swgl.core.util.math.Numbers; import java.util.Arrays; import java.util.StringJoiner; import static org.overrun.swgl.core.gl.batch.GLBatchLang.*; /** * The base batch command. * * @author squid233 * @since 0.2.0 */ public abstract class GLBatchCmd { protected final String[] args; public GLBatchCmd(String[] args) { if (args.length < getRequiredArgCount() || args.length > getAllowArgCount()) throw new ArrayIndexOutOfBoundsException(getValue() + "arguments count is invalid. Required: " + getRequiredArgCount() + ", Allow: " + getAllowArgCount() + ", Actual: " + args.length); this.args = args; } public static boolean isSameAs(String cmdName, GLBatchCmd cmd) { return cmd.getValue().equals(cmdName); } public static GLBatchCmd beginf(String[] args) { return of(args, KWD_BEGINF, 2, 2); } public static GLBatchCmd end(String[] args) { return of(args, KWD_END, 0, 0); } public static GLBatchCmd vertex(String[] args) { return of(args, KWD_VERTEX, 2, 4); } public static GLBatchCmd color(String[] args) { return of(args, KWD_COLOR, 3, 4); } public static GLBatchCmd texCoord(String[] args) { return of(args, KWD_TEX_COORD, 1, 4); } public static GLBatchCmd normal(String[] args) { return of(args, KWD_NORMAL, 3, 3); } public static GLBatchCmd ib(String[] args) { return of(args, KWD_INDEX_BEFORE, 1, Integer.MAX_VALUE); } public static GLBatchCmd ia(String[] args) { return of(args, KWD_INDEX_AFTER, 1, Integer.MAX_VALUE); } public static GLBatchCmd emit(String[] args) { return of(args, KWD_EMIT, 0, 0); } private static GLBatchCmd of(String[] args, String value, int minCount, int maxCount) { return new GLBatchCmd(args) { @Override public String getValue() { return value; } @Override public int getRequiredArgCount() { return minCount; } @Override public int getAllowArgCount() { return maxCount; } }; } public abstract String getValue(); public abstract int getRequiredArgCount(); public abstract int getAllowArgCount(); public int getArgCount() { return args.length; } public String getString(int index) { return args[index]; } public float getFloat(int index) throws NullPointerException, NumberFormatException { return Float.parseFloat(args[index]); } public int getInt(int index, int radix) throws NumberFormatException { return Integer.parseInt(args[index], radix); } public int getInt(int index) throws NumberFormatException { return Integer.parseInt(args[index]); } public int getIntAuto4(int index) throws NumberFormatException { return Numbers.parseIntAuto4(args[index]); } public boolean isSame(String cmd) { return isSameAs(cmd, this); } @Override public String toString() { var joiner = new StringJoiner(", ", GLBatchCmd.class.getSimpleName() + "[", "]") .add("name=" + getValue()); if (args.length > 0) joiner.add("args=" + Arrays.toString(args)); return joiner.add("minCount=" + getRequiredArgCount()) .add("maxCount=" + getAllowArgCount()) .add("count=" + getArgCount()) .toString(); } }
3e1753773e3a1d09d93d5433baca14b9c472ee25
1,558
java
Java
src/main/java/com/hp/application/automation/tools/model/SseProxySettings.java
orenbm21/hp-application-automation-tools-plugin
987536f5551bc76fd028d746a951d1fd72c7567a
[ "MIT" ]
19
2015-01-26T16:21:49.000Z
2017-07-22T09:07:45.000Z
src/main/java/com/hp/application/automation/tools/model/SseProxySettings.java
orenbm21/hp-application-automation-tools-plugin
987536f5551bc76fd028d746a951d1fd72c7567a
[ "MIT" ]
140
2015-01-06T17:19:02.000Z
2017-08-10T12:20:48.000Z
src/main/java/com/hp/application/automation/tools/model/SseProxySettings.java
orenbm21/hp-application-automation-tools-plugin
987536f5551bc76fd028d746a951d1fd72c7567a
[ "MIT" ]
70
2015-01-06T17:12:26.000Z
2017-07-10T12:28:38.000Z
24.730159
97
0.716945
9,933
package com.hp.application.automation.tools.model; import org.kohsuke.stapler.DataBoundConstructor; import hudson.util.Secret; /** * This model is for sse build step's proxy setting. * It's different from the class ProxySettings. Here we use credentials instead of name/password. * @author llu4 * */ public class SseProxySettings { private String fsProxyAddress; private String fsProxyCredentialsId; /** * To store the user name which get from the credentials. * Is set in sseBuilder while performing. */ private String fsProxyUserName; /** * To store the password which get from the credentials. * Is set in sseBuilder while performing. */ private Secret fsProxyPassword; /** * These two variables are set directly by the jelly form. */ @DataBoundConstructor public SseProxySettings(String fsProxyAddress, String fsProxyCredentialsId) { this.fsProxyAddress = fsProxyAddress; this.fsProxyCredentialsId = fsProxyCredentialsId; } public String getFsProxyAddress() { return fsProxyAddress; } public String getFsProxyCredentialsId() { return fsProxyCredentialsId; } public String getFsProxyUserName() { return fsProxyUserName; } public void setFsProxyUserName(String fsProxyUserName) { this.fsProxyUserName = fsProxyUserName; } public Secret getFsProxyPassword() { return fsProxyPassword; } public void setFsProxyPassword(Secret fsProxyPassword) { this.fsProxyPassword = fsProxyPassword; } }
3e1753e332ae0f6081aec63ab306b4345d864902
1,159
java
Java
java/spring-security/java-config/src/test/java/sample/spring/security/test/MyTestServiceTest.java
opengl-8080/Samples
bf4f3b41a2bb77637284376e8aa3a97412b8cf4b
[ "MIT" ]
3
2018-05-06T06:53:23.000Z
2018-05-26T18:53:28.000Z
java/spring-security/java-config/src/test/java/sample/spring/security/test/MyTestServiceTest.java
opengl-8080/Samples
bf4f3b41a2bb77637284376e8aa3a97412b8cf4b
[ "MIT" ]
2
2017-03-03T14:48:25.000Z
2018-05-26T11:42:26.000Z
java/spring-security/java-config/src/test/java/sample/spring/security/test/MyTestServiceTest.java
opengl-8080/Samples
bf4f3b41a2bb77637284376e8aa3a97412b8cf4b
[ "MIT" ]
6
2017-05-08T23:51:56.000Z
2021-04-10T02:09:06.000Z
34.088235
95
0.753236
9,934
package sample.spring.security.test; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes=MyTestSpringSecurityConfig.class) public class MyTestServiceTest { @Autowired private MyTestService service; @Test(expected = AuthenticationCredentialsNotFoundException.class) public void test_getMessage_no_authentication() throws Exception { // exercise this.service.getMessage(); } @Test @WithMockUser(username = "hoge") public void test_getMessage() throws Exception { // exercise String message = this.service.getMessage(); // verify Assert.assertEquals("Hello hoge", message); } }
3e1754532b9b65c96702ddd6e6375260ebbba349
335
java
Java
src/test/java/com/springShop/SpringShopApplicationTests.java
mjozefowski/spring-shop
6bf1692bba85eeea07ec5f4cb963e04ec37889ac
[ "MIT" ]
null
null
null
src/test/java/com/springShop/SpringShopApplicationTests.java
mjozefowski/spring-shop
6bf1692bba85eeea07ec5f4cb963e04ec37889ac
[ "MIT" ]
null
null
null
src/test/java/com/springShop/SpringShopApplicationTests.java
mjozefowski/spring-shop
6bf1692bba85eeea07ec5f4cb963e04ec37889ac
[ "MIT" ]
null
null
null
19.705882
60
0.81194
9,935
package com.springShop; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpringShopApplicationTests { @Test public void contextLoads() { } }
3e17548e7defe9a9e155999a39bd9576f52763e1
2,007
java
Java
src/main/java/net/etalia/jalia/WeakIdentityHashMap.java
VeloxManagementLimited/jalia
2415d7a1718dce1b02151bfdd35064bc6be0d25d
[ "Apache-2.0" ]
1
2019-10-04T07:26:39.000Z
2019-10-04T07:26:39.000Z
src/main/java/net/etalia/jalia/WeakIdentityHashMap.java
VeloxManagementLimited/jalia
2415d7a1718dce1b02151bfdd35064bc6be0d25d
[ "Apache-2.0" ]
3
2016-03-30T23:26:43.000Z
2021-06-16T01:54:51.000Z
src/main/java/net/etalia/jalia/WeakIdentityHashMap.java
VeloxManagementLimited/jalia
2415d7a1718dce1b02151bfdd35064bc6be0d25d
[ "Apache-2.0" ]
3
2019-02-19T06:52:49.000Z
2022-02-15T08:15:24.000Z
24.180723
76
0.56004
9,936
package net.etalia.jalia; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; public class WeakIdentityHashMap<K, V> { private final HashMap<WeakReference<K>, V> mMap = new HashMap<>(); private final ReferenceQueue<Object> mRefQueue = new ReferenceQueue<>(); private void cleanUp() { Reference<?> ref; while ((ref = mRefQueue.poll()) != null) { mMap.remove(ref); } } public void put(K key, V value) { cleanUp(); mMap.put(new CmpWeakReference<>(key, mRefQueue), value); } public V get(K key) { cleanUp(); return mMap.get(new CmpWeakReference<>(key)); } public Collection<V> values() { cleanUp(); return mMap.values(); } public Set<Map.Entry<WeakReference<K>, V>> entrySet() { return mMap.entrySet(); } public int size() { cleanUp(); return mMap.size(); } public boolean isEmpty() { cleanUp(); return mMap.isEmpty(); } private static class CmpWeakReference<K> extends WeakReference<K> { private final int mHashCode; public CmpWeakReference(K key) { super(key); mHashCode = System.identityHashCode(key); } public CmpWeakReference(K key, ReferenceQueue<Object> refQueue) { super(key, refQueue); mHashCode = System.identityHashCode(key); } @Override public boolean equals(Object o) { if (o == this) { return true; } K k = get(); if (k != null && o instanceof CmpWeakReference) { return ((CmpWeakReference) o).get() == k; } return false; } @Override public int hashCode() { return mHashCode; } } }
3e1755139846ff688f2936eb679472c894cf5daf
155
java
Java
src/main/java/exnihiloadscensio/registries/manager/IFluidOnTopDefaultRegistryProvider.java
MikeLydeamore/ExNihiloAdscensio
a5fab7984d692b7084e2283c71a06f79fa2d32a3
[ "MIT" ]
24
2016-09-11T22:50:19.000Z
2021-10-01T00:17:43.000Z
src/main/java/exnihiloadscensio/registries/manager/IFluidOnTopDefaultRegistryProvider.java
MikeLydeamore/ExNihiloAdscensio
a5fab7984d692b7084e2283c71a06f79fa2d32a3
[ "MIT" ]
144
2016-09-01T02:03:04.000Z
2019-07-26T23:41:38.000Z
src/main/java/exnihiloadscensio/registries/manager/IFluidOnTopDefaultRegistryProvider.java
MikeLydeamore/ExNihiloAdscensio
a5fab7984d692b7084e2283c71a06f79fa2d32a3
[ "MIT" ]
37
2016-03-03T15:37:16.000Z
2021-11-10T06:57:34.000Z
19.375
53
0.851613
9,937
package exnihiloadscensio.registries.manager; public interface IFluidOnTopDefaultRegistryProvider { public void registerFluidOnTopRecipeDefaults(); }
3e1755397738ff1e5c696e52ba3092004c9a8896
2,067
java
Java
src/main/java/org/javajdj/jswing/jtrace/TraceMarker.java
jandejongh/jswing
b7bb684fb614a3d855b2f9bb0e3f51fd28c41d65
[ "Apache-2.0" ]
null
null
null
src/main/java/org/javajdj/jswing/jtrace/TraceMarker.java
jandejongh/jswing
b7bb684fb614a3d855b2f9bb0e3f51fd28c41d65
[ "Apache-2.0" ]
3
2020-01-04T14:23:21.000Z
2022-01-07T16:32:09.000Z
src/main/java/org/javajdj/jswing/jtrace/TraceMarker.java
jandejongh/jswing
b7bb684fb614a3d855b2f9bb0e3f51fd28c41d65
[ "Apache-2.0" ]
null
null
null
31.439394
132
0.518554
9,938
/* * Copyright 2010-2020 Jan de Jongh <lyhxr@example.com>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.javajdj.jswing.jtrace; import java.util.logging.Logger; /** A marker (type) for a trace (or multiple) for displaying in a {@link JTrace} panel. * * @author Jan de Jongh {@literal <lyhxr@example.com>} * * @see TraceEntry * @see JTrace * * @see TraceEntry#withTraceMarkers * @see TraceEntry#withTraceMarkersAdded * * @see JTrace#setTraceMarkers * @see JTrace#addTraceMarkers * * @see TraceDB#getTraceMarkers * @see TraceDB#setTraceMarkers * @see TraceDB#addTraceMarkers * */ public enum TraceMarker { /** A marker on the side of the trace display showing the value zero of X. * */ ZERO_X_SIDE_MARKER, /** A marker on the side of the trace display showing the value zero of Y. * */ ZERO_Y_SIDE_MARKER; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // LOGGER // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private static final Logger LOG = Logger.getLogger (TraceMarker.class.getName ()); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // END OF FILE // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// }