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
sequence | 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
sequence | 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
sequence | 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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e01e3e44513ddc8cb5a78e65935a1812bae1720 | 4,747 | java | Java | taotao-cloud-microservice/taotao-cloud-auth/taotao-cloud-auth-biz/src/main/java/com/taotao/cloud/auth/biz/configuration/WebClientConfiguration.java | shuigedeng/taotao-cloud-parent | b2f0f46daa32399bb8651486c4faccb1f569b0b2 | [
"Apache-2.0"
] | 47 | 2021-04-13T10:32:13.000Z | 2022-03-31T10:30:30.000Z | taotao-cloud-microservice/taotao-cloud-auth/taotao-cloud-auth-biz/src/main/java/com/taotao/cloud/auth/biz/configuration/WebClientConfiguration.java | shuigedeng/taotao-cloud-parent | b2f0f46daa32399bb8651486c4faccb1f569b0b2 | [
"Apache-2.0"
] | 1 | 2021-11-01T07:41:04.000Z | 2021-11-01T07:41:10.000Z | taotao-cloud-microservice/taotao-cloud-auth/taotao-cloud-auth-biz/src/main/java/com/taotao/cloud/auth/biz/configuration/WebClientConfiguration.java | shuigedeng/taotao-cloud-project | ff8aabc3853abc42fd3ea8bf74c1072b676a88f8 | [
"Apache-2.0"
] | 21 | 2021-04-13T10:32:17.000Z | 2022-03-26T07:43:22.000Z | 40.922414 | 131 | 0.820518 | 803 | package com.taotao.cloud.auth.biz.configuration;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.client.OAuth2AuthorizationContext;
import org.springframework.security.oauth2.client.OAuth2AuthorizeRequest;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.function.client.WebClient;
@Configuration
public class WebClientConfiguration {
@Bean
WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client =
new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
return WebClient
.builder()
.apply(oauth2Client.oauth2Configuration())
.build();
}
@Bean
OAuth2AuthorizedClientManager authorizedClientManager(
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken()
.clientCredentials()
.password()
.build();
DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
// Assuming the `username` and `password` are supplied as `HttpServletRequest` parameters,
// map the `HttpServletRequest` parameters to `OAuth2AuthorizationContext.getAttributes()`
authorizedClientManager.setContextAttributesMapper(contextAttributesMapper());
return authorizedClientManager;
}
private Function<OAuth2AuthorizeRequest, Map<String, Object>> contextAttributesMapper() {
return authorizeRequest -> {
Map<String, Object> contextAttributes = Collections.emptyMap();
HttpServletRequest servletRequest = authorizeRequest.getAttribute(
HttpServletRequest.class.getName());
String username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME);
String password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD);
String scope = servletRequest.getParameter(OAuth2ParameterNames.SCOPE);
if (StringUtils.hasText(scope)) {
contextAttributes = new HashMap<>();
contextAttributes.put(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME,
StringUtils.delimitedListToStringArray(scope, " "));
}
if (!StringUtils.hasText(username) && !StringUtils.hasText(password)) {
Authentication authentication = authorizeRequest.getPrincipal();
if (authentication instanceof UsernamePasswordAuthenticationToken) {
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
Object principal = token.getPrincipal();
username = token.getName();
password = (String) token.getCredentials();
if (principal instanceof User) {
User user = (User) principal;
username = user.getUsername();
}
}
}
if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
if (CollectionUtils.isEmpty(contextAttributes)) {
contextAttributes = new HashMap<>();
}
// `PasswordOAuth2AuthorizedClientProvider` requires both attributes
contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
}
return contextAttributes;
};
}
}
|
3e01e5c6ce121de1f48b98d2e6d4c2f7a85df8fb | 4,710 | java | Java | src/main/java/frc/robot/Vision.java | Gongoliers/Robot2019 | f8cac72bc1d4e75f3ebb5cdd3aa004283e77adbc | [
"BSD-3-Clause",
"MIT"
] | 2 | 2019-01-26T17:05:35.000Z | 2019-01-26T18:09:36.000Z | src/main/java/frc/robot/Vision.java | Gongoliers/Robot2019 | f8cac72bc1d4e75f3ebb5cdd3aa004283e77adbc | [
"BSD-3-Clause",
"MIT"
] | 24 | 2019-02-04T15:41:47.000Z | 2019-03-09T02:47:02.000Z | src/main/java/frc/robot/Vision.java | Gongoliers/Robot2019 | f8cac72bc1d4e75f3ebb5cdd3aa004283e77adbc | [
"BSD-3-Clause",
"MIT"
] | null | null | null | 35.149254 | 186 | 0.711465 | 804 | package frc.robot;
import java.util.ArrayList;
import java.util.List;
import com.kylecorry.frc.vision.camera.CameraSettings;
import com.kylecorry.frc.vision.camera.FOV;
import com.kylecorry.frc.vision.camera.Resolution;
import edu.wpi.cscore.UsbCamera;
import edu.wpi.cscore.VideoSink;
import edu.wpi.first.cameraserver.CameraServer;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import frc.robot.vision.CargoBayDetector;
import frc.robot.vision.TargetFinderFactory;
import frc.robot.vision.VideoCameraVisionTargetDetector;
import frc.robot.vision.VisionTarget;
import frc.robot.vision.VisionTargetDetector;
/**
* The target finding vision system is controlled from within this class.
*/
public class Vision extends Subsystem {
public static enum CameraSide {
HATCH, CARGO
}
// Driver camera
private static final Resolution DRIVER_CAMERA_RESOLUTION = new Resolution(160, 120);
// Target camera
private static final Resolution TARGET_CAMERA_RESOLUTION = new Resolution(160, 120);
private static final FOV TARGET_CAMERA_VIEW_ANGLES = new FOV(61, 34.3);
private static final boolean TARGET_CAMERA_INVERTED = false;
public UsbCamera hatchDriverCamera;
public UsbCamera cargoDriverCamera;
private VideoSink server;
private CameraSettings cameraSettings;
private CargoBayDetector targetDetector;
public VisionTarget lastFoundTarget;
private CameraSide currentCamera;
public Vision() {
// Initialize the driver camera
hatchDriverCamera = CameraServer.getInstance().startAutomaticCapture("Driver camera (hatch)", RobotMap.driverCamera);
hatchDriverCamera.setResolution(DRIVER_CAMERA_RESOLUTION.getWidth(), DRIVER_CAMERA_RESOLUTION.getHeight());
cargoDriverCamera = CameraServer.getInstance().startAutomaticCapture("Driver camera (cargo)", RobotMap.cargoDriverCamera);
cargoDriverCamera.setResolution(DRIVER_CAMERA_RESOLUTION.getWidth(), DRIVER_CAMERA_RESOLUTION.getHeight());
// Initialize the targeting camera
// targetingCamera = CameraServer.getInstance().startAutomaticCapture("Targeting camera", RobotMap.targetingCamera);
// targetingCamera.setResolution(TARGET_CAMERA_RESOLUTION.getWidth(), TARGET_CAMERA_RESOLUTION.getHeight());
// enableTargetMode(targetingCamera);
// cameraSettings = new CameraSettings(TARGET_CAMERA_INVERTED, TARGET_CAMERA_VIEW_ANGLES, TARGET_CAMERA_RESOLUTION);
// VisionTargetDetector visionTargetDetector = new VideoCameraVisionTargetDetector(targetingCamera, cameraSettings, TargetFinderFactory.getCargoShipTargetFinder(cameraSettings));
// targetDetector = new CargoBayDetector(visionTargetDetector);
// Initialize the server
server = CameraServer.getInstance().addSwitchedCamera("Driving camera");
setPrimaryCamera(CameraSide.HATCH);
}
@Override
public void periodic() {
if (lastFoundTarget != null){
SmartDashboard.putNumber("Target Angle", lastFoundTarget.getHorizontalAngle());
SmartDashboard.putNumber("Target Distance", lastFoundTarget.getDistance());
}
}
/**
* Detects the vision targets.
*
* @return The vision targets sorted by percent area (largest to smallest).
*/
public List<VisionTarget> detectTargets() {
return new ArrayList<VisionTarget>();
// return targetDetector.getTargets();
}
/**
* Enable targeting mode on a camera (low exposure).
* @param camera the camera to enable targeting mode on
*/
public void enableTargetMode(UsbCamera camera) {
if (camera == null){
return;
}
camera.setBrightness(0);
camera.setExposureManual(0);
// camera.setWhiteBalanceManual(value); TODO: Test to see if this is necessary or not
}
/**
* Disable targeting mode on a camera (auto exposure).
* @param camera the camera to disable targeting mode on
*/
public void disableTargetMode(UsbCamera camera) {
if (camera == null){
return;
}
camera.setBrightness(50);
camera.setExposureAuto();
camera.setWhiteBalanceAuto();
}
public void setPrimaryCamera(CameraSide cameraSide){
if (cameraSide == CameraSide.HATCH){
currentCamera = cameraSide;
server.setSource(hatchDriverCamera);
} else {
currentCamera = cameraSide;
// server.setSource(cargoDriverCamera);
}
}
@Override
protected void initDefaultCommand() {
// No default command
}
}
|
3e01e5f3a0651a8fa9902e94fbd490cc16b87654 | 4,727 | java | Java | uwins-JndiMQRef/uwins-JndiMQRef-web/src/main/java/lan/capstone/uwins/jndimqref/DestinationTest.java | MikeNeilson/uwins | 33e505d909bc25cd263a9b2bf9aa3b0a31f1007c | [
"Apache-2.0"
] | null | null | null | uwins-JndiMQRef/uwins-JndiMQRef-web/src/main/java/lan/capstone/uwins/jndimqref/DestinationTest.java | MikeNeilson/uwins | 33e505d909bc25cd263a9b2bf9aa3b0a31f1007c | [
"Apache-2.0"
] | null | null | null | uwins-JndiMQRef/uwins-JndiMQRef-web/src/main/java/lan/capstone/uwins/jndimqref/DestinationTest.java | MikeNeilson/uwins | 33e505d909bc25cd263a9b2bf9aa3b0a31f1007c | [
"Apache-2.0"
] | null | null | null | 37.816 | 124 | 0.638671 | 805 | /*
* Copyright 2018 Mike Neilson.
*
* 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 lan.capstone.uwins.jndimqref;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Mike Neilson
*/
@WebServlet(name = "DestinationTest", urlPatterns = {"/DestinationTest"})
public class DestinationTest extends HttpServlet {
@Resource( lookup = "uwinsl:/jms/TEST/QUEUE")
javax.jms.Destination dest;
@Resource( lookup ="uwinsl:/jms/NOTAQUEUE")
javax.jms.Destination dest2;
@Resource( lookup ="uwinsl:/jms/data/rc")
javax.jms.Destination dest3;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
javax.jms.Destination d3 = (javax.jms.Destination)InitialContext.doLookup("uwinsl:/jms/TEST/QUEUE");
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet DestinationTest</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet DestinationTest at " + request.getContextPath() + "</h1>");
out.println("<h1>Destination physical name is " + dest.toString() + "</h1>");
out.println("<h1>Is of Type " + dest.getClass().getName() + "</h1>");
out.println("<h1>Dest2 " + dest2 + "</h1>");
out.println("<h1>" + System.getProperty(Context.URL_PKG_PREFIXES) + "</h1>");
out.println("<h1>" + d3 + "</h1>");
out.println("<h1>" + dest3 + "</h1>");
out.println("</body>");
out.println("</html>");
} catch (NamingException ex) {
Logger.getLogger(DestinationTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
3e01e613e7cefb828448edfbec428b2fc6cd6fba | 1,894 | java | Java | src/main/java/bwapi/Force.java | JavaBWAPI/JBWAPI | e5521b21c35dbd5981da828bde4db0e486cc3f82 | [
"MIT"
] | 12 | 2018-12-31T11:02:07.000Z | 2022-03-20T18:57:36.000Z | src/main/java/bwapi/Force.java | JavaBWAPI/JBWAPI | e5521b21c35dbd5981da828bde4db0e486cc3f82 | [
"MIT"
] | 53 | 2019-01-01T13:38:20.000Z | 2022-03-20T13:49:29.000Z | src/main/java/bwapi/Force.java | JavaBWAPI/JBWAPI | e5521b21c35dbd5981da828bde4db0e486cc3f82 | [
"MIT"
] | 8 | 2019-03-02T04:31:28.000Z | 2021-09-15T05:08:28.000Z | 25.253333 | 96 | 0.605069 | 806 | package bwapi;
import bwapi.ClientData.ForceData;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* The {@link Force} class is used to get information about each force in a match.
* Normally this is considered a team.
* <p>
* It is not called a team because players on the same force do not necessarily need
* to be allied at the beginning of a match.
*/
public final class Force implements Comparable<Force> {
private final Game game;
private final int id;
private final String name;
Force(final ForceData forceData, int id, final Game game) {
this.game = game;
this.id = id;
this.name = forceData.getName();
}
/**
* Retrieves the unique ID that represents this {@link Force}.
*
* @return An integer containing the ID for the {@link Force}.
*/
public int getID() {
return id;
}
/**
* Retrieves the name of the {@link Force}.
*
* @return A String object containing the name of the force.
*/
public String getName() {
return name;
}
/**
* Retrieves the set of players that belong to this {@link Force}.
*
* @return A List<Player> object containing the players that are part of this {@link Force}.
*/
public List<Player> getPlayers() {
return game.getPlayers().stream()
.filter(p -> equals(p.getForce()))
.collect(Collectors.toList());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Force force = (Force) o;
return id == force.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public int compareTo(final Force other) {
return id - other.id;
}
}
|
3e01e62fbd5ea7a2974efb242826ce1bbae8ba35 | 1,918 | java | Java | work-common-web/src/main/java/cn/chenyilei/work/web/config/MvcGlobalConfigure.java | ChenYilei2016/WorkingTraining | 7d864e7f90e9d18b913e7ee5c50d5caa880e2863 | [
"Apache-2.0"
] | null | null | null | work-common-web/src/main/java/cn/chenyilei/work/web/config/MvcGlobalConfigure.java | ChenYilei2016/WorkingTraining | 7d864e7f90e9d18b913e7ee5c50d5caa880e2863 | [
"Apache-2.0"
] | null | null | null | work-common-web/src/main/java/cn/chenyilei/work/web/config/MvcGlobalConfigure.java | ChenYilei2016/WorkingTraining | 7d864e7f90e9d18b913e7ee5c50d5caa880e2863 | [
"Apache-2.0"
] | null | null | null | 36.865385 | 125 | 0.717267 | 807 | package cn.chenyilei.work.web.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 全局编码设置
*
* @author chenyilei
* @email [email protected]
* @date 2019/09/09 16:02
*/
@Configuration
@ConditionalOnProperty(prefix = "aaa",name = "aa",havingValue = "1")
public class MvcGlobalConfigure implements WebMvcConfigurer {
private class CharsetCodeInterceptor extends HandlerInterceptorAdapter{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
return true;
}
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CharsetCodeInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/static/**");
}
// @Override
// public void addCorsMappings(CorsRegistry registry) {
// registry.addMapping("/**")
// .allowedOrigins("*")
// .allowedMethods("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "TRACE")
// .allowCredentials(true);
// ;
// }
}
|
3e01e76a736a45fe39cf131b6246fa16f246f71e | 1,301 | java | Java | src/main/java/com/ruoyi/project/module/memberAward/service/IMemberAwardService.java | bihu0201/card-pro | 36c4b3f783d2d5b639beff09cabb697a700d1487 | [
"MIT"
] | null | null | null | src/main/java/com/ruoyi/project/module/memberAward/service/IMemberAwardService.java | bihu0201/card-pro | 36c4b3f783d2d5b639beff09cabb697a700d1487 | [
"MIT"
] | null | null | null | src/main/java/com/ruoyi/project/module/memberAward/service/IMemberAwardService.java | bihu0201/card-pro | 36c4b3f783d2d5b639beff09cabb697a700d1487 | [
"MIT"
] | null | null | null | 18.323944 | 78 | 0.645657 | 808 | package com.ruoyi.project.module.memberAward.service;
import com.ruoyi.project.module.memberAward.domain.MemberAward;
import com.ruoyi.project.module.userPay.domain.UserPay;
import java.util.List;
/**
* 会员抽奖 服务层
*
* @author snailever
* @date 2018-10-11
*/
public interface IMemberAwardService
{
/**
* 查询会员抽奖信息
*
* @param id 会员抽奖ID
* @return 会员抽奖信息
*/
public MemberAward selectMemberAwardById(Integer id);
/**
* 查询会员抽奖列表
*
* @param memberAward 会员抽奖信息
* @return 会员抽奖集合
*/
public List<MemberAward> selectMemberAwardList(MemberAward memberAward);
/**
* 新增会员抽奖
*
* @param memberAward 会员抽奖信息
* @return 结果
*/
public int insertMemberAward(MemberAward memberAward);
/**
* 新增会员抽奖
*
* @param memberAward 会员抽奖信息
* @return 结果
*/
public int insertMemberAwardAndBiz(MemberAward memberAward, UserPay userPay);
/**
* 修改会员抽奖
*
* @param memberAward 会员抽奖信息
* @return 结果
*/
public int updateMemberAward(MemberAward memberAward);
/**
* 删除会员抽奖信息
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteMemberAwardByIds(String ids);
/**
* 查询中奖条目
* @param num
* @return 结果
*/
public List<MemberAward> fetchMemberAwardGetNum(Integer num);
}
|
3e01e98881395e10ab8e8c2f0ce7329bc2e415fc | 204 | java | Java | libs/reactive-core/src/main/java/no/nav/testnav/libs/reactivecore/filter/LogRequest.java | navikt/testnorge | 8400ad28d37ec5dee87a4fe76e233632d2cfdbd1 | [
"MIT"
] | 3 | 2020-06-30T18:14:44.000Z | 2022-03-07T10:10:48.000Z | libs/reactive-core/src/main/java/no/nav/testnav/libs/reactivecore/filter/LogRequest.java | navikt/testnorge | 8400ad28d37ec5dee87a4fe76e233632d2cfdbd1 | [
"MIT"
] | 1,546 | 2020-05-25T14:39:45.000Z | 2022-03-31T13:41:00.000Z | libs/reactive-core/src/main/java/no/nav/testnav/libs/reactivecore/filter/LogRequest.java | navikt/testnorge | 8400ad28d37ec5dee87a4fe76e233632d2cfdbd1 | [
"MIT"
] | 1 | 2021-11-03T16:02:17.000Z | 2021-11-03T16:02:17.000Z | 25.5 | 66 | 0.813725 | 809 | package no.nav.testnav.libs.reactivecore.filter;
import org.springframework.http.server.reactive.ServerHttpRequest;
public interface LogRequest {
void log(ServerHttpRequest request, String body);
}
|
3e01ebf549563dde8444e278bbcf3d8790823c03 | 4,289 | java | Java | app/src/main/java/baidu/com/testlibproject/ui/TestSpinnerActivity.java | weimuhua/TestLibProject | d5bec31a6baab0d7be410c385f8f3721bad13d7d | [
"Apache-2.0"
] | null | null | null | app/src/main/java/baidu/com/testlibproject/ui/TestSpinnerActivity.java | weimuhua/TestLibProject | d5bec31a6baab0d7be410c385f8f3721bad13d7d | [
"Apache-2.0"
] | null | null | null | app/src/main/java/baidu/com/testlibproject/ui/TestSpinnerActivity.java | weimuhua/TestLibProject | d5bec31a6baab0d7be410c385f8f3721bad13d7d | [
"Apache-2.0"
] | null | null | null | 32.740458 | 115 | 0.659594 | 810 | package baidu.com.testlibproject.ui;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Spinner;
import java.util.ArrayList;
import java.util.List;
import baidu.com.commontools.threadpool.MhThreadPool;
import baidu.com.commontools.utils.MobileInfo;
import baidu.com.testlibproject.R;
public class TestSpinnerActivity extends Activity implements Handler.Callback, AdapterView.OnItemSelectedListener {
private static final int MSG_LOAD_GALLERY_DRAWABLE_DONE = 1;
private Handler mHandler;
private Context mContext;
/* Android已经将Gallery废弃掉了,推荐使用HorizontalScrollVIew和ViewPager代替*/
private Gallery mGallery;
private ImageView mImageView;
private GalleryAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner_layout);
mContext = this;
mHandler = new Handler(this);
initView();
initData();
}
private void initView() {
Spinner spinner = findViewById(R.id.spinner);
String[] strArr = new String[]{
"Baidu", "AliBaBa", "Tencent", "JingDong"
};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.main_activity_item, strArr);
spinner.setAdapter(adapter);
mGallery = findViewById(R.id.gallery);
mImageView = findViewById(R.id.gallery_select_img);
}
private void initData() {
MhThreadPool.getInstance().addUiTask(new Runnable() {
@Override
public void run() {
PackageManager pm = mContext.getPackageManager();
List<PackageInfo> infoList = pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);
List<Drawable> drawableList = new ArrayList<>();
for (PackageInfo info : infoList) {
if ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
drawableList.add(info.applicationInfo.loadIcon(pm));
}
}
mAdapter = new GalleryAdapter(drawableList);
mHandler.sendEmptyMessage(MSG_LOAD_GALLERY_DRAWABLE_DONE);
}
});
}
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MSG_LOAD_GALLERY_DRAWABLE_DONE:
mGallery.setAdapter(mAdapter);
mGallery.setOnItemSelectedListener(this);
break;
}
return false;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mImageView.setImageDrawable(mAdapter.getItem(position));
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
private class GalleryAdapter extends BaseAdapter {
private List<Drawable> mDrawableList;
public GalleryAdapter(List<Drawable> drawableList) {
mDrawableList = drawableList;
}
@Override
public int getCount() {
return mDrawableList.size();
}
@Override
public Drawable getItem(int position) {
return mDrawableList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageDrawable(mDrawableList.get(position));
imageView.setLayoutParams(new Gallery.LayoutParams((int) MobileInfo.dp2px(mContext, 60),
(int) MobileInfo.dp2px(mContext, 60)));
return imageView;
}
}
} |
3e01ecc40c6390805000026bf5084cbc18099454 | 6,466 | java | Java | worldedit-core/src/main/java/com/fastasyncworldedit/core/queue/implementation/blocks/BitSetBlocks.java | IntellectualSites/FastAsyncWorldEdit | 59d4247ddb108521ee62a6a4a90673293905f7f1 | [
"BSD-3-Clause"
] | 370 | 2020-02-01T20:46:14.000Z | 2022-03-29T09:44:11.000Z | worldedit-core/src/main/java/com/fastasyncworldedit/core/queue/implementation/blocks/BitSetBlocks.java | IntellectualSites/FastAsyncWorldEdit | 59d4247ddb108521ee62a6a4a90673293905f7f1 | [
"BSD-3-Clause"
] | 1,133 | 2020-01-31T17:19:52.000Z | 2022-03-31T19:52:17.000Z | worldedit-core/src/main/java/com/fastasyncworldedit/core/queue/implementation/blocks/BitSetBlocks.java | IntellectualSites/FastAsyncWorldEdit | 59d4247ddb108521ee62a6a4a90673293905f7f1 | [
"BSD-3-Clause"
] | 204 | 2020-02-02T21:12:05.000Z | 2022-03-19T15:45:24.000Z | 26.829876 | 96 | 0.590628 | 811 | package com.fastasyncworldedit.core.queue.implementation.blocks;
import com.fastasyncworldedit.core.FaweCache;
import com.fastasyncworldedit.core.extent.processor.heightmap.HeightMapType;
import com.fastasyncworldedit.core.queue.IChunkSet;
import com.fastasyncworldedit.core.util.collection.MemBlockSet;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockTypesCache;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
public class BitSetBlocks implements IChunkSet {
private final MemBlockSet.RowZ row;
private final BlockState blockState;
private final int minSectionPosition;
private final int maxSectionPosition;
private final int layers;
public BitSetBlocks(BlockState blockState, int minSectionPosition, int maxSectionPosition) {
this.row = new MemBlockSet.RowZ(minSectionPosition, maxSectionPosition);
this.blockState = blockState;
this.minSectionPosition = minSectionPosition;
this.maxSectionPosition = maxSectionPosition;
this.layers = maxSectionPosition - minSectionPosition + 1;
}
@Override
public boolean hasSection(int layer) {
layer -= minSectionPosition;
return row.rows[layer] != MemBlockSet.NULL_ROW_Y;
}
@Override
public boolean setBiome(int x, int y, int z, BiomeType biome) {
return false;
}
@Override
public <T extends BlockStateHolder<T>> boolean setBlock(int x, int y, int z, T holder) {
y -= minSectionPosition << 4;
row.set(null, x, y, z, minSectionPosition, maxSectionPosition);
return true;
}
@Override
public void setBlocks(int layer, char[] data) {
layer -= minSectionPosition;
row.reset(layer);
int by = layer << 4;
for (int y = 0, index = 0; y < 16; y++) {
for (int z = 0; z < 16; z++) {
for (int x = 0; x < 16; x++, index++) {
if (data[index] != BlockTypesCache.ReservedIDs.__RESERVED__) {
row.set(null, x, by + y, z, minSectionPosition, maxSectionPosition);
}
}
}
}
}
@Override
public boolean isEmpty() {
return row.isEmpty();
}
@Override
public boolean setTile(int x, int y, int z, CompoundTag tile) {
return false;
}
@Override
public void setBlockLight(int x, int y, int z, int value) {
}
@Override
public void setSkyLight(int x, int y, int z, int value) {
}
@Override
public void setHeightMap(HeightMapType type, int[] heightMap) {
}
@Override
public void setLightLayer(int layer, char[] toSet) {
}
@Override
public void setSkyLightLayer(int layer, char[] toSet) {
}
@Override
public void removeSectionLighting(int layer, boolean sky) {
}
@Override
public void setFullBright(int layer) {
}
@Override
public void setEntity(CompoundTag tag) {
}
@Override
public void removeEntity(UUID uuid) {
}
@Override
public BlockState getBlock(int x, int y, int z) {
if (row.get(null, x, y, z)) {
return blockState;
}
return null;
}
@Override
public char[] load(int layer) {
layer -= minSectionPosition;
char[] arr = FaweCache.INSTANCE.SECTION_BITS_TO_CHAR.get();
MemBlockSet.IRow nullRowY = row.getRow(layer);
if (nullRowY instanceof MemBlockSet.RowY) {
char value = blockState.getOrdinalChar();
MemBlockSet.RowY rowY = (MemBlockSet.RowY) nullRowY;
long[] bits = rowY.getBits();
for (int y = 0, longIndex = 0, blockIndex = 0; y < 16; y++) {
for (int z = 0; z < 16; z += 4, longIndex++, blockIndex += 64) {
long bitBuffer = bits[longIndex];
if (bitBuffer != 0) {
if (bitBuffer == -1L) {
Arrays.fill(arr, blockIndex, blockIndex + 64, value);
continue;
}
Arrays.fill(arr, Character.MIN_VALUE);
do {
final long lowBit = Long.lowestOneBit(bitBuffer);
final int bitIndex = Long.bitCount(lowBit - 1);
arr[blockIndex + bitIndex] = value;
bitBuffer = bitBuffer ^ lowBit;
} while (bitBuffer != 0);
}
}
}
}
return arr;
}
// No need to do anything different
@Nullable
@Override
public char[] loadIfPresent(final int layer) {
return load(layer);
}
@Override
public BiomeType[][] getBiomes() {
return null;
}
@Override
public char[][] getLight() {
return new char[0][];
}
@Override
public char[][] getSkyLight() {
return new char[0][];
}
@Override
public BiomeType getBiomeType(int x, int y, int z) {
return null;
}
@Override
public Map<BlockVector3, CompoundTag> getTiles() {
return Collections.emptyMap();
}
@Override
public CompoundTag getTile(int x, int y, int z) {
return null;
}
@Override
public Set<CompoundTag> getEntities() {
return Collections.emptySet();
}
@Override
public Set<UUID> getEntityRemoves() {
return null;
}
@Override
public IChunkSet reset() {
row.reset();
return this;
}
@Override
public boolean hasBiomes(final int layer) {
return false;
}
@Override
public int getSectionCount() {
return layers;
}
@Override
public int getMaxSectionPosition() {
return minSectionPosition;
}
@Override
public int getMinSectionPosition() {
return maxSectionPosition;
}
@Override
public boolean trim(boolean aggressive) {
return false;
}
@Override
public boolean trim(boolean aggressive, int layer) {
return false;
}
}
|
3e01ed75378fc64cafae43b9bc63997453e2e2ae | 1,905 | java | Java | hard/java/c0055_297_serialize-and-deserialize-binary-tree/00_leetcode_0055.java | drunkwater/leetcode | 8cc4a07763e71efbaedb523015f0c1eff2927f60 | [
"Ruby"
] | null | null | null | hard/java/c0055_297_serialize-and-deserialize-binary-tree/00_leetcode_0055.java | drunkwater/leetcode | 8cc4a07763e71efbaedb523015f0c1eff2927f60 | [
"Ruby"
] | null | null | null | hard/java/c0055_297_serialize-and-deserialize-binary-tree/00_leetcode_0055.java | drunkwater/leetcode | 8cc4a07763e71efbaedb523015f0c1eff2927f60 | [
"Ruby"
] | 3 | 2018-02-09T02:46:48.000Z | 2021-02-20T08:32:03.000Z | 47.625 | 295 | 0.719685 | 812 | // DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//297. Serialize and Deserialize Binary Tree
//Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
//Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
//For example, you may serialize the following tree
// 1
// / \
// 2 3
// / \
// 4 5
//as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
// Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
//Credits:
//Special thanks to @Louis1992 for adding this problem and creating all test cases.
///**
// * Definition for a binary tree node.
// * public class TreeNode {
// * int val;
// * TreeNode left;
// * TreeNode right;
// * TreeNode(int x) { val = x; }
// * }
// */
//public class Codec {
// // Encodes a tree to a single string.
// public String serialize(TreeNode root) {
// }
// // Decodes your encoded data to tree.
// public TreeNode deserialize(String data) {
// }
//}
//// Your Codec object will be instantiated and called as such:
//// Codec codec = new Codec();
//// codec.deserialize(codec.serialize(root));
// Time Is Money |
3e01eda611aa7dd85173c464f217aeab5616bf23 | 253 | java | Java | valuegen/src/test/java/scenariotests/samplepojos/simplepojos/IntObject.java | opennano/reflection-assert | 7e1266a5d28a5b2b8750824667b504ae0a1cff68 | [
"Unlicense"
] | 2 | 2020-04-29T01:56:44.000Z | 2020-04-29T19:18:56.000Z | valuegen/src/test/java/scenariotests/samplepojos/simplepojos/IntObject.java | opennano/value-object | 7e1266a5d28a5b2b8750824667b504ae0a1cff68 | [
"Unlicense"
] | 1 | 2019-10-12T20:13:03.000Z | 2019-10-12T20:13:03.000Z | valuegen/src/test/java/scenariotests/samplepojos/simplepojos/IntObject.java | opennano/value-object | 7e1266a5d28a5b2b8750824667b504ae0a1cff68 | [
"Unlicense"
] | null | null | null | 16.866667 | 47 | 0.73913 | 813 | package scenariotests.samplepojos.simplepojos;
public class IntObject {
private int testedField;
public int getTestedField() {
return testedField;
}
public void setTestedField(int testedField) {
this.testedField = testedField;
}
}
|
3e01ee24a1b34c9947ef6d5175468883e123a904 | 1,758 | java | Java | src/main/java/com/hotproperties/web/config/ApiConfig.java | jesus-dayo/hotproperties-services-ph | d5afe9a158795e68c5265d60937d6d6637f4d874 | [
"MIT"
] | null | null | null | src/main/java/com/hotproperties/web/config/ApiConfig.java | jesus-dayo/hotproperties-services-ph | d5afe9a158795e68c5265d60937d6d6637f4d874 | [
"MIT"
] | null | null | null | src/main/java/com/hotproperties/web/config/ApiConfig.java | jesus-dayo/hotproperties-services-ph | d5afe9a158795e68c5265d60937d6d6637f4d874 | [
"MIT"
] | null | null | null | 31.392857 | 93 | 0.812287 | 814 | package com.hotproperties.web.config;
import java.util.Collections;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.servlet.ModelAndView;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
@Configuration
public class ApiConfig {
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
@Bean
public ObjectWriter objectWriter(ObjectMapper objectMapper) {
return objectMapper().writerWithDefaultPrettyPrinter();
}
@Bean
public ErrorViewResolver supportPathBasedLocationStrategyWithoutHashes() {
return new ErrorViewResolver() {
@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status,
Map<String, Object> model) {
return status == HttpStatus.NOT_FOUND
? new ModelAndView("index.html", Collections.<String, Object>emptyMap(), HttpStatus.OK)
: null;
}
};
}
}
|
3e01ee4b4aee17b26def3bf3ebe33949e150731b | 1,468 | java | Java | enterprise/web.jsf/src/org/netbeans/modules/web/jsf/api/facesmodel/Redirect.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 1,056 | 2019-04-25T20:00:35.000Z | 2022-03-30T04:46:14.000Z | enterprise/web.jsf/src/org/netbeans/modules/web/jsf/api/facesmodel/Redirect.java | Marc382/netbeans | 4bee741d24a3fdb05baf135de5e11a7cd95bd64e | [
"Apache-2.0"
] | 1,846 | 2019-04-25T20:50:05.000Z | 2022-03-31T23:40:41.000Z | enterprise/web.jsf/src/org/netbeans/modules/web/jsf/api/facesmodel/Redirect.java | Marc382/netbeans | 4bee741d24a3fdb05baf135de5e11a7cd95bd64e | [
"Apache-2.0"
] | 550 | 2019-04-25T20:04:33.000Z | 2022-03-25T17:43:01.000Z | 34.139535 | 84 | 0.749319 | 815 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.web.jsf.api.facesmodel;
import java.util.List;
import org.netbeans.modules.web.jsf.impl.facesmodel.JSFConfigQNames;
/**
* @author ads
*
*/
public interface Redirect extends IdentifiableElement {
String INCLUDE_VIEW_PARAMS = JSFConfigQNames.INCLUDE_VIEW_PARAMS.getLocalName();
String VIEW_PARAM = JSFConfigQNames.VIEW_PARAM.getLocalName();
Boolean getIncludeViewParams();
void setIncludeViewParams( Boolean value );
List<ViewParam> getViewParams();
void addViewParam( ViewParam param );
void addViewParam( int index , ViewParam param );
void removeViewParam( ViewParam param );
}
|
3e01ee6b2bc4fef0cc18349a6648c0f33ac0bdf1 | 11,156 | java | Java | MatisseLib/src/org/specs/matisselib/typeinference/rules/MatrixSetInstructionRule.java | specs-feup/matisse | 8e0838e3f42cac0a5f5be8979a3444231b9ba944 | [
"Apache-2.0"
] | null | null | null | MatisseLib/src/org/specs/matisselib/typeinference/rules/MatrixSetInstructionRule.java | specs-feup/matisse | 8e0838e3f42cac0a5f5be8979a3444231b9ba944 | [
"Apache-2.0"
] | null | null | null | MatisseLib/src/org/specs/matisselib/typeinference/rules/MatrixSetInstructionRule.java | specs-feup/matisse | 8e0838e3f42cac0a5f5be8979a3444231b9ba944 | [
"Apache-2.0"
] | null | null | null | 42.580153 | 118 | 0.634457 | 816 | /**
* Copyright 2015 SPeCS.
*
* 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. under the License.
*/
package org.specs.matisselib.typeinference.rules;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.specs.CIR.Types.TypeShape;
import org.specs.CIR.Types.VariableType;
import org.specs.CIR.Types.ATypes.Matrix.MatrixType;
import org.specs.CIR.Types.ATypes.Matrix.MatrixUtils;
import org.specs.CIR.Types.ATypes.Scalar.ScalarType;
import org.specs.CIR.Types.ATypes.Scalar.ScalarUtils;
import org.specs.CIRTypes.Types.DynamicMatrix.DynamicMatrixType;
import org.specs.CIRTypes.Types.StaticMatrix.StaticMatrixType;
import org.specs.CIRTypes.Types.StaticMatrix.StaticMatrixTypeBuilder;
import org.specs.matisselib.PassMessage;
import org.specs.matisselib.functionproperties.AssumeMatrixIndicesInRangeProperty;
import org.specs.matisselib.helpers.ConstantUtils;
import org.specs.matisselib.ssa.InstructionLocation;
import org.specs.matisselib.ssa.instructions.MatrixSetInstruction;
import org.specs.matisselib.ssa.instructions.SsaInstruction;
import org.specs.matisselib.typeinference.TypeInferenceContext;
import org.specs.matisselib.typeinference.TypeInferencePass;
import org.specs.matisselib.typeinference.TypeInferenceRule;
import pt.up.fe.specs.util.exceptions.NotImplementedException;
public class MatrixSetInstructionRule implements TypeInferenceRule {
@Override
public boolean accepts(SsaInstruction instruction) {
return instruction instanceof MatrixSetInstruction;
}
@Override
public void inferTypes(TypeInferenceContext context,
InstructionLocation location,
SsaInstruction instruction) {
// Here's what can happen
// 1. The normal case (Matrix replace scalar value at position)
// 2. Multiple replacements (e.g. A(1:3) = [1 2 3])
// 3. Insertion (e.g. A = 1; A(2) = 1;)
// In insertion, the right side must be a scalar or a matrix with equal shape to the output.
// As such, A(1:3) = [1 2]; is not valid.
// Elimination (such as A(4) = []) is an entirely separate operation.
MatrixSetInstruction set = (MatrixSetInstruction) instruction;
String matrix = set.getInputMatrix();
List<String> indices = set.getIndices();
String value = set.getValue();
String output = set.getOutput();
Optional<VariableType> candidateMatrixType = context.getVariableType(matrix);
Optional<VariableType> matrixOverrideType = context.getDefaultVariableType(output);
if (!candidateMatrixType.isPresent()) {
handleUndefinedSet(context, set, matrixOverrideType);
return;
}
VariableType matrixType = candidateMatrixType.get();
List<VariableType> indicesTypes = indices.stream()
.map(index -> context.getVariableType(index).get())
.collect(Collectors.toList());
VariableType valueType = context.getVariableType(value).get();
if (!(matrixType instanceof MatrixType)) {
// FIXME: It is perfectly valid to convert a scalar to a matrix using a set.
throw new NotImplementedException("Converting scalar to matrix by setting a value");
}
if (indicesTypes.stream().anyMatch(type -> !(type instanceof ScalarType))) {
handleRangeSet(context, set, matrixOverrideType);
return;
}
if (!(valueType instanceof ScalarType)) {
// We are in the presence of A(scalars) = matrix;
//
// Not a scalar set.
// These sets never change the size of the output matrix.
context.addVariable(output, matrixType);
return;
}
// Now, we can assume we have a scalar set.
// We can have an insertion or a replacement.
ScalarType underlyingType = MatrixUtils.getElementType(matrixType);
TypeShape matrixShape = MatrixUtils.getShape(matrixType);
if ((indices.size() == 1
&& !matrixShape.isKnownEmpty()
&& matrixShape.isFullyDefined()
&& matrixShape.getNumDims() <= 2
&& (matrixShape.getDim(0) == 1 || matrixShape.getDim(1) == 1)
&& ScalarUtils.isInteger(indicesTypes.get(0))
&& ScalarUtils.hasConstant(indicesTypes.get(0))
&& ScalarUtils.getConstant(indicesTypes.get(0)).intValue() <= matrixShape.getNumElements()) ||
context.getPropertyStream(AssumeMatrixIndicesInRangeProperty.class).findAny().isPresent()) {
// In range
context.addVariable(output, matrixType, matrixOverrideType);
} else {
// Potentially out-of-range
int lastRelevantIndex = getLastRelevantIndex(context, indices);
// TODO: We can do better in determining the shape
TypeShape newShape = TypeShape.newUndefinedShape();
if (lastRelevantIndex == 0) {
// Preserves num dims
if (matrixShape.getRawNumDims() == 2 && matrixShape.getDim(0) == 1) {
newShape = TypeShape.newRow();
} else if (matrixShape.isKnown1D()) {
newShape = TypeShape.new1D();
} else if (matrixShape.getNumDims() >= 0) {
newShape = TypeShape.newDimsShape(matrixShape.getRawNumDims());
}
} else if (lastRelevantIndex < matrixShape.getRawNumDims()) {
// Maybe out of range, but preserves num dims
int numDims = -1;
if (matrixShape.getRawNumDims() >= 0) {
numDims = matrixShape.getRawNumDims();
}
newShape = TypeShape.newDimsShape(numDims);
} else if (matrixShape.getRawNumDims() > 0) {
// Matrix may grow to the number of dimensions specified by the indices.
newShape = TypeShape.newDimsShape(lastRelevantIndex + 1);
}
DynamicMatrixType newType = DynamicMatrixType.newInstance(underlyingType, newShape);
context.addVariable(output, newType, matrixOverrideType);
}
}
private static void handleUndefinedSet(TypeInferenceContext context,
MatrixSetInstruction set,
Optional<VariableType> matrixOverrideType) {
List<String> indices = set.getIndices();
String value = set.getValue();
VariableType valueType = context.getVariableType(value).get();
if (!ScalarUtils.isScalar(valueType)) {
throw new NotImplementedException("Non-scalar matrix set of undefined matrix");
}
DynamicMatrixType suggestedType;
if (indices.size() != 1) {
TypeShape shape = indices.size() > 1 ? TypeShape.newDimsShape(indices.size())
: TypeShape.newUndefinedShape();
suggestedType = DynamicMatrixType.newInstance(ScalarUtils.removeConstant(valueType),
shape);
} else {
String index = indices.get(0);
VariableType indexType = context.getVariableType(index).get();
int numRows;
if (ScalarUtils.isScalar(indexType) && ScalarUtils.isInteger(indexType)
&& ScalarUtils.hasConstant(indexType)) {
numRows = ScalarUtils.getConstant(indexType).intValue();
if (numRows <= 0) {
context.getPassData()
.get(TypeInferencePass.INSTRUCTION_REPORT_SERVICE)
.emitMessage(context.getInstance(), set, PassMessage.CORRECTNESS_ERROR,
"Accessing non-positive index.");
numRows = -1;
}
} else {
numRows = -1;
}
suggestedType = DynamicMatrixType.newInstance(
ScalarUtils.setConstant(valueType, null),
Arrays.asList(1, numRows));
}
context.addVariable(set.getOutput(), suggestedType, matrixOverrideType);
}
private static void handleRangeSet(TypeInferenceContext context,
MatrixSetInstruction set,
Optional<VariableType> matrixOverrideType) {
String output = set.getOutput();
// In order to determine whether a matrix set resizes a matrix, we need only look
// at the left side of the assignment.
String inputMatrix = set.getInputMatrix();
MatrixType inputType = (MatrixType) context.getVariableType(inputMatrix).get();
ScalarType elementType = inputType.matrix().getElementType();
TypeShape inputShape = inputType.getTypeShape();
List<String> indices = set.getIndices();
if (indices.size() == 1) {
String index = indices.get(0);
VariableType indexType = context.getVariableType(index).get();
if (inputType instanceof StaticMatrixType && indexType instanceof StaticMatrixType) {
Number upperBound = ((StaticMatrixType) indexType).getUpperBound();
if (inputShape.isFullyDefined() && upperBound != null
&& upperBound.intValue() <= inputShape.getNumElements()) {
// Not resized
MatrixType outputType = StaticMatrixTypeBuilder
.fromElementTypeAndShape(elementType, inputShape)
.build();
context.addVariable(output, outputType, matrixOverrideType);
return;
}
}
}
int lastRelevantIndex = getLastRelevantIndex(context, indices);
TypeShape newShape = TypeShape.newUndefinedShape();
int sourceDims = inputShape.getRawNumDims();
if (sourceDims > 0) {
int rawNumDims = Math.max(sourceDims, lastRelevantIndex + 1);
newShape = TypeShape.newDimsShape(rawNumDims);
}
DynamicMatrixType matrixType = DynamicMatrixType.newInstance(elementType, newShape);
context.addVariable(output,
matrixType,
matrixOverrideType);
}
private static int getLastRelevantIndex(TypeInferenceContext context, List<String> indices) {
int lastRelevantIndex = indices.size() - 1;
while (lastRelevantIndex > 0 &&
ConstantUtils.isConstantOne(context.getVariableType(indices.get(lastRelevantIndex)).get())) {
--lastRelevantIndex;
}
return lastRelevantIndex;
}
}
|
3e01ee8633c002a691d3d80d8d8052cc591b9b6d | 4,351 | java | Java | polardbx-cdc-canal/src/main/java/com/aliyun/polardbx/binlog/canal/binlog/dbms/DBMSColumn.java | ApsaraDB/galaxycdc | f1fe96be6ffb50e002687d15fa18ef7ac09a31e6 | [
"Apache-2.0"
] | 25 | 2021-10-16T06:02:22.000Z | 2022-02-17T10:55:08.000Z | polardbx-cdc-canal/src/main/java/com/aliyun/polardbx/binlog/canal/binlog/dbms/DBMSColumn.java | ApsaraDB/galaxycdc | f1fe96be6ffb50e002687d15fa18ef7ac09a31e6 | [
"Apache-2.0"
] | 1 | 2022-01-13T07:32:22.000Z | 2022-01-13T07:32:22.000Z | polardbx-cdc-canal/src/main/java/com/aliyun/polardbx/binlog/canal/binlog/dbms/DBMSColumn.java | ApsaraDB/galaxycdc | f1fe96be6ffb50e002687d15fa18ef7ac09a31e6 | [
"Apache-2.0"
] | 14 | 2021-10-18T02:45:50.000Z | 2022-03-25T03:02:46.000Z | 25.745562 | 79 | 0.578947 | 817 | /*
*
* Copyright (c) 2013-2021, Alibaba Group Holding Limited;
* 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.aliyun.polardbx.binlog.canal.binlog.dbms;
import java.io.Serializable;
/**
* This class defines a SQL column information. <br />
*
* @author Changyuan.lh
* @version 1.0
*/
public abstract class DBMSColumn implements Serializable {
private static final long serialVersionUID = 3756103775996253511L;
protected transient int columnIndex;
/**
* Return the column name.
*/
public abstract String getName();
/**
* Return the current column index.
*/
public int getColumnIndex() {
return columnIndex;
}
/**
* Change the current column index.
*/
public void setColumnIndex(int columnIndex) {
this.columnIndex = columnIndex;
}
/**
* Return the ordinal column index.
*/
public abstract int getOrdinalIndex();
/**
* Return the column SQL type. See {@link java.sql.Types} for type details.
*
* @see java.sql.Types
*/
public abstract int getSqlType();
/**
* Return true if the column is singned.
*/
public abstract boolean isSigned();
/**
* Return true if the column is <code>NULL</code> column.
*/
public abstract boolean isNullable();
/**
* Return true if the column is a part of primary key.
*/
public abstract boolean isPrimaryKey();
/**
* Return true if the column is a part of unique key.
*/
public abstract boolean isUniqueKey();
/**
* {@inheritDoc}
*
* @see Object#equals(Object)
*/
@Override
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (other instanceof DBMSColumn) {
return this.equals((DBMSColumn) other);
}
return false;
}
/**
* {@inheritDoc}
*
* @see Object#hashCode()
*/
@Override
public int hashCode() {
return getName().hashCode() ^ getOrdinalIndex();
}
/**
* Return true if the column is equals other.
*/
public boolean equals(DBMSColumn other) {
if (other == null) {
return false;
}
if (!this.getName().equals(other.getName())) {
return false;
}
if (this.getOrdinalIndex() != other.getOrdinalIndex()) {
return false;
}
if (this.getSqlType() != other.getSqlType()) {
return false;
}
if (this.isSigned() != other.isSigned()) {
return false;
}
if (this.isNullable() != other.isNullable()) {
return false;
}
if (this.isPrimaryKey() != other.isPrimaryKey()) {
return false;
}
if (this.isUniqueKey() != other.isUniqueKey()) {
return false;
}
return true;
}
/**
* {@inheritDoc}
*
* @see Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder( // NL
getClass().getName());
builder.append('(');
builder.append("name: ");
builder.append(this.getName());
builder.append(", ordinalIndex: ");
builder.append(this.getOrdinalIndex());
builder.append(", sqlType: ");
builder.append(this.getSqlType());
builder.append(",\n signed: ");
builder.append(this.isSigned());
builder.append(", nullable: ");
builder.append(this.isNullable());
builder.append(", primaryKey: ");
builder.append(this.isPrimaryKey());
builder.append(", uniqueKey: ");
builder.append(this.isUniqueKey());
builder.append(')');
return builder.toString();
}
}
|
3e01eef3c5c3c36dc45162bccdd0693da7748d6c | 743 | java | Java | commons/src/main/java/ru/jts/common/GlobalConstans.java | ChaosPaladin/jts | 42d81605505f6db0aa62a6d839e747263e18244c | [
"Apache-2.0"
] | null | null | null | commons/src/main/java/ru/jts/common/GlobalConstans.java | ChaosPaladin/jts | 42d81605505f6db0aa62a6d839e747263e18244c | [
"Apache-2.0"
] | null | null | null | commons/src/main/java/ru/jts/common/GlobalConstans.java | ChaosPaladin/jts | 42d81605505f6db0aa62a6d839e747263e18244c | [
"Apache-2.0"
] | 1 | 2020-01-08T01:10:58.000Z | 2020-01-08T01:10:58.000Z | 28.576923 | 75 | 0.722746 | 818 | /*
* Copyright 2012 jts
*
* 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 ru.jts.common;
/**
* @author : Camelion
* @date : 13.08.12 21:40
*/
public class GlobalConstans {
public static final boolean DEBUG = false;
}
|
3e01efb5a22e3713f0af75ececbabf7da191a799 | 88,963 | java | Java | src/main/java/eshop/api/product/Products.java | tshy0931/eshop-api | ff78acdc78a12048b10d444cd43fe4e0b9597c0f | [
"Apache-2.0"
] | null | null | null | src/main/java/eshop/api/product/Products.java | tshy0931/eshop-api | ff78acdc78a12048b10d444cd43fe4e0b9597c0f | [
"Apache-2.0"
] | null | null | null | src/main/java/eshop/api/product/Products.java | tshy0931/eshop-api | ff78acdc78a12048b10d444cd43fe4e0b9597c0f | [
"Apache-2.0"
] | null | null | null | 32.36195 | 173 | 0.598755 | 819 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Products.proto
package eshop.api.product;
public final class Products {
private Products() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
public interface ProductOrBuilder extends
// @@protoc_insertion_point(interface_extends:eshop.api.product.Product)
com.google.protobuf.MessageOrBuilder {
/**
* <code>string id = 1;</code>
*/
java.lang.String getId();
/**
* <code>string id = 1;</code>
*/
com.google.protobuf.ByteString
getIdBytes();
/**
* <code>string vendorId = 2;</code>
*/
java.lang.String getVendorId();
/**
* <code>string vendorId = 2;</code>
*/
com.google.protobuf.ByteString
getVendorIdBytes();
/**
* <code>string name = 3;</code>
*/
java.lang.String getName();
/**
* <code>string name = 3;</code>
*/
com.google.protobuf.ByteString
getNameBytes();
/**
* <code>string desc = 4;</code>
*/
java.lang.String getDesc();
/**
* <code>string desc = 4;</code>
*/
com.google.protobuf.ByteString
getDescBytes();
/**
* <code>repeated string tags = 5;</code>
*/
java.util.List<java.lang.String>
getTagsList();
/**
* <code>repeated string tags = 5;</code>
*/
int getTagsCount();
/**
* <code>repeated string tags = 5;</code>
*/
java.lang.String getTags(int index);
/**
* <code>repeated string tags = 5;</code>
*/
com.google.protobuf.ByteString
getTagsBytes(int index);
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
java.util.List<eshop.api.product.Products.ProductSubType>
getSubTypesList();
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
eshop.api.product.Products.ProductSubType getSubTypes(int index);
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
int getSubTypesCount();
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
java.util.List<? extends eshop.api.product.Products.ProductSubTypeOrBuilder>
getSubTypesOrBuilderList();
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
eshop.api.product.Products.ProductSubTypeOrBuilder getSubTypesOrBuilder(
int index);
}
/**
* Protobuf type {@code eshop.api.product.Product}
*/
public static final class Product extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:eshop.api.product.Product)
ProductOrBuilder {
private static final long serialVersionUID = 0L;
// Use Product.newBuilder() to construct.
private Product(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private Product() {
id_ = "";
vendorId_ = "";
name_ = "";
desc_ = "";
tags_ = com.google.protobuf.LazyStringArrayList.EMPTY;
subTypes_ = java.util.Collections.emptyList();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private Product(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
java.lang.String s = input.readStringRequireUtf8();
id_ = s;
break;
}
case 18: {
java.lang.String s = input.readStringRequireUtf8();
vendorId_ = s;
break;
}
case 26: {
java.lang.String s = input.readStringRequireUtf8();
name_ = s;
break;
}
case 34: {
java.lang.String s = input.readStringRequireUtf8();
desc_ = s;
break;
}
case 42: {
java.lang.String s = input.readStringRequireUtf8();
if (!((mutable_bitField0_ & 0x00000010) == 0x00000010)) {
tags_ = new com.google.protobuf.LazyStringArrayList();
mutable_bitField0_ |= 0x00000010;
}
tags_.add(s);
break;
}
case 50: {
if (!((mutable_bitField0_ & 0x00000020) == 0x00000020)) {
subTypes_ = new java.util.ArrayList<eshop.api.product.Products.ProductSubType>();
mutable_bitField0_ |= 0x00000020;
}
subTypes_.add(
input.readMessage(eshop.api.product.Products.ProductSubType.parser(), extensionRegistry));
break;
}
default: {
if (!parseUnknownFieldProto3(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000010) == 0x00000010)) {
tags_ = tags_.getUnmodifiableView();
}
if (((mutable_bitField0_ & 0x00000020) == 0x00000020)) {
subTypes_ = java.util.Collections.unmodifiableList(subTypes_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return eshop.api.product.Products.internal_static_eshop_api_product_Product_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return eshop.api.product.Products.internal_static_eshop_api_product_Product_fieldAccessorTable
.ensureFieldAccessorsInitialized(
eshop.api.product.Products.Product.class, eshop.api.product.Products.Product.Builder.class);
}
private int bitField0_;
public static final int ID_FIELD_NUMBER = 1;
private volatile java.lang.Object id_;
/**
* <code>string id = 1;</code>
*/
public java.lang.String getId() {
java.lang.Object ref = id_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
id_ = s;
return s;
}
}
/**
* <code>string id = 1;</code>
*/
public com.google.protobuf.ByteString
getIdBytes() {
java.lang.Object ref = id_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int VENDORID_FIELD_NUMBER = 2;
private volatile java.lang.Object vendorId_;
/**
* <code>string vendorId = 2;</code>
*/
public java.lang.String getVendorId() {
java.lang.Object ref = vendorId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
vendorId_ = s;
return s;
}
}
/**
* <code>string vendorId = 2;</code>
*/
public com.google.protobuf.ByteString
getVendorIdBytes() {
java.lang.Object ref = vendorId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
vendorId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int NAME_FIELD_NUMBER = 3;
private volatile java.lang.Object name_;
/**
* <code>string name = 3;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
* <code>string name = 3;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int DESC_FIELD_NUMBER = 4;
private volatile java.lang.Object desc_;
/**
* <code>string desc = 4;</code>
*/
public java.lang.String getDesc() {
java.lang.Object ref = desc_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
desc_ = s;
return s;
}
}
/**
* <code>string desc = 4;</code>
*/
public com.google.protobuf.ByteString
getDescBytes() {
java.lang.Object ref = desc_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
desc_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int TAGS_FIELD_NUMBER = 5;
private com.google.protobuf.LazyStringList tags_;
/**
* <code>repeated string tags = 5;</code>
*/
public com.google.protobuf.ProtocolStringList
getTagsList() {
return tags_;
}
/**
* <code>repeated string tags = 5;</code>
*/
public int getTagsCount() {
return tags_.size();
}
/**
* <code>repeated string tags = 5;</code>
*/
public java.lang.String getTags(int index) {
return tags_.get(index);
}
/**
* <code>repeated string tags = 5;</code>
*/
public com.google.protobuf.ByteString
getTagsBytes(int index) {
return tags_.getByteString(index);
}
public static final int SUBTYPES_FIELD_NUMBER = 6;
private java.util.List<eshop.api.product.Products.ProductSubType> subTypes_;
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public java.util.List<eshop.api.product.Products.ProductSubType> getSubTypesList() {
return subTypes_;
}
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public java.util.List<? extends eshop.api.product.Products.ProductSubTypeOrBuilder>
getSubTypesOrBuilderList() {
return subTypes_;
}
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public int getSubTypesCount() {
return subTypes_.size();
}
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public eshop.api.product.Products.ProductSubType getSubTypes(int index) {
return subTypes_.get(index);
}
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public eshop.api.product.Products.ProductSubTypeOrBuilder getSubTypesOrBuilder(
int index) {
return subTypes_.get(index);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!getIdBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, id_);
}
if (!getVendorIdBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, vendorId_);
}
if (!getNameBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, name_);
}
if (!getDescBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, desc_);
}
for (int i = 0; i < tags_.size(); i++) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, tags_.getRaw(i));
}
for (int i = 0; i < subTypes_.size(); i++) {
output.writeMessage(6, subTypes_.get(i));
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!getIdBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, id_);
}
if (!getVendorIdBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, vendorId_);
}
if (!getNameBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, name_);
}
if (!getDescBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, desc_);
}
{
int dataSize = 0;
for (int i = 0; i < tags_.size(); i++) {
dataSize += computeStringSizeNoTag(tags_.getRaw(i));
}
size += dataSize;
size += 1 * getTagsList().size();
}
for (int i = 0; i < subTypes_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(6, subTypes_.get(i));
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof eshop.api.product.Products.Product)) {
return super.equals(obj);
}
eshop.api.product.Products.Product other = (eshop.api.product.Products.Product) obj;
boolean result = true;
result = result && getId()
.equals(other.getId());
result = result && getVendorId()
.equals(other.getVendorId());
result = result && getName()
.equals(other.getName());
result = result && getDesc()
.equals(other.getDesc());
result = result && getTagsList()
.equals(other.getTagsList());
result = result && getSubTypesList()
.equals(other.getSubTypesList());
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + ID_FIELD_NUMBER;
hash = (53 * hash) + getId().hashCode();
hash = (37 * hash) + VENDORID_FIELD_NUMBER;
hash = (53 * hash) + getVendorId().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
hash = (37 * hash) + DESC_FIELD_NUMBER;
hash = (53 * hash) + getDesc().hashCode();
if (getTagsCount() > 0) {
hash = (37 * hash) + TAGS_FIELD_NUMBER;
hash = (53 * hash) + getTagsList().hashCode();
}
if (getSubTypesCount() > 0) {
hash = (37 * hash) + SUBTYPES_FIELD_NUMBER;
hash = (53 * hash) + getSubTypesList().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static eshop.api.product.Products.Product parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static eshop.api.product.Products.Product parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static eshop.api.product.Products.Product parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static eshop.api.product.Products.Product parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static eshop.api.product.Products.Product parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static eshop.api.product.Products.Product parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static eshop.api.product.Products.Product parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static eshop.api.product.Products.Product parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static eshop.api.product.Products.Product parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static eshop.api.product.Products.Product parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static eshop.api.product.Products.Product parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static eshop.api.product.Products.Product parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(eshop.api.product.Products.Product prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code eshop.api.product.Product}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:eshop.api.product.Product)
eshop.api.product.Products.ProductOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return eshop.api.product.Products.internal_static_eshop_api_product_Product_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return eshop.api.product.Products.internal_static_eshop_api_product_Product_fieldAccessorTable
.ensureFieldAccessorsInitialized(
eshop.api.product.Products.Product.class, eshop.api.product.Products.Product.Builder.class);
}
// Construct using eshop.api.product.Products.Product.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getSubTypesFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
id_ = "";
vendorId_ = "";
name_ = "";
desc_ = "";
tags_ = com.google.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000010);
if (subTypesBuilder_ == null) {
subTypes_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000020);
} else {
subTypesBuilder_.clear();
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return eshop.api.product.Products.internal_static_eshop_api_product_Product_descriptor;
}
@java.lang.Override
public eshop.api.product.Products.Product getDefaultInstanceForType() {
return eshop.api.product.Products.Product.getDefaultInstance();
}
@java.lang.Override
public eshop.api.product.Products.Product build() {
eshop.api.product.Products.Product result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public eshop.api.product.Products.Product buildPartial() {
eshop.api.product.Products.Product result = new eshop.api.product.Products.Product(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
result.id_ = id_;
result.vendorId_ = vendorId_;
result.name_ = name_;
result.desc_ = desc_;
if (((bitField0_ & 0x00000010) == 0x00000010)) {
tags_ = tags_.getUnmodifiableView();
bitField0_ = (bitField0_ & ~0x00000010);
}
result.tags_ = tags_;
if (subTypesBuilder_ == null) {
if (((bitField0_ & 0x00000020) == 0x00000020)) {
subTypes_ = java.util.Collections.unmodifiableList(subTypes_);
bitField0_ = (bitField0_ & ~0x00000020);
}
result.subTypes_ = subTypes_;
} else {
result.subTypes_ = subTypesBuilder_.build();
}
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return (Builder) super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof eshop.api.product.Products.Product) {
return mergeFrom((eshop.api.product.Products.Product)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(eshop.api.product.Products.Product other) {
if (other == eshop.api.product.Products.Product.getDefaultInstance()) return this;
if (!other.getId().isEmpty()) {
id_ = other.id_;
onChanged();
}
if (!other.getVendorId().isEmpty()) {
vendorId_ = other.vendorId_;
onChanged();
}
if (!other.getName().isEmpty()) {
name_ = other.name_;
onChanged();
}
if (!other.getDesc().isEmpty()) {
desc_ = other.desc_;
onChanged();
}
if (!other.tags_.isEmpty()) {
if (tags_.isEmpty()) {
tags_ = other.tags_;
bitField0_ = (bitField0_ & ~0x00000010);
} else {
ensureTagsIsMutable();
tags_.addAll(other.tags_);
}
onChanged();
}
if (subTypesBuilder_ == null) {
if (!other.subTypes_.isEmpty()) {
if (subTypes_.isEmpty()) {
subTypes_ = other.subTypes_;
bitField0_ = (bitField0_ & ~0x00000020);
} else {
ensureSubTypesIsMutable();
subTypes_.addAll(other.subTypes_);
}
onChanged();
}
} else {
if (!other.subTypes_.isEmpty()) {
if (subTypesBuilder_.isEmpty()) {
subTypesBuilder_.dispose();
subTypesBuilder_ = null;
subTypes_ = other.subTypes_;
bitField0_ = (bitField0_ & ~0x00000020);
subTypesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getSubTypesFieldBuilder() : null;
} else {
subTypesBuilder_.addAllMessages(other.subTypes_);
}
}
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
eshop.api.product.Products.Product parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (eshop.api.product.Products.Product) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.lang.Object id_ = "";
/**
* <code>string id = 1;</code>
*/
public java.lang.String getId() {
java.lang.Object ref = id_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
id_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>string id = 1;</code>
*/
public com.google.protobuf.ByteString
getIdBytes() {
java.lang.Object ref = id_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string id = 1;</code>
*/
public Builder setId(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
id_ = value;
onChanged();
return this;
}
/**
* <code>string id = 1;</code>
*/
public Builder clearId() {
id_ = getDefaultInstance().getId();
onChanged();
return this;
}
/**
* <code>string id = 1;</code>
*/
public Builder setIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
id_ = value;
onChanged();
return this;
}
private java.lang.Object vendorId_ = "";
/**
* <code>string vendorId = 2;</code>
*/
public java.lang.String getVendorId() {
java.lang.Object ref = vendorId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
vendorId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>string vendorId = 2;</code>
*/
public com.google.protobuf.ByteString
getVendorIdBytes() {
java.lang.Object ref = vendorId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
vendorId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string vendorId = 2;</code>
*/
public Builder setVendorId(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
vendorId_ = value;
onChanged();
return this;
}
/**
* <code>string vendorId = 2;</code>
*/
public Builder clearVendorId() {
vendorId_ = getDefaultInstance().getVendorId();
onChanged();
return this;
}
/**
* <code>string vendorId = 2;</code>
*/
public Builder setVendorIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
vendorId_ = value;
onChanged();
return this;
}
private java.lang.Object name_ = "";
/**
* <code>string name = 3;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>string name = 3;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string name = 3;</code>
*/
public Builder setName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
onChanged();
return this;
}
/**
* <code>string name = 3;</code>
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
* <code>string name = 3;</code>
*/
public Builder setNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
onChanged();
return this;
}
private java.lang.Object desc_ = "";
/**
* <code>string desc = 4;</code>
*/
public java.lang.String getDesc() {
java.lang.Object ref = desc_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
desc_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>string desc = 4;</code>
*/
public com.google.protobuf.ByteString
getDescBytes() {
java.lang.Object ref = desc_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
desc_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string desc = 4;</code>
*/
public Builder setDesc(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
desc_ = value;
onChanged();
return this;
}
/**
* <code>string desc = 4;</code>
*/
public Builder clearDesc() {
desc_ = getDefaultInstance().getDesc();
onChanged();
return this;
}
/**
* <code>string desc = 4;</code>
*/
public Builder setDescBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
desc_ = value;
onChanged();
return this;
}
private com.google.protobuf.LazyStringList tags_ = com.google.protobuf.LazyStringArrayList.EMPTY;
private void ensureTagsIsMutable() {
if (!((bitField0_ & 0x00000010) == 0x00000010)) {
tags_ = new com.google.protobuf.LazyStringArrayList(tags_);
bitField0_ |= 0x00000010;
}
}
/**
* <code>repeated string tags = 5;</code>
*/
public com.google.protobuf.ProtocolStringList
getTagsList() {
return tags_.getUnmodifiableView();
}
/**
* <code>repeated string tags = 5;</code>
*/
public int getTagsCount() {
return tags_.size();
}
/**
* <code>repeated string tags = 5;</code>
*/
public java.lang.String getTags(int index) {
return tags_.get(index);
}
/**
* <code>repeated string tags = 5;</code>
*/
public com.google.protobuf.ByteString
getTagsBytes(int index) {
return tags_.getByteString(index);
}
/**
* <code>repeated string tags = 5;</code>
*/
public Builder setTags(
int index, java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureTagsIsMutable();
tags_.set(index, value);
onChanged();
return this;
}
/**
* <code>repeated string tags = 5;</code>
*/
public Builder addTags(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureTagsIsMutable();
tags_.add(value);
onChanged();
return this;
}
/**
* <code>repeated string tags = 5;</code>
*/
public Builder addAllTags(
java.lang.Iterable<java.lang.String> values) {
ensureTagsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, tags_);
onChanged();
return this;
}
/**
* <code>repeated string tags = 5;</code>
*/
public Builder clearTags() {
tags_ = com.google.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000010);
onChanged();
return this;
}
/**
* <code>repeated string tags = 5;</code>
*/
public Builder addTagsBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
ensureTagsIsMutable();
tags_.add(value);
onChanged();
return this;
}
private java.util.List<eshop.api.product.Products.ProductSubType> subTypes_ =
java.util.Collections.emptyList();
private void ensureSubTypesIsMutable() {
if (!((bitField0_ & 0x00000020) == 0x00000020)) {
subTypes_ = new java.util.ArrayList<eshop.api.product.Products.ProductSubType>(subTypes_);
bitField0_ |= 0x00000020;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
eshop.api.product.Products.ProductSubType, eshop.api.product.Products.ProductSubType.Builder, eshop.api.product.Products.ProductSubTypeOrBuilder> subTypesBuilder_;
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public java.util.List<eshop.api.product.Products.ProductSubType> getSubTypesList() {
if (subTypesBuilder_ == null) {
return java.util.Collections.unmodifiableList(subTypes_);
} else {
return subTypesBuilder_.getMessageList();
}
}
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public int getSubTypesCount() {
if (subTypesBuilder_ == null) {
return subTypes_.size();
} else {
return subTypesBuilder_.getCount();
}
}
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public eshop.api.product.Products.ProductSubType getSubTypes(int index) {
if (subTypesBuilder_ == null) {
return subTypes_.get(index);
} else {
return subTypesBuilder_.getMessage(index);
}
}
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public Builder setSubTypes(
int index, eshop.api.product.Products.ProductSubType value) {
if (subTypesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSubTypesIsMutable();
subTypes_.set(index, value);
onChanged();
} else {
subTypesBuilder_.setMessage(index, value);
}
return this;
}
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public Builder setSubTypes(
int index, eshop.api.product.Products.ProductSubType.Builder builderForValue) {
if (subTypesBuilder_ == null) {
ensureSubTypesIsMutable();
subTypes_.set(index, builderForValue.build());
onChanged();
} else {
subTypesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public Builder addSubTypes(eshop.api.product.Products.ProductSubType value) {
if (subTypesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSubTypesIsMutable();
subTypes_.add(value);
onChanged();
} else {
subTypesBuilder_.addMessage(value);
}
return this;
}
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public Builder addSubTypes(
int index, eshop.api.product.Products.ProductSubType value) {
if (subTypesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSubTypesIsMutable();
subTypes_.add(index, value);
onChanged();
} else {
subTypesBuilder_.addMessage(index, value);
}
return this;
}
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public Builder addSubTypes(
eshop.api.product.Products.ProductSubType.Builder builderForValue) {
if (subTypesBuilder_ == null) {
ensureSubTypesIsMutable();
subTypes_.add(builderForValue.build());
onChanged();
} else {
subTypesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public Builder addSubTypes(
int index, eshop.api.product.Products.ProductSubType.Builder builderForValue) {
if (subTypesBuilder_ == null) {
ensureSubTypesIsMutable();
subTypes_.add(index, builderForValue.build());
onChanged();
} else {
subTypesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public Builder addAllSubTypes(
java.lang.Iterable<? extends eshop.api.product.Products.ProductSubType> values) {
if (subTypesBuilder_ == null) {
ensureSubTypesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, subTypes_);
onChanged();
} else {
subTypesBuilder_.addAllMessages(values);
}
return this;
}
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public Builder clearSubTypes() {
if (subTypesBuilder_ == null) {
subTypes_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000020);
onChanged();
} else {
subTypesBuilder_.clear();
}
return this;
}
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public Builder removeSubTypes(int index) {
if (subTypesBuilder_ == null) {
ensureSubTypesIsMutable();
subTypes_.remove(index);
onChanged();
} else {
subTypesBuilder_.remove(index);
}
return this;
}
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public eshop.api.product.Products.ProductSubType.Builder getSubTypesBuilder(
int index) {
return getSubTypesFieldBuilder().getBuilder(index);
}
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public eshop.api.product.Products.ProductSubTypeOrBuilder getSubTypesOrBuilder(
int index) {
if (subTypesBuilder_ == null) {
return subTypes_.get(index); } else {
return subTypesBuilder_.getMessageOrBuilder(index);
}
}
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public java.util.List<? extends eshop.api.product.Products.ProductSubTypeOrBuilder>
getSubTypesOrBuilderList() {
if (subTypesBuilder_ != null) {
return subTypesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(subTypes_);
}
}
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public eshop.api.product.Products.ProductSubType.Builder addSubTypesBuilder() {
return getSubTypesFieldBuilder().addBuilder(
eshop.api.product.Products.ProductSubType.getDefaultInstance());
}
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public eshop.api.product.Products.ProductSubType.Builder addSubTypesBuilder(
int index) {
return getSubTypesFieldBuilder().addBuilder(
index, eshop.api.product.Products.ProductSubType.getDefaultInstance());
}
/**
* <code>repeated .eshop.api.product.ProductSubType subTypes = 6;</code>
*/
public java.util.List<eshop.api.product.Products.ProductSubType.Builder>
getSubTypesBuilderList() {
return getSubTypesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
eshop.api.product.Products.ProductSubType, eshop.api.product.Products.ProductSubType.Builder, eshop.api.product.Products.ProductSubTypeOrBuilder>
getSubTypesFieldBuilder() {
if (subTypesBuilder_ == null) {
subTypesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
eshop.api.product.Products.ProductSubType, eshop.api.product.Products.ProductSubType.Builder, eshop.api.product.Products.ProductSubTypeOrBuilder>(
subTypes_,
((bitField0_ & 0x00000020) == 0x00000020),
getParentForChildren(),
isClean());
subTypes_ = null;
}
return subTypesBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFieldsProto3(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:eshop.api.product.Product)
}
// @@protoc_insertion_point(class_scope:eshop.api.product.Product)
private static final eshop.api.product.Products.Product DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new eshop.api.product.Products.Product();
}
public static eshop.api.product.Products.Product getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<Product>
PARSER = new com.google.protobuf.AbstractParser<Product>() {
@java.lang.Override
public Product parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new Product(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<Product> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<Product> getParserForType() {
return PARSER;
}
@java.lang.Override
public eshop.api.product.Products.Product getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
public interface ProductSubTypeOrBuilder extends
// @@protoc_insertion_point(interface_extends:eshop.api.product.ProductSubType)
com.google.protobuf.MessageOrBuilder {
/**
* <code>string id = 1;</code>
*/
java.lang.String getId();
/**
* <code>string id = 1;</code>
*/
com.google.protobuf.ByteString
getIdBytes();
/**
* <code>string productId = 2;</code>
*/
java.lang.String getProductId();
/**
* <code>string productId = 2;</code>
*/
com.google.protobuf.ByteString
getProductIdBytes();
/**
* <code>string name = 3;</code>
*/
java.lang.String getName();
/**
* <code>string name = 3;</code>
*/
com.google.protobuf.ByteString
getNameBytes();
/**
* <code>string desc = 4;</code>
*/
java.lang.String getDesc();
/**
* <code>string desc = 4;</code>
*/
com.google.protobuf.ByteString
getDescBytes();
/**
* <code>repeated string imgUrls = 5;</code>
*/
java.util.List<java.lang.String>
getImgUrlsList();
/**
* <code>repeated string imgUrls = 5;</code>
*/
int getImgUrlsCount();
/**
* <code>repeated string imgUrls = 5;</code>
*/
java.lang.String getImgUrls(int index);
/**
* <code>repeated string imgUrls = 5;</code>
*/
com.google.protobuf.ByteString
getImgUrlsBytes(int index);
}
/**
* Protobuf type {@code eshop.api.product.ProductSubType}
*/
public static final class ProductSubType extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:eshop.api.product.ProductSubType)
ProductSubTypeOrBuilder {
private static final long serialVersionUID = 0L;
// Use ProductSubType.newBuilder() to construct.
private ProductSubType(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ProductSubType() {
id_ = "";
productId_ = "";
name_ = "";
desc_ = "";
imgUrls_ = com.google.protobuf.LazyStringArrayList.EMPTY;
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private ProductSubType(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
java.lang.String s = input.readStringRequireUtf8();
id_ = s;
break;
}
case 18: {
java.lang.String s = input.readStringRequireUtf8();
productId_ = s;
break;
}
case 26: {
java.lang.String s = input.readStringRequireUtf8();
name_ = s;
break;
}
case 34: {
java.lang.String s = input.readStringRequireUtf8();
desc_ = s;
break;
}
case 42: {
java.lang.String s = input.readStringRequireUtf8();
if (!((mutable_bitField0_ & 0x00000010) == 0x00000010)) {
imgUrls_ = new com.google.protobuf.LazyStringArrayList();
mutable_bitField0_ |= 0x00000010;
}
imgUrls_.add(s);
break;
}
default: {
if (!parseUnknownFieldProto3(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000010) == 0x00000010)) {
imgUrls_ = imgUrls_.getUnmodifiableView();
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return eshop.api.product.Products.internal_static_eshop_api_product_ProductSubType_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return eshop.api.product.Products.internal_static_eshop_api_product_ProductSubType_fieldAccessorTable
.ensureFieldAccessorsInitialized(
eshop.api.product.Products.ProductSubType.class, eshop.api.product.Products.ProductSubType.Builder.class);
}
private int bitField0_;
public static final int ID_FIELD_NUMBER = 1;
private volatile java.lang.Object id_;
/**
* <code>string id = 1;</code>
*/
public java.lang.String getId() {
java.lang.Object ref = id_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
id_ = s;
return s;
}
}
/**
* <code>string id = 1;</code>
*/
public com.google.protobuf.ByteString
getIdBytes() {
java.lang.Object ref = id_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PRODUCTID_FIELD_NUMBER = 2;
private volatile java.lang.Object productId_;
/**
* <code>string productId = 2;</code>
*/
public java.lang.String getProductId() {
java.lang.Object ref = productId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
productId_ = s;
return s;
}
}
/**
* <code>string productId = 2;</code>
*/
public com.google.protobuf.ByteString
getProductIdBytes() {
java.lang.Object ref = productId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
productId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int NAME_FIELD_NUMBER = 3;
private volatile java.lang.Object name_;
/**
* <code>string name = 3;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
* <code>string name = 3;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int DESC_FIELD_NUMBER = 4;
private volatile java.lang.Object desc_;
/**
* <code>string desc = 4;</code>
*/
public java.lang.String getDesc() {
java.lang.Object ref = desc_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
desc_ = s;
return s;
}
}
/**
* <code>string desc = 4;</code>
*/
public com.google.protobuf.ByteString
getDescBytes() {
java.lang.Object ref = desc_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
desc_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int IMGURLS_FIELD_NUMBER = 5;
private com.google.protobuf.LazyStringList imgUrls_;
/**
* <code>repeated string imgUrls = 5;</code>
*/
public com.google.protobuf.ProtocolStringList
getImgUrlsList() {
return imgUrls_;
}
/**
* <code>repeated string imgUrls = 5;</code>
*/
public int getImgUrlsCount() {
return imgUrls_.size();
}
/**
* <code>repeated string imgUrls = 5;</code>
*/
public java.lang.String getImgUrls(int index) {
return imgUrls_.get(index);
}
/**
* <code>repeated string imgUrls = 5;</code>
*/
public com.google.protobuf.ByteString
getImgUrlsBytes(int index) {
return imgUrls_.getByteString(index);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!getIdBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, id_);
}
if (!getProductIdBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, productId_);
}
if (!getNameBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, name_);
}
if (!getDescBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, desc_);
}
for (int i = 0; i < imgUrls_.size(); i++) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, imgUrls_.getRaw(i));
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!getIdBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, id_);
}
if (!getProductIdBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, productId_);
}
if (!getNameBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, name_);
}
if (!getDescBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, desc_);
}
{
int dataSize = 0;
for (int i = 0; i < imgUrls_.size(); i++) {
dataSize += computeStringSizeNoTag(imgUrls_.getRaw(i));
}
size += dataSize;
size += 1 * getImgUrlsList().size();
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof eshop.api.product.Products.ProductSubType)) {
return super.equals(obj);
}
eshop.api.product.Products.ProductSubType other = (eshop.api.product.Products.ProductSubType) obj;
boolean result = true;
result = result && getId()
.equals(other.getId());
result = result && getProductId()
.equals(other.getProductId());
result = result && getName()
.equals(other.getName());
result = result && getDesc()
.equals(other.getDesc());
result = result && getImgUrlsList()
.equals(other.getImgUrlsList());
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + ID_FIELD_NUMBER;
hash = (53 * hash) + getId().hashCode();
hash = (37 * hash) + PRODUCTID_FIELD_NUMBER;
hash = (53 * hash) + getProductId().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
hash = (37 * hash) + DESC_FIELD_NUMBER;
hash = (53 * hash) + getDesc().hashCode();
if (getImgUrlsCount() > 0) {
hash = (37 * hash) + IMGURLS_FIELD_NUMBER;
hash = (53 * hash) + getImgUrlsList().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static eshop.api.product.Products.ProductSubType parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static eshop.api.product.Products.ProductSubType parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static eshop.api.product.Products.ProductSubType parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static eshop.api.product.Products.ProductSubType parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static eshop.api.product.Products.ProductSubType parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static eshop.api.product.Products.ProductSubType parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static eshop.api.product.Products.ProductSubType parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static eshop.api.product.Products.ProductSubType parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static eshop.api.product.Products.ProductSubType parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static eshop.api.product.Products.ProductSubType parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static eshop.api.product.Products.ProductSubType parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static eshop.api.product.Products.ProductSubType parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(eshop.api.product.Products.ProductSubType prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code eshop.api.product.ProductSubType}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:eshop.api.product.ProductSubType)
eshop.api.product.Products.ProductSubTypeOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return eshop.api.product.Products.internal_static_eshop_api_product_ProductSubType_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return eshop.api.product.Products.internal_static_eshop_api_product_ProductSubType_fieldAccessorTable
.ensureFieldAccessorsInitialized(
eshop.api.product.Products.ProductSubType.class, eshop.api.product.Products.ProductSubType.Builder.class);
}
// Construct using eshop.api.product.Products.ProductSubType.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
id_ = "";
productId_ = "";
name_ = "";
desc_ = "";
imgUrls_ = com.google.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000010);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return eshop.api.product.Products.internal_static_eshop_api_product_ProductSubType_descriptor;
}
@java.lang.Override
public eshop.api.product.Products.ProductSubType getDefaultInstanceForType() {
return eshop.api.product.Products.ProductSubType.getDefaultInstance();
}
@java.lang.Override
public eshop.api.product.Products.ProductSubType build() {
eshop.api.product.Products.ProductSubType result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public eshop.api.product.Products.ProductSubType buildPartial() {
eshop.api.product.Products.ProductSubType result = new eshop.api.product.Products.ProductSubType(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
result.id_ = id_;
result.productId_ = productId_;
result.name_ = name_;
result.desc_ = desc_;
if (((bitField0_ & 0x00000010) == 0x00000010)) {
imgUrls_ = imgUrls_.getUnmodifiableView();
bitField0_ = (bitField0_ & ~0x00000010);
}
result.imgUrls_ = imgUrls_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return (Builder) super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof eshop.api.product.Products.ProductSubType) {
return mergeFrom((eshop.api.product.Products.ProductSubType)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(eshop.api.product.Products.ProductSubType other) {
if (other == eshop.api.product.Products.ProductSubType.getDefaultInstance()) return this;
if (!other.getId().isEmpty()) {
id_ = other.id_;
onChanged();
}
if (!other.getProductId().isEmpty()) {
productId_ = other.productId_;
onChanged();
}
if (!other.getName().isEmpty()) {
name_ = other.name_;
onChanged();
}
if (!other.getDesc().isEmpty()) {
desc_ = other.desc_;
onChanged();
}
if (!other.imgUrls_.isEmpty()) {
if (imgUrls_.isEmpty()) {
imgUrls_ = other.imgUrls_;
bitField0_ = (bitField0_ & ~0x00000010);
} else {
ensureImgUrlsIsMutable();
imgUrls_.addAll(other.imgUrls_);
}
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
eshop.api.product.Products.ProductSubType parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (eshop.api.product.Products.ProductSubType) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.lang.Object id_ = "";
/**
* <code>string id = 1;</code>
*/
public java.lang.String getId() {
java.lang.Object ref = id_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
id_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>string id = 1;</code>
*/
public com.google.protobuf.ByteString
getIdBytes() {
java.lang.Object ref = id_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string id = 1;</code>
*/
public Builder setId(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
id_ = value;
onChanged();
return this;
}
/**
* <code>string id = 1;</code>
*/
public Builder clearId() {
id_ = getDefaultInstance().getId();
onChanged();
return this;
}
/**
* <code>string id = 1;</code>
*/
public Builder setIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
id_ = value;
onChanged();
return this;
}
private java.lang.Object productId_ = "";
/**
* <code>string productId = 2;</code>
*/
public java.lang.String getProductId() {
java.lang.Object ref = productId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
productId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>string productId = 2;</code>
*/
public com.google.protobuf.ByteString
getProductIdBytes() {
java.lang.Object ref = productId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
productId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string productId = 2;</code>
*/
public Builder setProductId(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
productId_ = value;
onChanged();
return this;
}
/**
* <code>string productId = 2;</code>
*/
public Builder clearProductId() {
productId_ = getDefaultInstance().getProductId();
onChanged();
return this;
}
/**
* <code>string productId = 2;</code>
*/
public Builder setProductIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
productId_ = value;
onChanged();
return this;
}
private java.lang.Object name_ = "";
/**
* <code>string name = 3;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>string name = 3;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string name = 3;</code>
*/
public Builder setName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
onChanged();
return this;
}
/**
* <code>string name = 3;</code>
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
* <code>string name = 3;</code>
*/
public Builder setNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
onChanged();
return this;
}
private java.lang.Object desc_ = "";
/**
* <code>string desc = 4;</code>
*/
public java.lang.String getDesc() {
java.lang.Object ref = desc_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
desc_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>string desc = 4;</code>
*/
public com.google.protobuf.ByteString
getDescBytes() {
java.lang.Object ref = desc_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
desc_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string desc = 4;</code>
*/
public Builder setDesc(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
desc_ = value;
onChanged();
return this;
}
/**
* <code>string desc = 4;</code>
*/
public Builder clearDesc() {
desc_ = getDefaultInstance().getDesc();
onChanged();
return this;
}
/**
* <code>string desc = 4;</code>
*/
public Builder setDescBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
desc_ = value;
onChanged();
return this;
}
private com.google.protobuf.LazyStringList imgUrls_ = com.google.protobuf.LazyStringArrayList.EMPTY;
private void ensureImgUrlsIsMutable() {
if (!((bitField0_ & 0x00000010) == 0x00000010)) {
imgUrls_ = new com.google.protobuf.LazyStringArrayList(imgUrls_);
bitField0_ |= 0x00000010;
}
}
/**
* <code>repeated string imgUrls = 5;</code>
*/
public com.google.protobuf.ProtocolStringList
getImgUrlsList() {
return imgUrls_.getUnmodifiableView();
}
/**
* <code>repeated string imgUrls = 5;</code>
*/
public int getImgUrlsCount() {
return imgUrls_.size();
}
/**
* <code>repeated string imgUrls = 5;</code>
*/
public java.lang.String getImgUrls(int index) {
return imgUrls_.get(index);
}
/**
* <code>repeated string imgUrls = 5;</code>
*/
public com.google.protobuf.ByteString
getImgUrlsBytes(int index) {
return imgUrls_.getByteString(index);
}
/**
* <code>repeated string imgUrls = 5;</code>
*/
public Builder setImgUrls(
int index, java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureImgUrlsIsMutable();
imgUrls_.set(index, value);
onChanged();
return this;
}
/**
* <code>repeated string imgUrls = 5;</code>
*/
public Builder addImgUrls(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureImgUrlsIsMutable();
imgUrls_.add(value);
onChanged();
return this;
}
/**
* <code>repeated string imgUrls = 5;</code>
*/
public Builder addAllImgUrls(
java.lang.Iterable<java.lang.String> values) {
ensureImgUrlsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, imgUrls_);
onChanged();
return this;
}
/**
* <code>repeated string imgUrls = 5;</code>
*/
public Builder clearImgUrls() {
imgUrls_ = com.google.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000010);
onChanged();
return this;
}
/**
* <code>repeated string imgUrls = 5;</code>
*/
public Builder addImgUrlsBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
ensureImgUrlsIsMutable();
imgUrls_.add(value);
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFieldsProto3(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:eshop.api.product.ProductSubType)
}
// @@protoc_insertion_point(class_scope:eshop.api.product.ProductSubType)
private static final eshop.api.product.Products.ProductSubType DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new eshop.api.product.Products.ProductSubType();
}
public static eshop.api.product.Products.ProductSubType getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ProductSubType>
PARSER = new com.google.protobuf.AbstractParser<ProductSubType>() {
@java.lang.Override
public ProductSubType parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new ProductSubType(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<ProductSubType> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ProductSubType> getParserForType() {
return PARSER;
}
@java.lang.Override
public eshop.api.product.Products.ProductSubType getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_eshop_api_product_Product_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_eshop_api_product_Product_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_eshop_api_product_ProductSubType_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_eshop_api_product_ProductSubType_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\016Products.proto\022\021eshop.api.product\"\206\001\n\007" +
"Product\022\n\n\002id\030\001 \001(\t\022\020\n\010vendorId\030\002 \001(\t\022\014\n" +
"\004name\030\003 \001(\t\022\014\n\004desc\030\004 \001(\t\022\014\n\004tags\030\005 \003(\t\022" +
"3\n\010subTypes\030\006 \003(\0132!.eshop.api.product.Pr" +
"oductSubType\"\\\n\016ProductSubType\022\n\n\002id\030\001 \001" +
"(\t\022\021\n\tproductId\030\002 \001(\t\022\014\n\004name\030\003 \001(\t\022\014\n\004d" +
"esc\030\004 \001(\t\022\017\n\007imgUrls\030\005 \003(\tb\006proto3"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
}, assigner);
internal_static_eshop_api_product_Product_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_eshop_api_product_Product_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_eshop_api_product_Product_descriptor,
new java.lang.String[] { "Id", "VendorId", "Name", "Desc", "Tags", "SubTypes", });
internal_static_eshop_api_product_ProductSubType_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_eshop_api_product_ProductSubType_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_eshop_api_product_ProductSubType_descriptor,
new java.lang.String[] { "Id", "ProductId", "Name", "Desc", "ImgUrls", });
}
// @@protoc_insertion_point(outer_class_scope)
}
|
3e01f13b7a5f34385ec0a0e2fcaaa9895dffa18f | 9,874 | java | Java | apps/sasquatch/src/androidTest/java/com/microsoft/appcenter/sasquatch/activities/CrashesTest.java | G-arj/appcenter-sdk-android | 142a29983c232c262aa903c9a545f8cf1e427b91 | [
"MIT"
] | 136 | 2019-05-15T18:02:10.000Z | 2022-03-08T06:34:05.000Z | apps/sasquatch/src/androidTest/java/com/microsoft/appcenter/sasquatch/activities/CrashesTest.java | G-arj/appcenter-sdk-android | 142a29983c232c262aa903c9a545f8cf1e427b91 | [
"MIT"
] | 275 | 2019-05-13T19:20:29.000Z | 2022-03-31T11:41:10.000Z | apps/sasquatch/src/androidTest/java/com/microsoft/appcenter/sasquatch/activities/CrashesTest.java | G-arj/appcenter-sdk-android | 142a29983c232c262aa903c9a545f8cf1e427b91 | [
"MIT"
] | 76 | 2019-05-17T21:23:07.000Z | 2022-03-21T11:33:08.000Z | 39.027668 | 125 | 0.701033 | 820 | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
package com.microsoft.appcenter.sasquatch.activities;
import android.content.Context;
import android.content.Intent;
import androidx.annotation.StringRes;
import androidx.core.app.ActivityCompat;
import androidx.test.espresso.EspressoException;
import androidx.test.espresso.FailureHandler;
import androidx.test.espresso.IdlingRegistry;
import androidx.test.espresso.ViewInteraction;
import androidx.test.espresso.matcher.BoundedMatcher;
import androidx.test.rule.ActivityTestRule;
import android.view.View;
import com.microsoft.appcenter.AppCenter;
import com.microsoft.appcenter.Constants;
import com.microsoft.appcenter.crashes.Crashes;
import com.microsoft.appcenter.crashes.CrashesPrivateHelper;
import com.microsoft.appcenter.crashes.model.ErrorReport;
import com.microsoft.appcenter.crashes.utils.ErrorLogHelper;
import com.microsoft.appcenter.sasquatch.CrashTestHelper;
import com.microsoft.appcenter.sasquatch.R;
import com.microsoft.appcenter.sasquatch.listeners.SasquatchCrashesListener;
import com.microsoft.appcenter.utils.storage.SharedPreferencesManager;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.io.File;
import java.lang.reflect.Method;
import java.util.Date;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
import static androidx.test.espresso.Espresso.onData;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.RootMatchers.isDialog;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.isRoot;
import static androidx.test.espresso.matcher.ViewMatchers.withChild;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static android.util.Log.getStackTraceString;
import static com.microsoft.appcenter.sasquatch.activities.utils.EspressoUtils.CHECK_DELAY;
import static com.microsoft.appcenter.sasquatch.activities.utils.EspressoUtils.TOAST_DELAY;
import static com.microsoft.appcenter.sasquatch.activities.utils.EspressoUtils.onToast;
import static com.microsoft.appcenter.sasquatch.activities.utils.EspressoUtils.waitFor;
import static com.microsoft.appcenter.sasquatch.activities.utils.EspressoUtils.withContainsText;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
@SuppressWarnings("unused")
public class CrashesTest {
@Rule
public final ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class, true, false);
private Context mContext;
private static Matcher<Object> withCrashTitle(@StringRes final int titleId) {
return new BoundedMatcher<Object, CrashTestHelper.Crash>(CrashTestHelper.Crash.class) {
@Override
public boolean matchesSafely(CrashTestHelper.Crash map) {
return map.title == titleId;
}
@Override
public void describeTo(Description description) {
description.appendText("with item title from resource id: ");
description.appendValue(titleId);
}
};
}
@Before
public void setUp() {
mContext = getInstrumentation().getTargetContext();
/* Clear preferences. */
SharedPreferencesManager.initialize(mContext);
SharedPreferencesManager.clear();
/* Clear crashes. */
Constants.loadFromContext(mContext);
for (File logFile : ErrorLogHelper.getErrorStorageDirectory().listFiles()) {
if (!logFile.isDirectory()) {
assertTrue(logFile.delete());
}
}
/* Clear listeners. */
MainActivity.sAnalyticsListener = null;
MainActivity.sCrashesListener = null;
/* Launch main activity and go to setting page. Required to properly initialize. */
mActivityTestRule.launchActivity(new Intent());
/* Register IdlingResource */
IdlingRegistry.getInstance().register(SasquatchCrashesListener.crashesIdlingResource);
}
@After
public final void tearDown() {
/* Unregister IdlingResource */
IdlingRegistry.getInstance().unregister(SasquatchCrashesListener.crashesIdlingResource);
}
@Test
public void testCrashTest() throws InterruptedException {
crashTest(R.string.title_test_crash);
}
@Test
public void divideByZeroTest() throws InterruptedException {
crashTest(R.string.title_crash_divide_by_0);
}
@Test
public void uiCrashTest() throws InterruptedException {
crashTest(R.string.title_test_ui_crash);
}
@Test
public void variableMessageTest() throws InterruptedException {
crashTest(R.string.title_variable_message);
}
/**
* Crash and sending report test.
* <p>
* We can't truly restart application in tests, so some kind of crashes can't be tested by this method.
* Out of memory or stack overflow - crash the test process;
* UI states errors - problems with restart activity;
* <p>
* Also to avoid flakiness, please setup your test environment
* (https://google.github.io/android-testing-support-library/docs/espresso/setup/index.html#setup-your-test-environment).
* On your device, under Settings->Developer options disable the following 3 settings:
* - Window animation scale
* - Transition animation scale
* - Animator duration scale
*
* @param titleId Title string resource to find list item.
* @throws InterruptedException If the current thread is interrupted.
*/
private void crashTest(@StringRes int titleId) throws InterruptedException {
/* Crash. */
onView(allOf(
withChild(withText(R.string.title_crashes)),
withChild(withText(R.string.description_crashes))))
.perform(click());
CrashFailureHandler failureHandler = new CrashFailureHandler();
onCrash(titleId)
.withFailureHandler(failureHandler)
.perform(click());
/* Check error report. */
assertTrue(Crashes.hasCrashedInLastSession().get());
ErrorReport errorReport = Crashes.getLastSessionCrashReport().get();
assertNotNull(errorReport);
assertNotNull(errorReport.getId());
assertEquals(mContext.getMainLooper().getThread().getName(), errorReport.getThreadName());
assertThat("AppStartTime",
new Date().getTime() - errorReport.getAppStartTime().getTime(),
lessThan(60000L));
assertThat("AppErrorTime",
new Date().getTime() - errorReport.getAppErrorTime().getTime(),
lessThan(10000L));
assertNotNull(errorReport.getDevice());
assertTrue(errorReport.getStackTrace().contains(failureHandler.uncaughtException.getMessage()));
/* Send report. */
waitFor(onView(withText(R.string.crash_confirmation_dialog_send_button))
.inRoot(isDialog()), 1000)
.perform(click());
/* Check toasts. */
waitFor(onToast(mActivityTestRule.getActivity(),
withText(R.string.crash_before_sending)), TOAST_DELAY)
.check(matches(isDisplayed()));
onView(isRoot()).perform(waitFor(CHECK_DELAY));
waitFor(onToast(mActivityTestRule.getActivity(), anyOf(
withContainsText(R.string.crash_sent_succeeded),
withText(R.string.crash_sent_failed))), TOAST_DELAY)
.check(matches(isDisplayed()));
}
private ViewInteraction onCrash(@StringRes int titleId) {
return onData(allOf(instanceOf(CrashTestHelper.Crash.class), withCrashTitle(titleId)))
.perform();
}
private class CrashFailureHandler implements FailureHandler {
Throwable uncaughtException;
@Override
public void handle(Throwable error, Matcher<View> viewMatcher) {
uncaughtException = error instanceof EspressoException ? error.getCause() : error;
/* Save exception. */
CrashesPrivateHelper.saveUncaughtException(mContext.getMainLooper().getThread(), uncaughtException);
/* Relaunch. */
relaunchActivity();
}
private void relaunchActivity() {
/* Destroy old instances. */
ActivityCompat.finishAffinity(mActivityTestRule.getActivity());
unsetInstance(AppCenter.class);
unsetInstance(Crashes.class);
/* Clear listeners. */
MainActivity.sAnalyticsListener = null;
MainActivity.sCrashesListener = null;
/* Launch activity again. */
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
mActivityTestRule.launchActivity(intent);
}
@SuppressWarnings("unchecked")
private void unsetInstance(Class clazz) {
try {
Method m = clazz.getDeclaredMethod("unsetInstance");
m.setAccessible(true);
m.invoke(null);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} |
3e01f27e47b1d5ab05684c12009ebabc4ef4b528 | 659 | java | Java | src/main/java/com/felypeganzert/cacapalavras/exception/RecursoNaoEncontradoException.java | FelypeGanzert/caca-palavras-backend-api | 14ba51b7c1201dca753dfb91fb63c56911828f6d | [
"MIT"
] | null | null | null | src/main/java/com/felypeganzert/cacapalavras/exception/RecursoNaoEncontradoException.java | FelypeGanzert/caca-palavras-backend-api | 14ba51b7c1201dca753dfb91fb63c56911828f6d | [
"MIT"
] | null | null | null | src/main/java/com/felypeganzert/cacapalavras/exception/RecursoNaoEncontradoException.java | FelypeGanzert/caca-palavras-backend-api | 14ba51b7c1201dca753dfb91fb63c56911828f6d | [
"MIT"
] | null | null | null | 24.407407 | 96 | 0.778452 | 821 | package com.felypeganzert.cacapalavras.exception;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class RecursoNaoEncontradoException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String nomeRecurso;
private String nomeCampo;
private Object valorCampo;
public RecursoNaoEncontradoException(String nomeRecurso, String nomeCampo, Object valorCampo) {
super();
this.nomeRecurso = nomeRecurso;
this.nomeCampo = nomeCampo;
this.valorCampo = valorCampo;
}
public String getMessage(){
return String.format("%s não encontrado com %s: '%s'", nomeRecurso, nomeCampo, valorCampo);
}
} |
3e01f27ee0cb288d12566728e5ee6cd9079340d9 | 2,438 | java | Java | insight/insight-camel/src/main/java/org/fusesource/insight/camel/breadcrumb/BreadcrumbsProcessor.java | gnodet/fuse | 6d5640333d506d4137f32abe4903c4c71526296b | [
"Apache-2.0"
] | 1 | 2016-03-31T09:17:06.000Z | 2016-03-31T09:17:06.000Z | insight/insight-camel/src/main/java/org/fusesource/insight/camel/breadcrumb/BreadcrumbsProcessor.java | gnodet/fuse | 6d5640333d506d4137f32abe4903c4c71526296b | [
"Apache-2.0"
] | 1 | 2020-02-11T01:52:36.000Z | 2020-02-11T01:52:36.000Z | insight/insight-camel/src/main/java/org/fusesource/insight/camel/breadcrumb/BreadcrumbsProcessor.java | gnodet/fuse | 6d5640333d506d4137f32abe4903c4c71526296b | [
"Apache-2.0"
] | 6 | 2015-10-23T01:08:22.000Z | 2018-08-31T06:34:56.000Z | 33.861111 | 79 | 0.700164 | 822 | /**
* Copyright (C) FuseSource, Inc.
* http://fusesource.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.fusesource.insight.camel.breadcrumb;
import org.apache.camel.AsyncCallback;
import org.apache.camel.DelegateProcessor;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.processor.DelegateAsyncProcessor;
import org.apache.camel.processor.aggregate.AggregateProcessor;
import org.apache.camel.processor.aggregate.AggregationStrategy;
import org.fusesource.insight.camel.base.SwitchableContainerStrategy;
import java.util.Set;
/**
*
*/
public class BreadcrumbsProcessor extends DelegateAsyncProcessor {
private final SwitchableContainerStrategy breadcrumbs;
public BreadcrumbsProcessor(Breadcrumbs breadcrumbs, Processor processor) {
super(processor);
this.breadcrumbs = breadcrumbs;
for (Processor proc = processor; proc != null;) {
if (proc instanceof AggregateProcessor) {
AggregateProcessor ap = (AggregateProcessor) proc;
ap.setAggregationStrategy(wrap(ap.getAggregationStrategy()));
}
if (proc instanceof DelegateProcessor) {
proc = ((DelegateProcessor) proc).getProcessor();
} else {
proc = null;
}
}
}
protected AggregationStrategy wrap(AggregationStrategy strategy) {
return new BreadcrumbAggregationStrategy(strategy);
}
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
if (breadcrumbs.isEnabled(exchange)) {
Set<String> breadcrumbs = Breadcrumbs.getBreadcrumbs(exchange);
breadcrumbs.add(exchange.getExchangeId());
}
return processor.process(exchange, callback);
}
@Override
public String toString() {
return "Breadcrumbs[" + processor + "]";
}
}
|
3e01f29b2e17956bc6779c5b9b548ce0af348552 | 631 | java | Java | src/main/java/org/xcsp/modeler/problems/Riddle5.java | bytecar/XCSP3-Solver | 3052a7aa3aac47e2a0c3503fc3040edb3f81cc0a | [
"MIT"
] | null | null | null | src/main/java/org/xcsp/modeler/problems/Riddle5.java | bytecar/XCSP3-Solver | 3052a7aa3aac47e2a0c3503fc3040edb3f81cc0a | [
"MIT"
] | null | null | null | src/main/java/org/xcsp/modeler/problems/Riddle5.java | bytecar/XCSP3-Solver | 3052a7aa3aac47e2a0c3503fc3040edb3f81cc0a | [
"MIT"
] | null | null | null | 26.25 | 155 | 0.688889 | 823 | /**
* AbsCon - Copyright (c) 2017, CRIL-CNRS - [email protected]
*
* All rights reserved.
*
* This program and the accompanying materials are made available under the terms of the CONTRAT DE LICENCE DE LOGICIEL LIBRE CeCILL which accompanies this
* distribution, and is available at http://www.cecill.info
*/
package org.xcsp.modeler.problems;
import org.xcsp.common.IVar.Var;
import org.xcsp.modeler.ProblemAPI;
class Riddle5 implements ProblemAPI {
@Override
public void model() {
Var x[] = array("x", size(4), i -> dom(range(15)));
forall(range(3), i -> equal(add(x[i], 1), x[i + 1]));
sum(x, EQ, 14);
}
}
|
3e01f32b5b845ea25fcc17ecfba2ca256140e793 | 1,531 | java | Java | CS307_Pro/dbproj/src/main/java/com/sustech/dbproj/domain/Order.java | zc-BEAR/Projs_repo | bbbcc83992f3e837dfb21615bb8e81d86f397f83 | [
"MIT"
] | null | null | null | CS307_Pro/dbproj/src/main/java/com/sustech/dbproj/domain/Order.java | zc-BEAR/Projs_repo | bbbcc83992f3e837dfb21615bb8e81d86f397f83 | [
"MIT"
] | null | null | null | CS307_Pro/dbproj/src/main/java/com/sustech/dbproj/domain/Order.java | zc-BEAR/Projs_repo | bbbcc83992f3e837dfb21615bb8e81d86f397f83 | [
"MIT"
] | null | null | null | 20.144737 | 55 | 0.611365 | 824 | package com.sustech.dbproj.domain;
import javax.persistence.*;
@Entity
@Table(name = "order_info")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
// @Temporal( value = TemporalType.TIMESTAMP)
private String create_time;
@ManyToOne(cascade = {CascadeType.ALL})
@JoinColumn(name = "passenger", nullable = false)
private Passenger passenger;
@ManyToOne(cascade = {CascadeType.ALL})
@JoinColumn(name = "ticket", nullable = false)
private Ticket ticket;
/**
* 订单有以下几种状态:
* -1:failed,所有操作取消的订单,座位释放
* 0:创建订单成功,锁定座位,尚未付款
* 1:付款成功,订单待执行(尚未发车)
* 2:车辆发车,订单结束
*/
@Column(nullable = false)
private Integer status;
public Order() {
}
public Integer getId() {
return id;
}
public void setId( Integer id ) {
this.id = id;
}
public String getCreate_time() {
return create_time;
}
public void setCreate_time( String create_time ) {
this.create_time = create_time;
}
public Passenger getPassenger() {
return passenger;
}
public void setPassenger( Passenger passenger ) {
this.passenger = passenger;
}
public Ticket getTicket() {
return ticket;
}
public void setTicket( Ticket ticket ) {
this.ticket = ticket;
}
public Integer getStatus() {
return status;
}
public void setStatus( Integer status ) {
this.status = status;
}
}
|
3e01f52045ff6dfa771d0045f198a8a9783d8c87 | 583 | java | Java | src/test/java/com/baitu/shop/service/AsyncTaskServiceTest.java | ChangFeng2015/spring-boot-demo-prototype | d93e91a7ef804b1ee6d63e7bae149777ef97c827 | [
"Apache-2.0"
] | null | null | null | src/test/java/com/baitu/shop/service/AsyncTaskServiceTest.java | ChangFeng2015/spring-boot-demo-prototype | d93e91a7ef804b1ee6d63e7bae149777ef97c827 | [
"Apache-2.0"
] | null | null | null | src/test/java/com/baitu/shop/service/AsyncTaskServiceTest.java | ChangFeng2015/spring-boot-demo-prototype | d93e91a7ef804b1ee6d63e7bae149777ef97c827 | [
"Apache-2.0"
] | null | null | null | 23.32 | 60 | 0.718696 | 825 | package com.baitu.shop.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.inject.Inject;
@RunWith(SpringRunner.class)
@SpringBootTest
public class AsyncTaskServiceTest {
@Inject
AsyncTaskService asyncTaskService;
@Test
public void execureAsyncTask() {
for (int i = 0; i < 10; i++) {
asyncTaskService.execureAsyncTask(i);
asyncTaskService.executeAsyncTaskPlus(i);
}
}
} |
3e01f5fbbd1418a5dc979b9f4ee3aa3bc9f9f9b5 | 1,893 | java | Java | MyRuns5/app/src/main/java/com/dartmouth/cs/myruns2/MySQLiteOpenHelper.java | lpzjerry/MyRuns | a6f3afd161f1739d95f921da5a498ecf602abda6 | [
"MIT"
] | null | null | null | MyRuns5/app/src/main/java/com/dartmouth/cs/myruns2/MySQLiteOpenHelper.java | lpzjerry/MyRuns | a6f3afd161f1739d95f921da5a498ecf602abda6 | [
"MIT"
] | null | null | null | MyRuns5/app/src/main/java/com/dartmouth/cs/myruns2/MySQLiteOpenHelper.java | lpzjerry/MyRuns | a6f3afd161f1739d95f921da5a498ecf602abda6 | [
"MIT"
] | null | null | null | 37.86 | 84 | 0.663497 | 826 | package com.dartmouth.cs.myruns2;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "records.db";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_RECORDS = "records";
public static final String COLUMN_ID = "id";
public static final String COLUMN_TYPE = "type";
public static final String COLUMN_DATE = "date";
public static final String COLUMN_DURATION = "duration";
public static final String COLUMN_DISTANCE = "distance";
public static final String COLUMN_CALORIES = "calories";
public static final String COLUMN_HEART_RATE = "heartrate";
private static MySQLiteOpenHelper instance = null;
public static MySQLiteOpenHelper getInstance(Context context) {
if (instance == null) {
instance = new MySQLiteOpenHelper(context);
}
return instance;
}
public MySQLiteOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase database) {
String sql = "create table "
+ TABLE_RECORDS + "(" + COLUMN_ID
+ " integer primary key autoincrement, "
+ COLUMN_TYPE + " text not null,"
+ COLUMN_DATE + " text not null,"
+ COLUMN_DURATION + " text not null,"
+ COLUMN_DISTANCE + " double not null,"
+ COLUMN_CALORIES + " double not null,"
+ COLUMN_HEART_RATE + " text not null);";
database.execSQL(sql);
}
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
Log.d("pengze", "onUpgrade() called");
}
} |
3e01f61950f77944bdb0797e417629810f13d9e5 | 4,231 | java | Java | src/main/java/com/nike/cerberus/operation/rds/CleanUpRdsSnapshotsOperation.java | Nike-Inc/cerberus-lifecycle-cli | e870a66c6d0be5ed136bc2a1432271cb07b627e5 | [
"Apache-2.0"
] | 16 | 2016-11-18T18:30:51.000Z | 2020-02-07T17:26:07.000Z | src/main/java/com/nike/cerberus/operation/rds/CleanUpRdsSnapshotsOperation.java | Nike-Inc/cerberus-lifecycle-cli | e870a66c6d0be5ed136bc2a1432271cb07b627e5 | [
"Apache-2.0"
] | 25 | 2016-11-20T06:14:14.000Z | 2021-04-02T22:40:37.000Z | src/main/java/com/nike/cerberus/operation/rds/CleanUpRdsSnapshotsOperation.java | Nike-Inc/cerberus-lifecycle-cli | e870a66c6d0be5ed136bc2a1432271cb07b627e5 | [
"Apache-2.0"
] | 10 | 2016-11-18T18:30:53.000Z | 2020-07-13T03:29:50.000Z | 42.31 | 125 | 0.650674 | 827 | /*
* Copyright (c) 2019 Nike, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nike.cerberus.operation.rds;
import com.amazonaws.regions.Regions;
import com.nike.cerberus.command.rds.CleanUpRdsSnapshotsCommand;
import com.nike.cerberus.domain.environment.Stack;
import com.nike.cerberus.operation.Operation;
import com.nike.cerberus.service.CloudFormationService;
import com.nike.cerberus.service.RdsService;
import com.nike.cerberus.store.ConfigStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Named;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import static com.nike.cerberus.module.CerberusModule.ENV_NAME;
public class CleanUpRdsSnapshotsOperation implements Operation<CleanUpRdsSnapshotsCommand> {
private final Logger log = LoggerFactory.getLogger(getClass());
private final ConfigStore configStore;
private final String environmentName;
private final RdsService rdsService;
private final CloudFormationService cloudFormationService;
@Inject
public CleanUpRdsSnapshotsOperation(ConfigStore configStore,
@Named(ENV_NAME) String environmentName,
RdsService rdsService,
CloudFormationService cloudFormationService) {
this.configStore = configStore;
this.environmentName = environmentName;
this.rdsService = rdsService;
this.cloudFormationService = cloudFormationService;
}
@Override
public void run(CleanUpRdsSnapshotsCommand command) {
Regions primaryRegion = configStore.getPrimaryRegion();
Date oldestAcceptableSnapshotCreationDate = Date.from(Instant.now().minus(command.getDays(), ChronoUnit.DAYS));
// Go through each config region
configStore.getConfigEnabledRegions().stream()
// and filter out the primary region, because rds cleans those snapshots automatically
.filter(region -> ! region.equals(primaryRegion))
.forEach(region ->
// in each region list all the snapshots
rdsService.getDbSnapshots(region).stream()
// filter out snapshots that are not from the cluster / environment under question
// and are older than the number of acceptable days
.filter(snapshot ->
rdsService.wasSnapshotGeneratedFromCmsCluster(snapshot) &&
snapshot.getSnapshotCreateTime().before(oldestAcceptableSnapshotCreationDate))
// delete the snapshots
.forEach(snapshot -> {
if (command.isDryRun()) {
log.info("snapshot: {} with creation date: {} in region: {}",
snapshot.getDBClusterSnapshotIdentifier(), snapshot.getSnapshotCreateTime(), region);
} else {
rdsService.deleteSnapshot(snapshot, region);
}
}));
}
@Override
public boolean isRunnable(CleanUpRdsSnapshotsCommand command) {
boolean isRunnable = true;
if (! cloudFormationService.isStackPresent(configStore.getPrimaryRegion(),
Stack.DATABASE.getFullName(environmentName))) {
log.error("The Database stack must exist in the primary region in order to have snapshots to clean up");
isRunnable = false;
}
return isRunnable;
}
}
|
3e01f6e85bc19d34e0aabd0511fb1e246f2e9968 | 5,255 | java | Java | conjure-java-undertow-runtime/src/test/java/com/palantir/conjure/java/undertow/runtime/SerializerRegistryTest.java | jamesthomp/conjure-java | 8a6ab763755d0e1fad7e62a77b6a290ff8c16c4a | [
"Apache-2.0"
] | null | null | null | conjure-java-undertow-runtime/src/test/java/com/palantir/conjure/java/undertow/runtime/SerializerRegistryTest.java | jamesthomp/conjure-java | 8a6ab763755d0e1fad7e62a77b6a290ff8c16c4a | [
"Apache-2.0"
] | null | null | null | conjure-java-undertow-runtime/src/test/java/com/palantir/conjure/java/undertow/runtime/SerializerRegistryTest.java | jamesthomp/conjure-java | 8a6ab763755d0e1fad7e62a77b6a290ff8c16c4a | [
"Apache-2.0"
] | null | null | null | 39.511278 | 118 | 0.714367 | 828 | /*
* (c) Copyright 2018 Palantir 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
*
* 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.palantir.conjure.java.undertow.runtime;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.google.common.reflect.TypeToken;
import com.palantir.conjure.java.undertow.HttpServerExchanges;
import com.palantir.logsafe.exceptions.SafeIllegalArgumentException;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;
import java.io.InputStream;
import java.io.OutputStream;
import org.junit.Test;
public class SerializerRegistryTest {
@Test
public void testRequestContentType() {
Serializer json = new StubSerializer("application/json");
Serializer plain = new StubSerializer("text/plain");
HttpServerExchange exchange = HttpServerExchanges.createStub();
exchange.getRequestHeaders().put(Headers.CONTENT_TYPE, "text/plain");
ConjureSerializerRegistry serializers = new ConjureSerializerRegistry(json, plain);
Serializer serializer = serializers.getRequestDeserializer(exchange);
assertThat(serializer).isSameAs(plain);
}
@Test
public void testRequestNoContentType() {
HttpServerExchange exchange = HttpServerExchanges.createStub();
ConjureSerializerRegistry serializers = new ConjureSerializerRegistry(new StubSerializer("application/json"));
assertThatThrownBy(() -> serializers.getRequestDeserializer(exchange))
.isInstanceOf(SafeIllegalArgumentException.class)
.hasMessageContaining("Request is missing Content-Type header");
}
@Test
public void testUnsupportedRequestContentType() {
HttpServerExchange exchange = HttpServerExchanges.createStub();
exchange.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/unknown");
ConjureSerializerRegistry serializers = new ConjureSerializerRegistry(new StubSerializer("application/json"));
assertThatThrownBy(() -> serializers.getRequestDeserializer(exchange))
.isInstanceOf(FrameworkException.class)
.hasMessageContaining("Unsupported Content-Type");
}
@Test
public void testResponseContentType() {
Serializer json = new StubSerializer("application/json");
Serializer plain = new StubSerializer("text/plain");
HttpServerExchange exchange = HttpServerExchanges.createStub();
exchange.getRequestHeaders().put(Headers.ACCEPT, "text/plain");
ConjureSerializerRegistry serializers = new ConjureSerializerRegistry(json, plain);
Serializer serializer = serializers.getResponseSerializer(exchange);
assertThat(serializer).isSameAs(plain);
}
@Test
public void testResponseNoContentType() {
Serializer json = new StubSerializer("application/json");
Serializer plain = new StubSerializer("text/plain");
HttpServerExchange exchange = HttpServerExchanges.createStub();
ConjureSerializerRegistry serializers = new ConjureSerializerRegistry(json, plain);
Serializer serializer = serializers.getResponseSerializer(exchange);
assertThat(serializer).isSameAs(json);
}
@Test
public void testResponseUnknownContentType() {
Serializer json = new StubSerializer("application/json");
Serializer plain = new StubSerializer("text/plain");
HttpServerExchange exchange = HttpServerExchanges.createStub();
exchange.getRequestHeaders().put(Headers.ACCEPT, "application/unknown");
ConjureSerializerRegistry serializers = new ConjureSerializerRegistry(json, plain);
Serializer serializer = serializers.getResponseSerializer(exchange);
assertThat(serializer).isSameAs(json);
}
public static final class StubSerializer implements Serializer {
private final String contentType;
StubSerializer(String contentType) {
this.contentType = contentType;
}
@Override
public void serialize(Object value, OutputStream output) {
throw new UnsupportedOperationException();
}
@Override
public <T> T deserialize(InputStream input, TypeToken<T> type) {
throw new UnsupportedOperationException();
}
@Override
public String getContentType() {
return contentType;
}
@Override
public boolean supportsContentType(String input) {
return contentType.equals(input);
}
@Override
public String toString() {
return "StubSerializer{" + contentType + '}';
}
}
}
|
3e01f7d56bab24eebca627eb2a5ef518783c9bdb | 4,133 | java | Java | presto-main/src/main/java/com/facebook/presto/sql/planner/plan/ExchangeNode.java | andytinycat/presto | 48b632cb8c411461198869bd210a5649a27cefe8 | [
"Apache-2.0"
] | 8 | 2017-09-27T17:10:24.000Z | 2020-07-14T20:15:54.000Z | presto-main/src/main/java/com/facebook/presto/sql/planner/plan/ExchangeNode.java | andytinycat/presto | 48b632cb8c411461198869bd210a5649a27cefe8 | [
"Apache-2.0"
] | 2 | 2016-04-18T21:53:43.000Z | 2019-02-15T22:44:50.000Z | presto-main/src/main/java/com/facebook/presto/sql/planner/plan/ExchangeNode.java | bowlofstew/presto | 5d7ad2393ebd34d9a3730ed94f22fb4145cc4454 | [
"Apache-2.0"
] | 4 | 2018-03-22T11:09:02.000Z | 2020-02-05T21:24:32.000Z | 28.902098 | 138 | 0.646746 | 829 | /*
* 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.plan;
import com.facebook.presto.sql.planner.Symbol;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableList;
import javax.annotation.concurrent.Immutable;
import java.util.List;
import java.util.Optional;
import static com.google.common.base.Preconditions.checkNotNull;
@Immutable
public class ExchangeNode
extends PlanNode
{
public static enum Type
{
GATHER,
REPARTITION,
REPLICATE
}
private final Type type;
private final List<Symbol> outputs;
private final List<PlanNode> sources;
private final List<Symbol> partitionKeys;
private final Optional<Symbol> hashSymbol;
// for each source, the list of inputs corresponding to each output
private final List<List<Symbol>> inputs;
@JsonCreator
public ExchangeNode(
@JsonProperty("id") PlanNodeId id,
@JsonProperty("type") Type type,
@JsonProperty("partitionKeys") List<Symbol> partitionKeys,
@JsonProperty("hashSymbol") Optional<Symbol> hashSymbol,
@JsonProperty("sources") List<PlanNode> sources,
@JsonProperty("outputs") List<Symbol> outputs,
@JsonProperty("inputs") List<List<Symbol>> inputs)
{
super(id);
checkNotNull(type, "type is null");
checkNotNull(sources, "sources is null");
checkNotNull(partitionKeys, "partitionKeys is null");
checkNotNull(hashSymbol, "hashSymbol is null");
checkNotNull(outputs, "outputs is null");
checkNotNull(inputs, "inputs is null");
this.type = type;
this.sources = sources;
this.partitionKeys = ImmutableList.copyOf(partitionKeys);
this.hashSymbol = hashSymbol;
this.outputs = ImmutableList.copyOf(outputs);
this.inputs = ImmutableList.copyOf(inputs);
}
public static ExchangeNode partitionedExchange(PlanNodeId id, PlanNode child, List<Symbol> partitionKeys, Optional<Symbol> hashSymbol)
{
return new ExchangeNode(
id,
ExchangeNode.Type.REPARTITION,
partitionKeys,
hashSymbol,
ImmutableList.of(child),
child.getOutputSymbols(),
ImmutableList.of(child.getOutputSymbols()));
}
public static ExchangeNode gatheringExchange(PlanNodeId id, PlanNode child)
{
return new ExchangeNode(
id,
ExchangeNode.Type.GATHER,
ImmutableList.of(),
Optional.<Symbol>empty(),
ImmutableList.of(child),
child.getOutputSymbols(),
ImmutableList.of(child.getOutputSymbols()));
}
@JsonProperty
public Type getType()
{
return type;
}
@Override
public List<PlanNode> getSources()
{
return sources;
}
@Override
@JsonProperty("outputs")
public List<Symbol> getOutputSymbols()
{
return outputs;
}
@JsonProperty
public List<Symbol> getPartitionKeys()
{
return partitionKeys;
}
@JsonProperty
public Optional<Symbol> getHashSymbol()
{
return hashSymbol;
}
@JsonProperty
public List<List<Symbol>> getInputs()
{
return inputs;
}
@Override
public <C, R> R accept(PlanVisitor<C, R> visitor, C context)
{
return visitor.visitExchange(this, context);
}
}
|
3e01f86baedff97e58bc92171ca0eb6750b39d17 | 910 | java | Java | hbase-sdk-core_2.1/src/main/java/com/github/CCweixiao/hql/rowkey/IntRowKey.java | endlessc/hbase-sdk | 4c62d1b1b19848949350db8314ca18be7ed2e2d2 | [
"MIT"
] | null | null | null | hbase-sdk-core_2.1/src/main/java/com/github/CCweixiao/hql/rowkey/IntRowKey.java | endlessc/hbase-sdk | 4c62d1b1b19848949350db8314ca18be7ed2e2d2 | [
"MIT"
] | null | null | null | hbase-sdk-core_2.1/src/main/java/com/github/CCweixiao/hql/rowkey/IntRowKey.java | endlessc/hbase-sdk | 4c62d1b1b19848949350db8314ca18be7ed2e2d2 | [
"MIT"
] | null | null | null | 22.75 | 57 | 0.695604 | 830 | package com.github.CCweixiao.hql.rowkey;
import com.github.CCwexiao.dsl.client.RowKey;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.hadoop.hbase.util.Bytes;
/**
* @author leojie 2020/11/28 12:40 下午
*/
public class IntRowKey implements RowKey {
private final int value;
public IntRowKey(int value) {
this.value = value;
}
@Override
public byte[] toBytes() {
return Bytes.toBytes(value);
}
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
|
3e01f8ff732783f1999216f1159cd093a0478d04 | 42,813 | java | Java | app/src/main/java/me/rain/liteforfacebook/MainActivity.java | raininsummer/Messenger-for-Facebook | 00747332bd8863998ffd9143659911cd9bd7b274 | [
"MIT"
] | 3 | 2017-03-15T22:00:41.000Z | 2018-08-25T10:45:37.000Z | app/src/main/java/me/rain/liteforfacebook/MainActivity.java | raininsummer/Messenger-for-Facebook | 00747332bd8863998ffd9143659911cd9bd7b274 | [
"MIT"
] | 1 | 2016-11-10T15:41:58.000Z | 2016-11-10T15:41:58.000Z | app/src/main/java/me/rain/liteforfacebook/MainActivity.java | raininsummer/Messenger-for-Facebook | 00747332bd8863998ffd9143659911cd9bd7b274 | [
"MIT"
] | null | null | null | 49.956826 | 442 | 0.633452 | 831 | package me.rain.liteforfacebook;
import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.anjlab.android.iab.v3.BillingProcessor;
import com.anjlab.android.iab.v3.TransactionDetails;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginBehavior;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.github.clans.fab.FloatingActionMenu;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.greysonparrelli.permiso.Permiso;
import com.mikepenz.actionitembadge.library.ActionItemBadge;
import com.mikepenz.actionitembadge.library.utils.BadgeStyle;
import com.squareup.picasso.Picasso;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import im.delight.android.webview.AdvancedWebView;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, BillingProcessor.IBillingHandler {
static final String FACEBOOK_URL_BASE = "https://m.facebook.com/";
private static final String FACEBOOK_URL_BASE_ENCODED = "https%3A%2F%2Fm.facebook.com%2F";
// private static final String FACEBOOK_URL_BASE_ENCODED_R = "https%3A%2F%2Ffacebook.com%2F";
private static final List<String> HOSTNAMES = Arrays.asList("facebook.com", "*.facebook.com", "*.fbcdn.net", "*.akamaihd.net");
private final BadgeStyle BADGE_SIDE_FULL = new BadgeStyle(BadgeStyle.Style.LARGE, R.layout.menu_badge_full, R.color.colorAccent, R.color.colorAccent, Color.WHITE);
// Members
SwipeRefreshLayout swipeView;
NavigationView mNavigationView;
View mCoordinatorLayoutView;
private FloatingActionMenu mMenuFAB;
private AdvancedWebView mWebView;
BillingProcessor bp;
private final View.OnClickListener mFABClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.textNewsFeed:
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('%23feed_jewel%20%3E%20a').click()%7Dcatch(_)%7Bwindow.location.href%3D'" + FACEBOOK_URL_BASE_ENCODED + "home.php'%7D%7D)()");
break;
case R.id.textFAB:
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('button%5Bname%3D%22view_overview%22%5D').click()%7Dcatch(_)%7Bwindow.location.href%3D%22" + FACEBOOK_URL_BASE_ENCODED + "%3Fpageload%3Dcomposer%22%7D%7D)()");
break;
case R.id.photoFAB:
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('button%5Bname%3D%22view_photo%22%5D').click()%7Dcatch(_)%7Bwindow.location.href%3D%22" + FACEBOOK_URL_BASE_ENCODED + "%3Fpageload%3Dcomposer_photo%22%7D%7D)()");
break;
case R.id.checkinFAB:
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('button%5Bname%3D%22view_location%22%5D').click()%7Dcatch(_)%7Bwindow.location.href%3D%22" + FACEBOOK_URL_BASE_ENCODED + "%3Fpageload%3Dcomposer_checkin%22%7D%7D)()");
break;
default:
break;
}
mMenuFAB.close(true);
}
};
private MenuItem mNotificationButton;
private MenuItem mMessageButton;
private CallbackManager callbackManager;
private Snackbar loginSnackbar = null;
@SuppressWarnings("FieldCanBeLocal") // Will be garbage collected as a local variable
private SharedPreferences.OnSharedPreferenceChangeListener listener;
private boolean requiresReload = false;
private String mUserLink = null;
private SharedPreferences mPreferences;
private ImageView profileImage;
private ImageView profileCover;
private TextView profileName;
private AdView adView;
private String PRODUCT_ID = "removeads";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this.getApplicationContext());
setContentView(R.layout.activity_main);
Permiso.getInstance().setActivity(this);
// PackageInfo info;
// try {
// info = getPackageManager().getPackageInfo("me.rain.liteforfacebook", PackageManager.GET_SIGNATURES);
// for (Signature signature : info.signatures) {
// MessageDigest md;
// md = MessageDigest.getInstance("SHA");
// md.update(signature.toByteArray());
// String something = new String(Base64.encode(md.digest(), 0));
// //String something = new String(Base64.encodeBytes(md.digest()));
// Log.e("hash key", something);
// Snackbar.make(mCoordinatorLayoutView, something, Snackbar.LENGTH_LONG).show();
// }
// } catch (PackageManager.NameNotFoundException e1) {
// Log.e("name not found", e1.toString());
// } catch (NoSuchAlgorithmException e) {
// Log.e("no such an algorithm", e.toString());
// } catch (Exception e) {
// Log.e("exception", e.toString());
// }
// Preferences
PreferenceManager.setDefaultValues(this, R.xml.settings, false);
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
switch (key) {
case SettingsActivity.KEY_PREF_JUMP_TOP_BUTTON:
mNavigationView.getMenu().findItem(R.id.nav_jump_top).setVisible(prefs.getBoolean(key, false));
break;
case SettingsActivity.KEY_PREF_STOP_IMAGES:
mWebView.getSettings().setBlockNetworkImage(prefs.getBoolean(key, false));
requiresReload = true;
break;
case SettingsActivity.KEY_PREF_BACK_BUTTON:
mNavigationView.getMenu().findItem(R.id.nav_back).setVisible(prefs.getBoolean(key, false));
break;
case SettingsActivity.KEY_PREF_MESSAGING:
mNavigationView.getMenu().findItem(R.id.nav_messages).setVisible(prefs.getBoolean(key, false));
break;
case SettingsActivity.KEY_PREF_LOCATION:
if (prefs.getBoolean(key, false)) {
Permiso.getInstance().requestPermissions(new Permiso.IOnPermissionResult() {
@Override
public void onPermissionResult(Permiso.ResultSet resultSet) {
if (resultSet.areAllPermissionsGranted()) {
mWebView.setGeolocationEnabled(true);
} else {
Snackbar.make(mCoordinatorLayoutView, R.string.permission_denied, Snackbar.LENGTH_SHORT).show();
}
}
@Override
public void onRationaleRequested(Permiso.IOnRationaleProvided callback, String... permissions) {
// TODO Permiso.getInstance().showRationaleInDialog("Title", "Message", null, callback);
callback.onRationaleProvided();
}
}, Manifest.permission.ACCESS_FINE_LOCATION);
}
break;
case SettingsActivity.KEY_PREF_MOST_RECENT_MENU:
boolean most_recent = prefs.getBoolean(key, true);
mNavigationView.getMenu().findItem(R.id.nav_news).setVisible(!most_recent);
mNavigationView.getMenu().findItem(R.id.nav_top_stories).setVisible(most_recent);
mNavigationView.getMenu().findItem(R.id.nav_most_recent).setVisible(most_recent);
requiresReload = true;
break;
case SettingsActivity.KEY_PREF_FAB_SCROLL:
if (!mPreferences.getBoolean(SettingsActivity.KEY_PREF_FAB_BTN, false)) {
mMenuFAB.showMenuButton(true);
} else {
mMenuFAB.hideMenuButton(true);
}
break;
case SettingsActivity.KEY_PREF_FAB_BTN:
mMenuFAB.hideMenuButton(true);
break;
case SettingsActivity.KEY_PREF_HIDE_EDITOR:
requiresReload = true;
break;
case SettingsActivity.KEY_PREF_HIDE_SPONSORED:
requiresReload = true;
break;
case SettingsActivity.KEY_PREF_HIDE_BIRTHDAYS:
requiresReload = true;
break;
case SettingsActivity.KEY_PREF_NOTIFICATIONS_ENABLED:
PollReceiver.scheduleAlarms(getApplicationContext(), false);
break;
case SettingsActivity.KEY_PREF_NOTIFICATION_INTERVAL:
PollReceiver.scheduleAlarms(getApplicationContext(), false);
break;
default:
break;
}
}
};
mPreferences.registerOnSharedPreferenceChangeListener(listener);
// Setup the toolbar
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
// Setup the DrawLayout
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
mNavigationView = (NavigationView) findViewById(R.id.nav_view);
mNavigationView.setNavigationItemSelectedListener(this);
// Create the badge for messages
ActionItemBadge.update(this, mNavigationView.getMenu().findItem(R.id.nav_messages), (Drawable) null, BADGE_SIDE_FULL, Integer.MIN_VALUE);
ActionItemBadge.update(this, mNavigationView.getMenu().findItem(R.id.nav_friendreq), (Drawable) null, BADGE_SIDE_FULL, Integer.MIN_VALUE);
// Hide buttons if they are disabled
if (!mPreferences.getBoolean(SettingsActivity.KEY_PREF_MESSAGING, false)) {
mNavigationView.getMenu().findItem(R.id.nav_messages).setVisible(false);
}
if (!mPreferences.getBoolean(SettingsActivity.KEY_PREF_JUMP_TOP_BUTTON, false)) {
mNavigationView.getMenu().findItem(R.id.nav_jump_top).setVisible(false);
}
if (!mPreferences.getBoolean(SettingsActivity.KEY_PREF_BACK_BUTTON, false)) {
mNavigationView.getMenu().findItem(R.id.nav_back).setVisible(false);
}
boolean most_recent = mPreferences.getBoolean(SettingsActivity.KEY_PREF_MOST_RECENT_MENU, true);
mNavigationView.getMenu().findItem(R.id.nav_news).setVisible(!most_recent);
mNavigationView.getMenu().findItem(R.id.nav_top_stories).setVisible(most_recent);
mNavigationView.getMenu().findItem(R.id.nav_most_recent).setVisible(most_recent);
// Bind the Coordinator to member
mCoordinatorLayoutView = findViewById(R.id.coordinatorLayout);
// Start the Swipe to reload listener
swipeView = (SwipeRefreshLayout) findViewById(R.id.swipeLayout);
swipeView.setColorSchemeResources(R.color.colorPrimary);
swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
mWebView.reload();
}
});
// Inflate the FAB menu
mMenuFAB = (FloatingActionMenu) findViewById(R.id.menuFAB);
// Nasty hack to get the FAB menu button
mMenuFAB.getChildAt(4).setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
mMenuFAB.hideMenu(true);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Show your View after 3 seconds
mMenuFAB.showMenu(true);
}
}, 3000);
return false;
}
});
findViewById(R.id.textNewsFeed).setOnClickListener(mFABClickListener);
findViewById(R.id.textFAB).setOnClickListener(mFABClickListener);
findViewById(R.id.photoFAB).setOnClickListener(mFABClickListener);
findViewById(R.id.checkinFAB).setOnClickListener(mFABClickListener);
adView = (AdView) findViewById(R.id.fragment_main_adview);
// Load the WebView
mWebView = (AdvancedWebView) findViewById(R.id.webview);
mWebView.addPermittedHostnames(HOSTNAMES);
mWebView.setGeolocationEnabled(mPreferences.getBoolean(SettingsActivity.KEY_PREF_LOCATION, false));
mWebView.setListener(this, new WebViewListener(this, mWebView));
mWebView.addJavascriptInterface(new JavaScriptInterfaces(this), "android");
registerForContextMenu(mWebView);
mWebView.getSettings().setBlockNetworkImage(mPreferences.getBoolean(SettingsActivity.KEY_PREF_STOP_IMAGES, false));
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDisplayZoomControls(false);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
// Impersonate iPhone to prevent advertising garbage
mWebView.getSettings().setUserAgentString("Mozilla/5.0 (BB10; Touch) AppleWebKit/537.1+ (KHTML, like Gecko) Version/10.0.0.1337 Mobile Safari/537.1+");
// Long press
registerForContextMenu(mWebView);
mWebView.setLongClickable(true);
mWebView.setWebChromeClient(new CustomWebChromeClient(this, mWebView, (FrameLayout) findViewById(R.id.fullscreen_custom_content)));
// Add OnClick listener to Profile picture
profileCover = (ImageView) mNavigationView.getHeaderView(0).findViewById(R.id.profile_cover);
profileName = (TextView) mNavigationView.getHeaderView(0).findViewById(R.id.profile_name);
profileImage = (ImageView) mNavigationView.getHeaderView(0).findViewById(R.id.profile_picture);
profileImage.setClickable(true);
profileImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mUserLink != null) {
drawer.closeDrawers();
mWebView.loadUrl(mUserLink);
}
}
});
callbackManager = CallbackManager.Factory.create();
FacebookCallback<LoginResult> loginResult = new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
mWebView.loadUrl(chooseUrl());
updateUserInfo();
}
@Override
public void onCancel() {
checkLoggedInState();
}
@Override
public void onError(FacebookException error) {
Snackbar.make(mCoordinatorLayoutView, R.string.error_login, Snackbar.LENGTH_LONG).show();
Log.e(Helpers.LogTag, error.toString());
LoginManager.getInstance().logOut();
checkLoggedInState();
}
};
LoginManager.getInstance().setLoginBehavior(LoginBehavior.WEB_ONLY);
LoginManager.getInstance().registerCallback(callbackManager, loginResult);
if (checkLoggedInState()) {
mWebView.loadUrl(chooseUrl());
updateUserInfo();
}
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice(getString(R.string.admob_test_device_id))
.build();
adView.loadAd(adRequest);
updateView();
bp = new BillingProcessor(this, "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApwZHWZCnrQD3dCySU6+BcJ/HRMqYWxy3senidFz9Qvge2c+tMn5XgslngPcRUlsp6HMQv9RfygW86zCcB683TcOfG4voAfWEKO0FB040uDxaR/l6YJ8f8oxeIuBIExCnDg4FQfEkFcgUaLstfui6I3ea/vgS58iAaSN2CzGeZ5+UZGEYP2yIX8rWkhDf8I2n7r9+8hHK/u/WXKq+VlHbX7wUiSdy9Xs0j82NZOr6koWJ3q69GQz7k4CBjlz9vAmWTSdG5sTIvF3N5HUYBj/3G1AEj5wiVl70GGuNumhjrE5xQxo/RaIgroja79dOU8HEvZ6elCl6M7WjIEVpq2wNeQIDAQAB", this);
}
private void updateView() {
// Hide Ads
if (mPreferences.getBoolean(SettingsActivity.KEY_PREF_ADS, false)) {
adView.setVisibility(View.GONE);
} else {
adView.setVisibility(View.VISIBLE);
}
}
@Override
protected void onResume() {
super.onResume();
mWebView.onResume();
Permiso.getInstance().setActivity(this);
// Check if we need to show a page reload snackbar
if (requiresReload) {
Snackbar reloadSnackbar = Snackbar.make(mCoordinatorLayoutView, R.string.hide_editor_newsfeed_snackbar, Snackbar.LENGTH_LONG);
reloadSnackbar.setAction(R.string.menu_refresh, new View.OnClickListener() {
@Override
public void onClick(View v) {
mWebView.reload();
}
});
reloadSnackbar.show();
requiresReload = false;
}
registerForContextMenu(mWebView);
}
@Override
protected void onDestroy() {
mWebView.onDestroy();
if (bp != null)
bp.release();
super.onDestroy();
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
if (!bp.handleActivityResult(requestCode, resultCode, data))
super.onActivityResult(requestCode, resultCode, data);
// super.onActivityResult(requestCode, resultCode, data);
mWebView.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Permiso.getInstance().onRequestPermissionResult(requestCode, permissions, grantResults);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
mNotificationButton = menu.findItem(R.id.action_notifications);
mMessageButton = menu.findItem(R.id.action_message);
ActionItemBadge.update(this, mNotificationButton, ResourcesCompat.getDrawable(getResources(), R.drawable.ic_menu_notifications, null), ActionItemBadge.BadgeStyles.RED, Integer.MIN_VALUE);
ActionItemBadge.update(this, mMessageButton, ResourcesCompat.getDrawable(getResources(), R.drawable.ic_menu_messages, null), ActionItemBadge.BadgeStyles.RED, Integer.MIN_VALUE);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here
int id = item.getItemId();
if (id == R.id.action_notifications) {
// Load the notification page
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('%23notifications_jewel%20%3E%20a').click()%7Dcatch(_)%7Bwindow.location.href%3D'" + FACEBOOK_URL_BASE_ENCODED + "notifications.php'%7D%7D)()");
Helpers.uncheckRadioMenu(mNavigationView.getMenu());
} else if (id == R.id.action_message) {
mWebView.loadUrl("https://m.facebook.com/messages/?more");
}
// Update the notifications
JavaScriptHelpers.updateNums(mWebView);
return super.onOptionsItemSelected(item);
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
switch (item.getItemId()) {
case R.id.nav_news:
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('%23feed_jewel%20%3E%20a').click()%7Dcatch(_)%7Bwindow.location.href%3D'" + FACEBOOK_URL_BASE_ENCODED + "home.php'%7D%7D)()");
item.setChecked(true);
case R.id.nav_top_stories:
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('a%5Bhref*%3D%22%2Fhome.php%3Fsk%3Dh_nor%22%5D').click()%7Dcatch(_)%7Bwindow.location.href%3D%22" + FACEBOOK_URL_BASE_ENCODED + "home.php%3Fsk%3Dh_nor%22%7D%7D)()");
item.setChecked(true);
break;
case R.id.nav_most_recent:
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('a%5Bhref*%3D%22%2Fhome.php%3Fsk%3Dh_chr%22%5D').click()%7Dcatch(_)%7Bwindow.location.href%3D%22" + FACEBOOK_URL_BASE_ENCODED + "home.php%3Fsk%3Dh_chr%22%7D%7D)()");
item.setChecked(true);
break;
case R.id.nav_me:
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('%23me_jewel%20%3E%20a').click()%7Dcatch(_)%7Bwindow.location.href%3D'" + FACEBOOK_URL_BASE_ENCODED + "me%27%7D%7D)()");
item.setChecked(true);
break;
case R.id.nav_friendreq:
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('%23requests_jewel%20%3E%20a').click()%7Dcatch(_)%7Bwindow.location.href%3D'" + FACEBOOK_URL_BASE_ENCODED + "friends%2Fcenter%2Frequests%2F'%7D%7D)()");
item.setChecked(true);
break;
case R.id.nav_messages:
mWebView.loadUrl("https://m.facebook.com/messages/?more");
JavaScriptHelpers.updateNums(mWebView);
item.setChecked(true);
break;
case R.id.nav_messages_requests:
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('%23messages_request_jewel%20%3E%20a').click()%7Dcatch(_)%7Bwindow.location.href%3D'" + FACEBOOK_URL_BASE_ENCODED + "messages%2F%3Ffolder%3Dpending'%7D%7D)()");
item.setChecked(true);
break;
case R.id.nav_search:
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('%23search_jewel%20%3E%20a').click()%7Dcatch(_)%7Bwindow.location.href%3D'" + FACEBOOK_URL_BASE_ENCODED + "search%2F'%7D%7D)()");
item.setChecked(true);
break;
case R.id.nav_mainmenu:
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('%23bookmarks_jewel%20%3E%20a').click()%7Dcatch(_)%7Bwindow.location.href%3D'" + FACEBOOK_URL_BASE_ENCODED + "home.php'%7D%7D)()");
item.setChecked(true);
break;
case R.id.nav_photo:
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('%23photo_jewel%20%3E%20a').click()%7Dcatch(_)%7Bwindow.location.href%3D'" + FACEBOOK_URL_BASE_ENCODED + "profile.php%3Fv%3Dphotos%26soft%3Dcomposer%27%7D%7D)()");
item.setChecked(true);
break;
case R.id.nav_trending:
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('%23trending_jewel%20%3E%20a').click()%7Dcatch(_)%7Bwindow.location.href%3D'" + FACEBOOK_URL_BASE_ENCODED + "search%2Ftrending-news%2F%3Fref%3Dbookmark%27%7D%7D)()");
item.setChecked(true);
break;
case R.id.nav_online_friend:
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('%23online_friend_jewel%20%3E%20a').click()%7Dcatch(_)%7Bwindow.location.href%3D'" + FACEBOOK_URL_BASE_ENCODED + "buddylist.php%27%7D%7D)()");
item.setChecked(true);
break;
case R.id.nav_group:
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('%23groups_jewel%20%3E%20a').click()%7Dcatch(_)%7Bwindow.location.href%3D'" + FACEBOOK_URL_BASE_ENCODED + "groups%2F%3Fcategory%3Dmembership%27%7D%7D)()");
item.setChecked(true);
break;
case R.id.nav_page:
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('%23page_jewel%20%3E%20a').click()%7Dcatch(_)%7Bwindow.location.href%3D'" + FACEBOOK_URL_BASE_ENCODED + "pages%2Flaunchpoint%2F%3Ffrom%3Dpages_nav_discover%26ref%3Dbookmarks%27%7D%7D)()");
item.setChecked(true);
break;
case R.id.nav_events:
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('%23events_jewel%20%3E%20a').click()%7Dcatch(_)%7Bwindow.location.href%3D'" + FACEBOOK_URL_BASE_ENCODED + "events%27%7D%7D)()");
item.setChecked(true);
break;
case R.id.nav_on_this_day:
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('%23on_this_day_jewel%20%3E%20a').click()%7Dcatch(_)%7Bwindow.location.href%3D'" + FACEBOOK_URL_BASE_ENCODED + "onthisday%27%7D%7D)()");
item.setChecked(true);
break;
case R.id.nav_save:
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('%23saved_jewel%20%3E%20a').click()%7Dcatch(_)%7Bwindow.location.href%3D'" + FACEBOOK_URL_BASE_ENCODED + "saved%27%7D%7D)()");
item.setChecked(true);
break;
case R.id.nav_notes:
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('%23notes_jewel%20%3E%20a').click()%7Dcatch(_)%7Bwindow.location.href%3D'" + FACEBOOK_URL_BASE_ENCODED + "notes%27%7D%7D)()");
item.setChecked(true);
break;
case R.id.nav_pokes:
mWebView.loadUrl("javascript:(function()%7Btry%7Bdocument.querySelector('%23pokes_jewel%20%3E%20a').click()%7Dcatch(_)%7Bwindow.location.href%3D'" + FACEBOOK_URL_BASE_ENCODED + "pokes%27%7D%7D)()");
item.setChecked(true);
break;
case R.id.nav_fblogin:
LoginManager.getInstance().logInWithReadPermissions(this, Helpers.FB_PERMISSIONS);
break;
case R.id.nav_jump_top:
mWebView.scrollTo(0, 0);
break;
case R.id.nav_back:
mWebView.goBack();
break;
case R.id.nav_reload:
mWebView.reload();
break;
case R.id.nav_forward:
mWebView.goForward();
break;
case R.id.nav_rate:
rateApp();
break;
case R.id.nav_donate:
//TOdo
bp.purchase(this, PRODUCT_ID);
// mPreferences.edit().putBoolean(SettingsActivity.KEY_PREF_ADS, true).apply();
break;
case R.id.nav_share:
shareApp();
break;
case R.id.nav_settings:
Intent settingsActivity = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(settingsActivity);
break;
default:
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void rateApp() {
Uri uri = Uri.parse("market://details?id=com.rain.liteforfacebook");
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
// To count with Play market backstack, After pressing back button,
// to taken back to our application, we need to add following flags to intent.
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=com.rain.liteforfacebook")));
}
}
private void shareApp() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "http://play.google.com/store/apps/details?id=com.rain.liteforfacebook");
startActivity(Intent.createChooser(shareIntent, "Share App"));
}
public void setLoading(boolean loading) {
// Toggle the WebView and Spinner visibility
// mWebView.setVisibility(loading ? View.GONE : View.VISIBLE);
swipeView.setRefreshing(loading);
}
public boolean checkLoggedInState() {
if (loginSnackbar != null) {
loginSnackbar.dismiss();
}
if (AccessToken.getCurrentAccessToken() != null && Helpers.getCookie() != null) {
// Logged in, show webview
mWebView.setVisibility(View.VISIBLE);
// Hide login button
mNavigationView.getMenu().findItem(R.id.nav_fblogin).setVisible(false);
// Enable navigation buttons
mNavigationView.getMenu().setGroupEnabled(R.id.group_fbnav, true);
mNavigationView.getMenu().setGroupEnabled(R.id.group_fbnav_1, true);
mNavigationView.getMenu().setGroupEnabled(R.id.group_fbnav_2, true);
// Start the Notification service (if not already running)
PollReceiver.scheduleAlarms(getApplicationContext(), false);
return true;
} else {
// Not logged in (possibly logged into Facebook OAuth and/or webapp)
loginSnackbar = Helpers.loginPrompt(mCoordinatorLayoutView);
setLoading(false);
mWebView.setVisibility(View.GONE);
// Show login button
mNavigationView.getMenu().findItem(R.id.nav_fblogin).setVisible(true);
// Disable navigation buttons
mNavigationView.getMenu().setGroupEnabled(R.id.group_fbnav, false);
mNavigationView.getMenu().setGroupEnabled(R.id.group_fbnav_1, false);
mNavigationView.getMenu().setGroupEnabled(R.id.group_fbnav_2, false);
// Cancel the Notification service if we are logged out
PollReceiver.scheduleAlarms(getApplicationContext(), true);
// Kill the Feed URL, so we don't get the wrong notifications
mPreferences.edit().putString("feed_uri", null).apply();
return false;
}
}
private void updateUserInfo() {
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Update header
try {
String userID = object.getString("id");
mUserLink = object.getString("link");
// final View header = findViewById(R.id.header_layout);
// Set the user's name under the header
profileName.setText(object.optString("name"));
// Set the cover photo with resizing
Picasso.with(getApplicationContext()).load("https://graph.facebook.com/" + userID + "/picture?type=large").into(profileImage);
Picasso.with(getApplicationContext()).load(object.optJSONObject("cover").optString("source")).error(R.drawable.side_nav_bar).into(profileCover);
// Picasso.with(getApplicationContext()).load(object.getJSONObject("cover").getString("source")).resize(header.getWidth(), header.getHeight()).centerCrop().error(R.drawable.side_nav_bar).into(new Target() {
// @Override
// public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
// Log.v(Helpers.LogTag, "Set cover photo");
// header.setBackground(new BitmapDrawable(getResources(), bitmap));
// }
//
// @Override
// public void onBitmapFailed(Drawable errorDrawable) {
// }
//
// @Override
// public void onPrepareLoad(Drawable placeHolderDrawable) {
// }
// });
} catch (NullPointerException e) {
Snackbar.make(mCoordinatorLayoutView, R.string.error_facebook_noconnection, Snackbar.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
Snackbar.make(mCoordinatorLayoutView, R.string.error_facebook_error, Snackbar.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
Snackbar.make(mCoordinatorLayoutView, R.string.error_super_wrong, Snackbar.LENGTH_LONG).show();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,cover,link");
request.setParameters(parameters);
request.executeAsync();
}
public void setNotificationNum(int num) {
if (num > 0) {
ActionItemBadge.update(mNotificationButton, ResourcesCompat.getDrawable(getResources(), R.drawable.ic_menu_notifications_active, null), num);
// sendNotification(num, 0);
} else {
// Hide the badge and show the washed-out button
ActionItemBadge.update(mNotificationButton, ResourcesCompat.getDrawable(getResources(), R.drawable.ic_menu_notifications, null), Integer.MIN_VALUE);
}
}
public void setMessagesNum(int num) {
// Only update message count if enabled
if (mPreferences.getBoolean(SettingsActivity.KEY_PREF_MESSAGING, false)) {
if (num > 0) {
ActionItemBadge.update(mNavigationView.getMenu().findItem(R.id.nav_messages), num);
ActionItemBadge.update(mMessageButton, ResourcesCompat.getDrawable(getResources(), R.drawable.ic_menu_messages, null), num);
// sendNotification(num, 1);
} else {
// Hide the badge and show the washed-out button
ActionItemBadge.update(mNavigationView.getMenu().findItem(R.id.nav_messages), Integer.MIN_VALUE);
ActionItemBadge.update(mMessageButton, ResourcesCompat.getDrawable(getResources(), R.drawable.ic_menu_messages, null), Integer.MIN_VALUE);
}
}
}
public void setRequestsNum(int num) {
if (num > 0) {
ActionItemBadge.update(mNavigationView.getMenu().findItem(R.id.nav_friendreq), num);
// sendNotification(num, 2);
} else {
// Hide the badge and show the washed-out button
ActionItemBadge.update(mNavigationView.getMenu().findItem(R.id.nav_friendreq), Integer.MIN_VALUE);
}
}
// private void sendNotification(int num, int type) {
// SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// if (!preferences.getBoolean(SettingsActivity.KEY_PREF_NOTIFICATIONS_ENABLED, false)) {
// return;
// }
// NotificationCompat.Builder mBuilder =
// new NotificationCompat.Builder(this)
// .setColor(ContextCompat.getColor(this, R.color.colorPrimary))
// .setSmallIcon(R.mipmap.ic_launcher)
// .setContentTitle(getString(R.string.app_name))
// .setAutoCancel(true)
// .setDefaults(-1);
//
// // Intent depends on context
// Intent resultIntent;
//
// // If there are multiple notifications, mention the number
//// String text = getString(R.string.notification_multiple_text, num);
//
// String text = num + (type == 0 ? " New Notifications" : type == 1 ? " New Messages" : " New Friend Requests");
// mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(text)).setContentText(text);
//
// // Set the url to the notification centre
// resultIntent = new Intent(this, MainActivity.class);
// resultIntent.setAction(Intent.ACTION_VIEW);
// resultIntent.setData(Uri.parse(MainActivity.FACEBOOK_URL_BASE + (type == 0 ? "notifications/" : type == 1 ? "messages/" : "friends/center/requests/")));
//
//
// // Notification Priority (make LED blink)
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// mBuilder.setPriority(Notification.PRIORITY_HIGH);
// }
//
// // Vibration
// if (mPreferences.getBoolean(SettingsActivity.KEY_PREF_NOTIFICATION_VIBRATE, true)) {
// mBuilder.setVibrate(new long[]{500, 500});
// } else {
// mBuilder.setVibrate(null);
// }
//
// // Create TaskStack to ensure correct back button behaviour
// TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// // Adds the back stack for the Intent (but not the Intent itself)
// stackBuilder.addParentStack(MainActivity.class);
// // Adds the Intent that starts the Activity to the top of the stack
// stackBuilder.addNextIntent(resultIntent);
// PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// mBuilder.setContentIntent(resultPendingIntent);
//
// // Build the notification
// Notification notification = mBuilder.build();
//
// // Set the LED colour
// notification.ledARGB = ContextCompat.getColor(this, R.color.colorPrimary);
//
// NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// // notifyID allows you to update the notification later on.
// mNotificationManager.notify(type, notification);
//
// Log.i(Helpers.LogTag, "Notification posted");
// }
private String chooseUrl() {
// Handle intents
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
if (URLUtil.isValidUrl(intent.getStringExtra(Intent.EXTRA_TEXT))) {
try {
Log.v(Helpers.LogTag, "Shared URL Intent");
return "https://mbasic.facebook.com/composer/?text=" + URLEncoder.encode(intent.getStringExtra(Intent.EXTRA_TEXT), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
} else if (Intent.ACTION_VIEW.equals(action) && intent.getData() != null && URLUtil.isValidUrl(intent.getData().toString())) {
// If there is a intent containing a facebook link, go there
Log.v(Helpers.LogTag, "Opened URL Intent");
return intent.getData().toString();
}
// If nothing has happened at this point, we want the default url
return FACEBOOK_URL_BASE;
}
@Override
public void onProductPurchased(String productId, TransactionDetails details) {
mPreferences.edit().putBoolean(SettingsActivity.KEY_PREF_ADS, true).apply();
updateView();
}
@Override
public void onPurchaseHistoryRestored() {
if (bp.isPurchased(PRODUCT_ID)) {
mPreferences.edit().putBoolean(SettingsActivity.KEY_PREF_ADS, true).apply();
updateView();
}
}
@Override
public void onBillingError(int errorCode, Throwable error) {
showToast("Billing Error");
}
@Override
public void onBillingInitialized() {
}
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
|
3e01fa4de7132076e5ff76294d7b6944a9b17bc4 | 1,886 | java | Java | Datalib/src/main/java/com/cognizant/cognizantits/datalib/model/Tag.java | AdonisCelestine/CITS | 22a2194909f4ad207355a82d0f19afb5e7f7a23d | [
"Apache-2.0"
] | 1 | 2018-02-25T00:30:22.000Z | 2018-02-25T00:30:22.000Z | Datalib/src/main/java/com/cognizant/cognizantits/datalib/model/Tag.java | AdonisCelestine/CITS | 22a2194909f4ad207355a82d0f19afb5e7f7a23d | [
"Apache-2.0"
] | 1 | 2022-03-29T11:03:51.000Z | 2022-03-29T11:03:51.000Z | Datalib/src/main/java/com/cognizant/cognizantits/datalib/model/Tag.java | AdonisCelestine/CITS | 22a2194909f4ad207355a82d0f19afb5e7f7a23d | [
"Apache-2.0"
] | 2 | 2022-01-13T21:49:46.000Z | 2022-01-18T08:40:52.000Z | 23.873418 | 75 | 0.663839 | 832 | /*
* Copyright 2014 - 2017 Cognizant Technology Solutions
*
* 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.cognizant.cognizantits.datalib.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import java.util.Objects;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"value"
})
/**
*
*
*/
public class Tag {
@JsonProperty("value")
private String value;
@JsonIgnore
public boolean state = false;
@JsonProperty("value")
public String getValue() {
return value;
}
@JsonProperty("value")
public void setValue(String value) {
this.value = value;
}
@JsonIgnore
@Override
public String toString() {
return value;
}
@JsonIgnore
@Override
public boolean equals(Object o) {
if (o instanceof Tag) {
o = ((Tag) o).value;
}
return Objects.deepEquals(value, o);
}
@Override
public int hashCode() {
int hash = 3;
hash = 67 * hash + Objects.hashCode(this.value);
return hash;
}
public static Tag create(String value) {
Tag t = new Tag();
t.setValue(value);
return t;
}
}
|
3e01fa62d943c884f913d016741c9de9f211f923 | 904 | java | Java | yqlplus_engine/src/test/java/com/yahoo/yqlplus/engine/sources/PersonListMakeSource.java | Bing-ok/yql-plus | c11443c59025435e01ef3ab1b92e41419d8e413b | [
"Apache-2.0"
] | 39 | 2016-12-15T22:59:42.000Z | 2022-01-18T00:25:14.000Z | yqlplus_engine/src/test/java/com/yahoo/yqlplus/engine/sources/PersonListMakeSource.java | Bing-ok/yql-plus | c11443c59025435e01ef3ab1b92e41419d8e413b | [
"Apache-2.0"
] | 56 | 2016-12-15T23:23:20.000Z | 2021-12-09T20:37:31.000Z | yqlplus_engine/src/test/java/com/yahoo/yqlplus/engine/sources/PersonListMakeSource.java | Bing-ok/yql-plus | c11443c59025435e01ef3ab1b92e41419d8e413b | [
"Apache-2.0"
] | 15 | 2016-12-15T23:21:57.000Z | 2021-02-10T11:14:23.000Z | 32.285714 | 169 | 0.70354 | 833 | /*
* Copyright (c) 2016 Yahoo Inc.
* Licensed under the terms of the Apache version 2.0 license.
* See LICENSE file for terms.
*/
package com.yahoo.yqlplus.engine.sources;
import java.util.List;
import com.google.common.collect.Lists;
import com.yahoo.yqlplus.api.Source;
import com.yahoo.yqlplus.api.annotations.Key;
import com.yahoo.yqlplus.api.annotations.Query;
import com.yahoo.yqlplus.engine.java.Person;
public class PersonListMakeSource implements Source {
@Query
public List<Person> lookup(@Key("id") List<String> ids, int low, int high) {
List<Person> persons = Lists.newArrayList();
for (String id:ids) {
persons.add(new Person(id, id, Integer.parseInt(id)));
}
return (List<Person>) (Object)Lists.newArrayList(persons.stream().filter(person -> person.getIidPrimitive() > low && person.getIidPrimitive() < high).toArray());
}
}
|
3e01fb6d2f247cf494e32b10af04ca8bb1d51b79 | 2,755 | java | Java | src-app/swift/application/swiftlinks/SwiftLinksAPI.java | marsleezm/cprdt | 268838bb33423c30ad82b1bbef8789432eb6ed40 | [
"Apache-2.0"
] | 1 | 2016-01-20T16:12:54.000Z | 2016-01-20T16:12:54.000Z | src-app/swift/application/swiftlinks/SwiftLinksAPI.java | marsleezm/cprdt | 268838bb33423c30ad82b1bbef8789432eb6ed40 | [
"Apache-2.0"
] | null | null | null | src-app/swift/application/swiftlinks/SwiftLinksAPI.java | marsleezm/cprdt | 268838bb33423c30ad82b1bbef8789432eb6ed40 | [
"Apache-2.0"
] | null | null | null | 26.747573 | 113 | 0.673321 | 834 | package swift.application.swiftlinks;
import java.util.List;
import swift.application.swiftlinks.cprdt.SortedNode;
import swift.application.swiftlinks.crdt.DecoratedNode;
import swift.application.swiftlinks.crdt.VoteDirection;
import swift.crdt.core.SwiftSession;
/**
* Trying to replicate (partially) the API: http://www.reddit.com/dev/api
* Without the web related parameters
*
* @author Iwan Briquemont
*/
public interface SwiftLinksAPI {
public SwiftSession getSwift();
// Account
/**
* http://www.reddit.com/dev/api#POST_api_delete_user
*/
// public void deleteUser(String username, String password);
/**
* http://www.reddit.com/dev/api#POST_api_login
*/
public boolean login(String username, String password);
public void logout();
/**
* http://www.reddit.com/dev/api#GET_api_me.json
*/
public User me();
/**
* http://www.reddit.com/dev/api#POST_api_register
*/
public User register(String username, String password, String email);
/**
* http://www.reddit.com/dev/api#POST_api_update
*/
public void update(String currentPassword, String newPassword, String newEmail);
// Subreddits/forums
public void createSubreddit(String name);
// Links and comments
/**
* http://www.reddit.com/dev/api#POST_api_comment
*
* @param parentComment Parent comment, null if root comment
*/
public SortedNode<Comment> comment(String linkId, SortedNode<Comment> parentComment, long date, String text);
/**
* http://www.reddit.com/dev/api#POST_api_del
*/
public boolean deleteLink(Link link);
public boolean deleteComment(Link link, SortedNode<Comment> comment);
/**
* http://www.reddit.com/dev/api#POST_api_submit
*
* @param linkId
* is optional
*/
public Link submit(String linkId, String subreddit, String title, long date, String url, String text);
/*
* http://www.reddit.com/dev/api#POST_api_vote
*/
public void voteLink(Link link, VoteDirection direction);
public void voteComment(SortedNode<Comment> comment, VoteDirection direction);
public Vote voteOfLink(Link link);
public Vote voteOfComment(SortedNode<Comment> comment);
// Listings
/**
* List of links
* before and after cannot both be set at the same time
*/
public List<Link> links(String subreddit, SortingOrder sort, Link before, Link after, int limit);
/**
* Tree of comments
*
* http://www.reddit.com/dev/api#GET_comments_{article}
*/
public List<SortedNode<Comment>> comments(String linkId, SortedNode<Comment> from,
int context, SortingOrder sort, int limit);
}
|
3e01fb9f74bbaacc703c6c048b6d5d3779173202 | 621 | java | Java | src/main/java/it/nicogiangregorio/home/service/impl/CitizensServiceImpl.java | nicogiangregorio/spring-base-webapp | 8d68d19432e08f5da7a0e175b469a785ffa361b6 | [
"Apache-2.0"
] | null | null | null | src/main/java/it/nicogiangregorio/home/service/impl/CitizensServiceImpl.java | nicogiangregorio/spring-base-webapp | 8d68d19432e08f5da7a0e175b469a785ffa361b6 | [
"Apache-2.0"
] | null | null | null | src/main/java/it/nicogiangregorio/home/service/impl/CitizensServiceImpl.java | nicogiangregorio/spring-base-webapp | 8d68d19432e08f5da7a0e175b469a785ffa361b6 | [
"Apache-2.0"
] | null | null | null | 27 | 69 | 0.8438 | 835 | package it.nicogiangregorio.home.service.impl;
import it.nicogiangregorio.home.model.CitizenLocation;
import it.nicogiangregorio.home.repositories.CitizensRepository;
import it.nicogiangregorio.home.service.CitizensService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CitizensServiceImpl implements CitizensService{
@Autowired
CitizensRepository citizensRepo;
@Override
public List<CitizenLocation> getCitizenLocations(String idCitizen) {
return citizensRepo.getCitizenLocations(idCitizen);
}
}
|
3e01fd26a71761bdfda4167c514b52113609029a | 159 | java | Java | java/servlet/src/main/java/study/ywork/servlet/registration/Pagable.java | y2ghost/study | c5278611b0a732fe19e3d805c0c079e530b1d3b2 | [
"MIT"
] | null | null | null | java/servlet/src/main/java/study/ywork/servlet/registration/Pagable.java | y2ghost/study | c5278611b0a732fe19e3d805c0c079e530b1d3b2 | [
"MIT"
] | null | null | null | java/servlet/src/main/java/study/ywork/servlet/registration/Pagable.java | y2ghost/study | c5278611b0a732fe19e3d805c0c079e530b1d3b2 | [
"MIT"
] | null | null | null | 13.25 | 41 | 0.716981 | 836 | package study.ywork.servlet.registration;
public interface Pagable {
String getPageViewInfo();
String getPageModelInfo();
String getPath();
}
|
3e01fd4ed8ae2586c19a7b1749b4c4819d9fcbca | 2,661 | java | Java | arc-core/src/main/java/fr/insee/arc/core/service/handler/FormatFichierHandler.java | sl-insee/ARC | d04766d1e8aafda0c5caa99590668b043b427bc6 | [
"MIT"
] | 7 | 2019-06-28T13:21:31.000Z | 2021-02-18T10:41:14.000Z | arc-core/src/main/java/fr/insee/arc/core/service/handler/FormatFichierHandler.java | sl-insee/ARC | d04766d1e8aafda0c5caa99590668b043b427bc6 | [
"MIT"
] | 41 | 2019-06-20T13:13:00.000Z | 2022-01-14T09:01:54.000Z | arc-core/src/main/java/fr/insee/arc/core/service/handler/FormatFichierHandler.java | sl-insee/ARC | d04766d1e8aafda0c5caa99590668b043b427bc6 | [
"MIT"
] | 7 | 2019-06-20T12:10:48.000Z | 2021-10-01T12:07:13.000Z | 34.558442 | 141 | 0.656144 | 837 | package fr.insee.arc.core.service.handler;
import java.util.ArrayList;
import java.util.HashMap;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
/**
* Parser pour lire le fichier contenant le format sous forme xml necessaire pour créer un fichier xml à partir
* du fichier clef-valeur.
* Il permet de créer une map de la forme (rubrique, père) qui permet à partir d'une rubrique de remonter jusqu'à son
* père, et ainsi savoir qu'elles seront les balises à ouvrir et fermer.
*
* Diagramme d'activité : <a href="https://gforge.insee.fr/forum/message.php?msg_id=5232&group_id=865"> ici </a>
*
* @author S4LWO8
*
*/
public class FormatFichierHandler extends DefaultHandler {
//L'arbre de la forme, <enfant;parent>
public HashMap<String, String> arbre = new HashMap<String, String>();
//la liste des pères de l'éléments courant
public ArrayList<String> listePere = new ArrayList<String>();
public String nomNorme;
@Override
public void startDocument() throws SAXException {
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
String pere;
//revient à voir si on est sur la première balise ou non
//Si oui son père est null, sinon c'est son ... père...
if (listePere.size()==0) {
pere = null;
} else {
pere = listePere.get(listePere.size()-1);
}
// Avant de mettre à jour l'arbre on regarde si la rubrique est déjà présente. Si oui on soulève une erreur car
// le formatage du fichiers n'est pas le bon car on a soit : des balises à des niveaux différents
// avec le même nom (!!) soit des balises soeurs avec le même nom pour symboliser que se cas existe.
// Si le deuxième cas ne va pas poser problème grâce à l'implémentation de la méthode put(K,V), le second lui si
// Autant soulever une exception est mettre le fichier en erreur.
if (arbre.containsKey(qName)) {
throw new SAXParseException("Fichier de format non pris en compte, on retrouve plusieurs fois une même rubrique.","", "", 0, 0);
}
arbre.put(qName, pere);
listePere.add(qName);
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
listePere.remove(qName);
}
@Override
public void endDocument() throws SAXException {
}
}
|
3e01fda708d60097f640adfa5543d37534e04c4c | 1,301 | java | Java | reactive-TFidF/app/bigdata/reactive/actors/calculate/supervisors/TermFrequencyActor.java | gbrsouza/reactive_systems | 7b2da41244f9f38a6e69e548d7dc15c1cfc6c575 | [
"MIT"
] | 1 | 2019-06-24T19:46:34.000Z | 2019-06-24T19:46:34.000Z | reactive-TFidF/app/bigdata/reactive/actors/calculate/supervisors/TermFrequencyActor.java | gbrsouza/reactive_systems | 7b2da41244f9f38a6e69e548d7dc15c1cfc6c575 | [
"MIT"
] | null | null | null | reactive-TFidF/app/bigdata/reactive/actors/calculate/supervisors/TermFrequencyActor.java | gbrsouza/reactive_systems | 7b2da41244f9f38a6e69e548d7dc15c1cfc6c575 | [
"MIT"
] | 1 | 2019-06-23T17:05:02.000Z | 2019-06-23T17:05:02.000Z | 27.104167 | 81 | 0.744043 | 838 | package bigdata.reactive.actors.calculate.supervisors;
import java.util.ArrayList;
import java.util.List;
import akka.actor.AbstractActor;
import akka.actor.Props;
import bigdata.reactive.CellMultiTable;
import bigdata.reactive.messages.CellListMessage;
import bigdata.reactive.messages.requests.RequestTermFrequencyMessage;
public class TermFrequencyActor extends AbstractActor {
@Override
public Receive createReceive() {
return receiveBuilder()
.match(RequestTermFrequencyMessage.class, msg->{
getSender().tell(term_frequency(msg), getSelf());
}).build();
}
private CellListMessage term_frequency ( RequestTermFrequencyMessage message ) {
double occurrence_number = 0.0;
double terms_number = 1.0;
double value = 0.0;
List<CellMultiTable> cells = new ArrayList<CellMultiTable>();
for (String s : message.getTerms().keySet() ) {
occurrence_number = (double) message.get_occurrences(s);
if (occurrence_number != 0.0) {
terms_number = (double) message.getDocument().get_number_terms();
value = occurrence_number/ terms_number;
cells.add(new CellMultiTable(message.document_name(), s, value));
}
}
return new CellListMessage(cells);
}
public static Props props () {
return Props.create(TermFrequencyActor.class);
}
}
|
3e01fddf090827ef0d799ac09b7a82fe82b3b8a6 | 22,256 | java | Java | google/cloud/automl/v1beta1/google-cloud-automl-v1beta1-java/proto-google-cloud-automl-v1beta1-java/src/main/java/com/google/cloud/automl/v1beta1/GcrDestination.java | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 7 | 2021-02-21T10:39:41.000Z | 2021-12-07T07:31:28.000Z | google/cloud/automl/v1beta1/google-cloud-automl-v1beta1-java/proto-google-cloud-automl-v1beta1-java/src/main/java/com/google/cloud/automl/v1beta1/GcrDestination.java | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 6 | 2021-02-02T23:46:11.000Z | 2021-11-15T01:46:02.000Z | google/cloud/automl/v1beta1/google-cloud-automl-v1beta1-java/proto-google-cloud-automl-v1beta1-java/src/main/java/com/google/cloud/automl/v1beta1/GcrDestination.java | googleapis/googleapis-gen | d84824c78563d59b0e58d5664bfaa430e9ad7e7a | [
"Apache-2.0"
] | 4 | 2021-01-28T23:25:45.000Z | 2021-08-30T01:55:16.000Z | 34.24 | 130 | 0.686556 | 839 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/automl/v1beta1/io.proto
package com.google.cloud.automl.v1beta1;
/**
* <pre>
* The GCR location where the image must be pushed to.
* </pre>
*
* Protobuf type {@code google.cloud.automl.v1beta1.GcrDestination}
*/
public final class GcrDestination extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.cloud.automl.v1beta1.GcrDestination)
GcrDestinationOrBuilder {
private static final long serialVersionUID = 0L;
// Use GcrDestination.newBuilder() to construct.
private GcrDestination(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GcrDestination() {
outputUri_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new GcrDestination();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private GcrDestination(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
java.lang.String s = input.readStringRequireUtf8();
outputUri_ = s;
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.cloud.automl.v1beta1.Io.internal_static_google_cloud_automl_v1beta1_GcrDestination_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.automl.v1beta1.Io.internal_static_google_cloud_automl_v1beta1_GcrDestination_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.automl.v1beta1.GcrDestination.class, com.google.cloud.automl.v1beta1.GcrDestination.Builder.class);
}
public static final int OUTPUT_URI_FIELD_NUMBER = 1;
private volatile java.lang.Object outputUri_;
/**
* <pre>
* Required. Google Contained Registry URI of the new image, up to 2000
* characters long. See
* https:
* //cloud.google.com/container-registry/do
* // cs/pushing-and-pulling#pushing_an_image_to_a_registry
* Accepted forms:
* * [HOSTNAME]/[PROJECT-ID]/[IMAGE]
* * [HOSTNAME]/[PROJECT-ID]/[IMAGE]:[TAG]
* The requesting user must have permission to push images the project.
* </pre>
*
* <code>string output_uri = 1;</code>
* @return The outputUri.
*/
@java.lang.Override
public java.lang.String getOutputUri() {
java.lang.Object ref = outputUri_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
outputUri_ = s;
return s;
}
}
/**
* <pre>
* Required. Google Contained Registry URI of the new image, up to 2000
* characters long. See
* https:
* //cloud.google.com/container-registry/do
* // cs/pushing-and-pulling#pushing_an_image_to_a_registry
* Accepted forms:
* * [HOSTNAME]/[PROJECT-ID]/[IMAGE]
* * [HOSTNAME]/[PROJECT-ID]/[IMAGE]:[TAG]
* The requesting user must have permission to push images the project.
* </pre>
*
* <code>string output_uri = 1;</code>
* @return The bytes for outputUri.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getOutputUriBytes() {
java.lang.Object ref = outputUri_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
outputUri_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(outputUri_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, outputUri_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(outputUri_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, outputUri_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.automl.v1beta1.GcrDestination)) {
return super.equals(obj);
}
com.google.cloud.automl.v1beta1.GcrDestination other = (com.google.cloud.automl.v1beta1.GcrDestination) obj;
if (!getOutputUri()
.equals(other.getOutputUri())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + OUTPUT_URI_FIELD_NUMBER;
hash = (53 * hash) + getOutputUri().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.automl.v1beta1.GcrDestination parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.automl.v1beta1.GcrDestination parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.automl.v1beta1.GcrDestination parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.automl.v1beta1.GcrDestination parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.automl.v1beta1.GcrDestination parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.automl.v1beta1.GcrDestination parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.automl.v1beta1.GcrDestination parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.cloud.automl.v1beta1.GcrDestination parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.cloud.automl.v1beta1.GcrDestination parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.automl.v1beta1.GcrDestination parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.cloud.automl.v1beta1.GcrDestination parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.cloud.automl.v1beta1.GcrDestination parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.automl.v1beta1.GcrDestination prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* The GCR location where the image must be pushed to.
* </pre>
*
* Protobuf type {@code google.cloud.automl.v1beta1.GcrDestination}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.cloud.automl.v1beta1.GcrDestination)
com.google.cloud.automl.v1beta1.GcrDestinationOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.cloud.automl.v1beta1.Io.internal_static_google_cloud_automl_v1beta1_GcrDestination_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.automl.v1beta1.Io.internal_static_google_cloud_automl_v1beta1_GcrDestination_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.automl.v1beta1.GcrDestination.class, com.google.cloud.automl.v1beta1.GcrDestination.Builder.class);
}
// Construct using com.google.cloud.automl.v1beta1.GcrDestination.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
outputUri_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.cloud.automl.v1beta1.Io.internal_static_google_cloud_automl_v1beta1_GcrDestination_descriptor;
}
@java.lang.Override
public com.google.cloud.automl.v1beta1.GcrDestination getDefaultInstanceForType() {
return com.google.cloud.automl.v1beta1.GcrDestination.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.automl.v1beta1.GcrDestination build() {
com.google.cloud.automl.v1beta1.GcrDestination result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.automl.v1beta1.GcrDestination buildPartial() {
com.google.cloud.automl.v1beta1.GcrDestination result = new com.google.cloud.automl.v1beta1.GcrDestination(this);
result.outputUri_ = outputUri_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.automl.v1beta1.GcrDestination) {
return mergeFrom((com.google.cloud.automl.v1beta1.GcrDestination)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.automl.v1beta1.GcrDestination other) {
if (other == com.google.cloud.automl.v1beta1.GcrDestination.getDefaultInstance()) return this;
if (!other.getOutputUri().isEmpty()) {
outputUri_ = other.outputUri_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.automl.v1beta1.GcrDestination parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.cloud.automl.v1beta1.GcrDestination) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object outputUri_ = "";
/**
* <pre>
* Required. Google Contained Registry URI of the new image, up to 2000
* characters long. See
* https:
* //cloud.google.com/container-registry/do
* // cs/pushing-and-pulling#pushing_an_image_to_a_registry
* Accepted forms:
* * [HOSTNAME]/[PROJECT-ID]/[IMAGE]
* * [HOSTNAME]/[PROJECT-ID]/[IMAGE]:[TAG]
* The requesting user must have permission to push images the project.
* </pre>
*
* <code>string output_uri = 1;</code>
* @return The outputUri.
*/
public java.lang.String getOutputUri() {
java.lang.Object ref = outputUri_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
outputUri_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Required. Google Contained Registry URI of the new image, up to 2000
* characters long. See
* https:
* //cloud.google.com/container-registry/do
* // cs/pushing-and-pulling#pushing_an_image_to_a_registry
* Accepted forms:
* * [HOSTNAME]/[PROJECT-ID]/[IMAGE]
* * [HOSTNAME]/[PROJECT-ID]/[IMAGE]:[TAG]
* The requesting user must have permission to push images the project.
* </pre>
*
* <code>string output_uri = 1;</code>
* @return The bytes for outputUri.
*/
public com.google.protobuf.ByteString
getOutputUriBytes() {
java.lang.Object ref = outputUri_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
outputUri_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Required. Google Contained Registry URI of the new image, up to 2000
* characters long. See
* https:
* //cloud.google.com/container-registry/do
* // cs/pushing-and-pulling#pushing_an_image_to_a_registry
* Accepted forms:
* * [HOSTNAME]/[PROJECT-ID]/[IMAGE]
* * [HOSTNAME]/[PROJECT-ID]/[IMAGE]:[TAG]
* The requesting user must have permission to push images the project.
* </pre>
*
* <code>string output_uri = 1;</code>
* @param value The outputUri to set.
* @return This builder for chaining.
*/
public Builder setOutputUri(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
outputUri_ = value;
onChanged();
return this;
}
/**
* <pre>
* Required. Google Contained Registry URI of the new image, up to 2000
* characters long. See
* https:
* //cloud.google.com/container-registry/do
* // cs/pushing-and-pulling#pushing_an_image_to_a_registry
* Accepted forms:
* * [HOSTNAME]/[PROJECT-ID]/[IMAGE]
* * [HOSTNAME]/[PROJECT-ID]/[IMAGE]:[TAG]
* The requesting user must have permission to push images the project.
* </pre>
*
* <code>string output_uri = 1;</code>
* @return This builder for chaining.
*/
public Builder clearOutputUri() {
outputUri_ = getDefaultInstance().getOutputUri();
onChanged();
return this;
}
/**
* <pre>
* Required. Google Contained Registry URI of the new image, up to 2000
* characters long. See
* https:
* //cloud.google.com/container-registry/do
* // cs/pushing-and-pulling#pushing_an_image_to_a_registry
* Accepted forms:
* * [HOSTNAME]/[PROJECT-ID]/[IMAGE]
* * [HOSTNAME]/[PROJECT-ID]/[IMAGE]:[TAG]
* The requesting user must have permission to push images the project.
* </pre>
*
* <code>string output_uri = 1;</code>
* @param value The bytes for outputUri to set.
* @return This builder for chaining.
*/
public Builder setOutputUriBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
outputUri_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.automl.v1beta1.GcrDestination)
}
// @@protoc_insertion_point(class_scope:google.cloud.automl.v1beta1.GcrDestination)
private static final com.google.cloud.automl.v1beta1.GcrDestination DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.automl.v1beta1.GcrDestination();
}
public static com.google.cloud.automl.v1beta1.GcrDestination getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<GcrDestination>
PARSER = new com.google.protobuf.AbstractParser<GcrDestination>() {
@java.lang.Override
public GcrDestination parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new GcrDestination(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<GcrDestination> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<GcrDestination> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.automl.v1beta1.GcrDestination getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
3e01fe07221b6bdc40b31437da1df857f3066aa1 | 3,840 | java | Java | dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional4/JavaConfigReferenceBeanConditionalTest4.java | xiaoheitalk/dubbo | d44ca1f3db9b3f208a72dd041eb49f4f5de697cf | [
"Apache-2.0"
] | 18,012 | 2015-01-01T00:59:11.000Z | 2018-03-19T09:21:57.000Z | dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional4/JavaConfigReferenceBeanConditionalTest4.java | xiaoheitalk/dubbo | d44ca1f3db9b3f208a72dd041eb49f4f5de697cf | [
"Apache-2.0"
] | 2,824 | 2018-03-20T00:27:49.000Z | 2019-05-24T12:59:35.000Z | dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional4/JavaConfigReferenceBeanConditionalTest4.java | xiaoheitalk/dubbo | d44ca1f3db9b3f208a72dd041eb49f4f5de697cf | [
"Apache-2.0"
] | 10,640 | 2015-01-03T08:47:16.000Z | 2018-03-19T09:00:46.000Z | 34.594595 | 124 | 0.733333 | 840 | /*
* 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.dubbo.config.spring.boot.conditional4;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.ReferenceBean;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.config.spring.context.annotation.provider.HelloServiceImpl;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import java.util.Map;
/**
* issue: https://github.com/apache/dubbo-spring-boot-project/issues/779
*/
@SpringBootTest(
properties = {
"dubbo.application.name=consumer-app",
"dubbo.registry.address=N/A",
"myapp.group=demo"
},
classes = {
JavaConfigReferenceBeanConditionalTest4.class
}
)
@Configuration
//@ComponentScan
@EnableDubbo
public class JavaConfigReferenceBeanConditionalTest4 {
@BeforeAll
public static void beforeAll(){
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll(){
DubboBootstrap.reset();
}
@Autowired
private HelloService helloService;
@Autowired
private ApplicationContext applicationContext;
@Test
public void testConsumer() {
Map<String, HelloService> helloServiceMap = applicationContext.getBeansOfType(HelloService.class);
Assertions.assertEquals(1, helloServiceMap.size());
Assertions.assertNull(helloServiceMap.get("helloService"));
HelloService helloService = helloServiceMap.get("helloServiceImpl");
Assertions.assertNotNull(helloService);
Assertions.assertTrue(helloService instanceof HelloServiceImpl, "Not expected bean type: "+helloService.getClass());
}
@Order(Integer.MAX_VALUE-2)
@Configuration
public static class ServiceBeanConfiguration {
@Bean
public HelloService helloServiceImpl() {
return new HelloServiceImpl();
}
}
// make sure that the one using condition runs after.
@Order(Integer.MAX_VALUE-1)
@Configuration
public static class AnnotationBeanConfiguration {
//TEST Conditional, this bean should be ignored
@Bean
@ConditionalOnMissingBean(HelloService.class)
@DubboReference(group = "${myapp.group}", init = false)
public ReferenceBean<HelloService> helloService() {
return new ReferenceBean();
}
}
}
|
3e01fe103f9aa8af5860d182ee89a0d85b7b55b5 | 237 | java | Java | len-core/src/main/java/com/len/util/UuidUtil.java | Juminiy/lenosp | 383f1a79d2eb1c042b7f115bb4582281c63c473d | [
"Apache-2.0"
] | 1 | 2021-02-10T07:20:28.000Z | 2021-02-10T07:20:28.000Z | len-core/src/main/java/com/len/util/UuidUtil.java | LuJenning/duorou | 2ddcc7912937e93be9b2f91e66e11c6db301b203 | [
"Apache-2.0"
] | null | null | null | len-core/src/main/java/com/len/util/UuidUtil.java | LuJenning/duorou | 2ddcc7912937e93be9b2f91e66e11c6db301b203 | [
"Apache-2.0"
] | null | null | null | 15.8 | 75 | 0.616034 | 841 | package com.len.util;
import java.util.UUID;
/**
* @author zxm
* @date 2019-11-15.
*/
public class UuidUtil {
public static String getUuid() {
return UUID.randomUUID().toString().replace("-", "").toLowerCase();
}
}
|
3e01febfaa5e7793bb7b4420262933718091d18c | 3,900 | java | Java | core/modules/spring/src/main/java/org/onetwo/common/spring/resource/AnnotationComponentScanner.java | wayshall/onetwo | 221ddfc0cbf3eafbef8ec090c21b9972c7d8ea23 | [
"Apache-2.0"
] | 19 | 2015-05-27T02:18:43.000Z | 2021-11-16T11:02:17.000Z | core/modules/spring/src/main/java/org/onetwo/common/spring/resource/AnnotationComponentScanner.java | wayshall/onetwo | 221ddfc0cbf3eafbef8ec090c21b9972c7d8ea23 | [
"Apache-2.0"
] | 58 | 2017-03-07T03:06:32.000Z | 2022-02-01T00:57:27.000Z | core/modules/spring/src/main/java/org/onetwo/common/spring/resource/AnnotationComponentScanner.java | wayshall/onetwo | 221ddfc0cbf3eafbef8ec090c21b9972c7d8ea23 | [
"Apache-2.0"
] | 12 | 2016-08-11T03:26:34.000Z | 2019-01-09T10:56:29.000Z | 35.135135 | 109 | 0.780769 | 842 | package org.onetwo.common.spring.resource;
import java.lang.annotation.Annotation;
import java.util.Collection;
import org.apache.commons.lang3.ArrayUtils;
import org.onetwo.common.exception.BaseException;
import org.onetwo.common.log.JFishLoggerFactory;
import org.onetwo.common.reflect.ReflectUtils;
import org.onetwo.common.spring.SpringUtils;
import org.onetwo.common.spring.utils.JFishResourcesScanner;
import org.slf4j.Logger;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
/****
* 扫描指定注解的类,并注册……
* @author way
*
* @param <T>
*/
abstract public class AnnotationComponentScanner<T extends Annotation> {
protected final Logger logger = JFishLoggerFactory.getLogger(this.getClass());
private JFishResourcesScanner resourcesScanner = new JFishResourcesScanner();
private BeanDefinitionRegistry registry;
private String[] packagesToScan;
private Class<T> annotationClass;
// private AnnotationMetadata importingClassMetadata;
public AnnotationComponentScanner(BeanDefinitionRegistry registry) {
this.registry = registry;
// this.importingClassMetadata = importingClassMetadata;
}
public AnnotationComponentScanner(ApplicationContext applicationContext) {
this.registry = SpringUtils.getBeanDefinitionRegistry(applicationContext);
}
public void setPackagesToScan(String[] packagesToScan) {
this.packagesToScan = packagesToScan;
}
@SuppressWarnings("unchecked")
public boolean scanAndRegisterBeans() {
String[] packagesToScan = getComponentPackages();
if(ArrayUtils.isEmpty(packagesToScan)){
logger.info("no packages config to scan for {} ....", annotationClass);
return false;
}
logger.info("start to register @{} bean ....", annotationClass.getSimpleName());
Collection<Class<T>> componentClassList = resourcesScanner.scan((metadataReader, res, index)->{
if( metadataReader.getAnnotationMetadata().hasAnnotation(annotationClass.getName()) ){
Class<T> cls = (Class<T>)ReflectUtils.loadClass(metadataReader.getClassMetadata().getClassName(), false);
return cls;
}
return null;
}, packagesToScan);
for(Class<T> repositoryClass: componentClassList){
this.doRegisterComponent(repositoryClass);
// BeanDefinitionBuilder beandefBuilder = createBeanDefinitionBuilder(repositoryClass);
// BeanDefinitionBuilder.rootBeanDefinition(AnnotationDynamicQueryHandlerProxyCreator.class)
// .addConstructorArgValue(repositoryClass)
// .addConstructorArgValue(methodCache)
// .setScope(BeanDefinition.SCOPE_SINGLETON)
// .setRole(BeanDefinition.ROLE_APPLICATION)
// .getBeanDefinition()
}
boolean scaned = !componentClassList.isEmpty();
return scaned;
}
protected void doRegisterComponent(Class<T> repositoryClass) {
if(isComponentExist(repositoryClass)){
return ;
}
if (repositoryClass.isInterface()) {
throw new BaseException("interface can not register as a bean: " + repositoryClass);
}
String className = repositoryClass.getName();
BeanDefinitionBuilder beandefBuilder = BeanDefinitionBuilder.rootBeanDefinition(repositoryClass);
registry.registerBeanDefinition(className, beandefBuilder.getBeanDefinition());
logger.info("register @{} bean: {} ", annotationClass.getSimpleName(), className);
}
final protected boolean isComponentExist(Class<T> repositoryClass) {
String className = repositoryClass.getName();
return registry.containsBeanDefinition(className);
}
protected String[] getComponentPackages() {
String[] packs = this.packagesToScan;
// if(LangUtils.isEmpty(packs) && importingClassMetadata!=null){
// packs = new String[]{ClassUtils.getPackageName(importingClassMetadata.getClassName())};
// }
return packs;
}
public BeanDefinitionRegistry getRegistry() {
return registry;
}
}
|
3e01ff41966b72d94f07592f79175c40a46b751b | 783 | java | Java | src/main/java/org/lucidant/InterestRate.java | christweekie/codingwars | 824786ea6b48635d47ebdd4ba2cc3ed214df34e2 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/lucidant/InterestRate.java | christweekie/codingwars | 824786ea6b48635d47ebdd4ba2cc3ed214df34e2 | [
"Apache-2.0"
] | 1 | 2019-11-02T10:26:42.000Z | 2019-11-02T10:26:42.000Z | src/main/java/org/lucidant/InterestRate.java | christweekie/codingwars | 824786ea6b48635d47ebdd4ba2cc3ed214df34e2 | [
"Apache-2.0"
] | null | null | null | 22.371429 | 82 | 0.735632 | 843 | /**
*
*/
package org.lucidant;
import java.math.BigDecimal;
import java.util.List;
/**
* @author chrisfaulkner
*
*/
public class InterestRate {
private static final BigDecimal LESS_THOUSAND_RATE = new BigDecimal("0.01");
private static final BigDecimal MORE_THOUSAND_RATE = new BigDecimal("0.02");
private static final BigDecimal MORE_FIVE_THOUSAND_RATE = new BigDecimal("0.03");
private List<InterestBounds> interestBounds;
public InterestRate(List<InterestBounds> interestBounds) {
this.interestBounds = interestBounds;
}
public BigDecimal calculate(BigDecimal amount) {
return interestBounds.stream()
.filter(bound -> bound.inRange(amount))
.findFirst()
.map(bound -> bound.calculate(amount))
.orElse(BigDecimal.ZERO.setScale(2));
}
}
|
3e01ff5c28bd235c055eac3a6f5855ab26d9a814 | 1,480 | java | Java | testing/ux-automation/src/test/java/com/comcast/redirector/thucydides/tests/main/rules/flavor/template/FlavorRulesTemplatesTest.java | deebugger/redirector | 01fe3a18fee8e29a06ee09419b0392fd17ddc089 | [
"Apache-2.0"
] | 9 | 2017-06-10T08:29:58.000Z | 2019-05-16T06:43:51.000Z | testing/ux-automation/src/test/java/com/comcast/redirector/thucydides/tests/main/rules/flavor/template/FlavorRulesTemplatesTest.java | deebugger/redirector | 01fe3a18fee8e29a06ee09419b0392fd17ddc089 | [
"Apache-2.0"
] | 6 | 2018-06-25T00:39:00.000Z | 2021-01-20T23:55:44.000Z | testing/ux-automation/src/test/java/com/comcast/redirector/thucydides/tests/main/rules/flavor/template/FlavorRulesTemplatesTest.java | Comcast/redirector | 6770fe01383bc7ea110c7c8e14c137212ebc0ba1 | [
"Apache-2.0"
] | 11 | 2017-06-09T20:22:36.000Z | 2019-09-06T12:53:23.000Z | 36.365854 | 90 | 0.788062 | 844 | /**
* Copyright 2017 Comcast Cable Communications Management, 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.
*
* @author Stanislav Menshykov ([email protected])
*/
package com.comcast.redirector.thucydides.tests.main.rules.flavor.template;
import com.comcast.redirector.thucydides.util.TestConstants;
import net.thucydides.core.annotations.ManagedPages;
import net.thucydides.core.pages.Pages;
import net.thucydides.junit.runners.ThucydidesRunner;
import org.junit.FixMethodOrder;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import static com.comcast.redirector.thucydides.tests.UxTestSuite.Constants.RULE_FLAVOR_3;
@RunWith(ThucydidesRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class FlavorRulesTemplatesTest extends FlavorRulesTemplatesBaseTest {
@ManagedPages(defaultUrl = TestConstants.MAIN_UX_URL)
private Pages pages;
@Override
String getFlavor() {
return RULE_FLAVOR_3;
}
}
|
3e0200262c464dc766dd5dee0ad778db0e5026bf | 11,042 | java | Java | src/balanceTrackerBetaV1/ui/UpdateAccountJListDialog.java | dewitjin/balanceTrackerApp | 5ebf9215c01766e1511afd988cd5ed630c706634 | [
"MIT",
"Unlicense"
] | null | null | null | src/balanceTrackerBetaV1/ui/UpdateAccountJListDialog.java | dewitjin/balanceTrackerApp | 5ebf9215c01766e1511afd988cd5ed630c706634 | [
"MIT",
"Unlicense"
] | null | null | null | src/balanceTrackerBetaV1/ui/UpdateAccountJListDialog.java | dewitjin/balanceTrackerApp | 5ebf9215c01766e1511afd988cd5ed630c706634 | [
"MIT",
"Unlicense"
] | null | null | null | 34.832808 | 138 | 0.721971 | 845 | /**
*Project: balanceTrackerBetaV1
*File: UpdateAccountJListDialog.java
*Date: Jan 1, 2016
*Time: 5:41:58 PM
*/
package balanceTrackerBetaV1.ui;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.AbstractListModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import net.miginfocom.swing.MigLayout;
import javax.swing.JList;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import balanceTrackerBetaV1.data.Account;
import balanceTrackerBetaV1.utilities.SortByBankPrefixWithAccountObjects;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
/**
* This class shows in a list what accounts are available to create balance
* objects in. You can either select list element, double click on element, or
* select list element and then press okay to start the add balance dialog.
* NOTE: placing a closed status on an account does not remove the account on the JLIST
* because we want to still see the account on the list BUT it will add a CLOSED status
* NOTE: then we update the account tables to reflect the closed status too, the bank tables can be left alone
*
* @author Dewi Tjin
*
*/
public class UpdateAccountJListDialog extends JDialog {
private static final long serialVersionUID = 1L;
private static final Font FIXEDFONT = new Font("Monospaced", Font.PLAIN, 12);
private final JPanel contentPanel = new JPanel();
@SuppressWarnings("unused")
private List<Account> allAccountsToView = new ArrayList<Account>();
private SortedListModel accountSortedModel = new SortedListModel();
private JList<Account> listOfAccounts = new JList<Account>();
private static final Logger LOG = LogManager
.getLogger(UpdateAccountJListDialog.class);
/**
* Create dialog that has a list of accounts available to update, when you
* double click on a list element, select and press enter, or select and
* press okay you will be able to update the balance.
*
* @param account
*/
public UpdateAccountJListDialog(List<Account> allAccounts) {
allAccountsToView = allAccounts;
setBounds(100, 100, 788, 487);
setTitle("VIEW ALL EXISINT ACCOUNTS");
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
setLocationRelativeTo(null);
contentPanel.setLayout(new MigLayout("", "[grow]", "[grow]"));
//sorts out by bank prefix for readability
for (Account account : allAccounts) {
try {
accountSortedModel.add(account);
} catch (Exception e) {
LOG.error(e.getMessage());
}
}
{
listOfAccounts.setModel(accountSortedModel);
listOfAccounts.setFont(FIXEDFONT);
listOfAccounts.setSelectedIndex(0); //this selects the first element on the list, preventing the null error when the dialog first opens
listOfAccounts.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
getClickAndEnterActions();
}
}
});
listOfAccounts.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
getClickAndEnterActions();
}
}
});
JScrollPane scrollPane = new JScrollPane(listOfAccounts);
// instead of this we had the scrollbar contentPanel.add(listOfAccounts, "cell 0 0,grow");
contentPanel.add(scrollPane, "cell 0 0,grow");
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAddBalanceDialog();
}
});
{
JButton btnPlaceAClosed = new JButton("Place a CLOSED status ");
btnPlaceAClosed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addsClosedStatusToAccounts();
}
});
buttonPane.add(btnPlaceAClosed);
}
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
UpdateAccountJListDialog.this.dispose();
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
}
/**
* This helper method disables account updates that are closed and enables
* account updates for others.
*/
public void getClickAndEnterActions() {
try{
if(listOfAccounts.getSelectedValue().getName().trim().length() <= 9){
openAddBalanceDialog(); //this takes care of account names that are less than 9 letters
}else if (listOfAccounts.getSelectedValue().getName().substring(0, 9)
.equalsIgnoreCase("ClosedOn-") && listOfAccounts.getSelectedValue().getName().trim().length() >= 9 ) {
JOptionPane.showMessageDialog(null,
"This account is now CLOSED. \n" + "Can not update"); //this is if the nine letters are ClosedOn-
}else{
openAddBalanceDialog();
}
}catch(Exception e){
LOG.error(e.getMessage());
}
}
/**
* This method finds the account data that was selected in the list, then
* pass that data into a add balance dialog
*/
public void openAddBalanceDialog() {
try {
Account selectAccount = listOfAccounts.getSelectedValue();
if(selectAccount == null){
JOptionPane.showMessageDialog(null, "Please select and account");
}
if(selectAccount.getType().equalsIgnoreCase(Account.Types.CASH.getAccountType())){
// pass this account to add balance dialog to start the dialog, and look up the current foreign rate first
ExchangeRateJListDialog dialog = new ExchangeRateJListDialog(selectAccount.getBank().getPrefix().substring(0, 3), selectAccount);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setLocation(800, 50);;
dialog.setVisible(true);
//AddBalanceDialog addBalanceDialog = new AddBalanceDialog(selectAccount);
}else{
// pass this account to add balance dialog to start the dialog
AddBalanceDialog addBalanceDialog = new AddBalanceDialog(selectAccount, null);
addBalanceDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
addBalanceDialog.setVisible(true);
}
} catch (Exception e1) {
LOG.error(e1.getMessage());
}
}
/**
* This method finds the account data that was selected in the list, then goes
* into the balance and account table and changes the account name to PREPEND the words
* ClosedOn dash and "the day it was closed" and the account name (readByAccountAndUpdate())
* Note: this method will leave the bank table alone because other accounts with
* the same bank might be open so we don't need to place a bank close status
*/
public void addsClosedStatusToAccounts() {
Account selectAccount = null;
try {
LocalDate date = LocalDate.now();
selectAccount = listOfAccounts.getSelectedValue();
MainFrame.balanceDao.readByAccountAndUpdate(selectAccount, date);
//need to change the account table too so that the JList gets updated properly
MainFrame.accountDao.readByAccountAndUpdate(selectAccount, date);
UpdateAccountJListDialog.this.dispose();
JOptionPane.showMessageDialog(null, "This account is now CLOSED. \n" +
"You will see old balances updated with the CLOSED status");
//TODO: find a better way to re-open the JList Dialog to show that the account has now have the closed status??
try {
UpdateAccountJListDialog dialog = new UpdateAccountJListDialog(MainFrame.accountDao.getAllAccounts());
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e1) {
LOG.error(e1.getMessage());
}
} catch (Exception e1) {
LOG.error(e1.getMessage());
}
}
/**
* Inner class to sort list in model
* In order to customize the code for this App, instead of just creating
* a plain treeSet constructor, I had to pass a class that implements Comparator and takes Account as objects.
* The code from the URL was comparing Strings, but I needed the model to hold Account objects
* so I could pass Account objects to the other dialogs. The SortByBankPrefixWithAccountObjects class
* compares the bank name prefix (String).
* @author used: http://www.java2s.com/Tutorials/Java/Swing/JList/Create_a_sorted_List_Model_for_JList_in_Java.htm
*
*/
public class SortedListModel extends AbstractListModel<Account>{
SortedSet<Account> model;
public SortedListModel() {
model = new TreeSet(new SortByBankPrefixWithAccountObjects());
}
@Override
public int getSize() {
return model.size();
}
@Override
public Account getElementAt(int index) {
return (Account)model.toArray()[index];
}
public void add(Object element) {
if (model.add((Account)element)) {
fireContentsChanged(this, 0, getSize());
}
}
//extra methods that don't really need to be here... but was from the URL, might use for future
public void addAll(Object elements[]) {
Collection c = Arrays.asList(elements);
model.addAll(c);
fireContentsChanged(this, 0, getSize());
}
public void clear() {
model.clear();
fireContentsChanged(this, 0, getSize());
}
public boolean contains(Object element) {
return model.contains(element);
}
public Object firstElement() {
return model.first();
}
public Iterator iterator() {
return model.iterator();
}
public Object lastElement() {
return model.last();
}
public boolean removeElement(Object element) {
boolean removed = model.remove(element);
if (removed) {
fireContentsChanged(this, 0, getSize());
}
return removed;
}
}
}
//NOTE: if I wanted to create a model based on the DefaultListModel class it would look something like this
//private DefaultListModel<Account> accountModel = new DefaultListModel<Account>();
//for (Account account : allAccounts) {
// try {
// accountModel.addElement(account);
// } catch (Exception e) {
// LOG.error(e.getMessage());
// }
//}
//pass model into list so we can see the account to_string
//listOfAccounts = new JList<Account>(accountModel); this is what you would do with the defaultListModel
|
3e02014fe515489ae8f50c36842c31aae32f6930 | 4,121 | java | Java | xutil/src/main/java/com/luffykou/xutil/KeyboardUtil.java | luffykou/xutil | a18512869907f7233c23129097e54fdfbdfe6744 | [
"Apache-2.0"
] | null | null | null | xutil/src/main/java/com/luffykou/xutil/KeyboardUtil.java | luffykou/xutil | a18512869907f7233c23129097e54fdfbdfe6744 | [
"Apache-2.0"
] | null | null | null | xutil/src/main/java/com/luffykou/xutil/KeyboardUtil.java | luffykou/xutil | a18512869907f7233c23129097e54fdfbdfe6744 | [
"Apache-2.0"
] | null | null | null | 34.057851 | 118 | 0.610289 | 846 | package com.luffykou.xutil;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
public class KeyboardUtil {
private KeyboardUtil() {
}
/**
* 动态隐藏软键盘
*/
public static void hideSoftInput(Activity activity) {
View view = activity.getWindow().peekDecorView();
if (view != null) {
InputMethodManager manager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
/**
* 动态隐藏软键盘
*/
public static void hideSoftInput(Context context, EditText editText) {
editText.clearFocus();
InputMethodManager manager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
manager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
/**
* 点击屏幕空白区域隐藏软键盘(方法1)
* <p>在onTouch中处理,未获焦点则隐藏
* <p>参照以下注释代码
*/
public static void clickBlankArea2HideSoftInput0() {
Log.i("tips", "U should copy the following code.");
/*
@Override
public boolean onTouchEvent (MotionEvent event){
if (null != this.getCurrentFocus()) {
InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
}
return super.onTouchEvent(event);
}
*/
}
/**
* 点击屏幕空白区域隐藏软键盘(方法2)
* <p>根据EditText所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘
* <p>需重写dispatchTouchEvent
* <p>参照以下注释代码
*/
public static void clickBlankArea2HideSoftInput1() {
Log.i("tips", "U should copy the following code.");
/*
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (isShouldHideKeyboard(v, ev)) {
hideKeyboard(v.getWindowToken());
}
}
return super.dispatchTouchEvent(ev);
}
// 根据EditText所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘
private boolean isShouldHideKeyboard(View v, MotionEvent event) {
if (v != null && (v instanceof EditText)) {
int[] l = {0, 0};
v.getLocationInWindow(l);
int left = l[0],
top = l[1],
bottom = top + v.getHeight(),
right = left + v.getWidth();
return !(event.getX() > left && event.getX() < right
&& event.getY() > top && event.getY() < bottom);
}
return false;
}
// 获取InputMethodManager,隐藏软键盘
private void hideKeyboard(IBinder token) {
if (token != null) {
InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
}
}
*/
}
/**
* 动态显示软键盘
*/
public static void showSoftInput(Context context, EditText editText) {
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.requestFocus();
InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(editText, 0);
}
/**
* 切换键盘显示与否状态
*/
public static void toggleSoftInput(Context context, EditText editText) {
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.requestFocus();
InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
|
3e0201add078aaaf01596bdfc31aafefb1d7c849 | 15,416 | java | Java | client/src/main/java/com/cezarykluczynski/stapi/client/api/StapiSoapClient.java | tj-harris/stapi | a7db769841d2dbf4c0bd05f00e26bdc9fd9e5341 | [
"MIT"
] | 104 | 2017-04-27T17:50:40.000Z | 2022-03-20T07:50:34.000Z | client/src/main/java/com/cezarykluczynski/stapi/client/api/StapiSoapClient.java | tj-harris/stapi | a7db769841d2dbf4c0bd05f00e26bdc9fd9e5341 | [
"MIT"
] | 15 | 2017-06-17T11:54:29.000Z | 2022-03-02T02:38:51.000Z | client/src/main/java/com/cezarykluczynski/stapi/client/api/StapiSoapClient.java | tj-harris/stapi | a7db769841d2dbf4c0bd05f00e26bdc9fd9e5341 | [
"MIT"
] | 14 | 2017-05-05T19:50:46.000Z | 2022-01-15T12:58:23.000Z | 35.851163 | 90 | 0.840361 | 847 | package com.cezarykluczynski.stapi.client.api;
import com.cezarykluczynski.stapi.client.api.soap.Animal;
import com.cezarykluczynski.stapi.client.api.soap.ApiKeySupplier;
import com.cezarykluczynski.stapi.client.api.soap.AstronomicalObject;
import com.cezarykluczynski.stapi.client.api.soap.Book;
import com.cezarykluczynski.stapi.client.api.soap.BookCollection;
import com.cezarykluczynski.stapi.client.api.soap.BookSeries;
import com.cezarykluczynski.stapi.client.api.soap.Character;
import com.cezarykluczynski.stapi.client.api.soap.ComicCollection;
import com.cezarykluczynski.stapi.client.api.soap.ComicSeries;
import com.cezarykluczynski.stapi.client.api.soap.ComicStrip;
import com.cezarykluczynski.stapi.client.api.soap.Comics;
import com.cezarykluczynski.stapi.client.api.soap.Company;
import com.cezarykluczynski.stapi.client.api.soap.Conflict;
import com.cezarykluczynski.stapi.client.api.soap.Element;
import com.cezarykluczynski.stapi.client.api.soap.Episode;
import com.cezarykluczynski.stapi.client.api.soap.Food;
import com.cezarykluczynski.stapi.client.api.soap.Literature;
import com.cezarykluczynski.stapi.client.api.soap.Location;
import com.cezarykluczynski.stapi.client.api.soap.Magazine;
import com.cezarykluczynski.stapi.client.api.soap.MagazineSeries;
import com.cezarykluczynski.stapi.client.api.soap.Material;
import com.cezarykluczynski.stapi.client.api.soap.MedicalCondition;
import com.cezarykluczynski.stapi.client.api.soap.Movie;
import com.cezarykluczynski.stapi.client.api.soap.Occupation;
import com.cezarykluczynski.stapi.client.api.soap.Organization;
import com.cezarykluczynski.stapi.client.api.soap.Performer;
import com.cezarykluczynski.stapi.client.api.soap.Season;
import com.cezarykluczynski.stapi.client.api.soap.Series;
import com.cezarykluczynski.stapi.client.api.soap.Soundtrack;
import com.cezarykluczynski.stapi.client.api.soap.Spacecraft;
import com.cezarykluczynski.stapi.client.api.soap.SpacecraftClass;
import com.cezarykluczynski.stapi.client.api.soap.Species;
import com.cezarykluczynski.stapi.client.api.soap.Staff;
import com.cezarykluczynski.stapi.client.api.soap.Technology;
import com.cezarykluczynski.stapi.client.api.soap.Title;
import com.cezarykluczynski.stapi.client.api.soap.TradingCard;
import com.cezarykluczynski.stapi.client.api.soap.TradingCardDeck;
import com.cezarykluczynski.stapi.client.api.soap.TradingCardSet;
import com.cezarykluczynski.stapi.client.api.soap.VideoGame;
import com.cezarykluczynski.stapi.client.api.soap.VideoRelease;
import com.cezarykluczynski.stapi.client.api.soap.Weapon;
import com.cezarykluczynski.stapi.client.v1.soap.AnimalPortType;
import com.cezarykluczynski.stapi.client.v1.soap.AstronomicalObjectPortType;
import com.cezarykluczynski.stapi.client.v1.soap.BookCollectionPortType;
import com.cezarykluczynski.stapi.client.v1.soap.BookPortType;
import com.cezarykluczynski.stapi.client.v1.soap.BookSeriesPortType;
import com.cezarykluczynski.stapi.client.v1.soap.CharacterPortType;
import com.cezarykluczynski.stapi.client.v1.soap.ComicCollectionPortType;
import com.cezarykluczynski.stapi.client.v1.soap.ComicSeriesPortType;
import com.cezarykluczynski.stapi.client.v1.soap.ComicStripPortType;
import com.cezarykluczynski.stapi.client.v1.soap.ComicsPortType;
import com.cezarykluczynski.stapi.client.v1.soap.CompanyPortType;
import com.cezarykluczynski.stapi.client.v1.soap.ConflictPortType;
import com.cezarykluczynski.stapi.client.v1.soap.ElementPortType;
import com.cezarykluczynski.stapi.client.v1.soap.EpisodePortType;
import com.cezarykluczynski.stapi.client.v1.soap.FoodPortType;
import com.cezarykluczynski.stapi.client.v1.soap.LiteraturePortType;
import com.cezarykluczynski.stapi.client.v1.soap.LocationPortType;
import com.cezarykluczynski.stapi.client.v1.soap.MagazinePortType;
import com.cezarykluczynski.stapi.client.v1.soap.MagazineSeriesPortType;
import com.cezarykluczynski.stapi.client.v1.soap.MaterialPortType;
import com.cezarykluczynski.stapi.client.v1.soap.MedicalConditionPortType;
import com.cezarykluczynski.stapi.client.v1.soap.MoviePortType;
import com.cezarykluczynski.stapi.client.v1.soap.OccupationPortType;
import com.cezarykluczynski.stapi.client.v1.soap.OrganizationPortType;
import com.cezarykluczynski.stapi.client.v1.soap.PerformerPortType;
import com.cezarykluczynski.stapi.client.v1.soap.SeasonPortType;
import com.cezarykluczynski.stapi.client.v1.soap.SeriesPortType;
import com.cezarykluczynski.stapi.client.v1.soap.SoundtrackPortType;
import com.cezarykluczynski.stapi.client.v1.soap.SpacecraftClassPortType;
import com.cezarykluczynski.stapi.client.v1.soap.SpacecraftPortType;
import com.cezarykluczynski.stapi.client.v1.soap.SpeciesPortType;
import com.cezarykluczynski.stapi.client.v1.soap.StaffPortType;
import com.cezarykluczynski.stapi.client.v1.soap.TechnologyPortType;
import com.cezarykluczynski.stapi.client.v1.soap.TitlePortType;
import com.cezarykluczynski.stapi.client.v1.soap.TradingCardDeckPortType;
import com.cezarykluczynski.stapi.client.v1.soap.TradingCardPortType;
import com.cezarykluczynski.stapi.client.v1.soap.TradingCardSetPortType;
import com.cezarykluczynski.stapi.client.v1.soap.VideoGamePortType;
import com.cezarykluczynski.stapi.client.v1.soap.VideoReleasePortType;
import com.cezarykluczynski.stapi.client.v1.soap.WeaponPortType;
import lombok.Getter;
public class StapiSoapClient extends AbstractStapiClient implements StapiClient {
@Getter
private String apiUrl;
private StapiSoapPortTypesProvider stapiSoapPortTypesProvider;
private ApiKeySupplier apiKeySupplier;
@Getter
private AnimalPortType animalPortType;
@Getter
private AstronomicalObjectPortType astronomicalObjectPortType;
@Getter
private BookPortType bookPortType;
@Getter
private BookCollectionPortType bookCollectionPortType;
@Getter
private BookSeriesPortType bookSeriesPortType;
@Getter
private CharacterPortType characterPortType;
@Getter
private ComicCollectionPortType comicCollectionPortType;
@Getter
private ComicsPortType comicsPortType;
@Getter
private ComicSeriesPortType comicSeriesPortType;
@Getter
private ComicStripPortType comicStripPortType;
@Getter
private CompanyPortType companyPortType;
@Getter
private ConflictPortType conflictPortType;
@Getter
private ElementPortType elementPortType;
@Getter
private EpisodePortType episodePortType;
@Getter
private FoodPortType foodPortType;
@Getter
private LiteraturePortType literaturePortType;
@Getter
private LocationPortType locationPortType;
@Getter
private MagazinePortType magazinePortType;
@Getter
private MagazineSeriesPortType magazineSeriesPortType;
@Getter
private MaterialPortType materialPortType;
@Getter
private MedicalConditionPortType medicalConditionPortType;
@Getter
private MoviePortType moviePortType;
@Getter
private OccupationPortType occupationPortType;
@Getter
private OrganizationPortType organizationPortType;
@Getter
private PerformerPortType performerPortType;
@Getter
private SeasonPortType seasonPortType;
@Getter
private SeriesPortType seriesPortType;
@Getter
private SoundtrackPortType soundtrackPortType;
@Getter
private SpacecraftPortType spacecraftPortType;
@Getter
private SpacecraftClassPortType spacecraftClassPortType;
@Getter
private SpeciesPortType speciesPortType;
@Getter
private StaffPortType staffPortType;
@Getter
private TechnologyPortType technologyPortType;
@Getter
private TitlePortType titlePortType;
@Getter
private TradingCardPortType tradingCardPortType;
@Getter
private TradingCardDeckPortType tradingCardDeckPortType;
@Getter
private TradingCardSetPortType tradingCardSetPortType;
@Getter
private VideoGamePortType videoGamePortType;
@Getter
private VideoReleasePortType videoReleasePortType;
@Getter
private WeaponPortType weaponPortType;
@Getter
private Animal animal;
@Getter
private AstronomicalObject astronomicalObject;
@Getter
private Book book;
@Getter
private BookCollection bookCollection;
@Getter
private BookSeries bookSeries;
@Getter
private Character character;
@Getter
private ComicCollection comicCollection;
@Getter
private Comics comics;
@Getter
private ComicSeries comicSeries;
@Getter
private ComicStrip comicStrip;
@Getter
private Company company;
@Getter
private Conflict conflict;
@Getter
private Element element;
@Getter
private Episode episode;
@Getter
private Food food;
@Getter
private Literature literature;
@Getter
private Location location;
@Getter
private Magazine magazine;
@Getter
private MagazineSeries magazineSeries;
@Getter
private Material material;
@Getter
private MedicalCondition medicalCondition;
@Getter
private Movie movie;
@Getter
private Occupation occupation;
@Getter
private Organization organization;
@Getter
private Performer performer;
@Getter
private Season season;
@Getter
private Series series;
@Getter
private Soundtrack soundtrack;
@Getter
private Spacecraft spacecraft;
@Getter
private SpacecraftClass spacecraftClass;
@Getter
private Species species;
@Getter
private Staff staff;
@Getter
private Technology technology;
@Getter
private Title title;
@Getter
private TradingCard tradingCard;
@Getter
private TradingCardDeck tradingCardDeck;
@Getter
private TradingCardSet tradingCardSet;
@Getter
private VideoGame videoGame;
@Getter
private VideoRelease videoRelease;
@Getter
private Weapon weapon;
public StapiSoapClient(String apiUrl, String apiKey) {
this.apiUrl = validateUrl(defaultIfBlank(apiUrl, CANONICAL_API_URL));
stapiSoapPortTypesProvider = new StapiSoapPortTypesProvider(this.apiUrl);
apiKeySupplier = new ApiKeySupplier(apiKey);
bindPortTypes();
createApiKeyAwareProxies();
}
private void bindPortTypes() {
animalPortType = stapiSoapPortTypesProvider.getAnimalPortType();
astronomicalObjectPortType = stapiSoapPortTypesProvider.getAstronomicalObjectPortType();
bookPortType = stapiSoapPortTypesProvider.getBookPortType();
bookCollectionPortType = stapiSoapPortTypesProvider.getBookCollectionPortType();
bookSeriesPortType = stapiSoapPortTypesProvider.getBookSeriesPortType();
characterPortType = stapiSoapPortTypesProvider.getCharacterPortType();
comicCollectionPortType = stapiSoapPortTypesProvider.getComicCollectionPortType();
comicsPortType = stapiSoapPortTypesProvider.getComicsPortType();
comicSeriesPortType = stapiSoapPortTypesProvider.getComicSeriesPortType();
comicStripPortType = stapiSoapPortTypesProvider.getComicStripPortType();
companyPortType = stapiSoapPortTypesProvider.getCompanyPortType();
conflictPortType = stapiSoapPortTypesProvider.getConflictPortType();
elementPortType = stapiSoapPortTypesProvider.getElementPortType();
episodePortType = stapiSoapPortTypesProvider.getEpisodePortType();
foodPortType = stapiSoapPortTypesProvider.getFoodPortType();
literaturePortType = stapiSoapPortTypesProvider.getLiteraturePortType();
locationPortType = stapiSoapPortTypesProvider.getLocationPortType();
magazinePortType = stapiSoapPortTypesProvider.getMagazinePortType();
magazineSeriesPortType = stapiSoapPortTypesProvider.getMagazineSeriesPortType();
materialPortType = stapiSoapPortTypesProvider.getMaterialPortType();
medicalConditionPortType = stapiSoapPortTypesProvider.getMedicalConditionPortType();
moviePortType = stapiSoapPortTypesProvider.getMoviePortType();
occupationPortType = stapiSoapPortTypesProvider.getOccupationPortType();
organizationPortType = stapiSoapPortTypesProvider.getOrganizationPortType();
performerPortType = stapiSoapPortTypesProvider.getPerformerPortType();
seasonPortType = stapiSoapPortTypesProvider.getSeasonPortType();
seriesPortType = stapiSoapPortTypesProvider.getSeriesPortType();
soundtrackPortType = stapiSoapPortTypesProvider.getSoundtrackPortType();
spacecraftPortType = stapiSoapPortTypesProvider.getSpacecraftPortType();
spacecraftClassPortType = stapiSoapPortTypesProvider.getSpacecraftClassPortType();
speciesPortType = stapiSoapPortTypesProvider.getSpeciesPortType();
staffPortType = stapiSoapPortTypesProvider.getStaffPortType();
technologyPortType = stapiSoapPortTypesProvider.getTechnologyPortType();
titlePortType = stapiSoapPortTypesProvider.getTitlePortType();
tradingCardPortType = stapiSoapPortTypesProvider.getTradingCardPortType();
tradingCardDeckPortType = stapiSoapPortTypesProvider.getTradingCardDeckPortType();
tradingCardSetPortType = stapiSoapPortTypesProvider.getTradingCardSetPortType();
videoGamePortType = stapiSoapPortTypesProvider.getVideoGamePortType();
videoReleasePortType = stapiSoapPortTypesProvider.getVideoReleasePortType();
weaponPortType = stapiSoapPortTypesProvider.getWeaponPortType();
}
private void createApiKeyAwareProxies() {
animal = new Animal(animalPortType, apiKeySupplier);
astronomicalObject = new AstronomicalObject(astronomicalObjectPortType, apiKeySupplier);
book = new Book(bookPortType, apiKeySupplier);
bookCollection = new BookCollection(bookCollectionPortType, apiKeySupplier);
bookSeries = new BookSeries(bookSeriesPortType, apiKeySupplier);
character = new Character(characterPortType, apiKeySupplier);
comicCollection = new ComicCollection(comicCollectionPortType, apiKeySupplier);
comics = new Comics(comicsPortType, apiKeySupplier);
comicSeries = new ComicSeries(comicSeriesPortType, apiKeySupplier);
comicStrip = new ComicStrip(comicStripPortType, apiKeySupplier);
company = new Company(companyPortType, apiKeySupplier);
conflict = new Conflict(conflictPortType, apiKeySupplier);
element = new Element(elementPortType, apiKeySupplier);
episode = new Episode(episodePortType, apiKeySupplier);
food = new Food(foodPortType, apiKeySupplier);
literature = new Literature(literaturePortType, apiKeySupplier);
location = new Location(locationPortType, apiKeySupplier);
magazine = new Magazine(magazinePortType, apiKeySupplier);
magazineSeries = new MagazineSeries(magazineSeriesPortType, apiKeySupplier);
material = new Material(materialPortType, apiKeySupplier);
medicalCondition = new MedicalCondition(medicalConditionPortType, apiKeySupplier);
movie = new Movie(moviePortType, apiKeySupplier);
occupation = new Occupation(occupationPortType, apiKeySupplier);
organization = new Organization(organizationPortType, apiKeySupplier);
performer = new Performer(performerPortType, apiKeySupplier);
season = new Season(seasonPortType, apiKeySupplier);
series = new Series(seriesPortType, apiKeySupplier);
soundtrack = new Soundtrack(soundtrackPortType, apiKeySupplier);
spacecraft = new Spacecraft(spacecraftPortType, apiKeySupplier);
spacecraftClass = new SpacecraftClass(spacecraftClassPortType, apiKeySupplier);
species = new Species(speciesPortType, apiKeySupplier);
staff = new Staff(staffPortType, apiKeySupplier);
technology = new Technology(technologyPortType, apiKeySupplier);
title = new Title(titlePortType, apiKeySupplier);
tradingCard = new TradingCard(tradingCardPortType, apiKeySupplier);
tradingCardDeck = new TradingCardDeck(tradingCardDeckPortType, apiKeySupplier);
tradingCardSet = new TradingCardSet(tradingCardSetPortType, apiKeySupplier);
videoGame = new VideoGame(videoGamePortType, apiKeySupplier);
videoRelease = new VideoRelease(videoReleasePortType, apiKeySupplier);
weapon = new Weapon(weaponPortType, apiKeySupplier);
}
}
|
3e0201f5eb650940a5f34bd375190f32eca06ec0 | 5,129 | java | Java | retro/throttling/src/test/java/edu/brown/cs/systems/retro/throttling/schedulers/MClockTester.java | maniaabdi/tracing-framework | fb1c35858bfe51635639a06c8a9db57cbc726d6b | [
"BSD-3-Clause"
] | 82 | 2016-02-29T05:21:22.000Z | 2021-12-05T05:31:54.000Z | retro/throttling/src/test/java/edu/brown/cs/systems/retro/throttling/schedulers/MClockTester.java | tejeswinisundaram/tracing-framework | 3560ffea96508c4ad04ae0f1b235603f3bf1d4cf | [
"BSD-3-Clause"
] | 4 | 2016-10-27T18:36:19.000Z | 2021-04-19T15:03:58.000Z | retro/throttling/src/test/java/edu/brown/cs/systems/retro/throttling/schedulers/MClockTester.java | tejeswinisundaram/tracing-framework | 3560ffea96508c4ad04ae0f1b235603f3bf1d4cf | [
"BSD-3-Clause"
] | 23 | 2016-03-19T16:14:10.000Z | 2021-12-05T05:31:56.000Z | 30.89759 | 116 | 0.570677 | 848 | package edu.brown.cs.systems.retro.throttling.schedulers;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import edu.brown.cs.systems.retro.throttling.mclock.MClock;
import edu.brown.cs.systems.retro.throttling.ratelimiters.RateLimiter;
public class MClockTester {
public static void main(String[] args) throws InterruptedException {
MClockTester t = new MClockTester(1, 1);
t.startThreads(1, 100, 1, 500000000);
t.startThreads(2, 100, 1, 500000000);
// t.startThreads(3, 20, 1, 500000000);
// t.startThreads(4, 40, 1, 500000000);
// t.setReservation(1, 1);
// t.setReservation(2, 5);
t.setLimit(1, 10);
// t.setWeight(1, 9);
// t.setWeight(2, 1);
for (int i = 0; i < 10; i++) {
Thread.currentThread().sleep(1000);
System.out.println(t);
}
t.setResourceCapacity(100);
while (!Thread.currentThread().isInterrupted()) {
Thread.currentThread().sleep(1000);
System.out.println(t);
}
t.shutdown();
}
private void shutdown() {
for (TenantTester t : tenants.values())
t.shutdown();
}
private static final Random rnd = new Random();
private static long sampleExponential(long mean) {
double x = rnd.nextDouble();
long e = Math.round(-Math.log(1 - x) * mean); // (1-x) because we want
// (0,1] not [0,1)
e = Math.min(mean * 20, e);
return e;
}
private final MClock mclock;
private final RateLimiter resource;
private Map<Integer, TenantTester> tenants = new HashMap<Integer, TenantTester>();
public MClockTester(int resourceCapacity, int mclockConcurrency) {
this.mclock = new MClock(mclockConcurrency);
this.resource = new RateLimiter(resourceCapacity);
}
public void startThreads(int tenantId, int numthreads, int opsize, long nanosBetweenRequests) {
TenantTester tester = tenants.get(tenantId);
if (tester == null) {
tester = new TenantTester(tenantId);
tenants.put(tenantId, tester);
}
tester.startThreads(numthreads, opsize, nanosBetweenRequests);
}
public void setResourceCapacity(double capacity) {
resource.setRate(capacity);
}
public void setReservation(int tenantId, double reservation) {
mclock.setReservation(tenantId, reservation);
}
public void setWeight(int tenantId, double weight) {
mclock.setWeight(tenantId, weight);
}
public void setLimit(int tenantId, double limit) {
mclock.setLimit(tenantId, limit);
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
Integer[] tenantIds = tenants.keySet().toArray(new Integer[0]);
Arrays.sort(tenantIds);
for (Integer tenantId : tenantIds) {
b.append(tenants.get(tenantId));
b.append("\n");
}
return b.toString();
}
private class TenantTester {
private Collection<TenantThread> threads = new HashSet<TenantThread>();
private AtomicInteger consumed = new AtomicInteger();
private final int tenantid;
public TenantTester(int tenantid) {
this.tenantid = tenantid;
}
public void shutdown() {
for (TenantThread t : threads)
t.interrupt();
}
public void startThreads(int numToStart, int opsize, long nanosBetweenRequests) {
for (int i = 0; i < numToStart; i++) {
TenantThread thread = new TenantThread(opsize, nanosBetweenRequests);
thread.start();
threads.add(thread);
}
}
@Override
public String toString() {
return String.format("t-%d numthreads=%d consumed=%d", tenantid, threads.size(), consumed.getAndSet(0));
}
private class TenantThread extends Thread {
private final int opsize;
private final long nanos;
public TenantThread(int opsize, long nanos) {
this.opsize = opsize;
this.nanos = nanos;
}
@Override
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
long tosleep = sampleExponential(nanos);
if (tosleep > 0)
Thread.sleep(nanos / 1000000, (int) (nanos % 1000000));
mclock.schedule(tenantid, opsize);
resource.acquire(opsize);
mclock.complete();
consumed.addAndGet(opsize);
}
} catch (InterruptedException e) {
// End thread
}
}
}
}
} |
3e020232bfc385362aa1c2c33e1d695859f77d11 | 3,107 | java | Java | src/main/java/act/app/RuntimeDirs.java | kehao-study/act_compile | b9381a9a0a83297bad7aebe8898f6ef12852ce03 | [
"Apache-2.0"
] | 776 | 2015-06-17T01:08:11.000Z | 2022-03-18T10:58:56.000Z | src/main/java/act/app/RuntimeDirs.java | kehao-study/act_compile | b9381a9a0a83297bad7aebe8898f6ef12852ce03 | [
"Apache-2.0"
] | 1,390 | 2015-05-25T20:24:44.000Z | 2022-01-24T23:49:33.000Z | src/main/java/act/app/RuntimeDirs.java | benstonezhang/actframework | 2554aced980de115939bfad4d003c74ff8f04112 | [
"Apache-2.0"
] | 149 | 2015-05-29T08:38:34.000Z | 2022-02-12T16:01:29.000Z | 31.383838 | 151 | 0.620212 | 849 | package act.app;
/*-
* #%L
* ACT Framework
* %%
* Copyright (C) 2014 - 2017 ActFramework
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import static act.app.ProjectLayout.Utils.file;
import static act.route.RouteTableRouterBuilder.ROUTES_FILE;
import act.Act;
import act.app.util.NamedPort;
import org.osgl.util.S;
import java.io.File;
import java.util.*;
/**
* Define application dir structure at runtime
*/
public enum RuntimeDirs {
;
public static final String CONF = "/conf";
public static final String ASSET = "/asset";
public static final String CLASSES = "/classes";
public static final String LIB = "/lib";
public static File home(App app) {
if (Act.isDev()) {
return app.layout().target(app.base());
} else {
return app.base();
}
}
public static File resource(App app) {
//return Act.isDev() ? app.layout().resource(app.base()) : classes(app);
return app.layout().resource(Act.isDev() ? app.base() : app.home());
}
public static File conf(App app) {
File confBase = app.layout().resource(Act.isDev() ? app.base() : app.home()); //Act.isDev() ? app.layout().resource(app.base()) : classes(app);
File file = new File(confBase, CONF);
return file.exists() ? file : confBase;
}
public static Map<String, List<File>> routes(App app) {
Map<String, List<File>> map = new HashMap();
File base = resource(app);
map.put(NamedPort.DEFAULT, routes(base, ROUTES_FILE));
for (NamedPort np : app.config().namedPorts()) {
String npName = np.name();
String routesConfName = S.concat("routes.", npName, ".conf");
map.put(npName, routes(base, routesConfName));
}
return map;
}
private static List<File> routes(File base, String name) {
List<File> routes = new ArrayList<>();
routes.add(file(base, name));
File confRoot = file(base, CONF);
routes.add(file(confRoot, name));
File profileRooot = file(confRoot, Act.profile());
routes.add(file(profileRooot, name));
return routes;
}
public static File classes(App app) {
File file = new File(app.home(), app.layout().classes());
if (!file.exists()) {
// suppose we starts PROD mode from IDE
file = new File(app.layout().target(app.home()), app.layout().classes());
}
return file;
}
public static File lib(App app) {
return new File(app.home(), LIB);
}
}
|
3e02028d33662fd4cbffe7e202eed7d6301c9a0d | 8,617 | java | Java | src/chess/ui/PieceUI.java | pvmoore/chess | f479699187dc773ac2b4814c4afe3242a0e1e218 | [
"MIT"
] | null | null | null | src/chess/ui/PieceUI.java | pvmoore/chess | f479699187dc773ac2b4814c4afe3242a0e1e218 | [
"MIT"
] | null | null | null | src/chess/ui/PieceUI.java | pvmoore/chess | f479699187dc773ac2b4814c4afe3242a0e1e218 | [
"MIT"
] | null | null | null | 35.755187 | 115 | 0.544273 | 850 | package chess.ui;
import chess.engine.Game;
import chess.engine.Move;
import chess.engine.Piece;
import chess.engine.Side;
import chess.engine.byteboard.MoveGenerator;
import chess.engine.byteboard.Position;
import juice.Frame;
import juice.animation.Animation;
import juice.animation.Key;
import juice.animation.easing.EasingType;
import juice.components.DragComponent;
import juice.components.Sprite;
import juice.components.UIComponent;
import juice.graphics.Texture;
import juice.types.Int2;
final public class PieceUI extends Sprite implements DragComponent.Listener, Game.Listener {
private ChessUI chess;
private Piece piece;
private Side side;
private DragComponent dragComponent;
private Int2 originalPos;
private int square = -1; // the square we are on, or -1 if not on the board
public Piece getPiece() { return piece; }
public Side getSide() { return side; }
public PieceUI(ChessUI chess, Piece p, Side side) {
this.chess = chess;
this.piece = p;
this.side = side;
this.dragComponent = new DragComponent(this);
this.dragComponent.disable();
var pieceStr = p.toString().toLowerCase();
var sideStr = side.toString().toLowerCase();
String filename = "128/"+sideStr+"_"+pieceStr+".png";
setTexture(Texture.get(filename, Texture.standardAttribs));
setVP(chess.getCamera().VP());
chess.getGame().addListener(this);
}
// Drag.Listener
@Override public UIComponent getComponent() {
return this;
}
public void setSquare(int sq) {
this.square = sq;
enableDragIfItsHumansTurn();
}
// UIComponent
@Override public void onRemoved() {
square = -1;
}
// Implement UIComponent / extend Sprite
@Override public void update(Frame frame) {
super.update(frame);
dragComponent.update(frame);
}
// Implement DragComponent.Listener
@Override public void onDragMoved(Int2 delta) {
if(originalPos==null) {
originalPos = getRelPos();
// Move this component to the end of the draw queue so that
// it is drawn over all other pieces
getStage().addAfterUpdateHook(()-> getParent().moveToFront(this));
}
}
// Implement DragComponent.Listener
@Override public void onDragDropped(Int2 delta) {
var board = (BoardUI)getParent();
var from = board.getBoardSquare(originalPos, getSize());
var to = board.getBoardSquare(getRelPos(), getSize());
var gen = new MoveGenerator();
var move = gen.getMove(chess.getGame().getPosition(), from, to);
//System.out.println("move "+Move.toString(move));
if(move==-1) {
// Move the piece back to its original position
animateTo(board.getPosForSquare(square), EasingType.EASE_OUT);
} else {
if(piece==Piece.PAWN && (to<8 || to>55)) {
// If move is a promotion then ask the player to select a piece
var popup = chess.getPromotionPopupUI();
getStage().addAfterUpdateHook(() -> {
setSquare(-1);
popup.activate(this, from, to);
});
} else {
chess.getGame().makeMove(move);
}
}
originalPos = null;
}
// Implement Game.Listener
@Override public void onNewGame(Position pos) {
enableDragIfItsHumansTurn();
}
// Implement Game.Listener
@Override public void onGameMove(Position pos, int move) {
if(!isOnBoard()) {
return;
}
var game = chess.getGame();
var to = Move.to(move);
boolean moved = Move.from(move)==square;
boolean captured = Move.to(move)==square;
var flags = Move.flags(move);
var moveSide = pos.sideToMove().opposite();
if(flags==Move.Flags.ENPASSANT) {
var enPassantPieceSquare = moveSide==Side.WHITE ? to-8 : to+8;
if(square==enPassantPieceSquare) {
captured = true;
}
}
if(moved) {
// This piece was moved
square = Move.to(move);
var board = (BoardUI)getParent();
var sqPos = board.getPosForSquare(square);
var easing = game.isHumansMove() ? EasingType.EASE_IN_OUT : EasingType.EASE_OUT;
Key.EndCallback atEnd = null;
// Handle promotion by computer
if(game.isHumansMove() && flags.isPromotion()) {
// After the move animation, detach this piece and add the promoted piece
atEnd = ()-> {
var ui = chess.getPieces().takeFromBox(flags.getPromotionPiece(), pos.sideToMove().opposite());
ui.setRelPos(getRelPos());
ui.setSize(getSize());
ui.setSquare(square);
chess.getBoardUI().add(ui);
setSquare(-1);
detach();
};
}
animateTo(sqPos, easing, atEnd);
} else if(captured) {
// This piece was captured
getStage().addAfterUpdateHook(()->{
// Move this piece to the captures UI component
var oldPos = getAbsPos();
var newPos = chess.getCapturesUI().getAbsPos();
var diff = oldPos.sub(newPos);
setRelPos(diff);
chess.getCapturesUI().add(this);
setSquare(-1);
});
} else if(piece==Piece.ROOK && Move.flags(move).isCastle()) {
// We are a rook and the move was a castle.
// Check to see if we are the affected rook
var rookFrom = to==6 ? 7 :
to==2 ? 0 :
to==62 ? 63 : 56;
if(rookFrom==square) {
// Yes. It's us
var board = (BoardUI)getParent();
var easing = chess.getGame().isHumansMove() ? EasingType.EASE_IN_OUT : EasingType.EASE_OUT;
var rookTo = Move.flags(move)==Move.Flags.OO ? square-2 : square+3;
var sqPos = board.getPosForSquare(rookTo);
square = rookTo;
animateTo(sqPos, easing);
}
}
enableDragIfItsHumansTurn();
}
// Implement Game.Listener
@Override public void onGameMoveUndone(Position pos, int move) {
if(Move.to(move)==square) {
// We got moved back
square = Move.from(move);
var board = (BoardUI)getParent();
var sqPos = board.getPosForSquare(square);
animateTo(sqPos, EasingType.EASE_IN_OUT);
}
enableDragIfItsHumansTurn();
}
// Implement Game.Listener
@Override public void onGameOver(Position pos, boolean resignation) {
dragComponent.disable();
}
//===========================================================================
private boolean isOnBoard() {
return square != -1;
}
private boolean itsHumansTurn() {
var game = chess.getGame();
var thisIsHumansPiece = (side==game.humanPlayersSide());
return thisIsHumansPiece && game.isHumansMove();
}
private void enableDragIfItsHumansTurn() {
if(isOnBoard() && itsHumansTurn()) {
dragComponent.enable();
} else {
dragComponent.disable();
}
}
private void animateTo(Int2 to, EasingType easingType) {
animateTo(to, easingType, null);
}
private void animateTo(Int2 to, EasingType easingType, Key.EndCallback atEnd) {
var pos = getRelPos();
Animation a = new Animation(60, new double[]{pos.getX(),pos.getY()}, Animation.EndPolicy.DISCARD)
.addKey(key->key.frame(30)
.values(new double[]{to.getX(), to.getY()})
.easing(easingType)
.atEnd(atEnd)
.eachFrame((frame, values) -> {
if(!isOnBoard()) {
return;
}
int x = (int)Math.round(values[0]);
int y = (int)Math.round(values[1]);
setRelPos(new Int2(x, y));
})
);
getStage().getAnimations().add(a, true);
}
}
|
3e02030d6757092ac9a113197682b7f46b0a78b6 | 1,636 | java | Java | spring-boot/src/main/java/xyy/java/note/aspect/HttpAspect.java | i37oC/java-note | 5c5e43ccb161e03cda5fcf014a6cd5acaafe14db | [
"Apache-2.0"
] | null | null | null | spring-boot/src/main/java/xyy/java/note/aspect/HttpAspect.java | i37oC/java-note | 5c5e43ccb161e03cda5fcf014a6cd5acaafe14db | [
"Apache-2.0"
] | null | null | null | spring-boot/src/main/java/xyy/java/note/aspect/HttpAspect.java | i37oC/java-note | 5c5e43ccb161e03cda5fcf014a6cd5acaafe14db | [
"Apache-2.0"
] | null | null | null | 28.206897 | 127 | 0.680318 | 851 | package xyy.java.note.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* @author xyy
* @version 1.0 2017/5/14.
* @since 1.0
*/
@Aspect
@Component
public class HttpAspect {
private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);
@Pointcut("execution(public * xyy.java.note.controller.GrilController.*(..))")
public void log(){
}
@Before("log()")
public void doBefore(JoinPoint joinPoint){
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//URL
logger.info("url={}", request.getRequestURL());
//METHOD
logger.info("method={}", request.getMethod());
//IP
logger.info("ip={}", request.getRemoteAddr());
//类方法
logger.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
//参数
logger.info("args={}", joinPoint.getArgs());
}
@After("log()")
public void doAfter(){
logger.info("2222222222");
}
@AfterReturning(pointcut = "log()", returning = "object")
public void doAfterReturing(Object object){
logger.info("response={}", object);
}
}
|
3e0203bb163b74759d250e16dadc9dae6e3fd2d9 | 7,151 | java | Java | rice-framework/krad-web-framework/src/main/java/org/kuali/rice/krad/uif/layout/GridLayoutManager.java | colostate-is/kualico-rice | d6707143751d4ec9617be8f9708466863aa5b4ef | [
"ECL-2.0"
] | 5 | 2017-07-14T20:30:18.000Z | 2021-08-02T09:06:37.000Z | rice-framework/krad-web-framework/src/main/java/org/kuali/rice/krad/uif/layout/GridLayoutManager.java | colostate-is/kualico-rice | d6707143751d4ec9617be8f9708466863aa5b4ef | [
"ECL-2.0"
] | 69 | 2015-07-22T00:51:58.000Z | 2021-02-05T22:13:19.000Z | rice-framework/krad-web-framework/src/main/java/org/kuali/rice/krad/uif/layout/GridLayoutManager.java | ua-eas/rice | 0082ff427b20fb49925a98aa4c7b9a6269150931 | [
"ECL-2.0"
] | 13 | 2017-05-30T20:18:00.000Z | 2022-01-15T03:27:06.000Z | 33.909953 | 134 | 0.645982 | 852 | /**
* Copyright 2005-2019 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.krad.uif.layout;
import java.util.List;
/**
* Layout manager interface for grid layouts.
*
* @author Kuali Rice Team ([email protected])
*/
public interface GridLayoutManager extends LayoutManager {
/**
* Indicates the number of columns that should make up one row of data
*
* <p>
* If the item count is greater than the number of columns, a new row will
* be created to render the remaining items (and so on until all items are
* placed).
* </p>
*
* <p>
* Note this does not include any generated columns by the layout manager,
* so the final column count could be greater (if label fields are
* separate).
* </p>
*
* @return int
*/
int getNumberOfColumns();
/**
* Setter for the number of columns (each row)
*
* @param numberOfColumns
*/
void setNumberOfColumns(int numberOfColumns);
/**
* Indicates whether the number of columns for the table data should match
* the number of fields given in the container's items list (so that each
* field takes up one column without wrapping), this overrides the configured
* numberOfColumns
*
* <p>
* If set to true during the initialize phase the number of columns will be
* set to the size of the container's field list, if false the configured
* number of columns is used
* </p>
*
* @return true if the column count should match the container's
* field count, false to use the configured number of columns
*/
boolean isSuppressLineWrapping();
/**
* Setter for the suppressLineWrapping indicator
*
* @param suppressLineWrapping
*/
void setSuppressLineWrapping(boolean suppressLineWrapping);
/**
* Indicates whether alternating row styles should be applied
*
* <p>
* Indicator to layout manager templates to apply alternating row styles.
* See the configured template for the actual style classes used
* </p>
*
* @return true if alternating styles should be applied, false if
* all rows should have the same style
*/
boolean isApplyAlternatingRowStyles();
/**
* Setter for the alternating row styles indicator
*
* @param applyAlternatingRowStyles
*/
void setApplyAlternatingRowStyles(boolean applyAlternatingRowStyles);
/**
* Indicates whether the manager should default the cell widths
*
* <p>
* If true, the manager will set the cell width by equally dividing by the
* number of columns
* </p>
*
* @return true if default cell widths should be applied, false if
* no defaults should be applied
*/
boolean isApplyDefaultCellWidths();
/**
* Setter for the default cell width indicator
*
* @param applyDefaultCellWidths
*/
void setApplyDefaultCellWidths(boolean applyDefaultCellWidths);
/**
* Indicates whether the first cell of each row should be rendered as a header cell (th)
*
* <p>
* When this flag is turned on, the first cell for each row will be rendered as a header cell. If
* {@link #isRenderAlternatingHeaderColumns()} is false, the remaining cells for the row will be rendered
* as data cells, else they will alternate between cell headers
* </p>
*
* @return true if first cell of each row should be rendered as a header cell
*/
boolean isRenderRowFirstCellHeader();
/**
* Setter for render first row column as header indicator
*
* @param renderRowFirstCellHeader
*/
void setRenderRowFirstCellHeader(boolean renderRowFirstCellHeader);
/**
* Indicates whether the first row of items rendered should all be rendered as table header (th) cells
*
* <p>
* Generally when using a grid layout all the cells will be tds or alternating th/td (with the label in the
* th cell). However in some cases it might be desired to display the labels in one row as table header cells (th)
* followed by a row with the corresponding fields in td cells. When this is enabled this type of layout is
* possible
* </p>
*
* @return true if first row should be rendered as header cells
*/
boolean isRenderFirstRowHeader();
/**
* Setter for the first row as header indicator
*
* @param renderFirstRowHeader
*/
void setRenderFirstRowHeader(boolean renderFirstRowHeader);
/**
* Indicates whether header columns (th for tables) should be rendered for
* every other item (alternating)
*
* <p>
* If true the first cell of each row will be rendered as an header, with
* every other cell in the row as a header
* </p>
*
* @return true if alternating headers should be rendered, false if not
*/
boolean isRenderAlternatingHeaderColumns();
/**
* Setter for the render alternating header columns indicator
*
* @param renderAlternatingHeaderColumns
*/
void setRenderAlternatingHeaderColumns(boolean renderAlternatingHeaderColumns);
/**
* List of styles for each row.
*
* <p>Each entry in the list gives the style for the row with the same index. This style will be added to
* the <tr> tag when the table rows are rendered in the grid.tag. This is used to store the styles for newly added lines
* and other special cases like the add item row.</p>
*
* @return list of styles for the rows
*/
List<String> getRowCssClasses();
/**
* @see #getRowCssClasses()
*/
void setRowCssClasses(List<String> rowCssClasses);
/**
* List of data attributes for each row.
*
* <p>Each entry in the list gives the data attributes for the row with the same index. These data attributes will be added to
* the <tr> tag when the table rows are rendered in the grid.tag. This is used to store the data attributes for newly added lines
* and other special cases like the add item row.</p>
*
* @return list of styles for the rows
*/
List<String> getRowDataAttributes();
/**
* @see #getRowDataAttributes()
*/
void setRowDataAttributes(List<String> rowDataAttributes);
}
|
3e0203ee737ba82b5ecee8627d948d67db201696 | 1,327 | java | Java | webservice-spring-cxf-demo-server/src/test/java/com/guigu/jaxrs/Server.java | freestylewill/webservice-spring-cxf-demo | f18a4af110f5a7a74dba007e816c8ff8bdd54c3f | [
"Apache-2.0"
] | null | null | null | webservice-spring-cxf-demo-server/src/test/java/com/guigu/jaxrs/Server.java | freestylewill/webservice-spring-cxf-demo | f18a4af110f5a7a74dba007e816c8ff8bdd54c3f | [
"Apache-2.0"
] | null | null | null | webservice-spring-cxf-demo-server/src/test/java/com/guigu/jaxrs/Server.java | freestylewill/webservice-spring-cxf-demo | f18a4af110f5a7a74dba007e816c8ff8bdd54c3f | [
"Apache-2.0"
] | null | null | null | 34.025641 | 118 | 0.699322 | 853 | package com.guigu.jaxrs;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;
import org.apache.cxf.transport.http.HTTPTransportFactory;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Administrator on 2017/4/11.
*/
public class Server {
public static void main(String[] args){
JAXRSServerFactoryBean factoryBean=new JAXRSServerFactoryBean();
factoryBean.setResourceClasses(ProjectService.class);
factoryBean.setResourceProvider(ProjectService.class,new SingletonResourceProvider(new ProjectServiceImpl()));
factoryBean.setAddress("http://localhost:8082/");
factoryBean.setDestinationFactory(new HTTPTransportFactory());
Map<Object, Object> extmaps=new HashMap<Object,Object>();
extmaps.put("json","application/json");
extmaps.put("xml","application/xml");
factoryBean.setExtensionMappings(extmaps);
Map<Object, Object> lmaps=new HashMap<Object,Object>();
lmaps.put("en","en-gb");
factoryBean.setLanguageMappings(lmaps);
org.apache.cxf.endpoint.Server server = factoryBean.create();
try {
Thread.sleep(1000*60*10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
3e0204d883f77baf252d0f630df22938dfb96a07 | 204 | java | Java | jar-in-jar-creator/src/main/java/com/anatawa12/jarInJar/creator/classPatch/Patcher.java | fixrtm/jar-in-jar-mod | 49db5c058d21ebe1007cd526fb093f969601ce9e | [
"MIT"
] | 3 | 2021-05-05T16:50:54.000Z | 2021-10-01T15:46:11.000Z | jar-in-jar-creator/src/main/java/com/anatawa12/jarInJar/creator/classPatch/Patcher.java | fixrtm/jar-in-jar-mod | 49db5c058d21ebe1007cd526fb093f969601ce9e | [
"MIT"
] | 12 | 2021-10-09T09:04:21.000Z | 2022-03-31T02:20:29.000Z | jar-in-jar-creator/src/main/java/com/anatawa12/jarInJar/creator/classPatch/Patcher.java | fixrtm/jar-in-jar-mod | 49db5c058d21ebe1007cd526fb093f969601ce9e | [
"MIT"
] | null | null | null | 25.5 | 75 | 0.808824 | 854 | package com.anatawa12.jarInJar.creator.classPatch;
import org.objectweb.asm.tree.ClassNode;
public abstract class Patcher {
public abstract ClassNode patch(ClassNode node, ClassPatchParam param);
}
|
3e0205ed48af67c626e77bfb0c0c12ef413c94bd | 902 | java | Java | jforgame-server/src/main/java/jforgame/server/game/admin/commands/CloseServerCommandHandler.java | apaz4/jforgame-master | 3ac0d1a9a0dafc0bcdb583e2d42a49b311d5fe67 | [
"Apache-2.0"
] | 784 | 2017-09-10T06:26:04.000Z | 2022-03-31T09:55:51.000Z | jforgame-server/src/main/java/jforgame/server/game/admin/commands/CloseServerCommandHandler.java | apaz4/jforgame-master | 3ac0d1a9a0dafc0bcdb583e2d42a49b311d5fe67 | [
"Apache-2.0"
] | 19 | 2017-10-18T15:02:06.000Z | 2022-01-06T08:59:58.000Z | jforgame-server/src/main/java/jforgame/server/game/admin/commands/CloseServerCommandHandler.java | apaz4/jforgame-master | 3ac0d1a9a0dafc0bcdb583e2d42a49b311d5fe67 | [
"Apache-2.0"
] | 262 | 2017-09-12T06:07:45.000Z | 2022-03-28T10:43:44.000Z | 33.407407 | 69 | 0.766075 | 855 | package jforgame.server.game.admin.commands;
import jforgame.server.game.admin.http.CommandHandler;
import jforgame.server.game.admin.http.HttpCommandHandler;
import jforgame.server.game.admin.http.HttpCommandParams;
import jforgame.server.game.admin.http.HttpCommandResponse;
import jforgame.server.game.admin.http.HttpCommands;
import jforgame.server.logs.LoggerSystem;
import jforgame.server.thread.SchedulerManager;
@CommandHandler(cmd = HttpCommands.CLOSE_SERVER)
public class CloseServerCommandHandler extends HttpCommandHandler {
@Override
public HttpCommandResponse action(HttpCommandParams httpParams) {
LoggerSystem.HTTP_COMMAND.getLogger().info("收到后台命令,准备停服");
SchedulerManager.schedule(() -> {
//发出关闭信号,交由ServerStartup的关闭钩子处理
Runtime.getRuntime().exit(0);
}, 5 * 1000);
return HttpCommandResponse.valueOfSucc();
}
}
|
3e0206563621f2d71ea524029153a39a39df6630 | 8,350 | java | Java | Examples/app/src/main/java/com/scichart/examples/fragments/FanChartFragment.java | ABTSoftware/SciChart.Android.Examples | 72816bdbe3d2c9c78def807c1773f4dbb73dcca0 | [
"MIT"
] | 198 | 2017-03-15T19:06:37.000Z | 2022-03-31T14:37:02.000Z | Examples/app/src/main/java/com/scichart/examples/fragments/FanChartFragment.java | ABTSoftware/SciChart.Android.Examples | 72816bdbe3d2c9c78def807c1773f4dbb73dcca0 | [
"MIT"
] | 9 | 2017-07-10T07:34:02.000Z | 2021-11-23T08:40:02.000Z | Examples/app/src/main/java/com/scichart/examples/fragments/FanChartFragment.java | ABTSoftware/SciChart.Android.Examples | 72816bdbe3d2c9c78def807c1773f4dbb73dcca0 | [
"MIT"
] | 57 | 2017-04-26T20:32:59.000Z | 2021-12-28T12:34:40.000Z | 51.251534 | 207 | 0.630117 | 856 | //******************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2017. All rights reserved.
//
// Web: http://www.scichart.com
// Support: [email protected]
// Sales: [email protected]
//
// FanChartFragment.java is part of the SCICHART® Examples. Permission is hereby granted
// to modify, create derivative works, distribute and publish any part of this source
// code whether for commercial, private or personal use.
//
// The SCICHART® examples are distributed in the hope that they will be useful, but
// without any warranty. It is provided "AS IS" without warranty of any kind, either
// expressed or implied.
//******************************************************************************
package com.scichart.examples.fragments;
import android.view.animation.DecelerateInterpolator;
import com.scichart.charting.model.dataSeries.XyDataSeries;
import com.scichart.charting.model.dataSeries.XyyDataSeries;
import com.scichart.charting.visuals.SciChartSurface;
import com.scichart.charting.visuals.axes.IAxis;
import com.scichart.charting.visuals.renderableSeries.FastBandRenderableSeries;
import com.scichart.charting.visuals.renderableSeries.FastLineRenderableSeries;
import com.scichart.core.common.Func1;
import com.scichart.core.framework.UpdateSuspender;
import com.scichart.core.utility.IterableUtil;
import com.scichart.drawing.utility.ColorUtil;
import com.scichart.examples.data.RandomWalkGenerator;
import com.scichart.examples.fragments.base.ExampleSingleChartBaseFragment;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class FanChartFragment extends ExampleSingleChartBaseFragment {
@Override
protected void initExample(SciChartSurface surface) {
final IAxis xAxis = sciChartBuilder.newDateAxis().withGrowBy(0.1, 0.1).build();
final IAxis yAxis = sciChartBuilder.newNumericAxis().withGrowBy(0.1, 0.1).build();
final XyDataSeries<Date, Double> actualDataSeries = sciChartBuilder.newXyDataSeries(Date.class, Double.class).build();
final XyyDataSeries<Date, Double> var3DataSeries = sciChartBuilder.newXyyDataSeries(Date.class, Double.class).build();
final XyyDataSeries<Date, Double> var2DataSeries = sciChartBuilder.newXyyDataSeries(Date.class, Double.class).build();
final XyyDataSeries<Date, Double> var1DataSeries = sciChartBuilder.newXyyDataSeries(Date.class, Double.class).build();
final List<VarPoint> varianceData = getVarianceData();
for (int i = 0; i < varianceData.size(); i++) {
final VarPoint dataPoint = varianceData.get(i);
actualDataSeries.append(dataPoint.date, dataPoint.actual);
var3DataSeries.append(dataPoint.date, dataPoint.varMin, dataPoint.varMax);
var2DataSeries.append(dataPoint.date, dataPoint.var1, dataPoint.var4);
var1DataSeries.append(dataPoint.date, dataPoint.var2, dataPoint.var3);
}
final FastBandRenderableSeries projectedVar3 = sciChartBuilder.newBandSeries().withDataSeries(var3DataSeries).withStrokeY1Style(ColorUtil.Transparent).withStrokeStyle(ColorUtil.Transparent).build();
final FastBandRenderableSeries projectedVar2 = sciChartBuilder.newBandSeries().withDataSeries(var2DataSeries).withStrokeY1Style(ColorUtil.Transparent).withStrokeStyle(ColorUtil.Transparent).build();
final FastBandRenderableSeries projectedVar = sciChartBuilder.newBandSeries().withDataSeries(var1DataSeries).withStrokeY1Style(ColorUtil.Transparent).withStrokeStyle(ColorUtil.Transparent).build();
final FastLineRenderableSeries lineSeries = sciChartBuilder.newLineSeries().withDataSeries(actualDataSeries).withStrokeStyle(ColorUtil.Red, 1f).build();
UpdateSuspender.using(surface, new Runnable() {
@Override
public void run() {
Collections.addAll(surface.getXAxes(), xAxis);
Collections.addAll(surface.getYAxes(), yAxis);
Collections.addAll(surface.getRenderableSeries(), projectedVar3, projectedVar2, projectedVar, lineSeries);
Collections.addAll(surface.getChartModifiers(), sciChartBuilder.newModifierGroupWithDefaultModifiers().build());
sciChartBuilder.newAnimator(lineSeries).withWaveTransformation().withInterpolator(new DecelerateInterpolator()).withDuration(3000).withStartDelay(350).start();
sciChartBuilder.newAnimator(projectedVar).withWaveTransformation().withInterpolator(new DecelerateInterpolator()).withDuration(3000).withStartDelay(350).start();
sciChartBuilder.newAnimator(projectedVar2).withWaveTransformation().withInterpolator(new DecelerateInterpolator()).withDuration(3000).withStartDelay(350).start();
sciChartBuilder.newAnimator(projectedVar3).withWaveTransformation().withInterpolator(new DecelerateInterpolator()).withDuration(3000).withStartDelay(350).start();
}
});
}
// Create a table of Variance data. Each row in the table consists of
//
// DateTime, Actual (Y-Value), Projected Min, Variance 1, 2, 3, 4 and Projected Maximum
//
// DateTime Actual Min Var1 Var2 Var3 Var4 Max
// Jan-11 y0 - - - - - -
// Feb-11 y1 - - - - - -
// Mar-11 y2 - - - - - -
// Apr-11 y3 - - - - - -
// May-11 y4 - - - - - -
// Jun-11 y5 min0 var1_0 var2_0 var3_0 var4_0 max_0
// Jul-11 y6 min1 var1_1 var2_1 var3_1 var4_1 max_1
// Aug-11 y7 min2 var1_2 var2_2 var3_2 var4_2 max_2
// Dec-11 y8 min3 var1_3 var2_3 var3_3 var4_3 max_3
// Jan-12 y9 min4 var1_4 var2_4 var3_4 var4_4 max_4
private static List<VarPoint> getVarianceData() {
final int count = 10;
final Date[] dates = IterableUtil.toArray(IterableUtil.range(0, count, new Func1<Integer, Date>() {
@Override
public Date func(Integer arg) {
final Calendar instance = Calendar.getInstance();
instance.clear();
instance.set(2011, 1, 1);
instance.add(Calendar.MONTH, arg);
return instance.getTime();
}
}), Date.class);
final double[] yValues = new RandomWalkGenerator().getRandomWalkSeries(count).yValues.getItemsArray();
final List<VarPoint> result = new ArrayList<>();
for (int i = 0; i < count; i++) {
double varMax = Double.NaN;
double var4 = Double.NaN;
double var3 = Double.NaN;
double var2 = Double.NaN;
double var1 = Double.NaN;
double varMin = Double.NaN;
if (i > 4) {
varMax = yValues[i] + (i - 5) * 0.3;
var4 = yValues[i] + (i - 5) * 0.2;
var3 = yValues[i] + (i - 5) * 0.1;
var2 = yValues[i] - (i - 5) * 0.1;
var1 = yValues[i] - (i - 5) * 0.2;
varMin = yValues[i] - (i - 5) * 0.3;
}
result.add(new VarPoint(dates[i], yValues[i], var4, var3, var2, var1, varMin, varMax));
}
return result;
}
private static class VarPoint {
public final Date date;
public final double actual;
public final double varMax;
public final double var4;
public final double var3;
public final double var2;
public final double var1;
public final double varMin;
public VarPoint(Date date, double actual, double var4, double var3, double var2, double var1, double varMin, double varMax) {
this.date = date;
this.actual = actual;
this.var4 = var4;
this.var3 = var3;
this.var2 = var2;
this.var1 = var1;
this.varMin = varMin;
this.varMax = varMax;
}
}
} |
3e0206e90b983f215d21014f9f18ce95cac97287 | 2,484 | java | Java | argouml/org/argouml/uml/ui/ActionCopy.java | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 46 | 2015-12-04T17:12:58.000Z | 2022-03-11T04:30:49.000Z | argouml/org/argouml/uml/ui/ActionCopy.java | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | null | null | null | argouml/org/argouml/uml/ui/ActionCopy.java | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 23 | 2016-10-24T09:18:14.000Z | 2022-02-25T02:11:35.000Z | 37.636364 | 74 | 0.678341 | 857 | // Copyright (c) 1996-01 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.uml.ui;
import org.tigris.gef.base.*;
import java.awt.event.*;
public class ActionCopy extends UMLChangeAction {
////////////////////////////////////////////////////////////////
// static variables
public static ActionCopy SINGLETON = new ActionCopy();
////////////////////////////////////////////////////////////////
// constructors
public ActionCopy() { super("Copy"); }
////////////////////////////////////////////////////////////////
// main methods
public boolean shouldBeEnabled() {
int size = 0;
try {
size = Globals.curEditor().getSelectionManager().selections().size();
}
//
// this can happen when running in a debugger, not sure why
//
catch(Exception e) {
size = 0;
}
return (size > 0);
}
public void actionPerformed(ActionEvent ae) {
CmdCopy cmd = new CmdCopy();
cmd.doIt();
super.actionPerformed(ae);
}
} /* end class ActionCopy */
|
3e02071514236b71088567899695fe3e9d281db2 | 64 | java | Java | .idea/fileTemplates/includes/File Header.java | WolfogreRecycleBin/JavaProgramming | 0e9def5bb2f29896e273464241b5879a11234698 | [
"MIT"
] | 1 | 2015-12-19T18:02:43.000Z | 2015-12-19T18:02:43.000Z | .idea/fileTemplates/includes/File Header.java | wolfogre/JavaProgramming | 0e9def5bb2f29896e273464241b5879a11234698 | [
"MIT"
] | null | null | null | .idea/fileTemplates/includes/File Header.java | wolfogre/JavaProgramming | 0e9def5bb2f29896e273464241b5879a11234698 | [
"MIT"
] | null | null | null | 16.75 | 58 | 0.626866 | 858 | /**
* Created by Jason Song([email protected]) on ${DATE}.
*/
|
3e0207f0afd66da5ebbee5d4f731dda25f62d9dd | 2,079 | java | Java | app/src/main/java/com/savor/savorphone/utils/CustomCachingGlideModule.java | SavorGit/Hotspot-master-devp | e35f32e80c46ff22932e140e89ec7cf03af0acf1 | [
"Apache-2.0"
] | 3 | 2017-08-23T01:39:02.000Z | 2020-08-06T14:05:25.000Z | app/src/main/java/com/savor/savorphone/utils/CustomCachingGlideModule.java | SavorGit/Hotspot-master-devp | e35f32e80c46ff22932e140e89ec7cf03af0acf1 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/savor/savorphone/utils/CustomCachingGlideModule.java | SavorGit/Hotspot-master-devp | e35f32e80c46ff22932e140e89ec7cf03af0acf1 | [
"Apache-2.0"
] | null | null | null | 40.764706 | 101 | 0.727754 | 859 | package com.savor.savorphone.utils;
import android.content.Context;
import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool;
import com.bumptech.glide.load.engine.cache.DiskCache;
import com.bumptech.glide.load.engine.cache.DiskLruCacheWrapper;
import com.bumptech.glide.load.engine.cache.LruResourceCache;
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.module.GlideModule;
import com.common.api.utils.AppUtils;
import java.io.File;
import java.io.InputStream;
/**
* Created by hezd on 2017/3/1.
*/
public class CustomCachingGlideModule implements GlideModule {
private static final int DISK_CACHE_SIZE = 100 * 1024 * 1024;
// private static final int MEMORY_CACHE_SIZE = 30 * 1024 * 1024;
@Override public void applyOptions(final Context context, GlideBuilder builder) {
builder.setDiskCache(new DiskCache.Factory() {
@Override
public DiskCache build() {
File cacheLocation = new File(AppUtils.getPath(context, AppUtils.StorageFile.cache));
cacheLocation.mkdirs();
return DiskLruCacheWrapper.get(cacheLocation, DISK_CACHE_SIZE);
}
});
// MemorySizeCalculator calculator = new MemorySizeCalculator(context);
// int defaultMemoryCacheSize = calculator.getMemoryCacheSize();
// int defaultBitmapPoolSize = calculator.getBitmapPoolSize();
//
// int customMemoryCacheSize = (int) (0.25 * defaultMemoryCacheSize);
// int customBitmapPoolSize = (int) (0.25* defaultBitmapPoolSize);
//
// builder.setMemoryCache( new LruResourceCache( customMemoryCacheSize ));
// builder.setBitmapPool( new LruBitmapPool( customBitmapPoolSize ));
}
@Override public void registerComponents(Context context, Glide glide) {
// nothing to do here
glide.register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory());
}
}
|
3e0207f270b397aec0b170f59affc6180c925614 | 2,162 | java | Java | integration/mediation-tests/tests-service/src/test/java/org/wso2/carbon/esb/car/deployment/test/XSLTTransformationCarTestCase.java | dulanjalidilmi/micro-integrator | ff2dd64cfd4203b4f019b229e7e9ef9ca1d3cb87 | [
"Apache-2.0"
] | 121 | 2019-04-04T12:54:00.000Z | 2022-03-21T09:06:22.000Z | integration/mediation-tests/tests-service/src/test/java/org/wso2/carbon/esb/car/deployment/test/XSLTTransformationCarTestCase.java | dulanjalidilmi/micro-integrator | ff2dd64cfd4203b4f019b229e7e9ef9ca1d3cb87 | [
"Apache-2.0"
] | 1,363 | 2019-03-19T08:50:27.000Z | 2022-03-31T07:36:37.000Z | integration/mediation-tests/tests-service/src/test/java/org/wso2/carbon/esb/car/deployment/test/XSLTTransformationCarTestCase.java | dulanjalidilmi/micro-integrator | ff2dd64cfd4203b4f019b229e7e9ef9ca1d3cb87 | [
"Apache-2.0"
] | 145 | 2019-03-18T10:02:59.000Z | 2022-02-15T03:37:24.000Z | 37.929825 | 135 | 0.753469 | 860 | /*
*Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*WSO2 Inc. licenses this file to you under the Apache License,
*Version 2.0 (the "License"); you may not use this file except
*in compliance with the License.
*You may obtain a copy of the License at
*
*http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing,
*software distributed under the License is distributed on an
*"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
*KIND, either express or implied. See the License for the
*specific language governing permissions and limitations
*under the License.
*/
package org.wso2.carbon.esb.car.deployment.test;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.utils.ServerConstants;
import org.wso2.esb.integration.common.utils.ESBIntegrationTest;
import org.wso2.esb.integration.common.utils.MicroRegistryManager;
import java.io.File;
public class XSLTTransformationCarTestCase extends ESBIntegrationTest {
private MicroRegistryManager registryManager = null;
String registryResource1 = "transform.xslt";
String registryResource2 = "transform_back.xslt";
@BeforeClass(alwaysRun = true)
protected void uploadCarFileTest() throws Exception {
super.init();
registryManager = new MicroRegistryManager();
}
@Test(groups = { "wso2.esb" }, description = "test endpoint deployment from car file")
public void artifactDeploymentAndServiceInvocation() throws Exception {
String carbonHome = System.getProperty(ServerConstants.CARBON_HOME);
String sourcePath = carbonHome + File.separator + "registry";
Assert.assertTrue(registryManager.checkResourceExist(sourcePath,"/config/", registryResource1),"Registry resources not found");
log.info(registryResource1 + "Registry resources found");
Assert.assertTrue(registryManager.checkResourceExist(sourcePath,"config/", registryResource2), "Registry resources not found");
log.info(registryResource2 + "Registry resources found");
}
}
|
3e0209917705b2605bc278944fc46e25ffa3e346 | 1,449 | java | Java | src/main/java/com/alipay/api/response/AlipayMarketingRecruitPlanlistQueryResponse.java | alipay/alipay-sdk-java-all | e87bc8e7f6750e168a5f9d37221124c085d1e3c1 | [
"Apache-2.0"
] | 333 | 2018-08-28T09:26:55.000Z | 2022-03-31T07:26:42.000Z | src/main/java/com/alipay/api/response/AlipayMarketingRecruitPlanlistQueryResponse.java | alipay/alipay-sdk-java-all | e87bc8e7f6750e168a5f9d37221124c085d1e3c1 | [
"Apache-2.0"
] | 46 | 2018-09-27T03:52:42.000Z | 2021-08-10T07:54:57.000Z | src/main/java/com/alipay/api/response/AlipayMarketingRecruitPlanlistQueryResponse.java | alipay/alipay-sdk-java-all | e87bc8e7f6750e168a5f9d37221124c085d1e3c1 | [
"Apache-2.0"
] | 158 | 2018-12-07T17:03:43.000Z | 2022-03-17T09:32:43.000Z | 19.581081 | 82 | 0.674258 | 861 | package com.alipay.api.response;
import java.util.List;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;
import com.alipay.api.domain.RecruitPlanLight;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: alipay.marketing.recruit.planlist.query response.
*
* @author auto create
* @since 1.0, 2021-09-13 20:55:35
*/
public class AlipayMarketingRecruitPlanlistQueryResponse extends AlipayResponse {
private static final long serialVersionUID = 4274727114525166761L;
/**
* 方案列表
*/
@ApiListField("data")
@ApiField("recruit_plan_light")
private List<RecruitPlanLight> data;
/**
* 第几页,默认1(从1开始计数)
*/
@ApiField("page_num")
private Long pageNum;
/**
* 每页记录条数,默认20
*/
@ApiField("page_size")
private Long pageSize;
/**
* 总数
*/
@ApiField("total")
private Long total;
public void setData(List<RecruitPlanLight> data) {
this.data = data;
}
public List<RecruitPlanLight> getData( ) {
return this.data;
}
public void setPageNum(Long pageNum) {
this.pageNum = pageNum;
}
public Long getPageNum( ) {
return this.pageNum;
}
public void setPageSize(Long pageSize) {
this.pageSize = pageSize;
}
public Long getPageSize( ) {
return this.pageSize;
}
public void setTotal(Long total) {
this.total = total;
}
public Long getTotal( ) {
return this.total;
}
}
|
3e020ae1f0343f3136b7c1dd7185945b1a8c4440 | 3,208 | java | Java | transportable-udfs-api/src/main/java/com/linkedin/transport/api/udf/StdUDF2.java | ljfgem/transport | b87a2aeb5f07b95d04d2db9a3e9fb29f7bbb16e0 | [
"BSD-2-Clause"
] | 225 | 2018-11-28T19:21:17.000Z | 2022-03-31T15:25:55.000Z | transportable-udfs-api/src/main/java/com/linkedin/transport/api/udf/StdUDF2.java | ljfgem/transport | b87a2aeb5f07b95d04d2db9a3e9fb29f7bbb16e0 | [
"BSD-2-Clause"
] | 50 | 2018-12-14T23:09:29.000Z | 2022-01-05T23:08:27.000Z | transportable-udfs-api/src/main/java/com/linkedin/transport/api/udf/StdUDF2.java | ljfgem/transport | b87a2aeb5f07b95d04d2db9a3e9fb29f7bbb16e0 | [
"BSD-2-Clause"
] | 63 | 2018-12-03T18:05:29.000Z | 2022-02-17T15:32:04.000Z | 50.125 | 122 | 0.737531 | 862 | /**
* Copyright 2018 LinkedIn Corporation. All rights reserved.
* Licensed under the BSD-2 Clause license.
* See LICENSE in the project root for license information.
*/
package com.linkedin.transport.api.udf;
import com.linkedin.transport.api.data.StdData;
/**
* A Standard UDF with three input arguments.
*
* @param <I1> the type of the first input argument
* @param <I2> the type of the second input argument
* @param <O> the type of the return value of the {@link StdUDF}
*/
// Suppressing class parameter type parameter name and arg naming style checks since this naming convention is more
// suitable to Standard UDFs, and the code is more readable this way.
@SuppressWarnings({"checkstyle:classtypeparametername", "checkstyle:regexpsinglelinejava"})
public abstract class StdUDF2<I1 extends StdData, I2 extends StdData, O extends StdData> extends StdUDF {
/**
* Returns the output of the {@link StdUDF} given the input arguments.
*
* This method is called once per input record. All UDF logic should be defined in this method.
*
* @param arg1 the first input argument
* @param arg2 the second input argument
* @return the output of the {@link StdUDF} given the input arguments.
*/
public abstract O eval(I1 arg1, I2 arg2);
/**
* Returns an array of file paths to be localized at the worker nodes.
*
* The Standard UDF framework localizes the files passed through this method and provides the localized file paths to
* {@link StdUDF#processRequiredFiles(String[])} for further processing. Users can use the pattern "#LATEST" instead
* of a concrete directory name in the path as a way of selecting the directory with the most recent timestamp, and
* hence obtaining the most recent version of a file.
* Example: 'hdfs:///data/derived/dwh/prop/testMemberId/#LATEST/testMemberId.txt'
*
* The arguments passed to {@link #eval(StdData, StdData)} are passed to this method as well to allow users to construct
* required file paths from arguments passed to the UDF. Since this method is called before any rows are processed,
* only constant UDF arguments should be used to construct the file paths. Values of non-constant arguments are not
* deterministic, and are null for most platforms. (Constant arguments are arguments whose literal values are given
* to the UDF as opposed to non-constant arguments that are expressions which depend on columns. For example, in the
* query {@code SELECT my_udf('my_value', T.Col1) FROM T}, {@literal my_value} is a constant argument to the UDF and
* its value is the same for all invocations of this UDF, while {@code T.Col1} is a non-constant argument since it is
* an expression that depends on a table column, and hence its value changes on a per-row basis).
*
* @param arg1 the first input argument if the argument is constant, null otherwise
* @param arg2 the second input argument if the argument is constant, null otherwise
* @return an array of file paths to be localized at the worker nodes.
*/
public String[] getRequiredFiles(I1 arg1, I2 arg2) {
return new String[]{};
}
protected final int numberOfArguments() {
return 2;
}
}
|
3e020b23c1d95d2f95cf47ac8b6109844b3e3cfd | 1,210 | java | Java | components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/api/service/WordpressServiceTaxonomy.java | LittleEntity/camel | da0d257a983859c25add75047498aa2aa319d7e2 | [
"Apache-2.0"
] | 4,262 | 2015-01-01T15:28:37.000Z | 2022-03-31T04:46:41.000Z | components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/api/service/WordpressServiceTaxonomy.java | LittleEntity/camel | da0d257a983859c25add75047498aa2aa319d7e2 | [
"Apache-2.0"
] | 3,408 | 2015-01-03T02:11:17.000Z | 2022-03-31T20:07:56.000Z | components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/api/service/WordpressServiceTaxonomy.java | LittleEntity/camel | da0d257a983859c25add75047498aa2aa319d7e2 | [
"Apache-2.0"
] | 5,505 | 2015-01-02T14:58:12.000Z | 2022-03-30T19:23:41.000Z | 39.032258 | 75 | 0.772727 | 863 | /*
* 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.camel.component.wordpress.api.service;
import java.util.Map;
import org.apache.camel.component.wordpress.api.model.Context;
import org.apache.camel.component.wordpress.api.model.Taxonomy;
public interface WordpressServiceTaxonomy extends WordpressService {
Map<String, Taxonomy> list(Context context, String postType);
Taxonomy retrieve(Context context, String taxonomy);
}
|
3e020c4229510290beb2e40dec13750551c7b147 | 3,878 | java | Java | app/src/main/java/com/kidscademy/atlas/app/AssetsRepository.java | kids-cademy/atlas | b66f78892b15b1af00445f8d5290b68903b00281 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/kidscademy/atlas/app/AssetsRepository.java | kids-cademy/atlas | b66f78892b15b1af00445f8d5290b68903b00281 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/kidscademy/atlas/app/AssetsRepository.java | kids-cademy/atlas | b66f78892b15b1af00445f8d5290b68903b00281 | [
"Apache-2.0"
] | null | null | null | 31.786885 | 102 | 0.579422 | 864 | package com.kidscademy.atlas.app;
import android.content.Context;
import android.content.res.Resources;
import android.support.annotation.NonNull;
import com.kidscademy.atlas.model.AtlasObject;
import com.kidscademy.atlas.model.AtlasRepository;
import com.kidscademy.atlas.model.SearchIndex;
import com.kidscademy.atlas.util.AssetsBase;
import com.kidscademy.atlas.util.AsyncTask;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.List;
import js.lang.GType;
import js.log.Log;
import js.log.LogFactory;
/**
* Atlas repository stored on application assets.
*
* @author Iulian Rotaru
*/
class AssetsRepository extends AssetsBase implements AtlasRepository {
/**
* Class logger.
*/
private static final Log log = LogFactory.getLog(AssetsRepository.class);
private final Resources resources;
private final String[] names;
private final AtlasObject[] objects;
private final Object searchIndexLock = new Object();
private List<SearchIndex> searchIndex;
AssetsRepository(Context context) throws IOException {
super(context);
log.trace("AssetsRepository(Context context)");
resources=context.getResources();
names = loadObject(getAssetReader("atlas/objects-list.json"), String[].class);
AsyncTask<Void> searchIndexLoader = new AsyncTask<Void>() {
@Override
protected Void execute() throws Throwable {
searchIndex = loadRawObject("search-index", new GType(List.class, SearchIndex.class));
synchronized (searchIndexLock) {
searchIndexLock.notify();
}
return null;
}
};
searchIndexLoader.start();
objects = new AtlasObject[names.length];
AsyncTask<Void> objectsLoader = new AsyncTask<Void>() {
@Override
protected Void execute() throws Throwable {
for (int index = 0; index < objects.length; ++index) {
if (objects[index] == null) {
synchronized (this) {
if (objects[index] == null) {
objects[index] = loadRawObject(names[index], AtlasObject.class);
}
}
}
}
return null;
}
};
objectsLoader.start();
}
@Override
public int getObjectsCount() {
return names.length;
}
@NonNull
@Override
public AtlasObject getObjectByIndex(int index) {
AtlasObject object = objects[index];
if (object == null) {
synchronized (this) {
object = objects[index];
if (object == null) {
object = loadRawObject(names[index], AtlasObject.class);
objects[index] = object;
}
}
}
return object;
}
@Override
public List<SearchIndex> getSearchIndices() {
if (searchIndex == null) {
synchronized (searchIndexLock) {
while (searchIndex == null) {
try {
searchIndexLock.wait();
} catch (InterruptedException e) {
log.debug(e);
}
}
}
}
return searchIndex;
}
private <T> T loadRawObject(String objectName, Type type) {
// raw resources name convention uses underscore '_' instead of dash '-'
objectName = objectName.replace('-', '_');
int resourceId = resources.getIdentifier(objectName, "raw", context.getPackageName());
return loadObject(new InputStreamReader(resources.openRawResource(resourceId)), type);
}
}
|
3e020d8d5176ae6d4af29714186bcdc4c12ae154 | 9,581 | java | Java | norconex-commons-wicket/src/main/java/com/norconex/commons/wicket/bootstrap/filesystem/BootstrapFileSystemDialog.java | Norconex/commons-wicket | cd8f145c03f9f39919de9c751885c1aeb1f2e3ff | [
"Apache-1.1"
] | 5 | 2015-03-24T09:46:20.000Z | 2017-10-25T15:27:54.000Z | norconex-commons-wicket/src/main/java/com/norconex/commons/wicket/bootstrap/filesystem/BootstrapFileSystemDialog.java | Norconex/commons-wicket | cd8f145c03f9f39919de9c751885c1aeb1f2e3ff | [
"Apache-1.1"
] | 2 | 2015-04-19T19:06:55.000Z | 2019-03-20T04:12:07.000Z | norconex-commons-wicket/src/main/java/com/norconex/commons/wicket/bootstrap/filesystem/BootstrapFileSystemDialog.java | Norconex/commons-wicket | cd8f145c03f9f39919de9c751885c1aeb1f2e3ff | [
"Apache-1.1"
] | null | null | null | 40.256303 | 83 | 0.604112 | 865 | /* Copyright 2012-2016 Norconex Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.norconex.commons.wicket.bootstrap.filesystem;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.validation.IFormValidator;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.ResourceModel;
import com.norconex.commons.wicket.behaviors.CssClassAppender;
import com.norconex.commons.wicket.behaviors.Title;
import com.norconex.commons.wicket.bootstrap.modal.BootstrapAjaxModal;
import com.norconex.commons.wicket.bootstrap.modal.BootstrapModalDefaultHeader;
import com.norconex.commons.wicket.markup.html.filesystem.FileSystemNavigator;
import com.norconex.commons.wicket.markup.html.filesystem.FileSystemTreeProvider;
/**
* A Bootstrap file system dialog component.
* @author Pascal Essiembre
*/
@SuppressWarnings("nls")
public abstract class BootstrapFileSystemDialog extends BootstrapAjaxModal {
private static final long serialVersionUID = 2910402645549674983L;
private transient FileFilter selectionValidator;
private final FileSystemNavigator navigator;
private final WebMarkupContainer navWrapper;
private final boolean multiSelectEnabled;
private final String homeDir = System.getProperty("user.home");
private final Component feedback =
new FeedbackPanel("feedback").setOutputMarkupPlaceholderTag(true);
public BootstrapFileSystemDialog(String id, IModel<String> title) {
this(id, title, null);
}
public BootstrapFileSystemDialog(
String id, IModel<String> title, boolean multiSelectEnabled) {
this(id, title, null, multiSelectEnabled);
}
public BootstrapFileSystemDialog(
String id, IModel<String> title, FilenameFilter filenameFilter) {
this(id, title, filenameFilter, false);
}
public BootstrapFileSystemDialog(
String id, IModel<String> title, FilenameFilter filenameFilter,
boolean multiSelectEnabled) {
super(id, title, new Model<String>());
setOutputMarkupId(true);
add(new CssClassAppender("nx-commons-fsdlg"));
this.multiSelectEnabled = multiSelectEnabled;
this.navigator = new BootstrapFileSystemNavigator(
"fileSystemNavigator");
navigator.getTreeProvider().setFileNameFilter(filenameFilter);
if (multiSelectEnabled) {
navigator.setFileSystemContent(new BootstrapMultiSelectableContent(
navigator.getTreeProvider()));
}
this.navWrapper = new WebMarkupContainer("navigatorWrapper") {
private static final long serialVersionUID = 8286836115004105516L;
@Override
protected void onBeforeRender() {
navigator.getTreeProvider().setFileNameFilter(
getFilenameFilter());
addOrReplace(navigator);
super.onBeforeRender();
}
};
navWrapper.setOutputMarkupId(true);
//do stuff...
}
@Override
protected Component createHeaderComponent(String id) {
return new BootstrapModalDefaultHeader(
id, getTitle(), "fa fa-folder-open-o");
}
@Override
protected Component createBodyComponent(String markupId) {
return new Body(markupId);
}
@Override
protected Component createFooterComponent(String id) {
return new Footer(id);
}
public FilenameFilter getFilenameFilter() {
return navigator.getTreeProvider().getFileNameFilter();
}
public void setFilenameFilter(FilenameFilter filenameFilter) {
navigator.getTreeProvider().setFileNameFilter(filenameFilter);
}
public FileFilter getSelectionValidator() {
return selectionValidator;
}
public void setSelectionValidator(FileFilter selectionValidator) {
this.selectionValidator = selectionValidator;
}
protected abstract void onSubmit(
AjaxRequestTarget target, File[] selectedFiles);
private void resetTreeProvider(
AjaxRequestTarget target, String rootDir) {
FileSystemTreeProvider provider = navigator.getTreeProvider();
FilenameFilter filter = provider.getFileNameFilter();
provider = new FileSystemTreeProvider(rootDir);
provider.setFileNameFilter(filter);
navigator.setTreeProvider(provider);
if (multiSelectEnabled) {
navigator.setFileSystemContent(
new BootstrapMultiSelectableContent(provider));
} else {
navigator.setFileSystemContent(
new BootstrapSelectableContent(provider));
}
navWrapper.addOrReplace(navigator);
target.add(navWrapper);
}
private class Body extends Panel {
private static final long serialVersionUID = 914125064944803011L;
public Body(String id) {
super(id);
AjaxButton homeButton = new AjaxButton("home") {
private static final long serialVersionUID =
5743601460587059505L;
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
resetTreeProvider(target, homeDir);
}
};
homeButton.setDefaultFormProcessing(false);
homeButton.add(new Title(new ResourceModel("btn.home.alt")));
AjaxButton rootButton = new AjaxButton("root") {
private static final long serialVersionUID =
5139526986732199148L;
@Override
public void onSubmit(AjaxRequestTarget target, Form<?> form) {
resetTreeProvider(target, "/");
}
};
rootButton.add(new Title(new ResourceModel("btn.root.alt")));
rootButton.setDefaultFormProcessing(false);
add(homeButton);
add(rootButton);
add(navWrapper);
add(feedback);
}
}
private class Footer extends Panel {
private static final long serialVersionUID = 4186844492615693026L;
private final Form<?> form;
public Footer(String id) {
super(id);
this.form = new Form<Void>("form");;
form.add(new IFormValidator() {
private static final long serialVersionUID = 2226366198621473423L;
@Override
public FormComponent<?>[] getDependentFormComponents() {
return new FormComponent[]{};
}
@Override
public void validate(Form<?> form) {
File[] files = navigator.getSelectedFiles();
if (files == null || files.length == 0) {
form.error(getString("err.noselect"));
} else {
for (File file : files) {
if (file == null) {
form.error(getString("err.noselect"));
} else if (selectionValidator != null
&& !selectionValidator.accept(file)) {
form.error(getString("err.invalidselect")
+ file);
}
}
}
}
});
form.add(new AjaxSubmitLink("submit", form) {
private static final long serialVersionUID =
2863084303922306231L;
@Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
target.add(feedback);
}
@Override
protected void onSubmit(
AjaxRequestTarget target, Form<?> form) {
hide(target);
BootstrapFileSystemDialog.this.onSubmit(
target, navigator.getSelectedFiles());
}
});
add(form);
}
}
}
|
3e020df297d5ddb27e0b96a795d4fee64d58023e | 767 | java | Java | SMT2-PBO/UTS/UKM.java | harisfi/TP_ALPRO | ee9ade78d939e504be4ba7810dca04ab6854fdb5 | [
"BSD-3-Clause"
] | 1 | 2021-04-06T02:57:29.000Z | 2021-04-06T02:57:29.000Z | SMT2-PBO/UTS/UKM.java | harisfi/TP_KULIAH | ee9ade78d939e504be4ba7810dca04ab6854fdb5 | [
"BSD-3-Clause"
] | null | null | null | SMT2-PBO/UTS/UKM.java | harisfi/TP_KULIAH | ee9ade78d939e504be4ba7810dca04ab6854fdb5 | [
"BSD-3-Clause"
] | null | null | null | 25.566667 | 106 | 0.617992 | 866 | /*
* 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 uts;
/**
*
* @author hryzx
*/
public class UKM extends OrganisasiKampus{
private String tipe;
public String getTipe() {
return tipe;
}
public void setTipe(String tipe) {
this.tipe = tipe;
}
@Override
public String getDescription() {
return super.getNama() + " adalah salah satu organisasi " + getTipe() + " yang melingkupi " +
super.getLingkup() + "\nyang berdiri pada " + super.getTahunBerdiri() + " dan saat ini " +
"memiliki " + super.getJumlahAngota() + " anggota.";
}
}
|
3e020e6b4511ced181639525ab54146b08773840 | 4,552 | java | Java | project/redis/src/main/java/com/cpq/redis/RedisConfigLettuce.java | CodingSoldier/java-learn | c480f0c26c95b65f49c082e0ffeb10706bd366b1 | [
"Apache-2.0"
] | 23 | 2018-02-11T13:28:42.000Z | 2021-12-24T05:53:13.000Z | project/redis/src/main/java/com/cpq/redis/RedisConfigLettuce.java | CodingSoldier/java-learn | c480f0c26c95b65f49c082e0ffeb10706bd366b1 | [
"Apache-2.0"
] | 5 | 2019-12-23T01:51:45.000Z | 2021-11-30T15:12:08.000Z | project/redis/src/main/java/com/cpq/redis/RedisConfigLettuce.java | CodingSoldier/java-learn | c480f0c26c95b65f49c082e0ffeb10706bd366b1 | [
"Apache-2.0"
] | 17 | 2018-02-11T13:28:03.000Z | 2022-01-24T20:30:02.000Z | 42.542056 | 156 | 0.707381 | 867 | //package com.cpq.redis;
//
//import com.fasterxml.jackson.annotation.JsonAutoDetect;
//import com.fasterxml.jackson.annotation.PropertyAccessor;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.data.redis.connection.RedisClusterConfiguration;
//import org.springframework.data.redis.connection.RedisConnectionFactory;
//import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
//import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
//import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
//import org.springframework.data.redis.serializer.StringRedisSerializer;
//
//import java.time.Duration;
//import java.util.List;
//
///**
// JedisClusterConfig 配置
// */
//@Configuration
//public class RedisConfigLettuce {
//
// /**
// ## cluster集群模式,使用lettuce客户端没法做故障迁移
// ## 连接池最大连接数(使用负值表示没有限制)
// #spring.redis.lettuce.pool.max-active=8
// ## 连接池中的最大空闲连接
// #spring.redis.lettuce.pool.max-idle=8
// ## 连接池中的最小空闲连接
// #spring.redis.lettuce.pool.min-idle=0
// ## 连接池最大阻塞等待时间(使用负值表示没有限制)
// #spring.redis.lettuce.pool.max-wait=1000
// ## 关闭超时时间
// #spring.redis.lettuce.shutdown-timeout=100
// #
// #spring.redis.cluster.nodes=192.168.4.176:7000, 192.168.4.176:7001, 192.168.4.176:7002, 192.168.4.176:7003, 192.168.4.176:7004, 192.168.4.176:7005
// ### 重定向次数
// #spring.redis.cluster.max-redirects=5
//
// */
//
// @Value("${spring.redis.lettuce.pool.max-active}")
// private Integer poolMaxActive;
// @Value("${spring.redis.lettuce.pool.max-idle}")
// private Integer poolMaxIdle;
// @Value("${spring.redis.lettuce.pool.min-idle}")
// private Integer poolMinIdle;
// @Value("${spring.redis.lettuce.pool.max-wait}")
// private Integer poolMaxWait;
// @Value("${spring.redis.cluster.nodes}")
// private List<String> clusterNodes;
// @Value("${spring.redis.cluster.max-redirects}")
// private Integer clusterMaxRedirects;
//
// @Bean
// public RedisConnectionFactory redisConnectionFactory() {
// GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
// poolConfig.setMaxTotal(poolMaxActive);
// poolConfig.setMaxIdle(poolMaxIdle);
// poolConfig.setMinIdle(poolMinIdle);
// poolConfig.setMaxWaitMillis(poolMaxWait);
// LettuceClientConfiguration clientConfig =
// LettucePoolingClientConfiguration.builder().commandTimeout(Duration.ofMillis(100))
// .poolConfig(poolConfig).build();
//
// // 集群redis
// RedisClusterConfiguration redisConfig = new RedisClusterConfiguration();
// redisConfig.setMaxRedirects(clusterMaxRedirects);
// for (String ipPort :clusterNodes){
// String[] ipPortArr = ipPort.split(":");
// redisConfig.clusterNode(ipPortArr[0], Integer.parseInt(ipPortArr[1]));
// }
//
// return new LettuceConnectionFactory(redisConfig, clientConfig);
// }
//
//
// @Bean
// public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
// RedisTemplate template = new RedisTemplate();
// template.setConnectionFactory(redisConnectionFactory);
//
// //key使用StringRedisSerializer
// StringRedisSerializer strSerializer = new StringRedisSerializer();
// template.setKeySerializer(strSerializer);
// template.setHashKeySerializer(strSerializer);
//
// Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
// ObjectMapper om = new ObjectMapper();
// om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
// jackson2JsonRedisSerializer.setObjectMapper(om);
//
// //value使用Jackson2JsonRedisSerializer
// template.setValueSerializer(jackson2JsonRedisSerializer);
// template.setHashValueSerializer(jackson2JsonRedisSerializer);
//
// return template;
// }
//
//
//} |
3e020ec3d9ecb66ffe97da36b5dcf0e61635000f | 3,956 | java | Java | InfoChartLib/src/main/java/com/infomining/infochartlib/handler/RealTimeDataHandler.java | infodevelop/AndroidInfoChart | 29f5e156883b6f6cee3f3164b6545885a28a4d80 | [
"Apache-2.0"
] | 8 | 2021-08-05T06:14:03.000Z | 2022-03-22T07:48:51.000Z | InfoChartLib/src/main/java/com/infomining/infochartlib/handler/RealTimeDataHandler.java | infodevelop/AndroidInfoChart | 29f5e156883b6f6cee3f3164b6545885a28a4d80 | [
"Apache-2.0"
] | 1 | 2022-01-14T04:00:24.000Z | 2022-01-21T07:18:18.000Z | InfoChartLib/src/main/java/com/infomining/infochartlib/handler/RealTimeDataHandler.java | infodevelop/AndroidInfoChart | 29f5e156883b6f6cee3f3164b6545885a28a4d80 | [
"Apache-2.0"
] | 1 | 2021-07-05T09:13:12.000Z | 2021-07-05T09:13:12.000Z | 23.270588 | 118 | 0.57634 | 868 | package com.infomining.infochartlib.handler;
import android.util.Log;
import com.infomining.infochartlib.dataProvider.IVitalChartDataProvider;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* 실시간 데이터를 관리하는 핸들러.
* 균일하지 못하거나 무작위로 들어오는 데이터를 Queue에 담아 일정 시간 간격으로 출력하여 위상의 지연되거나 겹치는 현상을 없애고 의도된 대로 균일하게 출력할 수 있도록 구체화한 객체
*
* @author Dahun Kim
*/
public class RealTimeDataHandler {
/**
* 메인 큐 Queue
*/
Queue<Float> mainQueue = new LinkedList<>();
/**
* 차트 데이터 프로바이더
*/
IVitalChartDataProvider mChart;
/**
* 기본 값. 보통은 스펙에서 Max와 Min의 중간 값이 되며, Queue에 데이터가 없을 경우 출력되는 값이다.
*/
Float defaultValue;
/**
* 마지막으로 dequeue된 값.
*/
Float lastValue;
/**
* 출력될 값을 담는 임시 변수.
*/
Float dequeueValue;
/**
* 스케쥴러
*/
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
/**
* Task
*/
DataDequeueTask task;
/**
* Task Flag
*/
boolean isRunning = false;
public RealTimeDataHandler(IVitalChartDataProvider provider) {
this.mChart = provider;
updateSettings();
}
/**
* 핸들러 설정값 업데이트.
* 차트의 스펙이 변경될 경우 호출됨
*/
public void updateSettings() {
this.defaultValue = ((mChart.getVitalMaxValue() - mChart.getVitalMinValue()) / 2) + mChart.getVitalMinValue();
}
/**
* Queue Enqueue.
* @param value 실시간 데이터
*/
public synchronized void enqueue(float value) {
run();
mainQueue.add(value);
}
/**
* Queue Dequeue.
*/
private void dequeue() {
lastValue = dequeueValue;
dequeueValue = mainQueue.poll();
dequeueValue = (dequeueValue != null) ? dequeueValue : defaultValue;
//dequeueValue = (dequeueValue != null) ? dequeueValue : lastValue;
mChart.dequeueRealTimeData(dequeueValue);
}
Future future;
/**
* 스케쥴러 실행.
* ex) 1초에 500개의 데이터를 그리는 경우, 0.02초 간격으로 데이터를 내보내는 스케쥴러가 생성됨.
*/
public void run() {
if(!isRunning && !executorService.isShutdown()) {
task = new DataDequeueTask(mChart.getOneSecondDataCount());
future = executorService.scheduleWithFixedDelay(task, 0, task.mOneDataTime, TimeUnit.MICROSECONDS);
isRunning = true;
}
}
/**
* 스케쥴러 정지
*/
public void stop() {
if(isRunning && !executorService.isShutdown()) {
if(future != null) {
future.cancel(true);
}
isRunning = false;
}
}
/**
* Queue Reset
*/
public void reset() {
mainQueue.clear();
}
/**
* 핸들러 자원 해제.
* (* 핸들러가 포함된 차트의 자원이 해제되거나 더 이상 핸들러를 사용하지 않을 경우 필히 이 메소드를 호출하여야 함. 앱 성능 저하의 원인이 될 수 있음.)
*/
public void destroy() {
stop();
if(!executorService.isShutdown()) {
executorService.shutdown();
}
}
/**
* Queue의 데이터를 dequeue() 하는 Task.
*
* @author Dahun Kim
*/
class DataDequeueTask implements Runnable {
int mOneDataTime;
long prevTime;
long nowTime;
long totalOverDelayTime;
DataDequeueTask(int oneSecondDataCount) {
// TODO: 최적화를 위한 계산식 수정
this.mOneDataTime = (int) Math.max((1000000 / oneSecondDataCount) * 1, 1);
this.prevTime = System.currentTimeMillis();
}
@Override
public void run() {
dequeue();
nowTime = System.currentTimeMillis();
totalOverDelayTime += nowTime - prevTime - 2;
//Log.e("Log", "delay = " + (nowTime - prevTime) + ", totalOverDelayTime = " + totalOverDelayTime);
prevTime = nowTime;
}
}
}
|
3e020f0af65fcc57ffc61fd869123afd462b9a73 | 2,244 | java | Java | src/ui/android/src/org/grammaticalframework/ui/android/TTS.java | fredefox/gf-core | d5d3a936fa9a2ee899fec24b2a97c8daa245ddfa | [
"BSD-3-Clause"
] | 148 | 2015-01-08T14:35:48.000Z | 2021-11-16T16:11:30.000Z | src/ui/android/src/org/grammaticalframework/ui/android/TTS.java | kitukb/GF | 30ae1b5a5f73513ac5825ca6712186ef8afe9fd4 | [
"BSD-3-Clause"
] | 35 | 2015-07-28T19:22:45.000Z | 2018-07-22T07:18:02.000Z | src/ui/android/src/org/grammaticalframework/ui/android/TTS.java | kitukb/GF | 30ae1b5a5f73513ac5825ca6712186ef8afe9fd4 | [
"BSD-3-Clause"
] | 57 | 2015-01-31T19:55:25.000Z | 2021-11-30T03:43:14.000Z | 29.526316 | 137 | 0.597594 | 869 | package org.grammaticalframework.ui.android;
import android.content.Context;
import android.media.AudioManager;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import java.util.HashMap;
import java.util.Locale;
public class TTS {
private static final String TAG = "TTS";
private TextToSpeech mTts;
private AudioManager mAudioManager;
public TTS(Context context) {
mTts = new TextToSpeech(context, new InitListener());
mAudioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
}
// TODO: handle speak() calls before service connects
public void speak(String language, String text) {
if (mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL) {
/* hack for missing TTS -- don't use for official release!
if (language.equals("bg-BG")) {
language = "ru-RU";
}
if (language.equals("ca-ES")) {
language = "es-ES"; // hardly politically correct...
}
*/
/* Google Chinese speech input has a nonstandard code. In output, yue works for Chi in Google, but SVOX uses the standard zh-CN */
if (language.equals("cmn-Hans-CN")) {
language = "zh-CN";
}
Locale locale = LocaleUtils.parseJavaLocale(language.replace('-', '_'),
Locale.getDefault());
int result = mTts.setLanguage(locale);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e(TAG, "Language is not available");
} else {
HashMap<String,String> params = new HashMap<String,String>();
mTts.speak(text, TextToSpeech.QUEUE_FLUSH, params);
}
}
}
public void destroy() {
if (mTts != null) {
mTts.stop();
mTts.shutdown();
}
}
private class InitListener implements TextToSpeech.OnInitListener {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Log.d(TAG, "Initialized TTS");
} else {
Log.e(TAG, "Failed to initialize TTS");
}
}
}
}
|
3e021150d1d94db43693a9d1e0733000f44ba1bd | 1,134 | java | Java | src/main/java/de/nullpointer/zauberei/events/InteractEvents.java | philipjar/DevAthlon2016 | e27d66ad9c16abb228593628191d023c79c43152 | [
"Apache-2.0"
] | 1 | 2016-07-06T08:45:09.000Z | 2016-07-06T08:45:09.000Z | src/main/java/de/nullpointer/zauberei/events/InteractEvents.java | philipjar/DevAthlon2016 | e27d66ad9c16abb228593628191d023c79c43152 | [
"Apache-2.0"
] | null | null | null | src/main/java/de/nullpointer/zauberei/events/InteractEvents.java | philipjar/DevAthlon2016 | e27d66ad9c16abb228593628191d023c79c43152 | [
"Apache-2.0"
] | null | null | null | 31.5 | 94 | 0.726631 | 870 | package main.java.de.nullpointer.zauberei.events;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import main.java.de.nullpointer.zauberei.Main;
import main.java.de.nullpointer.zauberei.QuidditchGame.Gamestate;
public class InteractEvents implements Listener {
public InteractEvents(Main plugin) {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@SuppressWarnings("deprecation")
@EventHandler
public void onPlayerClick(PlayerInteractEvent e) {
if (Main.game.getGamestate() == Gamestate.STARTED) {
if (e.getAction() == Action.RIGHT_CLICK_AIR | e.getAction() == Action.RIGHT_CLICK_BLOCK) {
Player p = e.getPlayer();
Material itemInHand = p.getItemInHand().getType();
if (itemInHand == Material.BLAZE_ROD) {
p.getItemInHand().setType(Material.STICK);
} else if (itemInHand == Material.STICK) {
p.getItemInHand().setType(Material.BLAZE_ROD);
}
}
}
}
}
|
3e0211eb55a212b4e0405c780bfbac2c41b42715 | 976 | java | Java | xs2a-core/src/main/java/de/adorsys/psd2/xs2a/core/psu/AdditionalPsuIdData.java | dberadze/xs2a | 71334ba664c6f87719ffa8fa48b486b9d726ce7c | [
"Apache-2.0"
] | 120 | 2018-04-19T13:15:59.000Z | 2022-03-27T21:50:38.000Z | xs2a-core/src/main/java/de/adorsys/psd2/xs2a/core/psu/AdditionalPsuIdData.java | dberadze/xs2a | 71334ba664c6f87719ffa8fa48b486b9d726ce7c | [
"Apache-2.0"
] | 72 | 2018-05-04T14:03:18.000Z | 2022-03-10T14:00:22.000Z | xs2a-core/src/main/java/de/adorsys/psd2/xs2a/core/psu/AdditionalPsuIdData.java | dberadze/xs2a | 71334ba664c6f87719ffa8fa48b486b9d726ce7c | [
"Apache-2.0"
] | 85 | 2018-05-07T09:56:46.000Z | 2022-03-09T10:10:29.000Z | 26.378378 | 187 | 0.765369 | 871 | package de.adorsys.psd2.xs2a.core.psu;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Stream;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class AdditionalPsuIdData {
private String psuIpPort;
private String psuUserAgent;
private String psuGeoLocation;
private String psuAccept;
private String psuAcceptCharset;
private String psuAcceptEncoding;
private String psuAcceptLanguage;
private String psuHttpMethod;
private UUID psuDeviceId;
@JsonIgnore
public boolean isEmpty() {
return Stream.of(psuIpPort, psuUserAgent, psuGeoLocation, psuAccept, psuAcceptCharset, psuAcceptEncoding, psuAcceptLanguage, psuHttpMethod, psuDeviceId).allMatch(Objects::isNull);
}
@JsonIgnore
public boolean isNotEmpty() {
return !isEmpty();
}
}
|
3e021208d70adab818d9b8312722b86e9e59ec37 | 3,167 | java | Java | examples/struts/WEB-INF/src/examples/app3/LogonAction.java | fluidinfo/velocity-tools-packaging | 05f4d577c957595ef01c737e14e62d89915ffda1 | [
"Apache-2.0"
] | null | null | null | examples/struts/WEB-INF/src/examples/app3/LogonAction.java | fluidinfo/velocity-tools-packaging | 05f4d577c957595ef01c737e14e62d89915ffda1 | [
"Apache-2.0"
] | null | null | null | examples/struts/WEB-INF/src/examples/app3/LogonAction.java | fluidinfo/velocity-tools-packaging | 05f4d577c957595ef01c737e14e62d89915ffda1 | [
"Apache-2.0"
] | null | null | null | 36.402299 | 86 | 0.662457 | 872 | package examples.app3;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
/**
* Implementation of <strong>Action</strong> that validates a user logon.
*
* @author Craig R. McClanahan
* @author Ted Husted
* @version $Revision: 477914 $ $Date: 2006-11-21 13:52:11 -0800 (Tue, 21 Nov 2006) $
*/
public final class LogonAction extends Action
{
// ---------------------------------------------------- Public Methods
/**
* Login the user.
* The event is logged if the debug level is >= Constants.DEBUG.
*
* @param mapping The ActionMapping used to select this instance
* @param actionForm The ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
String username = ((LogonForm) form).getUsername();
String password = ((LogonForm) form).getPassword();
// Save our logged-in user in the session,
// because we use it again later.
HttpSession session = request.getSession();
session.setAttribute(Constants.USER_KEY, form);
// Log this event
StringBuffer message = new StringBuffer("LogonAction: User '");
message.append(username);
message.append("' logged on in session ");
message.append(session.getId());
servlet.log(message.toString());
// Forward control to the success URI
// specified in struts-config.xml
return (mapping.findForward(Constants.CONTINUE));
}
}
|
3e02147ffc858b8197b7cf2e369037620fca92f6 | 6,814 | java | Java | javacompiler/src/main/java/javax/lang/model/util/SimpleElementVisitor6.java | qtiuto/luadroid | 1e1825a6413ac10bed38a8a5f41011d80017288b | [
"BSD-3-Clause"
] | 96 | 2018-09-22T23:29:49.000Z | 2022-03-27T05:52:42.000Z | javacompiler/src/main/java/javax/lang/model/util/SimpleElementVisitor6.java | qtiuto/luadroid | 1e1825a6413ac10bed38a8a5f41011d80017288b | [
"BSD-3-Clause"
] | 12 | 2018-12-24T12:51:26.000Z | 2022-03-29T15:40:24.000Z | javacompiler/src/main/java/javax/lang/model/util/SimpleElementVisitor6.java | qtiuto/luadroid | 1e1825a6413ac10bed38a8a5f41011d80017288b | [
"BSD-3-Clause"
] | 22 | 2018-11-14T03:15:25.000Z | 2022-02-19T15:37:46.000Z | 36.05291 | 95 | 0.686234 | 873 | /*
* Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.lang.model.util;
import javax.lang.model.element.*;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import static javax.lang.model.SourceVersion.*;
/**
* A simple visitor of program elements with default behavior
* appropriate for the {@link SourceVersion#RELEASE_6 RELEASE_6}
* source version.
*
* Visit methods corresponding to {@code RELEASE_6} language
* constructs call {@link #defaultAction defaultAction}, passing their
* arguments to {@code defaultAction}'s corresponding parameters.
*
* For constructs introduced in {@code RELEASE_7} and later, {@code
* visitUnknown} is called instead.
*
* <p> Methods in this class may be overridden subject to their
* general contract. Note that annotating methods in concrete
* subclasses with {@link java.lang.Override @Override} will help
* ensure that methods are overridden as intended.
*
* <p> <b>WARNING:</b> The {@code ElementVisitor} interface
* implemented by this class may have methods added to it in the
* future to accommodate new, currently unknown, language structures
* added to future versions of the Java™ programming language.
* Therefore, methods whose names begin with {@code "visit"} may be
* added to this class in the future; to avoid incompatibilities,
* classes which extend this class should not declare any instance
* methods with names beginning with {@code "visit"}.
*
* <p>When such a new visit method is added, the default
* implementation in this class will be to call the {@link
* #visitUnknown visitUnknown} method. A new simple element visitor
* class will also be introduced to correspond to the new language
* level; this visitor will have different default behavior for the
* visit method in question. When the new visitor is introduced, all
* or portions of this visitor may be deprecated.
*
* @param <R> the return type of this visitor's methods. Use {@code Void}
* for visitors that do not need to return results.
* @param <P> the type of the additional parameter to this visitor's methods. Use {@code Void}
* for visitors that do not need an additional parameter.
*
* @author Joseph D. Darcy
* @author Scott Seligman
* @author Peter von der Ahé
*
* @see SimpleElementVisitor7
* @see SimpleElementVisitor8
* @see SimpleElementVisitor9
* @since 1.6
*/
@SupportedSourceVersion(RELEASE_6)
public class SimpleElementVisitor6<R, P> extends AbstractElementVisitor6<R, P> {
/**
* Default value to be returned; {@link #defaultAction
* defaultAction} returns this value unless the method is
* overridden.
*/
protected final R DEFAULT_VALUE;
/**
* Constructor for concrete subclasses; uses {@code null} for the
* default value.
* @deprecated Release 6 is obsolete; update to a visitor for a newer
* release level.
*/
@Deprecated()
protected SimpleElementVisitor6(){
DEFAULT_VALUE = null;
}
/**
* Constructor for concrete subclasses; uses the argument for the
* default value.
*
* @param defaultValue the value to assign to {@link #DEFAULT_VALUE}
* @deprecated Release 6 is obsolete; update to a visitor for a newer
* release level.
*/
@Deprecated()
protected SimpleElementVisitor6(R defaultValue){
DEFAULT_VALUE = defaultValue;
}
/**
* The default action for visit methods. The implementation in
* this class just returns {@link #DEFAULT_VALUE}; subclasses will
* commonly override this method.
*
* @param e the element to process
* @param p a visitor-specified parameter
* @return {@code DEFAULT_VALUE} unless overridden
*/
protected R defaultAction(Element e, P p) {
return DEFAULT_VALUE;
}
/**
* {@inheritDoc} This implementation calls {@code defaultAction}.
*
* @param e {@inheritDoc}
* @param p {@inheritDoc}
* @return the result of {@code defaultAction}
*/
public R visitPackage(PackageElement e, P p) {
return defaultAction(e, p);
}
/**
* {@inheritDoc} This implementation calls {@code defaultAction}.
*
* @param e {@inheritDoc}
* @param p {@inheritDoc}
* @return the result of {@code defaultAction}
*/
public R visitType(TypeElement e, P p) {
return defaultAction(e, p);
}
/**
* {@inheritDoc}
*
* This implementation calls {@code defaultAction}, unless the
* element is a {@code RESOURCE_VARIABLE} in which case {@code
* visitUnknown} is called.
*
* @param e {@inheritDoc}
* @param p {@inheritDoc}
* @return the result of {@code defaultAction} or {@code visitUnknown}
*/
public R visitVariable(VariableElement e, P p) {
if (e.getKind() != ElementKind.RESOURCE_VARIABLE)
return defaultAction(e, p);
else
return visitUnknown(e, p);
}
/**
* {@inheritDoc} This implementation calls {@code defaultAction}.
*
* @param e {@inheritDoc}
* @param p {@inheritDoc}
* @return the result of {@code defaultAction}
*/
public R visitExecutable(ExecutableElement e, P p) {
return defaultAction(e, p);
}
/**
* {@inheritDoc} This implementation calls {@code defaultAction}.
*
* @param e {@inheritDoc}
* @param p {@inheritDoc}
* @return the result of {@code defaultAction}
*/
public R visitTypeParameter(TypeParameterElement e, P p) {
return defaultAction(e, p);
}
}
|
3e02148ac272679e51ef5be38dedd5992f9cc9c8 | 651 | java | Java | dm-resilience4j/src/main/java/com/ysz/dm/resilience4j/circuit/dm/Circuit_Dm_IntervalFunction_Dm_003.java | carl10086/dm-learnin | 7763e70fb649ef2a6e3be3537c3b273a7ebd6fbe | [
"Apache-2.0"
] | null | null | null | dm-resilience4j/src/main/java/com/ysz/dm/resilience4j/circuit/dm/Circuit_Dm_IntervalFunction_Dm_003.java | carl10086/dm-learnin | 7763e70fb649ef2a6e3be3537c3b273a7ebd6fbe | [
"Apache-2.0"
] | 8 | 2020-08-18T03:56:02.000Z | 2021-08-03T06:40:20.000Z | dm-resilience4j/src/main/java/com/ysz/dm/resilience4j/circuit/dm/Circuit_Dm_IntervalFunction_Dm_003.java | carl10086/dm-learnin | 7763e70fb649ef2a6e3be3537c3b273a7ebd6fbe | [
"Apache-2.0"
] | 1 | 2020-11-25T04:15:54.000Z | 2020-11-25T04:15:54.000Z | 27.125 | 84 | 0.737327 | 874 | package com.ysz.dm.resilience4j.circuit.dm;
import io.github.resilience4j.core.IntervalFunction;
public class Circuit_Dm_IntervalFunction_Dm_003 {
public void execute() throws Exception {
/*貌似本质上就是利用 function 的 迭代实现的指数功能. Stream.iterate ..*/
final IntervalFunction intervalFunction = IntervalFunction.ofExponentialBackoff(
10L,
2.0
);
System.err.println(intervalFunction.apply(1));
System.err.println(intervalFunction.apply(2));
System.err.println(intervalFunction.apply(3));
}
public static void main(String[] args) throws Exception {
new Circuit_Dm_IntervalFunction_Dm_003().execute();
}
}
|
3e0215662e714d739841d4cada01f63bc47c51eb | 2,863 | java | Java | Mage.Sets/src/mage/cards/s/SpawnOfMayhem.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,444 | 2015-01-02T00:25:38.000Z | 2022-03-31T13:57:18.000Z | Mage.Sets/src/mage/cards/s/SpawnOfMayhem.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 6,180 | 2015-01-02T19:10:09.000Z | 2022-03-31T21:10:44.000Z | Mage.Sets/src/mage/cards/s/SpawnOfMayhem.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,001 | 2015-01-01T01:15:20.000Z | 2022-03-30T20:23:04.000Z | 30.457447 | 164 | 0.683898 | 875 | package mage.cards.s;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.BeginningOfUpkeepTriggeredAbility;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.common.DamagePlayersEffect;
import mage.abilities.effects.common.counter.AddCountersSourceEffect;
import mage.abilities.keyword.FlyingAbility;
import mage.abilities.keyword.SpectacleAbility;
import mage.abilities.keyword.TrampleAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.constants.SubType;
import mage.constants.TargetController;
import mage.counters.CounterType;
import mage.game.Game;
import mage.players.Player;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class SpawnOfMayhem extends CardImpl {
public SpawnOfMayhem(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{B}{B}");
this.subtype.add(SubType.DEMON);
this.power = new MageInt(4);
this.toughness = new MageInt(4);
// Spectacle {1}{B}{B}
this.addAbility(new SpectacleAbility(this, new ManaCostsImpl("{1}{B}{B}")));
// Flying
this.addAbility(FlyingAbility.getInstance());
// Trample
this.addAbility(TrampleAbility.getInstance());
// At the beginning of your upkeep, Spawn of Mayhem deals 1 damage to each player. Then if you have 10 or less life, put a +1/+1 counter on Spawn of Mayhem.
Ability ability = new BeginningOfUpkeepTriggeredAbility(
new DamagePlayersEffect(1, TargetController.ANY),
TargetController.YOU, false
);
ability.addEffect(new SpawnOfMayhemEffect());
this.addAbility(ability);
}
private SpawnOfMayhem(final SpawnOfMayhem card) {
super(card);
}
@Override
public SpawnOfMayhem copy() {
return new SpawnOfMayhem(this);
}
}
class SpawnOfMayhemEffect extends OneShotEffect {
SpawnOfMayhemEffect() {
super(Outcome.Benefit);
staticText = "Then if you have 10 or less life, put a +1/+1 counter on {this}.";
}
private SpawnOfMayhemEffect(final SpawnOfMayhemEffect effect) {
super(effect);
}
@Override
public SpawnOfMayhemEffect copy() {
return new SpawnOfMayhemEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Player player = game.getPlayer(source.getControllerId());
if (player == null) {
return false;
}
if (player.getLife() < 11) {
return new AddCountersSourceEffect(
CounterType.P1P1.createInstance()
).apply(game, source);
}
return false;
}
} |
3e02162402ca112d965caf5aa5ca0ce6cff126f1 | 1,888 | java | Java | Q-municate_app/src/main/java/com/eklanku/otuChat/ui/adapters/payment/SpinnerAdapterPPOB.java | SeasiaDeveloper/otu-chat-indonesia | 3204cbcedaa4bb583c1179a69adf120413995db1 | [
"Apache-2.0"
] | null | null | null | Q-municate_app/src/main/java/com/eklanku/otuChat/ui/adapters/payment/SpinnerAdapterPPOB.java | SeasiaDeveloper/otu-chat-indonesia | 3204cbcedaa4bb583c1179a69adf120413995db1 | [
"Apache-2.0"
] | null | null | null | Q-municate_app/src/main/java/com/eklanku/otuChat/ui/adapters/payment/SpinnerAdapterPPOB.java | SeasiaDeveloper/otu-chat-indonesia | 3204cbcedaa4bb583c1179a69adf120413995db1 | [
"Apache-2.0"
] | null | null | null | 29.968254 | 87 | 0.704449 | 876 | package com.eklanku.otuChat.ui.adapters.payment;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.eklanku.otuChat.R;;
import com.eklanku.otuChat.ui.activities.main.Utils;
import com.eklanku.otuChat.ui.activities.payment.models.DataProduct;
import java.util.ArrayList;
import java.util.List;
public class SpinnerAdapterPPOB extends BaseAdapter {
Context context;
private ArrayList<String> nama, price, ep;
LayoutInflater inflter;
List<DataProduct> products;
public SpinnerAdapterPPOB(Context applicationContext, List<DataProduct> products) {
this.context = applicationContext;
this.products = products;
inflter = (LayoutInflater.from(applicationContext));
}
@Override
public int getCount() {
return products.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = inflter.inflate(R.layout.item_product_list, null);
TextView text_denom = (TextView) convertView.findViewById(R.id.denom);
TextView text_nominal = (TextView) convertView.findViewById(R.id.nominal);
text_nominal.setVisibility(View.GONE);
TextView text_point = (TextView) convertView.findViewById(R.id.point);
final DataProduct item = products.get(position);
double x = Double.valueOf(item.getPrice());
long y = (long) x;
text_denom.setText(item.getName());
//text_nominal.setText("Rp" + Utils.DoubleToCurency(y));
text_point.setText(item.getEp());
return convertView;
}
}
|
3e0216e06ee3e694a2576c2139f4fb5247acb6cc | 238 | java | Java | src/jp/narr/reader/DocumentHandler.java | tohateam/narr-code-pad | 96f85eedffecfb0b384aad2cdb2ac719c74982b8 | [
"Apache-2.0"
] | null | null | null | src/jp/narr/reader/DocumentHandler.java | tohateam/narr-code-pad | 96f85eedffecfb0b384aad2cdb2ac719c74982b8 | [
"Apache-2.0"
] | null | null | null | src/jp/narr/reader/DocumentHandler.java | tohateam/narr-code-pad | 96f85eedffecfb0b384aad2cdb2ac719c74982b8 | [
"Apache-2.0"
] | null | null | null | 26.444444 | 58 | 0.789916 | 877 | package jp.narr.reader;
public interface DocumentHandler {
public String getFileMimeType();
public String getFilePrettifyClass();
public String getFileFormattedString(String fileString);
public String getFileScriptFiles();
}
|
3e021700c002b9d66676c5aab9a7d636b1de1468 | 1,201 | java | Java | src/controller/WindowC.java | CybR37/Zen-initie | e259db633fe8672f36e7a248c0fef56c8f1f2d11 | [
"MIT"
] | null | null | null | src/controller/WindowC.java | CybR37/Zen-initie | e259db633fe8672f36e7a248c0fef56c8f1f2d11 | [
"MIT"
] | null | null | null | src/controller/WindowC.java | CybR37/Zen-initie | e259db633fe8672f36e7a248c0fef56c8f1f2d11 | [
"MIT"
] | null | null | null | 25.553191 | 72 | 0.671107 | 878 | package controller;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
/**
* Window controller, manages events related to the frame status
* @author Théo Koenigs
*/
public class WindowC implements WindowListener {
/** Menu model instance */
private model.ZenInitie modelMenu;
/**
* Class constructor, initializes the attributes with the parameters
* @param modelMenu menu model instance
*/
public WindowC(model.ZenInitie modelMenu){
if(modelMenu != null){
this.modelMenu = modelMenu;
}
}
public void windowOpened(WindowEvent e) {}
/**
* Triggered when the frame is about to close
* @param e event generated
*/
public void windowClosing(WindowEvent e) {
model.Game currentGame = this.modelMenu.getCurrentGame();
if(currentGame != null){
currentGame.saveState("saveFile.zenSave");
}
}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
} |
3e0217a2f5735b5b203bcb25c67d7ac95953f4c3 | 2,811 | java | Java | module/nuls-cross-chain/cross-chain/src/main/java/io/nuls/crosschain/nuls/srorage/imp/SendedHeightServiceImpl.java | DATTPlatform/BASEChain | 39ef9fdc18d4b933d59ad5e5bcac457936add01f | [
"MIT"
] | 226 | 2019-05-13T07:17:22.000Z | 2022-02-13T02:08:23.000Z | module/nuls-cross-chain/cross-chain/src/main/java/io/nuls/crosschain/nuls/srorage/imp/SendedHeightServiceImpl.java | DATTPlatform/BASEChain | 39ef9fdc18d4b933d59ad5e5bcac457936add01f | [
"MIT"
] | 31 | 2019-06-29T10:38:43.000Z | 2021-08-20T02:39:00.000Z | module/nuls-cross-chain/cross-chain/src/main/java/io/nuls/crosschain/nuls/srorage/imp/SendedHeightServiceImpl.java | DATTPlatform/BASEChain | 39ef9fdc18d4b933d59ad5e5bcac457936add01f | [
"MIT"
] | 54 | 2019-05-17T07:29:52.000Z | 2022-03-20T18:10:37.000Z | 32.310345 | 138 | 0.626112 | 879 | package io.nuls.crosschain.nuls.srorage.imp;
import io.nuls.core.core.annotation.Component;
import io.nuls.crosschain.nuls.constant.NulsCrossChainConstant;
import io.nuls.crosschain.nuls.model.po.SendCtxHashPO;
import io.nuls.crosschain.nuls.srorage.SendedHeightService;
import io.nuls.core.rockdb.model.Entry;
import io.nuls.core.rockdb.service.RocksDBService;
import io.nuls.core.log.Log;
import io.nuls.core.model.ByteUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 待广播给其他链节点的区块高度和广播的跨链交易Hash列表数据库相关操作
* Block Height Broadcast to Other Chain Nodes and Related Operation of Broadcast Cross-Chain Transaction Hash List Database
*
* @author tag
* 2019/4/16
* */
@Component
public class SendedHeightServiceImpl implements SendedHeightService {
@Override
public boolean save(long height, SendCtxHashPO po, int chainID) {
if(height == 0 || po == null){
return false;
}
try {
return RocksDBService.put(NulsCrossChainConstant.DB_NAME_SENDED_HEIGHT+chainID, ByteUtils.longToBytes(height),po.serialize());
}catch(Exception e){
Log.error(e);
}
return false;
}
@Override
public SendCtxHashPO get(long height, int chainID) {
if(height == 0){
return null;
}
try {
byte[] valueBytes = RocksDBService.get(NulsCrossChainConstant.DB_NAME_SENDED_HEIGHT+chainID, ByteUtils.longToBytes(height));
if(valueBytes == null){
return null;
}
SendCtxHashPO po = new SendCtxHashPO();
po.parse(valueBytes,0);
return po;
}catch (Exception e){
Log.error(e);
}
return null;
}
@Override
public boolean delete(long height, int chainID) {
try {
if(height == 0){
return false;
}
return RocksDBService.delete(NulsCrossChainConstant.DB_NAME_SENDED_HEIGHT+chainID,ByteUtils.longToBytes(height));
}catch (Exception e){
Log.error(e);
}
return false;
}
@Override
public Map<Long, SendCtxHashPO> getList(int chainID) {
try {
List<Entry<byte[], byte[]>> list = RocksDBService.entryList(NulsCrossChainConstant.DB_NAME_SENDED_HEIGHT+chainID);
Map<Long, SendCtxHashPO> poMap = new HashMap<>(NulsCrossChainConstant.INIT_CAPACITY_16);
for (Entry<byte[], byte[]> entry:list) {
SendCtxHashPO po = new SendCtxHashPO();
po.parse(entry.getValue(),0);
poMap.put(ByteUtils.byteToLong(entry.getKey()), po);
}
return poMap;
}catch (Exception e){
Log.error(e);
}
return null;
}
}
|
3e0218229113f5a9191f7309481e72ec3a866ad6 | 1,072 | java | Java | SpringWEB/SpringSecurity/LiveSessions/CommonAttacks/csrf/secure/file-upload/src/test/java/livelessons/FileUploadTests.java | anupamdev/Spring | 3236bce601779f65809ead080621cff9c743ea7f | [
"Apache-2.0"
] | 25 | 2020-08-24T20:07:37.000Z | 2022-03-04T20:13:20.000Z | SpringWEB/SpringSecurity/LiveSessions/CommonAttacks/csrf/secure/file-upload/src/test/java/livelessons/FileUploadTests.java | anupamdev/Spring | 3236bce601779f65809ead080621cff9c743ea7f | [
"Apache-2.0"
] | 20 | 2021-05-18T19:45:12.000Z | 2022-03-24T06:25:40.000Z | SpringWEB/SpringSecurity/LiveSessions/CommonAttacks/csrf/secure/file-upload/src/test/java/livelessons/FileUploadTests.java | anupamdev/Spring | 3236bce601779f65809ead080621cff9c743ea7f | [
"Apache-2.0"
] | 19 | 2020-09-07T10:01:20.000Z | 2022-03-05T11:34:45.000Z | 35.733333 | 103 | 0.831157 | 880 | package livelessons;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WithMockUser
@SpringBootTest
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
public class FileUploadTests {
@Autowired
private MockMvc mockMvc;
@Test
public void csrfProtectionEnabled() throws Exception {
this.mockMvc.perform(multipart("/upload").file(new MockMultipartFile("name", "the-file".getBytes())))
.andExpect(status().isForbidden());
}
}
|
3e021abdb197350ad739d3734bf18805a9e6f624 | 5,060 | java | Java | flink-ml-core/src/main/java/org/apache/flink/ml/builder/Pipeline.java | JingGe/flink-ml | 857131751e34e3bb1df4c063d9d1a4c57f5fd761 | [
"Apache-2.0"
] | 142 | 2021-03-28T01:49:24.000Z | 2022-03-31T03:39:47.000Z | flink-ml-core/src/main/java/org/apache/flink/ml/builder/Pipeline.java | JingGe/flink-ml | 857131751e34e3bb1df4c063d9d1a4c57f5fd761 | [
"Apache-2.0"
] | 57 | 2021-03-29T07:32:54.000Z | 2022-03-30T09:57:00.000Z | flink-ml-core/src/main/java/org/apache/flink/ml/builder/Pipeline.java | JingGe/flink-ml | 857131751e34e3bb1df4c063d9d1a4c57f5fd761 | [
"Apache-2.0"
] | 35 | 2021-03-29T06:21:11.000Z | 2022-03-23T13:29:34.000Z | 38.045113 | 100 | 0.67668 | 882 | /*
* 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.ml.builder;
import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.ml.api.AlgoOperator;
import org.apache.flink.ml.api.Estimator;
import org.apache.flink.ml.api.Stage;
import org.apache.flink.ml.param.Param;
import org.apache.flink.ml.util.ParamUtils;
import org.apache.flink.ml.util.ReadWriteUtils;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.util.Preconditions;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A Pipeline acts as an Estimator. It consists of an ordered list of stages, each of which could be
* an Estimator, Model, Transformer or AlgoOperator.
*/
@PublicEvolving
public final class Pipeline implements Estimator<Pipeline, PipelineModel> {
private static final long serialVersionUID = 6384850154817512318L;
private final List<Stage<?>> stages;
private final Map<Param<?>, Object> paramMap = new HashMap<>();
public Pipeline(List<Stage<?>> stages) {
this.stages = Preconditions.checkNotNull(stages);
ParamUtils.initializeMapWithDefaultValues(paramMap, this);
}
/**
* Trains the pipeline to fit on the given tables.
*
* <p>This method goes through all stages of this pipeline in order and does the following on
* each stage until the last Estimator (inclusive).
*
* <ul>
* <li>If a stage is an Estimator, invoke {@link Estimator#fit(Table...)} with the input
* tables to generate a Model. And if there is Estimator after this stage, transform the
* input tables using the generated Model to get result tables, then pass the result
* tables to the next stage as inputs.
* <li>If a stage is an AlgoOperator AND there is Estimator after this stage, transform the
* input tables using this stage to get result tables, then pass the result tables to the
* next stage as inputs.
* </ul>
*
* <p>After all the Estimators are trained to fit their input tables, a new PipelineModel will
* be created with the same stages in this pipeline, except that all the Estimators in the
* PipelineModel are replaced with the models generated in the above process.
*
* @param inputs a list of tables
* @return a PipelineModel
*/
@Override
public PipelineModel fit(Table... inputs) {
int lastEstimatorIdx = -1;
for (int i = 0; i < stages.size(); i++) {
if (stages.get(i) instanceof Estimator) {
lastEstimatorIdx = i;
}
}
List<Stage<?>> modelStages = new ArrayList<>(stages.size());
Table[] lastInputs = inputs;
for (int i = 0; i < stages.size(); i++) {
Stage<?> stage = stages.get(i);
AlgoOperator<?> modelStage;
if (stage instanceof AlgoOperator) {
modelStage = (AlgoOperator<?>) stage;
} else {
modelStage = ((Estimator<?, ?>) stage).fit(lastInputs);
}
modelStages.add(modelStage);
// Transforms inputs only if there exists Estimator stage after this stage.
if (i < lastEstimatorIdx) {
lastInputs = modelStage.transform(lastInputs);
}
}
return new PipelineModel(modelStages);
}
@Override
public Map<Param<?>, Object> getParamMap() {
return paramMap;
}
@Override
public void save(String path) throws IOException {
ReadWriteUtils.savePipeline(this, stages, path);
}
public static Pipeline load(StreamExecutionEnvironment env, String path) throws IOException {
return new Pipeline(ReadWriteUtils.loadPipeline(env, path, Pipeline.class.getName()));
}
/**
* Returns a list of all stages in this Pipeline in order. The list is immutable.
*
* @return an immutable list of stages.
*/
@VisibleForTesting
List<Stage<?>> getStages() {
return Collections.unmodifiableList(stages);
}
}
|
3e021c09c5719d986984faacdbad40b02b1ad8a7 | 1,644 | java | Java | src/view/Cadastro.java | MaelSantos/Pesquisa-Amostral | 852303612a04e68584b32d9fc0709e32f91eaaa5 | [
"Apache-2.0"
] | null | null | null | src/view/Cadastro.java | MaelSantos/Pesquisa-Amostral | 852303612a04e68584b32d9fc0709e32f91eaaa5 | [
"Apache-2.0"
] | null | null | null | src/view/Cadastro.java | MaelSantos/Pesquisa-Amostral | 852303612a04e68584b32d9fc0709e32f91eaaa5 | [
"Apache-2.0"
] | null | null | null | 20.810127 | 97 | 0.723236 | 883 | package view;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JTextField;
import model.Dados;
public class Cadastro extends PanelGenerico {
private JLabel lblNome,lblPesquisa ,lblQuantidade;
private JTextField tfdNome;
private JComboBox<String> cbxPesquisa;
private JButton btnAdd;
private int quantidade;
public Cadastro() {
super("Cadastro");
}
public void inicializar() {
quantidade = Dados.getInstance().getPesquisas().get(Dados.pesquisaAtual).getEntidades().size();
lblNome = new JLabel("Nome:");
lblPesquisa = new JLabel("Pesquisa:");
lblQuantidade = new JLabel("Quantidade: "+quantidade);
btnAdd = new JButton("Add");
tfdNome = new JTextField(10);
cbxPesquisa = new JComboBox<String>();
add(lblNome);
add(tfdNome);
add(lblPesquisa);
add(cbxPesquisa);
add(lblQuantidade);
add(btnAdd);
}
public void atualizar() {
quantidade = Dados.getInstance().getPesquisas().get(Dados.pesquisaAtual).getEntidades().size();
lblQuantidade.setText("Quantidade: "+quantidade);
cbxPesquisa.removeAllItems();
for(String s: Dados.getInstance().getPesquisas().get(Dados.pesquisaAtual).getTipos())
cbxPesquisa.addItem(s);
}
//metodos de acesso
public JLabel getLblQuantidade() {
return lblQuantidade;
}
public JTextField getTfdNome() {
return tfdNome;
}
public JButton getBtnAdd() {
return btnAdd;
}
public int getQuantidade() {
return quantidade;
}
public void setQuantidade(int quantidade) {
this.quantidade = quantidade;
}
public JComboBox<String> getCbxPesquisa() {
return cbxPesquisa;
}
}
|
3e021cdb43733e202b51553a5feaf35356ff12a3 | 48,959 | java | Java | src/org/opengts/util/HTMLTools.java | aldridged/gtg-gts | 5764135319c463e82144c92cba9208436c51846d | [
"Apache-2.0"
] | null | null | null | src/org/opengts/util/HTMLTools.java | aldridged/gtg-gts | 5764135319c463e82144c92cba9208436c51846d | [
"Apache-2.0"
] | null | null | null | src/org/opengts/util/HTMLTools.java | aldridged/gtg-gts | 5764135319c463e82144c92cba9208436c51846d | [
"Apache-2.0"
] | null | null | null | 37.952713 | 162 | 0.54756 | 884 | // ----------------------------------------------------------------------------
// Copyright 2006-2010, GeoTelematic Solutions, 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
//
// 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.
//
// ----------------------------------------------------------------------------
// Description:
// HTML Tools
// ----------------------------------------------------------------------------
// Change History:
// 2006/05/15 Martin D. Flynn
// -Initial release
// 2008/02/27 Martin D. Flynn
// -Added methods 'getMimeTypeFromExtension' and 'getMimeTypeFromData'
// 2008/03/28 Martin D. Flynn
// -Added method 'inputStream_GET'.
// 2008/12/16 Martin D. Flynn
// -Added 'timeoutMS' option to 'inputStream_GET' method
// ----------------------------------------------------------------------------
package org.opengts.util;
import java.lang.*;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.net.*;
/**
*** Various HTML and HTTP utilities
**/
public class HTMLTools
{
public static final String PROP_HTMLTools_MIME_ = "HTMLTools.MIME.";
// ------------------------------------------------------------------------
public static final String SP = StringTools.HTML_SP;
public static final String LT = StringTools.HTML_LT;
public static final String GT = StringTools.HTML_GT;
public static final String AMP = StringTools.HTML_AMP;
public static final String QUOTE = StringTools.HTML_QUOTE;
public static final String BR = StringTools.HTML_BR;
public static final String HR = StringTools.HTML_HR;
public static final String HTML = "<html>";
public static final String REQUEST_GET = "GET";
public static final String REQUEST_POST = "POST";
// ------------------------------------------------------------------------
public static final byte MAGIC_GIF_87a[] = new byte[]{(byte)0x47,(byte)0x49,(byte)0x46,(byte)0x38,(byte)0x37,(byte)0x61}; // "GIF87a"
public static final byte MAGIC_GIF_89a[] = new byte[]{(byte)0x47,(byte)0x49,(byte)0x46,(byte)0x38,(byte)0x39,(byte)0x61}; // "GIF89a"
public static final byte MAGIC_JPEG[] = new byte[]{(byte)0xFF,(byte)0xD8,(byte)0xFF,(byte)0xE0};
public static final byte MAGIC_PNG[] = new byte[]{(byte)0x89,(byte)0x50,(byte)0x4E,(byte)0x47,(byte)0x0D,(byte)0x0A,(byte)0x1A,(byte)0x0A};
// ------------------------------------------------------------------------
public static final String CHARSET_UTF8 = "charset=utf-8";
// ------------------------------------------------------------------------
public static final String HEADER_CONTENT_TYPE = "Content-Type";
public static final String HEADER_CONTENT_DISPOSITION = "Content-Disposition";
public static final String HEADER_CONTENT_LENGTH = "Content-Length";
public static final String HEADER_USER_AGENT = "User-Agent";
public static final String HEADER_REFERER = "Referer";
public static final String HEADER_HOST = "Host";
public static final String HEADER_SOAPACTION = "SOAPAction";
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
public static final String PROP_User_Agent = "User-Agent";
public static final String DEFAULT_USER_AGENT = "HTMLTools/1.3";
private static String HTTPUserAgent = null;
/**
*** Sets the HTTP "User-Agent" value to use for HTTP requests.
*** @param userAgent The user-agent
**/
public static void setHttpUserAgent(String userAgent)
{
HTTPUserAgent = userAgent;
}
/**
*** Gets the HTTP "User-Agent" value to use for HTTP requests.
*** @return The user-agent
**/
public static String getHttpUserAgent()
{
if (!StringTools.isBlank(HTTPUserAgent)) {
return HTTPUserAgent;
} else {
return RTConfig.getString(RTKey.HTTP_USER_AGENT, DEFAULT_USER_AGENT);
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
public static final String CONTENT_FORM_MULTIPART = "multipart/form-data";
public static final String CONTENT_FORM_URLENCODED = "application/x-www-form-urlencoded";
/**
*** Returns true if the content type is a multipart form
*** @param ct The content type
*** @return True if "multipart/form-data"
**/
public static boolean isContentMultipartForm(String ct)
{
return (ct != null)? ct.toLowerCase().startsWith(CONTENT_FORM_MULTIPART) : false;
}
/**
*** Gets the "boundary=" value
*** @param ct The content type
*** @return The "boundary=" value
**/
public static String getContentMultipartBoundary(String ct)
{
int p = (ct != null)? ct.indexOf("boundary=") : -1;
if (p < 0) {
return null;
} else {
String b = ct.substring(p + 9);
if (b.startsWith("\"")) {
int q = b.lastIndexOf("\"");
b = (q > 0)? b.substring(1,q) : b.substring(1);
}
return b;
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
public static final String CONTENT_TYPE_PLAIN = "text/plain";
public static final String CONTENT_TYPE_TEXT = CONTENT_TYPE_PLAIN;
public static final String CONTENT_TYPE_XML = "text/xml";
public static final String CONTENT_TYPE_HTML = "text/html";
public static final String CONTENT_TYPE_GIF = "image/gif"; // "GIF87a", "GIF89a"
public static final String CONTENT_TYPE_JPEG = "image/jpeg"; // 0xFF,0xD8,0xFF,0xE0
public static final String CONTENT_TYPE_PNG = "image/png"; // 0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A
public static final String CONTENT_TYPE_OCTET = "application/octet-stream";
public static final String CONTENT_TYPE_BINARY = "application/binary";
public static final String CONTENT_TYPE_DOC = "application/msword";
public static final String CONTENT_TYPE_XLS = "application/vnd.ms-excel";
public static final String CONTENT_TYPE_CSV_OLD = "text/comma-separated-values";
public static final String CONTENT_TYPE_CSV = "text/csv"; // RFC-4180 [http://tools.ietf.org/html/rfc4180]
public static final String CONTENT_TYPE_PDF = "application/pdf";
public static final String CONTENT_TYPE_PS = "application/postscript";
public static final String CONTENT_TYPE_ZIP = "application/x-zip-compressed";
public static final String CONTENT_TYPE_JAD = "text/vnd.sun.j2me.app-descriptor";
public static final String CONTENT_TYPE_JAR = "application/java-archive";
public static final String CONTENT_TYPE_KML_XML = "application/vnd.google-earth.kml+xml kml";
public static final String CONTENT_TYPE_KML = "application/vnd.google-earth.kml+xml";
public static final String CONTENT_TYPE_KMZ = "application/vnd.google-earth.kmz";
public static final String CONTENT_TYPE_JSON = "application/jsonrequest";
/**
*** Returns "zip" MIME type
*** @return "zip" MIME type
**/
public static String MIME_ZIP()
{
return HTMLTools.getMimeType("zip", HTMLTools.CONTENT_TYPE_ZIP);
}
/**
*** Returns "plain" MIME type
*** @return "plain" MIME type
**/
public static String MIME_PLAIN()
{
return HTMLTools.getMimeType("plain", HTMLTools.CONTENT_TYPE_PLAIN);
}
/**
*** Returns "html" MIME type
*** @return "html" MIME type
**/
public static String MIME_HTML()
{
return HTMLTools.getMimeType("html", HTMLTools.CONTENT_TYPE_HTML);
}
/**
*** Returns "xml" MIME type
*** @return "xml" MIME type
**/
public static String MIME_XML()
{
return HTMLTools.getMimeType("xml", HTMLTools.CONTENT_TYPE_XML);
}
/**
*** Returns "xml" MIME type, with added character set
*** @return "xml" MIME type, with added character set
**/
public static String MIME_XML(String charSet)
{
return HTMLTools.getMimeTypeCharset(MIME_XML(), charSet);
}
/**
*** Returns "csv" MIME type
*** @return "csv" MIME type
**/
public static String MIME_CSV()
{
return HTMLTools.getMimeType("csv", HTMLTools.CONTENT_TYPE_CSV);
}
/**
*** Returns "kml" MIME type
*** @return "kml" MIME type
**/
public static String MIME_KML()
{
return HTMLTools.getMimeType("kml", HTMLTools.CONTENT_TYPE_KML);
}
/**
*** Returns "binary" MIME type
*** @return "binary" MIME type
**/
public static String MIME_BINARY()
{
return HTMLTools.getMimeType("binary", HTMLTools.CONTENT_TYPE_BINARY);
}
/**
*** Returns "png" MIME type
*** @return "png" MIME type
**/
public static String MIME_PNG()
{
return HTMLTools.getMimeType("png", HTMLTools.CONTENT_TYPE_PNG);
}
/**
*** Returns "gif" MIME type
*** @return "gif" MIME type
**/
public static String MIME_GIF()
{
return HTMLTools.getMimeType("gif", HTMLTools.CONTENT_TYPE_GIF);
}
/**
*** Returns "jpeg" MIME type
*** @return "jpeg" MIME type
**/
public static String MIME_JPEG()
{
return HTMLTools.getMimeType("jpeg", HTMLTools.CONTENT_TYPE_JPEG);
}
/**
*** Returns the requested mime type
*** @param type The short name of the MIME type to return
*** @return The MIME type
**/
public static String getMimeType(String name, String dftType)
{
String mimeKey = PROP_HTMLTools_MIME_ + name;
String mimeType = RTConfig.getString(mimeKey, null);
if (!StringTools.isBlank(mimeType)) {
return mimeType;
} else
if (!StringTools.isBlank(dftType)) {
return dftType;
} else {
return HTMLTools.getMimeTypeFromExtension(name, dftType);
}
}
/**
*** Appends the default "charset" to mime type
*** @param type The Mime type
*** @return The combined mime-type/charset
**/
public static String getMimeTypeCharset(String type)
{
return HTMLTools.getMimeTypeCharset(type, StringTools.getCharacterEncoding());
}
/**
*** Appends the specified "charset" to mime type
*** @param type The Mime type
*** @param charSet The 'charset'
*** @return The combined mime-type/charset
**/
public static String getMimeTypeCharset(String type, String charSet)
{
if (StringTools.isBlank(type) || StringTools.isBlank(charSet)) {
return type;
} else {
return type + "; charset=" + charSet;
}
}
/**
*** Returns the MIME type for the specified extension
*** @param extn The extension
*** @return The MIME type (default to CONTENT_TYPE_OCTET if the extension is not recognized)
**/
public static String getMimeTypeFromExtension(String extn)
{
return getMimeTypeFromExtension(extn, CONTENT_TYPE_OCTET);
}
/**
*** Returns the MIME type for the specified extension
*** @param extn The extension
*** @param dft The default MIME type to return if the extension is not recognized
*** @return The MIME type
**/
public static String getMimeTypeFromExtension(String extn, String dft)
{
/* default only */
if (extn == null) {
return dft;
}
/* image files */
if (extn.equalsIgnoreCase("gif")) {
return CONTENT_TYPE_GIF;
} else
if (extn.equalsIgnoreCase("jpeg") || extn.equalsIgnoreCase("jpg")) {
return CONTENT_TYPE_JPEG;
} else
if (extn.equalsIgnoreCase("png")) {
return CONTENT_TYPE_PNG;
}
/* plain */
if (extn.equalsIgnoreCase("js")) {
return CONTENT_TYPE_PLAIN;
} else
if (extn.equalsIgnoreCase("plain") || extn.equalsIgnoreCase("txt") || extn.equalsIgnoreCase("text")) {
return CONTENT_TYPE_PLAIN;
} else
if (extn.equalsIgnoreCase("out") || extn.equalsIgnoreCase("conf")) {
return CONTENT_TYPE_PLAIN;
}
/* XML types */
if (extn.equalsIgnoreCase("xml") || extn.equalsIgnoreCase("dtd")) {
return CONTENT_TYPE_XML;
} else
if (extn.equalsIgnoreCase("xls")) {
return CONTENT_TYPE_XLS;
} else
if (extn.equalsIgnoreCase("kml")) {
return CONTENT_TYPE_KML;
} else
if (extn.equalsIgnoreCase("kmz")) {
return CONTENT_TYPE_KMZ;
} else
if (extn.equalsIgnoreCase("json")) {
return CONTENT_TYPE_JSON;
}
/* document types */
if (extn.equalsIgnoreCase("html") || extn.equalsIgnoreCase("htm")) {
return CONTENT_TYPE_HTML;
} else
if (extn.equalsIgnoreCase("pdf")) {
return CONTENT_TYPE_PDF;
} else
if (extn.equalsIgnoreCase("ps")) {
return CONTENT_TYPE_PS;
} else
if (extn.equalsIgnoreCase("doc")) {
return CONTENT_TYPE_DOC;
} else
if (extn.equalsIgnoreCase("csv")) {
return CONTENT_TYPE_CSV;
}
/* archive types */
if (extn.equalsIgnoreCase("zip")) {
return CONTENT_TYPE_ZIP;
} else
if (extn.equalsIgnoreCase("jad")) {
return CONTENT_TYPE_JAD;
} else
if (extn.equalsIgnoreCase("jar")) {
return CONTENT_TYPE_JAR;
} else
if (extn.equalsIgnoreCase("binary") || extn.equalsIgnoreCase("bin")) {
return CONTENT_TYPE_BINARY;
} else
if (extn.equalsIgnoreCase("octet")) {
return CONTENT_TYPE_OCTET;
}
/* not found, return default */
return dft;
}
/**
*** Return the MIME type based on the data Magic Number
*** @param data The data buffer to test for specific Magin-Numbers
*** @return The MIME type (default to CONTENT_TYPE_OCTET if data is not recognized)
**/
public static String getMimeTypeFromData(byte data[])
{
return getMimeTypeFromData(data, CONTENT_TYPE_OCTET);
}
/**
*** Return the MIME type based on the data Magic Number
*** @param data The data buffer to test for specific Magin-Numbers
*** @param dft The default MIME type to return if the data is not recognized
*** @return The MIME type
**/
public static String getMimeTypeFromData(byte data[], String dft)
{
/* invalid data? */
if (data == null) {
return dft;
}
/* GIF */
if (StringTools.compareEquals(data,MAGIC_GIF_87a,-1)) {
return CONTENT_TYPE_GIF;
} else
if (StringTools.compareEquals(data,MAGIC_GIF_89a,-1)) {
return CONTENT_TYPE_GIF;
}
/* JPEG */
if (StringTools.compareEquals(data,MAGIC_JPEG,-1)) { // ([6..10]=="JFIF")
return CONTENT_TYPE_JPEG;
}
/* PNG */
if (StringTools.compareEquals(data,MAGIC_PNG,-1)) {
return CONTENT_TYPE_PNG;
}
/* default */
return dft;
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
public static final TagBlock TAG_HTML = new TagBlock("<html>", "</html>");
public static final TagBlock TAG_H1 = new TagBlock("<h1>", "</h1>");
public static final TagBlock TAG_H2 = new TagBlock("<h2>", "</h2>");
public static final TagBlock TAG_H3 = new TagBlock("<h3>", "</h3>");
public static final TagBlock TAG_CENTER = new TagBlock("<center>", "</center>");
public static final TagBlock TAG_BLOCKQUOTE = new TagBlock("<blockquote>", "</blockquote>");
public static final TagBlock TAG_RIGHT = new TagBlock("<div align=right>", "</div>");
public static final TagBlock TAG_BOLD = new TagBlock("<B>", "</B>");
public static final TagBlock TAG_ITALIC = new TagBlock("<I>", "</I>");
public static final TagBlock TAG_MONOSPACE = new TagBlock("<tt>", "</tt>");
public static final TagBlock TAG_MONORIGHT = new TagBlock(TAG_MONOSPACE, TAG_RIGHT);
public static final TagBlock TAG_MONOCENTER = new TagBlock(TAG_MONOSPACE, TAG_CENTER);
public static final TagBlock TAG_RED = TAG_COLOR("#FF0000");
public static final TagBlock TAG_REDBOLD = new TagBlock(TAG_BOLD, TAG_RED);
public static final TagBlock TAG_GREEN = TAG_COLOR("#007700");
public static final TagBlock TAG_GREENBOLD = new TagBlock(TAG_BOLD, TAG_GREEN);
public static final TagBlock TAG_BLUE = TAG_COLOR("#0000FF");
public static final TagBlock TAG_BLUEBOLD = new TagBlock(TAG_BOLD, TAG_BLUE);
public static final TagBlock TAG_SMALLFONT = new TagBlock("<font size=-1>", "</font>");
public static final TagBlock TAG_SMALLCENTER = new TagBlock(TAG_SMALLFONT, TAG_CENTER);
public static final TagBlock TAG_NUMBERLIST = new TagBlock("<ol>", "</ol>");
public static final TagBlock TAG_BULLETLIST = new TagBlock("<ul>", "</ul>");
public static final TagBlock TAG_LISTITEM = new TagBlock("<li>", "</li>");
/**
*** Returns a TagBlock 'font' wrapper with the specified color
*** @param c The font color
*** @return The TagBlock 'font' wrapper
**/
public static TagBlock TAG_COLOR(Color c)
{
return TAG_COLOR(ColorTools.toHexString(c));
}
/**
*** Returns a TagBlock 'font' wrapper with the specified color String
*** @param cs The font color String
*** @return The TagBlock 'font' wrapper
**/
public static TagBlock TAG_COLOR(String cs)
{
if ((cs != null) && !cs.startsWith("#")) { cs = "#" + cs; }
return new TagBlock("<font color=\"" + cs + "\">", "</font>");
}
/**
*** Returns a TagBlock 'span' wrapper with the specified title/tooltip
*** @param tip The title/tooltip
*** @return The TagBlock 'span' wrapper
**/
public static TagBlock TAG_TOOLTIP(String tip)
{
String t = StringTools.quoteString(tip);
return new TagBlock("<span title=" + t + ">", "</span>");
}
/**
*** Returns a TagBlock 'a href=' wrapper with the specified url
*** @param url The URL
*** @return The TagBlock 'a' wrapper
**/
public static TagBlock TAG_LINK(String url)
{
return new TagBlock("<a href=\"" + url + "\">", "</a>");
}
/**
*** Returns a TagBlock 'a href=' wrapper with the specified url
*** @param url The URL
*** @param newWindow True to specify "target=_blank"
*** @return The TagBlock 'a' wrapper
**/
public static TagBlock TAG_LINK(String url, boolean newWindow)
{
StringBuffer a = new StringBuffer();
a.append("<a href=\"").append(url).append("\"");
if (newWindow) { a.append(" target='_blank'"); }
a.append(">");
return new TagBlock(a.toString(), "</a>");
}
// ------------------------------------------------------------------------
/* encode HTML parameter */
private static final String ENC_CHARS = " %=<>&'\"";
/**
*** Encode specific characters in the specified text object
*** @param text The text Object
*** @return The encoded String
**/
public static String encodeParameter(Object text)
{
String s = text.toString();
/* encode special characters */
char ch[] = new char[s.length()];
s.getChars(0, s.length(), ch, 0);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < ch.length; i++) {
if (ENC_CHARS.indexOf(ch[i]) >= 0) {
int x = (int)ch[i] + 0x100;
sb.append("%" + Integer.toHexString(x).substring(1).toUpperCase());
} else {
sb.append(ch[i]);
}
}
return sb.toString();
}
/**
*** Decode URL encoded hex values from the specified String
*** @param text The encoded text
*** @return The decoded String
**/
public static String decodeParameter(String text)
{
StringBuffer sb = new StringBuffer();
if (!StringTools.isBlank(text)) {
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if ((ch == '%') && ((i + 2) < text.length())) {
int h1 = StringTools.hexIndex(text.charAt(i+1));
int h2 = StringTools.hexIndex(text.charAt(i+2));
if ((h1 >= 0) && (h2 >= 0)) {
sb.append((char)((h1 * 16) + h2));
i += 2;
continue;
}
}
sb.append(ch);
}
}
return sb.toString();
}
// ------------------------------------------------------------------------
/**
*** Encode the specified color into a String value
*** @param color The Color object
*** @return The String representation of the color
**/
public static String color(Color color)
{
int ci = 0x000000;
ci |= (color.getRed() << 16) & 0xFF0000;
ci |= (color.getGreen() << 8) & 0x00FF00;
ci |= (color.getBlue() << 0) & 0x0000FF;
String cs = Integer.toHexString(ci | 0x1000000).substring(1).toUpperCase();
return "#" + cs;
}
// ------------------------------------------------------------------------
/**
*** Creates/Returns a String representing a link to a URL with the specified text description
*** and attributes.
*** @param ref The referenced URL link ("target='_blank'" will be applied)
*** @param text The link text (html filtering will be applied)
*** @return The assembled link ('a' tag)
**/
public static String createLink(String ref, Object text)
{
return HTMLTools.createLink(ref, true, text, true);
}
/**
*** Creates/Returns a String representing a link to a URL with the specified text description
*** and attributes.
*** @param ref The referenced URL link
*** @param newWindow If true, "target='_blank'" will be specified
*** @param text The link text (html filtering will be applied)
*** @return The assembled link ('a' tag)
**/
public static String createLink(String ref, boolean newWindow, Object text)
{
return createLink(ref, newWindow, text, true);
}
/**
*** Creates/Returns a String representing a link to a URL with the specified text description
*** and attributes.
*** @param ref The referenced URL link
*** @param newWindow If true, "target='_blank'" will be specified
*** @param text The link text
*** @param filterText True to apply HTML filtering to the specified text
*** @return The assembled link ('a' tag)
**/
public static String createLink(String ref, boolean newWindow, Object text, boolean filterText)
{
String t = (text != null)? text.toString() : "";
StringBuffer sb = new StringBuffer();
sb.append("<a href='").append(ref).append("'");
if (newWindow) { sb.append(" target='_blank'"); }
sb.append(">");
sb.append(filterText? StringTools.htmlFilterText(t) : t);
sb.append("</a>");
return sb.toString();
}
// ------------------------------------------------------------------------
/**
*** Returns a 'span' wrapper with the specified 'font' specification
*** @param family The font family
*** @param style The font style ('normal', 'italic', 'oblique')
*** @param variant The font variant ('normal', 'small-caps')
*** @param weight The font weight ('normal', 'bold', 'bolder', 'lighter', etc)
*** @param ptsize The font point size
*** @return The 'font' tag specification
***/
public static String font(String family, String style, String variant, String weight, int ptsize)
{
// Reference: http://www.w3.org/TR/CSS21/fonts.html
StringBuffer sb = new StringBuffer();
sb.append("<span style='");
if ((family != null) && !family.equals("")) {
// "Arial,Helvetica,san-serif"
sb.append("font-family:").append(family).append(";");
}
if ((style != null) && !style.equals("")) {
// "normal", "italic", "oblique"
sb.append("font-style:").append(style).append(";");
}
if ((variant != null) && !variant.equals("")) {
// "normal", "small-caps"
sb.append("font-variant:").append(variant).append(";");
}
if ((weight != null) && !weight.equals("")) {
// "normal"(400), "bold"(700), "bolder", "lighter", "100".."900"
sb.append("font-weight:").append(weight).append(";");
}
if (ptsize > 0) {
sb.append("font-size:").append(ptsize).append("pt;");
}
sb.append("'>");
return sb.toString();
}
/**
*** Closes a 'span' tag used to specify 'font' style.
**/
public static String _font()
{
return "</span>";
}
// ------------------------------------------------------------------------
/**
*** Returns a String representing a start-of-JavaScript tag
***/
public static String startJavaScript()
{
return "<script language='JavaScript'><!--";
}
/**
*** Returns a String representing an end-of-JavaScript tag
***/
public static String endJavaScript()
{
return "// --></script>";
}
// ------------------------------------------------------------------------
/**
*** Returns a 'meta' tag with a 'refresh' option
*** @param delay Delay before next update
*** @param url The URL to jump to after the delay
*** @return The String representing the assembled 'meta' tag
***/
public static String autoRefresh(int delay, String url)
{
StringBuffer sb = new StringBuffer();
sb.append("<meta http-equiv='Refresh' ");
sb.append("content='").append(delay).append(";URL=").append(url).append("'>");
return sb.toString();
}
// ------------------------------------------------------------------------
/**
*** Sends a POST to the specified URL, then reads and returns the response
*** @param pageURLStr The URL to which the POST is sent
*** @param contentType The MIME type of the POST data sent to the server
*** @param postData The data sent to the server
*** @param timeoutMS Connection timeout in milliseconds (<=0 for indefinite timeout)
*** @return The response from the server
*** @throws NoRouteToHostException if the remote host could not be reached
*** @throws IOException if an I/O error occurs
***/
public static byte[] readPage_POST(String pageURLStr, String contentType, byte postData[], int timeoutMS)
throws IOException
{
URL pageURL = new URL(pageURLStr);
return readPage_POST(pageURL, contentType, postData, timeoutMS);
}
/**
*** Sends a POST to the specified URL, then reads and returns the response
*** @param pageURL The URL to which the POST is sent
*** @param contentType The MIME type of the POST data sent to the server
*** @param postData The data sent to the server
*** @param timeoutMS Connection timeout in milliseconds (<=0 for indefinite timeout)
*** @return The response from the server
*** @throws NoRouteToHostException if the remote host could not be reached
*** @throws IOException if an I/O error occurs
***/
public static byte[] readPage_POST(URL pageURL, String contentType, byte postData[], int timeoutMS)
throws IOException
{
if (!StringTools.isBlank(contentType)) {
Properties hp = new Properties();
hp.setProperty(HEADER_CONTENT_TYPE, contentType);
return readPage_POST(pageURL, hp, postData, timeoutMS);
} else {
return readPage_POST(pageURL, (Properties)null, postData, timeoutMS);
}
}
/**
*** Sends a POST to the specified URL, then reads and returns the response
*** @param pageURL The URL to which the POST is sent
*** @param headerProps The POST header properties
*** @param postData The data sent to the server
*** @param timeoutMS Connection timeout in milliseconds (<=0 for indefinite timeout)
*** @return The response from the server
*** @throws NoRouteToHostException if the remote host could not be reached
*** @throws IOException if an I/O error occurs
***/
public static byte[] readPage_POST(String pageURLStr, Properties headerProps, byte postData[], int timeoutMS)
throws IOException
{
URL pageURL = new URL(pageURLStr);
return readPage_POST(pageURL, headerProps, postData, timeoutMS);
}
/**
*** Sends a POST to the specified URL, then reads and returns the response
*** @param pageURL The URL to which the POST is sent
*** @param headerProps The POST header properties
*** @param postData The data sent to the server
*** @param timeoutMS Connection timeout in milliseconds (<=0 for indefinite timeout)
*** @return The response from the server
*** @throws NoRouteToHostException if the remote host could not be reached
*** @throws IOException if an I/O error occurs
***/
public static byte[] readPage_POST(URL pageURL, Properties headerProps, byte postData[], int timeoutMS)
throws IOException
{
/* valid url? */
if (pageURL == null) {
return null;
}
/* send POST */
byte data[] = null;
HttpURLConnection httpConnect = null;
OutputStream postOutput = null;
InputStream postInput = null;
try {
//Print.logInfo("POST v1.2");
/* init connection */
httpConnect = (HttpURLConnection)(pageURL.openConnection());
httpConnect.setRequestMethod(REQUEST_POST);
httpConnect.setAllowUserInteraction(false);
httpConnect.setDoInput(true);
httpConnect.setDoOutput(true);
httpConnect.setUseCaches(false);
httpConnect.setRequestProperty(PROP_User_Agent, HTMLTools.getHttpUserAgent());
if (timeoutMS >= 0) {
httpConnect.setConnectTimeout(timeoutMS);
}
/* header properties */
if (headerProps != null) {
for (Enumeration<?> pe = headerProps.propertyNames(); pe.hasMoreElements();) {
String hk = (String)pe.nextElement();
String hv = headerProps.getProperty(hk);
httpConnect.setRequestProperty(hk, hv);
}
}
/* write data */
if (postData != null) {
httpConnect.setRequestProperty(HEADER_CONTENT_LENGTH, String.valueOf(postData.length));
postOutput = httpConnect.getOutputStream();
postOutput.write(postData);
postOutput.flush();
}
/* connect */
httpConnect.connect(); // possible NoRouteToHostException, etc.
/* read data */
//int contentLen = httpConnect.getContentLength();
//Print.logInfo("Read ContentLength: " + contentLen);
//if ((contentLen > 0) || (contentLen == -1)) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
postInput = new BufferedInputStream(httpConnect.getInputStream());
FileTools.copyStreams(postInput, output);
data = output.toByteArray();
//} else {
// data = new byte[0];
//}
} finally {
/* close */
if (postOutput != null) { postOutput.close(); }
if (postInput != null) { postInput.close(); }
if (httpConnect != null) { httpConnect.disconnect(); }
}
/* return data */
return data;
}
// ------------------------------------------------------------------------
/**
*** Sends a GET to the specified URL, then reads and returns the response
*** @param pageURLStr The URL to which the GET is sent
*** @param timeoutMS Connection timeout in milliseconds (<=0 for indefinite timeout)
*** @return The response from the server
*** @throws NoRouteToHostException if the remote host could not be reached
*** @throws IOException if an I/O error occurs
***/
public static byte[] readPage_GET(String pageURLStr, int timeoutMS)
throws Throwable
{
URL pageURL = new URL(pageURLStr);
return readPage_GET(pageURL, timeoutMS);
}
/**
*** Sends a GET to the specified URL, then reads and returns the response
*** @param pageURL The URL to which the GET is sent
*** @param timeoutMS Connection timeout in milliseconds (<=0 for indefinite timeout)
*** @return The response from the server
*** @throws NoRouteToHostException if the remote host could not be reached
*** @throws IOException if an I/O error occurs
***/
public static byte[] readPage_GET(URL pageURL, int timeoutMS)
throws Throwable
{
byte data[] = null;
HttpURLConnection httpConnect = null;
try {
/* init connection */
httpConnect = (HttpURLConnection)(pageURL.openConnection());
httpConnect.setAllowUserInteraction(false);
httpConnect.setRequestMethod(REQUEST_GET);
httpConnect.setRequestProperty(PROP_User_Agent, HTMLTools.getHttpUserAgent());
if (timeoutMS >= 0) {
httpConnect.setConnectTimeout(timeoutMS);
}
/* connect */
//Print.logDebug("Connecting ...");
httpConnect.connect(); // possible NoRouteToHostException, etc.
//Print.logDebug("Connected.");
/* read data */
int contentLen = httpConnect.getContentLength();
if ((contentLen > 0) || (contentLen == -1)) {
data = FileTools.readStream(new BufferedInputStream(httpConnect.getInputStream()));
} else {
data = new byte[0];
}
} finally {
if (httpConnect != null) { httpConnect.disconnect(); }
}
return data;
}
// ------------------------------------------------------------------------
/**
*** Sends a GET to the specified URL, then reads and returns the response. This method
*** will not throw any Exceptions. Instead, the returned response is null if any errors
*** are encountered.
*** @param pageURLStr The URL to which the GET is sent
*** @param timeoutMS Connection timeout in milliseconds (<=0 for indefinite timeout)
*** @return The response from the server
***/
public static byte[] readPage_GET_LogError(String pageURLStr, int timeoutMS)
{
try {
URL pageURL = new URL(pageURLStr);
return readPage_GET_LogError(pageURL, timeoutMS);
} catch (MalformedURLException mue) {
Print.logError(mue.toString()); // DNS?
return null;
}
}
/**
*** Sends a GET to the specified URL, then reads and returns the response. This method
*** will not throw any Exceptions. Instead, the returned response is null if any errors
*** are encountered.
*** @param pageURL The URL to which the GET is sent
*** @param timeoutMS Connection timeout in milliseconds (<=0 for indefinite timeout)
*** @return The response from the server
***/
public static byte[] readPage_GET_LogError(URL pageURL, int timeoutMS)
{
try {
return HTMLTools.readPage_GET(pageURL, timeoutMS);
} catch (UnknownHostException uhe) {
Print.logError(uhe.toString()); // DNS?
} catch (NoRouteToHostException nrthe) {
Print.logError(nrthe.toString()); // DNS?
} catch (ConnectException ce) {
Print.logError(ce.toString()); // timed out?
} catch (SocketException se) {
Print.logError(se.toString()); // DNS?
} catch (FileNotFoundException fnfe) {
Print.logError(fnfe.toString()); // wrong URL?
} catch (Throwable t) {
Print.logStackTrace("Read page", t);
}
return null;
}
// ------------------------------------------------------------------------
/**
*** Returns an InputStream for reading the contents of the specified URL
*** @param pageURLStr The URL
*** @param timeoutMS Connection timeout in milliseconds (<=0 for indefinite timeout)
*** @return The InputStream
*** @throws NoRouteToHostException if the remote host could not be reached
*** @throws IOException if an I/O error occurs
**/
public static InputStream inputStream_GET(String pageURLStr, int timeoutMS)
throws IOException
{
URL pageURL = new URL(pageURLStr);
return inputStream_GET(pageURL, timeoutMS);
}
/**
*** Returns an InputStream for reading the contents of the specified URL
*** @param pageURL The URL
*** @param timeoutMS Connection timeout in milliseconds (<=0 for indefinite timeout)
*** @return The InputStream
*** @throws NoRouteToHostException if the remote host could not be reached
*** @throws IOException if an I/O error occurs
**/
public static InputStream inputStream_GET(URL pageURL, int timeoutMS)
throws IOException
{
/* init connection */
final HttpURLConnection httpConnect = (HttpURLConnection)(pageURL.openConnection());
httpConnect.setAllowUserInteraction(false);
httpConnect.setRequestMethod(REQUEST_GET);
httpConnect.setRequestProperty(PROP_User_Agent, HTMLTools.getHttpUserAgent());
if (timeoutMS >= 0) {
httpConnect.setConnectTimeout(timeoutMS);
}
/* connect */
httpConnect.connect(); // possible NoRouteToHostException, etc.
/* read data */
int contentLen = httpConnect.getContentLength();
if ((contentLen > 0) || (contentLen == -1)) {
return new BufferedInputStream(httpConnect.getInputStream()) {
public void close() throws IOException {
//Print.logInfo("Closing HTTP stream ...");
httpConnect.disconnect();
}
};
} else {
httpConnect.disconnect();
return null;
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Custom TagBlock class
**/
public static class TagBlock
{
private String startTag = null;
private String endTag = null;
private TagBlock tagGroup[] = null;
public TagBlock(String startTag, String endTag) {
this.startTag = startTag;
this.endTag = endTag;
}
public TagBlock(TagBlock group[]) {
this((String)null, (String)null);
this.tagGroup = group;
}
public TagBlock(TagBlock tb1, TagBlock tb2) {
this(new TagBlock[] { tb1, tb2 });
}
public TagBlock(TagBlock tb1, TagBlock tb2, TagBlock tb3) {
this(new TagBlock[] { tb1, tb2, tb3 });
}
public String getStartTag() {
StringBuffer sb = new StringBuffer();
if (this.tagGroup != null) {
for (int i = 0; i < this.tagGroup.length; i++) {
if (this.tagGroup[i] != null) {
sb.append(this.tagGroup[i].getStartTag());
}
}
}
if (this.startTag != null) {
sb.append(this.startTag);
}
return sb.toString();
}
public String getEndTag() {
StringBuffer sb = new StringBuffer();
if (this.endTag != null) {
sb.append(this.endTag);
}
if (this.tagGroup != null) {
for (int i = (this.tagGroup.length - 1); i >= 0; i--) {
if (this.tagGroup[i] != null) {
sb.append(this.tagGroup[i].getEndTag());
}
}
}
return sb.toString();
}
public StringBuffer wrap(Object text, boolean htmlFilter, StringBuffer sb) {
if (sb == null) { sb = new StringBuffer(); }
if (text != null) {
String v = text.toString();
sb.append(this.getStartTag());
sb.append(htmlFilter? StringTools.htmlFilterText(v) : v);
sb.append(this.getEndTag());
}
return sb;
}
public String wrap(Object text, boolean htmlFilter) {
return this.wrap(text, htmlFilter, new StringBuffer()).toString();
}
public String wrap(Object text) {
return this.wrap(text, false);
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Custom tag wrapper class
**/
public static class TagWrap
{
private Object text = null;
private TagBlock tags[] = null;
public TagWrap(Object text, TagBlock tags[]) {
this.text = text;
this.tags = tags;
}
public TagWrap(Object text, TagBlock tag) {
this(text, new TagBlock[] { tag });
}
public String toString(boolean html) {
if (this.text != null) {
if (html) {
String v = (this.text instanceof TagWrap)? ((TagWrap)this.text).toString(html) : StringTools.htmlFilterText(this.text);
if ((this.tags != null) && (this.tags.length > 0)) {
for (int i = 0; i < this.tags.length; i++) {
if (this.tags[i] != null) { v = this.tags[i].wrap(v); }
}
}
return v;
} else {
return this.text.toString();
}
} else {
return "";
}
}
public String toString() {
return this.toString(false);
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Creates an IField/ILayer section.
*** @param srcURL The source URL displayed within the frame
*** @param sb The destination StringBuffer
*** @return The StringBuffer where the created IFrame/ILayer section is placed
**/
public static StringBuffer createIFrameTemplate(String srcURL, StringBuffer sb)
{
return HTMLTools.createIFrameTemplate(-1, -1, srcURL, sb);
}
/**
*** Creates an IField/ILayer section.
*** @param srcURL The source URL displayed within the frame
*** @return The String containing the IFrame/ILayer section
**/
public static String createIFrameTemplate(String srcURL)
{
return HTMLTools.createIFrameTemplate(-1, -1, srcURL, null).toString();
}
/**
*** Creates an IField/ILayer section.
*** @param w The width of the IFrame
*** @param h The height of the IFrame
*** @param srcURL The source URL displayed within the frame
*** @return The String containing the IFrame/ILayer section
**/
public static String createIFrameTemplate(int w, int h, String srcURL)
{
return HTMLTools.createIFrameTemplate(w, h, srcURL, null).toString();
}
/**
*** Creates an IField/ILayer section.
*** @param w The width of the IFrame
*** @param h The height of the IFrame
*** @param srcURL The source URL displayed within the frame
*** @param sb The destination StringBuffer
*** @return The StringBuffer where the created IFrame/ILayer section is placed
**/
public static StringBuffer createIFrameTemplate(int w, int h, String srcURL, StringBuffer sb)
{
if (sb == null) { sb = new StringBuffer(); }
String id = "id.iframe";
String ws = (w > 0)? String.valueOf(w) : "100%";
String hs = (h > 0)? String.valueOf(h) : "100%";
//String style = "STYLE='{visibility=visible;width=" + w + "px;height=" + h + "px}' ";
sb.append("<IFRAME WIDTH='"+ws+"' HEIGHT='"+hs+"' FRAMEBORDER='0' ID='"+id+"' SRC='"+srcURL+"'>\n");
sb.append("<ILAYER WIDTH='"+ws+"' HEIGHT='"+hs+"' FRAMEBORDER='0' ID='"+id+"' SRC='"+srcURL+"'>\n");
sb.append("InternetExplorer or Netscape is required to view this page\n");
sb.append("</ILAYER>\n");
sb.append("</IFRAME>\n");
return sb;
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
private static final String ARG_GET[] = new String[] { "get" };
private static final String ARG_POST[] = new String[] { "post" };
private static final String ARG_DECODE[] = new String[] { "decode", "dec" };
/**
*** Main entry point for testing/debugging
*** @param argv Comand-line arguments
**/
public static void main(String argv[])
{
RTConfig.setCommandLineArgs(argv);
if (RTConfig.hasProperty(ARG_DECODE)) {
String s = RTConfig.getString(ARG_DECODE,"");
Print.sysPrintln("Decoded: " + HTMLTools.decodeParameter(s));
System.exit(0);
}
if (RTConfig.hasProperty(ARG_GET)) {
try {
URIArg uri = new URIArg(RTConfig.getString(ARG_GET,""));
byte data[] = readPage_GET(uri.toString(), -1);
String s = StringTools.toStringValue(data);
Print.sysPrintln("Response:\n");
Print.sysPrintln(s);
System.exit(0);
} catch (Throwable th) {
Print.logException("Error", th);
System.exit(99);
}
}
if (RTConfig.hasProperty(ARG_POST)) {
try {
URIArg uri = new URIArg(RTConfig.getString(ARG_POST,""));
byte data[] = readPage_POST(uri.getURI(), (Properties)null, uri.getArgString().getBytes(), -1);
String s = StringTools.toStringValue(data);
Print.sysPrintln("Response:\n");
Print.sysPrintln(s);
System.exit(0);
} catch (Throwable th) {
Print.logException("Error", th);
System.exit(99);
}
}
Print.logWarn("Missing options ...");
}
}
|
3e021d0c2c22318e369ada33d590873565786d7e | 9,161 | java | Java | aws-java-sdk-cloudfront/src/main/java/com/amazonaws/services/cloudfront/model/CachedMethods.java | twigkit/aws-sdk-java | 0b8dd8cf5e52ad7ae57acd2ce7a584fd83a998be | [
"Apache-2.0"
] | null | null | null | aws-java-sdk-cloudfront/src/main/java/com/amazonaws/services/cloudfront/model/CachedMethods.java | twigkit/aws-sdk-java | 0b8dd8cf5e52ad7ae57acd2ce7a584fd83a998be | [
"Apache-2.0"
] | 1 | 2016-06-06T08:33:14.000Z | 2016-06-06T08:33:14.000Z | aws-java-sdk-cloudfront/src/main/java/com/amazonaws/services/cloudfront/model/CachedMethods.java | twigkit/aws-sdk-java | 0b8dd8cf5e52ad7ae57acd2ce7a584fd83a998be | [
"Apache-2.0"
] | 1 | 2016-06-02T10:45:22.000Z | 2016-06-02T10:45:22.000Z | 33.804428 | 118 | 0.606702 | 885 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.cloudfront.model;
import java.io.Serializable;
/**
* A complex type that controls whether CloudFront caches the response to
* requests using the specified HTTP methods. There are two choices: -
* CloudFront caches responses to GET and HEAD requests. - CloudFront caches
* responses to GET, HEAD, and OPTIONS requests. If you pick the second choice
* for your S3 Origin, you may need to forward Access-Control-Request-Method,
* Access-Control-Request-Headers and Origin headers for the responses to be
* cached correctly.
*/
public class CachedMethods implements Serializable, Cloneable {
/**
* The number of HTTP methods for which you want CloudFront to cache
* responses. Valid values are 2 (for caching responses to GET and HEAD
* requests) and 3 (for caching responses to GET, HEAD, and OPTIONS
* requests).
*/
private Integer quantity;
/**
* A complex type that contains the HTTP methods that you want CloudFront to
* cache responses to.
*/
private com.amazonaws.internal.SdkInternalList<String> items;
/**
* The number of HTTP methods for which you want CloudFront to cache
* responses. Valid values are 2 (for caching responses to GET and HEAD
* requests) and 3 (for caching responses to GET, HEAD, and OPTIONS
* requests).
*
* @param quantity
* The number of HTTP methods for which you want CloudFront to cache
* responses. Valid values are 2 (for caching responses to GET and
* HEAD requests) and 3 (for caching responses to GET, HEAD, and
* OPTIONS requests).
*/
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
/**
* The number of HTTP methods for which you want CloudFront to cache
* responses. Valid values are 2 (for caching responses to GET and HEAD
* requests) and 3 (for caching responses to GET, HEAD, and OPTIONS
* requests).
*
* @return The number of HTTP methods for which you want CloudFront to cache
* responses. Valid values are 2 (for caching responses to GET and
* HEAD requests) and 3 (for caching responses to GET, HEAD, and
* OPTIONS requests).
*/
public Integer getQuantity() {
return this.quantity;
}
/**
* The number of HTTP methods for which you want CloudFront to cache
* responses. Valid values are 2 (for caching responses to GET and HEAD
* requests) and 3 (for caching responses to GET, HEAD, and OPTIONS
* requests).
*
* @param quantity
* The number of HTTP methods for which you want CloudFront to cache
* responses. Valid values are 2 (for caching responses to GET and
* HEAD requests) and 3 (for caching responses to GET, HEAD, and
* OPTIONS requests).
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public CachedMethods withQuantity(Integer quantity) {
setQuantity(quantity);
return this;
}
/**
* A complex type that contains the HTTP methods that you want CloudFront to
* cache responses to.
*
* @return A complex type that contains the HTTP methods that you want
* CloudFront to cache responses to.
* @see Method
*/
public java.util.List<String> getItems() {
if (items == null) {
items = new com.amazonaws.internal.SdkInternalList<String>();
}
return items;
}
/**
* A complex type that contains the HTTP methods that you want CloudFront to
* cache responses to.
*
* @param items
* A complex type that contains the HTTP methods that you want
* CloudFront to cache responses to.
* @see Method
*/
public void setItems(java.util.Collection<String> items) {
if (items == null) {
this.items = null;
return;
}
this.items = new com.amazonaws.internal.SdkInternalList<String>(items);
}
/**
* A complex type that contains the HTTP methods that you want CloudFront to
* cache responses to.
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if
* any). Use {@link #setItems(java.util.Collection)} or
* {@link #withItems(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param items
* A complex type that contains the HTTP methods that you want
* CloudFront to cache responses to.
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see Method
*/
public CachedMethods withItems(String... items) {
if (this.items == null) {
setItems(new com.amazonaws.internal.SdkInternalList<String>(
items.length));
}
for (String ele : items) {
this.items.add(ele);
}
return this;
}
/**
* A complex type that contains the HTTP methods that you want CloudFront to
* cache responses to.
*
* @param items
* A complex type that contains the HTTP methods that you want
* CloudFront to cache responses to.
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see Method
*/
public CachedMethods withItems(java.util.Collection<String> items) {
setItems(items);
return this;
}
/**
* A complex type that contains the HTTP methods that you want CloudFront to
* cache responses to.
*
* @param items
* A complex type that contains the HTTP methods that you want
* CloudFront to cache responses to.
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see Method
*/
public CachedMethods withItems(Method... items) {
com.amazonaws.internal.SdkInternalList<String> itemsCopy = new com.amazonaws.internal.SdkInternalList<String>(
items.length);
for (Method value : items) {
itemsCopy.add(value.toString());
}
if (getItems() == null) {
setItems(itemsCopy);
} else {
getItems().addAll(itemsCopy);
}
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getQuantity() != null)
sb.append("Quantity: " + getQuantity() + ",");
if (getItems() != null)
sb.append("Items: " + getItems());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CachedMethods == false)
return false;
CachedMethods other = (CachedMethods) obj;
if (other.getQuantity() == null ^ this.getQuantity() == null)
return false;
if (other.getQuantity() != null
&& other.getQuantity().equals(this.getQuantity()) == false)
return false;
if (other.getItems() == null ^ this.getItems() == null)
return false;
if (other.getItems() != null
&& other.getItems().equals(this.getItems()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode
+ ((getQuantity() == null) ? 0 : getQuantity().hashCode());
hashCode = prime * hashCode
+ ((getItems() == null) ? 0 : getItems().hashCode());
return hashCode;
}
@Override
public CachedMethods clone() {
try {
return (CachedMethods) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
}
|
3e021d4df1e2cae98e022445119541886e13553c | 6,031 | java | Java | lang/java/avro/src/test/java/org/apache/avro/generic/TestGenericData.java | RonZamkadny/avro | 214803f7333fa6681caf0c36abf5899b7e861992 | [
"Apache-2.0"
] | null | null | null | lang/java/avro/src/test/java/org/apache/avro/generic/TestGenericData.java | RonZamkadny/avro | 214803f7333fa6681caf0c36abf5899b7e861992 | [
"Apache-2.0"
] | null | null | null | lang/java/avro/src/test/java/org/apache/avro/generic/TestGenericData.java | RonZamkadny/avro | 214803f7333fa6681caf0c36abf5899b7e861992 | [
"Apache-2.0"
] | null | null | null | 35.476471 | 125 | 0.702205 | 886 | /**
* 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.avro.generic;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Collection;
import java.util.ArrayDeque;
import static org.junit.Assert.*;
import java.util.Arrays;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Field;
import org.apache.avro.AvroRuntimeException;
import org.apache.avro.Schema.Type;
import org.apache.avro.util.Utf8;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Test;
public class TestGenericData {
@Test(expected=AvroRuntimeException.class)
public void testrecordConstructorNullSchema() throws Exception {
new GenericData.Record(null);
}
@Test(expected=AvroRuntimeException.class)
public void testrecordConstructorWrongSchema() throws Exception {
new GenericData.Record(Schema.create(Schema.Type.INT));
}
@Test(expected=AvroRuntimeException.class)
public void testArrayConstructorNullSchema() throws Exception {
new GenericData.Array<Object>(1, null);
}
@Test(expected=AvroRuntimeException.class)
public void testArrayConstructorWrongSchema() throws Exception {
new GenericData.Array<Object>(1, Schema.create(Schema.Type.INT));
}
@Test
/** Make sure that even with nulls, hashCode() doesn't throw NPE. */
public void testHashCode() {
GenericData.get().hashCode(null, Schema.create(Type.NULL));
GenericData.get().hashCode(null, Schema.createUnion(
Arrays.asList(Schema.create(Type.BOOLEAN), Schema.create(Type.STRING))));
List<CharSequence> stuff = new ArrayList<CharSequence>();
stuff.add("string");
Schema schema = recordSchema();
GenericRecord r = new GenericData.Record(schema);
r.put(0, stuff);
GenericData.get().hashCode(r, schema);
}
@Test
public void testEquals() {
Schema s = recordSchema();
GenericRecord r0 = new GenericData.Record(s);
GenericRecord r1 = new GenericData.Record(s);
GenericRecord r2 = new GenericData.Record(s);
Collection<CharSequence> l0 = new ArrayDeque<CharSequence>();
List<CharSequence> l1 = new ArrayList<CharSequence>();
GenericArray<CharSequence> l2 =
new GenericData.Array<CharSequence>(1,s.getFields().get(0).schema());
String foo = "foo";
l0.add(new StringBuffer(foo));
l1.add(foo);
l2.add(new Utf8(foo));
r0.put(0, l0);
r1.put(0, l1);
r2.put(0, l2);
assertEquals(r0, r1);
assertEquals(r0, r2);
assertEquals(r1, r2);
}
private Schema recordSchema() {
List<Field> fields = new ArrayList<Field>();
fields.add(new Field("anArray", Schema.createArray(Schema.create(Type.STRING)), null, null));
Schema schema = Schema.createRecord("arrayFoo", "test", "mytest", false);
schema.setFields(fields);
return schema;
}
@Test
public void testRecordGetFieldDoesntExist() throws Exception {
List<Field> fields = new ArrayList<Field>();
Schema schema = Schema.createRecord(fields);
GenericData.Record record = new GenericData.Record(schema);
assertNull(record.get("does not exist"));
}
@Test
public void testArrayReversal() {
Schema schema = Schema.createArray(Schema.create(Schema.Type.INT));
GenericArray<Integer> forward = new GenericData.Array<Integer>(10, schema);
GenericArray<Integer> backward = new GenericData.Array<Integer>(10, schema);
for (int i = 0; i <= 9; i++) {
forward.add(i);
}
for (int i = 9; i >= 0; i--) {
backward.add(i);
}
forward.reverse();
assertTrue(forward.equals(backward));
}
@Test
public void testArrayListInterface() {
Schema schema = Schema.createArray(Schema.create(Schema.Type.INT));
GenericArray<Integer> array = new GenericData.Array<Integer>(1, schema);
array.add(99);
assertEquals(new Integer(99), array.get(0));
try {
array.get(2);
fail("Expected IndexOutOfBoundsException getting index 2");
} catch (IndexOutOfBoundsException e) {}
array.clear();
assertEquals(0, array.size());
try {
array.get(0);
fail("Expected IndexOutOfBoundsException getting index 0 after clear()");
} catch (IndexOutOfBoundsException e) {}
}
@Test
public void testToStringIsJson() throws JsonParseException, IOException {
Field stringField = new Field("string", Schema.create(Type.STRING), null, null);
Field enumField = new Field("enum", Schema.createEnum("my_enum", "doc", null, Arrays.asList("a", "b", "c")), null, null);
Schema schema = Schema.createRecord("my_record", "doc", "mytest", false);
schema.setFields(Arrays.asList(stringField, enumField));
GenericRecord r = new GenericData.Record(schema);
r.put(stringField.name(), "hello\nthere\"\tyou}");
r.put(enumField.name(), new GenericData.EnumSymbol("a"));
String json = r.toString();
JsonFactory factory = new JsonFactory();
JsonParser parser = factory.createJsonParser(json);
ObjectMapper mapper = new ObjectMapper();
// will throw exception if string is not parsable json
mapper.readTree(parser);
}
}
|
3e021d76aff7963bd9fb7e8fdeb607975ad16405 | 771 | java | Java | app/src/androidTest/java/com/developer/nennenwodo/medmanager/ExampleInstrumentedTest.java | AdoraNwodo/MedManager | 337a56ac4c85fef3c06853d1ea6e235f9332b66a | [
"MIT"
] | 13 | 2018-11-14T19:18:43.000Z | 2022-03-15T01:08:47.000Z | app/src/androidTest/java/com/developer/nennenwodo/medmanager/ExampleInstrumentedTest.java | serignolebagabriel/MedManager | 337a56ac4c85fef3c06853d1ea6e235f9332b66a | [
"MIT"
] | null | null | null | app/src/androidTest/java/com/developer/nennenwodo/medmanager/ExampleInstrumentedTest.java | serignolebagabriel/MedManager | 337a56ac4c85fef3c06853d1ea6e235f9332b66a | [
"MIT"
] | 9 | 2018-11-14T18:43:57.000Z | 2020-04-21T21:31:34.000Z | 28.555556 | 89 | 0.753567 | 887 | package com.developer.nennenwodo.medmanager;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.developer.nennenwodo.medmanager", appContext.getPackageName());
}
}
|
3e021f56fa1389c2a934a1e2b4536819671d054c | 2,432 | java | Java | app/src/main/java/id/wonderdeal/wonderdealapps/base/BaseActivity.java | agustinaindah/wonderdeal | 738d4c26d0fdaefcebfbc3125fff7cb1f2ddd557 | [
"IJG"
] | null | null | null | app/src/main/java/id/wonderdeal/wonderdealapps/base/BaseActivity.java | agustinaindah/wonderdeal | 738d4c26d0fdaefcebfbc3125fff7cb1f2ddd557 | [
"IJG"
] | null | null | null | app/src/main/java/id/wonderdeal/wonderdealapps/base/BaseActivity.java | agustinaindah/wonderdeal | 738d4c26d0fdaefcebfbc3125fff7cb1f2ddd557 | [
"IJG"
] | null | null | null | 30.4 | 103 | 0.686678 | 888 | package id.wonderdeal.wonderdealapps.base;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import butterknife.ButterKnife;
import id.wonderdeal.wonderdealapps.R;
import id.wonderdeal.wonderdealapps.utils.Consts;
/**
* Created by agustinaindah on 13/09/2017.
*/
public abstract class BaseActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(setView());
ButterKnife.bind(this);
onActivityCreated(savedInstanceState);
}
protected abstract void onActivityCreated(Bundle savedInstanceState);
protected abstract int setView();
public void gotoFragment(FragmentManager fm, Fragment fragment, boolean addBackStack, String tag) {
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(
android.R.anim.slide_in_left,
android.R.anim.slide_out_right,
android.R.anim.slide_in_left,
android.R.anim.slide_out_right
);
ft.replace(R.id.fragmentContainer, fragment, tag);
if (addBackStack)
ft.addToBackStack(null);
ft.commit();
}
public void gotoFragment(FragmentManager fm, Fragment fragment, boolean addBackStack) {
gotoFragment(fm, fragment, addBackStack, Consts.FRAGMENT);
}
public void gotoFragment(FragmentManager fm, Fragment fragment) {
gotoFragment(fm, fragment, false);
}
public void gotoActivity(Class<?> cls, boolean isFinish) {
Intent intent = new Intent(this, cls);
startActivity(intent);
if (isFinish) finish();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
public void gotoActivity(Class<?> cls) {
gotoActivity(cls, false);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return true;
}
}
|
3e021f69286ca6dd8e530bb06746168a67542c2d | 479 | java | Java | src/main/java/com/langdon/ioc/BeanReference.java | Langdon-Chen/java-web-server | c9f715fa5842a69203f0dad7653b17c9f9e6215c | [
"MIT"
] | null | null | null | src/main/java/com/langdon/ioc/BeanReference.java | Langdon-Chen/java-web-server | c9f715fa5842a69203f0dad7653b17c9f9e6215c | [
"MIT"
] | null | null | null | src/main/java/com/langdon/ioc/BeanReference.java | Langdon-Chen/java-web-server | c9f715fa5842a69203f0dad7653b17c9f9e6215c | [
"MIT"
] | null | null | null | 15.1875 | 39 | 0.580247 | 889 | package com.langdon.ioc;
/**
* @author [email protected]
*/
public class BeanReference {
private String name;
private Object bean;
public BeanReference(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object getBean() {
return bean;
}
public void setBean(Object bean) {
this.bean = bean;
}
}
|
3e021ff44de20bbf497e9362df13dd0090fec31d | 2,922 | java | Java | codegen/java-gen/src/test/resources/tests/value-entity/state-events-in-different-pacakge/generated-test-managed/org/example/valueentity/domain/CounterTestKit.java | eigr-labs/akkaserverless-java-sdk | 80b7c61e5f12d8439159df3aa5d85f0d17378470 | [
"Apache-2.0"
] | 21 | 2021-03-18T03:48:22.000Z | 2022-03-31T15:07:31.000Z | codegen/java-gen/src/test/resources/tests/value-entity/state-events-in-different-pacakge/generated-test-managed/org/example/valueentity/domain/CounterTestKit.java | eigr-labs/akkaserverless-java-sdk | 80b7c61e5f12d8439159df3aa5d85f0d17378470 | [
"Apache-2.0"
] | 457 | 2021-05-26T23:41:54.000Z | 2022-03-31T13:22:04.000Z | codegen/java-gen/src/test/resources/tests/value-entity/state-events-in-different-pacakge/generated-test-managed/org/example/valueentity/domain/CounterTestKit.java | eigr-labs/akkaserverless-java-sdk | 80b7c61e5f12d8439159df3aa5d85f0d17378470 | [
"Apache-2.0"
] | 26 | 2021-05-26T22:53:16.000Z | 2022-03-02T16:43:00.000Z | 35.634146 | 105 | 0.768994 | 890 | package org.example.valueentity.domain;
import com.akkaserverless.javasdk.impl.effect.MessageReplyImpl;
import com.akkaserverless.javasdk.impl.effect.SecondaryEffectImpl;
import com.akkaserverless.javasdk.impl.valueentity.ValueEntityEffectImpl;
import com.akkaserverless.javasdk.testkit.ValueEntityResult;
import com.akkaserverless.javasdk.testkit.impl.TestKitValueEntityContext;
import com.akkaserverless.javasdk.testkit.impl.ValueEntityResultImpl;
import com.akkaserverless.javasdk.valueentity.ValueEntity;
import com.akkaserverless.javasdk.valueentity.ValueEntityContext;
import com.google.protobuf.Empty;
import org.example.valueentity.CounterApi;
import org.example.valueentity.state.OuterCounterState;
import java.util.function.Function;
// This code is managed by Akka Serverless tooling.
// It will be re-generated to reflect any changes to your protobuf definitions.
// DO NOT EDIT
/**
* TestKit for unit testing Counter
*/
public final class CounterTestKit {
private OuterCounterState.CounterState state;
private Counter entity;
/**
* Create a testkit instance of Counter
* @param entityFactory A function that creates a Counter based on the given ValueEntityContext,
* a default entity id is used.
*/
public static CounterTestKit of(Function<ValueEntityContext, Counter> entityFactory) {
return of("testkit-entity-id", entityFactory);
}
/**
* Create a testkit instance of Counter with a specific entity id.
*/
public static CounterTestKit of(String entityId, Function<ValueEntityContext, Counter> entityFactory) {
return new CounterTestKit(entityFactory.apply(new TestKitValueEntityContext(entityId)));
}
/** Construction is done through the static CounterTestKit.of-methods */
private CounterTestKit(Counter entity) {
this.state = entity.emptyState();
this.entity = entity;
}
private CounterTestKit(Counter entity, OuterCounterState.CounterState state) {
this.state = state;
this.entity = entity;
}
/**
* @return The current state of the Counter under test
*/
public OuterCounterState.CounterState getState() {
return state;
}
private <Reply> ValueEntityResult<Reply> interpretEffects(ValueEntity.Effect<Reply> effect) {
@SuppressWarnings("unchecked")
ValueEntityResultImpl<Reply> result = new ValueEntityResultImpl<>(effect);
if (result.stateWasUpdated()) {
this.state = (OuterCounterState.CounterState) result.getUpdatedState();
}
return result;
}
public ValueEntityResult<Empty> increase(CounterApi.IncreaseValue increaseValue) {
ValueEntity.Effect<Empty> effect = entity.increase(state, increaseValue);
return interpretEffects(effect);
}
public ValueEntityResult<Empty> decrease(CounterApi.DecreaseValue decreaseValue) {
ValueEntity.Effect<Empty> effect = entity.decrease(state, decreaseValue);
return interpretEffects(effect);
}
}
|
3e022064c71758850772967cf839b7eee341136e | 4,511 | java | Java | platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/common/AbstractValueHintTreeComponent.java | liveqmock/platform-tools-idea | 1c4b76108add6110898a7e3f8f70b970e352d3d4 | [
"Apache-2.0"
] | 2 | 2015-05-08T15:07:10.000Z | 2022-03-09T05:47:53.000Z | platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/common/AbstractValueHintTreeComponent.java | lshain-android-source/tools-idea | b37108d841684bcc2af45a2539b75dd62c4e283c | [
"Apache-2.0"
] | null | null | null | platform/xdebugger-impl/src/com/intellij/xdebugger/impl/evaluate/quick/common/AbstractValueHintTreeComponent.java | lshain-android-source/tools-idea | b37108d841684bcc2af45a2539b75dd62c4e283c | [
"Apache-2.0"
] | 2 | 2017-04-24T15:48:40.000Z | 2022-03-09T05:48:05.000Z | 33.169118 | 131 | 0.711594 | 891 | /*
* Copyright 2000-2009 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.xdebugger.impl.evaluate.quick.common;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.*;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.xdebugger.XDebuggerBundle;
import javax.swing.*;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
/**
* @author nik
*/
public abstract class AbstractValueHintTreeComponent<H> {
private static final int HISTORY_SIZE = 11;
private final ArrayList<H> myHistory = new ArrayList<H>();
private int myCurrentIndex = -1;
private final AbstractValueHint myValueHint;
private final Tree myTree;
private JPanel myMainPanel;
protected AbstractValueHintTreeComponent(final AbstractValueHint valueHint, final Tree tree, final H initialItem) {
myValueHint = valueHint;
myTree = tree;
myHistory.add(initialItem);
}
public JPanel getMainPanel() {
if (myMainPanel == null) {
myMainPanel = new JPanel(new BorderLayout());
myMainPanel.add(ScrollPaneFactory.createScrollPane(myTree), BorderLayout.CENTER);
myMainPanel.add(createToolbar(myMainPanel), BorderLayout.NORTH);
}
return myMainPanel;
}
private AnAction createGoForwardAction(){
return new AnAction(CodeInsightBundle.message("quick.definition.forward"), null, AllIcons.Actions.Forward){
public void actionPerformed(AnActionEvent e) {
if (myHistory.size() > 1 && myCurrentIndex < myHistory.size() - 1){
myCurrentIndex ++;
updateHint();
}
}
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(myHistory.size() > 1 && myCurrentIndex < myHistory.size() - 1);
}
};
}
private void updateHint() {
myValueHint.shiftLocation();
updateTree(myHistory.get(myCurrentIndex));
}
private AnAction createGoBackAction(){
return new AnAction(CodeInsightBundle.message("quick.definition.back"), null, AllIcons.Actions.Back){
public void actionPerformed(AnActionEvent e) {
if (myHistory.size() > 1 && myCurrentIndex > 0) {
myCurrentIndex--;
updateHint();
}
}
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(myHistory.size() > 1 && myCurrentIndex > 0);
}
};
}
protected abstract void updateTree(H selectedItem);
protected void addToHistory(final H item) {
if (myCurrentIndex < HISTORY_SIZE) {
if (myCurrentIndex != -1) {
myCurrentIndex += 1;
} else {
myCurrentIndex = 1;
}
myHistory.add(myCurrentIndex, item);
}
}
private JComponent createToolbar(final JPanel parent) {
DefaultActionGroup group = new DefaultActionGroup();
group.add(createSetRoot());
AnAction back = createGoBackAction();
back.registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, KeyEvent.ALT_MASK)), parent);
group.add(back);
AnAction forward = createGoForwardAction();
forward.registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, KeyEvent.ALT_MASK)), parent);
group.add(forward);
return ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, group, true).getComponent();
}
private AnAction createSetRoot() {
final String title = XDebuggerBundle.message("xdebugger.popup.value.tree.set.root.action.tooltip");
return new AnAction(title, title, AllIcons.Modules.UnmarkWebroot) {
public void actionPerformed(AnActionEvent e) {
final TreePath path = myTree.getSelectionPath();
if (path == null) return;
final Object node = path.getLastPathComponent();
setNodeAsRoot(node);
}
};
}
protected abstract void setNodeAsRoot(Object node);
}
|
3e022116a8c819b4e8408c1b7347843bf5fb5f4b | 10,014 | java | Java | jasperexamplev1/src/test/java/com/felixso/web/rest/AuthorResourceIntTest.java | felixso-infotech/JasperExampleProjects | c802cb048322b5aa17ba8806f8134e45bd7e087d | [
"Apache-2.0"
] | null | null | null | jasperexamplev1/src/test/java/com/felixso/web/rest/AuthorResourceIntTest.java | felixso-infotech/JasperExampleProjects | c802cb048322b5aa17ba8806f8134e45bd7e087d | [
"Apache-2.0"
] | 1 | 2022-02-12T11:47:55.000Z | 2022-02-12T11:47:55.000Z | jasperexamplev1/src/test/java/com/felixso/web/rest/AuthorResourceIntTest.java | felixso-infotech/JasperExampleProjects | c802cb048322b5aa17ba8806f8134e45bd7e087d | [
"Apache-2.0"
] | null | null | null | 35.892473 | 100 | 0.698522 | 892 | package com.felixso.web.rest;
import com.felixso.JasperExamplev1App;
import com.felixso.domain.Author;
import com.felixso.repository.AuthorRepository;
import com.felixso.service.AuthorService;
import com.felixso.service.dto.AuthorDTO;
import com.felixso.service.mapper.AuthorMapper;
import com.felixso.web.rest.errors.ExceptionTranslator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.util.List;
import static com.felixso.web.rest.TestUtil.createFormattingConversionService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the AuthorResource REST controller.
*
* @see AuthorResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = JasperExamplev1App.class)
public class AuthorResourceIntTest {
private static final String DEFAULT_NAME = "AAAAAAAAAA";
private static final String UPDATED_NAME = "BBBBBBBBBB";
@Autowired
private AuthorRepository authorRepository;
@Autowired
private AuthorMapper authorMapper;
@Autowired
private AuthorService authorService;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
private MockMvc restAuthorMockMvc;
private Author author;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
final AuthorResource authorResource = new AuthorResource(authorService);
this.restAuthorMockMvc = MockMvcBuilders.standaloneSetup(authorResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Author createEntity(EntityManager em) {
Author author = new Author()
.name(DEFAULT_NAME);
return author;
}
@Before
public void initTest() {
author = createEntity(em);
}
@Test
@Transactional
public void createAuthor() throws Exception {
int databaseSizeBeforeCreate = authorRepository.findAll().size();
// Create the Author
AuthorDTO authorDTO = authorMapper.toDto(author);
restAuthorMockMvc.perform(post("/api/authors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(authorDTO)))
.andExpect(status().isCreated());
// Validate the Author in the database
List<Author> authorList = authorRepository.findAll();
assertThat(authorList).hasSize(databaseSizeBeforeCreate + 1);
Author testAuthor = authorList.get(authorList.size() - 1);
assertThat(testAuthor.getName()).isEqualTo(DEFAULT_NAME);
}
@Test
@Transactional
public void createAuthorWithExistingId() throws Exception {
int databaseSizeBeforeCreate = authorRepository.findAll().size();
// Create the Author with an existing ID
author.setId(1L);
AuthorDTO authorDTO = authorMapper.toDto(author);
// An entity with an existing ID cannot be created, so this API call must fail
restAuthorMockMvc.perform(post("/api/authors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(authorDTO)))
.andExpect(status().isBadRequest());
// Validate the Author in the database
List<Author> authorList = authorRepository.findAll();
assertThat(authorList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void getAllAuthors() throws Exception {
// Initialize the database
authorRepository.saveAndFlush(author);
// Get all the authorList
restAuthorMockMvc.perform(get("/api/authors?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(author.getId().intValue())))
.andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString())));
}
@Test
@Transactional
public void getAuthor() throws Exception {
// Initialize the database
authorRepository.saveAndFlush(author);
// Get the author
restAuthorMockMvc.perform(get("/api/authors/{id}", author.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(author.getId().intValue()))
.andExpect(jsonPath("$.name").value(DEFAULT_NAME.toString()));
}
@Test
@Transactional
public void getNonExistingAuthor() throws Exception {
// Get the author
restAuthorMockMvc.perform(get("/api/authors/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateAuthor() throws Exception {
// Initialize the database
authorRepository.saveAndFlush(author);
int databaseSizeBeforeUpdate = authorRepository.findAll().size();
// Update the author
Author updatedAuthor = authorRepository.findById(author.getId()).get();
// Disconnect from session so that the updates on updatedAuthor are not directly saved in db
em.detach(updatedAuthor);
updatedAuthor
.name(UPDATED_NAME);
AuthorDTO authorDTO = authorMapper.toDto(updatedAuthor);
restAuthorMockMvc.perform(put("/api/authors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(authorDTO)))
.andExpect(status().isOk());
// Validate the Author in the database
List<Author> authorList = authorRepository.findAll();
assertThat(authorList).hasSize(databaseSizeBeforeUpdate);
Author testAuthor = authorList.get(authorList.size() - 1);
assertThat(testAuthor.getName()).isEqualTo(UPDATED_NAME);
}
@Test
@Transactional
public void updateNonExistingAuthor() throws Exception {
int databaseSizeBeforeUpdate = authorRepository.findAll().size();
// Create the Author
AuthorDTO authorDTO = authorMapper.toDto(author);
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restAuthorMockMvc.perform(put("/api/authors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(authorDTO)))
.andExpect(status().isBadRequest());
// Validate the Author in the database
List<Author> authorList = authorRepository.findAll();
assertThat(authorList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
public void deleteAuthor() throws Exception {
// Initialize the database
authorRepository.saveAndFlush(author);
int databaseSizeBeforeDelete = authorRepository.findAll().size();
// Get the author
restAuthorMockMvc.perform(delete("/api/authors/{id}", author.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate the database is empty
List<Author> authorList = authorRepository.findAll();
assertThat(authorList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Author.class);
Author author1 = new Author();
author1.setId(1L);
Author author2 = new Author();
author2.setId(author1.getId());
assertThat(author1).isEqualTo(author2);
author2.setId(2L);
assertThat(author1).isNotEqualTo(author2);
author1.setId(null);
assertThat(author1).isNotEqualTo(author2);
}
@Test
@Transactional
public void dtoEqualsVerifier() throws Exception {
TestUtil.equalsVerifier(AuthorDTO.class);
AuthorDTO authorDTO1 = new AuthorDTO();
authorDTO1.setId(1L);
AuthorDTO authorDTO2 = new AuthorDTO();
assertThat(authorDTO1).isNotEqualTo(authorDTO2);
authorDTO2.setId(authorDTO1.getId());
assertThat(authorDTO1).isEqualTo(authorDTO2);
authorDTO2.setId(2L);
assertThat(authorDTO1).isNotEqualTo(authorDTO2);
authorDTO1.setId(null);
assertThat(authorDTO1).isNotEqualTo(authorDTO2);
}
@Test
@Transactional
public void testEntityFromId() {
assertThat(authorMapper.fromId(42L).getId()).isEqualTo(42);
assertThat(authorMapper.fromId(null)).isNull();
}
}
|
3e0221fd8984eaf5631ab596101023512a57d13b | 1,803 | java | Java | openmessaging-spring-core/src/main/java/io/openmessaging/spring/helper/BeanDefinitionHelper.java | llIlll/openmessaging-spring | fa16927f816a6a8ed5655b73930c551bf38d7c9f | [
"Apache-2.0"
] | null | null | null | openmessaging-spring-core/src/main/java/io/openmessaging/spring/helper/BeanDefinitionHelper.java | llIlll/openmessaging-spring | fa16927f816a6a8ed5655b73930c551bf38d7c9f | [
"Apache-2.0"
] | null | null | null | openmessaging-spring-core/src/main/java/io/openmessaging/spring/helper/BeanDefinitionHelper.java | llIlll/openmessaging-spring | fa16927f816a6a8ed5655b73930c551bf38d7c9f | [
"Apache-2.0"
] | null | null | null | 36.06 | 112 | 0.722684 | 893 | /*
* 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 io.openmessaging.spring.helper;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
/**
* Utilities for processing {@link BeanDefinitionBuilder}.
*
* @version OMS 1.0.0
* @since OMS 1.0.0
*/
public class BeanDefinitionHelper {
public static void addValue(BeanDefinitionBuilder builder, String field, Object value) {
if (value == null) {
return;
}
builder.addPropertyValue(field, value);
}
public static void addValue(BeanDefinitionBuilder builder, Element element, String field, String property) {
String value = element.getAttribute(property);
if (StringUtils.hasText(value)) {
return;
}
builder.addPropertyValue(field, value);
}
public static void addValue(BeanDefinitionBuilder builder, Element element, String property) {
addValue(builder, element, property, property);
}
} |
3e02225ab7f56d9fee427e9808a0e4172078d246 | 1,330 | java | Java | app/src/main/java/com/gaofengze/demo/diy/retrofit/BaseObserver.java | GFZkkk/MVPdemo | aa7a8bae6bc63592320e9af6658b3c23f71fb1ff | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/gaofengze/demo/diy/retrofit/BaseObserver.java | GFZkkk/MVPdemo | aa7a8bae6bc63592320e9af6658b3c23f71fb1ff | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/gaofengze/demo/diy/retrofit/BaseObserver.java | GFZkkk/MVPdemo | aa7a8bae6bc63592320e9af6658b3c23f71fb1ff | [
"Apache-2.0"
] | null | null | null | 26.6 | 93 | 0.65188 | 894 | package com.gaofengze.demo.diy.retrofit;
import com.gaofengze.demo.callBack.BaseCallBack;
import com.gaofengze.demo.util.tools.DeBugUtil;
import java.io.IOException;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;
import retrofit2.HttpException;
/**
* Created by gaofengze on 2018/12/3
*/
public abstract class BaseObserver<T> implements Observer<T> {
private BaseCallBack callBackData;
public BaseObserver(BaseCallBack callBackData) {
this.callBackData = callBackData;
}
@Override
public void onSubscribe(Disposable d) {
callBackData.onSubscribe();
}
@Override
public void onError(Throwable e) {
// String msg = e.getMessage().contains(NetWorkData.logout) ? NetWorkData.logout : "";
String msg = e.getMessage();
DeBugUtil.error("msg: "+msg);
callBackData.onFailure(msg);
callBackData.onComplete();
if(e instanceof HttpException){
ResponseBody body = ((HttpException) e).response().errorBody();
try {
DeBugUtil.error(body.string());
} catch (IOException IOe) {
IOe.printStackTrace();
}
}
}
@Override
public void onComplete() {
callBackData.onComplete();
}
}
|
3e0222adc775dd70d135f24ffb8259e65bd4ec7b | 1,935 | java | Java | CommonUtils/src/main/java/com/common/utils/utils/log/BaseLogHandle.java | shixincube/CubeWare-Android | d15c546db8d187dc77d90128a346c396d9861648 | [
"MIT"
] | 11 | 2018-10-30T03:56:05.000Z | 2021-03-25T18:03:37.000Z | CommonUtils/src/main/java/com/common/utils/utils/log/BaseLogHandle.java | shixincube/CubeWare-Android | d15c546db8d187dc77d90128a346c396d9861648 | [
"MIT"
] | null | null | null | CommonUtils/src/main/java/com/common/utils/utils/log/BaseLogHandle.java | shixincube/CubeWare-Android | d15c546db8d187dc77d90128a346c396d9861648 | [
"MIT"
] | 3 | 2019-04-16T02:15:21.000Z | 2020-09-15T03:36:28.000Z | 21.988636 | 105 | 0.577778 | 895 | package com.common.utils.utils.log;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* 日志操作器。
*/
public abstract class BaseLogHandle {
protected static String TAG = "DEFAULT_TAG";
protected final StringBuilder buffer = new StringBuilder();
private SimpleDateFormat timeFormat = new SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.UK);
private Date date = new Date();
/**
* 获得日志句柄名称(默认类名)
*
* @return 返回日志句柄名称。
*/
public String getLogHandleName() {
return this.getClass().getName();
}
/**
* 日志打印
*
* @param level 日志级别
* @param tag 日志标签。
* @param message 日志内容。
* @param stackTrace 堆栈信息
*/
public abstract void log(LogLevel level, String tag, String message, StackTraceElement[] stackTrace);
/**
* 获取tag
*
* @return
*/
public String getTag() {
return TAG;
}
/**
* 设置tag
*
* @param tag
*/
public void setTag(String tag) {
TAG = tag;
}
/**
* 获取tag
*
* @return
*/
public String getDateTime() {
date.setTime(System.currentTimeMillis());
return timeFormat.format(date);
}
/**
* 获取堆栈信息
*
* @param stackTrace
*
* @return
*/
public String getStackTrace(StackTraceElement stackTrace) {
if (stackTrace == null) {
return "";
}
String format = "[(%s:%d)# %s -> %s]";
String fileName = stackTrace.getFileName();
int methodLine = stackTrace.getLineNumber();
String methodName = stackTrace.getMethodName();
String currentThread = Thread.currentThread().getName();
//String className = fileName.substring(0, fileName.lastIndexOf("."));
return String.format(Locale.CHINESE, format, fileName, methodLine, methodName, currentThread);
}
}
|
3e0222be774878d67dd32dd43359a4997ec5ad67 | 11,983 | java | Java | 08.mms_abstract/src/com/work/model/service/MemberService.java | ki-yungkim/studyspace_backup | abe385373de8687585d06b1862f5044f2d1e47b2 | [
"MIT"
] | null | null | null | 08.mms_abstract/src/com/work/model/service/MemberService.java | ki-yungkim/studyspace_backup | abe385373de8687585d06b1862f5044f2d1e47b2 | [
"MIT"
] | null | null | null | 08.mms_abstract/src/com/work/model/service/MemberService.java | ki-yungkim/studyspace_backup | abe385373de8687585d06b1862f5044f2d1e47b2 | [
"MIT"
] | null | null | null | 22.476548 | 136 | 0.582471 | 896 | // new-class에서 체크 체크 해서 만듬
/**
*
*/
package com.work.model.service;
import com.work.model.dto.AdminMember;
import com.work.model.dto.GeneralMember;
import com.work.model.dto.Member;
import com.work.model.dto.SpecialMember;
/**
* @author kky
*
*/
public class MemberService extends MemberServiceAbstract {
/**
* 회원들을 관리하기 위한 자료 저장구조 : 배열 다형성 반영(부모타입) :
* 생성자 사용 초기화, 확장, 고정 본인이 편한 로직으로 진행
*/
// private.. MemberService에 있어야 한다
private Member[] members = new Member[10];
private int count;
/**
* 현재 등록 인원수 조회
* @return 현재 등록 인원수
*/
public int getCount() {
return count;
}
/*
* 회원등록 구현 절차 :
* 1. 현재 등록된 회원수 (count)와 현재배열의 크기와 같은지 비교해서
*
* => 별도의 매서드로 분리설계 : 구현 클래스에서 메서드 (내가 맘대로 할 거니까)
* 2. 같으면 새로이 확장배열(기존배열의 크기 +)을 생성해서 (고정적, 동적 다 가능 고정 10개 or 배열의 크기만큼 더 추가 )
* 3. 새로이 확장한 배열요소에 기존 배열요소에 저장된 객체들을 이동저장 시킨 후
* 4. 기존에 참조하고 있는 배열대신에 새로이 확장한 배열요소 변경 참조설정
* ...
* 5. count의 배열요소에 아규먼트로 전달받은 회원객체 등록 :
* 6. count를 1 증가 시킴
*/
@Override //선언문 동일
public void addMember(Member dto) {
if (count == members.length) {
extendMembers();
}
if (exist(dto.getMemberId()) == -1) { //전달 받은 dto는 객체 지금 원하는건 속성 memberId
members[count++] = dto;
} else {
System.out.println("[오류]" + dto.getMemberId() + " 아이디는 사용할 수 없습니다.");
}
/* 무조건 등록 문제 : 중복 => 해결 방법 : 등록하기 전에 등록된 회원의 아이디가 같은지(같은 객체 equals())
* 동일아이디를 갖는 회원객체 존재하는 경우에는 오류메세지 출력 (void 라서 오류메세지로)
* 오류메세지 : [오류] 000 아이디는 사용할 수 없습니다.
*/
}
/* 기존 배열요소를 기본배열크기 + 배열크기를 확장처리 메서드
* System.arraycopy() 메서드 활용
* System.arraycopy(Object원본, int 시작위치, Object 복사해줄 대상, int 시작위치, int 길이)
* static 시스템이 가지고 있다
*/
/**
* <pre>
* 배열구조 추가 확장해서 기존 저장정보 이동 처리 메서드
* 1. memberTemp 배열을 member 길이만큼
* 2.
* 3.
* 4.
* </pre>
* @see java.lang.System#arraycopy(Object, int, Object, int, int)
*
*/
public void extendMembers() { //반환타입 필요 없다 members 가져온다
Member[] memberTemp = new Member[members.length + members.length];
System.arraycopy(members, 0, memberTemp, 0, members.length);
members = memberTemp;
}
/*
* 회원상세조회 절차 :
*
* 1. exist(String memberId) 수행결과 : 저장위치 반환
* 2. 저장위치 0보다 크거나 같은지 비교해서
* 3. True면 존재하니까 해당 배열요소의 객체를 return 반환
* 4. False면 (0보다 작으면) 존재하지 않음 : 존재하지 않으므로 객체타입의 기본 값 return null
*/
/**
* 회원상세조회
*/
@Override
public Member getMember(String memberId) {
int index = exist(memberId);
if (index >= 0) {
return members[index];
}
System.out.println("[오류]" + memberId + "는 존재하지 않는 아이디입니다.");
return null;
}
//The type MemberService must implement the inherited abstract method MemberServiceAbstract.exist(String)
/*
* CRUD 메서드에서 사용하기 위한 회원 존재유무 및 저장 위치 조회 메서드
* 1. 현재 등록된 회원수만큼 반복하면서
* 2. 배열에 저장된 순서대로 저장된 객체의 아이디와(dto.getMemberId()) 아규먼트로 전달받은 아이디가 같은지 비교해서 (Sting#equals(문자열))
* 3. 아이디가 같으면 현재 저장된 벼열요소의 인덱스 번호를 반환
*
* 4. 반복을 다 했는데도 return 되지 않았다면 아이디 정보를 갖는 회원객체가 존재하지 않으므로 return -1
* @param memberId 아이디
* @return 존재시에 저장위치 번호, 미존재시 -1
*/
@Override
public int exist(String memberId) {
for (int index = 0; index < count; index++) {
if(members[index].getMemberId().equals(memberId)) {
return index;
}
}
return -1;
}
@Override
public int existPw(String memberPw) {
for (int index = 0; index < count; index++) {
if(members[index].getMemberPw().equals(memberPw)) {
return index;
}
}
return -1;
}
@Override
public int existEntryDate(String entryDate) {
for (int index = 0; index < count; index++) {
if(members[index].getEntryDate().equals(entryDate)) {
return index;
}
}
return -1;
}
@Override
public int existMobile(String mobile) {
for (int index = 0; index < count; index++) {
if(members[index].getMobile().equals(mobile)) {
return index;
}
}
return -1;
}
@Override
public int existEmail(String email) {
for (int index = 0; index < count; index++) {
if(members[index].getEmail().equals(email)) {
return index;
}
}
return -1;
}
@Override
public int existGrade(String grade) {
for (int index = 0; index < count; index++) {
if(members[index].getGrade().equals(grade)) {
return index;
}
}
return -1;
}
@Override
public int[] existGradeArray(String grade) {
int[] temp = new int[count];
int index = 0;
for (int i = 0; i < count; i++) {
if(members[index].getGrade().equals(grade)) {
temp[i] = index ;
} else {
temp[i] = -1;
}
index++;
}
return temp;
}
/** 전체 조회
*
* System.arraycopy 사용
* 현재 등록된 모든 회원들의 정보만을 저장한 배열, 다형성 Member[]
*
* 뭔가 다른 방법이 있을 거다 생각해보자
*/
@Override
public Member[] getMember() {
Member[] memberPrint = new Member[members.length];
System.arraycopy(members, 0, memberPrint, 0, count);
for (int index = 0; index < count; index++) {
System.out.println(memberPrint[index]);
}
return null;
}
/**전체변경
* 존재하는 위치를 알아와서 아규먼트로 전달 받은 것을 왕창 교체 (아이디, 비밀번호, 이름 등등)
* 오류 발생시 메세지 처리
* 뭔가 이거 아닌거 같은데.. 일단 아이디가 동일하면 나머지 입력 받은 정보로 바꿔주는 메서드
* */
@Override
public void setMember(Member dto) {
int index = exist(dto.getMemberId());
if (index >= 0) {
members[index] = dto;
System.out.println(dto);
} else {
System.out.println("[오류]" + dto.getMemberId() + "는 존재하지 않는 아이디입니다.");
}
return;
}
/** 비밀번호 변경
* 아이디 찾고
* 저장되어 있는 비밀번호와 전달받은 비밀번호가 같은지 비교 equals - 같으면 변경 암호로 변경
* - setMemberPw, 아이디부터 없으면 존재X, 아이디는 존재하는데 비밀번호 안 맞으면 안 맞다고 출력
* (오류사항 2개)
* 매개변수 아이디, 비밀번호, 변경비밀번호
* boolean 암호변경성공 true, 실패하면 false
* */
@Override
public boolean setMemberPw(String memberId, String memberPw, String newPw) {
int index = exist(memberId);
if (index >= 0) {
if (members[index].getMemberPw().equals(memberPw) == true) {
members[index].setMemberPw(newPw);
System.out.println(members[index]);
} else {
System.out.println("맞지 않는 비밀번호입니다");
}
} else {
System.out.println("존재하지 않는 아이디입니다.");
}
return false;
}
/** 회원탈퇴
* 아이디 비밀번호 각각 조회 후 동일하면 null 넣으면 됨, (count - 1), null 칸이 늘어남 낭비, null 체크 코드 추가 해야함
* - 요소들 다 한칸 앞으로 이동시키는 방식은 IO 많이 발생!
* - 맨 마지막 요소를 삭제된 요소에 넣기 - 마지막 칸은 null 처리
* */
@Override
public void removeMember(String memberId, String memberPw) {
int indexId = exist(memberId);
int indexPw = existPw(memberPw);
if (indexId < 0) {
System.out.println("없는 아이디 입니다.");
}
if (indexId == indexPw) {
members[indexId] = members[(count - 1)];
members[(count - 1)] = null;
} else {
System.out.println("비밀번호가 틀립니다.");
}
for (int index = 0; index < count; index++) {
System.out.println(members[index]);
}
}
/** 회원 전체탈퇴 (데이터초기화)*/
@Override
public void removeMember() {
for (int index = 0; index < count; index++) {
members[index] = null;
System.out.println(members[index]);
}
System.out.println(members.length);
count = 0;
}
/**
* 초기회원 등록 메서드
*/
@Override
public void initMember() {
super.initMember();
Member dto1 = new GeneralMember("user01", "password01", "홍길동", "01012341000", "[email protected]", "2020-12-15", "G", 50000);
Member dto2 = new GeneralMember("user02", "password02", "강감찬", "01012342000", "[email protected]", "2021-01-05", "G", 950000);
Member dto3 = new SpecialMember("user03", "password03", "이순신", "01012343000", "[email protected]", "2020-11-15", "S", "강동원");
Member dto4 = new SpecialMember("user04", "password04", "김유신", "01012344000", "[email protected]", "2021-01-05", "S", "김하린");
Member dto5 = new AdminMember("administrator", "admin1004", "유관순", "01012345000", "[email protected]", "2020-04-01", "A", "선임");
addMember(dto1);
addMember(dto2);
addMember(dto3);
addMember(dto4);
addMember(dto5);
//for (int index = 0; index < count; index++) {
// System.out.println(members[index]);
//}
}
/**
* 계정 로그인 기능
* @param memberId
* @param memberPw
* @return
*
* 입력된 아이디 조회 - 있으면 입력된 아이디의 index 확인 - 입력된 비빌번호가 비밀번호[index]와 동일한지 확인 - 동일하면 로그인되었습니다
* - 없으면 아이디 또는 비밀번호가 틀립니다 - 다르면 아이디 또는 비밀번호가 틀립니다.
*
*/
public void login(String memberId, String memberPw) {
int indexId = exist(memberId);
int indexPw = existPw(memberPw);
// System.out.println(indexId);
// System.out.println(indexPw);
if (indexId < 0) {
System.out.println("아이디 또는 비밀번호가 틀립니다.");
return;
}
if (indexId == indexPw) {
System.out.println(memberId + "로 로그인되었습니다.");
} else {
System.out.println("아이디 또는 비밀번호가 틀립니다.");
}
}
/**
* 로그아웃 기능
* 지금은 특별히 할 수 있는 건 없다
* 이건 다음 번에 제대로
*/
public void logout(String memberId) {
System.out.println("로그아웃 되었습니다.");
}
/**
* 로그인 하면 마일리지 추가 해주는 코드
* getMileage 사용 필요
* GenenalMember 배열 선언하고 Member타입 배열인 members에 indexId에 있는 배열을 가져와서 mileage를 꺼내와야 한다
* members[indexId]를 memberG에 넣으려고 하는데 거기서 잘 안된다.
* getMileage를 못 쓰는 상태
* 형변환 문제인가
*/
// @Override
// public void loginplus(String memberId, String memberPw) {
//
// Member members = new GeneralMember();
// int indexId = exist(memberId);
// int indexPw = existPw(memberPw);
//
// if (indexId < 0) {
// return;
// }
//
// if (indexId == indexPw) {
// int mile = members[indexId].getMileage();
// members[indexId].setMileage((mile + 500));
//
// System.out.println(members[indexId]);
//
//
// } else {
// System.out.println("아이디 또는 비밀번호가 틀립니다.");
// }
//
// }
/**
* 가입일 조회해서 아이디 출력
* 추후에는 가입일 기준 그 이후 가입 아이디 출력 기능 구현
*/
@Override
public void entryDateId(String entryDate) {
int index = existEntryDate(entryDate);
if (index >= 0) {
String ID = members[index].getMemberId();
System.out.println("해당 가입일에 맞는 아이디는 : " + ID + "입니다");
} else {
System.out.println("[오류] 가입일 : " + entryDate + "인 아이디는 존재하지 않습니다.");
}
}
/**
* 전화번호, 이메일 조회해서 아이디 출력
*/
@Override
public void searchId(String mobile, String email) {
int indexMobile = existMobile(mobile);
int indexEmail = existEmail(email);
if (indexMobile < 0) {
System.out.println("없는 전화번호입니다.");
return;
}
if (indexEmail < 0) {
System.out.println("없는 이메일입니다.");
return;
}
if (indexMobile == indexEmail) {
String ID = members[indexMobile].getMemberId();
System.out.println( "해당 정보에 맞는 아이디는 " + ID + "입니다.");
} else {
System.out.println("전화번호 또는 이메일 정보가 정확하지 않습니다.");
}
}
/**
* 전화번호, 이메일 조회해서 비밀번호 출력
*/
@Override
public void searchPw(String mobile, String email) {
int indexMobile = existMobile(mobile);
int indexEmail = existEmail(email);
if (indexMobile < 0) {
System.out.println("없는 전화번호입니다.");
return;
}
if (indexEmail < 0) {
System.out.println("없는 이메일입니다.");
return;
}
if (indexMobile == indexEmail) {
String PW = members[indexMobile].getMemberPw();
System.out.println( "해당 정보에 맞는 비밀번호는 " + PW + "입니다.");
} else {
System.out.println("전화번호 또는 이메일 정보가 정확하지 않습니다.");
}
}
/**
* 등급별 아이디 조회
* 나온 아이디랑 같은게 나오면 다음 요소를 확인해봐라
* 0번 요소가 안 나오는 문제 발생
*
*/
@Override
public void gradeMember(String grade) {
int[] indexGrade = existGradeArray(grade);
String[] ID = new String[count];
for (int i = 0; i < count; i++) {
if (indexGrade[i] >= 0) {
int j = indexGrade[i];
ID[i] = members[j].getMemberId();
System.out.println("해당 등급에 해당하는 아이디는 : " + ID[i] + "입니다");
}
}
if (existGrade(grade) < 0) {
System.out.println("잘못된 등급을 입력하셨습니다.");
}
}
// else {
// System.out.println("[오류] 등급 : " + grade + "인 아이디는 존재하지 않습니다.");
}
|
3e0222f58910a1f1b9da063dac0d3f9c948bd1c8 | 1,170 | java | Java | app/src/main/java/asch/io/wallet/activity/AssetTransactionsActivity.java | AschPlatform/asch-android | a091bd031e0a5b9921c17d35ee0e42ce8720bb4c | [
"MIT"
] | 1 | 2020-04-08T02:13:47.000Z | 2020-04-08T02:13:47.000Z | app/src/main/java/asch/io/wallet/activity/AssetTransactionsActivity.java | AschPlatform/asch-android | a091bd031e0a5b9921c17d35ee0e42ce8720bb4c | [
"MIT"
] | null | null | null | app/src/main/java/asch/io/wallet/activity/AssetTransactionsActivity.java | AschPlatform/asch-android | a091bd031e0a5b9921c17d35ee0e42ce8720bb4c | [
"MIT"
] | null | null | null | 30.789474 | 106 | 0.768376 | 897 | package asch.io.wallet.activity;
import android.content.Intent;
import android.os.Bundle;
import com.alibaba.fastjson.JSON;
import asch.io.base.util.ActivityUtils;
import asch.io.wallet.R;
import asch.io.wallet.accounts.AssetManager;
import asch.io.wallet.contract.AssetTransactionsContract;
import asch.io.wallet.model.entity.AschAsset;
import asch.io.wallet.util.StatusBarUtil;
import asch.io.wallet.view.fragment.AssetTransactionsFragment;
/**
* Created by kimziv on 2017/9/27.
*/
public class AssetTransactionsActivity extends TitleToolbarActivity {
private AssetTransactionsContract.Presenter presenter;
private AssetTransactionsFragment fragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent=getIntent();
String name =intent.getExtras().getString("balance");
setTitle(name);
fragment=AssetTransactionsFragment.newInstance();
fragment.setArguments(intent.getExtras());
ActivityUtils.addFragmentToActivity(getSupportFragmentManager(),fragment,R.id.fragment_container);
StatusBarUtil.immersive(this);
}
}
|
3e02270ee251e16ae89f4b7b702f45330f49c78b | 683 | java | Java | src/main/java/com/evacipated/cardcrawl/mod/stslib/vfx/combat/TempDamageNumberEffect.java | a-personal-account/StSLib | ebcfc4442ff17d8de28a667c669030867b9112ce | [
"MIT"
] | 62 | 2018-07-12T15:35:06.000Z | 2021-11-26T13:48:43.000Z | src/main/java/com/evacipated/cardcrawl/mod/stslib/vfx/combat/TempDamageNumberEffect.java | a-personal-account/StSLib | ebcfc4442ff17d8de28a667c669030867b9112ce | [
"MIT"
] | 19 | 2018-12-30T17:02:57.000Z | 2022-02-04T15:18:29.000Z | src/main/java/com/evacipated/cardcrawl/mod/stslib/vfx/combat/TempDamageNumberEffect.java | a-personal-account/StSLib | ebcfc4442ff17d8de28a667c669030867b9112ce | [
"MIT"
] | 38 | 2018-07-27T21:23:28.000Z | 2022-03-08T15:38:44.000Z | 26.269231 | 85 | 0.713031 | 898 | package com.evacipated.cardcrawl.mod.stslib.vfx.combat;
import com.badlogic.gdx.graphics.Color;
import com.megacrit.cardcrawl.core.AbstractCreature;
import com.megacrit.cardcrawl.core.Settings;
import com.megacrit.cardcrawl.vfx.combat.DamageNumberEffect;
public class TempDamageNumberEffect extends DamageNumberEffect
{
private Color originalColor;
public TempDamageNumberEffect(AbstractCreature target, float x, float y, int amt)
{
super(target, x, y, amt);
color = Settings.GOLD_COLOR.cpy();
originalColor = color.cpy();
}
@Override
public void update()
{
super.update();
color = originalColor.cpy();
}
}
|
3e022914d126d0d62879e2ca24ac4f27ae426af2 | 367 | java | Java | src/main/java/com/example/ClusteringApp.java | codegenesis/scala-akka-example | b9859462922746a5c3c6c53fd978a64dbf887104 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/example/ClusteringApp.java | codegenesis/scala-akka-example | b9859462922746a5c3c6c53fd978a64dbf887104 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/example/ClusteringApp.java | codegenesis/scala-akka-example | b9859462922746a5c3c6c53fd978a64dbf887104 | [
"Apache-2.0"
] | null | null | null | 22.9375 | 102 | 0.773842 | 899 | package com.example;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
public class ClusteringApp {
public static void main(String[] args) {
ActorSystem system = ActorSystem.create(ClusteringConfig.CLUSTER_NAME);
ActorRef clusterListener = system.actorOf(Props.create(ClusterListener.class), "clusterListener");
}
}
|
3e022925ffd5e42565a952365fffdfa49310c042 | 3,765 | java | Java | modules/registry/registry-tools/jpa-gen/src/main/java/appcatalog/computeresource/JobManagerCommandGenerator.java | satyamsah/airavataocal | 727a3c7a07925594c6df2433961bec871be33235 | [
"ECL-2.0",
"Apache-2.0"
] | 74 | 2015-04-10T02:57:26.000Z | 2022-02-28T16:10:03.000Z | modules/registry/registry-tools/jpa-gen/src/main/java/appcatalog/computeresource/JobManagerCommandGenerator.java | satyamsah/airavataocal | 727a3c7a07925594c6df2433961bec871be33235 | [
"ECL-2.0",
"Apache-2.0"
] | 126 | 2015-04-26T02:55:26.000Z | 2022-02-16T22:43:28.000Z | modules/registry/registry-tools/jpa-gen/src/main/java/appcatalog/computeresource/JobManagerCommandGenerator.java | satyamsah/airavataocal | 727a3c7a07925594c6df2433961bec871be33235 | [
"ECL-2.0",
"Apache-2.0"
] | 163 | 2015-01-22T14:05:24.000Z | 2022-03-17T12:24:34.000Z | 45.361446 | 182 | 0.79575 | 900 | /**
*
* 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 appcatalog.computeresource;
import generators.JPAClassGenerator;
import generators.JPAResourceClassGenerator;
import generators.SQLGenerator;
import java.util.Arrays;
import model.JPAClassModel;
import model.JPAResourceClassModel;
import model.SQLData;
public class JobManagerCommandGenerator {
private static SQLData createSQLData() {
SQLData data = new SQLData();
data.setTableName("JOB_MANAGER_COMMAND");
data.getFieldData().put("RESOURCE_JOB_MANAGER_ID", Arrays.asList(new String[]{"VARCHAR", "(255)", "NOT", "NULL"}));
data.getFieldData().put("COMMAND_TYPE", Arrays.asList(new String[]{"VARCHAR", "(255)", "NOT", "NULL"}));
data.getFieldData().put("COMMAND", Arrays.asList(new String[]{"VARCHAR", "(255)",}));
data.getPrimaryKeys().add("RESOURCE_JOB_MANAGER_ID");
data.getPrimaryKeys().add("COMMAND_TYPE");
data.getForiegnKeys().put("RESOURCE_JOB_MANAGER_ID", new SQLData.ForiegnKeyData("RESOURCE_JOB_MANAGER(RESOURCE_JOB_MANAGER_ID)","ResourceJobManager","ResourceJobManagerResource"));
return data;
}
public static void testSqlGen() {
SQLData data = createSQLData();
SQLGenerator sqlGenerator = new SQLGenerator();
System.out.println(sqlGenerator.generateSQLCreateQuery(data));
}
public static void testJPAClassGen() {
SQLData data = createSQLData();
JPAClassGenerator jpaClassGenerator = new JPAClassGenerator();
jpaClassGenerator.setJpaClassPackageName("org.apache.aiaravata.application.catalog.data.model");
JPAClassModel model = jpaClassGenerator.createJPAClassModel(data);
System.out.println(jpaClassGenerator.generateJPAClass(model));
System.out.println(jpaClassGenerator.generateJPAPKClass(model.pkClassModel));
System.out.println(jpaClassGenerator.generatePersistenceXmlEntry(model));
}
public static void testJPAResourceClassGen() {
SQLData data = createSQLData();
JPAClassGenerator jpaClassGenerator = new JPAClassGenerator();
JPAClassModel model = jpaClassGenerator.createJPAClassModel(data);
JPAResourceClassGenerator jpaResourceClassGenerator = new JPAResourceClassGenerator();
jpaResourceClassGenerator.setExceptionClassName("AppCatalogException");
jpaResourceClassGenerator.setJpaUtilsClassName("AppCatalogJPAUtils");
jpaResourceClassGenerator.setResourceTypeClassName("AppCatalogResourceType");
jpaResourceClassGenerator.setQueryGeneratorClassName("AppCatalogQueryGenerator");
JPAResourceClassModel model2 = jpaResourceClassGenerator.createJPAResourceClassModel(model);
System.out.println(jpaResourceClassGenerator.generateJPAResourceClass(model2));
System.out.println(jpaResourceClassGenerator.generateAbstractResourceClassUpdates(model2));
System.out.println(jpaResourceClassGenerator.generateAppCatalogResourceTypeUpdates(model2));
System.out.println(jpaResourceClassGenerator.generateAppCatalogJPAUtilUpdates(model2));
}
public static void main(String[] args) {
testSqlGen();
testJPAClassGen();
testJPAResourceClassGen();
}
}
|
3e022b1624cf483fa9eee7de0605f3ce366a7a15 | 5,686 | java | Java | eventmesh-connector-rocketmq/src/main/java/com/webank/eventmesh/connector/rocketmq/producer/RocketMQProducerImpl.java | MajorHe1/EventMesh | 86e490f6fd6947238f89fdae07e2c338a953134e | [
"Apache-2.0"
] | null | null | null | eventmesh-connector-rocketmq/src/main/java/com/webank/eventmesh/connector/rocketmq/producer/RocketMQProducerImpl.java | MajorHe1/EventMesh | 86e490f6fd6947238f89fdae07e2c338a953134e | [
"Apache-2.0"
] | null | null | null | eventmesh-connector-rocketmq/src/main/java/com/webank/eventmesh/connector/rocketmq/producer/RocketMQProducerImpl.java | MajorHe1/EventMesh | 86e490f6fd6947238f89fdae07e2c338a953134e | [
"Apache-2.0"
] | null | null | null | 35.098765 | 144 | 0.730215 | 901 | /*
* 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 com.webank.eventmesh.connector.rocketmq.producer;
import com.webank.eventmesh.api.RRCallback;
import com.webank.eventmesh.api.producer.MeshMQProducer;
import com.webank.eventmesh.connector.rocketmq.common.ProxyConstants;
import com.webank.eventmesh.connector.rocketmq.config.ClientConfiguration;
import com.webank.eventmesh.connector.rocketmq.config.ConfigurationWraper;
import io.openmessaging.api.*;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
public class RocketMQProducerImpl implements MeshMQProducer {
public Logger logger = LoggerFactory.getLogger(this.getClass());
private ProducerImpl producer;
public final String DEFAULT_ACCESS_DRIVER = "com.webank.eventmesh.connector.rocketmq.MessagingAccessPointImpl";
@Override
public synchronized void init(Properties keyValue) {
ConfigurationWraper configurationWraper =
new ConfigurationWraper(ProxyConstants.PROXY_CONF_HOME
+ File.separator
+ ProxyConstants.PROXY_CONF_FILE, false);
final ClientConfiguration clientConfiguration = new ClientConfiguration(configurationWraper);
clientConfiguration.init();
String producerGroup = keyValue.getProperty("producerGroup");
String omsNamesrv = clientConfiguration.namesrvAddr;
Properties properties = new Properties();
properties.put(OMSBuiltinKeys.DRIVER_IMPL, DEFAULT_ACCESS_DRIVER);
properties.put("ACCESS_POINTS", omsNamesrv);
properties.put("REGION", "namespace");
properties.put("RMQ_PRODUCER_GROUP", producerGroup);
properties.put("OPERATION_TIMEOUT", 3000);
properties.put("PRODUCER_ID", producerGroup);
MessagingAccessPoint messagingAccessPoint = OMS.builder().build(properties);
producer = (ProducerImpl) messagingAccessPoint.createProducer(properties);
}
@Override
public boolean isStarted() {
return producer.isStarted();
}
@Override
public boolean isClosed() {
return producer.isClosed();
}
@Override
public void start() {
producer.start();
}
@Override
public synchronized void shutdown() {
producer.shutdown();
}
@Override
public void send(Message message, SendCallback sendCallback) throws Exception {
producer.sendAsync(message, sendCallback);
}
@Override
public void request(Message message, SendCallback sendCallback, RRCallback rrCallback, long timeout)
throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
throw new UnsupportedOperationException("not support request-reply mode when eventstore=rocketmq");
}
@Override
public Message request(Message message, long timeout) throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
throw new UnsupportedOperationException("not support request-reply mode when eventstore=rocketmq");
}
@Override
public boolean reply(final Message message, final SendCallback sendCallback) throws Exception {
throw new UnsupportedOperationException("not support request-reply mode when eventstore=rocketmq");
}
@Override
public MeshMQProducer getMeshMQProducer() {
return this;
}
@Override
public String buildMQClientId() {
return producer.getRocketmqProducer().buildMQClientId();
}
@Override
public void setExtFields() {
producer.setExtFields();
}
@Override
public void getDefaultTopicRouteInfoFromNameServer(String topic, long timeout) throws Exception {
producer.getRocketmqProducer().getDefaultMQProducerImpl()
.getmQClientFactory().getMQClientAPIImpl().getDefaultTopicRouteInfoFromNameServer(topic,
timeout);
}
@Override
public SendResult send(Message message) {
return producer.send(message);
}
@Override
public void sendOneway(Message message) {
producer.sendOneway(message);
}
@Override
public void sendAsync(Message message, SendCallback sendCallback) {
producer.sendAsync(message, sendCallback);
}
@Override
public void setCallbackExecutor(ExecutorService callbackExecutor) {
producer.setCallbackExecutor(callbackExecutor);
}
@Override
public void updateCredential(Properties credentialProperties) {
producer.updateCredential(credentialProperties);
}
@Override
public <T> MessageBuilder<T> messageBuilder() {
return null;
}
}
|
3e022bb7222b181c69099d564a382fd6e177c6a9 | 1,935 | java | Java | resources/facts/evosuite-eval-pipeline/gen-tests/secor/io.confluent=kafka-avro-serializer/evosuite-tests/com/pinterest/secor/parser/AvroMessageParser_ESTest.java | d-fact/CSlicer | 809a2799fa0979bedec9c575609c0d5ec270fbac | [
"Apache-2.0"
] | null | null | null | resources/facts/evosuite-eval-pipeline/gen-tests/secor/io.confluent=kafka-avro-serializer/evosuite-tests/com/pinterest/secor/parser/AvroMessageParser_ESTest.java | d-fact/CSlicer | 809a2799fa0979bedec9c575609c0d5ec270fbac | [
"Apache-2.0"
] | null | null | null | resources/facts/evosuite-eval-pipeline/gen-tests/secor/io.confluent=kafka-avro-serializer/evosuite-tests/com/pinterest/secor/parser/AvroMessageParser_ESTest.java | d-fact/CSlicer | 809a2799fa0979bedec9c575609c0d5ec270fbac | [
"Apache-2.0"
] | null | null | null | 36.509434 | 176 | 0.723514 | 902 | /*
* This file was automatically generated by EvoSuite
* Wed Aug 21 07:55:45 GMT 2019
*/
package com.pinterest.secor.parser;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import com.pinterest.secor.common.SecorConfig;
import com.pinterest.secor.parser.AvroMessageParser;
import org.apache.commons.configuration.XMLPropertiesConfiguration;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true)
public class AvroMessageParser_ESTest extends AvroMessageParser_ESTest_scaffolding {
@Test(timeout = 4000)
public void test0() throws Throwable {
XMLPropertiesConfiguration xMLPropertiesConfiguration0 = new XMLPropertiesConfiguration();
SecorConfig secorConfig0 = new SecorConfig(xMLPropertiesConfiguration0);
AvroMessageParser avroMessageParser0 = null;
try {
avroMessageParser0 = new AvroMessageParser(secorConfig0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// Failed to find required configuration option 'secor.offsets.prefix'.
//
verifyException("com.pinterest.secor.common.SecorConfig", e);
}
}
@Test(timeout = 4000)
public void test1() throws Throwable {
AvroMessageParser avroMessageParser0 = null;
try {
avroMessageParser0 = new AvroMessageParser((SecorConfig) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.pinterest.secor.parser.MessageParser", e);
}
}
}
|
3e022bd4e091246f41a7cd83a70dc4ded038ab2f | 809 | java | Java | src/samplesource/net/sf/jelly/apt/samplesource/Gender.java | ctarbide/apt-jelly | 44e898e2991ab394bd9e795405ace11540549587 | [
"Apache-2.0"
] | null | null | null | src/samplesource/net/sf/jelly/apt/samplesource/Gender.java | ctarbide/apt-jelly | 44e898e2991ab394bd9e795405ace11540549587 | [
"Apache-2.0"
] | null | null | null | src/samplesource/net/sf/jelly/apt/samplesource/Gender.java | ctarbide/apt-jelly | 44e898e2991ab394bd9e795405ace11540549587 | [
"Apache-2.0"
] | null | null | null | 24.515152 | 76 | 0.668727 | 903 | /**
* Copyright 2006 Ryan Heaton
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.jelly.apt.samplesource;
/**
* @author Ryan Heaton
*/
public enum Gender {
/**
* The male gender.
*/
MALE,
/**
* The female gender.
*/
FEMALE
}
|
Subsets and Splits