blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
332
content_id
stringlengths
40
40
detected_licenses
listlengths
0
50
license_type
stringclasses
2 values
repo_name
stringlengths
7
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
557 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
77.7k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
82 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
5.41M
extension
stringclasses
11 values
content
stringlengths
7
5.41M
authors
listlengths
1
1
author
stringlengths
0
161
d8d1d1f0569741bb59082abb9319738758008ea9
0e668e1efd8cd95b9b9ade1da7e8ab401944de4d
/src/com/thoughtworks/pos/domains/VIPdb.java
423bbc7f93f3e30d5f9628c51ad674baa8453df3
[ "MIT" ]
permissive
BJUT-2016-YU-LT/Pos-seed-06
49d120c969b76ef428c76910ed909a00274c5afc
aa538935cfd555690ddf6a06040423500cfce575
refs/heads/master
2021-01-20T18:24:12.401579
2016-06-30T13:29:19
2016-06-30T13:29:19
61,513,585
0
0
null
2016-06-27T06:20:13
2016-06-20T03:13:35
null
UTF-8
Java
false
false
349
java
package com.thoughtworks.pos.domains; /** * Created by pc on 2016/6/24. */ public class VIPdb { private String name; private boolean isVip; private int points; public String getName() { return name; } public int getPoints(){return points;} public boolean getisVip() { return isVip; } }
[ "915547778@qq.com" ]
915547778@qq.com
038ea078a1ad649e3d8ca07c7235a1157bef6678
54eab5d312e4994d9db7171c97fc1df7decf78ee
/devoxx-client/devoxx-client-admin/src/main/java/fr/soat/devoxx/game/webmvc/controllers/AdminUserController.java
aa367ca0338292553c3173d78e374177a86df4e9
[]
no_license
soatexpert/devoxxFr2012
caf5bcb8a898d144877014e491f1e1040a2837af
b78d9a2e2258f121eccb66a85fa84d29a720391c
refs/heads/master
2021-01-25T05:27:48.755167
2012-03-07T22:15:44
2012-03-07T22:15:44
3,529,568
1
2
null
null
null
null
UTF-8
Java
false
false
4,621
java
/* * Copyright (c) 2012 Aurélien VIALE * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package fr.soat.devoxx.game.webmvc.controllers; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import fr.soat.devoxx.game.admin.pojo.dto.AllUserResponseDto; import fr.soat.devoxx.game.business.admin.AdminResultService; import fr.soat.devoxx.game.business.admin.AdminUserService; import fr.soat.devoxx.game.business.exception.UserServiceException; import fr.soat.devoxx.game.pojo.ResultResponseDto; import fr.soat.devoxx.game.pojo.UserResponseDto; import fr.soat.devoxx.game.webmvc.utils.TilesUtil; /** * @author aurelien * */ @Controller @RequestMapping(value = "/admin/user") public class AdminUserController { @Autowired AdminResultService adminResultService; @Autowired AdminUserService adminUserService; private static Logger LOGGER = LoggerFactory.getLogger(AdminUserController.class); @RequestMapping(value = "/") public String showAllUser(Model model) { String forward = TilesUtil.DFR_ERRORS_ERRORMSG_PAGE; try { AllUserResponseDto allUsers = adminUserService.getAllUsers(); model.addAttribute("allUserResponses", allUsers.getUserResponses()); forward = TilesUtil.DFR_ADMIN_SHOWALLUSERS_PAGE; } catch (UserServiceException e) { model.addAttribute("error", "admin.error.user.getall"); LOGGER.info("Error while fetching all users", e); } return forward; } @RequestMapping(value = "/{userId}") public String showUser(@PathVariable Long userId, Model model) { String forward = TilesUtil.DFR_ERRORS_ERRORMSG_PAGE; try { UserResponseDto userResponse = adminUserService.getUser(userId); model.addAttribute("userResponse", userResponse); String email = StringUtils.isEmpty(userResponse.getMail()) ? StringUtils.EMPTY : userResponse.getMail().trim().toLowerCase(); model.addAttribute("mailHash", DigestUtils.md5Hex(email)); ResultResponseDto resultResponse = adminResultService.getResultForUser(userId); model.addAttribute("resultResponse", resultResponse); forward = TilesUtil.DFR_ADMIN_SHOWUSER_PAGE; } catch (UserServiceException e) { model.addAttribute("error", "admin.error.user.get"); model.addAttribute("errorParams", userId); LOGGER.info("Error while fetching user", e); } return forward; } @RequestMapping(value = "/{userId}/delete") public String removeUser(@PathVariable Long userId, Model model) { String forward = TilesUtil.DFR_ERRORS_ERRORMSG_PAGE; try { adminUserService.deleteUser(userId); forward = "redirect:/admin/user/"; } catch (UserServiceException e) { model.addAttribute("error", "admin.error.user.delete"); model.addAttribute("errorParams", userId); LOGGER.info("Error while deleting user", e); } return forward; } }
[ "aure77+github@gmail.com" ]
aure77+github@gmail.com
90b2190c2c1dbfe23e0a83bc91f29dfffb2aa78c
31cddb4114f8973ea006de49a30e7f1996547ab3
/src/main/java/com/cs/dao/model/ApplyPO.java
d94756faf4912ec4abcad4736d430c43c387be4e
[]
no_license
lslwsjly/android_server
e80d58089be878a6c25ff874c795d8895a983db9
8614605cb7d3b3c3a4719f57ba12e4579a29b377
refs/heads/master
2021-01-19T11:37:20.445300
2015-01-20T01:06:22
2015-01-20T01:06:22
26,108,272
0
0
null
null
null
null
UTF-8
Java
false
false
908
java
/** * */ package com.cs.dao.model; /** * 申请持久类. * @author 李思良. * */ public class ApplyPO extends BasePO { private int activity = 0; private int person = 0; private int status = -1; /** * @return 活动id. */ public int getActivity() { return activity; } /** * @param activity 活动id. */ public void setActivity(int activity) { this.activity = activity; } /** * @return 申请人id. */ public int getPerson() { return person; } /** * @param person 申请人id. */ public void setPerson(int person) { this.person = person; } /** * * @return 申请状态,2为未审核,0为被拒绝,1为审核通过. */ public int getStatus() { return this.status; } /** * * @param status 申请状态,2为未审核,0为被拒绝,1为审核通过. */ public void setStatus(int status) { this.status = status; } }
[ "lisl10@163.com" ]
lisl10@163.com
d3774f32ee0705da3e8c3fc2ba46f0e2a2def586
44e0ce7fdba98f998ec4d44ccdbcc68b9bc9bca8
/naturelife/src/main/java/com/nature/life/config/WebConfiguration.java
b90606b3f68da14c1ee1e4667df5d805a45cbd2c
[]
no_license
PabloCumpe/nature-life-2019
06170a6d110dd2384a88a4e808d27257d354addb
8ae47c949bc1330eaf35310a0eb7185d8f445f51
refs/heads/master
2022-07-13T00:58:03.871555
2019-10-31T14:53:51
2019-10-31T14:53:51
213,656,168
0
0
null
null
null
null
UTF-8
Java
false
false
698
java
package com.nature.life.config; import com.nature.life.filters.LoggingFilter; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfiguration implements WebMvcConfigurer { @Bean public FilterRegistrationBean<LoggingFilter> loggingFilter() { FilterRegistrationBean<LoggingFilter> registrationBean = new FilterRegistrationBean<LoggingFilter>(new LoggingFilter()); registrationBean.setOrder(1); return registrationBean; } }
[ "pablo.cumpe@almundo.com" ]
pablo.cumpe@almundo.com
6d9fea3cef9270bc271c6909aaeb08dd6891e8e7
f6bd9a1e602a6f97b1feeb175c99b9145da26087
/enculette/src/main/java/org/bzs/enculette/HelloWorld.java
1ab6004898f90d2baca232c384d4ea7d8d7a596e
[]
no_license
TrTLE/Enculette
b2aec2668879c3fae0d206b486be28b318932181
44cef95003ebf180b25cf870f0d5ba14d5963be1
refs/heads/master
2021-01-12T03:23:26.926853
2017-01-09T10:33:37
2017-01-09T10:33:37
78,204,766
1
0
null
null
null
null
UTF-8
Java
false
false
640
java
package org.bzs.enculette; /** * TODO apaquin This type ... * * @author apaquin */ public class HelloWorld { private int call; /** * The constructor. */ public HelloWorld() { } /** * The constructor. * * @param num */ public HelloWorld(int num) { this.call = 0; } /** * @return une string contenant la chaine "Hello" */ public String sayhello() { this.call = this.call + 1; return "Hello"; } /** * @return le nombre de fois où la fonction sayhello a été appelé */ public int countCall() { return this.call; } }
[ "chpaqou@gmail.com" ]
chpaqou@gmail.com
9205b01358b98676dd81d94ab4b69a173ac90ca3
05722cbf7f9b16ee1e365127de195f4d27d54765
/src/main/java/com/xwkj/cost/util/DateUtil.java
b6c770d13df6db4faf709d36d905ce052812b7ea
[]
no_license
Kingman-LF/electricity_cost
69f63012fb93fe38a3ea80eaade2c3e5f6277ca2
316026dc14ed12db5967ffeee322eb2be1befa11
refs/heads/master
2023-03-23T04:37:13.629675
2021-03-22T01:16:05
2021-03-22T01:16:05
313,499,771
0
0
null
null
null
null
UTF-8
Java
false
false
3,649
java
package com.xwkj.cost.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * 日期工具类 * * @author 张永辉 */ public class DateUtil { public final static String YYYY_MM_DD = "yyyy-MM-dd"; public final static String YYYY_MM = "yyyy-MM"; public final static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; public final static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss"; public final static String HH_MM = "HH:mm"; public static void main(String[] args) throws ParseException { Date date = stringToDate("2019-01-01", YYYY_MM_DD); String s = dateToString(date, "yy-MM-dd HH:mm"); System.out.println(s); } /** * 返回两个日期之间相差的月数 * * @param startDate * @param endDate * @return */ public static Integer getDifMonth(Date startDate, Date endDate) { Calendar start = Calendar.getInstance(); Calendar end = Calendar.getInstance(); start.setTime(startDate); end.setTime(endDate); int result = end.get(Calendar.MONTH) - start.get(Calendar.MONTH); int month = (end.get(Calendar.YEAR) - start.get(Calendar.YEAR)) * 12; return Math.abs(month + result); } /** * 返回日期中的月份 * * @param date * @return */ public static Integer getMonth(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int month = calendar.get(Calendar.MONTH); return month + 1; } /** * String类型转换为Date类型 * * @param strTime * @param formatType * @return */ public static Date stringToDate(String strTime, String formatType) throws ParseException { SimpleDateFormat formatter = new SimpleDateFormat(formatType); Date date = null; date = formatter.parse(strTime); return date; } /** * Date类型转换为String类型 * * @param data * @param formatType * @return */ public static String dateToString(Date data, String formatType) { return new SimpleDateFormat(formatType).format(data); } /** * 获取当年的第一天 * * @param * @return */ public static Date getCurrYearFirst() { Calendar currCal = Calendar.getInstance(); int currentYear = currCal.get(Calendar.YEAR); return getYearFirst(currentYear); } /** * 获取某年第一天日期 * * @param year 年份 * @return Date */ public static Date getYearFirst(int year) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); Date currYearFirst = calendar.getTime(); return currYearFirst; } /** * 获取两个日期之间的间隔小时数 * @param start * @param end * @return */ public static Integer getBetweenHours(Date start , Date end){ long startTime = start.getTime(); long endTime = end.getTime(); int between = (int)(Math.abs(endTime-startTime)/(3600*1000)); return between; } /** * 获取两个日期之间的间隔天数 * @param start * @param end * @return */ public static Integer getBetweenDay(Date start , Date end){ long startTime = start.getTime(); long endTime = end.getTime(); int between = (int)(Math.abs(endTime-startTime)/(3600*1000*24)); return between; } }
[ "172654669@qq.com" ]
172654669@qq.com
b69de7877988872004d0791c6de83ee2722e58fe
8c97a8a7ce1fee938d440e164676ff64acd1014a
/app/src/main/java/android/rushdroid/model/NotFound.java
2d2dd55b9717cac762565cdd8064fbe2483760eb
[]
no_license
leondoofus/RushDroid
2f8d779167b20fabd1aef1c46331b5e694060437
c77628f27c0ddc012e857df81cdd7c8fbc18424f
refs/heads/master
2021-05-11T20:02:14.164433
2018-01-14T12:52:36
2018-01-14T12:52:36
117,428,860
0
0
null
null
null
null
UTF-8
Java
false
false
158
java
package android.rushdroid.model; public class NotFound extends Exception { public NotFound (String message){ super (message); } }
[ "teenage_96@yahoo.com" ]
teenage_96@yahoo.com
97eba89ccfe63c4349a249c6d706513016d906d2
6e57bdc0a6cd18f9f546559875256c4570256c45
/packages/apps/DocumentsUI/src/com/android/documentsui/selection/MotionEvents.java
1915c5ab6fce208645e6976ed6370e41dea7e1e9
[]
no_license
dongdong331/test
969d6e945f7f21a5819cd1d5f536d12c552e825c
2ba7bcea4f9d9715cbb1c4e69271f7b185a0786e
refs/heads/master
2023-03-07T06:56:55.210503
2020-12-07T04:15:33
2020-12-07T04:15:33
134,398,935
2
1
null
2022-11-21T07:53:41
2018-05-22T10:26:42
null
UTF-8
Java
false
false
3,129
java
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.documentsui.selection; import android.graphics.Point; import android.view.KeyEvent; import android.view.MotionEvent; /** * Utility methods for working with {@link MotionEvent} instances. */ final class MotionEvents { private MotionEvents() {} static boolean isMouseEvent(MotionEvent e) { return e.getToolType(0) == MotionEvent.TOOL_TYPE_MOUSE; } static boolean isTouchEvent(MotionEvent e) { return e.getToolType(0) == MotionEvent.TOOL_TYPE_FINGER; } static boolean isActionMove(MotionEvent e) { return e.getActionMasked() == MotionEvent.ACTION_MOVE; } static boolean isActionDown(MotionEvent e) { return e.getActionMasked() == MotionEvent.ACTION_DOWN; } static boolean isActionUp(MotionEvent e) { return e.getActionMasked() == MotionEvent.ACTION_UP; } static boolean isActionPointerUp(MotionEvent e) { return e.getActionMasked() == MotionEvent.ACTION_POINTER_UP; } static boolean isActionPointerDown(MotionEvent e) { return e.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN; } static boolean isActionCancel(MotionEvent e) { return e.getActionMasked() == MotionEvent.ACTION_CANCEL; } static Point getOrigin(MotionEvent e) { return new Point((int) e.getX(), (int) e.getY()); } static boolean isPrimaryButtonPressed(MotionEvent e) { return e.isButtonPressed(MotionEvent.BUTTON_PRIMARY); } public static boolean isSecondaryButtonPressed(MotionEvent e) { return e.isButtonPressed(MotionEvent.BUTTON_SECONDARY); } public static boolean isTertiaryButtonPressed(MotionEvent e) { return e.isButtonPressed(MotionEvent.BUTTON_TERTIARY); } static boolean isShiftKeyPressed(MotionEvent e) { return hasBit(e.getMetaState(), KeyEvent.META_SHIFT_ON); } static boolean isCtrlKeyPressed(MotionEvent e) { return hasBit(e.getMetaState(), KeyEvent.META_CTRL_ON); } static boolean isAltKeyPressed(MotionEvent e) { return hasBit(e.getMetaState(), KeyEvent.META_ALT_ON); } public static boolean isTouchpadScroll(MotionEvent e) { // Touchpad inputs are treated as mouse inputs, and when scrolling, there are no buttons // returned. return isMouseEvent(e) && isActionMove(e) && e.getButtonState() == 0; } private static boolean hasBit(int metaState, int bit) { return (metaState & bit) != 0; } }
[ "dongdong331@163.com" ]
dongdong331@163.com
acfe1b1c6d04935255624d97b57148cda05d9835
02838ecffa3010e566f95bafb437527546a22dc4
/app/src/main/java/com/cds/iot/data/source/remote/HttpApi.java
591beedce6cbdee1fd08bafb4d2ce1b4cb68a37d
[ "Apache-2.0" ]
permissive
cheng2016/app-frame
c7feec83d11385f717f99d9547eb97cb41c17070
6ef55b2bccafbeefadc47c0b93aa1394f7fc5e40
refs/heads/master
2020-03-23T16:03:18.740519
2018-08-09T08:08:56
2018-08-09T08:08:56
141,791,654
1
0
null
null
null
null
UTF-8
Java
false
false
3,192
java
package com.cds.iot.data.source.remote; import com.cds.iot.data.entity.BaseResp; import com.cds.iot.data.entity.GankDaily; import com.cds.iot.data.entity.NewsList; import io.reactivex.Observable; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.POST; import retrofit2.http.Path; import retrofit2.http.Query; /** * Created by chengzj on 2017/6/18. */ public interface HttpApi { //http://gank.io/api/day/2016/10/12 public static final String base_url = "http://sit.wecarelove.com/api/"; @GET("day/{year}/{month}/{day}") Observable<GankDaily> getDaily( @Path("year") int year, @Path("month") int month, @Path("day") int day); @GET("list") Observable<NewsList> getNewsList(@Query("req_funType") String funType, @Query("req_count") String count); /*--------------------------------------------- 用户相关 -----------------------------------------*/ @POST("user/register") Observable<BaseResp> register(@Query("content") String json); @POST("user/login") Observable<BaseResp> login(@Query("content") String json, @Header("custom_token") String token); @POST("user/thridlogin") Observable<BaseResp> thridlogin(@Query("content") String json); @POST("user/thridbind") Observable<BaseResp> thridbind(@Query("content") String json); @POST("user/thridunbind") Observable<BaseResp> thridunbind(@Query("content") String json); @GET("user/info") Observable<BaseResp> getInfo(@Query("content") String json); @POST("user/info") Observable<BaseResp> updateInfo(@Query("content") String json); @POST("user/sendcode") Observable<BaseResp> sendcode(@Query("content") String json); @POST("user/resetpwd") Observable<BaseResp> resetpwd(@Query("content") String json); @POST("user/updatepwd") Observable<BaseResp> updatepwd(@Query("content") String json); @POST("user/updatephonenumber") Observable<BaseResp> updatephonenumber(@Query("content") String json); @POST("user/feedback") Observable<BaseResp> feedback(@Query("content") String json); /*--------------------------------------------- 设备相关 -----------------------------------------*/ @POST("device/delete") Observable<BaseResp> deleteDevice(@Query("content") String json); @GET("device/info") Observable<BaseResp> getDeviceInfo(@Query("content") String json); @POST("device/info") Observable<BaseResp> updateDeviceInfo(@Query("content") String json); /*--------------------------------------------- 场景相关 -----------------------------------------*/ @POST("scene/delete") Observable<BaseResp> deleteScene(@Query("content") String json); @GET("scene/info") Observable<BaseResp> getSceneInfo(@Query("content") String json); @POST("scene/info") Observable<BaseResp> updateSceneInfo(@Query("content") String json); /*--------------------------------------------- 版本相关 -----------------------------------------*/ @GET("version/update") Observable<BaseResp> updateVersion(@Query("content") String json); }
[ "1102743539@qq.com" ]
1102743539@qq.com
b927b8bea4168c59630f57fade022cf89ece4f14
a859962a1631182105b26310417dab44c8a2e2a6
/src/main/java/com/test/MinNumberValidator.java
58bbe1ac4866e8030d3f7ffa1ef54442f87398a7
[]
no_license
cheese-stands-alone/JFoenixTest
8f114c77c8915411c328864b63240ff7c50e4084
114a4714c596ec1162f29db1f24481a3b9ea4e2b
refs/heads/master
2023-08-08T05:08:47.011413
2018-01-29T17:21:37
2018-01-29T17:21:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,085
java
package com.test; import com.jfoenix.validation.NumberValidator; import javafx.scene.control.TextInputControl; public class MinNumberValidator extends NumberValidator { private int min; MinNumberValidator(int min) { this.min = min; } @Override protected void eval() { if (srcControl.get() instanceof TextInputControl) { TextInputControl textField = (TextInputControl) srcControl.get(); try { if(textField.getText().isEmpty()) { hasErrors.set(false); } else { int result = Integer.parseInt(textField.getText()); if (result < min) { message.set(result + " is < " + min); hasErrors.set(true); } else { hasErrors.set(false); } } } catch (Exception e) { message.set(textField.getText() + " is not a number"); hasErrors.set(true); } } } }
[ "rwhite@oaklandcorp.com" ]
rwhite@oaklandcorp.com
11db1b89a52a05ea80de7d056d04e0a69da2d9d4
0b4372ef9b1d8cc5748ad986fcac7b842caf9491
/app/src/main/java/com/majorleaguegaming/evetest/Model/Widget.java
4f8e717dd6aeace99848af4b91dc992d29804240
[]
no_license
mlg-apritykin/EVETest
e6c112728096e6447c7c1db914b62784c7c82e23
2062e9d66dbc444d737e66170f7a23e1d919a559
refs/heads/master
2021-01-12T12:22:22.685066
2016-11-09T19:21:46
2016-11-09T19:21:46
72,468,081
0
0
null
null
null
null
UTF-8
Java
false
false
6,978
java
package com.majorleaguegaming.evetest.Model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import javax.annotation.Generated; @Generated("org.jsonschema2pojo") public class Widget { @SerializedName("id") @Expose private int id; @SerializedName("name_1") @Expose private String name1; @SerializedName("name_1_type") @Expose private String name1Type; @SerializedName("name_2") @Expose private Object name2; @SerializedName("name_2_type") @Expose private Object name2Type; @SerializedName("image_1_url") @Expose private Object image1Url; @SerializedName("image_2_url") @Expose private Object image2Url; @SerializedName("data_type") @Expose private String dataType; @SerializedName("data_1") @Expose private String data1; @SerializedName("data_2") @Expose private Object data2; @SerializedName("text") @Expose private String text; @SerializedName("active") @Expose private boolean active; @SerializedName("created_at") @Expose private String createdAt; @SerializedName("updated_at") @Expose private String updatedAt; @SerializedName("boulder") @Expose private int boulder; @SerializedName("image_1") @Expose private String image1; @SerializedName("image_2") @Expose private String image2; @SerializedName("active_text") @Expose private String activeText; @SerializedName("name_1_display_name") @Expose private String name1DisplayName; /** * * @return * The id */ public int getId() { return id; } /** * * @param id * The id */ public void setId(int id) { this.id = id; } /** * * @return * The name1 */ public String getName1() { return name1; } /** * * @param name1 * The name_1 */ public void setName1(String name1) { this.name1 = name1; } /** * * @return * The name1Type */ public String getName1Type() { return name1Type; } /** * * @param name1Type * The name_1_type */ public void setName1Type(String name1Type) { this.name1Type = name1Type; } /** * * @return * The name2 */ public Object getName2() { return name2; } /** * * @param name2 * The name_2 */ public void setName2(Object name2) { this.name2 = name2; } /** * * @return * The name2Type */ public Object getName2Type() { return name2Type; } /** * * @param name2Type * The name_2_type */ public void setName2Type(Object name2Type) { this.name2Type = name2Type; } /** * * @return * The image1Url */ public Object getImage1Url() { return image1Url; } /** * * @param image1Url * The image_1_url */ public void setImage1Url(Object image1Url) { this.image1Url = image1Url; } /** * * @return * The image2Url */ public Object getImage2Url() { return image2Url; } /** * * @param image2Url * The image_2_url */ public void setImage2Url(Object image2Url) { this.image2Url = image2Url; } /** * * @return * The dataType */ public String getDataType() { return dataType; } /** * * @param dataType * The data_type */ public void setDataType(String dataType) { this.dataType = dataType; } /** * * @return * The data1 */ public String getData1() { return data1; } /** * * @param data1 * The data_1 */ public void setData1(String data1) { this.data1 = data1; } /** * * @return * The data2 */ public Object getData2() { return data2; } /** * * @param data2 * The data_2 */ public void setData2(Object data2) { this.data2 = data2; } /** * * @return * The text */ public String getText() { return text; } /** * * @param text * The text */ public void setText(String text) { this.text = text; } /** * * @return * The active */ public boolean isActive() { return active; } /** * * @param active * The active */ public void setActive(boolean active) { this.active = active; } /** * * @return * The createdAt */ public String getCreatedAt() { return createdAt; } /** * * @param createdAt * The created_at */ public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } /** * * @return * The updatedAt */ public String getUpdatedAt() { return updatedAt; } /** * * @param updatedAt * The updated_at */ public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; } /** * * @return * The boulder */ public int getBoulder() { return boulder; } /** * * @param boulder * The boulder */ public void setBoulder(int boulder) { this.boulder = boulder; } /** * * @return * The image1 */ public String getImage1() { return image1; } /** * * @param image1 * The image_1 */ public void setImage1(String image1) { this.image1 = image1; } /** * * @return * The image2 */ public String getImage2() { return image2; } /** * * @param image2 * The image_2 */ public void setImage2(String image2) { this.image2 = image2; } /** * * @return * The activeText */ public String getActiveText() { return activeText; } /** * * @param activeText * The active_text */ public void setActiveText(String activeText) { this.activeText = activeText; } /** * * @return * The name1DisplayName */ public String getName1DisplayName() { return name1DisplayName; } /** * * @param name1DisplayName * The name_1_display_name */ public void setName1DisplayName(String name1DisplayName) { this.name1DisplayName = name1DisplayName; } }
[ "apritykin@mlg.tv" ]
apritykin@mlg.tv
95fbf09b35b5ad51e347396dd9fe0625b60ed045
4f12dcf91ec9f5b65a81668b5c402f3234b05634
/src/main/java/com/mstartup/bugtracking/web/rest/BugResource.java
e2a4e509b388cd66f8ec4f05aa3d297b4d5d442f
[]
no_license
MahametH/bugTracking
2fbe566f2c256d23cb554fbf452689b14a0d510c
cccf9c1078783cb41e08a41f7b6f6a88785f7e08
refs/heads/master
2023-06-27T08:27:31.250320
2021-07-27T16:27:00
2021-07-27T16:27:00
390,053,188
0
0
null
null
null
null
UTF-8
Java
false
false
6,143
java
package com.mstartup.bugtracking.web.rest; import com.mstartup.bugtracking.service.BugService; import com.mstartup.bugtracking.web.rest.errors.BadRequestAlertException; import com.mstartup.bugtracking.service.dto.BugDTO; import com.mstartup.bugtracking.service.dto.BugCriteria; import com.mstartup.bugtracking.service.BugQueryService; import io.github.jhipster.web.util.HeaderUtil; import io.github.jhipster.web.util.PaginationUtil; import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; /** * REST controller for managing {@link com.mstartup.bugtracking.domain.Bug}. */ @RestController @RequestMapping("/api") public class BugResource { private final Logger log = LoggerFactory.getLogger(BugResource.class); private static final String ENTITY_NAME = "bug"; @Value("${jhipster.clientApp.name}") private String applicationName; private final BugService bugService; private final BugQueryService bugQueryService; public BugResource(BugService bugService, BugQueryService bugQueryService) { this.bugService = bugService; this.bugQueryService = bugQueryService; } /** * {@code POST /bugs} : Create a new bug. * * @param bugDTO the bugDTO to create. * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new bugDTO, or with status {@code 400 (Bad Request)} if the bug has already an ID. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PostMapping("/bugs") public ResponseEntity<BugDTO> createBug(@Valid @RequestBody BugDTO bugDTO) throws URISyntaxException { log.debug("REST request to save Bug : {}", bugDTO); if (bugDTO.getId() != null) { throw new BadRequestAlertException("A new bug cannot already have an ID", ENTITY_NAME, "idexists"); } BugDTO result = bugService.save(bugDTO); return ResponseEntity.created(new URI("/api/bugs/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString())) .body(result); } /** * {@code PUT /bugs} : Updates an existing bug. * * @param bugDTO the bugDTO to update. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated bugDTO, * or with status {@code 400 (Bad Request)} if the bugDTO is not valid, * or with status {@code 500 (Internal Server Error)} if the bugDTO couldn't be updated. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PutMapping("/bugs") public ResponseEntity<BugDTO> updateBug(@Valid @RequestBody BugDTO bugDTO) throws URISyntaxException { log.debug("REST request to update Bug : {}", bugDTO); if (bugDTO.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } BugDTO result = bugService.save(bugDTO); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, bugDTO.getId().toString())) .body(result); } /** * {@code GET /bugs} : get all the bugs. * * @param pageable the pagination information. * @param criteria the criteria which the requested entities should match. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of bugs in body. */ @GetMapping("/bugs") public ResponseEntity<List<BugDTO>> getAllBugs(BugCriteria criteria, Pageable pageable) { log.debug("REST request to get Bugs by criteria: {}", criteria); Page<BugDTO> page = bugQueryService.findByCriteria(criteria, pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); return ResponseEntity.ok().headers(headers).body(page.getContent()); } /** * {@code GET /bugs/count} : count all the bugs. * * @param criteria the criteria which the requested entities should match. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the count in body. */ @GetMapping("/bugs/count") public ResponseEntity<Long> countBugs(BugCriteria criteria) { log.debug("REST request to count Bugs by criteria: {}", criteria); return ResponseEntity.ok().body(bugQueryService.countByCriteria(criteria)); } /** * {@code GET /bugs/:id} : get the "id" bug. * * @param id the id of the bugDTO to retrieve. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the bugDTO, or with status {@code 404 (Not Found)}. */ @GetMapping("/bugs/{id}") public ResponseEntity<BugDTO> getBug(@PathVariable Long id) { log.debug("REST request to get Bug : {}", id); Optional<BugDTO> bugDTO = bugService.findOne(id); return ResponseUtil.wrapOrNotFound(bugDTO); } /** * {@code DELETE /bugs/:id} : delete the "id" bug. * * @param id the id of the bugDTO to delete. * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. */ @DeleteMapping("/bugs/{id}") public ResponseEntity<Void> deleteBug(@PathVariable Long id) { log.debug("REST request to delete Bug : {}", id); bugService.delete(id); return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())).build(); } }
[ "37776898+MahametH@users.noreply.github.com" ]
37776898+MahametH@users.noreply.github.com
c71b5214810e32780823cb6b2c41031186686373
271dd653c6f3209a5dc19b2a519e36bcf3c1ecc9
/tugas4/Tempair.java
5d95e7b3b5153cd956ea720032a971246441d1a7
[]
no_license
13020180064/TUGAS-4_PBO
0b79a1a6970916a78c9703f23aa8ccf5398f6731
21f30d50ea577c86d37b2e9f6090f7277d330614
refs/heads/master
2021-05-17T08:30:19.567780
2020-03-29T10:31:50
2020-03-29T10:31:50
250,708,885
0
0
null
null
null
null
UTF-8
Java
false
false
689
java
import java.util.Scanner; /* contoh pemakaian IF tiga kasus : wujud air */ public class Tempair { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub /* Kamus : */ int T; Scanner masukan=new Scanner(System.in); /* Program */ System.out.print ("Contoh IF tiga kasus \n"); System.out.print ("Temperatur (der. C) = "); T=masukan.nextInt(); if (T < 0) { System.out.print ("Wujud air beku \n"+ T); }else if ((0 <= T) && (T <= 100)){ System.out.print ("Wujud air cair \n"+ T); }else if (T > 100){ System.out.print ("Wujud air uap/gas \n"+ T); }; } }
[ "noreply@github.com" ]
noreply@github.com
6d208705a8d6d09a1dade09913d2ad9c8573f9ed
2e96aafbdea2fb683e3cffd9b906a89402c0227e
/cmtester/src/main/java/algorithm/mp/mp4Acc/MP134Acc.java
519d46c69cf4d92298b2610d0c3a5e5843115bed
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "MIT", "NCSA", "LicenseRef-scancode-unknown-license-reference" ]
permissive
phantomDai/CMTJmcr
b439db17411c05e745ac98b07b037c168b02a008
56c91914a6aa0500ff89e71381a66ecd2bfa63ed
refs/heads/master
2023-05-11T16:17:58.057163
2023-05-04T12:21:34
2023-05-04T12:21:34
323,773,780
0
0
null
null
null
null
UTF-8
Java
false
false
357
java
package algorithm.mp.mp4Acc; import algorithm.mp.MP; import algorithm.mp.MetamorphicPattern; import java.util.List; /** * @author GN * @description * @date 2020/10/6 */ public class MP134Acc extends MP implements MetamorphicPattern { @Override public List<String> followUpSeqWithoutSort(List<String> sourceSeq) { return null; } }
[ "daihepeng@sina.cn" ]
daihepeng@sina.cn
21f5dc67baa77e1f195c30b38010fd9352c451c1
7a7ebbb4d0a98aa5c267e505046a63ddcb54d715
/Observer/Observer/src/Watch.java
6a438823b2330671f183b81e19a30c45a08f1d79
[]
no_license
lcsmas/OOSE
866f6e8421873a540e2b941c9b5fda420936afc4
7bea78f205f4bf3e07607eaadc0ee5030d86474b
refs/heads/master
2023-02-19T17:27:56.588339
2019-10-25T14:22:16
2019-10-25T14:22:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,886
java
import java.awt.*; import java.awt.event.*; import java.util.Vector; import javax.swing.*; public class Watch extends JFrame implements ActionListener, ItemListener, Subject { Button Close; JRadioButton red, green, blue; Vector observers; public Watch() { super("Change 2 other frames"); // list of observing frames observers = new Vector(); // add panel to content pane JPanel p = new JPanel(true); p.setLayout(new BorderLayout()); getContentPane().add("Center", p); // vertical box layout Box box = new Box(BoxLayout.Y_AXIS); p.add("Center", box); // add 3 radio buttons box.add(red = new JRadioButton("Red")); box.add(green = new JRadioButton("Green")); box.add(blue = new JRadioButton("Blue")); // listen for clicks on radio buttons blue.addItemListener(this); red.addItemListener(this); green.addItemListener(this); // make all part of same button group ButtonGroup bgr = new ButtonGroup(); bgr.add(red); bgr.add(green); bgr.add(blue); pack(); setVisible(true); // create observers ColorFrame cframe = new ColorFrame(this); ListFrame lframe = new ListFrame(this); } public void itemStateChanged(ItemEvent e) { // responds to radio button clicks // if the button is selected if (e.getStateChange() == ItemEvent.SELECTED) notifyObservers((JRadioButton) e.getSource()); } private void notifyObservers(JRadioButton rad) { // sends text of selected button to all observers String color = rad.getText(); for (int i = 0; i < observers.size(); i++) ((Observer) (observers.elementAt(i))).sendNotify(color); } public void registerInterest(Observer obs) { observers.addElement(obs); } public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub } public static void main(String[] arg){ Watch w = new Watch(); } } // class Watch
[ "lucas_mas@msn.com" ]
lucas_mas@msn.com
d239358d2a75cfab5ff5fb8aad3ca53894b8489b
29c6809142627cb6cfcb6613a585fa80f077e738
/Lab 9 Priority Queue - PLR/src/priorityQueue/AbstractListPriorityQueue.java
1bc0d53e212d66a19f8b34b450b9bd4457a74770
[]
no_license
pedrorivera40/DataStructuresLab
6948330c3bd4b12d6f2d807851f75bca4378f885
dfe4f81e34b632b09f68a730a0769b1379d70208
refs/heads/master
2020-05-23T07:54:14.354169
2017-06-05T21:40:37
2017-06-05T21:40:37
80,462,083
0
1
null
null
null
null
UTF-8
Java
false
false
1,601
java
package priorityQueue; import java.util.ArrayList; import java.util.Comparator; import priorityQueueInterfaces.Entry; /** * Implementation of a PriorityQueue based in an ArrayList<Entry<K, V>>. * @author pedroirivera-vega * * @param <K> * @param <V> */ public abstract class AbstractListPriorityQueue<K, V> extends AbstractPriorityQueue<K, V> { protected ArrayList<Entry<K,V>> list; protected AbstractListPriorityQueue(Comparator<K> cmp) { super(cmp); list = new ArrayList<>(); } protected AbstractListPriorityQueue() { super(); list = new ArrayList<>(); } @Override public int size() { return list.size(); } @Override public Entry<K, V> min() { if (this.isEmpty()) return null; return list.get(minEntryIndex()); } /** * Internal method to find the index of the element in list * containing an entry having min key. Subclasses will * implement as needed. * * @return index of the element having min key in list. */ protected abstract int minEntryIndex(); /** * This method is mainly for testing purposes. Elements (entries) * are displayed as they are inside the internal list, from first * to last; hence, in this case, they they are not seen in any * particular order (increasing or decreasing), but just as they * are in the list.... */ public void display() { if (this.isEmpty()) System.out.println("EMPTY"); else for (Entry<K,V> e : list) System.out.println(e); } @Override public Entry<K, V> removeMin() { if(this.isEmpty()) return null; return list.remove(minEntryIndex()); } }
[ "4035b20@guanabana.ece.uprm.edu" ]
4035b20@guanabana.ece.uprm.edu
26f757c1920d25dd5c63d43c3e184f03dd3a8bc0
2a6f1c71d576ddca3cf15fa62afb1f25e9cac138
/src/main/java/com/sfgdi/sfgdi/controllers/ConstrucorInjectedController.java
54406f8674d46f8ccbec8e7b47274a6897a3fb43
[]
no_license
alvinsyarifudin/sfg-di
f6e632bdf684a4072e3dd02f07f4a9bdfc27ff5f
e5fd3f67574f3a67568f86e2d78428a64d930406
refs/heads/master
2022-11-16T09:17:49.608631
2020-07-19T15:43:49
2020-07-19T15:43:49
280,618,560
0
0
null
2020-07-18T08:52:31
2020-07-18T08:52:30
null
UTF-8
Java
false
false
575
java
package com.sfgdi.sfgdi.controllers; import com.sfgdi.sfgdi.services.GreetingServices; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; @Controller public class ConstrucorInjectedController { private final GreetingServices greetingServices; public ConstrucorInjectedController(@Qualifier("constructorGreetingService") GreetingServices greetingServices) { this.greetingServices = greetingServices; } public String getGreeting(){ return greetingServices.sayGreeting(); } }
[ "alvinsyarifudin@gmail.com" ]
alvinsyarifudin@gmail.com
acbf850f53fecd31ae615f340c2fd1de52025a27
9aef8d2b990c88421e588d31b9324eee67ea6ba7
/app/src/main/java/com/example/thoriqsalafi/quiz/showResult.java
83850c778075fb2798f64c5f84089ca5b3c5dcec
[]
no_license
thoriqsalafi/quiz
966b3a4fc7b7e1bfe571dbeb112892141b8f3124
4b2dd4ff61a9c1586691d7374d96c1d86f8b61ff
refs/heads/master
2021-01-13T04:30:22.878837
2017-02-08T01:15:44
2017-02-08T01:15:44
79,781,038
0
0
null
null
null
null
UTF-8
Java
false
false
859
java
package com.example.thoriqsalafi.quiz; import android.app.Activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.method.LinkMovementMethod; import android.view.View; import android.widget.Button; import android.widget.TextView; public class showResult extends Activity { Button yesButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_result); yesButton = (Button)findViewById(R.id.yesButton); yesButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(showResult.this, MainActivity.class); startActivity(i); } }); } }
[ "thoriq@u.nus.edu" ]
thoriq@u.nus.edu
50de1c3fcca9d6907f6cb3da50aa13a172494eca
298fc2ca1efaa6e0f7d17c2bc1735ccc67cdfe7b
/pubUtils/src/main/java/com/linkage/lib/BitmapUtils.java
0630fe9697fd0fd7173a3b2b0a3e4945ee5885b1
[]
no_license
chaoyuexing/Test
0a4647bf1329a35aabe59b44ba8f7ae2b21b08e6
8d4257895dbe536a003992e5c41187fc41b36d1c
refs/heads/master
2021-01-19T02:18:23.025024
2019-06-21T12:42:14
2019-06-21T12:42:14
43,409,763
0
0
null
null
null
null
UTF-8
Java
false
false
16,762
java
/* * Copyright (c) 2013. wyouflf (wyouflf@gmail.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 com.linkage.lib; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.text.TextUtils; import android.view.View; import android.view.animation.Animation; import com.linkage.lib.bitmap.BitmapCacheListener; import com.linkage.lib.bitmap.BitmapCommonUtils; import com.linkage.lib.bitmap.BitmapDisplayConfig; import com.linkage.lib.bitmap.BitmapGlobalConfig; import com.linkage.lib.bitmap.callback.BitmapLoadCallBack; import com.linkage.lib.bitmap.callback.BitmapLoadFrom; import com.linkage.lib.bitmap.callback.DefaultBitmapLoadCallBack; import com.linkage.lib.bitmap.core.AsyncDrawable; import com.linkage.lib.bitmap.core.BitmapSize; import com.linkage.lib.bitmap.download.Downloader; import com.linkage.lib.util.core.CompatibleAsyncTask; import com.linkage.lib.util.core.LruDiskCache; import java.io.File; import java.lang.ref.WeakReference; public class BitmapUtils { private boolean pauseTask = false; private final Object pauseTaskLock = new Object(); private Context context; private BitmapGlobalConfig globalConfig; private BitmapDisplayConfig defaultDisplayConfig; /////////////////////////////////////////////// create /////////////////////////////////////////////////// public BitmapUtils(Context context) { this(context, null); } public BitmapUtils(Context context, String diskCachePath) { if (context == null) { throw new IllegalArgumentException("context may not be null"); } this.context = context; globalConfig = new BitmapGlobalConfig(context, diskCachePath); defaultDisplayConfig = new BitmapDisplayConfig(); } public BitmapUtils(Context context, String diskCachePath, int memoryCacheSize) { this(context, diskCachePath); globalConfig.setMemoryCacheSize(memoryCacheSize); } public BitmapUtils(Context context, String diskCachePath, int memoryCacheSize, int diskCacheSize) { this(context, diskCachePath); globalConfig.setMemoryCacheSize(memoryCacheSize); globalConfig.setDiskCacheSize(diskCacheSize); } public BitmapUtils(Context context, String diskCachePath, float memoryCachePercent) { this(context, diskCachePath); globalConfig.setMemCacheSizePercent(memoryCachePercent); } public BitmapUtils(Context context, String diskCachePath, float memoryCachePercent, int diskCacheSize) { this(context, diskCachePath); globalConfig.setMemCacheSizePercent(memoryCachePercent); globalConfig.setDiskCacheSize(diskCacheSize); } //////////////////////////////////////// config //////////////////////////////////////////////////////////////////// public BitmapUtils configDefaultLoadingImage(Drawable drawable) { defaultDisplayConfig.setLoadingDrawable(drawable); return this; } public BitmapUtils configDefaultLoadingImage(int resId) { defaultDisplayConfig.setLoadingDrawable(context.getResources().getDrawable(resId)); return this; } public BitmapUtils configDefaultLoadingImage(Bitmap bitmap) { defaultDisplayConfig.setLoadingDrawable(new BitmapDrawable(context.getResources(), bitmap)); return this; } public BitmapUtils configDefaultLoadFailedImage(Drawable drawable) { defaultDisplayConfig.setLoadFailedDrawable(drawable); return this; } public BitmapUtils configDefaultLoadFailedImage(int resId) { defaultDisplayConfig.setLoadFailedDrawable(context.getResources().getDrawable(resId)); return this; } public BitmapUtils configDefaultLoadFailedImage(Bitmap bitmap) { defaultDisplayConfig.setLoadFailedDrawable(new BitmapDrawable(context.getResources(), bitmap)); return this; } public BitmapUtils configDefaultBitmapMaxSize(int maxWidth, int maxHeight) { defaultDisplayConfig.setBitmapMaxSize(new BitmapSize(maxWidth, maxHeight)); return this; } public BitmapUtils configDefaultBitmapMaxSize(BitmapSize maxSize) { defaultDisplayConfig.setBitmapMaxSize(maxSize); return this; } public BitmapUtils configDefaultImageLoadAnimation(Animation animation) { defaultDisplayConfig.setAnimation(animation); return this; } public BitmapUtils configDefaultAutoRotation(boolean autoRotation) { defaultDisplayConfig.setAutoRotation(autoRotation); return this; } public BitmapUtils configDefaultShowOriginal(boolean showOriginal) { defaultDisplayConfig.setShowOriginal(showOriginal); return this; } public BitmapUtils configDefaultBitmapConfig(Bitmap.Config config) { defaultDisplayConfig.setBitmapConfig(config); return this; } public BitmapUtils configDefaultDisplayConfig(BitmapDisplayConfig displayConfig) { defaultDisplayConfig = displayConfig; return this; } public BitmapUtils configDownloader(Downloader downloader) { globalConfig.setDownloader(downloader); return this; } public BitmapUtils configDefaultCacheExpiry(long defaultExpiry) { globalConfig.setDefaultCacheExpiry(defaultExpiry); return this; } public BitmapUtils configDefaultConnectTimeout(int connectTimeout) { globalConfig.setDefaultConnectTimeout(connectTimeout); return this; } public BitmapUtils configDefaultReadTimeout(int readTimeout) { globalConfig.setDefaultReadTimeout(readTimeout); return this; } public BitmapUtils configThreadPoolSize(int threadPoolSize) { globalConfig.setThreadPoolSize(threadPoolSize); return this; } public BitmapUtils configMemoryCacheEnabled(boolean enabled) { globalConfig.setMemoryCacheEnabled(enabled); return this; } public BitmapUtils configDiskCacheEnabled(boolean enabled) { globalConfig.setDiskCacheEnabled(enabled); return this; } public BitmapUtils configDiskCacheFileNameGenerator(LruDiskCache.DiskCacheFileNameGenerator diskCacheFileNameGenerator) { globalConfig.setDiskCacheFileNameGenerator(diskCacheFileNameGenerator); return this; } public BitmapUtils configBitmapCacheListener(BitmapCacheListener listener) { globalConfig.setBitmapCacheListener(listener); return this; } public BitmapUtils configGlobalConfig(BitmapGlobalConfig globalConfig) { this.globalConfig = globalConfig; return this; } ////////////////////////// display //////////////////////////////////// public <T extends View> void display(T container, String uri) { display(container, uri, null, null); } public <T extends View> void display(T container, String uri, BitmapDisplayConfig displayConfig) { display(container, uri, displayConfig, null); } public <T extends View> void display(T container, String uri, BitmapLoadCallBack<T> callBack) { display(container, uri, null, callBack); } public <T extends View> void display(T container, String uri, BitmapDisplayConfig displayConfig, BitmapLoadCallBack<T> callBack) { if (container == null) { return; } container.clearAnimation(); if (callBack == null) { callBack = new DefaultBitmapLoadCallBack<T>(); } if (displayConfig == null || displayConfig == defaultDisplayConfig) { displayConfig = defaultDisplayConfig.cloneNew(); } // Optimize Max Size BitmapSize size = displayConfig.getBitmapMaxSize(); displayConfig.setBitmapMaxSize(BitmapCommonUtils.optimizeMaxSizeByView(container, size.getWidth(), size.getHeight())); callBack.onPreLoad(container, uri, displayConfig); if (TextUtils.isEmpty(uri)) { callBack.onLoadFailed(container, uri, displayConfig.getLoadFailedDrawable()); return; } Bitmap bitmap = globalConfig.getBitmapCache().getBitmapFromMemCache(uri, displayConfig); if (bitmap != null) { callBack.onLoadStarted(container, uri, displayConfig); callBack.onLoadCompleted( container, uri, bitmap, displayConfig, BitmapLoadFrom.MEMORY_CACHE); } else if (!bitmapLoadTaskExist(container, uri, callBack)) { final BitmapLoadTask<T> loadTask = new BitmapLoadTask<T>(container, uri, displayConfig, callBack); // set loading image final AsyncDrawable<T> asyncDrawable = new AsyncDrawable<T>( displayConfig.getLoadingDrawable(), loadTask); callBack.setDrawable(container, asyncDrawable); // load bitmap from uri or diskCache loadTask.executeOnExecutor(globalConfig.getBitmapLoadExecutor()); } } /////////////////////////////////////////////// cache ///////////////////////////////////////////////////////////////// /** * @author 方达 * 同时清除内存 和硬盘中的cache */ public void clearCache() { globalConfig.clearCache(); } public void clearMemoryCache() { globalConfig.clearMemoryCache(); } public void clearDiskCache() { globalConfig.clearDiskCache(); } /** * @author 方达 * 同时清除内存 和硬盘中的cache */ public void clearCache(String uri) { globalConfig.clearCache(uri); } public void clearMemoryCache(String uri) { globalConfig.clearMemoryCache(uri); } public void clearDiskCache(String uri) { globalConfig.clearDiskCache(uri); } public void flushCache() { globalConfig.flushCache(); } public void closeCache() { globalConfig.closeCache(); } public File getBitmapFileFromDiskCache(String uri) { return globalConfig.getBitmapCache().getBitmapFileFromDiskCache(uri); } public Bitmap getBitmapFromMemCache(String uri, BitmapDisplayConfig config) { if (config == null) { config = defaultDisplayConfig; } return globalConfig.getBitmapCache().getBitmapFromMemCache(uri, config); } ////////////////////////////////////////// tasks ////////////////////////////////////////////////////////////////////// public void resumeTasks() { pauseTask = false; synchronized (pauseTaskLock) { pauseTaskLock.notifyAll(); } } public void pauseTasks() { pauseTask = true; flushCache(); } public void stopTasks() { pauseTask = true; synchronized (pauseTaskLock) { pauseTaskLock.notifyAll(); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// @SuppressWarnings("unchecked") private static <T extends View> BitmapLoadTask<T> getBitmapTaskFromContainer(T container, BitmapLoadCallBack<T> callBack) { if (container != null) { final Drawable drawable = callBack.getDrawable(container); if (drawable instanceof AsyncDrawable) { final AsyncDrawable<T> asyncDrawable = (AsyncDrawable<T>) drawable; return asyncDrawable.getBitmapWorkerTask(); } } return null; } private static <T extends View> boolean bitmapLoadTaskExist(T container, String uri, BitmapLoadCallBack<T> callBack) { final BitmapLoadTask<T> oldLoadTask = getBitmapTaskFromContainer(container, callBack); if (oldLoadTask != null) { final String oldUrl = oldLoadTask.uri; if (TextUtils.isEmpty(oldUrl) || !oldUrl.equals(uri)) { oldLoadTask.cancel(true); } else { return true; } } return false; } public class BitmapLoadTask<T extends View> extends CompatibleAsyncTask<Object, Object, Bitmap> { private final String uri; private final WeakReference<T> containerReference; private final BitmapLoadCallBack<T> callBack; private final BitmapDisplayConfig displayConfig; private BitmapLoadFrom from = BitmapLoadFrom.DISK_CACHE; public BitmapLoadTask(T container, String uri, BitmapDisplayConfig config, BitmapLoadCallBack<T> callBack) { if (container == null || uri == null || config == null || callBack == null) { throw new IllegalArgumentException("args may not be null"); } this.containerReference = new WeakReference<T>(container); this.callBack = callBack; this.uri = uri; this.displayConfig = config; } @Override protected Bitmap doInBackground(Object... params) { synchronized (pauseTaskLock) { while (pauseTask && !this.isCancelled()) { try { pauseTaskLock.wait(); } catch (Throwable e) { } } } Bitmap bitmap = null; // get cache from disk cache if (!this.isCancelled() && this.getTargetContainer() != null) { this.publishProgress(PROGRESS_LOAD_STARTED); bitmap = globalConfig.getBitmapCache().getBitmapFromDiskCache(uri, displayConfig); } // download image if (bitmap == null && !this.isCancelled() && this.getTargetContainer() != null) { bitmap = globalConfig.getBitmapCache().downloadBitmap(uri, displayConfig, this); from = BitmapLoadFrom.URI; } return bitmap; } public void updateProgress(long total, long current) { this.publishProgress(PROGRESS_LOADING, total, current); } private static final int PROGRESS_LOAD_STARTED = 0; private static final int PROGRESS_LOADING = 1; @Override protected void onProgressUpdate(Object... values) { if (values == null || values.length == 0) return; final T container = this.getTargetContainer(); if (container == null) return; switch ((Integer) values[0]) { case PROGRESS_LOAD_STARTED: callBack.onLoadStarted(container, uri, displayConfig); break; case PROGRESS_LOADING: if (values.length != 3) return; callBack.onLoading(container, uri, displayConfig, (Long) values[1], (Long) values[2]); break; default: break; } } @Override protected void onPostExecute(Bitmap bitmap) { final T container = this.getTargetContainer(); if (container != null) { if (bitmap != null) { callBack.onLoadCompleted( container, this.uri, bitmap, displayConfig, from); } else { callBack.onLoadFailed( container, this.uri, displayConfig.getLoadFailedDrawable()); } } } @Override protected void onCancelled(Bitmap bitmap) { synchronized (pauseTaskLock) { pauseTaskLock.notifyAll(); } } public T getTargetContainer() { final T container = containerReference.get(); final BitmapLoadTask<T> bitmapWorkerTask = getBitmapTaskFromContainer(container, callBack); if (this == bitmapWorkerTask) { return container; } return null; } } }
[ "931368239@qq.com" ]
931368239@qq.com
5287926e673a3586735d35774be225887b33771c
70a178cbfdb19387344c574ff5c58d75343a5179
/refund/src/test/java/com/chl/refund/RefundApplicationTests.java
402bf552a874d274e3c94519e25722a188709352
[ "Apache-2.0" ]
permissive
lirenweigui713/nb-pay
325dc45ed267e71867e7d3c800b69ee6a8523c74
ad423977b8cc43bb2df0485f43de63ed8996266d
refs/heads/master
2022-07-18T11:04:31.515891
2021-03-01T14:19:10
2021-03-01T14:19:10
246,987,249
1
1
Apache-2.0
2020-10-13T20:49:39
2020-03-13T04:21:13
Java
UTF-8
Java
false
false
215
java
package com.chl.refund; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class RefundApplicationTests { @Test void contextLoads() { } }
[ "lirenweigui713@163.com" ]
lirenweigui713@163.com
8e9d882e67e104547e03f5d98e461c4bb2bdaf16
30c099f779327f181ba21cc8feb0e1b2518e5d56
/delta/src/main/java/io/github/ms/cloudappwatch/DeltaApp.java
ddceae2ea47695011f4d3e0774c4e266440588e1
[ "MIT" ]
permissive
mstane/cloud-app-watch
582598f9c863134f5456ad3d8eff1b743319048b
1f591646f62d5d52fa3a6a829bc85371a59e664e
refs/heads/develop
2022-12-21T01:50:19.455382
2019-10-05T14:18:54
2019-10-05T14:18:54
184,435,949
0
1
MIT
2022-12-16T05:05:59
2019-05-01T15:18:50
Java
UTF-8
Java
false
false
4,453
java
package io.github.ms.cloudappwatch; import io.github.ms.cloudappwatch.config.ApplicationProperties; import io.github.ms.cloudappwatch.config.DefaultProfileUtil; import io.github.jhipster.config.JHipsterConstants; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.core.env.Environment; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Collection; @SpringBootApplication @EnableConfigurationProperties({ApplicationProperties.class}) @EnableDiscoveryClient public class DeltaApp implements InitializingBean { private static final Logger log = LoggerFactory.getLogger(DeltaApp.class); private final Environment env; public DeltaApp(Environment env) { this.env = env; } /** * Initializes delta. * <p> * Spring profiles can be configured with a program argument --spring.profiles.active=your-active-profile * <p> * You can find more information on how profiles work with JHipster on <a href="https://www.jhipster.tech/profiles/">https://www.jhipster.tech/profiles/</a>. */ @Override public void afterPropertiesSet() throws Exception { Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles()); if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) { log.error("You have misconfigured your application! It should not run " + "with both the 'dev' and 'prod' profiles at the same time."); } if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD)) { log.error("You have misconfigured your application! It should not " + "run with both the 'dev' and 'cloud' profiles at the same time."); } } /** * Main method, used to run the application. * * @param args the command line arguments. */ public static void main(String[] args) { SpringApplication app = new SpringApplication(DeltaApp.class); DefaultProfileUtil.addDefaultProfile(app); Environment env = app.run(args).getEnvironment(); logApplicationStartup(env); } private static void logApplicationStartup(Environment env) { String protocol = "http"; if (env.getProperty("server.ssl.key-store") != null) { protocol = "https"; } String serverPort = env.getProperty("server.port"); String contextPath = env.getProperty("server.servlet.context-path"); if (StringUtils.isBlank(contextPath)) { contextPath = "/"; } String hostAddress = "localhost"; try { hostAddress = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { log.warn("The host name could not be determined, using `localhost` as fallback"); } log.info("\n----------------------------------------------------------\n\t" + "Application '{}' is running! Access URLs:\n\t" + "Local: \t\t{}://localhost:{}{}\n\t" + "External: \t{}://{}:{}{}\n\t" + "Profile(s): \t{}\n----------------------------------------------------------", env.getProperty("spring.application.name"), protocol, serverPort, contextPath, protocol, hostAddress, serverPort, contextPath, env.getActiveProfiles()); String configServerStatus = env.getProperty("configserver.status"); if (configServerStatus == null) { configServerStatus = "Not found or not setup for this application"; } log.info("\n----------------------------------------------------------\n\t" + "Config Server: \t{}\n----------------------------------------------------------", configServerStatus); } }
[ "mstane@gmail.com" ]
mstane@gmail.com
cce2756acb5338803ee487211ceda8eb4d278f27
b878386c941632b3c0862e40bf6072b95913ae85
/src/main/java/com/epam/esm/task1/controller/rest/NewsAuthorController.java
5109a062113c901b5bbe9e78a540939ffdc439c6
[]
no_license
Vault1996/news
459de4fcfed6cf826b61ab1a7f87004e9b9abf93
7d335045261ec6c72479a089eba635516223a20a
refs/heads/master
2021-01-22T04:05:04.889478
2017-05-25T17:39:50
2017-05-25T17:39:50
92,428,346
0
0
null
null
null
null
UTF-8
Java
false
false
3,803
java
package com.epam.esm.task1.controller.rest; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; import com.epam.esm.task1.dto.NewsAuthorDTO; import com.epam.esm.task1.exception.ValidationException; import com.epam.esm.task1.service.NewsAuthorService; /** * Rest Service to perform operations with NewsAuthor resource * * @author Algis_Ivashkiavichus * */ @CrossOrigin @RestController @RequestMapping("/authors") public class NewsAuthorController { private static final String ID = "/{id:[\\d]+}"; private static final String AUTHORS_PATH = "/authors/{id}"; @Autowired private NewsAuthorService newsAuthorService; /** * Method to find all authors in the system * * @return List of all authors */ @GetMapping public List<NewsAuthorDTO> findAll() { return newsAuthorService.findAll(); } /** * Method to find NewsAuthor by id * * @param id * id of NewsAuthor to find * @return found NewsAuthor or null otherwise */ @GetMapping(ID) public NewsAuthorDTO findById(@PathVariable Long id) { return newsAuthorService.findById(id); } /** * Method to save NewsAuthor in the system * * @param newsAuthor * entity to save * @return Response entity with CREATED http status code and location header */ @PostMapping public ResponseEntity<Void> save(@Valid @RequestBody NewsAuthorDTO newsAuthor, UriComponentsBuilder b) { NewsAuthorDTO newsAuthorDTO = newsAuthorService.save(newsAuthor); UriComponents uriComponents = b.path(AUTHORS_PATH).buildAndExpand(newsAuthorDTO.getId()); HttpHeaders headers = new HttpHeaders(); headers.setLocation(uriComponents.toUri()); return new ResponseEntity<>(headers, HttpStatus.CREATED); } /** * Method to edit NewsAuthor in the system. Param id and param newsAuthor.id * should be the same * * @param id * id of NewsAuthor to edit * @param newsAuthor * NewsAuthor entity to update * @return Response entity with CREATED http status code and location header */ @PutMapping(ID) public ResponseEntity<Void> edit(@PathVariable Long id, @Valid @RequestBody NewsAuthorDTO newsAuthor, UriComponentsBuilder b) { if (!id.equals(newsAuthor.getId())) { throw new ValidationException("Id in path and in request body should be the same"); } NewsAuthorDTO newsAuthorDTO = newsAuthorService.update(newsAuthor); UriComponents uriComponents = b.path(AUTHORS_PATH).buildAndExpand(newsAuthorDTO.getId()); HttpHeaders headers = new HttpHeaders(); headers.setLocation(uriComponents.toUri()); return new ResponseEntity<>(headers, HttpStatus.OK); } /** * Method to delete NewsAuthor from the system * * @param id * id of NewsAuthor to delete */ @DeleteMapping(ID) @ResponseStatus(code = HttpStatus.NO_CONTENT) public void delete(@PathVariable Long id) { newsAuthorService.delete(id); } }
[ "Algis_Ivashkiavichus@epam.com" ]
Algis_Ivashkiavichus@epam.com
91730ad0b775b01f9227c0783896a4a40640f1e2
a0e6d28dcaca504c4b80fa5fb192d7fb627ccafc
/libgdx/core/src/com/eje/fallapart/services/Inputs.java
9acf1a3890cdde9a2cc04ca27f5cc04c05c9b44b
[]
no_license
edgaruriel/optVideoGame
545ce5047ecb4ed2cade49a905963c2edec56db4
dc2a22ed8fa1d18de239235125c3ba77296cbed7
refs/heads/master
2020-05-02T05:30:14.746262
2014-12-09T21:09:54
2014-12-09T21:09:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
913
java
package com.eje.fallapart.services; public class Inputs { public static int x; public static int y; public static boolean down; public static boolean pdown; public static boolean[] keys; public static boolean[] pkeys; private static final int NUM_KEYS = 2; public static final int BUTTON1 = 0; public static final int BUTTON2 = 1; static { keys = new boolean[NUM_KEYS]; pkeys = new boolean[NUM_KEYS]; } public static void update() { pdown = down; for(int i = 0; i < NUM_KEYS; i++) { pkeys[i] = keys[i]; } } public static boolean isDown() { return down; } public static boolean isPressed() { return down && !pdown; } public static boolean isReleased() { return !down && pdown; } public static void setKey(int i, boolean b) { keys[i] = b; } public static boolean isDown(int i) { return keys[i]; } public static boolean isPressed(int i) { return keys[i] && !pkeys[i]; } }
[ "eddieparedes11@gmail.com" ]
eddieparedes11@gmail.com
183ac30c74f65c68484188654b3a8ce6221fa082
68dfea5aed37113ab715db1dfd6a6d03328ba39e
/openglmodule/src/main/java/com/chenli/openglmodule/triangle/TriangleRender.java
8c3f0507b27f2e8154275e990f03a195bd4d3622
[]
no_license
chenliabc/AndroidDemo
02da79b20d5aa16bd208a77990c8b0a49579e713
64e72bbce2a8c743a9afcdb44372b887393cf654
refs/heads/master
2020-03-14T22:24:40.718830
2018-05-02T08:18:19
2018-05-02T08:18:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,262
java
package com.chenli.openglmodule.triangle; import android.content.Context; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.opengl.Matrix; import com.chenli.commonlib.util.gameutil.ShaderUtils; import com.chenli.openglmodule.R; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; /** * Created by Lenovo on 2018/5/1. */ public class TriangleRender implements GLSurfaceView.Renderer { private Context context; private float[] vMatrix = new float[16]; private float[] mProjectMatrix=new float[16]; private float[] mViewMatrix=new float[16]; private float[] triangleCoords = { 0.5f,0.5f,0.0f, -0.5f,-0.5f,0.0f, 0.5f,-0.5f,0.0f }; //设置颜色 float color[] = { 0.0f, 1.0f, 0.0f, 1.0f , 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f }; private final FloatBuffer floatBuffer; private final FloatBuffer floatColor; private int vColor; private int matrixHandler; public TriangleRender(Context context){ this.context = context; floatBuffer = ByteBuffer.allocateDirect(triangleCoords.length * 4) .order(ByteOrder.nativeOrder()) .asFloatBuffer(); floatBuffer.put(triangleCoords); floatBuffer.position(0); floatColor = ByteBuffer.allocateDirect(color.length * 4) .order(ByteOrder.nativeOrder()) .asFloatBuffer(); floatColor.put(color); floatColor.position(0); } @Override public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) { GLES20.glClearColor(0.5f,0.5f,0.5f,1.0f); String fragmentShader = ShaderUtils.readTextFileFromResource(context, R.raw.triangle_fragment_shander); String vertexShader = ShaderUtils.readTextFileFromResource(context, R.raw.triangle_vertex_shander); int program = ShaderUtils.buildProgram(vertexShader, fragmentShader); GLES20.glUseProgram(program); matrixHandler = GLES20.glGetUniformLocation(program, "vMatrix"); vColor = GLES20.glGetAttribLocation(program, "vColor"); GLES20.glVertexAttribPointer(vColor,3,GLES20.GL_FLOAT,false,0,floatColor); GLES20.glEnableVertexAttribArray(vColor); int vPosition = GLES20.glGetAttribLocation(program, "vPosition"); GLES20.glVertexAttribPointer(vPosition,3,GLES20.GL_FLOAT,false,0,floatBuffer); GLES20.glEnableVertexAttribArray(vPosition); } @Override public void onSurfaceChanged(GL10 gl10, int i, int i1) { GLES20.glViewport(0,0,i,i1); float ratio = i*1.0f/i1; Matrix.perspectiveM(mProjectMatrix,0,45,ratio,-ratio,ratio); Matrix.setLookAtM(mViewMatrix, 0, 0, 0, 7.0f, 0f, 0f, 0f, 0f, 1.0f, 0.0f); Matrix.multiplyMM(vMatrix,0,mProjectMatrix,0,mViewMatrix,0); } @Override public void onDrawFrame(GL10 gl10) { GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); GLES20.glUniformMatrix4fv(matrixHandler,1,false,vMatrix,0); GLES20.glDrawArrays(GLES20.GL_TRIANGLES,0,3); } }
[ "cl1210243907@163.com" ]
cl1210243907@163.com
e32d3fa82e7d8b007c74b1bb55073301f3e1d100
0f92ff625c5d5831a89bc8c5fd33c3733dcea6f1
/src/main/java/Storage.java
0a4b012c0135411be8fb842c89b88283198e6c22
[]
no_license
grrrrnt/duke
367977477734da514ff6c0b4a9f75a5e6e330598
c9c1f5cffd52dee13db41798198cdbf5fbe6b652
refs/heads/master
2020-12-19T13:09:50.333460
2020-02-29T22:14:29
2020-02-29T22:14:29
235,742,634
0
0
null
2020-02-20T15:28:08
2020-01-23T07:12:58
Java
UTF-8
Java
false
false
3,041
java
import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Represents a collection of methods to read and write files in the data folder. * A <code>Storage</code> object corresponds to a file path represented as a String * and a <code>File</code> object that accesses the file at the path. */ public class Storage { private String filePath; private File f; public Storage(String filePath) { this.filePath = filePath; f = new File(filePath); } /** * Retrieves and returns list of tasks from data folder. * * @return List of tasks. * @throws FileNotFoundException If storage file cannot be found in data folder. */ public List<Task> getList() throws FileNotFoundException { List<Task> list = new ArrayList<>(); Scanner sc = new Scanner(f); while (sc.hasNext()) { String str = sc.nextLine(); String[] elements = str.split(" \\| "); Task t = new Task(); switch (elements[0]) { case "T": if (elements.length > 3) { t = new TodoWithinPeriod(elements[2], elements[3], elements[4]); } else { t = new Todo(elements[2]); } break; case "E": t = new Event(elements[2], elements[3]); break; case "D": t = new Deadline(elements[2], elements[3]); } if (Integer.parseInt(elements[1]) == 1) t.markAsDone(); list.add(t); } return list; } /** * Updates storage file in storage folder with list of tasks. * * @param list List of tasks. * @throws IOException If there is an error with writing to storage file. */ public void writeTaskList(List<Task> list) throws IOException { FileWriter fw = new FileWriter(filePath); for (Task t : list) fw.write(taskToString(t)); fw.close(); } private static String taskToString(Task t) { String str = ""; int done = t.getIsDone() ? 1 : 0; if (t instanceof TodoWithinPeriod) str = "T | " + done + " | " + t.getDescription() + " | " + Parser.formatTime(((TodoWithinPeriod) t).getBetweenDate()) + " | " + Parser.formatTime(((TodoWithinPeriod) t).getAndDate()); if (t instanceof Todo) str = "T | " + done + " | " + t.getDescription(); if (t instanceof Event) str = "E | " + done + " | " + t.getDescription() + " | " + Parser.formatTime(((Event) t).getDayTime()); if (t instanceof Deadline) str = "D | " + done + " | " + t.getDescription() + " | " + Parser.formatTime(((Deadline) t).getDayTime()); assert ! str.equals("") : "String has information"; return str + "\n"; } }
[ "grantlee97@gmail.com" ]
grantlee97@gmail.com
006c8f4d7c3094c5abffbcba9aa3f07f3a2c1504
35d69980e7ee5c5a0c9266840e42302cd229521e
/scaffold/src/main/java/net/granoeste/scaffold/lifecyclecallbacks/LifecycleCallbacksSupportFragmentActivity.java
f9eca4a6b259a8a692b1e634532a0bff69423514
[]
no_license
granoeste/net.granoeste.libs
6e77d49e641bc2ac464f72090f24204d29f00a15
607c84582b76411326cacf4921ad339ad1a9cb9a
refs/heads/master
2021-01-10T10:55:13.127681
2016-01-04T07:26:05
2016-01-04T07:26:05
48,981,649
0
0
null
null
null
null
UTF-8
Java
false
false
5,471
java
/* * Copyright (C) 2012 uPhyca Inc. http://www.uphyca.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 net.granoeste.scaffold.lifecyclecallbacks; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; public abstract class LifecycleCallbacksSupportFragmentActivity extends FragmentActivity { private LifecycleCallbacksSupportApplication getApplicationCompat() { return LifecycleCallbacksSupportApplication.applicationOf(this); } @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(newBase); dispatchAttachBaseContext(getApplicationCompat(), this, newBase); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); dispatchCreate(getApplicationCompat(), this, savedInstanceState); } @Override protected void onStart() { super.onStart(); dispatchStart(getApplicationCompat(), this); } @Override protected void onResume() { super.onResume(); dispatchResume(getApplicationCompat(), this); } @Override protected void onPause() { super.onPause(); dispatchPause(getApplicationCompat(), this); } @Override protected void onStop() { super.onStop(); dispatchStop(getApplicationCompat(), this); } @Override protected void onDestroy() { super.onDestroy(); dispatchDestroy(getApplicationCompat(), this); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); dispatchSavedInstanceState(getApplicationCompat(), this, outState); } @Override public void onAttachFragment(Fragment fragment) { super.onAttachFragment(fragment); dispatchAttachFragment(getApplicationCompat(), this, fragment); } private static void dispatchAttachBaseContext(LifecycleCallbacksSupportApplication application, Activity activity, Context newBase) { if (application == null) { return; } application.dispatchActivityAttachBaseContextCompat(activity, newBase); } private static void dispatchCreate(LifecycleCallbacksSupportApplication application, Activity activity, Bundle savedInstanceState) { if (application == null) { return; } application.dispatchActivityCreatedCompat(activity, savedInstanceState); } private static void dispatchStart(LifecycleCallbacksSupportApplication application, Activity activity) { if (application == null) { return; } application.dispatchActivityStartedCompat(activity); } private static void dispatchResume(LifecycleCallbacksSupportApplication application, Activity activity) { if (application == null) { return; } application.dispatchActivityResumedCompat(activity); } private static void dispatchPause(LifecycleCallbacksSupportApplication application, Activity activity) { if (application == null) { return; } application.dispatchActivityPausedCompat(activity); } private static void dispatchStop(LifecycleCallbacksSupportApplication application, Activity activity) { if (application == null) { return; } application.dispatchActivityStoppedCompat(activity); } private static void dispatchDestroy(LifecycleCallbacksSupportApplication application, Activity activity) { if (application == null) { return; } application.dispatchActivityDestroyedCompat(activity); } private static void dispatchSavedInstanceState(LifecycleCallbacksSupportApplication application, Activity activity, Bundle outState) { if (application == null) { return; } application.dispatchActivitySaveInstanceStateCompat(activity, outState); } private static void dispatchAttachFragment(LifecycleCallbacksSupportApplication application, Activity activity, Fragment fragment) { if (application == null) { return; } application.dispatchActivityAttachFragmentCompat(activity, fragment); } }
[ "granoeste@gmail.com" ]
granoeste@gmail.com
86a834d05f6f45c056451bb0c3495792157e4c22
869ce0e483369afac3e853ad1193ce973eb37929
/src/main/java/com/karakays/leetcode/solutions/S8.java
2dad1124ef14194e81856d69138c0a1636f69b5e
[]
no_license
karakays/leetcode
9d337c61bb82b6e4f122811c4ed337242eeae906
00767d565f363f3c3ce943e09a5f7459f65af2d3
refs/heads/master
2023-01-24T15:26:14.137490
2020-11-16T17:54:24
2020-11-16T17:54:24
309,086,514
0
0
null
null
null
null
UTF-8
Java
false
false
1,396
java
package com.karakays.leetcode.solutions; public class S8 { public int myAtoi(String s) { int i = 0; while(i < s.length() && ' ' == (s.charAt(i))) i++; s = s.substring(i); i = 0; int sign = 1; if(i < s.length() && s.charAt(i) == '-') { i++; sign = -1; } else if(i < s.length() && s.charAt(i) == '+') { i++; } s = s.substring(i); i = 0; while(i < s.length() && Character.isDigit(s.charAt(i))) i++; if(i == 0) { // not a number return 0; } s = s.substring(0, i); int n = s.length(); int t = 0; i = sign * (s.charAt(t++) - 48); while(t < n) { if(i > Integer.MAX_VALUE / 10) { return Integer.MAX_VALUE; } else if(i < Integer.MIN_VALUE / 10) { return Integer.MIN_VALUE; } else { i *= 10; int digit = s.charAt(t++) - 48; if((i == (Integer.MAX_VALUE - 7)) && digit > 7) { return Integer.MAX_VALUE; } else if((i == (Integer.MIN_VALUE + 8)) && digit > 8) { return Integer.MIN_VALUE; } else { i = i + (sign * digit); } } } return i; } }
[ "skarakayali@gmail.com" ]
skarakayali@gmail.com
a436f65eef36a4a39fbf2e35cb4dda5f3cfbfec6
28f1dedfa55de3381f0e2124c7c819f582767e2a
/core/components/dependencies/src/org/smartfrog/services/dependencies/threadpool/ThreadPoolTester.java
f596ce5b5bc63bdfa41ae56f1685317b66531f4a
[]
no_license
rhusar/smartfrog
3bd0032888c03a8a04036945c2d857f72a89dba6
0b4db766fb1ec1e1c2e48cbf5f7bf6bfd2df4e89
refs/heads/master
2021-01-10T05:07:39.218946
2014-11-28T08:52:32
2014-11-28T08:52:32
47,347,494
0
1
null
null
null
null
UTF-8
Java
false
false
2,630
java
/** (C) Copyright 1998-2009 Hewlett-Packard Development Company, LP This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA For more information: www.smartfrog.org */ package org.smartfrog.services.dependencies.threadpool; import org.smartfrog.sfcore.common.SmartFrogException; import org.smartfrog.sfcore.prim.PrimImpl; import org.smartfrog.sfcore.prim.Prim; import org.smartfrog.sfcore.prim.TerminationRecord; import java.rmi.RemoteException; /** * Created by IntelliJ IDEA. * User: pcg * Date: 23-Nov-2005 * Time: 14:50:40 * To change this template use File | Settings | File Templates. */ public class ThreadPoolTester extends PrimImpl implements Prim, Runnable { public ThreadPoolTester() throws RemoteException { } ThreadPool tp; Thread t; int count = 0; private class Job implements Runnable { int i; public Job(int i){ this.i = i; } public void run() { System.out.println("job " + i + " running"); try{ Thread.sleep(2000); } catch (Exception e){ } System.out.println("job " + i + " done"); } } public void sfDeploy() throws RemoteException, SmartFrogException { super.sfDeploy(); tp = (ThreadPool) sfResolve("threadPool"); } public void sfStart() throws RemoteException, SmartFrogException { super.sfStart(); t = new Thread(this); t.start(); } public void sfTerminateWith(TerminationRecord tr) { count = 1000; t.interrupt(); } public void run() { try { int i = 0; while (i++ < 10) { int j = 0; while (j++ < 30) { Thread.sleep(100); tp.addToQueue(new Job(count++)); } Thread.sleep(10000); } } catch (InterruptedException e) { // done } } }
[ "anfarr@9868f95a-be1e-0410-b3e3-a02e98b909e6" ]
anfarr@9868f95a-be1e-0410-b3e3-a02e98b909e6
3cb7495bdb7f5d139dc8090fc9fc04a48d52e925
5598faaaaa6b3d1d8502cbdaca903f9037d99600
/code_changes/Apache_projects/HDFS-40/64d4c056fa958c0540608d25fd24d802af2c14dd/~FSNamesystem.java
e7b67bbbb874db880cad77dae58abd78f170960f
[]
no_license
SPEAR-SE/LogInBugReportsEmpirical_Data
94d1178346b4624ebe90cf515702fac86f8e2672
ab9603c66899b48b0b86bdf63ae7f7a604212b29
refs/heads/master
2022-12-18T02:07:18.084659
2020-09-09T16:49:34
2020-09-09T16:49:34
286,338,252
0
2
null
null
null
null
UTF-8
Java
false
false
228,478
java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.namenode; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_PERSIST_BLOCKS_DEFAULT; import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_PERSIST_BLOCKS_KEY; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.EnumSet; import java.util.Formatter; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.Random; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import javax.management.StandardMBean; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.ContentSummary; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsAction; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.fs.permission.PermissionStatus; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.DFSUtil; import org.apache.hadoop.hdfs.protocol.AlreadyBeingCreatedException; import org.apache.hadoop.hdfs.protocol.Block; import org.apache.hadoop.hdfs.protocol.BlockListAsLongs; import org.apache.hadoop.hdfs.protocol.ClientProtocol; import org.apache.hadoop.hdfs.protocol.DatanodeID; import org.apache.hadoop.hdfs.protocol.DatanodeInfo; import org.apache.hadoop.hdfs.protocol.DirectoryListing; import org.apache.hadoop.hdfs.protocol.FSConstants; import org.apache.hadoop.hdfs.protocol.HdfsFileStatus; import org.apache.hadoop.hdfs.protocol.LocatedBlock; import org.apache.hadoop.hdfs.protocol.LocatedBlocks; import org.apache.hadoop.hdfs.protocol.UnregisteredDatanodeException; import org.apache.hadoop.hdfs.security.token.block.BlockTokenSecretManager; import org.apache.hadoop.hdfs.security.token.block.ExportedBlockKeys; import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier; import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenSecretManager; import org.apache.hadoop.hdfs.server.common.GenerationStamp; import org.apache.hadoop.hdfs.server.common.HdfsConstants; import org.apache.hadoop.hdfs.server.common.HdfsConstants.StartupOption; import org.apache.hadoop.hdfs.server.common.Storage.StorageDirType; import org.apache.hadoop.hdfs.server.common.Storage.StorageDirectory; import org.apache.hadoop.hdfs.server.common.Storage; import org.apache.hadoop.hdfs.server.common.UpgradeStatusReport; import org.apache.hadoop.hdfs.server.namenode.BlocksMap.BlockInfo; import org.apache.hadoop.hdfs.server.namenode.LeaseManager.Lease; import org.apache.hadoop.hdfs.server.namenode.UnderReplicatedBlocks.BlockIterator; import org.apache.hadoop.hdfs.server.namenode.metrics.FSNamesystemMBean; import org.apache.hadoop.hdfs.server.protocol.BlocksWithLocations; import org.apache.hadoop.hdfs.server.protocol.DatanodeCommand; import org.apache.hadoop.hdfs.server.protocol.DatanodeRegistration; import org.apache.hadoop.hdfs.server.protocol.DisallowedDatanodeException; import org.apache.hadoop.hdfs.server.protocol.KeyUpdateCommand; import org.apache.hadoop.hdfs.server.protocol.NamespaceInfo; import org.apache.hadoop.hdfs.server.protocol.UpgradeCommand; import org.apache.hadoop.hdfs.server.protocol.BlocksWithLocations.BlockWithLocations; import org.apache.hadoop.hdfs.server.protocol.BalancerBandwidthCommand; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.io.Text; import org.apache.hadoop.ipc.Server; import org.apache.hadoop.fs.FileAlreadyExistsException; import org.apache.hadoop.metrics2.MetricsBuilder; import org.apache.hadoop.metrics2.MetricsSource; import org.apache.hadoop.metrics2.MetricsSystem; import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; import org.apache.hadoop.metrics2.util.MBeans; import org.apache.hadoop.net.CachedDNSToSwitchMapping; import org.apache.hadoop.net.DNSToSwitchMapping; import org.apache.hadoop.net.NetworkTopology; import org.apache.hadoop.net.Node; import org.apache.hadoop.net.NodeBase; import org.apache.hadoop.net.ScriptBasedMapping; import org.apache.hadoop.security.AccessControlException; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.security.token.SecretManager.InvalidToken; import org.apache.hadoop.security.token.delegation.DelegationKey; import org.apache.hadoop.util.Daemon; import org.apache.hadoop.util.HostsFileReader; import org.apache.hadoop.util.QueueProcessingStatistics; import org.apache.hadoop.util.ReflectionUtils; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.util.VersionInfo; import org.mortbay.util.ajax.JSON; /*************************************************** * FSNamesystem does the actual bookkeeping work for the * DataNode. * * It tracks several important tables. * * 1) valid fsname --> blocklist (kept on disk, logged) * 2) Set of all valid blocks (inverted #1) * 3) block --> machinelist (kept in memory, rebuilt dynamically from reports) * 4) machine --> blocklist (inverted #2) * 5) LRU cache of updated-heartbeat machines ***************************************************/ public class FSNamesystem implements FSConstants, FSNamesystemMBean, FSClusterStats, NameNodeMXBean, MetricsSource { public static final Log LOG = LogFactory.getLog(FSNamesystem.class); public static final String AUDIT_FORMAT = "ugi=%s\t" + // ugi "ip=%s\t" + // remote IP "cmd=%s\t" + // command "src=%s\t" + // src path "dst=%s\t" + // dst path (optional) "perm=%s"; // permissions (optional) private static final ThreadLocal<Formatter> auditFormatter = new ThreadLocal<Formatter>() { protected Formatter initialValue() { return new Formatter(new StringBuilder(AUDIT_FORMAT.length() * 4)); } }; private static final void logAuditEvent(UserGroupInformation ugi, InetAddress addr, String cmd, String src, String dst, HdfsFileStatus stat) { final Formatter fmt = auditFormatter.get(); ((StringBuilder)fmt.out()).setLength(0); auditLog.info(fmt.format(AUDIT_FORMAT, ugi, addr, cmd, src, dst, (stat == null) ? null : stat.getOwner() + ':' + stat.getGroup() + ':' + stat.getPermission() ).toString()); } public static final Log auditLog = LogFactory.getLog( FSNamesystem.class.getName() + ".audit"); // Default initial capacity and load factor of map public static final int DEFAULT_INITIAL_MAP_CAPACITY = 16; public static final float DEFAULT_MAP_LOAD_FACTOR = 0.75f; static int BLOCK_DELETION_INCREMENT = 1000; private float blocksInvalidateWorkPct; private int blocksReplWorkMultiplier; private boolean isPermissionEnabled; private boolean persistBlocks; private UserGroupInformation fsOwner; private String supergroup; private PermissionStatus defaultPermission; // FSNamesystemMetrics counter variables private long capacityTotal = 0L, capacityUsed = 0L, capacityRemaining = 0L; private int totalLoad = 0; boolean isAccessTokenEnabled; BlockTokenSecretManager accessTokenHandler; private long accessKeyUpdateInterval; private long accessTokenLifetime; // Scan interval is not configurable. private static final long DELEGATION_TOKEN_REMOVER_SCAN_INTERVAL = TimeUnit.MILLISECONDS.convert(1, TimeUnit.HOURS); private DelegationTokenSecretManager dtSecretManager; volatile long pendingReplicationBlocksCount = 0L; volatile long corruptReplicaBlocksCount = 0L; volatile long underReplicatedBlocksCount = 0L; volatile long scheduledReplicationBlocksCount = 0L; volatile long excessBlocksCount = 0L; volatile long pendingDeletionBlocksCount = 0L; // // Stores the correct file name hierarchy // public FSDirectory dir; // // Mapping: Block -> { INode, datanodes, self ref } // Updated only in response to client-sent information. // final BlocksMap blocksMap = new BlocksMap(DEFAULT_INITIAL_MAP_CAPACITY, DEFAULT_MAP_LOAD_FACTOR); // // Store blocks-->datanodedescriptor(s) map of corrupt replicas // public CorruptReplicasMap corruptReplicas = new CorruptReplicasMap(); /** * Stores the datanode -> block map. * <p> * Done by storing a set of {@link DatanodeDescriptor} objects, sorted by * storage id. In order to keep the storage map consistent it tracks * all storages ever registered with the namenode. * A descriptor corresponding to a specific storage id can be * <ul> * <li>added to the map if it is a new storage id;</li> * <li>updated with a new datanode started as a replacement for the old one * with the same storage id; and </li> * <li>removed if and only if an existing datanode is restarted to serve a * different storage id.</li> * </ul> <br> * The list of the {@link DatanodeDescriptor}s in the map is checkpointed * in the namespace image file. Only the {@link DatanodeInfo} part is * persistent, the list of blocks is restored from the datanode block * reports. * <p> * Mapping: StorageID -> DatanodeDescriptor */ NavigableMap<String, DatanodeDescriptor> datanodeMap = new TreeMap<String, DatanodeDescriptor>(); // // Keeps a Collection for every named machine containing // blocks that have recently been invalidated and are thought to live // on the machine in question. // Mapping: StorageID -> ArrayList<Block> // private Map<String, Collection<Block>> recentInvalidateSets = new TreeMap<String, Collection<Block>>(); // // Keeps a TreeSet for every named node. Each treeset contains // a list of the blocks that are "extra" at that location. We'll // eventually remove these extras. // Mapping: StorageID -> TreeSet<Block> // Map<String, Collection<Block>> excessReplicateMap = new TreeMap<String, Collection<Block>>(); Random r = new Random(); /** * Stores a set of DatanodeDescriptor objects. * This is a subset of {@link #datanodeMap}, containing nodes that are * considered alive. * The {@link HeartbeatMonitor} periodically checks for outdated entries, * and removes them from the list. */ ArrayList<DatanodeDescriptor> heartbeats = new ArrayList<DatanodeDescriptor>(); /** * Store set of Blocks that need to be replicated 1 or more times. * Set of: Block */ private UnderReplicatedBlocks neededReplications = new UnderReplicatedBlocks(); // We also store pending replication-orders. private PendingReplicationBlocks pendingReplications; public LeaseManager leaseManager = new LeaseManager(this); // // Threaded object that checks to see if we have been // getting heartbeats from all clients. // Daemon hbthread = null; // HeartbeatMonitor thread public Daemon lmthread = null; // LeaseMonitor thread Daemon smmthread = null; // SafeModeMonitor thread public Daemon replthread = null; // Replication thread private ReplicationMonitor replmon = null; // Replication metrics private volatile boolean fsRunning = true; long systemStart = 0; // The maximum number of replicates we should allow for a single block private int maxReplication; // How many outgoing replication streams a given node should have at one time private int maxReplicationStreams; // MIN_REPLICATION is how many copies we need in place or else we disallow the write private int minReplication; // Default replication private int defaultReplication; // Variable to stall new replication checks for testing purposes private volatile boolean stallReplicationWork = false; // heartbeatRecheckInterval is how often namenode checks for expired datanodes private long heartbeatRecheckInterval; // heartbeatExpireInterval is how long namenode waits for datanode to report // heartbeat private long heartbeatExpireInterval; //replicationRecheckInterval is how often namenode checks for new replication work private long replicationRecheckInterval; // default block size of a file private long defaultBlockSize = 0; // allow file appending (for test coverage) private boolean allowBrokenAppend = false; // enable durable sync private boolean durableSync = true; /** * Last block index used for replication work. */ private int replIndex = 0; private long missingBlocksInCurIter = 0; private long missingBlocksInPrevIter = 0; public static FSNamesystem fsNamesystemObject; /** NameNode RPC address */ private InetSocketAddress nameNodeAddress = null; // TODO: name-node has this field, it should be removed here private SafeModeInfo safeMode; // safe mode information private Host2NodesMap host2DataNodeMap = new Host2NodesMap(); // datanode networktoplogy NetworkTopology clusterMap = new NetworkTopology(); private DNSToSwitchMapping dnsToSwitchMapping; // for block replicas placement BlockPlacementPolicy replicator; private HostsFileReader hostsReader; private Daemon dnthread = null; private long maxFsObjects = 0; // maximum number of fs objects /** * The global generation stamp for this file system. */ private final GenerationStamp generationStamp = new GenerationStamp(); // Ask Datanode only up to this many blocks to delete. int blockInvalidateLimit = DFSConfigKeys.DFS_BLOCK_INVALIDATE_LIMIT_DEFAULT; // precision of access times. private long accessTimePrecision = 0; private String nameNodeHostName; /** Whether or not to check stale DataNodes for read/write */ private boolean checkForStaleDataNodes; /** The interval for judging stale DataNodes for read/write */ private long staleInterval; /** Whether or not to avoid using stale DataNodes for writing */ private volatile boolean avoidStaleDataNodesForWrite; private boolean initialAvoidWriteStaleNodes; /** The number of stale DataNodes */ private volatile int numStaleNodes; /** * When the ratio of stale datanodes reaches this number, stop avoiding * writing to stale datanodes, i.e., continue using stale nodes for writing. */ private float ratioUseStaleDataNodesForWrite; /** * FSNamesystem constructor. */ FSNamesystem(NameNode nn, Configuration conf) throws IOException { try { initialize(nn, conf); } catch (IOException e) { LOG.error(getClass().getSimpleName() + " initialization failed.", e); close(); shutdown(); throw e; } catch (RuntimeException e) { LOG.error(getClass().getSimpleName() + " initialization failed.", e); close(); shutdown(); throw e; } } void activateSecretManager() throws IOException { if (dtSecretManager != null) { dtSecretManager.startThreads(); } } /** * Initialize FSNamesystem. */ private void initialize(NameNode nn, Configuration conf) throws IOException { this.systemStart = now(); setConfigurationParameters(conf); dtSecretManager = createDelegationTokenSecretManager(conf); this.nameNodeAddress = nn.getNameNodeAddress(); this.registerMBean(conf); // register the MBean for the FSNamesystemStutus this.dir = new FSDirectory(this, conf); StartupOption startOpt = NameNode.getStartupOption(conf); this.dir.loadFSImage(getNamespaceDirs(conf), getNamespaceEditsDirs(conf), startOpt); long timeTakenToLoadFSImage = now() - systemStart; LOG.info("Finished loading FSImage in " + timeTakenToLoadFSImage + " msecs"); NameNode.getNameNodeMetrics().setFsImageLoadTime(timeTakenToLoadFSImage); this.safeMode = new SafeModeInfo(conf); setBlockTotal(); pendingReplications = new PendingReplicationBlocks( conf.getInt("dfs.replication.pending.timeout.sec", -1) * 1000L); if (isAccessTokenEnabled) { accessTokenHandler = new BlockTokenSecretManager(true, accessKeyUpdateInterval, accessTokenLifetime); } this.hbthread = new Daemon(new HeartbeatMonitor()); this.lmthread = new Daemon(leaseManager.new Monitor()); this.replmon = new ReplicationMonitor(); this.replthread = new Daemon(replmon); hbthread.start(); lmthread.start(); replthread.start(); this.hostsReader = new HostsFileReader(conf.get("dfs.hosts",""), conf.get("dfs.hosts.exclude","")); this.dnthread = new Daemon(new DecommissionManager(this).new Monitor( conf.getInt("dfs.namenode.decommission.interval", 30), conf.getInt("dfs.namenode.decommission.nodes.per.interval", 5))); dnthread.start(); this.dnsToSwitchMapping = ReflectionUtils.newInstance( conf.getClass("topology.node.switch.mapping.impl", ScriptBasedMapping.class, DNSToSwitchMapping.class), conf); /* If the dns to swith mapping supports cache, resolve network * locations of those hosts in the include list, * and store the mapping in the cache; so future calls to resolve * will be fast. */ if (dnsToSwitchMapping instanceof CachedDNSToSwitchMapping) { dnsToSwitchMapping.resolve(new ArrayList<String>(hostsReader.getHosts())); } InetSocketAddress socAddr = NameNode.getAddress(conf); this.nameNodeHostName = socAddr.getHostName(); registerWith(DefaultMetricsSystem.INSTANCE); } public static Collection<File> getNamespaceDirs(Configuration conf) { Collection<String> dirNames = conf.getStringCollection("dfs.name.dir"); if (dirNames.isEmpty()) dirNames.add("/tmp/hadoop/dfs/name"); Collection<File> dirs = new ArrayList<File>(dirNames.size()); for(String name : dirNames) { dirs.add(new File(name)); } return dirs; } public static Collection<File> getNamespaceEditsDirs(Configuration conf) { Collection<String> editsDirNames = conf.getStringCollection("dfs.name.edits.dir"); if (editsDirNames.isEmpty()) editsDirNames.add("/tmp/hadoop/dfs/name"); Collection<File> dirs = new ArrayList<File>(editsDirNames.size()); for(String name : editsDirNames) { dirs.add(new File(name)); } return dirs; } /** * dirs is a list of directories where the filesystem directory state * is stored */ FSNamesystem(FSImage fsImage, Configuration conf) throws IOException { setConfigurationParameters(conf); this.dir = new FSDirectory(fsImage, this, conf); dtSecretManager = createDelegationTokenSecretManager(conf); } /** * Initializes some of the members from configuration */ private void setConfigurationParameters(Configuration conf) throws IOException { fsNamesystemObject = this; fsOwner = UserGroupInformation.getCurrentUser(); LOG.info("fsOwner=" + fsOwner); this.supergroup = conf.get("dfs.permissions.supergroup", "supergroup"); this.isPermissionEnabled = conf.getBoolean("dfs.permissions", true); LOG.info("supergroup=" + supergroup); LOG.info("isPermissionEnabled=" + isPermissionEnabled); this.persistBlocks = conf.getBoolean(DFS_PERSIST_BLOCKS_KEY, DFS_PERSIST_BLOCKS_DEFAULT); short filePermission = (short)conf.getInt("dfs.upgrade.permission", 0777); this.defaultPermission = PermissionStatus.createImmutable( fsOwner.getShortUserName(), supergroup, new FsPermission(filePermission)); this.blocksInvalidateWorkPct = DFSUtil.getInvalidateWorkPctPerIteration(conf); this.blocksReplWorkMultiplier = DFSUtil.getReplWorkMultiplier(conf); this.replicator = BlockPlacementPolicy.getInstance(conf, this, clusterMap); this.defaultReplication = conf.getInt("dfs.replication", 3); this.maxReplication = conf.getInt("dfs.replication.max", 512); this.minReplication = conf.getInt("dfs.replication.min", 1); if (minReplication <= 0) throw new IOException( "Unexpected configuration parameters: dfs.replication.min = " + minReplication + " must be greater than 0"); if (maxReplication >= (int)Short.MAX_VALUE) throw new IOException( "Unexpected configuration parameters: dfs.replication.max = " + maxReplication + " must be less than " + (Short.MAX_VALUE)); if (maxReplication < minReplication) throw new IOException( "Unexpected configuration parameters: dfs.replication.min = " + minReplication + " must be less than dfs.replication.max = " + maxReplication); this.maxReplicationStreams = conf.getInt("dfs.max-repl-streams", 2); long heartbeatInterval = conf.getLong("dfs.heartbeat.interval", 3) * 1000; this.heartbeatRecheckInterval = conf.getInt( "heartbeat.recheck.interval", 5 * 60 * 1000); // 5 minutes this.heartbeatExpireInterval = 2 * heartbeatRecheckInterval + 10 * heartbeatInterval; this.replicationRecheckInterval = conf.getInt("dfs.replication.interval", 3) * 1000L; this.defaultBlockSize = conf.getLong("dfs.block.size", DEFAULT_BLOCK_SIZE); this.maxFsObjects = conf.getLong("dfs.max.objects", 0); //default limit this.blockInvalidateLimit = Math.max(this.blockInvalidateLimit, 20*(int)(heartbeatInterval/1000)); //use conf value if it is set. this.blockInvalidateLimit = conf.getInt( DFSConfigKeys.DFS_BLOCK_INVALIDATE_LIMIT_KEY, this.blockInvalidateLimit); LOG.info(DFSConfigKeys.DFS_BLOCK_INVALIDATE_LIMIT_KEY + "=" + this.blockInvalidateLimit); this.accessTimePrecision = conf.getLong("dfs.access.time.precision", 0); this.allowBrokenAppend = conf.getBoolean("dfs.support.broken.append", false); if (conf.getBoolean("dfs.support.append", false)) { LOG.warn("The dfs.support.append option is in your configuration, " + "however append is not supported. This configuration option " + "is no longer required to enable sync."); } this.durableSync = conf.getBoolean("dfs.durable.sync", true); if (!durableSync) { LOG.warn("Durable sync disabled. Beware data loss when running " + "programs like HBase that require durable sync!"); } this.isAccessTokenEnabled = conf.getBoolean( DFSConfigKeys.DFS_BLOCK_ACCESS_TOKEN_ENABLE_KEY, false); if (isAccessTokenEnabled) { this.accessKeyUpdateInterval = conf.getLong( DFSConfigKeys.DFS_BLOCK_ACCESS_KEY_UPDATE_INTERVAL_KEY, 600) * 60 * 1000L; // 10 hrs this.accessTokenLifetime = conf.getLong( DFSConfigKeys.DFS_BLOCK_ACCESS_TOKEN_LIFETIME_KEY, 600) * 60 * 1000L; // 10 hrs } LOG.info("isAccessTokenEnabled=" + isAccessTokenEnabled + " accessKeyUpdateInterval=" + accessKeyUpdateInterval / (60 * 1000) + " min(s), accessTokenLifetime=" + accessTokenLifetime / (60 * 1000) + " min(s)"); // set the value of stale interval based on configuration checkForStaleDataNodes = conf.getBoolean( DFSConfigKeys.DFS_NAMENODE_CHECK_STALE_DATANODE_KEY, DFSConfigKeys.DFS_NAMENODE_CHECK_STALE_DATANODE_DEFAULT); staleInterval = getStaleIntervalFromConf(conf, heartbeatExpireInterval); avoidStaleDataNodesForWrite = getAvoidStaleForWriteFromConf(conf, checkForStaleDataNodes); initialAvoidWriteStaleNodes = avoidStaleDataNodesForWrite; ratioUseStaleDataNodesForWrite = getRatioUseStaleNodesForWriteFromConf(conf); } private static float getRatioUseStaleNodesForWriteFromConf(Configuration conf) { float ratioUseStaleDataNodesForWrite = conf.getFloat( DFSConfigKeys.DFS_NAMENODE_USE_STALE_DATANODE_FOR_WRITE_RATIO_KEY, DFSConfigKeys.DFS_NAMENODE_USE_STALE_DATANODE_FOR_WRITE_RATIO_DEFAULT); if (ratioUseStaleDataNodesForWrite > 0 && ratioUseStaleDataNodesForWrite <= 1.0f) { return ratioUseStaleDataNodesForWrite; } else { throw new IllegalArgumentException( DFSConfigKeys.DFS_NAMENODE_USE_STALE_DATANODE_FOR_WRITE_RATIO_KEY + " = '" + ratioUseStaleDataNodesForWrite + "' is invalid. It should be a positive non-zero float value," + " not greater than 1.0f."); } } private static long getStaleIntervalFromConf(Configuration conf, long heartbeatExpireInterval) { long staleInterval = conf.getLong( DFSConfigKeys.DFS_NAMENODE_STALE_DATANODE_INTERVAL_KEY, DFSConfigKeys.DFS_NAMENODE_STALE_DATANODE_INTERVAL_DEFAULT); if (staleInterval <= 0) { throw new IllegalArgumentException( DFSConfigKeys.DFS_NAMENODE_STALE_DATANODE_INTERVAL_KEY + " = '" + staleInterval + "' is invalid. It should be a positive non-zero value."); } final long heartbeatIntervalSeconds = conf.getLong( DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_DEFAULT); // The stale interval value cannot be smaller than // 3 times of heartbeat interval final long minStaleInterval = conf.getInt( DFSConfigKeys.DFS_NAMENODE_STALE_DATANODE_MINIMUM_INTERVAL_KEY, DFSConfigKeys.DFS_NAMENODE_STALE_DATANODE_MINIMUM_INTERVAL_DEFAULT) * heartbeatIntervalSeconds * 1000; if (staleInterval < minStaleInterval) { LOG.warn("The given interval for marking stale datanode = " + staleInterval + ", which is less than " + DFSConfigKeys.DFS_NAMENODE_STALE_DATANODE_MINIMUM_INTERVAL_DEFAULT + " heartbeat intervals. This may cause too frequent changes of " + "stale states of DataNodes since a heartbeat msg may be missing " + "due to temporary short-term failures. Reset stale interval to " + minStaleInterval + "."); staleInterval = minStaleInterval; } if (staleInterval > heartbeatExpireInterval) { LOG.warn("The given interval for marking stale datanode = " + staleInterval + ", which is larger than heartbeat expire interval " + heartbeatExpireInterval + "."); } return staleInterval; } static boolean getAvoidStaleForWriteFromConf(Configuration conf, boolean checkForStale) { boolean avoid = conf.getBoolean( DFSConfigKeys.DFS_NAMENODE_AVOID_STALE_DATANODE_FOR_WRITE_KEY, DFSConfigKeys.DFS_NAMENODE_AVOID_STALE_DATANODE_FOR_WRITE_DEFAULT); boolean avoidStaleDataNodesForWrite = checkForStale && avoid; if (!checkForStale && avoid) { LOG.warn("Cannot set " + DFSConfigKeys.DFS_NAMENODE_CHECK_STALE_DATANODE_KEY + " as false while setting " + DFSConfigKeys.DFS_NAMENODE_AVOID_STALE_DATANODE_FOR_WRITE_KEY + " as true."); } return avoidStaleDataNodesForWrite; } /** * Return the default path permission when upgrading from releases with no * permissions (<=0.15) to releases with permissions (>=0.16) */ protected PermissionStatus getUpgradePermission() { return defaultPermission; } /** Return the FSNamesystem object * */ public static FSNamesystem getFSNamesystem() { return fsNamesystemObject; } synchronized NamespaceInfo getNamespaceInfo() { return new NamespaceInfo(dir.fsImage.getNamespaceID(), dir.fsImage.getCTime(), getDistributedUpgradeVersion()); } /** * Close down this file system manager. * Causes heartbeat and lease daemons to stop; waits briefly for * them to finish, but a short timeout returns control back to caller. */ public void close() { fsRunning = false; try { if (pendingReplications != null) pendingReplications.stop(); if (hbthread != null) hbthread.interrupt(); if (replthread != null) replthread.interrupt(); if (dnthread != null) dnthread.interrupt(); if (smmthread != null) smmthread.interrupt(); if (dtSecretManager != null) dtSecretManager.stopThreads(); } catch (Exception e) { LOG.warn("Exception shutting down FSNamesystem", e); } finally { // using finally to ensure we also wait for lease daemon try { if (lmthread != null) { lmthread.interrupt(); lmthread.join(3000); } dir.close(); blocksMap.close(); } catch (InterruptedException ie) { } catch (IOException ie) { LOG.error("Error closing FSDirectory", ie); IOUtils.cleanup(LOG, dir); } } } /** Is this name system running? */ boolean isRunning() { return fsRunning; } /** * Dump all metadata into specified file */ synchronized void metaSave(String filename) throws IOException { checkSuperuserPrivilege(); File file = new File(System.getProperty("hadoop.log.dir"), filename); PrintWriter out = new PrintWriter(new BufferedWriter( new FileWriter(file, true))); long totalInodes = this.dir.totalInodes(); long totalBlocks = this.getBlocksTotal(); ArrayList<DatanodeDescriptor> live = new ArrayList<DatanodeDescriptor>(); ArrayList<DatanodeDescriptor> dead = new ArrayList<DatanodeDescriptor>(); this.DFSNodesStatus(live, dead); String str = totalInodes + " files and directories, " + totalBlocks + " blocks = " + (totalInodes + totalBlocks) + " total"; out.println(str); out.println("Live Datanodes: "+live.size()); out.println("Dead Datanodes: "+dead.size()); // // Dump contents of neededReplication // synchronized (neededReplications) { out.println("Metasave: Blocks waiting for replication: " + neededReplications.size()); for (Block block : neededReplications) { List<DatanodeDescriptor> containingNodes = new ArrayList<DatanodeDescriptor>(); NumberReplicas numReplicas = new NumberReplicas(); // source node returned is not used chooseSourceDatanode(block, containingNodes, numReplicas); int usableReplicas = numReplicas.liveReplicas() + numReplicas.decommissionedReplicas(); if (block instanceof BlockInfo) { String fileName = FSDirectory.getFullPathName(((BlockInfo) block) .getINode()); out.print(fileName + ": "); } // l: == live:, d: == decommissioned c: == corrupt e: == excess out.print(block + ((usableReplicas > 0)? "" : " MISSING") + " (replicas:" + " l: " + numReplicas.liveReplicas() + " d: " + numReplicas.decommissionedReplicas() + " c: " + numReplicas.corruptReplicas() + " e: " + numReplicas.excessReplicas() + ") "); Collection<DatanodeDescriptor> corruptNodes = corruptReplicas.getNodes(block); for (Iterator<DatanodeDescriptor> jt = blocksMap.nodeIterator(block); jt.hasNext();) { DatanodeDescriptor node = jt.next(); String state = ""; if (corruptNodes != null && corruptNodes.contains(node)) { state = "(corrupt)"; } else if (node.isDecommissioned() || node.isDecommissionInProgress()) { state = "(decommissioned)"; } out.print(" " + node + state + " : "); } out.println(""); } } // // Dump blocks from pendingReplication // pendingReplications.metaSave(out); // // Dump blocks that are waiting to be deleted // dumpRecentInvalidateSets(out); // // Dump all datanodes // datanodeDump(out); out.flush(); out.close(); } /** * Tell all datanodes to use a new, non-persistent bandwidth value for * dfs.balance.bandwidthPerSec. * * A system administrator can tune the balancer bandwidth parameter * (dfs.balance.bandwidthPerSec) dynamically by calling * "dfsadmin -setBalanacerBandwidth newbandwidth", at which point the * following 'bandwidth' variable gets updated with the new value for each * node. Once the heartbeat command is issued to update the value on the * specified datanode, this value will be set back to 0. * * @param bandwidth Blanacer bandwidth in bytes per second for all datanodes. * @throws IOException */ public void setBalancerBandwidth(long bandwidth) throws IOException { checkSuperuserPrivilege(); synchronized(datanodeMap) { for (DatanodeDescriptor nodeInfo : datanodeMap.values()) { nodeInfo.setBalancerBandwidth(bandwidth); } } } long getDefaultBlockSize() { return defaultBlockSize; } long getAccessTimePrecision() { return accessTimePrecision; } private boolean isAccessTimeSupported() { return accessTimePrecision > 0; } /* get replication factor of a block */ private int getReplication(Block block) { INodeFile fileINode = blocksMap.getINode(block); if (fileINode == null) { // block does not belong to any file return 0; } assert !fileINode.isDirectory() : "Block cannot belong to a directory."; return fileINode.getReplication(); } /* updates a block in under replication queue */ synchronized void updateNeededReplications(Block block, int curReplicasDelta, int expectedReplicasDelta) { NumberReplicas repl = countNodes(block); int curExpectedReplicas = getReplication(block); neededReplications.update(block, repl.liveReplicas(), repl.decommissionedReplicas(), curExpectedReplicas, curReplicasDelta, expectedReplicasDelta); } ///////////////////////////////////////////////////////// // // These methods are called by secondary namenodes // ///////////////////////////////////////////////////////// /** * return a list of blocks & their locations on <code>datanode</code> whose * total size is <code>size</code> * * @param datanode on which blocks are located * @param size total size of blocks */ synchronized BlocksWithLocations getBlocks(DatanodeID datanode, long size) throws IOException { checkSuperuserPrivilege(); DatanodeDescriptor node = getDatanode(datanode); if (node == null) { NameNode.stateChangeLog.warn("BLOCK* NameSystem.getBlocks: " + "Asking for blocks from an unrecorded node " + datanode.getName()); throw new IllegalArgumentException( "Unexpected exception. Got getBlocks message for datanode " + datanode.getName() + ", but there is no info for it"); } int numBlocks = node.numBlocks(); if(numBlocks == 0) { return new BlocksWithLocations(new BlockWithLocations[0]); } Iterator<Block> iter = node.getBlockIterator(); int startBlock = r.nextInt(numBlocks); // starting from a random block // skip blocks for(int i=0; i<startBlock; i++) { iter.next(); } List<BlockWithLocations> results = new ArrayList<BlockWithLocations>(); long totalSize = 0; while(totalSize<size && iter.hasNext()) { totalSize += addBlock(iter.next(), results); } if(totalSize<size) { iter = node.getBlockIterator(); // start from the beginning for(int i=0; i<startBlock&&totalSize<size; i++) { totalSize += addBlock(iter.next(), results); } } return new BlocksWithLocations( results.toArray(new BlockWithLocations[results.size()])); } /** * Get access keys * * @return current access keys */ ExportedBlockKeys getBlockKeys() { return isAccessTokenEnabled ? accessTokenHandler.exportKeys() : ExportedBlockKeys.DUMMY_KEYS; } /** * Get all valid locations of the block & add the block to results * return the length of the added block; 0 if the block is not added */ private long addBlock(Block block, List<BlockWithLocations> results) { ArrayList<String> machineSet = new ArrayList<String>(blocksMap.numNodes(block)); for(Iterator<DatanodeDescriptor> it = blocksMap.nodeIterator(block); it.hasNext();) { String storageID = it.next().getStorageID(); // filter invalidate replicas Collection<Block> blocks = recentInvalidateSets.get(storageID); if(blocks==null || !blocks.contains(block)) { machineSet.add(storageID); } } if(machineSet.size() == 0) { return 0; } else { results.add(new BlockWithLocations(block, machineSet.toArray(new String[machineSet.size()]))); return block.getNumBytes(); } } ///////////////////////////////////////////////////////// // // These methods are called by HadoopFS clients // ///////////////////////////////////////////////////////// /** * Set permissions for an existing file. * @throws IOException */ public void setPermission(String src, FsPermission permission ) throws IOException { synchronized (this) { if (isInSafeMode()) throw new SafeModeException("Cannot set permission for " + src, safeMode); checkOwner(src); dir.setPermission(src, permission); } getEditLog().logSync(); if (auditLog.isInfoEnabled() && isExternalInvocation()) { final HdfsFileStatus stat = dir.getFileInfo(src); logAuditEvent(UserGroupInformation.getCurrentUser(), Server.getRemoteIp(), "setPermission", src, null, stat); } } /** * Set owner for an existing file. * @throws IOException */ public void setOwner(String src, String username, String group ) throws IOException { synchronized (this) { if (isInSafeMode()) throw new SafeModeException("Cannot set owner for " + src, safeMode); FSPermissionChecker pc = checkOwner(src); if (!pc.isSuper) { if (username != null && !pc.user.equals(username)) { throw new AccessControlException("Non-super user cannot change owner."); } if (group != null && !pc.containsGroup(group)) { throw new AccessControlException("User does not belong to " + group + " ."); } } dir.setOwner(src, username, group); } getEditLog().logSync(); if (auditLog.isInfoEnabled() && isExternalInvocation()) { final HdfsFileStatus stat = dir.getFileInfo(src); logAuditEvent(UserGroupInformation.getCurrentUser(), Server.getRemoteIp(), "setOwner", src, null, stat); } } /** * Get block locations within the specified range. * * @see #getBlockLocations(String, long, long) */ LocatedBlocks getBlockLocations(String clientMachine, String src, long offset, long length) throws IOException { LocatedBlocks blocks = getBlockLocations(src, offset, length, true, true, true); if (blocks != null) { //sort the blocks DatanodeDescriptor client = host2DataNodeMap.getDatanodeByHost( clientMachine); DFSUtil.StaleComparator comparator = null; if (checkForStaleDataNodes) { comparator = new DFSUtil.StaleComparator(staleInterval); } // Note: the last block is also included and sorted for (LocatedBlock b : blocks.getLocatedBlocks()) { clusterMap.pseudoSortByDistance(client, b.getLocations()); if (checkForStaleDataNodes) { Arrays.sort(b.getLocations(), comparator); } } } return blocks; } /** * Get block locations within the specified range. * @see ClientProtocol#getBlockLocations(String, long, long) */ public LocatedBlocks getBlockLocations(String src, long offset, long length ) throws IOException { return getBlockLocations(src, offset, length, false, true, true); } /** * Get block locations within the specified range. * @see ClientProtocol#getBlockLocations(String, long, long) */ public LocatedBlocks getBlockLocations(String src, long offset, long length, boolean doAccessTime, boolean needBlockToken, boolean checkSafeMode) throws IOException { if (isPermissionEnabled) { checkPathAccess(src, FsAction.READ); } if (offset < 0) { throw new IOException("Negative offset is not supported. File: " + src ); } if (length < 0) { throw new IOException("Negative length is not supported. File: " + src ); } final LocatedBlocks ret = getBlockLocationsInternal(src, offset, length, Integer.MAX_VALUE, doAccessTime, needBlockToken); if (auditLog.isInfoEnabled() && isExternalInvocation()) { logAuditEvent(UserGroupInformation.getCurrentUser(), Server.getRemoteIp(), "open", src, null, null); } if (checkSafeMode && isInSafeMode()) { for (LocatedBlock b : ret.getLocatedBlocks()) { // if safemode & no block locations yet then throw safemodeException if ((b.getLocations() == null) || (b.getLocations().length == 0)) { throw new SafeModeException("Zero blocklocations for " + src, safeMode); } } } return ret; } private synchronized LocatedBlocks getBlockLocationsInternal(String src, long offset, long length, int nrBlocksToReturn, boolean doAccessTime, boolean needBlockToken) throws IOException { INodeFile inode = dir.getFileINode(src); if(inode == null) { return null; } if (doAccessTime && isAccessTimeSupported()) { dir.setTimes(src, inode, -1, now(), false); } Block[] blocks = inode.getBlocks(); if (blocks == null) { return null; } if (blocks.length == 0) { return inode.createLocatedBlocks(new ArrayList<LocatedBlock>(blocks.length)); } List<LocatedBlock> results; results = new ArrayList<LocatedBlock>(blocks.length); int curBlk = 0; long curPos = 0, blkSize = 0; int nrBlocks = (blocks[0].getNumBytes() == 0) ? 0 : blocks.length; for (curBlk = 0; curBlk < nrBlocks; curBlk++) { blkSize = blocks[curBlk].getNumBytes(); assert blkSize > 0 : "Block of size 0"; if (curPos + blkSize > offset) { break; } curPos += blkSize; } if (nrBlocks > 0 && curBlk == nrBlocks) // offset >= end of file return null; long endOff = offset + length; do { // get block locations int numNodes = blocksMap.numNodes(blocks[curBlk]); int numCorruptNodes = countNodes(blocks[curBlk]).corruptReplicas(); int numCorruptReplicas = corruptReplicas.numCorruptReplicas(blocks[curBlk]); if (numCorruptNodes != numCorruptReplicas) { LOG.warn("Inconsistent number of corrupt replicas for " + blocks[curBlk] + "blockMap has " + numCorruptNodes + " but corrupt replicas map has " + numCorruptReplicas); } DatanodeDescriptor[] machineSet = null; boolean blockCorrupt = false; if (inode.isUnderConstruction() && curBlk == blocks.length - 1 && blocksMap.numNodes(blocks[curBlk]) == 0) { // get unfinished block locations INodeFileUnderConstruction cons = (INodeFileUnderConstruction)inode; machineSet = cons.getTargets(); blockCorrupt = false; } else { blockCorrupt = (numCorruptNodes == numNodes); int numMachineSet = blockCorrupt ? numNodes : (numNodes - numCorruptNodes); machineSet = new DatanodeDescriptor[numMachineSet]; if (numMachineSet > 0) { numNodes = 0; for(Iterator<DatanodeDescriptor> it = blocksMap.nodeIterator(blocks[curBlk]); it.hasNext();) { DatanodeDescriptor dn = it.next(); boolean replicaCorrupt = corruptReplicas.isReplicaCorrupt(blocks[curBlk], dn); if (blockCorrupt || (!blockCorrupt && !replicaCorrupt)) machineSet[numNodes++] = dn; } } } LocatedBlock b = new LocatedBlock(blocks[curBlk], machineSet, curPos, blockCorrupt); if(isAccessTokenEnabled && needBlockToken) { b.setBlockToken(accessTokenHandler.generateToken(b.getBlock(), EnumSet.of(BlockTokenSecretManager.AccessMode.READ))); } results.add(b); curPos += blocks[curBlk].getNumBytes(); curBlk++; } while (curPos < endOff && curBlk < blocks.length && results.size() < nrBlocksToReturn); return inode.createLocatedBlocks(results); } /** * stores the modification and access time for this inode. * The access time is precise upto an hour. The transaction, if needed, is * written to the edits log but is not flushed. */ public synchronized void setTimes(String src, long mtime, long atime) throws IOException { if (!isAccessTimeSupported() && atime != -1) { throw new IOException("Access time for hdfs is not configured. " + " Please set dfs.access.time.precision configuration parameter."); } if (isInSafeMode()) { throw new SafeModeException("Cannot set accesstimes for " + src, safeMode); } // // The caller needs to have write access to set access & modification times. if (isPermissionEnabled) { checkPathAccess(src, FsAction.WRITE); } INodeFile inode = dir.getFileINode(src); if (inode != null) { dir.setTimes(src, inode, mtime, atime, true); if (auditLog.isInfoEnabled() && isExternalInvocation()) { final HdfsFileStatus stat = dir.getFileInfo(src); logAuditEvent(UserGroupInformation.getCurrentUser(), Server.getRemoteIp(), "setTimes", src, null, stat); } } else { throw new FileNotFoundException("File " + src + " does not exist."); } } /** * Set replication for an existing file. * * The NameNode sets new replication and schedules either replication of * under-replicated data blocks or removal of the eccessive block copies * if the blocks are over-replicated. * * @see ClientProtocol#setReplication(String, short) * @param src file name * @param replication new replication * @return true if successful; * false if file does not exist or is a directory */ public boolean setReplication(String src, short replication) throws IOException { boolean status = setReplicationInternal(src, replication); getEditLog().logSync(); if (status && auditLog.isInfoEnabled() && isExternalInvocation()) { logAuditEvent(UserGroupInformation.getCurrentUser(), Server.getRemoteIp(), "setReplication", src, null, null); } return status; } private synchronized boolean setReplicationInternal(String src, short replication ) throws IOException { if (isInSafeMode()) throw new SafeModeException("Cannot set replication for " + src, safeMode); verifyReplication(src, replication, null); if (isPermissionEnabled) { checkPathAccess(src, FsAction.WRITE); } int[] oldReplication = new int[1]; Block[] fileBlocks; fileBlocks = dir.setReplication(src, replication, oldReplication); if (fileBlocks == null) // file not found or is a directory return false; int oldRepl = oldReplication[0]; if (oldRepl == replication) // the same replication return true; // update needReplication priority queues for(int idx = 0; idx < fileBlocks.length; idx++) updateNeededReplications(fileBlocks[idx], 0, replication-oldRepl); if (oldRepl > replication) { // old replication > the new one; need to remove copies LOG.info("Reducing replication for file " + src + ". New replication is " + replication); for(int idx = 0; idx < fileBlocks.length; idx++) processOverReplicatedBlock(fileBlocks[idx], replication, null, null); } else { // replication factor is increased LOG.info("Increasing replication for file " + src + ". New replication is " + replication); } return true; } long getPreferredBlockSize(String filename) throws IOException { if (isPermissionEnabled) { checkTraverse(filename); } return dir.getPreferredBlockSize(filename); } /** * Check whether the replication parameter is within the range * determined by system configuration. */ private void verifyReplication(String src, short replication, String clientName ) throws IOException { String text = "file " + src + ((clientName != null) ? " on client " + clientName : "") + ".\n" + "Requested replication " + replication; if (replication > maxReplication) throw new IOException(text + " exceeds maximum " + maxReplication); if (replication < minReplication) throw new IOException( text + " is less than the required minimum " + minReplication); } /* * Verify that parent dir exists */ private void verifyParentDir(String src) throws FileAlreadyExistsException, FileNotFoundException { Path parent = new Path(src).getParent(); if (parent != null) { INode[] pathINodes = dir.getExistingPathINodes(parent.toString()); if (pathINodes[pathINodes.length - 1] == null) { throw new FileNotFoundException("Parent directory doesn't exist: " + parent.toString()); } else if (!pathINodes[pathINodes.length - 1].isDirectory()) { throw new FileAlreadyExistsException("Parent path is not a directory: " + parent.toString()); } } } /** * Create a new file entry in the namespace. * * @see ClientProtocol#create(String, FsPermission, String, boolean, short, long) * * @throws IOException if file name is invalid * {@link FSDirectory#isValidToCreate(String)}. */ void startFile(String src, PermissionStatus permissions, String holder, String clientMachine, boolean overwrite, boolean createParent, short replication, long blockSize ) throws IOException { startFileInternal(src, permissions, holder, clientMachine, overwrite, false, createParent, replication, blockSize); getEditLog().logSync(); if (auditLog.isInfoEnabled() && isExternalInvocation()) { final HdfsFileStatus stat = dir.getFileInfo(src); logAuditEvent(UserGroupInformation.getCurrentUser(), Server.getRemoteIp(), "create", src, null, stat); } } private synchronized void startFileInternal(String src, PermissionStatus permissions, String holder, String clientMachine, boolean overwrite, boolean append, boolean createParent, short replication, long blockSize ) throws IOException { if (NameNode.stateChangeLog.isDebugEnabled()) { NameNode.stateChangeLog.debug("DIR* NameSystem.startFile: src=" + src + ", holder=" + holder + ", clientMachine=" + clientMachine + ", createParent=" + createParent + ", replication=" + replication + ", overwrite=" + overwrite + ", append=" + append); } if (isInSafeMode()) throw new SafeModeException("Cannot create file" + src, safeMode); if (!DFSUtil.isValidName(src)) { throw new IOException("Invalid file name: " + src); } // Verify that the destination does not exist as a directory already. boolean pathExists = dir.exists(src); if (pathExists && dir.isDir(src)) { throw new IOException("Cannot create file "+ src + "; already exists as a directory."); } if (isPermissionEnabled) { if (append || (overwrite && pathExists)) { checkPathAccess(src, FsAction.WRITE); } else { checkAncestorAccess(src, FsAction.WRITE); } } if (!createParent) { verifyParentDir(src); } try { INode myFile = dir.getFileINode(src); recoverLeaseInternal(myFile, src, holder, clientMachine, false); try { verifyReplication(src, replication, clientMachine); } catch(IOException e) { throw new IOException("failed to create "+e.getMessage()); } if (append) { if (myFile == null) { throw new FileNotFoundException("failed to append to non-existent file " + src + " on client " + clientMachine); } else if (myFile.isDirectory()) { throw new IOException("failed to append to directory " + src +" on client " + clientMachine); } } else if (!dir.isValidToCreate(src)) { if (overwrite) { delete(src, true); } else { throw new IOException("failed to create file " + src +" on client " + clientMachine +" either because the filename is invalid or the file exists"); } } DatanodeDescriptor clientNode = host2DataNodeMap.getDatanodeByHost(clientMachine); if (append) { // // Replace current node with a INodeUnderConstruction. // Recreate in-memory lease record. // INodeFile node = (INodeFile) myFile; INodeFileUnderConstruction cons = new INodeFileUnderConstruction( node.getLocalNameBytes(), node.getReplication(), node.getModificationTime(), node.getPreferredBlockSize(), node.getBlocks(), node.getPermissionStatus(), holder, clientMachine, clientNode); dir.replaceNode(src, node, cons); leaseManager.addLease(cons.clientName, src); } else { // Now we can add the name to the filesystem. This file has no // blocks associated with it. // checkFsObjectLimit(); // increment global generation stamp long genstamp = nextGenerationStamp(); INodeFileUnderConstruction newNode = dir.addFile(src, permissions, replication, blockSize, holder, clientMachine, clientNode, genstamp); if (newNode == null) { throw new IOException("DIR* NameSystem.startFile: " + "Unable to add file to namespace."); } leaseManager.addLease(newNode.clientName, src); if (NameNode.stateChangeLog.isDebugEnabled()) { NameNode.stateChangeLog.debug("DIR* NameSystem.startFile: " +"add "+src+" to namespace for "+holder); } } } catch (IOException ie) { NameNode.stateChangeLog.warn("DIR* NameSystem.startFile: " +ie.getMessage()); throw ie; } } /** * Recover lease; * Immediately revoke the lease of the current lease holder and start lease * recovery so that the file can be forced to be closed. * * @param src the path of the file to start lease recovery * @param holder the lease holder's name * @param clientMachine the client machine's name * @return true if the file is already closed * @throws IOException */ synchronized boolean recoverLease(String src, String holder, String clientMachine) throws IOException { if (isInSafeMode()) { throw new SafeModeException( "Cannot recover the lease of " + src, safeMode); } if (!DFSUtil.isValidName(src)) { throw new IOException("Invalid file name: " + src); } INode inode = dir.getFileINode(src); if (inode == null) { throw new FileNotFoundException("File not found " + src); } if (!inode.isUnderConstruction()) { return true; } if (isPermissionEnabled) { checkPathAccess(src, FsAction.WRITE); } recoverLeaseInternal(inode, src, holder, clientMachine, true); return false; } private void recoverLeaseInternal(INode fileInode, String src, String holder, String clientMachine, boolean force) throws IOException { if (fileInode != null && fileInode.isUnderConstruction()) { INodeFileUnderConstruction pendingFile = (INodeFileUnderConstruction) fileInode; // // If the file is under construction , then it must be in our // leases. Find the appropriate lease record. // Lease lease = leaseManager.getLease(holder); // // We found the lease for this file. And surprisingly the original // holder is trying to recreate this file. This should never occur. // if (!force && lease != null) { Lease leaseFile = leaseManager.getLeaseByPath(src); if (leaseFile != null && leaseFile.equals(lease)) { throw new AlreadyBeingCreatedException( "failed to create file " + src + " for " + holder + " on client " + clientMachine + " because current leaseholder is trying to recreate file."); } } // // Find the original holder. // lease = leaseManager.getLease(pendingFile.clientName); if (lease == null) { throw new AlreadyBeingCreatedException( "failed to create file " + src + " for " + holder + " on client " + clientMachine + " because pendingCreates is non-null but no leases found."); } if (force) { // close now: no need to wait for soft lease expiration and // close only the file src LOG.info("recoverLease: recover lease " + lease + ", src=" + src + " from client " + pendingFile.clientName); internalReleaseLeaseOne(lease, src); } else { // // If the original holder has not renewed in the last SOFTLIMIT // period, then start lease recovery. // if (lease.expiredSoftLimit()) { LOG.info("startFile: recover lease " + lease + ", src=" + src + " from client " + pendingFile.clientName); internalReleaseLease(lease, src); } throw new AlreadyBeingCreatedException( "failed to create file " + src + " for " + holder + " on client " + clientMachine + ", because this file is already being created by " + pendingFile.getClientName() + " on " + pendingFile.getClientMachine()); } } } /** * Append to an existing file in the namespace. */ LocatedBlock appendFile(String src, String holder, String clientMachine ) throws IOException { if (!allowBrokenAppend) { throw new IOException("Append is not supported. " + "Please see the dfs.support.append configuration parameter."); } startFileInternal(src, null, holder, clientMachine, false, true, false, (short)maxReplication, (long)0); getEditLog().logSync(); // // Create a LocatedBlock object for the last block of the file // to be returned to the client. Return null if the file does not // have a partial block at the end. // LocatedBlock lb = null; synchronized (this) { // Need to re-check existence here, since the file may have been deleted // in between the synchronized blocks INodeFileUnderConstruction file = checkLease(src, holder); Block[] blocks = file.getBlocks(); if (blocks != null && blocks.length > 0) { Block last = blocks[blocks.length-1]; BlockInfo storedBlock = blocksMap.getStoredBlock(last); if (file.getPreferredBlockSize() > storedBlock.getNumBytes()) { long fileLength = file.computeContentSummary().getLength(); DatanodeDescriptor[] targets = new DatanodeDescriptor[blocksMap.numNodes(last)]; Iterator<DatanodeDescriptor> it = blocksMap.nodeIterator(last); for (int i = 0; it != null && it.hasNext(); i++) { targets[i] = it.next(); } // remove the replica locations of this block from the blocksMap for (int i = 0; i < targets.length; i++) { targets[i].removeBlock(storedBlock); } // set the locations of the last block in the lease record file.setLastBlock(storedBlock, targets); lb = new LocatedBlock(last, targets, fileLength-storedBlock.getNumBytes()); if (isAccessTokenEnabled) { lb.setBlockToken(accessTokenHandler.generateToken(lb.getBlock(), EnumSet.of(BlockTokenSecretManager.AccessMode.WRITE))); } // Remove block from replication queue. updateNeededReplications(last, 0, 0); // remove this block from the list of pending blocks to be deleted. // This reduces the possibility of triggering HADOOP-1349. // for (DatanodeDescriptor dd : targets) { String datanodeId = dd.getStorageID(); Collection<Block> v = recentInvalidateSets.get(datanodeId); if (v != null && v.remove(last)) { if (v.isEmpty()) { recentInvalidateSets.remove(datanodeId); } pendingDeletionBlocksCount--; } } } } } if (lb != null) { if (NameNode.stateChangeLog.isDebugEnabled()) { NameNode.stateChangeLog.debug("DIR* NameSystem.appendFile: file " +src+" for "+holder+" at "+clientMachine +" block " + lb.getBlock() +" block size " + lb.getBlock().getNumBytes()); } } if (auditLog.isInfoEnabled() && isExternalInvocation()) { logAuditEvent(UserGroupInformation.getCurrentUser(), Server.getRemoteIp(), "append", src, null, null); } return lb; } /** * Stub for old callers pre-HDFS-630 */ public LocatedBlock getAdditionalBlock(String src, String clientName ) throws IOException { return getAdditionalBlock(src, clientName, null); } /** * The client would like to obtain an additional block for the indicated * filename (which is being written-to). Return an array that consists * of the block, plus a set of machines. The first on this list should * be where the client writes data. Subsequent items in the list must * be provided in the connection to the first datanode. * * Make sure the previous blocks have been reported by datanodes and * are replicated. Will return an empty 2-elt array if we want the * client to "try again later". */ public LocatedBlock getAdditionalBlock(String src, String clientName, HashMap<Node, Node> excludedNodes ) throws IOException { long fileLength, blockSize; int replication; DatanodeDescriptor clientNode = null; Block newBlock = null; NameNode.stateChangeLog.debug("BLOCK* NameSystem.getAdditionalBlock: file " +src+" for "+clientName); synchronized (this) { if (isInSafeMode()) {//check safemode first for failing-fast throw new SafeModeException("Cannot add block to " + src, safeMode); } // have we exceeded the configured limit of fs objects. checkFsObjectLimit(); INodeFileUnderConstruction pendingFile = checkLease(src, clientName); // // If we fail this, bad things happen! // if (!checkFileProgress(pendingFile, false)) { throw new NotReplicatedYetException("Not replicated yet:" + src); } fileLength = pendingFile.computeContentSummary().getLength(); blockSize = pendingFile.getPreferredBlockSize(); clientNode = pendingFile.getClientNode(); replication = (int)pendingFile.getReplication(); } // choose targets for the new block to be allocated. DatanodeDescriptor targets[] = replicator.chooseTarget(src, replication, clientNode, excludedNodes, blockSize); if (targets.length < this.minReplication) { throw new IOException("File " + src + " could only be replicated to " + targets.length + " nodes, instead of " + minReplication); } // Allocate a new block and record it in the INode. synchronized (this) { if (isInSafeMode()) { //make sure it is not in safemode again. throw new SafeModeException("Cannot add block to " + src, safeMode); } INode[] pathINodes = dir.getExistingPathINodes(src); int inodesLen = pathINodes.length; checkLease(src, clientName, pathINodes[inodesLen-1]); INodeFileUnderConstruction pendingFile = (INodeFileUnderConstruction) pathINodes[inodesLen - 1]; if (!checkFileProgress(pendingFile, false)) { throw new NotReplicatedYetException("Not replicated yet:" + src); } // allocate new block record block locations in INode. newBlock = allocateBlock(src, pathINodes); pendingFile.setTargets(targets); for (DatanodeDescriptor dn : targets) { dn.incBlocksScheduled(); } dir.persistBlocks(src, pendingFile); } if (persistBlocks) { getEditLog().logSync(); } // Create next block LocatedBlock b = new LocatedBlock(newBlock, targets, fileLength); if (isAccessTokenEnabled) { b.setBlockToken(accessTokenHandler.generateToken(b.getBlock(), EnumSet.of(BlockTokenSecretManager.AccessMode.WRITE))); } return b; } /** * The client would like to let go of the given block */ public synchronized boolean abandonBlock(Block b, String src, String holder ) throws IOException { // // Remove the block from the pending creates list // NameNode.stateChangeLog.debug("BLOCK* NameSystem.abandonBlock: " +b+"of file "+src); if (isInSafeMode()) { throw new SafeModeException("Cannot abandon block " + b + " for fle" + src, safeMode); } INodeFileUnderConstruction file = checkLease(src, holder); dir.removeBlock(src, file, b); NameNode.stateChangeLog.debug("BLOCK* NameSystem.abandonBlock: " + b + " is removed from pendingCreates"); dir.persistBlocks(src, file); if (persistBlocks) { getEditLog().logSync(); } return true; } // make sure that we still have the lease on this file. private INodeFileUnderConstruction checkLease(String src, String holder) throws IOException { INodeFile file = dir.getFileINode(src); checkLease(src, holder, file); return (INodeFileUnderConstruction)file; } private void checkLease(String src, String holder, INode file) throws IOException { if (file == null || file.isDirectory()) { Lease lease = leaseManager.getLease(holder); throw new LeaseExpiredException("No lease on " + src + " File does not exist. " + (lease != null ? lease.toString() : "Holder " + holder + " does not have any open files.")); } if (!file.isUnderConstruction()) { Lease lease = leaseManager.getLease(holder); throw new LeaseExpiredException("No lease on " + src + " File is not open for writing. " + (lease != null ? lease.toString() : "Holder " + holder + " does not have any open files.")); } INodeFileUnderConstruction pendingFile = (INodeFileUnderConstruction)file; if (holder != null && !pendingFile.getClientName().equals(holder)) { throw new LeaseExpiredException("Lease mismatch on " + src + " owned by " + pendingFile.getClientName() + " but is accessed by " + holder); } } /** * The FSNamesystem will already know the blocks that make up the file. * Before we return, we make sure that all the file's blocks have * been reported by datanodes and are replicated correctly. */ enum CompleteFileStatus { OPERATION_FAILED, STILL_WAITING, COMPLETE_SUCCESS } public CompleteFileStatus completeFile(String src, String holder) throws IOException { CompleteFileStatus status = completeFileInternal(src, holder); getEditLog().logSync(); return status; } private synchronized CompleteFileStatus completeFileInternal(String src, String holder) throws IOException { NameNode.stateChangeLog.debug("DIR* NameSystem.completeFile: " + src + " for " + holder); if (isInSafeMode()) throw new SafeModeException("Cannot complete file " + src, safeMode); INodeFileUnderConstruction pendingFile = checkLease(src, holder); Block[] fileBlocks = dir.getFileBlocks(src); if (fileBlocks == null ) { NameNode.stateChangeLog.warn("DIR* NameSystem.completeFile: " + "failed to complete " + src + " because dir.getFileBlocks() is null," + " pending from " + pendingFile.getClientMachine()); return CompleteFileStatus.OPERATION_FAILED; } if (!checkFileProgress(pendingFile, true)) { return CompleteFileStatus.STILL_WAITING; } finalizeINodeFileUnderConstruction(src, pendingFile); NameNode.stateChangeLog.info("DIR* NameSystem.completeFile: file " + src + " is closed by " + holder); return CompleteFileStatus.COMPLETE_SUCCESS; } /** * Check all blocks of a file. If any blocks are lower than their intended * replication factor, then insert them into neededReplication */ private void checkReplicationFactor(INodeFile file) { int numExpectedReplicas = file.getReplication(); Block[] pendingBlocks = file.getBlocks(); int nrBlocks = pendingBlocks.length; for (int i = 0; i < nrBlocks; i++) { // filter out containingNodes that are marked for decommission. NumberReplicas number = countNodes(pendingBlocks[i]); if (number.liveReplicas() < numExpectedReplicas) { neededReplications.add(pendingBlocks[i], number.liveReplicas(), number.decommissionedReplicas, numExpectedReplicas); } } } static Random randBlockId = new Random(); /** * Allocate a block at the given pending filename * * @param src path to the file * @param inodes INode representing each of the components of src. * <code>inodes[inodes.length-1]</code> is the INode for the file. */ private Block allocateBlock(String src, INode[] inodes) throws IOException { Block b = new Block(FSNamesystem.randBlockId.nextLong(), 0, 0); while(isValidBlock(b)) { b.setBlockId(FSNamesystem.randBlockId.nextLong()); } b.setGenerationStamp(getGenerationStamp()); b = dir.addBlock(src, inodes, b); NameNode.stateChangeLog.info("BLOCK* NameSystem.allocateBlock: " +src+ ". "+b); return b; } /** * Check that the indicated file's blocks are present and * replicated. If not, return false. If checkall is true, then check * all blocks, otherwise check only penultimate block. */ synchronized boolean checkFileProgress(INodeFile v, boolean checkall) { if (checkall) { // // check all blocks of the file. // for (Block block: v.getBlocks()) { if (blocksMap.numNodes(block) < this.minReplication) { return false; } } } else { // // check the penultimate block of this file // Block b = v.getPenultimateBlock(); if (b != null) { if (blocksMap.numNodes(b) < this.minReplication) { return false; } } } return true; } /** * Remove a datanode from the invalidatesSet * @param n datanode */ void removeFromInvalidates(String storageID) { Collection<Block> blocks = recentInvalidateSets.remove(storageID); if (blocks != null) { pendingDeletionBlocksCount -= blocks.size(); } } /** * Adds block to list of blocks which will be invalidated on * specified datanode * @param b block * @param n datanode * @param log true to create an entry in the log */ void addToInvalidates(Block b, DatanodeInfo dn, boolean log) { addToInvalidatesNoLog(b, dn); if (log) { NameNode.stateChangeLog.info("BLOCK* NameSystem.addToInvalidates: " + b.getBlockName() + " to " + dn.getName()); } } /** * Adds block to list of blocks which will be invalidated on specified * datanode and log the operation * * @param b * block * @param dn * datanode */ void addToInvalidates(Block b, DatanodeInfo dn) { addToInvalidates(b, dn, true); } /** * Adds block to list of blocks which will be invalidated on * specified datanode * @param b block * @param n datanode */ void addToInvalidatesNoLog(Block b, DatanodeInfo n) { Collection<Block> invalidateSet = recentInvalidateSets.get(n.getStorageID()); if (invalidateSet == null) { invalidateSet = new HashSet<Block>(); recentInvalidateSets.put(n.getStorageID(), invalidateSet); } if (invalidateSet.add(b)) { pendingDeletionBlocksCount++; } } /** * Adds block to list of blocks which will be invalidated on * all its datanodes. */ private void addToInvalidates(Block b) { StringBuilder datanodes = new StringBuilder(); for (Iterator<DatanodeDescriptor> it = blocksMap.nodeIterator(b); it.hasNext();) { DatanodeDescriptor node = it.next(); addToInvalidates(b, node, false); datanodes.append(node.getName()).append(" "); } if (datanodes.length() != 0) { NameNode.stateChangeLog.info("BLOCK* NameSystem.addToInvalidates: " + b.getBlockName() + " to " + datanodes.toString()); } } /** * dumps the contents of recentInvalidateSets */ private synchronized void dumpRecentInvalidateSets(PrintWriter out) { int size = recentInvalidateSets.values().size(); out.println("Metasave: Blocks " + pendingDeletionBlocksCount + " waiting deletion from " + size + " datanodes."); if (size == 0) { return; } for(Map.Entry<String,Collection<Block>> entry : recentInvalidateSets.entrySet()) { Collection<Block> blocks = entry.getValue(); if (blocks.size() > 0) { out.println(datanodeMap.get(entry.getKey()).getName() + blocks); } } } /** * Mark the block belonging to datanode as corrupt * @param blk Block to be marked as corrupt * @param dn Datanode which holds the corrupt replica */ public synchronized void markBlockAsCorrupt(Block blk, DatanodeInfo dn) throws IOException { DatanodeDescriptor node = getDatanode(dn); if (node == null) { throw new IOException("Cannot mark block" + blk.getBlockName() + " as corrupt because datanode " + dn.getName() + " does not exist. "); } final BlockInfo storedBlockInfo = blocksMap.getStoredBlock(blk); if (storedBlockInfo == null) { // Check if the replica is in the blockMap, if not // ignore the request for now. This could happen when BlockScanner // thread of Datanode reports bad block before Block reports are sent // by the Datanode on startup NameNode.stateChangeLog.info("BLOCK NameSystem.markBlockAsCorrupt: " + "block " + blk + " could not be marked " + "as corrupt as it does not exists in " + "blocksMap"); } else { INodeFile inode = storedBlockInfo.getINode(); if (inode == null) { NameNode.stateChangeLog.info("BLOCK NameSystem.markBlockAsCorrupt: " + "block " + blk + " could not be marked " + "as corrupt as it does not belong to " + "any file"); addToInvalidates(storedBlockInfo, node); return; } // Add this replica to corruptReplicas Map corruptReplicas.addToCorruptReplicasMap(storedBlockInfo, node); if (countNodes(storedBlockInfo).liveReplicas()>inode.getReplication()) { // the block is over-replicated so invalidate the replicas immediately invalidateBlock(storedBlockInfo, node); } else { // add the block to neededReplication updateNeededReplications(storedBlockInfo, -1, 0); } } } /** * Invalidates the given block on the given datanode. */ private synchronized void invalidateBlock(Block blk, DatanodeInfo dn) throws IOException { NameNode.stateChangeLog.info("DIR* NameSystem.invalidateBlock: " + blk + " on " + dn.getName()); DatanodeDescriptor node = getDatanode(dn); if (node == null) { throw new IOException("Cannot invalidate block " + blk + " because datanode " + dn.getName() + " does not exist."); } // Check how many copies we have of the block. If we have at least one // copy on a live node, then we can delete it. int count = countNodes(blk).liveReplicas(); if (count > 1) { addToInvalidates(blk, dn); removeStoredBlock(blk, node); NameNode.stateChangeLog.debug("BLOCK* NameSystem.invalidateBlocks: " + blk + " on " + dn.getName() + " listed for deletion."); } else { NameNode.stateChangeLog.info("BLOCK* NameSystem.invalidateBlocks: " + blk + " on " + dn.getName() + " is the only copy and was not deleted."); } } //////////////////////////////////////////////////////////////// // Here's how to handle block-copy failure during client write: // -- As usual, the client's write should result in a streaming // backup write to a k-machine sequence. // -- If one of the backup machines fails, no worries. Fail silently. // -- Before client is allowed to close and finalize file, make sure // that the blocks are backed up. Namenode may have to issue specific backup // commands to make up for earlier datanode failures. Once all copies // are made, edit namespace and return to client. //////////////////////////////////////////////////////////////// /** Change the indicated filename. */ public boolean renameTo(String src, String dst) throws IOException { boolean status = renameToInternal(src, dst); getEditLog().logSync(); if (status && auditLog.isInfoEnabled() && isExternalInvocation()) { final HdfsFileStatus stat = dir.getFileInfo(dst); logAuditEvent(UserGroupInformation.getCurrentUser(), Server.getRemoteIp(), "rename", src, dst, stat); } return status; } private synchronized boolean renameToInternal(String src, String dst ) throws IOException { NameNode.stateChangeLog.debug("DIR* NameSystem.renameTo: " + src + " to " + dst); if (isInSafeMode()) throw new SafeModeException("Cannot rename " + src, safeMode); if (!DFSUtil.isValidName(dst)) { throw new IOException("Invalid name: " + dst); } if (isPermissionEnabled) { //We should not be doing this. This is move() not renameTo(). //but for now, String actualdst = dir.isDir(dst)? dst + Path.SEPARATOR + new Path(src).getName(): dst; checkParentAccess(src, FsAction.WRITE); checkAncestorAccess(actualdst, FsAction.WRITE); } HdfsFileStatus dinfo = dir.getFileInfo(dst); if (dir.renameTo(src, dst)) { changeLease(src, dst, dinfo); // update lease with new filename return true; } return false; } /** * Remove the indicated filename from namespace. If the filename * is a directory (non empty) and recursive is set to false then throw exception. */ public boolean delete(String src, boolean recursive) throws IOException { if ((!recursive) && (!dir.isDirEmpty(src))) { throw new IOException(src + " is non empty"); } if (NameNode.stateChangeLog.isDebugEnabled()) { NameNode.stateChangeLog.debug("DIR* NameSystem.delete: " + src); } boolean status = deleteInternal(src, true); if (status && auditLog.isInfoEnabled() && isExternalInvocation()) { logAuditEvent(UserGroupInformation.getCurrentUser(), Server.getRemoteIp(), "delete", src, null, null); } return status; } /** * Remove a file/directory from the namespace. * <p> * For large directories, deletion is incremental. The blocks under the * directory are collected and deleted a small number at a time holding the * {@link FSNamesystem} lock. * <p> * For small directory or file the deletion is done in one shot. */ private boolean deleteInternal(String src, boolean enforcePermission) throws IOException { ArrayList<Block> collectedBlocks = new ArrayList<Block>(); synchronized (this) { if (isInSafeMode()) { throw new SafeModeException("Cannot delete " + src, safeMode); } if (enforcePermission && isPermissionEnabled) { checkPermission(src, false, null, FsAction.WRITE, null, FsAction.ALL); } // Unlink the target directory from directory tree if (!dir.delete(src, collectedBlocks)) { return false; } } // Log directory deletion to editlog getEditLog().logSync(); removeBlocks(collectedBlocks); // Incremental deletion of blocks collectedBlocks.clear(); if (NameNode.stateChangeLog.isDebugEnabled()) { NameNode.stateChangeLog.debug("DIR* Namesystem.delete: " + src + " is removed"); } return true; } /** From the given list, incrementally remove the blocks from blockManager */ private void removeBlocks(List<Block> blocks) { int start = 0; int end = 0; while (start < blocks.size()) { end = BLOCK_DELETION_INCREMENT + start; end = end > blocks.size() ? blocks.size() : end; synchronized (this) { for (int i = start; i < end; i++) { Block b = blocks.get(i); blocksMap.removeINode(b); corruptReplicas.removeFromCorruptReplicasMap(b); addToInvalidates(b); } } start = end; } } void removePathAndBlocks(String src, List<Block> blocks) { leaseManager.removeLeaseWithPrefixPath(src); if (blocks == null) { return; } removeBlocks(blocks); } /** Get the file info for a specific file. * @param src The string representation of the path to the file * @throws IOException if permission to access file is denied by the system * @return object containing information regarding the file * or null if file not found */ HdfsFileStatus getFileInfo(String src) throws IOException { if (isPermissionEnabled) { checkTraverse(src); } return dir.getFileInfo(src); } /** * Create all the necessary directories */ public boolean mkdirs(String src, PermissionStatus permissions ) throws IOException { boolean status = mkdirsInternal(src, permissions); getEditLog().logSync(); if (status && auditLog.isInfoEnabled() && isExternalInvocation()) { final HdfsFileStatus stat = dir.getFileInfo(src); logAuditEvent(UserGroupInformation.getCurrentUser(), Server.getRemoteIp(), "mkdirs", src, null, stat); } return status; } /** * Create all the necessary directories */ private synchronized boolean mkdirsInternal(String src, PermissionStatus permissions) throws IOException { NameNode.stateChangeLog.debug("DIR* NameSystem.mkdirs: " + src); if (isPermissionEnabled) { checkTraverse(src); } if (dir.isDir(src)) { // all the users of mkdirs() are used to expect 'true' even if // a new directory is not created. return true; } if (isInSafeMode()) throw new SafeModeException("Cannot create directory " + src, safeMode); if (!DFSUtil.isValidName(src)) { throw new IOException("Invalid directory name: " + src); } if (isPermissionEnabled) { checkAncestorAccess(src, FsAction.WRITE); } // validate that we have enough inodes. This is, at best, a // heuristic because the mkdirs() operation migth need to // create multiple inodes. checkFsObjectLimit(); if (!dir.mkdirs(src, permissions, false, now())) { throw new IOException("Invalid directory name: " + src); } return true; } ContentSummary getContentSummary(String src) throws IOException { if (isPermissionEnabled) { checkPermission(src, false, null, null, null, FsAction.READ_EXECUTE); } return dir.getContentSummary(src); } /** * Set the namespace quota and diskspace quota for a directory. * See {@link ClientProtocol#setQuota(String, long, long)} for the * contract. */ void setQuota(String path, long nsQuota, long dsQuota) throws IOException { synchronized (this) { if (isInSafeMode()) throw new SafeModeException("Cannot set quota on " + path, safeMode); if (isPermissionEnabled) { checkSuperuserPrivilege(); } dir.setQuota(path, nsQuota, dsQuota); } getEditLog().logSync(); } /** Persist all metadata about this file. * @param src The string representation of the path * @param clientName The string representation of the client * @throws IOException if path does not exist */ void fsync(String src, String clientName) throws IOException { NameNode.stateChangeLog.info("BLOCK* NameSystem.fsync: file " + src + " for " + clientName); synchronized (this) { if (isInSafeMode()) { throw new SafeModeException("Cannot fsync file " + src, safeMode); } INodeFileUnderConstruction pendingFile = checkLease(src, clientName); dir.persistBlocks(src, pendingFile); } getEditLog().logSync(); } /** * This is invoked when a lease expires. On lease expiry, * all the files that were written from that dfsclient should be * recovered. */ void internalReleaseLease(Lease lease, String src) throws IOException { if (lease.hasPath()) { // make a copy of the paths because internalReleaseLeaseOne removes // pathnames from the lease record. String[] leasePaths = new String[lease.getPaths().size()]; lease.getPaths().toArray(leasePaths); for (String p: leasePaths) { internalReleaseLeaseOne(lease, p); } } else { internalReleaseLeaseOne(lease, src); } } /** * Move a file that is being written to be immutable. * @param src The filename * @param lease The lease for the client creating the file */ void internalReleaseLeaseOne(Lease lease, String src) throws IOException { assert Thread.holdsLock(this); LOG.info("Recovering lease=" + lease + ", src=" + src); INodeFile iFile = dir.getFileINode(src); if (iFile == null) { final String message = "DIR* NameSystem.internalReleaseCreate: " + "attempt to release a create lock on " + src + " file does not exist."; NameNode.stateChangeLog.warn(message); throw new IOException(message); } if (!iFile.isUnderConstruction()) { final String message = "DIR* NameSystem.internalReleaseCreate: " + "attempt to release a create lock on " + src + " but file is already closed."; NameNode.stateChangeLog.warn(message); throw new IOException(message); } INodeFileUnderConstruction pendingFile = (INodeFileUnderConstruction) iFile; // Initialize lease recovery for pendingFile. If there are no blocks // associated with this file, then reap lease immediately. Otherwise // renew the lease and trigger lease recovery. if (pendingFile.getTargets() == null || pendingFile.getTargets().length == 0) { if (pendingFile.getBlocks().length == 0) { finalizeINodeFileUnderConstruction(src, pendingFile); NameNode.stateChangeLog.warn("BLOCK*" + " internalReleaseLease: No blocks found, lease removed for " + src); return; } // setup the Inode.targets for the last block from the blocksMap // Block[] blocks = pendingFile.getBlocks(); Block last = blocks[blocks.length-1]; DatanodeDescriptor[] targets = new DatanodeDescriptor[blocksMap.numNodes(last)]; Iterator<DatanodeDescriptor> it = blocksMap.nodeIterator(last); for (int i = 0; it != null && it.hasNext(); i++) { targets[i] = it.next(); } pendingFile.setTargets(targets); } // start lease recovery of the last block for this file. pendingFile.assignPrimaryDatanode(); Lease reassignedLease = reassignLease( lease, src, HdfsConstants.NN_RECOVERY_LEASEHOLDER, pendingFile); leaseManager.renewLease(reassignedLease); } private Lease reassignLease(Lease lease, String src, String newHolder, INodeFileUnderConstruction pendingFile) { if(newHolder == null) return lease; pendingFile.setClientName(newHolder); return leaseManager.reassignLease(lease, src, newHolder); } private void finalizeINodeFileUnderConstruction(String src, INodeFileUnderConstruction pendingFile) throws IOException { NameNode.stateChangeLog.info("Removing lease on file " + src + " from client " + pendingFile.clientName); leaseManager.removeLease(pendingFile.clientName, src); // The file is no longer pending. // Create permanent INode, update blockmap INodeFile newFile = pendingFile.convertToInodeFile(); dir.replaceNode(src, pendingFile, newFile); // close file and persist block allocations for this file dir.closeFile(src, newFile); checkReplicationFactor(newFile); } public void commitBlockSynchronization(Block lastblock, long newgenerationstamp, long newlength, boolean closeFile, boolean deleteblock, DatanodeID[] newtargets ) throws IOException { LOG.info("commitBlockSynchronization(lastblock=" + lastblock + ", newgenerationstamp=" + newgenerationstamp + ", newlength=" + newlength + ", newtargets=" + Arrays.asList(newtargets) + ", closeFile=" + closeFile + ", deleteBlock=" + deleteblock + ")"); String src = null; synchronized (this) { if (isInSafeMode()) { throw new SafeModeException("Cannot commitBlockSynchronization " + lastblock, safeMode); } final BlockInfo oldblockinfo = blocksMap.getStoredBlock(lastblock); if (oldblockinfo == null) { throw new IOException("Block (=" + lastblock + ") not found"); } INodeFile iFile = oldblockinfo.getINode(); if (!iFile.isUnderConstruction()) { throw new IOException("Unexpected block (=" + lastblock + ") since the file (=" + iFile.getLocalName() + ") is not under construction"); } INodeFileUnderConstruction pendingFile = (INodeFileUnderConstruction)iFile; // Remove old block from blocks map. This always have to be done // because the generation stamp of this block is changing. blocksMap.removeBlock(oldblockinfo); if (deleteblock) { pendingFile.removeBlock(lastblock); } else { // update last block, construct newblockinfo and add it to the blocks map lastblock.set(lastblock.getBlockId(), newlength, newgenerationstamp); final BlockInfo newblockinfo = blocksMap.addINode(lastblock, pendingFile); // find the DatanodeDescriptor objects // There should be no locations in the blocksMap till now because the // file is underConstruction DatanodeDescriptor[] descriptors = null; List<DatanodeDescriptor> descriptorsList = new ArrayList<DatanodeDescriptor>(newtargets.length); for(int i = 0; i < newtargets.length; i++) { DatanodeDescriptor node = datanodeMap.get(newtargets[i].getStorageID()); if (node != null) { if (closeFile) { // If we aren't closing the file, we shouldn't add it to the // block list for the node, since the block is still under // construction there. (in getAdditionalBlock, for example // we don't add to the block map for the targets) node.addBlock(newblockinfo); } descriptorsList.add(node); } else { LOG.error("commitBlockSynchronization included a target DN " + newtargets[i] + " which is not known to NN. Ignoring."); } } if (!descriptorsList.isEmpty()) { descriptors = descriptorsList.toArray(new DatanodeDescriptor[0]); } // add locations into the INodeUnderConstruction pendingFile.setLastBlock(newblockinfo, descriptors); } // If this commit does not want to close the file, persist // blocks (if durable sync is enabled) and return src = leaseManager.findPath(pendingFile); if (!closeFile) { if (durableSync) { dir.persistBlocks(src, pendingFile); getEditLog().logSync(); } LOG.info("commitBlockSynchronization(" + lastblock + ") successful"); return; } //remove lease, close file finalizeINodeFileUnderConstruction(src, pendingFile); } // end of synchronized section getEditLog().logSync(); LOG.info("commitBlockSynchronization(newblock=" + lastblock + ", file=" + src + ", newgenerationstamp=" + newgenerationstamp + ", newlength=" + newlength + ", newtargets=" + Arrays.asList(newtargets) + ") successful"); } /** * Renew the lease(s) held by the given client */ synchronized void renewLease(String holder) throws IOException { if (isInSafeMode()) throw new SafeModeException("Cannot renew lease for " + holder, safeMode); leaseManager.renewLease(holder); } /** * Get a partial listing of the indicated directory * * @param src the directory name * @param startAfter the name to start after * @return a partial listing starting after startAfter */ public DirectoryListing getListing(String src, byte[] startAfter) throws IOException { if (isPermissionEnabled) { if (dir.isDir(src)) { checkPathAccess(src, FsAction.READ_EXECUTE); } else { checkTraverse(src); } } if (auditLog.isInfoEnabled() && isExternalInvocation()) { logAuditEvent(UserGroupInformation.getCurrentUser(), Server.getRemoteIp(), "listStatus", src, null, null); } return dir.getListing(src, startAfter); } ///////////////////////////////////////////////////////// // // These methods are called by datanodes // ///////////////////////////////////////////////////////// /** * Register Datanode. * <p> * The purpose of registration is to identify whether the new datanode * serves a new data storage, and will report new data block copies, * which the namenode was not aware of; or the datanode is a replacement * node for the data storage that was previously served by a different * or the same (in terms of host:port) datanode. * The data storages are distinguished by their storageIDs. When a new * data storage is reported the namenode issues a new unique storageID. * <p> * Finally, the namenode returns its namespaceID as the registrationID * for the datanodes. * namespaceID is a persistent attribute of the name space. * The registrationID is checked every time the datanode is communicating * with the namenode. * Datanodes with inappropriate registrationID are rejected. * If the namenode stops, and then restarts it can restore its * namespaceID and will continue serving the datanodes that has previously * registered with the namenode without restarting the whole cluster. * * @see org.apache.hadoop.hdfs.server.datanode.DataNode#register() */ public synchronized void registerDatanode(DatanodeRegistration nodeReg ) throws IOException { String dnAddress = Server.getRemoteAddress(); if (dnAddress == null) { // Mostly called inside an RPC. // But if not, use address passed by the data-node. dnAddress = nodeReg.getHost(); } // check if the datanode is allowed to be connect to the namenode if (!verifyNodeRegistration(nodeReg, dnAddress)) { throw new DisallowedDatanodeException(nodeReg); } String hostName = nodeReg.getHost(); // update the datanode's name with ip:port DatanodeID dnReg = new DatanodeID(dnAddress + ":" + nodeReg.getPort(), nodeReg.getStorageID(), nodeReg.getInfoPort(), nodeReg.getIpcPort()); nodeReg.updateRegInfo(dnReg); nodeReg.exportedKeys = getBlockKeys(); NameNode.stateChangeLog.info( "BLOCK* NameSystem.registerDatanode: " + "node registration from " + nodeReg.getName() + " storage " + nodeReg.getStorageID()); DatanodeDescriptor nodeS = datanodeMap.get(nodeReg.getStorageID()); DatanodeDescriptor nodeN = host2DataNodeMap.getDatanodeByName(nodeReg.getName()); if (nodeN != null && nodeN != nodeS) { NameNode.LOG.info("BLOCK* NameSystem.registerDatanode: " + "node from name: " + nodeN.getName()); // nodeN previously served a different data storage, // which is not served by anybody anymore. removeDatanode(nodeN); // physically remove node from datanodeMap wipeDatanode(nodeN); nodeN = null; } if (nodeS != null) { if (nodeN == nodeS) { // The same datanode has been just restarted to serve the same data // storage. We do not need to remove old data blocks, the delta will // be calculated on the next block report from the datanode NameNode.stateChangeLog.debug("BLOCK* NameSystem.registerDatanode: " + "node restarted."); } else { // nodeS is found /* The registering datanode is a replacement node for the existing data storage, which from now on will be served by a new node. If this message repeats, both nodes might have same storageID by (insanely rare) random chance. User needs to restart one of the nodes with its data cleared (or user can just remove the StorageID value in "VERSION" file under the data directory of the datanode, but this is might not work if VERSION file format has changed */ NameNode.stateChangeLog.info( "BLOCK* NameSystem.registerDatanode: " + "node " + nodeS.getName() + " is replaced by " + nodeReg.getName() + " with the same storageID " + nodeReg.getStorageID()); } // update cluster map clusterMap.remove(nodeS); nodeS.updateRegInfo(nodeReg); nodeS.setHostName(hostName); // resolve network location resolveNetworkLocation(nodeS); clusterMap.add(nodeS); // also treat the registration message as a heartbeat synchronized(heartbeats) { if( !heartbeats.contains(nodeS)) { heartbeats.add(nodeS); //update its timestamp nodeS.updateHeartbeat(0L, 0L, 0L, 0); nodeS.isAlive = true; } } return; } // this is a new datanode serving a new data storage if (nodeReg.getStorageID().equals("")) { // this data storage has never been registered // it is either empty or was created by pre-storageID version of DFS nodeReg.storageID = newStorageID(); NameNode.stateChangeLog.debug( "BLOCK* NameSystem.registerDatanode: " + "new storageID " + nodeReg.getStorageID() + " assigned."); } // register new datanode DatanodeDescriptor nodeDescr = new DatanodeDescriptor(nodeReg, NetworkTopology.DEFAULT_RACK, hostName); resolveNetworkLocation(nodeDescr); unprotectedAddDatanode(nodeDescr); clusterMap.add(nodeDescr); // also treat the registration message as a heartbeat synchronized(heartbeats) { heartbeats.add(nodeDescr); nodeDescr.isAlive = true; // no need to update its timestamp // because its is done when the descriptor is created } if (safeMode != null) { safeMode.checkMode(); } return; } /* Resolve a node's network location */ private void resolveNetworkLocation (DatanodeDescriptor node) { List<String> names = new ArrayList<String>(1); if (dnsToSwitchMapping instanceof CachedDNSToSwitchMapping) { // get the node's IP address names.add(node.getHost()); } else { // get the node's host name String hostName = node.getHostName(); int colon = hostName.indexOf(":"); hostName = (colon==-1)?hostName:hostName.substring(0,colon); names.add(hostName); } // resolve its network location List<String> rName = dnsToSwitchMapping.resolve(names); String networkLocation; if (rName == null) { LOG.error("The resolve call returned null! Using " + NetworkTopology.DEFAULT_RACK + " for host " + names); networkLocation = NetworkTopology.DEFAULT_RACK; } else { networkLocation = rName.get(0); } node.setNetworkLocation(networkLocation); } /** * Get registrationID for datanodes based on the namespaceID. * * @see #registerDatanode(DatanodeRegistration) * @see FSImage#newNamespaceID() * @return registration ID */ public String getRegistrationID() { return Storage.getRegistrationID(dir.fsImage); } /** * Generate new storage ID. * * @return unique storage ID * * Note: that collisions are still possible if somebody will try * to bring in a data storage from a different cluster. */ private String newStorageID() { String newID = null; while(newID == null) { newID = "DS" + Integer.toString(r.nextInt()); if (datanodeMap.get(newID) != null) newID = null; } return newID; } private boolean isDatanodeDead(DatanodeDescriptor node) { return (node.getLastUpdate() < (now() - heartbeatExpireInterval)); } private void setDatanodeDead(DatanodeDescriptor node) { node.setLastUpdate(0); } /** * The given node has reported in. This method should: * 1) Record the heartbeat, so the datanode isn't timed out * 2) Adjust usage stats for future block allocation * * If a substantial amount of time passed since the last datanode * heartbeat then request an immediate block report. * * @return an array of datanode commands * @throws IOException */ DatanodeCommand[] handleHeartbeat(DatanodeRegistration nodeReg, long capacity, long dfsUsed, long remaining, int xceiverCount, int xmitsInProgress) throws IOException { DatanodeCommand cmd = null; synchronized (heartbeats) { synchronized (datanodeMap) { DatanodeDescriptor nodeinfo = null; try { nodeinfo = getDatanode(nodeReg); } catch(UnregisteredDatanodeException e) { return new DatanodeCommand[]{DatanodeCommand.REGISTER}; } // Check if this datanode should actually be shutdown instead. if (nodeinfo != null && shouldNodeShutdown(nodeinfo)) { setDatanodeDead(nodeinfo); throw new DisallowedDatanodeException(nodeinfo); } if (nodeinfo == null || !nodeinfo.isAlive) { return new DatanodeCommand[]{DatanodeCommand.REGISTER}; } updateStats(nodeinfo, false); nodeinfo.updateHeartbeat(capacity, dfsUsed, remaining, xceiverCount); updateStats(nodeinfo, true); //check lease recovery cmd = nodeinfo.getLeaseRecoveryCommand(Integer.MAX_VALUE); if (cmd != null) { return new DatanodeCommand[] {cmd}; } ArrayList<DatanodeCommand> cmds = new ArrayList<DatanodeCommand>(); //check pending replication cmd = nodeinfo.getReplicationCommand( maxReplicationStreams - xmitsInProgress); if (cmd != null) { cmds.add(cmd); } //check block invalidation cmd = nodeinfo.getInvalidateBlocks(blockInvalidateLimit); if (cmd != null) { cmds.add(cmd); } // check access key update if (isAccessTokenEnabled && nodeinfo.needKeyUpdate) { cmds.add(new KeyUpdateCommand(accessTokenHandler.exportKeys())); nodeinfo.needKeyUpdate = false; } // check for balancer bandwidth update if (nodeinfo.getBalancerBandwidth() > 0) { cmds.add(new BalancerBandwidthCommand(nodeinfo.getBalancerBandwidth())); // set back to 0 to indicate that datanode has been sent the new value nodeinfo.setBalancerBandwidth(0); } if (!cmds.isEmpty()) { return cmds.toArray(new DatanodeCommand[cmds.size()]); } } } //check distributed upgrade cmd = getDistributedUpgradeCommand(); if (cmd != null) { return new DatanodeCommand[] {cmd}; } return null; } private void updateStats(DatanodeDescriptor node, boolean isAdded) { // // The statistics are protected by the heartbeat lock // assert(Thread.holdsLock(heartbeats)); if (isAdded) { capacityTotal += node.getCapacity(); capacityUsed += node.getDfsUsed(); capacityRemaining += node.getRemaining(); totalLoad += node.getXceiverCount(); } else { capacityTotal -= node.getCapacity(); capacityUsed -= node.getDfsUsed(); capacityRemaining -= node.getRemaining(); totalLoad -= node.getXceiverCount(); } } /** * Update access keys. */ void updateAccessKey() throws IOException { this.accessTokenHandler.updateKeys(); synchronized (heartbeats) { for (DatanodeDescriptor nodeInfo : heartbeats) { nodeInfo.needKeyUpdate = true; } } } /** * Periodically calls heartbeatCheck() and updateAccessKey() */ class HeartbeatMonitor implements Runnable { private long lastHeartbeatCheck; private long lastAccessKeyUpdate; /** */ public void run() { while (fsRunning) { try { long now = now(); if (lastHeartbeatCheck + heartbeatRecheckInterval < now) { heartbeatCheck(); lastHeartbeatCheck = now; } if (isAccessTokenEnabled && (lastAccessKeyUpdate + accessKeyUpdateInterval < now)) { updateAccessKey(); lastAccessKeyUpdate = now; } } catch (Exception e) { FSNamesystem.LOG.error(StringUtils.stringifyException(e)); } try { Thread.sleep(5000); // 5 seconds } catch (InterruptedException ie) { } } } } /** * Periodically calls computeReplicationWork(). */ class ReplicationMonitor implements Runnable { ReplicateQueueProcessingStats replicateQueueStats = new ReplicateQueueProcessingStats(); InvalidateQueueProcessingStats invalidateQueueStats = new InvalidateQueueProcessingStats(); public void run() { while (fsRunning) { try { computeDatanodeWork(); processPendingReplications(); Thread.sleep(replicationRecheckInterval); } catch (InterruptedException ie) { LOG.warn("ReplicationMonitor thread received InterruptedException." + ie); break; } catch (IOException ie) { LOG.warn("ReplicationMonitor thread received exception. " + ie + " " + StringUtils.stringifyException(ie)); } catch (Throwable t) { LOG.warn("ReplicationMonitor thread received Runtime exception. " + t + " " + StringUtils.stringifyException(t)); Runtime.getRuntime().exit(-1); } } } /** * Just before exiting safe mode, {@link SafeModeInfo.leave()} scans all * blocks and identifies under-replicated and invalid blocks. These are * placed in work queues. Immediately after leaving safe mode, * {@link ReplicationMonitor} starts processing these queues via calls to * {@link #computeDatanodeWork()}. Each call does a chunk of work, then * waits 3 seconds before doing the next chunk of work, to avoid monopolizing * the CPUs and the global lock. It may take several cycles before the * queue is completely flushed. * * Here we use two concrete subclasses of {@link QueueProcessingStatistics} * to collect stats about these processes. */ private class ReplicateQueueProcessingStats extends QueueProcessingStatistics { ReplicateQueueProcessingStats() { super("ReplicateQueue", "blocks", FSNamesystem.LOG); } // @see org.apache.hadoop.hdfs.server.namenode.FSNamesystem.QueueProcessingStatistics#preCheckIsLastCycle(int) @Override public boolean preCheckIsLastCycle(int maxWorkToProcess) { return (maxWorkToProcess >= neededReplications.size()); } // @see org.apache.hadoop.hdfs.server.namenode.FSNamesystem.QueueProcessingStatistics#postCheckIsLastCycle(int) @Override public boolean postCheckIsLastCycle(int workFound) { return false; } } private class InvalidateQueueProcessingStats extends QueueProcessingStatistics { InvalidateQueueProcessingStats() { super("InvalidateQueue", "blocks", FSNamesystem.LOG); } // @see org.apache.hadoop.hdfs.server.namenode.FSNamesystem.QueueProcessingStatistics#preCheckIsLastCycle(int) @Override public boolean preCheckIsLastCycle(int maxWorkToProcess) { return false; } // @see org.apache.hadoop.hdfs.server.namenode.FSNamesystem.QueueProcessingStatistics#postCheckIsLastCycle(int) @Override public boolean postCheckIsLastCycle(int workFound) { return recentInvalidateSets.isEmpty(); } } } ///////////////////////////////////////////////////////// // // These methods are called by the Namenode system, to see // if there is any work for registered datanodes. // ///////////////////////////////////////////////////////// /** * Compute block replication and block invalidation work * that can be scheduled on data-nodes. * The datanode will be informed of this work at the next heartbeat. * * @return number of blocks scheduled for replication or removal. */ public int computeDatanodeWork() throws IOException { int replicationWorkFound = 0; int invalidationWorkFound = 0; int blocksToProcess = 0; int nodesToProcess = 0; // blocks should not be replicated or removed if safe mode is on if (isInSafeMode()) { replmon.replicateQueueStats.checkRestart(); replmon.invalidateQueueStats.checkRestart(); return 0; } synchronized(heartbeats) { blocksToProcess = (int)(heartbeats.size() * this.blocksReplWorkMultiplier); nodesToProcess = (int)Math.ceil((double)heartbeats.size() * this.blocksInvalidateWorkPct); } replmon.replicateQueueStats.startCycle(blocksToProcess); replicationWorkFound = computeReplicationWork(blocksToProcess); replmon.replicateQueueStats.endCycle(replicationWorkFound); // Update FSNamesystemMetrics counters synchronized (this) { pendingReplicationBlocksCount = pendingReplications.size(); underReplicatedBlocksCount = neededReplications.size(); scheduledReplicationBlocksCount = replicationWorkFound; corruptReplicaBlocksCount = corruptReplicas.size(); } replmon.invalidateQueueStats.startCycle(nodesToProcess); invalidationWorkFound = computeInvalidateWork(nodesToProcess); replmon.invalidateQueueStats.endCycle(invalidationWorkFound); return replicationWorkFound + invalidationWorkFound; } /** * Schedule blocks for deletion at datanodes * @param nodesToProcess number of datanodes to schedule deletion work * @return total number of block for deletion */ int computeInvalidateWork(int nodesToProcess) { int numOfNodes = 0; ArrayList<String> keyArray; synchronized (this) { numOfNodes = recentInvalidateSets.size(); // get an array of the keys keyArray = new ArrayList<String>(recentInvalidateSets.keySet()); } nodesToProcess = Math.min(numOfNodes, nodesToProcess); // randomly pick up <i>nodesToProcess</i> nodes // and put them at [0, nodesToProcess) int remainingNodes = numOfNodes - nodesToProcess; if (nodesToProcess < remainingNodes) { for(int i=0; i<nodesToProcess; i++) { int keyIndex = r.nextInt(numOfNodes-i)+i; Collections.swap(keyArray, keyIndex, i); // swap to front } } else { for(int i=0; i<remainingNodes; i++) { int keyIndex = r.nextInt(numOfNodes-i); Collections.swap(keyArray, keyIndex, numOfNodes-i-1); // swap to end } } int blockCnt = 0; for(int nodeCnt = 0; nodeCnt < nodesToProcess; nodeCnt++ ) { blockCnt += invalidateWorkForOneNode(keyArray.get(nodeCnt)); } return blockCnt; } /** * Scan blocks in {@link #neededReplications} and assign replication * work to data-nodes they belong to. * * The number of process blocks equals either twice the number of live * data-nodes or the number of under-replicated blocks whichever is less. * * @return number of blocks scheduled for replication during this iteration. */ private int computeReplicationWork( int blocksToProcess) throws IOException { // stall only useful for unit tests (see TestFileAppend4.java) if (stallReplicationWork) { return 0; } // Choose the blocks to be replicated List<List<Block>> blocksToReplicate = chooseUnderReplicatedBlocks(blocksToProcess); // replicate blocks int scheduledReplicationCount = 0; for (int i=0; i<blocksToReplicate.size(); i++) { for(Block block : blocksToReplicate.get(i)) { if (computeReplicationWorkForBlock(block, i)) { scheduledReplicationCount++; } } } return scheduledReplicationCount; } /** Get a list of block lists to be replicated * The index of block lists represents the * * @param blocksToProcess * @return Return a list of block lists to be replicated. * The block list index represents its replication priority. */ synchronized List<List<Block>> chooseUnderReplicatedBlocks(int blocksToProcess) { // initialize data structure for the return value List<List<Block>> blocksToReplicate = new ArrayList<List<Block>>(UnderReplicatedBlocks.LEVEL); for (int i=0; i<UnderReplicatedBlocks.LEVEL; i++) { blocksToReplicate.add(new ArrayList<Block>()); } synchronized(neededReplications) { if (neededReplications.size() == 0) { missingBlocksInCurIter = 0; missingBlocksInPrevIter = 0; return blocksToReplicate; } // Go through all blocks that need replications. BlockIterator neededReplicationsIterator = neededReplications.iterator(); // skip to the first unprocessed block, which is at replIndex for(int i=0; i < replIndex && neededReplicationsIterator.hasNext(); i++) { neededReplicationsIterator.next(); } // # of blocks to process equals either twice the number of live // data-nodes or the number of under-replicated blocks whichever is less blocksToProcess = Math.min(blocksToProcess, neededReplications.size()); for (int blkCnt = 0; blkCnt < blocksToProcess; blkCnt++, replIndex++) { if( ! neededReplicationsIterator.hasNext()) { // start from the beginning replIndex = 0; missingBlocksInPrevIter = missingBlocksInCurIter; missingBlocksInCurIter = 0; blocksToProcess = Math.min(blocksToProcess, neededReplications.size()); if(blkCnt >= blocksToProcess) break; neededReplicationsIterator = neededReplications.iterator(); assert neededReplicationsIterator.hasNext() : "neededReplications should not be empty."; } Block block = neededReplicationsIterator.next(); int priority = neededReplicationsIterator.getPriority(); if (priority < 0 || priority >= blocksToReplicate.size()) { LOG.warn("Unexpected replication priority: " + priority + " " + block); } else { blocksToReplicate.get(priority).add(block); } } // end for } // end synchronized return blocksToReplicate; } /** Replicate a block * * @param block block to be replicated * @param priority a hint of its priority in the neededReplication queue * @return if the block gets replicated or not */ boolean computeReplicationWorkForBlock(Block block, int priority) { int requiredReplication, numEffectiveReplicas; List<DatanodeDescriptor> containingNodes; DatanodeDescriptor srcNode; INodeFile fileINode = null; synchronized (this) { synchronized (neededReplications) { // block should belong to a file fileINode = blocksMap.getINode(block); // abandoned block or block reopened for append if(fileINode == null || fileINode.isUnderConstruction()) { neededReplications.remove(block, priority); // remove from neededReplications replIndex--; return false; } requiredReplication = fileINode.getReplication(); // get a source data-node containingNodes = new ArrayList<DatanodeDescriptor>(); NumberReplicas numReplicas = new NumberReplicas(); srcNode = chooseSourceDatanode(block, containingNodes, numReplicas); if ((numReplicas.liveReplicas() + numReplicas.decommissionedReplicas()) <= 0) { missingBlocksInCurIter++; } if(srcNode == null) // block can not be replicated from any node return false; // do not schedule more if enough replicas is already pending numEffectiveReplicas = numReplicas.liveReplicas() + pendingReplications.getNumReplicas(block); if(numEffectiveReplicas >= requiredReplication) { neededReplications.remove(block, priority); // remove from neededReplications replIndex--; NameNode.stateChangeLog.info("BLOCK* " + "Removing block " + block + " from neededReplications as it has enough replicas."); return false; } } } // choose replication targets: NOT HOLDING THE GLOBAL LOCK // It is costly to extract the filename for which chooseTargets is called, // so for now we pass in the Inode itself. DatanodeDescriptor targets[] = replicator.chooseTarget(fileINode, requiredReplication - numEffectiveReplicas, srcNode, containingNodes, block.getNumBytes()); if(targets.length == 0) return false; synchronized (this) { synchronized (neededReplications) { // Recheck since global lock was released // block should belong to a file fileINode = blocksMap.getINode(block); // abandoned block or block reopened for append if(fileINode == null || fileINode.isUnderConstruction()) { neededReplications.remove(block, priority); // remove from neededReplications replIndex--; return false; } requiredReplication = fileINode.getReplication(); // do not schedule more if enough replicas is already pending NumberReplicas numReplicas = countNodes(block); numEffectiveReplicas = numReplicas.liveReplicas() + pendingReplications.getNumReplicas(block); if(numEffectiveReplicas >= requiredReplication) { neededReplications.remove(block, priority); // remove from neededReplications replIndex--; NameNode.stateChangeLog.info("BLOCK* " + "Removing block " + block + " from neededReplications as it has enough replicas."); return false; } // Add block to the to be replicated list srcNode.addBlockToBeReplicated(block, targets); for (DatanodeDescriptor dn : targets) { dn.incBlocksScheduled(); } // Move the block-replication into a "pending" state. // The reason we use 'pending' is so we can retry // replications that fail after an appropriate amount of time. pendingReplications.add(block, targets.length); NameNode.stateChangeLog.debug( "BLOCK* block " + block + " is moved from neededReplications to pendingReplications"); // remove from neededReplications if(numEffectiveReplicas + targets.length >= requiredReplication) { neededReplications.remove(block, priority); // remove from neededReplications replIndex--; } if (NameNode.stateChangeLog.isInfoEnabled()) { StringBuffer targetList = new StringBuffer("datanode(s)"); for (int k = 0; k < targets.length; k++) { targetList.append(' '); targetList.append(targets[k].getName()); } NameNode.stateChangeLog.info( "BLOCK* ask " + srcNode.getName() + " to replicate " + block + " to " + targetList); NameNode.stateChangeLog.debug( "BLOCK* neededReplications = " + neededReplications.size() + " pendingReplications = " + pendingReplications.size()); } } } return true; } /** Choose a datanode near to the given address. */ public DatanodeInfo chooseDatanode(String srcPath, String address, long blocksize) { final DatanodeDescriptor clientNode = host2DataNodeMap.getDatanodeByHost( address); if (clientNode != null) { HashMap<Node,Node> excludedNodes = null; final DatanodeDescriptor[] datanodes = replicator.chooseTarget( srcPath, 1, clientNode, excludedNodes, blocksize); if (datanodes.length > 0) { return datanodes[0]; } } return null; } /** * Parse the data-nodes the block belongs to and choose one, * which will be the replication source. * * We prefer nodes that are in DECOMMISSION_INPROGRESS state to other nodes * since the former do not have write traffic and hence are less busy. * We do not use already decommissioned nodes as a source. * Otherwise we choose a random node among those that did not reach their * replication limit. * * In addition form a list of all nodes containing the block * and calculate its replication numbers. */ private DatanodeDescriptor chooseSourceDatanode( Block block, List<DatanodeDescriptor> containingNodes, NumberReplicas numReplicas) { containingNodes.clear(); DatanodeDescriptor srcNode = null; int live = 0; int decommissioned = 0; int corrupt = 0; int excess = 0; Iterator<DatanodeDescriptor> it = blocksMap.nodeIterator(block); Collection<DatanodeDescriptor> nodesCorrupt = corruptReplicas.getNodes(block); while(it.hasNext()) { DatanodeDescriptor node = it.next(); Collection<Block> excessBlocks = excessReplicateMap.get(node.getStorageID()); if ((nodesCorrupt != null) && (nodesCorrupt.contains(node))) corrupt++; else if (node.isDecommissionInProgress() || node.isDecommissioned()) decommissioned++; else if (excessBlocks != null && excessBlocks.contains(block)) { excess++; } else { live++; } containingNodes.add(node); // Check if this replica is corrupt // If so, do not select the node as src node if ((nodesCorrupt != null) && nodesCorrupt.contains(node)) continue; if(node.getNumberOfBlocksToBeReplicated() >= maxReplicationStreams) continue; // already reached replication limit // the block must not be scheduled for removal on srcNode if(excessBlocks != null && excessBlocks.contains(block)) continue; // never use already decommissioned nodes if(node.isDecommissioned()) continue; // we prefer nodes that are in DECOMMISSION_INPROGRESS state if(node.isDecommissionInProgress() || srcNode == null) { srcNode = node; continue; } if(srcNode.isDecommissionInProgress()) continue; // switch to a different node randomly // this to prevent from deterministically selecting the same node even // if the node failed to replicate the block on previous iterations if(r.nextBoolean()) srcNode = node; } if(numReplicas != null) numReplicas.initialize(live, decommissioned, corrupt, excess); return srcNode; } /** * Get blocks to invalidate for <i>nodeId</i> * in {@link #recentInvalidateSets}. * * @return number of blocks scheduled for removal during this iteration. */ private synchronized int invalidateWorkForOneNode(String nodeId) { // blocks should not be replicated or removed if safe mode is on if (isInSafeMode()) return 0; // get blocks to invalidate for the nodeId assert nodeId != null; DatanodeDescriptor dn = datanodeMap.get(nodeId); if (dn == null) { recentInvalidateSets.remove(nodeId); return 0; } Collection<Block> invalidateSet = recentInvalidateSets.get(nodeId); if (invalidateSet == null) { return 0; } ArrayList<Block> blocksToInvalidate = new ArrayList<Block>(blockInvalidateLimit); // # blocks that can be sent in one message is limited Iterator<Block> it = invalidateSet.iterator(); for(int blkCount = 0; blkCount < blockInvalidateLimit && it.hasNext(); blkCount++) { blocksToInvalidate.add(it.next()); it.remove(); } // If we send everything in this message, remove this node entry if (!it.hasNext()) { recentInvalidateSets.remove(nodeId); } dn.addBlocksToBeInvalidated(blocksToInvalidate); if(NameNode.stateChangeLog.isInfoEnabled()) { StringBuffer blockList = new StringBuffer(); for(Block blk : blocksToInvalidate) { blockList.append(' '); blockList.append(blk); } NameNode.stateChangeLog.info("BLOCK* ask " + dn.getName() + " to delete " + blockList); } pendingDeletionBlocksCount -= blocksToInvalidate.size(); return blocksToInvalidate.size(); } public void setNodeReplicationLimit(int limit) { this.maxReplicationStreams = limit; } /** * If there were any replication requests that timed out, reap them * and put them back into the neededReplication queue */ void processPendingReplications() { Block[] timedOutItems = pendingReplications.getTimedOutBlocks(); if (timedOutItems != null) { synchronized (this) { for (int i = 0; i < timedOutItems.length; i++) { NumberReplicas num = countNodes(timedOutItems[i]); neededReplications.add(timedOutItems[i], num.liveReplicas(), num.decommissionedReplicas(), getReplication(timedOutItems[i])); } } /* If we know the target datanodes where the replication timedout, * we could invoke decBlocksScheduled() on it. Its ok for now. */ } } /** * remove a datanode descriptor * @param nodeID datanode ID */ synchronized public void removeDatanode(DatanodeID nodeID) throws IOException { DatanodeDescriptor nodeInfo = getDatanode(nodeID); if (nodeInfo != null) { removeDatanode(nodeInfo); } else { NameNode.stateChangeLog.warn("BLOCK* NameSystem.removeDatanode: " + nodeID.getName() + " does not exist"); } } /** * remove a datanode descriptor * @param nodeInfo datanode descriptor */ private void removeDatanode(DatanodeDescriptor nodeInfo) { synchronized (heartbeats) { if (nodeInfo.isAlive) { updateStats(nodeInfo, false); heartbeats.remove(nodeInfo); nodeInfo.isAlive = false; } } for (Iterator<Block> it = nodeInfo.getBlockIterator(); it.hasNext();) { removeStoredBlock(it.next(), nodeInfo); } unprotectedRemoveDatanode(nodeInfo); clusterMap.remove(nodeInfo); if (safeMode != null) { safeMode.checkMode(); } } void unprotectedRemoveDatanode(DatanodeDescriptor nodeDescr) { nodeDescr.resetBlocks(); removeFromInvalidates(nodeDescr.getStorageID()); NameNode.stateChangeLog.debug( "BLOCK* NameSystem.unprotectedRemoveDatanode: " + nodeDescr.getName() + " is out of service now."); } void unprotectedAddDatanode(DatanodeDescriptor nodeDescr) { /* To keep host2DataNodeMap consistent with datanodeMap, remove from host2DataNodeMap the datanodeDescriptor removed from datanodeMap before adding nodeDescr to host2DataNodeMap. */ host2DataNodeMap.remove( datanodeMap.put(nodeDescr.getStorageID(), nodeDescr)); host2DataNodeMap.add(nodeDescr); NameNode.stateChangeLog.debug( "BLOCK* NameSystem.unprotectedAddDatanode: " + "node " + nodeDescr.getName() + " is added to datanodeMap."); } /** * Physically remove node from datanodeMap. * * @param nodeID node */ void wipeDatanode(DatanodeID nodeID) throws IOException { String key = nodeID.getStorageID(); host2DataNodeMap.remove(datanodeMap.remove(key)); NameNode.stateChangeLog.debug( "BLOCK* NameSystem.wipeDatanode: " + nodeID.getName() + " storage " + key + " is removed from datanodeMap."); } FSImage getFSImage() { return dir.fsImage; } FSEditLog getEditLog() { return getFSImage().getEditLog(); } /** * Check if there are any expired heartbeats, and if so, * whether any blocks have to be re-replicated. * While removing dead datanodes, make sure that only one datanode is marked * dead at a time within the synchronized section. Otherwise, a cascading * effect causes more datanodes to be declared dead. */ void heartbeatCheck() { if (isInSafeMode()) { // not to check dead nodes if in safemode return; } boolean allAlive = false; while (!allAlive) { boolean foundDead = false; DatanodeID dead = null; // check the number of stale nodes int numOfStaleNodes = 0; // locate the first dead node. If need to check stale nodes, // also count the number of stale nodes synchronized (heartbeats) { for (Iterator<DatanodeDescriptor> it = heartbeats.iterator(); it .hasNext();) { DatanodeDescriptor nodeInfo = it.next(); if (dead == null && isDatanodeDead(nodeInfo)) { foundDead = true; dead = nodeInfo; if (!this.checkForStaleDataNodes) { break; } } if (this.checkForStaleDataNodes && nodeInfo.isStale(this.staleInterval)) { numOfStaleNodes++; } } // Change whether to avoid using stale datanodes for writing // based on proportion of stale datanodes if (this.checkForStaleDataNodes) { this.numStaleNodes = numOfStaleNodes; if (numOfStaleNodes > heartbeats.size() * this.ratioUseStaleDataNodesForWrite) { this.avoidStaleDataNodesForWrite = false; } else { if (this.initialAvoidWriteStaleNodes) { this.avoidStaleDataNodesForWrite = true; } } } } // acquire the fsnamesystem lock, and then remove the dead node. if (foundDead) { synchronized (this) { synchronized(heartbeats) { synchronized (datanodeMap) { DatanodeDescriptor nodeInfo = null; try { nodeInfo = getDatanode(dead); } catch (IOException e) { nodeInfo = null; } if (nodeInfo != null && isDatanodeDead(nodeInfo)) { NameNode.stateChangeLog.info("BLOCK* NameSystem.heartbeatCheck: " + "lost heartbeat from " + nodeInfo.getName()); removeDatanode(nodeInfo); } } } } } allAlive = !foundDead; } } /** * Log a rejection of an addStoredBlock RPC, invalidate the reported block, * and return it. */ private Block rejectAddStoredBlock(Block block, DatanodeDescriptor node, String msg) { NameNode.stateChangeLog.info("BLOCK* NameSystem.addStoredBlock: " + "addStoredBlock request received for " + block + " on " + node.getName() + " size " + block.getNumBytes() + " but was rejected: " + msg); addToInvalidates(block, node); return block; } /** * It will update the targets for INodeFileUnderConstruction * * @param nodeID * - DataNode ID * @param blocksBeingWritten * - list of blocks which are still inprogress. * @throws IOException */ public synchronized void processBlocksBeingWrittenReport(DatanodeID nodeID, BlockListAsLongs blocksBeingWritten) throws IOException { DatanodeDescriptor dataNode = getDatanode(nodeID); if (dataNode == null) { throw new IOException("ProcessReport from unregistered node: " + nodeID.getName()); } // Check if this datanode should actually be shutdown instead. if (shouldNodeShutdown(dataNode)) { setDatanodeDead(dataNode); throw new DisallowedDatanodeException(dataNode); } Block block = new Block(); for (int i = 0; i < blocksBeingWritten.getNumberOfBlocks(); i++) { block.set(blocksBeingWritten.getBlockId(i), blocksBeingWritten .getBlockLen(i), blocksBeingWritten.getBlockGenStamp(i)); BlockInfo storedBlock = blocksMap.getStoredBlockWithoutMatchingGS(block); if (storedBlock == null) { rejectAddStoredBlock(new Block(block), dataNode, "Block not in blockMap with any generation stamp"); continue; } INodeFile inode = storedBlock.getINode(); if (inode == null) { rejectAddStoredBlock(new Block(block), dataNode, "Block does not correspond to any file"); continue; } boolean underConstruction = inode.isUnderConstruction(); boolean isLastBlock = inode.getLastBlock() != null && inode.getLastBlock().getBlockId() == block.getBlockId(); // Must be the last block of a file under construction, if (!underConstruction) { rejectAddStoredBlock(new Block(block), dataNode, "Reported as block being written but is a block of closed file."); continue; } if (!isLastBlock) { rejectAddStoredBlock(new Block(block), dataNode, "Reported as block being written but not the last block of " + "an under-construction file."); continue; } INodeFileUnderConstruction pendingFile = (INodeFileUnderConstruction) inode; pendingFile.addTarget(dataNode); incrementSafeBlockCount(pendingFile.getTargets().length); } } /** * The given node is reporting all its blocks. Use this info to * update the (machine-->blocklist) and (block-->machinelist) tables. */ public synchronized void processReport(DatanodeID nodeID, BlockListAsLongs newReport ) throws IOException { long startTime = now(); if (NameNode.stateChangeLog.isDebugEnabled()) { NameNode.stateChangeLog.debug("BLOCK* NameSystem.processReport: " + "from " + nodeID.getName()+" " + newReport.getNumberOfBlocks()+" blocks"); } DatanodeDescriptor node = getDatanode(nodeID); if (node == null || !node.isAlive) { throw new IOException("ProcessReport from dead or unregisterted node: " + nodeID.getName()); } // Check if this datanode should actually be shutdown instead. if (shouldNodeShutdown(node)) { setDatanodeDead(node); throw new DisallowedDatanodeException(node); } // To minimize startup time, we discard any second (or later) block reports // that we receive while still in startup phase. if (isInStartupSafeMode() && !node.firstBlockReport()) { NameNode.stateChangeLog.info("BLOCK* NameSystem.processReport: " + "discarded non-initial block report from " + nodeID.getName() + " because namenode still in startup phase"); return; } // // Modify the (block-->datanode) map, according to the difference // between the old and new block report. // Collection<Block> toAdd = new LinkedList<Block>(); Collection<Block> toRemove = new LinkedList<Block>(); Collection<Block> toInvalidate = new LinkedList<Block>(); node.reportDiff(blocksMap, newReport, toAdd, toRemove, toInvalidate); for (Block b : toRemove) { removeStoredBlock(b, node); } for (Block b : toAdd) { addStoredBlock(b, node, null); } for (Block b : toInvalidate) { NameNode.stateChangeLog.info("BLOCK* NameSystem.processReport: block " + b + " on " + node.getName() + " size " + b.getNumBytes() + " does not belong to any file."); addToInvalidates(b, node); } long endTime = now(); NameNode.getNameNodeMetrics().addBlockReport(endTime - startTime); NameNode.stateChangeLog.info("*BLOCK* NameSystem.processReport: from " + nodeID.getName() + ", blocks: " + newReport.getNumberOfBlocks() + ", processing time: " + (endTime - startTime) + " msecs"); node.processedBlockReport(); } /** * Modify (block-->datanode) map. Remove block from set of * needed replications if this takes care of the problem. * @return the block that is stored in blockMap. */ synchronized Block addStoredBlock(Block block, DatanodeDescriptor node, DatanodeDescriptor delNodeHint) { BlockInfo storedBlock = blocksMap.getStoredBlock(block); if (storedBlock == null) { // If we have a block in the block map with the same ID, but a different // generation stamp, and the corresponding file is under construction, // then we need to do some special processing. storedBlock = blocksMap.getStoredBlockWithoutMatchingGS(block); if (storedBlock == null) { return rejectAddStoredBlock( block, node, "Block not in blockMap with any generation stamp"); } INodeFile inode = storedBlock.getINode(); if (inode == null) { return rejectAddStoredBlock( block, node, "Block does not correspond to any file"); } boolean reportedOldGS = block.getGenerationStamp() < storedBlock.getGenerationStamp(); boolean reportedNewGS = block.getGenerationStamp() > storedBlock.getGenerationStamp(); boolean underConstruction = inode.isUnderConstruction(); boolean isLastBlock = inode.getLastBlock() != null && inode.getLastBlock().getBlockId() == block.getBlockId(); // We can report a stale generation stamp for the last block under construction, // we just need to make sure it ends up in targets. if (reportedOldGS && !(underConstruction && isLastBlock)) { return rejectAddStoredBlock( block, node, "Reported block has old generation stamp but is not the last block of " + "an under-construction file. (current generation is " + storedBlock.getGenerationStamp() + ")"); } // Don't add blocks to the DN when they're part of the in-progress last block // and have an inconsistent generation stamp. Instead just add them to targets // for recovery purposes. They will get added to the node when // commitBlockSynchronization runs if (underConstruction && isLastBlock && (reportedOldGS || reportedNewGS)) { NameNode.stateChangeLog.info( "BLOCK* NameSystem.addStoredBlock: " + "Targets updated: block " + block + " on " + node.getName() + " is added as a target for block " + storedBlock + " with size " + block.getNumBytes()); ((INodeFileUnderConstruction)inode).addTarget(node); return block; } } INodeFile fileINode = storedBlock.getINode(); if (fileINode == null) { return rejectAddStoredBlock( block, node, "Block does not correspond to any file"); } assert storedBlock != null : "Block must be stored by now"; // add block to the data-node boolean added = node.addBlock(storedBlock); // Is the block being reported the last block of an underconstruction file? boolean blockUnderConstruction = false; if (fileINode.isUnderConstruction()) { INodeFileUnderConstruction cons = (INodeFileUnderConstruction) fileINode; Block last = fileINode.getLastBlock(); if (last == null) { // This should never happen, but better to handle it properly than to throw // an NPE below. LOG.error("Null blocks for reported block=" + block + " stored=" + storedBlock + " inode=" + fileINode); return block; } blockUnderConstruction = last.equals(storedBlock); } // block == storedBlock when this addStoredBlock is the result of a block report if (block != storedBlock) { if (block.getNumBytes() >= 0) { long cursize = storedBlock.getNumBytes(); INodeFile file = storedBlock.getINode(); if (cursize == 0) { storedBlock.setNumBytes(block.getNumBytes()); } else if (cursize != block.getNumBytes()) { LOG.warn("Inconsistent size for block " + block + " reported from " + node.getName() + " current size is " + cursize + " reported size is " + block.getNumBytes()); try { if (cursize > block.getNumBytes() && !blockUnderConstruction) { // new replica is smaller in size than existing block. // Mark the new replica as corrupt. LOG.warn("Mark new replica " + block + " from " + node.getName() + "as corrupt because its length is shorter than existing ones"); markBlockAsCorrupt(block, node); } else { // new replica is larger in size than existing block. if (!blockUnderConstruction) { // Mark pre-existing replicas as corrupt. int numNodes = blocksMap.numNodes(block); int count = 0; DatanodeDescriptor nodes[] = new DatanodeDescriptor[numNodes]; Iterator<DatanodeDescriptor> it = blocksMap.nodeIterator(block); for (; it != null && it.hasNext();) { DatanodeDescriptor dd = it.next(); if (!dd.equals(node)) { nodes[count++] = dd; } } for (int j = 0; j < count; j++) { LOG.warn("Mark existing replica " + block + " from " + node.getName() + " as corrupt because its length is shorter than the new one"); markBlockAsCorrupt(block, nodes[j]); } } // // change the size of block in blocksMap // storedBlock.setNumBytes(block.getNumBytes()); } } catch (IOException e) { LOG.warn("Error in deleting bad block " + block + e); } } //Updated space consumed if required. long diff = (file == null) ? 0 : (file.getPreferredBlockSize() - storedBlock.getNumBytes()); if (diff > 0 && file.isUnderConstruction() && cursize < storedBlock.getNumBytes()) { try { String path = /* For finding parents */ leaseManager.findPath((INodeFileUnderConstruction)file); dir.updateSpaceConsumed(path, 0, -diff*file.getReplication()); } catch (IOException e) { LOG.warn("Unexpected exception while updating disk space : " + e.getMessage()); } } } block = storedBlock; } assert storedBlock == block : "Block must be stored by now"; int curReplicaDelta = 0; if (added) { curReplicaDelta = 1; // // At startup time, because too many new blocks come in // they take up lots of space in the log file. // So, we log only when namenode is out of safemode. // if (!isInSafeMode()) { NameNode.stateChangeLog.info("BLOCK* NameSystem.addStoredBlock: " +"blockMap updated: "+node.getName()+" is added to "+block+" size "+block.getNumBytes()); } } else { NameNode.stateChangeLog.warn("BLOCK* NameSystem.addStoredBlock: " + "Redundant addStoredBlock request received for " + block + " on " + node.getName() + " size " + block.getNumBytes()); } // filter out containingNodes that are marked for decommission. NumberReplicas num = countNodes(storedBlock); int numLiveReplicas = num.liveReplicas(); int numCurrentReplica = numLiveReplicas + pendingReplications.getNumReplicas(block); // check whether safe replication is reached for the block incrementSafeBlockCount(numCurrentReplica); // // if file is being actively written to, then do not check // replication-factor here. It will be checked when the file is closed. // if (blockUnderConstruction) { INodeFileUnderConstruction cons = (INodeFileUnderConstruction) fileINode; cons.addTarget(node); return block; } // do not handle mis-replicated blocks during startup if(isInSafeMode()) return block; // handle underReplication/overReplication short fileReplication = fileINode.getReplication(); if (numCurrentReplica >= fileReplication) { neededReplications.remove(block, numCurrentReplica, num.decommissionedReplicas, fileReplication); } else { updateNeededReplications(block, curReplicaDelta, 0); } if (numCurrentReplica > fileReplication) { processOverReplicatedBlock(block, fileReplication, node, delNodeHint); } // If the file replication has reached desired value // we can remove any corrupt replicas the block may have int corruptReplicasCount = corruptReplicas.numCorruptReplicas(block); int numCorruptNodes = num.corruptReplicas(); if ( numCorruptNodes != corruptReplicasCount) { LOG.warn("Inconsistent number of corrupt replicas for " + block + "blockMap has " + numCorruptNodes + " but corrupt replicas map has " + corruptReplicasCount); } if ((corruptReplicasCount > 0) && (numLiveReplicas >= fileReplication)) invalidateCorruptReplicas(block); return block; } /** * Invalidate corrupt replicas. * <p> * This will remove the replicas from the block's location list, * add them to {@link #recentInvalidateSets} so that they could be further * deleted from the respective data-nodes, * and remove the block from corruptReplicasMap. * <p> * This method should be called when the block has sufficient * number of live replicas. * * @param blk Block whose corrupt replicas need to be invalidated */ void invalidateCorruptReplicas(Block blk) { Collection<DatanodeDescriptor> nodes = corruptReplicas.getNodes(blk); boolean gotException = false; if (nodes == null) return; // Make a copy of this list, since calling invalidateBlock will modify // the original (avoid CME) nodes = new ArrayList<DatanodeDescriptor>(nodes); NameNode.stateChangeLog.debug("NameNode.invalidateCorruptReplicas: " + "invalidating corrupt replicas on " + nodes.size() + "nodes"); for (Iterator<DatanodeDescriptor> it = nodes.iterator(); it.hasNext(); ) { DatanodeDescriptor node = it.next(); try { invalidateBlock(blk, node); } catch (IOException e) { NameNode.stateChangeLog.info("NameNode.invalidateCorruptReplicas " + "error in deleting bad block " + blk + " on " + node + e); gotException = true; } } // Remove the block from corruptReplicasMap if (!gotException) corruptReplicas.removeFromCorruptReplicasMap(blk); } /** * For each block in the name-node verify whether it belongs to any file, * over or under replicated. Place it into the respective queue. */ private synchronized void processMisReplicatedBlocks() { long nrInvalid = 0, nrOverReplicated = 0, nrUnderReplicated = 0; neededReplications.clear(); for(BlocksMap.BlockInfo block : blocksMap.getBlocks()) { INodeFile fileINode = block.getINode(); if(fileINode == null) { // block does not belong to any file nrInvalid++; addToInvalidates(block); continue; } // calculate current replication short expectedReplication = fileINode.getReplication(); NumberReplicas num = countNodes(block); int numCurrentReplica = num.liveReplicas(); // add to under-replicated queue if need to be if (neededReplications.add(block, numCurrentReplica, num.decommissionedReplicas(), expectedReplication)) { nrUnderReplicated++; } if (numCurrentReplica > expectedReplication) { // over-replicated block nrOverReplicated++; processOverReplicatedBlock(block, expectedReplication, null, null); } } LOG.info("Total number of blocks = " + blocksMap.size()); LOG.info("Number of invalid blocks = " + nrInvalid); LOG.info("Number of under-replicated blocks = " + nrUnderReplicated); LOG.info("Number of over-replicated blocks = " + nrOverReplicated); } /** * Find how many of the containing nodes are "extra", if any. * If there are any extras, call chooseExcessReplicates() to * mark them in the excessReplicateMap. */ private void processOverReplicatedBlock(Block block, short replication, DatanodeDescriptor addedNode, DatanodeDescriptor delNodeHint) { if(addedNode == delNodeHint) { delNodeHint = null; } Collection<DatanodeDescriptor> nonExcess = new ArrayList<DatanodeDescriptor>(); Collection<DatanodeDescriptor> corruptNodes = corruptReplicas.getNodes(block); for (Iterator<DatanodeDescriptor> it = blocksMap.nodeIterator(block); it.hasNext();) { DatanodeDescriptor cur = it.next(); Collection<Block> excessBlocks = excessReplicateMap.get(cur.getStorageID()); if (excessBlocks == null || !excessBlocks.contains(block)) { if (!cur.isDecommissionInProgress() && !cur.isDecommissioned()) { // exclude corrupt replicas if (corruptNodes == null || !corruptNodes.contains(cur)) { nonExcess.add(cur); } } } } chooseExcessReplicates(nonExcess, block, replication, addedNode, delNodeHint); } /** * We want "replication" replicates for the block, but we now have too many. * In this method, copy enough nodes from 'srcNodes' into 'dstNodes' such that: * * srcNodes.size() - dstNodes.size() == replication * * We pick node that make sure that replicas are spread across racks and * also try hard to pick one with least free space. * The algorithm is first to pick a node with least free space from nodes * that are on a rack holding more than one replicas of the block. * So removing such a replica won't remove a rack. * If no such a node is available, * then pick a node with least free space */ void chooseExcessReplicates(Collection<DatanodeDescriptor> nonExcess, Block b, short replication, DatanodeDescriptor addedNode, DatanodeDescriptor delNodeHint) { INodeFile inode = blocksMap.getINode(b); // first form a rack to datanodes map and HashMap<String, ArrayList<DatanodeDescriptor>> rackMap = new HashMap<String, ArrayList<DatanodeDescriptor>>(); for (Iterator<DatanodeDescriptor> iter = nonExcess.iterator(); iter.hasNext();) { DatanodeDescriptor node = iter.next(); String rackName = node.getNetworkLocation(); ArrayList<DatanodeDescriptor> datanodeList = rackMap.get(rackName); if(datanodeList==null) { datanodeList = new ArrayList<DatanodeDescriptor>(); } datanodeList.add(node); rackMap.put(rackName, datanodeList); } // split nodes into two sets // priSet contains nodes on rack with more than one replica // remains contains the remaining nodes ArrayList<DatanodeDescriptor> priSet = new ArrayList<DatanodeDescriptor>(); ArrayList<DatanodeDescriptor> remains = new ArrayList<DatanodeDescriptor>(); for( Iterator<Entry<String, ArrayList<DatanodeDescriptor>>> iter = rackMap.entrySet().iterator(); iter.hasNext(); ) { Entry<String, ArrayList<DatanodeDescriptor>> rackEntry = iter.next(); ArrayList<DatanodeDescriptor> datanodeList = rackEntry.getValue(); if( datanodeList.size() == 1 ) { remains.add(datanodeList.get(0)); } else { priSet.addAll(datanodeList); } } // pick one node to delete that favors the delete hint // otherwise pick one with least space from priSet if it is not empty // otherwise one node with least space from remains boolean firstOne = true; while (nonExcess.size() - replication > 0) { DatanodeInfo cur = null; // check if we can del delNodeHint if (firstOne && delNodeHint !=null && nonExcess.contains(delNodeHint) && (priSet.contains(delNodeHint) || (addedNode != null && !priSet.contains(addedNode))) ) { cur = delNodeHint; } else { // regular excessive replica removal cur = replicator.chooseReplicaToDelete(inode, b, replication, priSet, remains); } firstOne = false; // adjust rackmap, priSet, and remains String rack = cur.getNetworkLocation(); ArrayList<DatanodeDescriptor> datanodes = rackMap.get(rack); datanodes.remove(cur); if(datanodes.isEmpty()) { rackMap.remove(rack); } if( priSet.remove(cur) ) { if (datanodes.size() == 1) { priSet.remove(datanodes.get(0)); remains.add(datanodes.get(0)); } } else { remains.remove(cur); } nonExcess.remove(cur); Collection<Block> excessBlocks = excessReplicateMap.get(cur.getStorageID()); if (excessBlocks == null) { excessBlocks = new TreeSet<Block>(); excessReplicateMap.put(cur.getStorageID(), excessBlocks); } if (excessBlocks.add(b)) { excessBlocksCount++; NameNode.stateChangeLog.debug("BLOCK* NameSystem.chooseExcessReplicates: " +"("+cur.getName()+", "+b +") is added to excessReplicateMap"); } // // The 'excessblocks' tracks blocks until we get confirmation // that the datanode has deleted them; the only way we remove them // is when we get a "removeBlock" message. // // The 'invalidate' list is used to inform the datanode the block // should be deleted. Items are removed from the invalidate list // upon giving instructions to the namenode. // addToInvalidatesNoLog(b, cur); NameNode.stateChangeLog.info("BLOCK* NameSystem.chooseExcessReplicates: " +"("+cur.getName()+", "+b+") is added to recentInvalidateSets"); } } /** * Modify (block-->datanode) map. Possibly generate * replication tasks, if the removed block is still valid. */ synchronized void removeStoredBlock(Block block, DatanodeDescriptor node) { NameNode.stateChangeLog.debug("BLOCK* NameSystem.removeStoredBlock: " +block + " from "+node.getName()); if (!blocksMap.removeNode(block, node)) { NameNode.stateChangeLog.debug("BLOCK* NameSystem.removeStoredBlock: " +block+" has already been removed from node "+node); return; } // // It's possible that the block was removed because of a datanode // failure. If the block is still valid, check if replication is // necessary. In that case, put block on a possibly-will- // be-replicated list. // INode fileINode = blocksMap.getINode(block); if (fileINode != null) { decrementSafeBlockCount(block); updateNeededReplications(block, -1, 0); } // // We've removed a block from a node, so it's definitely no longer // in "excess" there. // Collection<Block> excessBlocks = excessReplicateMap.get(node.getStorageID()); if (excessBlocks != null) { if (excessBlocks.remove(block)) { excessBlocksCount--; NameNode.stateChangeLog.debug("BLOCK* NameSystem.removeStoredBlock: " + block + " is removed from excessBlocks"); if (excessBlocks.size() == 0) { excessReplicateMap.remove(node.getStorageID()); } } } // Remove the replica from corruptReplicas corruptReplicas.removeFromCorruptReplicasMap(block, node); } /** * The given node is reporting that it received a certain block. */ public synchronized void blockReceived(DatanodeID nodeID, Block block, String delHint ) throws IOException { DatanodeDescriptor node = getDatanode(nodeID); if (node == null || !node.isAlive) { NameNode.stateChangeLog.warn("BLOCK* NameSystem.blockReceived: " + block + " is received from dead or unregistered node " + nodeID.getName()); throw new IOException( "Got blockReceived message from unregistered or dead node " + block); } if (NameNode.stateChangeLog.isDebugEnabled()) { NameNode.stateChangeLog.debug("BLOCK* NameSystem.blockReceived: " +block+" is received from " + nodeID.getName()); } // Check if this datanode should actually be shutdown instead. if (shouldNodeShutdown(node)) { setDatanodeDead(node); throw new DisallowedDatanodeException(node); } // get the deletion hint node DatanodeDescriptor delHintNode = null; if(delHint!=null && delHint.length()!=0) { delHintNode = datanodeMap.get(delHint); if(delHintNode == null) { NameNode.stateChangeLog.warn("BLOCK* NameSystem.blockReceived: " + block + " is expected to be removed from an unrecorded node " + delHint); } } // // Modify the blocks->datanode map and node's map. // pendingReplications.remove(block); addStoredBlock(block, node, delHintNode ); // decrement number of blocks scheduled to this datanode. node.decBlocksScheduled(); } public long getMissingBlocksCount() { // not locking return Math.max(missingBlocksInPrevIter, missingBlocksInCurIter); } long[] getStats() throws IOException { checkSuperuserPrivilege(); synchronized(heartbeats) { return new long[] {this.capacityTotal, this.capacityUsed, this.capacityRemaining, this.underReplicatedBlocksCount, this.corruptReplicaBlocksCount, getMissingBlocksCount()}; } } /** * Total raw bytes including non-dfs used space. */ public long getCapacityTotal() { synchronized (heartbeats) { return this.capacityTotal; } } /** * Total used space by data nodes */ public long getCapacityUsed() { synchronized(heartbeats){ return this.capacityUsed; } } /** * Total used space by data nodes as percentage of total capacity */ public float getCapacityUsedPercent() { synchronized(heartbeats){ if (capacityTotal <= 0) { return 100; } return ((float)capacityUsed * 100.0f)/(float)capacityTotal; } } /** * Total used space by data nodes for non DFS purposes such * as storing temporary files on the local file system */ public long getCapacityUsedNonDFS() { long nonDFSUsed = 0; synchronized(heartbeats){ nonDFSUsed = capacityTotal - capacityRemaining - capacityUsed; } return nonDFSUsed < 0 ? 0 : nonDFSUsed; } /** * Total non-used raw bytes. */ public long getCapacityRemaining() { synchronized (heartbeats) { return this.capacityRemaining; } } /** * Total remaining space by data nodes as percentage of total capacity */ public float getCapacityRemainingPercent() { synchronized(heartbeats){ if (capacityTotal <= 0) { return 0; } return ((float)capacityRemaining * 100.0f)/(float)capacityTotal; } } /** * Total number of connections. */ public int getTotalLoad() { synchronized (heartbeats) { return this.totalLoad; } } int getNumberOfDatanodes(DatanodeReportType type) { return getDatanodeListForReport(type).size(); } public synchronized ArrayList<DatanodeDescriptor> getDatanodeListForReport( DatanodeReportType type) { boolean listLiveNodes = type == DatanodeReportType.ALL || type == DatanodeReportType.LIVE; boolean listDeadNodes = type == DatanodeReportType.ALL || type == DatanodeReportType.DEAD; HashMap<String, String> mustList = new HashMap<String, String>(); if (listDeadNodes) { //first load all the nodes listed in include and exclude files. for (Iterator<String> it = hostsReader.getHosts().iterator(); it.hasNext();) { mustList.put(it.next(), ""); } for (Iterator<String> it = hostsReader.getExcludedHosts().iterator(); it.hasNext();) { mustList.put(it.next(), ""); } } ArrayList<DatanodeDescriptor> nodes = null; synchronized (datanodeMap) { nodes = new ArrayList<DatanodeDescriptor>(datanodeMap.size() + mustList.size()); for(Iterator<DatanodeDescriptor> it = datanodeMap.values().iterator(); it.hasNext();) { DatanodeDescriptor dn = it.next(); boolean isDead = isDatanodeDead(dn); if ( (isDead && listDeadNodes) || (!isDead && listLiveNodes) ) { nodes.add(dn); } //Remove any form of the this datanode in include/exclude lists. mustList.remove(dn.getName()); mustList.remove(dn.getHost()); mustList.remove(dn.getHostName()); } } if (listDeadNodes) { for (Iterator<String> it = mustList.keySet().iterator(); it.hasNext();) { DatanodeDescriptor dn = new DatanodeDescriptor(new DatanodeID(it.next())); dn.setLastUpdate(0); nodes.add(dn); } } return nodes; } public synchronized DatanodeInfo[] datanodeReport( DatanodeReportType type ) throws AccessControlException { checkSuperuserPrivilege(); ArrayList<DatanodeDescriptor> results = getDatanodeListForReport(type); DatanodeInfo[] arr = new DatanodeInfo[results.size()]; for (int i=0; i<arr.length; i++) { arr[i] = new DatanodeInfo(results.get(i)); } return arr; } /** * Save namespace image. * This will save current namespace into fsimage file and empty edits file. * Requires superuser privilege and safe mode. * * @throws AccessControlException if superuser privilege is violated. * @throws IOException if */ synchronized void saveNamespace() throws AccessControlException, IOException { checkSuperuserPrivilege(); if(!isInSafeMode()) { throw new IOException("Safe mode should be turned ON " + "in order to create namespace image."); } getFSImage().saveNamespace(true); LOG.info("New namespace image has been created."); } /** */ public synchronized void DFSNodesStatus(ArrayList<DatanodeDescriptor> live, ArrayList<DatanodeDescriptor> dead) { ArrayList<DatanodeDescriptor> results = getDatanodeListForReport(DatanodeReportType.ALL); for(Iterator<DatanodeDescriptor> it = results.iterator(); it.hasNext();) { DatanodeDescriptor node = it.next(); if (isDatanodeDead(node)) dead.add(node); else live.add(node); } } /** * Prints information about all datanodes. */ private synchronized void datanodeDump(PrintWriter out) { synchronized (datanodeMap) { out.println("Metasave: Number of datanodes: " + datanodeMap.size()); for(Iterator<DatanodeDescriptor> it = datanodeMap.values().iterator(); it.hasNext();) { DatanodeDescriptor node = it.next(); out.println(node.dumpDatanode()); } } } /** * Start decommissioning the specified datanode. */ private void startDecommission (DatanodeDescriptor node) throws IOException { if (!node.isDecommissionInProgress() && !node.isDecommissioned()) { LOG.info("Start Decommissioning node " + node.getName()); node.startDecommission(); node.decommissioningStatus.setStartTime(now()); // // all the blocks that reside on this node have to be // replicated. checkDecommissionStateInternal(node); } } /** * Stop decommissioning the specified datanodes. */ public void stopDecommission (DatanodeDescriptor node) throws IOException { LOG.info("Stop Decommissioning node " + node.getName()); node.stopDecommission(); } /** */ public DatanodeInfo getDataNodeInfo(String name) { return datanodeMap.get(name); } /** * @deprecated use {@link NameNode#getNameNodeAddress()} instead. */ @Deprecated public InetSocketAddress getDFSNameNodeAddress() { return nameNodeAddress; } /** */ public Date getStartTime() { return new Date(systemStart); } short getMaxReplication() { return (short)maxReplication; } short getMinReplication() { return (short)minReplication; } short getDefaultReplication() { return (short)defaultReplication; } public void stallReplicationWork() { stallReplicationWork = true; } public void restartReplicationWork() { stallReplicationWork = false; } /** * A immutable object that stores the number of live replicas and * the number of decommissined Replicas. */ static class NumberReplicas { private int liveReplicas; private int decommissionedReplicas; private int corruptReplicas; private int excessReplicas; NumberReplicas() { initialize(0, 0, 0, 0); } NumberReplicas(int live, int decommissioned, int corrupt, int excess) { initialize(live, decommissioned, corrupt, excess); } void initialize(int live, int decommissioned, int corrupt, int excess) { liveReplicas = live; decommissionedReplicas = decommissioned; corruptReplicas = corrupt; excessReplicas = excess; } int liveReplicas() { return liveReplicas; } int decommissionedReplicas() { return decommissionedReplicas; } int corruptReplicas() { return corruptReplicas; } int excessReplicas() { return excessReplicas; } } /** * Counts the number of nodes in the given list into active and * decommissioned counters. */ private NumberReplicas countNodes(Block b, Iterator<DatanodeDescriptor> nodeIter) { int count = 0; int live = 0; int corrupt = 0; int excess = 0; Collection<DatanodeDescriptor> nodesCorrupt = corruptReplicas.getNodes(b); while ( nodeIter.hasNext() ) { DatanodeDescriptor node = nodeIter.next(); if ((nodesCorrupt != null) && (nodesCorrupt.contains(node))) { corrupt++; } else if (node.isDecommissionInProgress() || node.isDecommissioned()) { count++; } else { Collection<Block> blocksExcess = excessReplicateMap.get(node.getStorageID()); if (blocksExcess != null && blocksExcess.contains(b)) { excess++; } else { live++; } } } return new NumberReplicas(live, count, corrupt, excess); } /** * Return the number of nodes that are live and decommissioned. */ NumberReplicas countNodes(Block b) { return countNodes(b, blocksMap.nodeIterator(b)); } private void logBlockReplicationInfo(Block block, DatanodeDescriptor srcNode, NumberReplicas num) { int curReplicas = num.liveReplicas(); int curExpectedReplicas = getReplication(block); INode fileINode = blocksMap.getINode(block); Iterator<DatanodeDescriptor> nodeIter = blocksMap.nodeIterator(block); StringBuffer nodeList = new StringBuffer(); while (nodeIter.hasNext()) { DatanodeDescriptor node = nodeIter.next(); nodeList.append(node.name); nodeList.append(" "); } FSNamesystem.LOG.info("Block: " + block + ", Expected Replicas: " + curExpectedReplicas + ", live replicas: " + curReplicas + ", corrupt replicas: " + num.corruptReplicas() + ", decommissioned replicas: " + num.decommissionedReplicas() + ", excess replicas: " + num.excessReplicas() + ", Is Open File: " + fileINode.isUnderConstruction() + ", Datanodes having this block: " + nodeList + ", Current Datanode: " + srcNode.name + ", Is current datanode decommissioning: " + srcNode.isDecommissionInProgress()); } /** * Return true if there are any blocks on this node that have not * yet reached their replication factor. Otherwise returns false. */ private boolean isReplicationInProgress(DatanodeDescriptor srcNode) { boolean status = false; int underReplicatedBlocks = 0; int decommissionOnlyReplicas = 0; int underReplicatedInOpenFiles = 0; for(final Iterator<Block> i = srcNode.getBlockIterator(); i.hasNext(); ) { final Block block = i.next(); INode fileINode = blocksMap.getINode(block); if (fileINode != null) { NumberReplicas num = countNodes(block); int curReplicas = num.liveReplicas(); int curExpectedReplicas = getReplication(block); if (curExpectedReplicas > curReplicas) { // Log info about one block for this node which needs replication if (!status) { status = true; logBlockReplicationInfo(block, srcNode, num); } underReplicatedBlocks++; if ((curReplicas == 0) && (num.decommissionedReplicas() > 0)) { decommissionOnlyReplicas++; } if (fileINode.isUnderConstruction()) { underReplicatedInOpenFiles++; } if (!neededReplications.contains(block) && pendingReplications.getNumReplicas(block) == 0) { // // These blocks have been reported from the datanode // after the startDecommission method has been executed. These // blocks were in flight when the decommission was started. // neededReplications.add(block, curReplicas, num.decommissionedReplicas(), curExpectedReplicas); } } } } srcNode.decommissioningStatus.set(underReplicatedBlocks, decommissionOnlyReplicas, underReplicatedInOpenFiles); return status; } /** * Change, if appropriate, the admin state of a datanode to * decommission completed. Return true if decommission is complete. */ boolean checkDecommissionStateInternal(DatanodeDescriptor node) { // // Check to see if all blocks in this decommissioned // node has reached their target replication factor. // if (node.isDecommissionInProgress()) { if (!isReplicationInProgress(node)) { node.setDecommissioned(); LOG.info("Decommission complete for node " + node.getName()); } } if (node.isDecommissioned()) { return true; } return false; } /** * Keeps track of which datanodes/ipaddress are allowed to connect to the namenode. */ private boolean inHostsList(DatanodeID node, String ipAddr) { Set<String> hostsList = hostsReader.getHosts(); return (hostsList.isEmpty() || (ipAddr != null && hostsList.contains(ipAddr)) || hostsList.contains(node.getHost()) || hostsList.contains(node.getName()) || ((node instanceof DatanodeInfo) && hostsList.contains(((DatanodeInfo)node).getHostName()))); } private boolean inExcludedHostsList(DatanodeID node, String ipAddr) { Set<String> excludeList = hostsReader.getExcludedHosts(); return ((ipAddr != null && excludeList.contains(ipAddr)) || excludeList.contains(node.getHost()) || excludeList.contains(node.getName()) || ((node instanceof DatanodeInfo) && excludeList.contains(((DatanodeInfo)node).getHostName()))); } /** * Rereads the config to get hosts and exclude list file names. * Rereads the files to update the hosts and exclude lists. It * checks if any of the hosts have changed states: * 1. Added to hosts --> no further work needed here. * 2. Removed from hosts --> mark AdminState as decommissioned. * 3. Added to exclude --> start decommission. * 4. Removed from exclude --> stop decommission. */ public void refreshNodes(Configuration conf) throws IOException { checkSuperuserPrivilege(); // Reread the config to get dfs.hosts and dfs.hosts.exclude filenames. // Update the file names and refresh internal includes and excludes list if (conf == null) conf = new Configuration(); hostsReader.updateFileNames(conf.get("dfs.hosts",""), conf.get("dfs.hosts.exclude", "")); hostsReader.refresh(); synchronized (this) { for (Iterator<DatanodeDescriptor> it = datanodeMap.values().iterator(); it.hasNext();) { DatanodeDescriptor node = it.next(); // Check if not include. if (!inHostsList(node, null)) { node.setDecommissioned(); // case 2. } else { if (inExcludedHostsList(node, null)) { if (!node.isDecommissionInProgress() && !node.isDecommissioned()) { startDecommission(node); // case 3. } } else { if (node.isDecommissionInProgress() || node.isDecommissioned()) { stopDecommission(node); // case 4. } } } } } } void finalizeUpgrade() throws IOException { checkSuperuserPrivilege(); getFSImage().finalizeUpgrade(); } /** * Checks if the node is not on the hosts list. If it is not, then * it will be ignored. If the node is in the hosts list, but is also * on the exclude list, then it will be decommissioned. * Returns FALSE if node is rejected for registration. * Returns TRUE if node is registered (including when it is on the * exclude list and is being decommissioned). */ private synchronized boolean verifyNodeRegistration(DatanodeRegistration nodeReg, String ipAddr) throws IOException { if (!inHostsList(nodeReg, ipAddr)) { return false; } if (inExcludedHostsList(nodeReg, ipAddr)) { DatanodeDescriptor node = getDatanode(nodeReg); if (node == null) { throw new IOException("verifyNodeRegistration: unknown datanode " + nodeReg.getName()); } if (!checkDecommissionStateInternal(node)) { startDecommission(node); } } return true; } /** * Checks if the Admin state bit is DECOMMISSIONED. If so, then * we should shut it down. * * Returns true if the node should be shutdown. */ private boolean shouldNodeShutdown(DatanodeDescriptor node) { return (node.isDecommissioned()); } /** * Get data node by storage ID. * * @param nodeID * @return DatanodeDescriptor or null if the node is not found. * @throws IOException */ public DatanodeDescriptor getDatanode(DatanodeID nodeID) throws IOException { UnregisteredDatanodeException e = null; DatanodeDescriptor node = datanodeMap.get(nodeID.getStorageID()); if (node == null) return null; if (!node.getName().equals(nodeID.getName())) { e = new UnregisteredDatanodeException(nodeID, node); NameNode.stateChangeLog.fatal("BLOCK* NameSystem.getDatanode: " + e.getLocalizedMessage()); throw e; } return node; } /** Stop at and return the datanode at index (used for content browsing)*/ @Deprecated private DatanodeDescriptor getDatanodeByIndex(int index) { int i = 0; for (DatanodeDescriptor node : datanodeMap.values()) { if (i == index) { return node; } i++; } return null; } @Deprecated public String randomDataNode() { int size = datanodeMap.size(); int index = 0; if (size != 0) { index = r.nextInt(size); for(int i=0; i<size; i++) { DatanodeDescriptor d = getDatanodeByIndex(index); if (d != null && !d.isDecommissioned() && !isDatanodeDead(d) && !d.isDecommissionInProgress()) { return d.getHost() + ":" + d.getInfoPort(); } index = (index + 1) % size; } } return null; } public DatanodeDescriptor getRandomDatanode() { return (DatanodeDescriptor)clusterMap.chooseRandom(NodeBase.ROOT); } /** * SafeModeInfo contains information related to the safe mode. * <p> * An instance of {@link SafeModeInfo} is created when the name node * enters safe mode. * <p> * During name node startup {@link SafeModeInfo} counts the number of * <em>safe blocks</em>, those that have at least the minimal number of * replicas, and calculates the ratio of safe blocks to the total number * of blocks in the system, which is the size of * {@link FSNamesystem#blocksMap}. When the ratio reaches the * {@link #threshold} it starts the {@link SafeModeMonitor} daemon in order * to monitor whether the safe mode {@link #extension} is passed. * Then it leaves safe mode and destroys itself. * <p> * If safe mode is turned on manually then the number of safe blocks is * not tracked because the name node is not intended to leave safe mode * automatically in the case. * * @see ClientProtocol#setSafeMode(FSConstants.SafeModeAction) * @see SafeModeMonitor */ class SafeModeInfo { // configuration fields /** Safe mode threshold condition %.*/ private double threshold; /** Safe mode minimum number of datanodes alive */ private int datanodeThreshold; /** Safe mode extension after the threshold. */ private int extension; /** Min replication required by safe mode. */ private int safeReplication; // internal fields /** Time when threshold was reached. * * <br>-1 safe mode is off * <br> 0 safe mode is on, but threshold is not reached yet */ private long reached = -1; /** Total number of blocks. */ int blockTotal; /** Number of safe blocks. */ private int blockSafe; /** time of the last status printout */ private long lastStatusReport = 0; /** * Creates SafeModeInfo when the name node enters * automatic safe mode at startup. * * @param conf configuration */ SafeModeInfo(Configuration conf) { this.threshold = conf.getFloat("dfs.safemode.threshold.pct", 0.95f); this.datanodeThreshold = conf.getInt( DFSConfigKeys.DFS_NAMENODE_SAFEMODE_MIN_DATANODES_KEY, DFSConfigKeys.DFS_NAMENODE_SAFEMODE_MIN_DATANODES_DEFAULT); this.extension = conf.getInt("dfs.safemode.extension", 0); this.safeReplication = conf.getInt("dfs.replication.min", 1); this.blockTotal = 0; this.blockSafe = 0; LOG.info("dfs.safemode.threshold.pct = " + threshold); LOG.info("dfs.namenode.safemode.min.datanodes = " + datanodeThreshold); LOG.info("dfs.safemode.extension = " + extension); } /** * Creates SafeModeInfo when safe mode is entered manually. * * The {@link #threshold} is set to 1.5 so that it could never be reached. * {@link #blockTotal} is set to -1 to indicate that safe mode is manual. * * @see SafeModeInfo */ private SafeModeInfo() { this.threshold = 1.5f; // this threshold can never be reached this.datanodeThreshold = Integer.MAX_VALUE; this.extension = Integer.MAX_VALUE; this.safeReplication = Short.MAX_VALUE + 1; // more than maxReplication this.blockTotal = -1; this.blockSafe = -1; this.reached = -1; enter(); reportStatus("STATE* Safe mode is ON.", true); } /** * Check if safe mode is on. * @return true if in safe mode */ synchronized boolean isOn() { try { assert isConsistent() : " SafeMode: Inconsistent filesystem state: " + "Total num of blocks, active blocks, or " + "total safe blocks don't match."; } catch(IOException e) { System.err.print(StringUtils.stringifyException(e)); } return this.reached >= 0; } /** * Enter safe mode. */ void enter() { this.reached = 0; } /** * Leave safe mode. * <p> * Switch to manual safe mode if distributed upgrade is required.<br> * Check for invalid, under- & over-replicated blocks in the end of startup. */ synchronized void leave(boolean checkForUpgrades) { if(checkForUpgrades) { // verify whether a distributed upgrade needs to be started boolean needUpgrade = false; try { needUpgrade = startDistributedUpgradeIfNeeded(); } catch(IOException e) { FSNamesystem.LOG.error(StringUtils.stringifyException(e)); } if(needUpgrade) { // switch to manual safe mode safeMode = new SafeModeInfo(); return; } } // verify blocks replications long startTimeMisReplicatedScan = now(); processMisReplicatedBlocks(); NameNode.stateChangeLog.info("STATE* Safe mode termination " + "scan for invalid, over- and under-replicated blocks " + "completed in " + (now() - startTimeMisReplicatedScan) + " msec"); long timeInSafemode = now() - systemStart; NameNode.stateChangeLog.info("STATE* Leaving safe mode after " + timeInSafemode/1000 + " secs."); NameNode.getNameNodeMetrics().setSafeModeTime(timeInSafemode); if (reached >= 0) { NameNode.stateChangeLog.info("STATE* Safe mode is OFF."); } reached = -1; safeMode = null; NameNode.stateChangeLog.info("STATE* Network topology has " +clusterMap.getNumOfRacks()+" racks and " +clusterMap.getNumOfLeaves()+ " datanodes"); NameNode.stateChangeLog.info("STATE* UnderReplicatedBlocks has " +neededReplications.size()+" blocks"); } /** * Safe mode can be turned off iff * the threshold is reached and * the extension time have passed. * @return true if can leave or false otherwise. */ synchronized boolean canLeave() { if (reached == 0) return false; if (now() - reached < extension) { reportStatus("STATE* Safe mode ON.", false); return false; } return !needEnter(); } /** * There is no need to enter safe mode * if DFS is empty or {@link #threshold} == 0 */ boolean needEnter() { return getSafeBlockRatio() < threshold || numLiveDataNodes() < datanodeThreshold; } /** * Ratio of the number of safe blocks to the total number of blocks * to be compared with the threshold. */ private float getSafeBlockRatio() { return (blockTotal == 0 ? 1 : (float)blockSafe/blockTotal); } /** * Check and trigger safe mode if needed. */ private void checkMode() { if (needEnter()) { enter(); reportStatus("STATE* Safe mode ON.", false); return; } // the threshold is reached if (!isOn() || // safe mode is off extension <= 0 || threshold <= 0) { // don't need to wait this.leave(true); // leave safe mode return; } if (reached > 0) { // threshold has already been reached before reportStatus("STATE* Safe mode ON.", false); return; } // start monitor reached = now(); smmthread = new Daemon(new SafeModeMonitor()); smmthread.start(); reportStatus("STATE* Safe mode extension entered.", true); } /** * Set total number of blocks. */ synchronized void setBlockTotal(int total) { this.blockTotal = total; checkMode(); } /** * Increment number of safe blocks if current block has * reached minimal replication. * @param replication current replication */ synchronized void incrementSafeBlockCount(short replication) { if ((int)replication == safeReplication) this.blockSafe++; checkMode(); } /** * Decrement number of safe blocks if current block has * fallen below minimal replication. * @param replication current replication */ synchronized void decrementSafeBlockCount(short replication) { if (replication == safeReplication-1) this.blockSafe--; checkMode(); } /** * Check if safe mode was entered manually or at startup. */ boolean isManual() { return extension == Integer.MAX_VALUE; } /** * Set manual safe mode. */ void setManual() { extension = Integer.MAX_VALUE; } /** * A tip on how safe mode is to be turned off: manually or automatically. */ String getTurnOffTip() { String leaveMsg = "Safe mode will be turned off automatically"; if(reached < 0) return "Safe mode is OFF."; if(isManual()) { if(getDistributedUpgradeState()) return leaveMsg + " upon completion of " + "the distributed upgrade: upgrade progress = " + getDistributedUpgradeStatus() + "%"; leaveMsg = "Use \"hadoop dfsadmin -safemode leave\" to turn safe mode off"; } if(blockTotal < 0) return leaveMsg + "."; int numLive = numLiveDataNodes(); String msg = ""; if (reached == 0) { if (getSafeBlockRatio() < threshold) { msg += String.format( "The reported blocks is only %d" + " but the threshold is %.4f and the total blocks %d.", blockSafe, threshold, blockTotal); } if (numLive < datanodeThreshold) { if (!"".equals(msg)) { msg += "\n"; } msg += String.format( "The number of live datanodes %d needs an additional %d live " + "datanodes to reach the minimum number %d.", numLive, (datanodeThreshold - numLive), datanodeThreshold); } msg += " " + leaveMsg; } else { msg = String.format("The reported blocks %d has reached the threshold" + " %.4f of total blocks %d.", blockSafe, threshold, blockTotal); if (datanodeThreshold > 0) { msg += String.format(" The number of live datanodes %d has reached " + "the minimum number %d.", numLive, datanodeThreshold); } msg += " " + leaveMsg; } if(reached == 0 || isManual()) { // threshold is not reached or manual return msg + "."; } // extension period is in progress return msg + " in " + Math.abs(reached + extension - now()) / 1000 + " seconds."; } /** * Print status every 20 seconds. */ private void reportStatus(String msg, boolean rightNow) { long curTime = now(); if(!rightNow && (curTime - lastStatusReport < 20 * 1000)) return; NameNode.stateChangeLog.info(msg + " \n" + getTurnOffTip()); lastStatusReport = curTime; } /** * Returns printable state of the class. */ public String toString() { String resText = "Current safe block ratio = " + getSafeBlockRatio() + ". Target threshold = " + threshold + ". Minimal replication = " + safeReplication + "."; if (reached > 0) resText += " Threshold was reached " + new Date(reached) + "."; return resText; } /** * Checks consistency of the class state. * This is costly and currently called only in assert. */ boolean isConsistent() throws IOException { if (blockTotal == -1 && blockSafe == -1) { return true; // manual safe mode } int activeBlocks = blocksMap.size() - (int)pendingDeletionBlocksCount; return (blockTotal == activeBlocks) || (blockSafe >= 0 && blockSafe <= blockTotal); } } /** * Periodically check whether it is time to leave safe mode. * This thread starts when the threshold level is reached. * */ class SafeModeMonitor implements Runnable { /** interval in msec for checking safe mode: {@value} */ private static final long recheckInterval = 1000; /** */ public void run() { while (fsRunning && (safeMode != null && !safeMode.canLeave())) { try { Thread.sleep(recheckInterval); } catch (InterruptedException ie) { } } // leave safe mode and stop the monitor try { leaveSafeMode(true); } catch(SafeModeException es) { // should never happen String msg = "SafeModeMonitor may not run during distributed upgrade."; assert false : msg; throw new RuntimeException(msg, es); } smmthread = null; } } /** * Current system time. * @return current time in msec. */ static long now() { return System.currentTimeMillis(); } boolean setSafeMode(SafeModeAction action) throws IOException { if (action != SafeModeAction.SAFEMODE_GET) { checkSuperuserPrivilege(); switch(action) { case SAFEMODE_LEAVE: // leave safe mode leaveSafeMode(false); break; case SAFEMODE_ENTER: // enter safe mode enterSafeMode(); break; } } return isInSafeMode(); } /** * Check whether the name node is in safe mode. * @return true if safe mode is ON, false otherwise */ boolean isInSafeMode() { if (safeMode == null) return false; return safeMode.isOn(); } /** * Check whether the name node is in startup mode. */ synchronized boolean isInStartupSafeMode() { if (safeMode == null) return false; return safeMode.isOn() && !safeMode.isManual(); } /** * Increment number of blocks that reached minimal replication. * @param replication current replication */ void incrementSafeBlockCount(int replication) { if (safeMode == null) return; safeMode.incrementSafeBlockCount((short)replication); } /** * Decrement number of blocks that reached minimal replication. */ void decrementSafeBlockCount(Block b) { if (safeMode == null) // mostly true return; safeMode.decrementSafeBlockCount((short)countNodes(b).liveReplicas()); } /** * Set the total number of blocks in the system. */ void setBlockTotal() { if (safeMode == null) return; safeMode.setBlockTotal(blocksMap.size()); } /** * Get the total number of blocks in the system. */ public long getBlocksTotal() { return blocksMap.size(); } /** * Enter safe mode manually. * @throws IOException */ synchronized void enterSafeMode() throws IOException { if (!isInSafeMode()) { safeMode = new SafeModeInfo(); return; } safeMode.setManual(); getEditLog().logSync(); NameNode.stateChangeLog.info("STATE* Safe mode is ON. " + safeMode.getTurnOffTip()); } /** * Leave safe mode. * @throws IOException */ synchronized void leaveSafeMode(boolean checkForUpgrades) throws SafeModeException { if (!isInSafeMode()) { NameNode.stateChangeLog.info("STATE* Safe mode is already OFF."); return; } if(getDistributedUpgradeState()) throw new SafeModeException("Distributed upgrade is in progress", safeMode); safeMode.leave(checkForUpgrades); } public String getSafeModeTip() { if (!isInSafeMode()) return ""; return safeMode.getTurnOffTip(); } long getEditLogSize() throws IOException { return getEditLog().getEditLogSize(); } synchronized CheckpointSignature rollEditLog() throws IOException { if (isInSafeMode()) { throw new SafeModeException("Checkpoint not created", safeMode); } LOG.info("Roll Edit Log from " + Server.getRemoteAddress()); return getFSImage().rollEditLog(); } synchronized void rollFSImage() throws IOException { if (isInSafeMode()) { throw new SafeModeException("Checkpoint not created", safeMode); } LOG.info("Roll FSImage from " + Server.getRemoteAddress()); getFSImage().rollFSImage(); } /** * Returns whether the given block is one pointed-to by a file. */ private boolean isValidBlock(Block b) { return (blocksMap.getINode(b) != null); } // Distributed upgrade manager UpgradeManagerNamenode upgradeManager = new UpgradeManagerNamenode(); UpgradeStatusReport distributedUpgradeProgress(UpgradeAction action ) throws IOException { return upgradeManager.distributedUpgradeProgress(action); } UpgradeCommand processDistributedUpgradeCommand(UpgradeCommand comm) throws IOException { return upgradeManager.processUpgradeCommand(comm); } int getDistributedUpgradeVersion() { return upgradeManager.getUpgradeVersion(); } UpgradeCommand getDistributedUpgradeCommand() throws IOException { return upgradeManager.getBroadcastCommand(); } boolean getDistributedUpgradeState() { return upgradeManager.getUpgradeState(); } short getDistributedUpgradeStatus() { return upgradeManager.getUpgradeStatus(); } boolean startDistributedUpgradeIfNeeded() throws IOException { return upgradeManager.startUpgrade(); } PermissionStatus createFsOwnerPermissions(FsPermission permission) { return new PermissionStatus(fsOwner.getShortUserName(), supergroup, permission); } private FSPermissionChecker checkOwner(String path) throws AccessControlException { return checkPermission(path, true, null, null, null, null); } private FSPermissionChecker checkPathAccess(String path, FsAction access ) throws AccessControlException { return checkPermission(path, false, null, null, access, null); } private FSPermissionChecker checkParentAccess(String path, FsAction access ) throws AccessControlException { return checkPermission(path, false, null, access, null, null); } private FSPermissionChecker checkAncestorAccess(String path, FsAction access ) throws AccessControlException { return checkPermission(path, false, access, null, null, null); } private FSPermissionChecker checkTraverse(String path ) throws AccessControlException { return checkPermission(path, false, null, null, null, null); } private void checkSuperuserPrivilege() throws AccessControlException { if (isPermissionEnabled) { PermissionChecker.checkSuperuserPrivilege(fsOwner, supergroup); } } /** * Check whether current user have permissions to access the path. * For more details of the parameters, see * {@link FSPermissionChecker#checkPermission(String, INodeDirectory, boolean, FsAction, FsAction, FsAction, FsAction)}. */ private FSPermissionChecker checkPermission(String path, boolean doCheckOwner, FsAction ancestorAccess, FsAction parentAccess, FsAction access, FsAction subAccess) throws AccessControlException { FSPermissionChecker pc = new FSPermissionChecker( fsOwner.getShortUserName(), supergroup); if (!pc.isSuper) { dir.waitForReady(); pc.checkPermission(path, dir.rootDir, doCheckOwner, ancestorAccess, parentAccess, access, subAccess); } return pc; } /** * Check to see if we have exceeded the limit on the number * of inodes. */ void checkFsObjectLimit() throws IOException { if (maxFsObjects != 0 && maxFsObjects <= dir.totalInodes() + getBlocksTotal()) { throw new IOException("Exceeded the configured number of objects " + maxFsObjects + " in the filesystem."); } } /** * Get the total number of objects in the system. */ long getMaxObjects() { return maxFsObjects; } public long getFilesTotal() { return this.dir.totalInodes(); } public long getPendingReplicationBlocks() { return pendingReplicationBlocksCount; } public long getUnderReplicatedBlocks() { return underReplicatedBlocksCount; } /** Returns number of blocks with corrupt replicas */ public long getCorruptReplicaBlocks() { return corruptReplicaBlocksCount; } public long getScheduledReplicationBlocks() { return scheduledReplicationBlocksCount; } public long getPendingDeletionBlocks() { return pendingDeletionBlocksCount; } public long getExcessBlocks() { return excessBlocksCount; } public synchronized int getBlockCapacity() { return blocksMap.getCapacity(); } public String getFSState() { return isInSafeMode() ? "safeMode" : "Operational"; } private ObjectName mbeanName; private ObjectName mxBean = null; /** * Register the FSNamesystem MBean using the name * "hadoop:service=NameNode,name=FSNamesystemState" * Register the FSNamesystem MXBean using the name * "hadoop:service=NameNode,name=NameNodeInfo" */ void registerMBean(Configuration conf) { // We wrap to bypass standard mbean naming convention. // This wraping can be removed in java 6 as it is more flexible in // package naming for mbeans and their impl. StandardMBean bean; try { bean = new StandardMBean(this,FSNamesystemMBean.class); mbeanName = MBeans.register("NameNode", "FSNamesystemState", bean); } catch (NotCompliantMBeanException e) { e.printStackTrace(); } mxBean = MBeans.register("NameNode", "NameNodeInfo", this); LOG.info("Registered FSNamesystemStateMBean and NameNodeMXBean"); } /** * shutdown FSNamesystem */ public void shutdown() { if (mbeanName != null) MBeans.unregister(mbeanName); if (mxBean != null) MBeans.unregister(mxBean); } /** * Number of live data nodes * @return Number of live data nodes */ public int numLiveDataNodes() { int numLive = 0; synchronized (datanodeMap) { for(Iterator<DatanodeDescriptor> it = datanodeMap.values().iterator(); it.hasNext();) { DatanodeDescriptor dn = it.next(); if (!isDatanodeDead(dn) ) { numLive++; } } } return numLive; } /** * Number of dead data nodes * @return Number of dead data nodes */ public int numDeadDataNodes() { int numDead = 0; synchronized (datanodeMap) { for(Iterator<DatanodeDescriptor> it = datanodeMap.values().iterator(); it.hasNext();) { DatanodeDescriptor dn = it.next(); if (isDatanodeDead(dn) ) { numDead++; } } } return numDead; } /** * Sets the generation stamp for this filesystem */ public void setGenerationStamp(long stamp) { generationStamp.setStamp(stamp); } /** * Gets the generation stamp for this filesystem */ public long getGenerationStamp() { return generationStamp.getStamp(); } /** * Increments, logs and then returns the stamp */ private long nextGenerationStamp() { long gs = generationStamp.nextStamp(); getEditLog().logGenerationStamp(gs); return gs; } /** * Verifies that the block is associated with a file that has a lease. * Increments, logs and then returns the stamp * * @param block block * @param fromNN if it is for lease recovery initiated by NameNode * @return a new generation stamp */ synchronized long nextGenerationStampForBlock(Block block, boolean fromNN) throws IOException { if (isInSafeMode()) { throw new SafeModeException("Cannot get nextGenStamp for " + block, safeMode); } BlockInfo storedBlock = blocksMap.getStoredBlock(block); if (storedBlock == null) { BlockInfo match = blocksMap.getStoredBlock(block.getWithWildcardGS()); String msg = (match == null) ? block + " is missing" : block + " has out of date GS " + block.getGenerationStamp() + " found " + match.getGenerationStamp() + ", may already be committed"; LOG.info(msg); throw new IOException(msg); } INodeFile fileINode = storedBlock.getINode(); if (!fileINode.isUnderConstruction()) { String msg = block + " is already commited, !fileINode.isUnderConstruction()."; LOG.info(msg); throw new IOException(msg); } // Disallow client-initiated recovery once // NameNode initiated lease recovery starts if (!fromNN && HdfsConstants.NN_RECOVERY_LEASEHOLDER.equals( leaseManager.getLeaseByPath(FSDirectory.getFullPathName(fileINode)).getHolder())) { String msg = block + "is being recovered by NameNode, ignoring the request from a client"; LOG.info(msg); throw new IOException(msg); } if (!((INodeFileUnderConstruction)fileINode).setLastRecoveryTime(now())) { String msg = block + " is already being recovered, ignoring this request."; LOG.info(msg); throw new IOException(msg); } return nextGenerationStamp(); } // rename was successful. If any part of the renamed subtree had // files that were being written to, update with new filename. // void changeLease(String src, String dst, HdfsFileStatus dinfo) throws IOException { String overwrite; String replaceBy; boolean destinationExisted = true; if (dinfo == null) { destinationExisted = false; } if (destinationExisted && dinfo.isDir()) { Path spath = new Path(src); Path parent = spath.getParent(); if (isRoot(parent)) { overwrite = parent.toString(); } else { overwrite = parent.toString() + Path.SEPARATOR; } replaceBy = dst + Path.SEPARATOR; } else { overwrite = src; replaceBy = dst; } leaseManager.changeLease(src, dst, overwrite, replaceBy); } private boolean isRoot(Path path) { return path.getParent() == null; } /** * Serializes leases. */ void saveFilesUnderConstruction(DataOutputStream out) throws IOException { synchronized (leaseManager) { out.writeInt(leaseManager.countPath()); // write the size for (Lease lease : leaseManager.getSortedLeases()) { for(String path : lease.getPaths()) { // verify that path exists in namespace INode node = dir.getFileINode(path); if (node == null) { throw new IOException("saveLeases found path " + path + " but no matching entry in namespace."); } if (!node.isUnderConstruction()) { throw new IOException("saveLeases found path " + path + " but is not under construction."); } INodeFileUnderConstruction cons = (INodeFileUnderConstruction) node; FSImage.writeINodeUnderConstruction(out, cons, path); } } } } public synchronized ArrayList<DatanodeDescriptor> getDecommissioningNodes() { ArrayList<DatanodeDescriptor> decommissioningNodes = new ArrayList<DatanodeDescriptor>(); ArrayList<DatanodeDescriptor> results = getDatanodeListForReport(DatanodeReportType.LIVE); for (Iterator<DatanodeDescriptor> it = results.iterator(); it.hasNext();) { DatanodeDescriptor node = it.next(); if (node.isDecommissionInProgress()) { decommissioningNodes.add(node); } } return decommissioningNodes; } /* * Delegation Token */ private DelegationTokenSecretManager createDelegationTokenSecretManager( Configuration conf) { return new DelegationTokenSecretManager(conf.getLong( "dfs.namenode.delegation.key.update-interval", 24*60*60*1000), conf.getLong( "dfs.namenode.delegation.token.max-lifetime", 7*24*60*60*1000), conf.getLong( "dfs.namenode.delegation.token.renew-interval", 24*60*60*1000), DELEGATION_TOKEN_REMOVER_SCAN_INTERVAL, this); } /** * Returns the DelegationTokenSecretManager instance in the namesystem. * @return delegation token secret manager object */ public DelegationTokenSecretManager getDelegationTokenSecretManager() { return dtSecretManager; } /** * @param renewer * @return Token<DelegationTokenIdentifier> * @throws IOException */ public Token<DelegationTokenIdentifier> getDelegationToken(Text renewer) throws IOException { if (isInSafeMode()) { throw new SafeModeException("Cannot issue delegation token", safeMode); } if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be issued only with kerberos or web authentication"); } if(dtSecretManager == null || !dtSecretManager.isRunning()) { LOG.warn("trying to get DT with no secret manager running"); return null; } UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); String user = ugi.getUserName(); Text owner = new Text(user); Text realUser = null; if (ugi.getRealUser() != null) { realUser = new Text(ugi.getRealUser().getUserName()); } DelegationTokenIdentifier dtId = new DelegationTokenIdentifier(owner, renewer, realUser); Token<DelegationTokenIdentifier> token = new Token<DelegationTokenIdentifier>( dtId, dtSecretManager); long expiryTime = dtSecretManager.getTokenExpiryTime(dtId); logGetDelegationToken(dtId, expiryTime); return token; } /** * * @param token * @return New expiryTime of the token * @throws InvalidToken * @throws IOException */ public long renewDelegationToken(Token<DelegationTokenIdentifier> token) throws InvalidToken, IOException { if (isInSafeMode()) { throw new SafeModeException("Cannot renew delegation token", safeMode); } if (!isAllowedDelegationTokenOp()) { throw new IOException( "Delegation Token can be renewed only with kerberos or web authentication"); } String renewer = UserGroupInformation.getCurrentUser().getShortUserName(); long expiryTime = dtSecretManager.renewToken(token, renewer); DelegationTokenIdentifier id = new DelegationTokenIdentifier(); ByteArrayInputStream buf = new ByteArrayInputStream(token.getIdentifier()); DataInputStream in = new DataInputStream(buf); id.readFields(in); logRenewDelegationToken(id, expiryTime); return expiryTime; } /** * * @param token * @throws IOException */ public void cancelDelegationToken(Token<DelegationTokenIdentifier> token) throws IOException { if (isInSafeMode()) { throw new SafeModeException("Cannot cancel delegation token", safeMode); } String canceller = UserGroupInformation.getCurrentUser().getUserName(); DelegationTokenIdentifier id = dtSecretManager .cancelToken(token, canceller); logCancelDelegationToken(id); } /** * @param out save state of the secret manager */ void saveSecretManagerState(DataOutputStream out) throws IOException { dtSecretManager.saveSecretManagerState(out); } /** * @param in load the state of secret manager from input stream */ void loadSecretManagerState(DataInputStream in) throws IOException { dtSecretManager.loadSecretManagerState(in); } /** * Log the getDelegationToken operation to edit logs * * @param id identifer of the new delegation token * @param expiryTime when delegation token expires */ private void logGetDelegationToken(DelegationTokenIdentifier id, long expiryTime) throws IOException { synchronized (this) { getEditLog().logGetDelegationToken(id, expiryTime); } getEditLog().logSync(); } /** * Log the renewDelegationToken operation to edit logs * * @param id identifer of the delegation token being renewed * @param expiryTime when delegation token expires */ private void logRenewDelegationToken(DelegationTokenIdentifier id, long expiryTime) throws IOException { synchronized (this) { getEditLog().logRenewDelegationToken(id, expiryTime); } getEditLog().logSync(); } /** * Log the cancelDelegationToken operation to edit logs * * @param id identifer of the delegation token being cancelled */ private void logCancelDelegationToken(DelegationTokenIdentifier id) throws IOException { synchronized (this) { getEditLog().logCancelDelegationToken(id); } getEditLog().logSync(); } /** * Log the updateMasterKey operation to edit logs * * @param key new delegation key. */ public void logUpdateMasterKey(DelegationKey key) throws IOException { synchronized (this) { getEditLog().logUpdateMasterKey(key); } getEditLog().logSync(); } /** * * @return true if delegation token operation is allowed */ private boolean isAllowedDelegationTokenOp() throws IOException { AuthenticationMethod authMethod = getConnectionAuthenticationMethod(); if (UserGroupInformation.isSecurityEnabled() && (authMethod != AuthenticationMethod.KERBEROS) && (authMethod != AuthenticationMethod.KERBEROS_SSL) && (authMethod != AuthenticationMethod.CERTIFICATE)) { return false; } return true; } /** * Returns authentication method used to establish the connection * @return AuthenticationMethod used to establish connection * @throws IOException */ private AuthenticationMethod getConnectionAuthenticationMethod() throws IOException { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); AuthenticationMethod authMethod = ugi.getAuthenticationMethod(); if (authMethod == AuthenticationMethod.PROXY) { authMethod = ugi.getRealUser().getAuthenticationMethod(); } return authMethod; } @Override // NameNodeMXBean public String getHostName() { return this.nameNodeHostName; } @Override // NameNodeMXBean public String getVersion() { return VersionInfo.getVersion() + ", r" + VersionInfo.getRevision(); } @Override // NameNodeMXBean public long getUsed() { return this.getCapacityUsed(); } @Override // NameNodeMXBean public long getFree() { return this.getCapacityRemaining(); } @Override // NameNodeMXBean public long getTotal() { return this.getCapacityTotal(); } @Override // NameNodeMXBean public String getSafemode() { if (!this.isInSafeMode()) return ""; return "Safe mode is ON." + this.getSafeModeTip(); } @Override // NameNodeMXBean public boolean isUpgradeFinalized() { return this.getFSImage().isUpgradeFinalized(); } @Override // NameNodeMXBean public long getNonDfsUsedSpace() { return getCapacityUsedNonDFS(); } @Override // NameNodeMXBean public float getPercentUsed() { return getCapacityUsedPercent(); } @Override // NameNodeMXBean public float getPercentRemaining() { return getCapacityRemainingPercent(); } @Override // NameNodeMXBean public long getTotalBlocks() { return getBlocksTotal(); } @Override // NameNodeMXBean public long getTotalFiles() { return getFilesTotal(); } @Override // NameNodeMXBean public int getThreads() { return ManagementFactory.getThreadMXBean().getThreadCount(); } /** * Returned information is a JSON representation of map with host name as the * key and value is a map of live node attribute keys to its values */ @Override // NameNodeMXBean public String getLiveNodes() { final Map<String, Object> info = new HashMap<String, Object>(); final ArrayList<DatanodeDescriptor> aliveNodeList = this.getDatanodeListForReport(DatanodeReportType.LIVE); for (DatanodeDescriptor node : aliveNodeList) { final Map<String, Object> innerinfo = new HashMap<String, Object>(); innerinfo.put("lastContact", getLastContact(node)); innerinfo.put("usedSpace", getDfsUsed(node)); info.put(node.getHostName(), innerinfo); } return JSON.toString(info); } /** * Returned information is a JSON representation of map with host name as the * key and value is a map of dead node attribute keys to its values */ @Override // NameNodeMXBean public String getDeadNodes() { final Map<String, Object> info = new HashMap<String, Object>(); final ArrayList<DatanodeDescriptor> deadNodeList = this.getDatanodeListForReport(DatanodeReportType.DEAD); removeDecomNodeFromDeadList(deadNodeList); for (DatanodeDescriptor node : deadNodeList) { final Map<String, Object> innerinfo = new HashMap<String, Object>(); innerinfo.put("lastContact", getLastContact(node)); info.put(node.getHostName(), innerinfo); } return JSON.toString(info); } /** * Returned information is a JSON representation of map with host name as the * key and value is a map of decomisioning node attribute keys to its values */ @Override // NameNodeMXBean public String getDecomNodes() { final Map<String, Object> info = new HashMap<String, Object>(); final ArrayList<DatanodeDescriptor> decomNodeList = this.getDecommissioningNodes(); for (DatanodeDescriptor node : decomNodeList) { final Map<String, Object> innerinfo = new HashMap<String, Object>(); innerinfo.put("underReplicatedBlocks", node.decommissioningStatus .getUnderReplicatedBlocks()); innerinfo.put("decommissionOnlyReplicas", node.decommissioningStatus .getDecommissionOnlyReplicas()); innerinfo.put("underReplicateInOpenFiles", node.decommissioningStatus .getUnderReplicatedInOpenFiles()); info.put(node.getHostName(), innerinfo); } return JSON.toString(info); } @Override // NameNodeMXBean public String getNameDirStatuses() { Map<String, Map<File, StorageDirType>> statusMap = new HashMap<String, Map<File, StorageDirType>>(); Map<File, StorageDirType> activeDirs = new HashMap<File, StorageDirType>(); for (Iterator<StorageDirectory> it = getFSImage().dirIterator(); it.hasNext();) { StorageDirectory st = it.next(); activeDirs.put(st.getRoot(), st.getStorageDirType()); } statusMap.put("active", activeDirs); List<Storage.StorageDirectory> removedStorageDirs = getFSImage().getRemovedStorageDirs(); Map<File, StorageDirType> failedDirs = new HashMap<File, StorageDirType>(); for (StorageDirectory st : removedStorageDirs) { failedDirs.put(st.getRoot(), st.getStorageDirType()); } statusMap.put("failed", failedDirs); return JSON.toString(statusMap); } private long getLastContact(DatanodeDescriptor alivenode) { return (System.currentTimeMillis() - alivenode.getLastUpdate())/1000; } private long getDfsUsed(DatanodeDescriptor alivenode) { return alivenode.getDfsUsed(); } private static int roundBytesToGBytes(long bytes) { return Math.round(((float)bytes/(1024 * 1024 * 1024))); } @Override public void getMetrics(MetricsBuilder builder, boolean all) { builder.addRecord("FSNamesystem").setContext("dfs") .addGauge("FilesTotal", "", getFilesTotal()) .addGauge("BlocksTotal", "", getBlocksTotal()) .addGauge("CapacityTotalGB", "", roundBytesToGBytes(getCapacityTotal())) .addGauge("CapacityUsedGB", "", roundBytesToGBytes(getCapacityUsed())) .addGauge("CapacityRemainingGB", "", roundBytesToGBytes(getCapacityRemaining())) .addGauge("TotalLoad", "", getTotalLoad()) .addGauge("CorruptBlocks", "", getCorruptReplicaBlocks()) .addGauge("ExcessBlocks", "", getExcessBlocks()) .addGauge("PendingDeletionBlocks", "", getPendingDeletionBlocks()) .addGauge("PendingReplicationBlocks", "", getPendingReplicationBlocks()) .addGauge("UnderReplicatedBlocks", "", getUnderReplicatedBlocks()) .addGauge("ScheduledReplicationBlocks", "", getScheduledReplicationBlocks()) .addGauge("MissingBlocks", "", getMissingBlocksCount()) .addGauge("BlockCapacity", "", getBlockCapacity()); } private void registerWith(MetricsSystem ms) { ms.register("FSNamesystemMetrics", "FSNamesystem metrics", this); } /** * If the remote IP for namenode method invokation is null, then the * invocation is internal to the namenode. Client invoked methods are invoked * over RPC and always have address != null. */ private boolean isExternalInvocation() { return Server.getRemoteIp() != null; } /** * Log fsck event in the audit log */ void logFsckEvent(String src, InetAddress remoteAddress) throws IOException { if (auditLog.isInfoEnabled()) { logAuditEvent(UserGroupInformation.getCurrentUser(), remoteAddress, "fsck", src, null, null); } } /** * Remove an already decommissioned data node who is neither in include nor * exclude lists from the dead node list. * @param dead, array list of dead nodes */ void removeDecomNodeFromDeadList(ArrayList<DatanodeDescriptor> dead) { // If the include list is empty, any nodes are welcomed and it does not // make sense to exclude any nodes from the cluster. Therefore, no remove. if (hostsReader.getHosts().isEmpty()) { return; } for (Iterator<DatanodeDescriptor> it = dead.iterator();it.hasNext();){ DatanodeDescriptor node = it.next(); if ((!inHostsList(node,null)) && (!inExcludedHostsList(node, null)) && node.isDecommissioned()){ // Include list is not empty, an existing datanode does not appear // in both include or exclude lists and it has been decommissioned. // Remove it from dead node list. it.remove(); } } } @Override public String toString() { return getClass().getSimpleName() + ": " + host2DataNodeMap; } /** * @return Return the current number of stale DataNodes (detected by * HeartbeatMonitor). */ public int getNumStaleNodes() { return this.numStaleNodes; } /** * @return whether or not to avoid writing to stale datanodes */ @Override // FSClusterStats public boolean isAvoidingStaleDataNodesForWrite() { return avoidStaleDataNodesForWrite; } /** * @return The interval used to judge whether or not a DataNode is stale */ public long getStaleInterval() { return this.staleInterval; } /** * Set the value of {@link DatanodeManager#avoidStaleDataNodesForWrite}. The * HeartbeatManager disable avoidStaleDataNodesForWrite when more than half of * the DataNodes are marked as stale. * * @param avoidStaleDataNodesForWrite * The value to set to * {@link DatanodeManager#avoidStaleDataNodesForWrite} */ void setAvoidStaleDataNodesForWrite(boolean avoidStaleDataNodesForWrite) { this.avoidStaleDataNodesForWrite = avoidStaleDataNodesForWrite; } }
[ "archen94@gmail.com" ]
archen94@gmail.com
48813d7213104807c5cb01511281dd8482b5e5cf
cbd39bfae9b72ea864a41b2a30fc092d6ad9a7cf
/app/src/main/java/com/example/walker/myhencoder/view/PaperPlaneView.java
73227ec861c133c6adf76e15c6552919764a14ff
[]
no_license
SingleWolf/MyHenCoder
aa16c718888b567d7830d224f42cdfdf43102195
cff117511af2ef82fd10a9ef7ee85a1b6343b333
refs/heads/master
2021-06-07T22:22:28.045036
2020-01-09T06:29:25
2020-01-09T06:29:25
138,259,792
0
0
null
null
null
null
UTF-8
Java
false
false
5,472
java
package com.example.walker.myhencoder.view; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.annotation.TargetApi; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.v4.view.animation.PathInterpolatorCompat; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.view.animation.LinearInterpolator; import android.widget.ImageView; import android.widget.RelativeLayout; import com.example.walker.myhencoder.R; import java.util.Random; public class PaperPlaneView extends RelativeLayout implements View.OnClickListener { private OnImageListener mOnClickListener; //自定义布局的宽、高 private int mHeight; private int mWidth; private LayoutParams lp; private Drawable[] drawables; private Random random = new Random(); //获取4架纸飞机的宽高 private int dHeight; private int dWidth; private int mX; private int mY; public PaperPlaneView(Context context) { super(context); init(); } public PaperPlaneView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public PaperPlaneView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public PaperPlaneView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(); } private void init() { // 初始化显示的图片 drawables = new Drawable[4]; Drawable pink = getResources().getDrawable(R.drawable.ic_plane_red); Drawable yellow = getResources().getDrawable(R.drawable.ic_plane_yellow); Drawable green = getResources().getDrawable(R.drawable.ic_plane_green); Drawable blue = getResources().getDrawable(R.drawable.ic_plane_blue); drawables[0] = blue; drawables[1] = yellow; drawables[2] = green; drawables[3] = pink; // 获取图的宽高 用于后面的计算 // 注意 我这里4张图片的大小都是一样的,所以我只取了一个 dHeight = dp2px(40); dWidth = dp2px(40); lp = new LayoutParams(dWidth, dHeight); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mWidth = w; mHeight = h; } //真正动画开始的入口,从外部进行调用,x、y分别表示飞机进入之后所 //停留的位置坐标 public void addHeart(int x, int y, int position) { mX = x; mY = y; ImageView imageView = new ImageView(getContext()); // 随机选一个 imageView.setImageDrawable(drawables[position]); imageView.setLayoutParams(lp); addView(imageView); //获取进入前后动画 Animator set = getAnimator(imageView); set.start(); imageView.setOnClickListener(this); } private Animator getAnimator(View target) { AnimatorSet set = getEnterAnimator(target); AnimatorSet set2 = getLineAnimation(target); AnimatorSet finalSet = new AnimatorSet(); finalSet.playSequentially(set, set2); finalSet.setInterpolator(new LinearInterpolator()); finalSet.setTarget(target); return finalSet; } private AnimatorSet getEnterAnimator(final View target) { ObjectAnimator alpha = ObjectAnimator .ofFloat(target, View.ALPHA, 0.2f, 1f); ObjectAnimator translationX = ObjectAnimator .ofFloat(target, View.TRANSLATION_X, -2 * mWidth, -mWidth); AnimatorSet enter = new AnimatorSet(); enter.setDuration(500); enter.setInterpolator(new LinearInterpolator()); enter.playTogether(translationX, alpha); enter.setTarget(target); return enter; } private AnimatorSet getLineAnimation(final View iconView) { ObjectAnimator transX = ObjectAnimator .ofFloat(iconView, "translationX", -dWidth, mX); ObjectAnimator transY = ObjectAnimator .ofFloat(iconView, "translationY", (mHeight - dHeight) / 2, mY); transY.setInterpolator(PathInterpolatorCompat .create(0.7f, 1f)); AnimatorSet flyUpAnim = new AnimatorSet(); flyUpAnim.setDuration(900); flyUpAnim.playTogether(transX, transY); flyUpAnim.setTarget(iconView); return flyUpAnim; } @Override public void onClick(View v) { if (mOnClickListener != null) { mOnClickListener.onClick((ImageView) v); } } public void setOnImageClickListener(OnImageListener listener) { mOnClickListener = listener; } //定义ImageView单击事件 public interface OnImageListener { void onClick(ImageView v); } private int dp2px(float dp) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()); } }
[ "feitianwumu@163.com" ]
feitianwumu@163.com
fee2df34c8043d2b3507537c9627d09a9ceca396
34bc2b0e69e18e8193000e5ff3a6104624f80a34
/Project 1 - Expense Reimbursement System/src/main/java/ers/servlets/EmployeeServlet.java
da0da1324fb2a3784f676867e5ac4d2fe9a7f2ea
[]
no_license
revature-13Aug18-java/code-samples-for-Giles-Farrington
38db6807b6bd431d61691e2c959d0a729674566e
bc873d8659809d2ad87afa90c8bd6bcc98ca2ec4
refs/heads/master
2020-03-31T21:52:43.440893
2018-10-22T15:06:30
2018-10-22T15:06:30
152,596,860
0
0
null
null
null
null
UTF-8
Java
false
false
3,394
java
package ers.servlets; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import com.fasterxml.jackson.databind.ObjectMapper; import ers.pojos.OutputReimbursement; import ers.pojos.Reimbursement; import ers.service.ReimbursementService; @WebServlet("/employee") public class EmployeeServlet extends HttpServlet{ private static Logger log = Logger.getLogger(LoginServlet.class); static ReimbursementService rService = new ReimbursementService(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ReimbursementService rService = new ReimbursementService(); List<Reimbursement> reimbursements = rService.getAll(); List<OutputReimbursement> outputs = new ArrayList<OutputReimbursement>(); System.out.println(reimbursements); for(int i=0;i<reimbursements.size();i++) { String s = reimbursements.get(i).getReimb_submitted().toString(); String r = ""; if(reimbursements.get(i).getReimb_resolved() != null) { r = reimbursements.get(i).getReimb_resolved().toString(); } OutputReimbursement temp = new OutputReimbursement(reimbursements.get(i).getReimb_id(), reimbursements.get(i).getReimb_amount(), s, r, reimbursements.get(i).getReimb_description(), reimbursements.get(i).getReimb_receipt(), reimbursements.get(i).getReimb_author(), reimbursements.get(i).getReimb_resolver(), reimbursements.get(i).getReimb_status_id(), reimbursements.get(i).getReimb_type_id()); outputs.add(temp); } ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(outputs); PrintWriter out = resp.getWriter(); resp.setContentType("application/json"); out.write(json); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { log.trace("Started doPost in EmployeeServlet!!!!!!!!"); BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream())); String json = ""; if(br != null) { log.trace("BUFFERED READER IS NOT NULL"); log.trace("br: " + br); json = br.readLine(); } //ObjectMapper mapper = new ObjectMapper(); Reimbursement toAdd = new Reimbursement(); log.trace(json.toString()); String[] input = json.toString().split(">"); log.trace("NEW SPLIT VALUES: " + input[0] + " & " + input[1] + " & " + input[2] + " & " + input[3]); toAdd.setReimb_amount(Double.parseDouble(input[0])); toAdd.setReimb_description(input[1]); toAdd.setReimb_author(Integer.parseInt(input[2])); toAdd.setReimb_receipt(null); toAdd.setReimb_resolved(null); toAdd.setReimb_resolver(1); toAdd.setReimb_status_id(1); Timestamp rSubmitted = new Timestamp(Calendar.getInstance().getTime().getTime()); toAdd.setReimb_submitted(rSubmitted); toAdd.setReimb_type_id(Integer.parseInt(input[3])); rService.save(toAdd); //Users u = mapper.readValue(json, Users.class); //System.out.println(u.toString()); } }
[ "farringtong@wit.edu" ]
farringtong@wit.edu
c1823b98a45684b4046c09f1bb4fbb7a2072ca1d
6c3cdeb3054dabb7fa180600baa9ef75a5db24b2
/src/main/java/com/citrus/backoffice/employer/domain/valueobjects/EmployerName.java
640e61d240c3d47840fa0e68dd99e1c535c1d9a2
[ "Unlicense" ]
permissive
Citrus-Software-Solutions/citrus-app-BackOffice
f091b6ff4c46e26ab7ec5718bc8c02ad46371bb5
34883b8ce5c13b710e1d36aaf4dc77c498194eac
refs/heads/master
2023-07-08T17:20:26.347526
2021-08-06T15:00:20
2021-08-06T15:00:20
375,538,891
0
0
null
null
null
null
UTF-8
Java
false
false
226
java
package com.citrus.backoffice.employer.domain.valueobjects; public class EmployerName { private String value; public EmployerName(String value) { this.value = value; } public String getValue() { return value; } }
[ "rafael.v.barrientos@gmail.com" ]
rafael.v.barrientos@gmail.com
bb67503e6713d0486983004f3b540fb12f31a6c7
858fa53fae3d1587065f22cab6a020e62c47a331
/Boat.java
3d10b8625a67a24398dc270bc0a189c6a9644d29
[]
no_license
camdensaks/Unit7-Camden
9639bb9d5f02e8b9eddc5b51d0084c4ab775431c
e5fffc76117ae924e95de712a8efd6e9b5dabf84
refs/heads/master
2021-02-25T21:56:55.345115
2020-03-13T16:23:43
2020-03-13T16:23:43
245,470,279
0
0
null
null
null
null
UTF-8
Java
false
false
1,353
java
public class Boat { private boolean hasMotor; private int topSpeed; private int length; public Boat(){ this.hasMotor = false; this.topSpeed = 0; this.length = 0; } public Boat(boolean hasMotor, int topSpeed, int length){ this.hasMotor = hasMotor; this.topSpeed = topSpeed; this.length = length; } public String move(int nautMiles){ if(hasMotor){ return "The boat moved " + nautMiles + " nautical miles quickly. "; } else return "The boat took forever to move " + nautMiles + " nautical miles. "; } public String sink(){ if(length > 10){ return "Boat sank in " + (length*2 + 9)/1.4 + " minutes"; } else return "Boat sank instantly"; } public String toString(){ return "Boat - \n\t Motor: " + hasMotor + "\n\t" + "Top Speed: " + topSpeed + " knots" + "\n\t" + "Length: " + length + "ft. "; } public static void main(String[] args){ Boat b = new Boat(); Boat myBoat = new Boat(true, 23, 44); System.out.println("Default boat: \n" + b); System.out.println("My boat: \n" + myBoat); System.out.println(myBoat.move(45)); System.out.println(myBoat.sink()); System.out.println(b.sink()); } }
[ "54951342+camdensaks@users.noreply.github.com" ]
54951342+camdensaks@users.noreply.github.com
25bcc1c7e2dcee0f0f177ef57365e613d27f980e
373d1b76ef8145653bae07e1d6814a6f3dae8da0
/src/main/java/com/bridgelabz/carservice/InvoiceSummery.java
962a45185438db82998a0c4e644c7f4fc3ec146a
[]
no_license
vaibhavkokate210/CabInvoiceGenerator
56dde9e38f4640384a2dd053b2b0b5e5907ba7a0
7846f1ce73a756fa7a9cd92f8cef868efb3ebb88
refs/heads/master
2023-08-18T15:15:00.324710
2021-09-17T06:02:51
2021-09-17T06:02:51
406,617,444
0
0
null
null
null
null
UTF-8
Java
false
false
405
java
package com.bridgelabz.carservice; public class InvoiceSummery { public int totalNumberOfRides; public double totalFare; public double avgFarePerRide; public InvoiceSummery(int totalNumberOfRides, double totalFare) { this.totalNumberOfRides = totalNumberOfRides; this.totalFare = totalFare; this.avgFarePerRide = totalFare/totalNumberOfRides; } }
[ "vaibhavkokate210@gmail.com" ]
vaibhavkokate210@gmail.com
319c5aca4b0fafda915223267bc56d8fd646e1bb
3144772be9d90dfc72346b6dec053730c804273d
/src/main/java/sul/protocol/java338/clientbound/UpdateBlockEntity.java
7047ba718522e64e7ba3a6bff378bf27e366df50
[ "MIT" ]
permissive
sel-utils/java
be42f04044674afd77808ae324515358995ba854
9b9cc88dfc6e871ceb7eddb3d7c6585756fe1e07
refs/heads/master
2021-01-23T05:57:03.737951
2018-02-05T12:12:02
2018-02-05T12:12:02
86,325,412
3
1
null
2017-06-14T20:36:36
2017-03-27T11:06:07
Java
UTF-8
Java
false
false
2,347
java
/* * This file was automatically generated by sel-utils and * released under the MIT License. * * License: https://github.com/sel-project/sel-utils/blob/master/LICENSE * Repository: https://github.com/sel-project/sel-utils * Generated from https://github.com/sel-project/sel-utils/blob/master/xml/protocol/java338.xml */ package sul.protocol.java338.clientbound; import java.util.Arrays; import sul.utils.*; public class UpdateBlockEntity extends Packet { public static final int ID = (int)9; public static final boolean CLIENTBOUND = true; public static final boolean SERVERBOUND = false; @Override public int getId() { return ID; } // action public static final byte MOB_SPAWNER_DATA = (byte)1; public static final byte COMMAND_BLOCK_TEXT = (byte)2; public static final byte BEACON_POWERS = (byte)3; public static final byte MOB_HEAD_DATA = (byte)4; public static final byte FLOWER_POT_FLOWER = (byte)5; public static final byte BANNER_DATA = (byte)6; public static final byte STRUCTURE_DATA = (byte)7; public static final byte END_GATEWAY_DESTINATION = (byte)8; public static final byte SIGN_TEXT = (byte)9; public static final byte SHULKER_BOX_DECLARATION = (byte)10; public static final byte BED_COLOR = (byte)11; public long position; public byte action; public byte[] nbt = new byte[0]; public UpdateBlockEntity() {} public UpdateBlockEntity(long position, byte action, byte[] nbt) { this.position = position; this.action = action; this.nbt = nbt; } @Override public int length() { return nbt.length + 10; } @Override public byte[] encode() { this._buffer = new byte[this.length()]; this.writeVaruint(ID); this.writeBigEndianLong(position); this.writeBigEndianByte(action); this.writeBytes(nbt); return this.getBuffer(); } @Override public void decode(byte[] buffer) { this._buffer = buffer; this.readVaruint(); position=readBigEndianLong(); action=readBigEndianByte(); nbt=this.readBytes(this._buffer.length-this._index); } public static UpdateBlockEntity fromBuffer(byte[] buffer) { UpdateBlockEntity ret = new UpdateBlockEntity(); ret.decode(buffer); return ret; } @Override public String toString() { return "UpdateBlockEntity(position: " + this.position + ", action: " + this.action + ", nbt: " + Arrays.toString(this.nbt) + ")"; } }
[ "selutils@mail.com" ]
selutils@mail.com
1ee467fcae289e2af00f6c07929ffbfcb4e7213f
a2a3e9dda3e1f9b294d1d556e4dbeb8be88084be
/src/main/java/com/bsbls/deneme/laf/desktopx/view/SearchPanel.java
ec9c04ef849007c2e6b2e49b852b62777ad20dce
[]
no_license
bosbeles/laf_demo
e35356d70cba107dc13a111a93102d5faa2c59b5
b3677056746f6939324a5520a6f4518076fa7578
refs/heads/master
2022-11-07T11:13:50.483185
2020-06-21T19:39:41
2020-06-21T19:39:41
273,088,946
0
0
null
null
null
null
UTF-8
Java
false
false
6,081
java
package com.bsbls.deneme.laf.desktopx.view; import com.bsbls.deneme.laf.desktopx.action.model.ActionDictionary; import com.bsbls.deneme.laf.desktopx.action.model.ActionWrapper; import com.bsbls.deneme.laf.util.GuiUtil; import javax.swing.*; import javax.swing.border.AbstractBorder; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import java.awt.*; import java.awt.event.ActionEvent; import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; public class SearchPanel extends JPanel { private final ActionDictionary dictionary; private JTextField searchBox; private JTabbedPane tabbedPane; private Consumer<SearchPanel> onEsc; public SearchPanel(ActionDictionary dictionary) { this.dictionary = dictionary; initPanel(); } public JTextField getSearchBox() { return searchBox; } private void initPanel() { setLayout(new GridBagLayout()); setBorder(BorderFactory.createLineBorder(new Color(97,97,97))); setPreferredSize(new Dimension(500, 300)); //searchBox = new JTextField("Search"); createSearchBox(); SearchPanelUI layerUI = new SearchPanelUI(searchBox); tabbedPane = new JTabbedPane(); tabbedPane.addChangeListener(e -> { Component selectedComponent = tabbedPane.getSelectedComponent(); if (selectedComponent instanceof TabContentPanel) { ((TabContentPanel) selectedComponent).updatePanel(); } }); JLayer<JComponent> layer = new JLayer<>(tabbedPane, layerUI); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 1.0; gbc.fill = GridBagConstraints.HORIZONTAL; this.add(searchBox, gbc); gbc.fill = GridBagConstraints.BOTH; gbc.gridy++; gbc.weighty = 1.0; this.add(layer, gbc); searchBox.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { search(searchBox.getText()); } @Override public void removeUpdate(DocumentEvent e) { search(searchBox.getText()); } @Override public void changedUpdate(DocumentEvent e) { search(searchBox.getText()); } }); getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ESCAPE"), "clear"); getActionMap().put("clear", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (searchBox.getText().isEmpty()) { onEsc.accept(SearchPanel.this); } else { searchBox.setText(""); } } }); } public void onEsc(Consumer<SearchPanel> consumer) { this.onEsc = consumer; } private void createSearchBox() { searchBox = new JTextField() { @Override public void paint(Graphics g) { super.paint(g); if (getText().length() == 0) { int h = getHeight(); ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); Insets ins = getInsets(); FontMetrics fm = g.getFontMetrics(); int c0 = getBackground().getRGB(); int c1 = getForeground().getRGB(); int m = 0xfefefefe; int c2 = ((c0 & m) >>> 1) + ((c1 & m) >>> 1); g.setColor(new Color(c2, true)); g.drawString(GuiUtil.getText("search.prompt"), ins.left, h / 2 + fm.getAscent() / 2 - 2); } } }; searchBox.setFont(new Font("Segoe UI", Font.PLAIN, 12)); Border outer = searchBox.getBorder(); Border search = new IconBorder(new ImageIcon(getClass().getClassLoader().getResource("search.png"))); searchBox.setBorder( new CompoundBorder( outer, new CompoundBorder(BorderFactory.createEmptyBorder(6, 2, 6, 6), search)) ); } private void search(String text) { List<ActionWrapper> searchResult = dictionary.search(text); System.out.println(searchResult); Component selectedComponent = tabbedPane.getSelectedComponent(); if (selectedComponent instanceof TabContentPanel) { TabContentPanel contentPanel = (TabContentPanel) selectedComponent; List<String> actions = searchResult.stream().map(a -> a.getName()).collect(Collectors.toList()); contentPanel.getMenu().getSearchMenu().setActionList(actions); contentPanel.updatePanel(); } } public void createTabPanel(String name, JComponent panel) { tabbedPane.addTab(name, panel); } private static class IconBorder extends AbstractBorder { private final Icon icon; IconBorder(Icon icon) { this.icon = icon; } private static final long serialVersionUID = 1; @Override public Insets getBorderInsets(Component c, Insets insets) { insets.left = icon.getIconWidth() + 4; insets.right = insets.top = insets.bottom = 0; return insets; } @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { icon.paintIcon(c, g, x, y + (height - icon.getIconHeight()) / 2); } } }
[ "bosbeles@gmail.com" ]
bosbeles@gmail.com
475f3ec2d530b8102126217e24a3c2fbf0c3e8be
afb3fef3c5ab5eb3140815f21ca6ad6e04d4499c
/cloud-mybatis/src/main/java/com/duoqio/cloud/mybatis/CloudMyBatisApplication.java
18cc2faa0c44d34aaff312ffd1a36e4c33b161fc
[]
no_license
C644753271/spring-boot-
b7024063fb5919e1ce69591693960d9fb453d03a
d05afb6ff5d85e7b18ef989d233396e2e33fdbfe
refs/heads/master
2020-04-24T07:12:42.247825
2019-02-21T08:27:48
2019-02-21T08:27:48
171,791,249
4
0
null
null
null
null
UTF-8
Java
false
false
362
java
package com.duoqio.cloud.mybatis; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class CloudMyBatisApplication { public static void main(String[] args) throws Exception { SpringApplication.run(CloudMyBatisApplication.class, args); } }
[ "noreply@github.com" ]
noreply@github.com
3237a6f117b9de7de08986f99e6aec53743853dc
46002d1f5751a5de398721dc57f034f16bc8f999
/app/src/main/java/com/example/game/Splash.java
9e1a3b2a4708bf4e909585ac7de2101a939a9463
[]
no_license
rajput-abdullah/QuizAndroidGame
16c35ac9664fcf355a1cef83b2c0d21b33aad26c
3067f99aca781b32ae67c75358863753431da8ed
refs/heads/master
2023-02-11T13:32:30.121910
2021-01-08T15:28:26
2021-01-08T15:28:26
327,940,155
1
0
null
null
null
null
UTF-8
Java
false
false
787
java
package com.example.game; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import androidx.appcompat.app.AppCompatActivity; public class Splash extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); new Handler().postDelayed(new Runnable() { @Override public void run() { // This method will be executed once the timer is over Intent i = new Intent(Splash.this, MainActivity.class); startActivity(i); finish(); } }, 2500); } }
[ "lun@gmail.com" ]
lun@gmail.com
dfd8f8772ce3f6dee1c4f51cd28eedc0c2036f47
7a1aeae562055859874d36da23a85c858115d62a
/src/main/java/com/dw2/reserva/persistence/repository/ReserveLaboratoryRepository.java
ead9225ff3de7bfa11bc183a59e9505ae1264f13
[]
no_license
Kainanpr/dw2_reserva
12a0b8e2e9fc63ab4fd71e5cb63668a21311a16c
173e02dfe47f34541264430853489763b7d23a2a
refs/heads/master
2020-08-17T11:03:18.348280
2019-11-18T21:12:22
2019-11-18T21:12:22
215,656,555
0
0
null
null
null
null
UTF-8
Java
false
false
388
java
package com.dw2.reserva.persistence.repository; import com.dw2.reserva.model.ReserveLaboratory; import java.util.List; public interface ReserveLaboratoryRepository { ReserveLaboratory getById(Integer id); List<ReserveLaboratory> getAll(); int save(ReserveLaboratory reserveLaboratory); int update(ReserveLaboratory reserveLaboratory); int delete(Integer id); }
[ "Kainan.Ramos@vistajet.com" ]
Kainan.Ramos@vistajet.com
5df98b5af3916431845428e50f58f6d6d9e5bb66
1f795e83ab6f2a49d3f241692b43300792102e7b
/src/main/java/com/flexnet/operations/webservices/CreatedOrganizationDataListType.java
c7c68db2d40d7d92ca742528bab9c96cdaf5bc2c
[]
no_license
ali-j-maqbool/FNOAvangateConnector
4b9f43626a074b33d7774ce2c5bf60b3312a31e7
93878e75bb9747e8b323065153bb280fc7b1f0b3
refs/heads/master
2021-01-17T21:11:29.063784
2016-06-24T11:29:34
2016-06-24T11:29:34
61,436,752
0
0
null
2016-06-24T11:29:35
2016-06-18T14:19:44
Java
UTF-8
Java
false
false
4,769
java
/** * CreatedOrganizationDataListType.java * * This file was auto-generated from WSDL * by the Apache Axis 1.3 Oct 05, 2005 (05:23:37 EDT) WSDL2Java emitter. */ package com.flexnet.operations.webservices; public class CreatedOrganizationDataListType implements java.io.Serializable { private com.flexnet.operations.webservices.OrganizationIdentifierType[] organization; public CreatedOrganizationDataListType() { } public CreatedOrganizationDataListType( com.flexnet.operations.webservices.OrganizationIdentifierType[] organization) { this.organization = organization; } /** * Gets the organization value for this CreatedOrganizationDataListType. * * @return organization */ public com.flexnet.operations.webservices.OrganizationIdentifierType[] getOrganization() { return organization; } /** * Sets the organization value for this CreatedOrganizationDataListType. * * @param organization */ public void setOrganization(com.flexnet.operations.webservices.OrganizationIdentifierType[] organization) { this.organization = organization; } public com.flexnet.operations.webservices.OrganizationIdentifierType getOrganization(int i) { return this.organization[i]; } public void setOrganization(int i, com.flexnet.operations.webservices.OrganizationIdentifierType _value) { this.organization[i] = _value; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof CreatedOrganizationDataListType)) return false; CreatedOrganizationDataListType other = (CreatedOrganizationDataListType) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((this.organization==null && other.getOrganization()==null) || (this.organization!=null && java.util.Arrays.equals(this.organization, other.getOrganization()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (getOrganization() != null) { for (int i=0; i<java.lang.reflect.Array.getLength(getOrganization()); i++) { java.lang.Object obj = java.lang.reflect.Array.get(getOrganization(), i); if (obj != null && !obj.getClass().isArray()) { _hashCode += obj.hashCode(); } } } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(CreatedOrganizationDataListType.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("urn:com.macrovision:flexnet/operations", "createdOrganizationDataListType")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("organization"); elemField.setXmlName(new javax.xml.namespace.QName("urn:com.macrovision:flexnet/operations", "organization")); elemField.setXmlType(new javax.xml.namespace.QName("urn:com.macrovision:flexnet/operations", "organizationIdentifierType")); elemField.setMinOccurs(0); elemField.setNillable(false); elemField.setMaxOccursUnbounded(true); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
[ "ali.j.maqbool@gmail.com" ]
ali.j.maqbool@gmail.com
8cad5fbb5ac39d4ae7417f52a181aa606b7a9acf
6f392eec228d3c608168d73342088a5cc4f09d2f
/entity-view/processor/src/main/java/com/blazebit/persistence/view/processor/BuilderClassWriter.java
f4ab415bda05b4864ebf1c4b40bd5a7bb5866535
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
omarlo88/blaze-persistence
e118d92b783a7337e48c73e75c5a0d422aa404ac
109277d66657c24dcfaa16400c299bf7f653dfad
refs/heads/master
2023-06-12T20:20:10.386088
2021-05-22T10:00:01
2021-06-05T09:18:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
92,464
java
/* * Copyright 2014 - 2021 Blazebit. * * 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.blazebit.persistence.view.processor; import com.blazebit.persistence.view.processor.annotation.AnnotationMetaCollection; import com.blazebit.persistence.view.processor.annotation.AnnotationMetaMap; import com.blazebit.persistence.view.processor.annotation.AnnotationMetaSingularAttribute; import javax.lang.model.element.ElementKind; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeVariable; import java.util.Collection; import java.util.List; /** * @author Christian Beikov * @since 1.5.0 */ public final class BuilderClassWriter { private static final String BUILDER_CLASS_NAME_SUFFIX = "Builder"; private static final String NEW_LINE = System.lineSeparator(); private static final String PARAMETER_PREFIX = "Param"; private BuilderClassWriter() { } public static void writeFile(StringBuilder sb, MetaEntityView entity, Context context) { sb.setLength(0); generateBody(sb, entity, context); ClassWriterUtils.writeFile(sb, entity.getPackageName(), entity.getSimpleName() + BUILDER_CLASS_NAME_SUFFIX, entity.getBuilderImportContext(), context); } private static void generateBody(StringBuilder sb, MetaEntityView entity, Context context) { if (context.addGeneratedAnnotation()) { ClassWriterUtils.writeGeneratedAnnotation(sb, entity.getBuilderImportContext(), context); sb.append(NEW_LINE); } if (context.isAddSuppressWarningsAnnotation()) { sb.append(ClassWriterUtils.writeSuppressWarnings()); sb.append(NEW_LINE); } sb.append("@").append(entity.builderImportType(Constants.STATIC_BUILDER)).append("(").append(entity.metamodelImportType(entity.getQualifiedName())).append(".class)"); sb.append(NEW_LINE); printClassDeclaration(sb, entity, context); sb.append(NEW_LINE); Collection<MetaAttribute> members = entity.getMembers(); for (MetaAttribute metaMember : members) { metaMember.appendBuilderAttributeDeclarationString(sb); sb.append(NEW_LINE); } sb.append(" protected final ").append(entity.builderImportType(Constants.MAP)).append("<String, Object> optionalParameters;").append(NEW_LINE); sb.append(NEW_LINE); printConstructors(sb, entity, context); sb.append(NEW_LINE); String builderTypeVariable = entity.getSafeTypeVariable("BuilderType"); for (MetaAttribute metaMember : members) { appendMember(sb, entity, metaMember, builderTypeVariable); } appendUtilityMethods(sb, entity, context); appendGetMethods(sb, entity, context); appendWithMethods(sb, entity, builderTypeVariable, context); appendWithBuilderMethods(sb, entity, builderTypeVariable, context); sb.append(NEW_LINE); List<TypeVariable> typeArguments = (List<TypeVariable>) ((DeclaredType) entity.getTypeElement().asType()).getTypeArguments(); String elementType = entity.getSafeTypeVariable("ElementType"); StringBuilder tempSb = new StringBuilder(); for (MetaConstructor constructor : entity.getConstructors()) { String className = Character.toUpperCase(constructor.getName().charAt(0)) + constructor.getName().substring(1); sb.append(NEW_LINE); sb.append(" public static class ").append(className); tempSb.setLength(0); tempSb.append(className); if (!typeArguments.isEmpty()) { sb.append("<"); tempSb.append("<"); printTypeVariable(sb, entity, typeArguments.get(0)); tempSb.append(typeArguments.get(0)); for (int i = 1; i < typeArguments.size(); i++) { sb.append(", "); printTypeVariable(sb, entity, typeArguments.get(i)); tempSb.append(", "); tempSb.append(typeArguments.get(i)); } sb.append(">"); tempSb.append(">"); } String builderType = tempSb.toString(); sb.append(" extends ").append(entity.getSimpleName()).append(BUILDER_CLASS_NAME_SUFFIX); sb.append("<"); for (int i = 0; i < typeArguments.size(); i++) { sb.append(typeArguments.get(i)); sb.append(", "); } sb.append(entity.importType(Constants.ENTITY_VIEW_BUILDER)).append("<").append(entity.builderImportType(entity.getQualifiedName())).append(">"); sb.append("> implements "); sb.append(entity.builderImportType(Constants.ENTITY_VIEW_BUILDER)); sb.append("<"); sb.append(entity.builderImportType(entity.getQualifiedName())); sb.append(">"); sb.append(" {").append(NEW_LINE); for (MetaAttribute metaMember : constructor.getParameters()) { metaMember.appendBuilderAttributeDeclarationString(sb); sb.append(NEW_LINE); } sb.append(NEW_LINE); sb.append(" public ").append(className).append("(").append(entity.builderImportType(Constants.MAP)).append("<String, Object> optionalParameters) {").append(NEW_LINE); sb.append(" super(optionalParameters);").append(NEW_LINE); for (MetaAttribute metaMember : constructor.getParameters()) { if (metaMember.getKind() == MappingKind.PARAMETER) { if (metaMember.isPrimitive()) { sb.append("!optionalParameters.containsKey(\"").append(metaMember.getMapping()).append("\") ? "); metaMember.appendDefaultValue(sb, false, true, entity.getBuilderImportContext()); sb.append(" : "); } sb.append(" this.").append(metaMember.getPropertyName()).append(" = (").append(entity.builderImportType(metaMember.getBuilderImplementationTypeString())).append(") optionalParameters.get(\"").append(metaMember.getMapping()).append("\");").append(NEW_LINE); } } sb.append(" }").append(NEW_LINE); // T build() sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public ").append(entity.builderImportType(entity.getQualifiedName())).append(" build() {").append(NEW_LINE); sb.append(" return new ").append(entity.builderImportType(TypeUtils.getDerivedTypeName(entity.getTypeElement()) + ImplementationClassWriter.IMPL_CLASS_NAME_SUFFIX)).append("("); if (members.isEmpty() && constructor.getParameters().isEmpty()) { sb.append("(").append(entity.builderImportType(TypeUtils.getDerivedTypeName(entity.getTypeElement()) + ImplementationClassWriter.IMPL_CLASS_NAME_SUFFIX)).append(") null, optionalParameters);").append(NEW_LINE); } else { sb.append(NEW_LINE); appendConstructorArguments(sb, entity, constructor); sb.append(NEW_LINE).append(" );").append(NEW_LINE); } sb.append(" }").append(NEW_LINE); // X with(int parameterIndex, Object value) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public "); sb.append(builderType); sb.append(" with(int parameterIndex, Object value) {").append(NEW_LINE); sb.append(" switch (parameterIndex) {").append(NEW_LINE); List<MetaAttribute> parameters = constructor.getParameters(); boolean first = true; for (int i = 0; i < parameters.size(); i++) { first = false; MetaAttribute metaMember = parameters.get(i); sb.append(" case ").append(i).append(":").append(NEW_LINE); sb.append(" this.").append(metaMember.getPropertyName()).append(" = "); sb.append("value == null ? "); metaMember.appendDefaultValue(sb, true, true, entity.getBuilderImportContext()); sb.append(" : "); sb.append("(").append(metaMember.getBuilderImplementationTypeString()).append(") value;").append(NEW_LINE); sb.append(" break;").append(NEW_LINE); } sb.append(" default:").append(NEW_LINE); sb.append(" throw new IllegalArgumentException(\"Unknown parameter index: \" + parameterIndex);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); if (!first) { sb.append(" return this;").append(NEW_LINE); } sb.append(" }").append(NEW_LINE); // <ElementType> ElementType get(int parameterIndex) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(elementType).append(" get(int parameterIndex) {").append(NEW_LINE); sb.append(" switch (parameterIndex) {").append(NEW_LINE); for (int i = 0; i < parameters.size(); i++) { MetaAttribute metaMember = parameters.get(i); sb.append(" case ").append(i).append(":").append(NEW_LINE); sb.append(" return (").append(elementType).append(") (Object) this.").append(metaMember.getPropertyName()).append(";").append(NEW_LINE); } sb.append(" }").append(NEW_LINE); sb.append(" throw new IllegalArgumentException(\"Unknown parameter index: \" + parameterIndex);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); for (MetaAttribute metaMember : entity.getMembers()) { appendMemberWith(sb, entity, metaMember, builderType); } appendWithMethods(sb, entity, builderType, context); appendWithBuilderMethods(sb, entity, builderType, context); appendWithBuilderMethods(sb, constructor, context, builderType); for (MetaAttribute metaMember : constructor.getParameters()) { appendMember(sb, entity, metaMember, builderType); } sb.append(" }").append(NEW_LINE); } MetaConstructor constructor = null; if (entity.hasEmptyConstructor()) { for (MetaConstructor entityConstructor : entity.getConstructors()) { if (entityConstructor.getParameters().isEmpty()) { constructor = entityConstructor; break; } } } else { constructor = entity.getConstructors().iterator().next(); } String builderResult = entity.getSafeTypeVariable("BuilderResult"); sb.append(NEW_LINE); sb.append(" public static class Nested<"); tempSb.setLength(0); tempSb.append("Nested<"); for (int i = 0; i < typeArguments.size(); i++) { printTypeVariable(sb, entity, typeArguments.get(i)); sb.append(", "); tempSb.append(typeArguments.get(i)); tempSb.append(", "); } sb.append(builderResult).append(">"); tempSb.append(builderResult).append(">"); String builderType = tempSb.toString(); sb.append(" extends ").append(entity.getSimpleName()).append(BUILDER_CLASS_NAME_SUFFIX); sb.append("<"); for (int i = 0; i < typeArguments.size(); i++) { sb.append(typeArguments.get(i)); sb.append(", "); } sb.append(builderType); sb.append("> implements "); sb.append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)); sb.append("<"); sb.append(entity.builderImportType(entity.getQualifiedName())); sb.append(", ").append(builderResult).append(", "); sb.append(builderType); sb.append("> {").append(NEW_LINE); sb.append(NEW_LINE); sb.append(" private final ").append(entity.builderImportType(Constants.ENTITY_VIEW_BUILDER_LISTENER)).append(" listener;").append(NEW_LINE); sb.append(" private final ").append(builderResult).append(" result;").append(NEW_LINE); for (MetaAttribute metaMember : constructor.getParameters()) { metaMember.appendBuilderAttributeDeclarationString(sb); sb.append(NEW_LINE); } sb.append(NEW_LINE); sb.append(" public Nested(").append(entity.builderImportType(Constants.MAP)).append("<String, Object> optionalParameters, ").append(entity.builderImportType(Constants.ENTITY_VIEW_BUILDER_LISTENER)).append(" listener, ").append(builderResult).append(" result) {").append(NEW_LINE); sb.append(" super(optionalParameters);").append(NEW_LINE); for (MetaAttribute metaMember : constructor.getParameters()) { if (metaMember.getKind() == MappingKind.PARAMETER) { if (metaMember.isPrimitive()) { sb.append("!optionalParameters.containsKey(\"").append(metaMember.getMapping()).append("\") ? "); metaMember.appendDefaultValue(sb, false, true, entity.getBuilderImportContext()); sb.append(" : "); } sb.append(" this.").append(metaMember.getPropertyName()).append(" = (").append(entity.builderImportType(metaMember.getBuilderImplementationTypeString())).append(") optionalParameters.get(\"").append(metaMember.getMapping()).append("\");").append(NEW_LINE); } } sb.append(" this.listener = listener;").append(NEW_LINE); sb.append(" this.result = result;").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // X build() sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public ").append(builderResult).append(" build() {").append(NEW_LINE); sb.append(" listener.onBuildComplete(new ").append(entity.builderImportType(TypeUtils.getDerivedTypeName(entity.getTypeElement()) + ImplementationClassWriter.IMPL_CLASS_NAME_SUFFIX)).append("("); if (members.isEmpty() && constructor.getParameters().isEmpty()) { sb.append("(").append(entity.builderImportType(TypeUtils.getDerivedTypeName(entity.getTypeElement()) + ImplementationClassWriter.IMPL_CLASS_NAME_SUFFIX)).append(") null, optionalParameters));").append(NEW_LINE); } else { sb.append(NEW_LINE); appendConstructorArguments(sb, entity, constructor); sb.append(NEW_LINE).append(" ));").append(NEW_LINE); } sb.append(" return result;").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // X with(int parameterIndex, Object value) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public "); sb.append(builderType); sb.append(" with(int parameterIndex, Object value) {").append(NEW_LINE); sb.append(" switch (parameterIndex) {").append(NEW_LINE); List<MetaAttribute> parameters = constructor.getParameters(); boolean first = true; for (int i = 0; i < parameters.size(); i++) { first = false; MetaAttribute metaMember = parameters.get(i); sb.append(" case ").append(i).append(":").append(NEW_LINE); sb.append(" this.").append(metaMember.getPropertyName()).append(" = "); sb.append("value == null ? "); metaMember.appendDefaultValue(sb, true, true, entity.getBuilderImportContext()); sb.append(" : "); sb.append("(").append(metaMember.getBuilderImplementationTypeString()).append(") value;").append(NEW_LINE); sb.append(" break;").append(NEW_LINE); } sb.append(" default:").append(NEW_LINE); sb.append(" throw new IllegalArgumentException(\"Unknown parameter index: \" + parameterIndex);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); if (!first) { sb.append(" return this;").append(NEW_LINE); } sb.append(" }").append(NEW_LINE); // <ElementType> ElementType get(int parameterIndex) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(elementType).append(" get(int parameterIndex) {").append(NEW_LINE); sb.append(" switch (parameterIndex) {").append(NEW_LINE); for (int i = 0; i < parameters.size(); i++) { MetaAttribute metaMember = parameters.get(i); sb.append(" case ").append(i).append(":").append(NEW_LINE); sb.append(" return (").append(elementType).append(") (Object) this.").append(metaMember.getPropertyName()).append(";").append(NEW_LINE); } sb.append(" }").append(NEW_LINE); sb.append(" throw new IllegalArgumentException(\"Unknown parameter index: \" + parameterIndex);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); for (MetaAttribute metaMember : entity.getMembers()) { appendMemberWith(sb, entity, metaMember, builderType); } appendWithMethods(sb, entity, builderType, context); appendWithBuilderMethods(sb, entity, builderType, context); appendWithBuilderMethods(sb, constructor, context, builderType); for (MetaAttribute metaMember : constructor.getParameters()) { appendMember(sb, entity, metaMember, builderType); } sb.append(" }").append(NEW_LINE); sb.append("}"); sb.append(NEW_LINE); } private static void appendConstructorArguments(StringBuilder sb, MetaEntityView entity, MetaConstructor constructor) { boolean first = true; MetaAttribute idMember = entity.getIdMember(); if (idMember != null) { sb.append(" this.").append(idMember.getPropertyName()); first = false; } for (MetaAttribute member : entity.getMembers()) { if (first) { first = false; } else if (member != idMember) { sb.append(",").append(NEW_LINE); } if (member != idMember) { if (member.getConvertedModelType() == null) { sb.append(" this.").append(member.getPropertyName()); } else if (member.isSubview()) { sb.append(" (").append(member.getImplementationTypeString()).append(") ") .append(entity.getSimpleName()).append(MetamodelClassWriter.META_MODEL_CLASS_NAME_SUFFIX).append(".") .append(member.getPropertyName()).append(".attr().getType().getConverter().convertToViewType(this.").append(member.getPropertyName()).append(')'); } else { sb.append(" (").append(member.getImplementationTypeString()).append(") ") .append(entity.getSimpleName()).append(MetamodelClassWriter.META_MODEL_CLASS_NAME_SUFFIX).append(".") .append(member.getPropertyName()).append(".getType().getConverter().convertToViewType(this.").append(member.getPropertyName()).append(')'); } } } for (MetaAttribute member : constructor.getParameters()) { if (first) { first = false; } else { sb.append(",").append(NEW_LINE); } sb.append(" this.").append(member.getPropertyName()); } } private static void appendMember(StringBuilder sb, MetaEntityView entity, MetaAttribute metaMember, String builderType) { metaMember.appendBuilderAttributeGetterAndSetterString(sb); sb.append(NEW_LINE); appendMemberWith(sb, entity, metaMember, builderType); } private static void appendMemberWith(StringBuilder sb, MetaEntityView entity, MetaAttribute metaMember, String builderType) { ElementKind kind = metaMember.getElement() == null ? null : metaMember.getElement().getKind(); sb.append(" public ").append(builderType).append(" with"); if (kind == ElementKind.PARAMETER) { sb.append(PARAMETER_PREFIX); } sb.append(Character.toUpperCase(metaMember.getPropertyName().charAt(0))); sb.append(metaMember.getPropertyName(), 1, metaMember.getPropertyName().length()); sb.append('('); sb.append(metaMember.getBuilderImplementationTypeString()); sb.append(' ') .append(metaMember.getPropertyName()) .append(") {").append(NEW_LINE) .append(" this.") .append(metaMember.getPropertyName()) .append(" = ") .append(metaMember.getPropertyName()) .append(";") .append(NEW_LINE) .append(" return (").append(builderType).append(") this;") .append(NEW_LINE) .append(" }"); if (metaMember.isSubview()) { String memberBuilderFqn = metaMember.getGeneratedTypePrefix() + BuilderClassWriter.BUILDER_CLASS_NAME_SUFFIX; List<TypeVariable> typeArguments = (List<TypeVariable>) ((DeclaredType) metaMember.getSubviewElement().asType()).getTypeArguments(); if (metaMember instanceof AnnotationMetaMap) { AnnotationMetaMap mapMember = (AnnotationMetaMap) metaMember; String listener = "new " + entity.builderImportType(Constants.ENTITY_VIEW_BUILDER_MAP_LISTENER) + "(getMap(\"" + metaMember.getPropertyName() + "\"), key)"; sb.append(NEW_LINE); sb.append(" public "); if (!typeArguments.isEmpty()) { sb.append("<"); for (int i = 0; i < typeArguments.size(); i++) { sb.append("Sub"); printTypeVariable(sb, entity, typeArguments.get(i)); sb.append(", "); } sb.setCharAt(sb.length() - 2, '>'); } sb.append(entity.builderImportType(memberBuilderFqn)).append(".Nested<"); for (int i = 0; i < typeArguments.size(); i++) { sb.append("Sub"); sb.append(typeArguments.get(i)); sb.append(", "); } sb.append("? extends ").append(builderType).append("> with"); if (kind == ElementKind.PARAMETER) { sb.append(PARAMETER_PREFIX); } sb.append(Character.toUpperCase(metaMember.getPropertyName().charAt(0))); sb.append(metaMember.getPropertyName(), 1, metaMember.getPropertyName().length()); sb.append("Builder(Object key) {") .append(NEW_LINE) .append(" return new ").append(entity.builderImportType(memberBuilderFqn)) .append(".Nested<>(optionalParameters, ").append(listener).append(", (").append(builderType).append(") this);") .append(NEW_LINE) .append(" }"); sb.append(NEW_LINE); if (mapMember.isKeySubview()) { String keyMemberBuilderFqn = mapMember.getGeneratedKeyTypePrefix() + BuilderClassWriter.BUILDER_CLASS_NAME_SUFFIX; List<TypeVariable> keyTypeArguments = (List<TypeVariable>) ((DeclaredType) mapMember.getKeySubviewElement().asType()).getTypeArguments(); sb.append(NEW_LINE); sb.append(" public "); if (!keyTypeArguments.isEmpty() || !typeArguments.isEmpty()) { sb.append("<"); for (int i = 0; i < keyTypeArguments.size(); i++) { printTypeVariable(sb, entity, keyTypeArguments.get(i)); sb.append(", "); } for (int i = 0; i < typeArguments.size(); i++) { printTypeVariable(sb, entity, typeArguments.get(i)); sb.append(", "); } sb.setCharAt(sb.length() - 2, '>'); } sb.append(entity.builderImportType(keyMemberBuilderFqn)).append(".Nested<"); for (int i = 0; i < keyTypeArguments.size(); i++) { sb.append(keyTypeArguments.get(i)); sb.append(", "); } sb.append("? extends ").append(entity.builderImportType(memberBuilderFqn)).append(".Nested<"); for (int i = 0; i < typeArguments.size(); i++) { sb.append(typeArguments.get(i)); sb.append(", "); } sb.append("? extends ").append(builderType).append(">> with"); if (kind == ElementKind.PARAMETER) { sb.append(PARAMETER_PREFIX); } sb.append(Character.toUpperCase(metaMember.getPropertyName().charAt(0))); sb.append(metaMember.getPropertyName(), 1, metaMember.getPropertyName().length()); sb.append("Builder() { ").append(NEW_LINE); sb.append(" ").append(entity.builderImportType(Constants.ENTITY_VIEW_BUILDER_LISTENER)).append(" listener = new ").append(entity.builderImportType(Constants.ENTITY_VIEW_BUILDER_MAP_KEY_LISTENER)).append("(getMap(\"").append(metaMember.getPropertyName()).append("\"));").append(NEW_LINE); sb.append(" return new ").append(entity.builderImportType(keyMemberBuilderFqn)) .append(".Nested<>(optionalParameters, listener, ").append(NEW_LINE); sb.append(" new ").append(entity.builderImportType(memberBuilderFqn)) .append(".Nested<>(optionalParameters, listener, (").append(builderType).append(") this)").append(NEW_LINE); sb.append(" );").append(NEW_LINE); sb.append(" }"); sb.append(NEW_LINE); } } else { String listener; if (metaMember instanceof AnnotationMetaCollection) { if (((AnnotationMetaCollection) metaMember).isIndexedList()) { listener = "new " + entity.builderImportType(Constants.ENTITY_VIEW_BUILDER_LIST_LISTENER) + "(getCollection(\"" + metaMember.getPropertyName() + "\"), index)"; sb.append(NEW_LINE); sb.append(" public "); if (!typeArguments.isEmpty()) { sb.append("<"); for (int i = 0; i < typeArguments.size(); i++) { sb.append("Sub"); printTypeVariable(sb, entity, typeArguments.get(i)); sb.append(", "); } sb.setCharAt(sb.length() - 2, '>'); } sb.append(entity.builderImportType(memberBuilderFqn)).append(".Nested<"); for (int i = 0; i < typeArguments.size(); i++) { sb.append("Sub"); sb.append(typeArguments.get(i)); sb.append(", "); } sb.append("? extends ").append(builderType).append("> with"); if (kind == ElementKind.PARAMETER) { sb.append(PARAMETER_PREFIX); } sb.append(Character.toUpperCase(metaMember.getPropertyName().charAt(0))); sb.append(metaMember.getPropertyName(), 1, metaMember.getPropertyName().length()); sb.append("Builder(int index) {") .append(NEW_LINE) .append(" return new ").append(entity.builderImportType(memberBuilderFqn)) .append(".Nested<>(optionalParameters, ").append(listener).append(", (").append(builderType).append(") this);") .append(NEW_LINE) .append(" }"); sb.append(NEW_LINE); } listener = "new " + entity.builderImportType(Constants.ENTITY_VIEW_BUILDER_COLLECTION_LISTENER) + "(getCollection(\"" + metaMember.getPropertyName() + "\"))"; } else { listener = "new " + entity.builderImportType(Constants.ENTITY_VIEW_BUILDER_SINGULAR_NAME_LISTENER) + "(this, \"" + metaMember.getPropertyName() + "\")"; } sb.append(NEW_LINE); sb.append(" public "); if (!typeArguments.isEmpty()) { sb.append("<"); for (int i = 0; i < typeArguments.size(); i++) { sb.append("Sub"); printTypeVariable(sb, entity, typeArguments.get(i)); sb.append(", "); } sb.setCharAt(sb.length() - 2, '>'); } sb.append(entity.builderImportType(memberBuilderFqn)).append(".Nested<"); for (int i = 0; i < typeArguments.size(); i++) { sb.append("Sub"); sb.append(typeArguments.get(i)); sb.append(", "); } sb.append("? extends ").append(builderType).append("> with"); if (kind == ElementKind.PARAMETER) { sb.append(PARAMETER_PREFIX); } sb.append(Character.toUpperCase(metaMember.getPropertyName().charAt(0))); sb.append(metaMember.getPropertyName(), 1, metaMember.getPropertyName().length()); sb.append("Builder() {") .append(NEW_LINE) .append(" return new ").append(entity.builderImportType(memberBuilderFqn)) .append(".Nested<>(optionalParameters, ").append(listener).append(", (").append(builderType).append(") this);") .append(NEW_LINE) .append(" }"); sb.append(NEW_LINE); } } sb.append(NEW_LINE); } private static void appendUtilityMethods(StringBuilder sb, MetaEntityView entity, Context context) { String collectionType = entity.getSafeTypeVariable("CollectionType"); String elementType = entity.getSafeTypeVariable("ElementType"); String keyType = entity.getSafeTypeVariable("KeyType"); sb.append(NEW_LINE); sb.append(" protected <").append(elementType).append("> ").append(elementType).append(" get(").append(entity.builderImportType(Constants.ATTRIBUTE)).append("<?, ?> attr) {").append(NEW_LINE); sb.append(" if (attr instanceof ").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") {").append(NEW_LINE); sb.append(" return get(((").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") attr).getName());").append(NEW_LINE); sb.append(" } else {").append(NEW_LINE); sb.append(" return get(((").append(entity.builderImportType(Constants.PARAMETER_ATTRIBUTE)).append(") attr).getIndex());").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(NEW_LINE); sb.append(" protected <").append(collectionType).append(" extends ").append(entity.builderImportType(Constants.COLLECTION)).append("<Object>> ").append(collectionType).append(" getCollection(").append(entity.builderImportType(Constants.ATTRIBUTE)).append("<?, ?> attr) {").append(NEW_LINE); sb.append(" if (attr instanceof ").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") {").append(NEW_LINE); sb.append(" return getCollection(((").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") attr).getName());").append(NEW_LINE); sb.append(" } else {").append(NEW_LINE); sb.append(" return getCollection(((").append(entity.builderImportType(Constants.PARAMETER_ATTRIBUTE)).append(") attr).getIndex());").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(NEW_LINE); sb.append(" protected <").append(collectionType).append(" extends ").append(entity.builderImportType(Constants.MAP)).append("<Object, Object>> ").append(collectionType).append(" getMap(").append(entity.builderImportType(Constants.ATTRIBUTE)).append("<?, ?> attr) {").append(NEW_LINE); sb.append(" if (attr instanceof ").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") {").append(NEW_LINE); sb.append(" return getMap(((").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") attr).getName());").append(NEW_LINE); sb.append(" } else {").append(NEW_LINE); sb.append(" return getMap(((").append(entity.builderImportType(Constants.PARAMETER_ATTRIBUTE)).append(") attr).getIndex());").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(NEW_LINE); sb.append(" protected <").append(collectionType).append(" extends ").append(entity.builderImportType(Constants.COLLECTION)).append("<Object>> ").append(collectionType).append(" getCollection(String attr) {").append(NEW_LINE); sb.append(" Object currentValue = get(attr);").append(NEW_LINE); sb.append(" if (currentValue == null) {").append(NEW_LINE); sb.append(" with(attr, null);").append(NEW_LINE); sb.append(" currentValue = get(attr);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(" if (currentValue instanceof ").append(entity.builderImportType(Constants.RECORDING_CONTAINER)).append("<?>) {").append(NEW_LINE); sb.append(" return (").append(collectionType).append(") ((").append(entity.builderImportType(Constants.RECORDING_CONTAINER)).append("<?>) currentValue).getDelegate();").append(NEW_LINE); sb.append(" } else {").append(NEW_LINE); sb.append(" return (").append(collectionType).append(") currentValue;").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(NEW_LINE); sb.append(" protected <").append(collectionType).append(" extends ").append(entity.builderImportType(Constants.MAP)).append("<Object, Object>> ").append(collectionType).append(" getMap(String attr) {").append(NEW_LINE); sb.append(" Object currentValue = get(attr);").append(NEW_LINE); sb.append(" if (currentValue == null) {").append(NEW_LINE); sb.append(" with(attr, null);").append(NEW_LINE); sb.append(" currentValue = get(attr);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(" if (currentValue instanceof ").append(entity.builderImportType(Constants.RECORDING_CONTAINER)).append("<?>) {").append(NEW_LINE); sb.append(" return (").append(collectionType).append(") ((").append(entity.builderImportType(Constants.RECORDING_CONTAINER)).append("<?>) currentValue).getDelegate();").append(NEW_LINE); sb.append(" } else {").append(NEW_LINE); sb.append(" return (").append(collectionType).append(") currentValue;").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(NEW_LINE); sb.append(" protected <").append(collectionType).append(" extends ").append(entity.builderImportType(Constants.COLLECTION)).append("<Object>> ").append(collectionType).append(" getCollection(int attr) {").append(NEW_LINE); sb.append(" Object currentValue = get(attr);").append(NEW_LINE); sb.append(" if (currentValue == null) {").append(NEW_LINE); sb.append(" with(attr, null);").append(NEW_LINE); sb.append(" currentValue = get(attr);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(" if (currentValue instanceof ").append(entity.builderImportType(Constants.RECORDING_CONTAINER)).append("<?>) {").append(NEW_LINE); sb.append(" return (").append(collectionType).append(") ((").append(entity.builderImportType(Constants.RECORDING_CONTAINER)).append("<?>) currentValue).getDelegate();").append(NEW_LINE); sb.append(" } else {").append(NEW_LINE); sb.append(" return (").append(collectionType).append(") currentValue;").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(NEW_LINE); sb.append(" protected <").append(collectionType).append(" extends ").append(entity.builderImportType(Constants.MAP)).append("<Object, Object>> ").append(collectionType).append(" getMap(int attr) {").append(NEW_LINE); sb.append(" Object currentValue = get(attr);").append(NEW_LINE); sb.append(" if (currentValue == null) {").append(NEW_LINE); sb.append(" with(attr, null);").append(NEW_LINE); sb.append(" currentValue = get(attr);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(" if (currentValue instanceof ").append(entity.builderImportType(Constants.RECORDING_CONTAINER)).append("<?>) {").append(NEW_LINE); sb.append(" return (").append(collectionType).append(") ((").append(entity.builderImportType(Constants.RECORDING_CONTAINER)).append("<?>) currentValue).getDelegate();").append(NEW_LINE); sb.append(" } else {").append(NEW_LINE); sb.append(" return (").append(collectionType).append(") currentValue;").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(NEW_LINE); sb.append(" protected void addListValue(").append(entity.builderImportType(Constants.LIST)).append("<Object> list, int index, Object value) {").append(NEW_LINE); sb.append(" if (index > list.size()) {").append(NEW_LINE); sb.append(" for (int i = list.size(); i < index; i++) {").append(NEW_LINE); sb.append(" list.add(null);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(" list.add(value);").append(NEW_LINE); sb.append(" } else if (index < list.size()) {").append(NEW_LINE); sb.append(" list.set(index, value);").append(NEW_LINE); sb.append(" } else {").append(NEW_LINE); sb.append(" list.add(value);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(" }").append(NEW_LINE); } private static void appendGetMethods(StringBuilder sb, MetaEntityView entity, Context context) { Collection<MetaAttribute> members = entity.getMembers(); String collectionType = entity.getSafeTypeVariable("CollectionType"); String elementType = entity.getSafeTypeVariable("ElementType"); String keyType = entity.getSafeTypeVariable("KeyType"); // <ElementType> ElementType get(String attribute) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(elementType).append(" get(String attribute) {").append(NEW_LINE); sb.append(" switch (attribute) {").append(NEW_LINE); for (MetaAttribute metaMember : members) { sb.append(" case \"").append(metaMember.getPropertyName()).append("\":").append(NEW_LINE); sb.append(" return (").append(elementType).append(") (Object) this.").append(metaMember.getPropertyName()).append(";").append(NEW_LINE); } sb.append(" }").append(NEW_LINE); sb.append(" throw new IllegalArgumentException(\"Unknown attribute: \" + attribute);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <ElementType> ElementType get(SingularAttribute<T, ElementType> attribute) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(elementType).append(" get(").append(entity.builderImportType(Constants.SINGULAR_ATTRIBUTE)).append("<").append(entity.builderImportType(entity.getQualifiedName())).append(", ").append(elementType).append("> attribute) {").append(NEW_LINE); sb.append(" return get((").append(entity.builderImportType(Constants.ATTRIBUTE)).append("<?, ?>) attribute);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <CollectionType> CollectionType get(PluralAttribute<T, CollectionType, ?> attribute) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(collectionType).append("> ").append(collectionType).append(" get(").append(entity.builderImportType(Constants.PLURAL_ATTRIBUTE)).append("<").append(entity.builderImportType(entity.getQualifiedName())).append(", ").append(collectionType).append(", ?> attribute) {").append(NEW_LINE); sb.append(" return get((").append(entity.builderImportType(Constants.ATTRIBUTE)).append("<?, ?>) attribute);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); } private static void appendWithMethods(StringBuilder sb, MetaEntityView entity, String builderType, Context context) { String builderTypeCast = "(" + builderType + ") "; Collection<MetaAttribute> members = entity.getMembers(); String collectionType = entity.getSafeTypeVariable("CollectionType"); String elementType = entity.getSafeTypeVariable("ElementType"); String keyType = entity.getSafeTypeVariable("KeyType"); // X with(String attribute, Object value) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public ").append(builderType).append(" with(String attribute, Object value) {").append(NEW_LINE); sb.append(" switch (attribute) {").append(NEW_LINE); for (MetaAttribute metaMember : members) { sb.append(" case \"").append(metaMember.getPropertyName()).append("\":").append(NEW_LINE); sb.append(" this.").append(metaMember.getPropertyName()).append(" = "); sb.append("value == null ? "); metaMember.appendDefaultValue(sb, true, true, entity.getBuilderImportContext()); sb.append(" : "); sb.append("(").append(metaMember.getBuilderImplementationTypeString()).append(") value;").append(NEW_LINE); sb.append(" break;").append(NEW_LINE); } sb.append(" default:").append(NEW_LINE); sb.append(" throw new IllegalArgumentException(\"Unknown attribute: \" + attribute);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); if (!members.isEmpty()) { sb.append(" return ").append(builderTypeCast).append("this;").append(NEW_LINE); } sb.append(" }").append(NEW_LINE); // <ElementType> X with(SingularAttribute<T, ElementType> attribute, ElementType value) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(builderType).append(" with(").append(entity.builderImportType(Constants.SINGULAR_ATTRIBUTE)).append("<").append(entity.builderImportType(entity.getQualifiedName())).append(", ").append(elementType).append("> attribute, ").append(elementType).append(" value) {").append(NEW_LINE); sb.append(" if (attribute instanceof ").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") {").append(NEW_LINE); sb.append(" return with(((").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") attribute).getName(), value);").append(NEW_LINE); sb.append(" } else {").append(NEW_LINE); sb.append(" return with(((").append(entity.builderImportType(Constants.PARAMETER_ATTRIBUTE)).append(") attribute).getIndex(), value);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <CollectionType> X with(PluralAttribute<T, CollectionType, ?> attribute, CollectionType value) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(collectionType).append("> ").append(builderType).append(" with(").append(entity.builderImportType(Constants.PLURAL_ATTRIBUTE)).append("<").append(entity.builderImportType(entity.getQualifiedName())).append(", ").append(collectionType).append(", ?> attribute, ").append(collectionType).append(" value) {").append(NEW_LINE); sb.append(" if (attribute instanceof ").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") {").append(NEW_LINE); sb.append(" return with(((").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") attribute).getName(), value);").append(NEW_LINE); sb.append(" } else {").append(NEW_LINE); sb.append(" return with(((").append(entity.builderImportType(Constants.PARAMETER_ATTRIBUTE)).append(") attribute).getIndex(), value);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // X withElement(String attribute, Object value) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public ").append(builderType).append(" withElement(String attribute, Object value) {").append(NEW_LINE); sb.append(" getCollection(attribute).add(value);").append(NEW_LINE); sb.append(" return ").append(builderTypeCast).append("this;").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // X withElement(int parameterIndex, Object value) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public ").append(builderType).append(" withElement(int parameterIndex, Object value) {").append(NEW_LINE); sb.append(" getCollection(parameterIndex).add(value);").append(NEW_LINE); sb.append(" return ").append(builderTypeCast).append("this;").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // X withListElement(String attribute, int index, Object value) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public ").append(builderType).append(" withListElement(String attribute, int index, Object value) {").append(NEW_LINE); sb.append(" List<Object> list = getCollection(attribute);").append(NEW_LINE); sb.append(" addListValue(list, index, value);").append(NEW_LINE); sb.append(" return ").append(builderTypeCast).append("this;").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // X withListElement(int parameterIndex, int index, Object value) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public ").append(builderType).append(" withListElement(int parameterIndex, int index, Object value) {").append(NEW_LINE); sb.append(" List<Object> list = getCollection(parameterIndex);").append(NEW_LINE); sb.append(" addListValue(list, index, value);").append(NEW_LINE); sb.append(" return ").append(builderTypeCast).append("this;").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // X withEntry(String attribute, Object key, Object value) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public ").append(builderType).append(" withEntry(String attribute, Object key, Object value) {").append(NEW_LINE); sb.append(" Map<Object, Object> map = getMap(attribute);").append(NEW_LINE); sb.append(" map.put(key, value);").append(NEW_LINE); sb.append(" return ").append(builderTypeCast).append("this;").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // X withEntry(int parameterIndex, Object key, Object value) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public ").append(builderType).append(" withEntry(int parameterIndex, Object key, Object value) {").append(NEW_LINE); sb.append(" Map<Object, Object> map = getMap(parameterIndex);").append(NEW_LINE); sb.append(" map.put(key, value);").append(NEW_LINE); sb.append(" return ").append(builderTypeCast).append("this;").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <ElementType> X withElement(CollectionAttribute<T, ElementType> attribute, ElementType value) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(builderType).append(" withElement(").append(entity.builderImportType(Constants.COLLECTION_ATTRIBUTE)).append("<").append(entity.builderImportType(entity.getQualifiedName())).append(", ").append(elementType).append("> attribute, ").append(elementType).append(" value) {").append(NEW_LINE); sb.append(" getCollection(attribute).add(value);").append(NEW_LINE); sb.append(" return ").append(builderTypeCast).append("this;").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <ElementType> X withElement(SetAttribute<T, ElementType> attribute, ElementType value) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(builderType).append(" withElement(").append(entity.builderImportType(Constants.SET_ATTRIBUTE)).append("<").append(entity.builderImportType(entity.getQualifiedName())).append(", ").append(elementType).append("> attribute, ").append(elementType).append(" value) {").append(NEW_LINE); sb.append(" getCollection(attribute).add(value);").append(NEW_LINE); sb.append(" return ").append(builderTypeCast).append("this;").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <ElementType> X withElement(ListAttribute<T, ElementType> attribute, ElementType value) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(builderType).append(" withElement(").append(entity.builderImportType(Constants.LIST_ATTRIBUTE)).append("<").append(entity.builderImportType(entity.getQualifiedName())).append(", ").append(elementType).append("> attribute, ").append(elementType).append(" value) {").append(NEW_LINE); sb.append(" getCollection(attribute).add(value);").append(NEW_LINE); sb.append(" return ").append(builderTypeCast).append("this;").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <ElementType> X withListElement(ListAttribute<T, ElementType> attribute, int index, ElementType value) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(builderType).append(" withListElement(").append(entity.builderImportType(Constants.LIST_ATTRIBUTE)).append("<").append(entity.builderImportType(entity.getQualifiedName())).append(", ").append(elementType).append("> attribute, int index, ").append(elementType).append(" value) {").append(NEW_LINE); sb.append(" List<Object> list = getCollection(attribute);").append(NEW_LINE); sb.append(" addListValue(list, index, value);").append(NEW_LINE); sb.append(" return ").append(builderTypeCast).append("this;").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <KeyType, ElementType> X withEntry(MapAttribute<T, KeyType, ElementType> attribute, KeyType key, ElementType value) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(keyType).append(", ").append(elementType).append("> ").append(builderType).append(" withEntry(") .append(entity.builderImportType(Constants.MAP_ATTRIBUTE)).append("<").append(entity.builderImportType(entity.getQualifiedName())).append(", ").append(keyType).append(", ").append(elementType).append("> attribute, ").append(keyType).append(" key, ").append(elementType).append(" value) {").append(NEW_LINE); sb.append(" Map<Object, Object> map = getMap(attribute);").append(NEW_LINE); sb.append(" map.put(key, value);").append(NEW_LINE); sb.append(" return ").append(builderTypeCast).append("this;").append(NEW_LINE); sb.append(" }").append(NEW_LINE); } private static void appendWithBuilderMethods(StringBuilder sb, MetaEntityView entity, String builderType, Context context) { Collection<MetaAttribute> members = entity.getMembers(); String collectionType = entity.getSafeTypeVariable("CollectionType"); String elementType = entity.getSafeTypeVariable("ElementType"); String keyType = entity.getSafeTypeVariable("KeyType"); // <ElementType> EntityViewNestedBuilder<ElementType, ? extends X, ?> withSingularBuilder(String attribute) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?> withSingularBuilder(String attribute) {").append(NEW_LINE); sb.append(" switch (attribute) {").append(NEW_LINE); for (MetaAttribute metaMember : members) { if (metaMember instanceof AnnotationMetaSingularAttribute && metaMember.isSubview()) { sb.append(" case \"").append(metaMember.getPropertyName()).append("\":").append(NEW_LINE); sb.append(" return (").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?>) (").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<?, ?, ?>) with"); sb.append(Character.toUpperCase(metaMember.getPropertyName().charAt(0))); sb.append(metaMember.getPropertyName(), 1, metaMember.getPropertyName().length()).append("Builder();").append(NEW_LINE); } } sb.append(" }").append(NEW_LINE); sb.append(" throw new IllegalArgumentException(\"Unknown attribute: \" + attribute);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <ElementType> EntityViewNestedBuilder<ElementType, ? extends X, ?> withCollectionBuilder(String attribute) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?> withCollectionBuilder(String attribute) {").append(NEW_LINE); sb.append(" switch (attribute) {").append(NEW_LINE); for (MetaAttribute metaMember : members) { if (metaMember instanceof AnnotationMetaCollection && !(metaMember instanceof AnnotationMetaMap) && metaMember.isSubview()) { sb.append(" case \"").append(metaMember.getPropertyName()).append("\":").append(NEW_LINE); sb.append(" return (").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?>) (").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<?, ?, ?>) with"); sb.append(Character.toUpperCase(metaMember.getPropertyName().charAt(0))); sb.append(metaMember.getPropertyName(), 1, metaMember.getPropertyName().length()).append("Builder();").append(NEW_LINE); } } sb.append(" }").append(NEW_LINE); sb.append(" throw new IllegalArgumentException(\"Unknown attribute: \" + attribute);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <ElementType> EntityViewNestedBuilder<ElementType, ? extends X, ?> withListBuilder(String attribute) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?> withListBuilder(String attribute) {").append(NEW_LINE); sb.append(" switch (attribute) {").append(NEW_LINE); for (MetaAttribute metaMember : members) { if (metaMember instanceof AnnotationMetaCollection && !(metaMember instanceof AnnotationMetaMap) && metaMember.isSubview()) { sb.append(" case \"").append(metaMember.getPropertyName()).append("\":").append(NEW_LINE); sb.append(" return (").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?>) (").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<?, ?, ?>) with"); sb.append(Character.toUpperCase(metaMember.getPropertyName().charAt(0))); sb.append(metaMember.getPropertyName(), 1, metaMember.getPropertyName().length()).append("Builder();").append(NEW_LINE); } } sb.append(" }").append(NEW_LINE); sb.append(" throw new IllegalArgumentException(\"Unknown attribute: \" + attribute);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <ElementType> EntityViewNestedBuilder<ElementType, ? extends X, ?> withListBuilder(String attribute, int index) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?> withListBuilder(String attribute, int index) {").append(NEW_LINE); sb.append(" switch (attribute) {").append(NEW_LINE); for (MetaAttribute metaMember : members) { if (metaMember instanceof AnnotationMetaCollection && ((AnnotationMetaCollection) metaMember).isIndexedList() && metaMember.isSubview()) { sb.append(" case \"").append(metaMember.getPropertyName()).append("\":").append(NEW_LINE); sb.append(" return (").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?>) (").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<?, ?, ?>) with"); sb.append(Character.toUpperCase(metaMember.getPropertyName().charAt(0))); sb.append(metaMember.getPropertyName(), 1, metaMember.getPropertyName().length()).append("Builder(index);").append(NEW_LINE); } } sb.append(" }").append(NEW_LINE); sb.append(" throw new IllegalArgumentException(\"Unknown attribute: \" + attribute);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <ElementType> EntityViewNestedBuilder<ElementType, ? extends X, ?> withSetBuilder(String attribute) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?> withSetBuilder(String attribute) {").append(NEW_LINE); sb.append(" switch (attribute) {").append(NEW_LINE); for (MetaAttribute metaMember : members) { if (metaMember instanceof AnnotationMetaCollection && !(metaMember instanceof AnnotationMetaMap) && metaMember.isSubview()) { sb.append(" case \"").append(metaMember.getPropertyName()).append("\":").append(NEW_LINE); sb.append(" return (").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?>) (").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<?, ?, ?>) with"); sb.append(Character.toUpperCase(metaMember.getPropertyName().charAt(0))); sb.append(metaMember.getPropertyName(), 1, metaMember.getPropertyName().length()).append("Builder();").append(NEW_LINE); } } sb.append(" }").append(NEW_LINE); sb.append(" throw new IllegalArgumentException(\"Unknown attribute: \" + attribute);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <ElementType> EntityViewNestedBuilder<ElementType, ? extends X, ?> withMapBuilder(String attribute, Object key) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?> withMapBuilder(String attribute, Object key) {").append(NEW_LINE); sb.append(" switch (attribute) {").append(NEW_LINE); for (MetaAttribute metaMember : members) { if (metaMember instanceof AnnotationMetaMap && metaMember.isSubview()) { sb.append(" case \"").append(metaMember.getPropertyName()).append("\":").append(NEW_LINE); sb.append(" return (").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?>) (").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<?, ?, ?>) with"); sb.append(Character.toUpperCase(metaMember.getPropertyName().charAt(0))); sb.append(metaMember.getPropertyName(), 1, metaMember.getPropertyName().length()).append("Builder(key);").append(NEW_LINE); } } sb.append(" }").append(NEW_LINE); sb.append(" throw new IllegalArgumentException(\"Unknown attribute: \" + attribute);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <KeyType, ElementType> EntityViewNestedBuilder<KeyType, ? extends EntityViewNestedBuilder<ElementType, ? extends X, ?>, ?> withMapBuilder(String attribute) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(keyType).append(", ").append(elementType).append("> ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)) .append("<").append(keyType).append(", ? extends ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?>, ?> withMapBuilder(String attribute) {").append(NEW_LINE); sb.append(" switch (attribute) {").append(NEW_LINE); for (MetaAttribute metaMember : members) { if (metaMember instanceof AnnotationMetaMap && ((AnnotationMetaMap) metaMember).isKeySubview() && metaMember.isSubview()) { sb.append(" case \"").append(metaMember.getPropertyName()).append("\":").append(NEW_LINE); sb.append(" return (").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(keyType).append(", ? extends ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)) .append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?>, ?>) (").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<?, ?, ?>) with"); sb.append(Character.toUpperCase(metaMember.getPropertyName().charAt(0))); sb.append(metaMember.getPropertyName(), 1, metaMember.getPropertyName().length()).append("Builder();").append(NEW_LINE); } } sb.append(" }").append(NEW_LINE); sb.append(" throw new IllegalArgumentException(\"Unknown attribute: \" + attribute);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <ElementType> EntityViewNestedBuilder<ElementType, ? extends X, ?> withBuilder(SingularAttribute<T, ElementType> attribute) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?> withBuilder(").append(entity.builderImportType(Constants.SINGULAR_ATTRIBUTE)); sb.append("<").append(entity.builderImportType(entity.getQualifiedName())).append(", ").append(elementType).append("> attr) {").append(NEW_LINE); sb.append(" if (attr instanceof ").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") {").append(NEW_LINE); sb.append(" return withSingularBuilder(((").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") attr).getName());").append(NEW_LINE); sb.append(" } else {").append(NEW_LINE); sb.append(" return withSingularBuilder(((").append(entity.builderImportType(Constants.PARAMETER_ATTRIBUTE)).append(") attr).getIndex());").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <ElementType> EntityViewNestedBuilder<ElementType, ? extends X, ?> withBuilder(CollectionAttribute<T, ElementType> attribute) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?> withBuilder(").append(entity.builderImportType(Constants.COLLECTION_ATTRIBUTE)); sb.append("<").append(entity.builderImportType(entity.getQualifiedName())).append(", ").append(elementType).append("> attr) {").append(NEW_LINE); sb.append(" if (attr instanceof ").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") {").append(NEW_LINE); sb.append(" return withCollectionBuilder(((").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") attr).getName());").append(NEW_LINE); sb.append(" } else {").append(NEW_LINE); sb.append(" return withCollectionBuilder(((").append(entity.builderImportType(Constants.PARAMETER_ATTRIBUTE)).append(") attr).getIndex());").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <ElementType> EntityViewNestedBuilder<ElementType, ? extends X, ?> withBuilder(ListAttribute<T, ElementType> attribute) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?> withBuilder(").append(entity.builderImportType(Constants.LIST_ATTRIBUTE)); sb.append("<").append(entity.builderImportType(entity.getQualifiedName())).append(", ").append(elementType).append("> attr) {").append(NEW_LINE); sb.append(" if (attr instanceof ").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") {").append(NEW_LINE); sb.append(" return withListBuilder(((").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") attr).getName());").append(NEW_LINE); sb.append(" } else {").append(NEW_LINE); sb.append(" return withListBuilder(((").append(entity.builderImportType(Constants.PARAMETER_ATTRIBUTE)).append(") attr).getIndex());").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <ElementType> EntityViewNestedBuilder<ElementType, ? extends X, ?> withBuilder(ListAttribute<T, ElementType> attribute, int index) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?> withBuilder(").append(entity.builderImportType(Constants.LIST_ATTRIBUTE)); sb.append("<").append(entity.builderImportType(entity.getQualifiedName())).append(", ").append(elementType).append("> attr, int index) {").append(NEW_LINE); sb.append(" if (attr instanceof ").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") {").append(NEW_LINE); sb.append(" return withListBuilder(((").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") attr).getName(), index);").append(NEW_LINE); sb.append(" } else {").append(NEW_LINE); sb.append(" return withListBuilder(((").append(entity.builderImportType(Constants.PARAMETER_ATTRIBUTE)).append(") attr).getIndex(), index);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <ElementType> EntityViewNestedBuilder<ElementType, ? extends X, ?> withBuilder(SetAttribute<T, ElementType> attribute) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?> withBuilder(").append(entity.builderImportType(Constants.SET_ATTRIBUTE)); sb.append("<").append(entity.builderImportType(entity.getQualifiedName())).append(", ").append(elementType).append("> attr) {").append(NEW_LINE); sb.append(" if (attr instanceof ").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") {").append(NEW_LINE); sb.append(" return withSetBuilder(((").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") attr).getName());").append(NEW_LINE); sb.append(" } else {").append(NEW_LINE); sb.append(" return withSetBuilder(((").append(entity.builderImportType(Constants.PARAMETER_ATTRIBUTE)).append(") attr).getIndex());").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <KeyType, ElementType> EntityViewNestedBuilder<ElementType, ? extends X, ?> withBuilder(MapAttribute<T, KeyType, ElementType> attribute, KeyType key) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(keyType).append(", ").append(elementType).append("> ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?> withBuilder(").append(entity.builderImportType(Constants.MAP_ATTRIBUTE)); sb.append("<").append(entity.builderImportType(entity.getQualifiedName())).append(", ").append(keyType).append(", ").append(elementType).append("> attr, ").append(keyType).append(" key) {").append(NEW_LINE); sb.append(" if (attr instanceof ").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") {").append(NEW_LINE); sb.append(" return withMapBuilder(((").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") attr).getName(), key);").append(NEW_LINE); sb.append(" } else {").append(NEW_LINE); sb.append(" return withMapBuilder(((").append(entity.builderImportType(Constants.PARAMETER_ATTRIBUTE)).append(") attr).getIndex(), key);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <KeyType, ElementType> EntityViewNestedBuilder<KeyType, ? extends EntityViewNestedBuilder<ElementType, ? extends X, ?>, ?> withBuilder(MapAttribute<T, KeyType, ElementType> attribute) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(keyType).append(", ").append(elementType).append("> ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(keyType).append(", ? extends ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?>, ?> withBuilder("); sb.append(entity.builderImportType(Constants.MAP_ATTRIBUTE)).append("<").append(entity.builderImportType(entity.getQualifiedName())).append(", ").append(keyType).append(", ").append(elementType).append("> attr) {").append(NEW_LINE); sb.append(" if (attr instanceof ").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") {").append(NEW_LINE); sb.append(" return withMapBuilder(((").append(entity.builderImportType(Constants.METHOD_ATTRIBUTE)).append(") attr).getName());").append(NEW_LINE); sb.append(" } else {").append(NEW_LINE); sb.append(" return withMapBuilder(((").append(entity.builderImportType(Constants.PARAMETER_ATTRIBUTE)).append(") attr).getIndex());").append(NEW_LINE); sb.append(" }").append(NEW_LINE); sb.append(" }").append(NEW_LINE); } private static void appendWithBuilderMethods(StringBuilder sb, MetaConstructor constructor, Context context, String builderType) { String collectionType = constructor.getHostingEntity().getSafeTypeVariable("CollectionType"); String elementType = constructor.getHostingEntity().getSafeTypeVariable("ElementType"); String keyType = constructor.getHostingEntity().getSafeTypeVariable("KeyType"); MetaEntityView entity = constructor.getHostingEntity(); List<MetaAttribute> members = constructor.getParameters(); // <ElementType> EntityViewNestedBuilder<ElementType, ? extends X, ?> withSingularBuilder(int parameterIndex) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?> withSingularBuilder(int parameterIndex) {").append(NEW_LINE); sb.append(" switch (parameterIndex) {").append(NEW_LINE); for (int i = 0; i < members.size(); i++) { MetaAttribute metaMember = members.get(i); if (metaMember instanceof AnnotationMetaSingularAttribute && metaMember.isSubview()) { sb.append(" case ").append(i).append(":").append(NEW_LINE); sb.append(" return (").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?>) with").append(PARAMETER_PREFIX); sb.append(Character.toUpperCase(metaMember.getPropertyName().charAt(0))); sb.append(metaMember.getPropertyName(), 1, metaMember.getPropertyName().length()).append("Builder();").append(NEW_LINE); } } sb.append(" }").append(NEW_LINE); sb.append(" throw new IllegalArgumentException(\"Unknown parameter index: \" + parameterIndex);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <ElementType> EntityViewNestedBuilder<ElementType, ? extends X, ?> withCollectionBuilder(int parameterIndex) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?> withCollectionBuilder(int parameterIndex) {").append(NEW_LINE); sb.append(" switch (parameterIndex) {").append(NEW_LINE); for (int i = 0; i < members.size(); i++) { MetaAttribute metaMember = members.get(i); if (metaMember instanceof AnnotationMetaCollection && !(metaMember instanceof AnnotationMetaMap) && metaMember.isSubview()) { sb.append(" case ").append(i).append(":").append(NEW_LINE); sb.append(" return (").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?>) with").append(PARAMETER_PREFIX); sb.append(Character.toUpperCase(metaMember.getPropertyName().charAt(0))); sb.append(metaMember.getPropertyName(), 1, metaMember.getPropertyName().length()).append("Builder();").append(NEW_LINE); } } sb.append(" }").append(NEW_LINE); sb.append(" throw new IllegalArgumentException(\"Unknown parameter index: \" + parameterIndex);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <ElementType> EntityViewNestedBuilder<ElementType, ? extends X, ?> withListBuilder(int parameterIndex) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?> withListBuilder(int parameterIndex) {").append(NEW_LINE); sb.append(" switch (parameterIndex) {").append(NEW_LINE); for (int i = 0; i < members.size(); i++) { MetaAttribute metaMember = members.get(i); if (metaMember instanceof AnnotationMetaCollection && !(metaMember instanceof AnnotationMetaMap) && metaMember.isSubview()) { sb.append(" case ").append(i).append(":").append(NEW_LINE); sb.append(" return (").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?>) with").append(PARAMETER_PREFIX); sb.append(Character.toUpperCase(metaMember.getPropertyName().charAt(0))); sb.append(metaMember.getPropertyName(), 1, metaMember.getPropertyName().length()).append("Builder();").append(NEW_LINE); } } sb.append(" }").append(NEW_LINE); sb.append(" throw new IllegalArgumentException(\"Unknown parameter index: \" + parameterIndex);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <ElementType> EntityViewNestedBuilder<ElementType, ? extends X, ?> withListBuilder(int parameterIndex, int index) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?> withListBuilder(int parameterIndex, int index) {").append(NEW_LINE); sb.append(" switch (parameterIndex) {").append(NEW_LINE); for (int i = 0; i < members.size(); i++) { MetaAttribute metaMember = members.get(i); if (metaMember instanceof AnnotationMetaCollection && ((AnnotationMetaCollection) metaMember).isIndexedList() && metaMember.isSubview()) { sb.append(" case ").append(i).append(":").append(NEW_LINE); sb.append(" return (").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?>) with").append(PARAMETER_PREFIX); sb.append(Character.toUpperCase(metaMember.getPropertyName().charAt(0))); sb.append(metaMember.getPropertyName(), 1, metaMember.getPropertyName().length()).append("Builder(index);").append(NEW_LINE); } } sb.append(" }").append(NEW_LINE); sb.append(" throw new IllegalArgumentException(\"Unknown parameter index: \" + parameterIndex);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <ElementType> EntityViewNestedBuilder<ElementType, ? extends X, ?> withSetBuilder(int parameterIndex) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?> withSetBuilder(int parameterIndex) {").append(NEW_LINE); sb.append(" switch (parameterIndex) {").append(NEW_LINE); for (int i = 0; i < members.size(); i++) { MetaAttribute metaMember = members.get(i); if (metaMember instanceof AnnotationMetaCollection && !(metaMember instanceof AnnotationMetaMap) && metaMember.isSubview()) { sb.append(" case ").append(i).append(":").append(NEW_LINE); sb.append(" return (").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?>) with").append(PARAMETER_PREFIX); sb.append(Character.toUpperCase(metaMember.getPropertyName().charAt(0))); sb.append(metaMember.getPropertyName(), 1, metaMember.getPropertyName().length()).append("Builder();").append(NEW_LINE); } } sb.append(" }").append(NEW_LINE); sb.append(" throw new IllegalArgumentException(\"Unknown parameter index: \" + parameterIndex);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <ElementType> EntityViewNestedBuilder<ElementType, ? extends X, ?> withMapBuilder(int parameterIndex, Object key) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(elementType).append("> ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?> withMapBuilder(int parameterIndex, Object key) {").append(NEW_LINE); sb.append(" switch (parameterIndex) {").append(NEW_LINE); for (int i = 0; i < members.size(); i++) { MetaAttribute metaMember = members.get(i); if (metaMember instanceof AnnotationMetaMap && metaMember.isSubview()) { sb.append(" case ").append(i).append(":").append(NEW_LINE); sb.append(" return (").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?>) with").append(PARAMETER_PREFIX); sb.append(Character.toUpperCase(metaMember.getPropertyName().charAt(0))); sb.append(metaMember.getPropertyName(), 1, metaMember.getPropertyName().length()).append("Builder(key);").append(NEW_LINE); } } sb.append(" }").append(NEW_LINE); sb.append(" throw new IllegalArgumentException(\"Unknown parameter index: \" + parameterIndex);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); // <KeyType, ElementType> EntityViewNestedBuilder<KeyType, ? extends EntityViewNestedBuilder<ElementType, ? extends X, ?>, ?> withMapBuilder(int parameterIndex) sb.append(NEW_LINE); sb.append(" @Override").append(NEW_LINE); sb.append(" public <").append(keyType).append(", ").append(elementType).append("> ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(keyType).append(", ? extends ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)) .append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?>, ?> withMapBuilder(int parameterIndex) {").append(NEW_LINE); sb.append(" switch (parameterIndex) {").append(NEW_LINE); for (int i = 0; i < members.size(); i++) { MetaAttribute metaMember = members.get(i); if (metaMember instanceof AnnotationMetaMap && ((AnnotationMetaMap) metaMember).isKeySubview() && metaMember.isSubview()) { sb.append(" case ").append(i).append(":").append(NEW_LINE); sb.append(" return (").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(keyType).append(", ? extends ").append(entity.builderImportType(Constants.ENTITY_VIEW_NESTED_BUILDER)).append("<").append(elementType).append(", ? extends ").append(builderType).append(", ?>, ?>) with"); sb.append(Character.toUpperCase(metaMember.getPropertyName().charAt(0))); sb.append(metaMember.getPropertyName(), 1, metaMember.getPropertyName().length()).append("Builder();").append(NEW_LINE); } } sb.append(" }").append(NEW_LINE); sb.append(" throw new IllegalArgumentException(\"Unknown parameter index: \" + parameterIndex);").append(NEW_LINE); sb.append(" }").append(NEW_LINE); } private static void printClassDeclaration(StringBuilder sb, MetaEntityView entity, Context context) { sb.append("public abstract class ").append(entity.getSimpleName()).append(BUILDER_CLASS_NAME_SUFFIX); String builderType = entity.getSafeTypeVariable("BuilderType"); List<TypeVariable> typeArguments = (List<TypeVariable>) ((DeclaredType) entity.getTypeElement().asType()).getTypeArguments(); sb.append("<"); if (!typeArguments.isEmpty()) { printTypeVariable(sb, entity, typeArguments.get(0)); for (int i = 1; i < typeArguments.size(); i++) { sb.append(", "); printTypeVariable(sb, entity, typeArguments.get(i)); } sb.append(", "); } sb.append(builderType).append(" extends EntityViewBuilderBase<"); sb.append(entity.builderImportType(entity.getQualifiedName())); sb.append(", ").append(builderType).append(">> implements "); sb.append(entity.builderImportType(Constants.ENTITY_VIEW_BUILDER_BASE)); sb.append("<"); sb.append(entity.builderImportType(entity.getQualifiedName())); sb.append(", ").append(builderType).append(">"); sb.append(" {"); sb.append(NEW_LINE); } private static void printTypeVariable(StringBuilder sb, MetaEntityView entity, TypeVariable t) { sb.append(t); if (t.getLowerBound().getKind() == TypeKind.NULL) { sb.append(" extends ").append(entity.builderImportType(t.getUpperBound().toString())); } else { sb.append(" super ").append(entity.builderImportType(t.getLowerBound().toString())); } } private static void printConstructors(StringBuilder sb, MetaEntityView entity, Context context) { sb.append(" public ").append(entity.getSimpleName()).append(BUILDER_CLASS_NAME_SUFFIX).append("(").append(entity.builderImportType(Constants.MAP)).append("<String, Object> optionalParameters) {").append(NEW_LINE); for (MetaAttribute member : entity.getMembers()) { sb.append(" this.").append(member.getPropertyName()).append(" = "); if (member.getKind() == MappingKind.PARAMETER) { if (member.isPrimitive()) { sb.append("!optionalParameters.containsKey(\"").append(member.getMapping()).append("\") ? "); member.appendDefaultValue(sb, false, true, entity.getBuilderImportContext()); sb.append(" : "); } sb.append("(").append(entity.builderImportType(member.getImplementationTypeString())).append(") optionalParameters.get(\"").append(member.getMapping()).append("\")").append(NEW_LINE); } else { member.appendDefaultValue(sb, true, true, entity.getBuilderImportContext()); } sb.append(";"); sb.append(NEW_LINE); } sb.append(" this.optionalParameters = optionalParameters;").append(NEW_LINE); sb.append(" }"); sb.append(NEW_LINE); } }
[ "christian.beikov@gmail.com" ]
christian.beikov@gmail.com
a4217545ec24a489250582f28b4e722f385dc640
1a4ddcc07587180ed226ab3622b426d573ff53f0
/src/main/java/com/academy/lesson06/polimorph/component/Component.java
77ac838b0f6baec95cf54a50b2bdd68c6f4dd5db
[]
no_license
Konstantin012/TelesensAcademy
1c0a20e9618ab30fac1b8e0d69141a11f2e982d8
557ee34b77a2f5347fb6f990553eb9658a300b51
refs/heads/master
2022-06-29T12:05:38.800731
2019-11-07T16:44:54
2019-11-07T16:44:54
200,520,795
0
0
null
2022-06-21T01:44:24
2019-08-04T17:14:34
Java
UTF-8
Java
false
false
2,424
java
package com.academy.lesson06.polimorph.component; import java.util.Objects; public abstract class Component { private Integer xPosition; private Integer yPosition; private Integer width; private Integer height; private String text; // надпись кнопки public Component() { this.xPosition = 0; this.yPosition = 0; this.width = 10; this.height = 12; this.text = "textnew"; } public Component(Integer xPosition, Integer yPosition, Integer width, Integer height, String text) { this.xPosition = xPosition; this.yPosition = yPosition; this.width = width; this.height = height; this.text = text; } public abstract void draw(); public Integer getxPosition() { return xPosition; } public void setxPosition(Integer xPosition) { this.xPosition = xPosition; } public Integer getyPosition() { return yPosition; } public void setyPosition(Integer yPosition) { this.yPosition = yPosition; } public Integer getWidth() { return width; } public void setWidth(Integer width) { this.width = width; } public Integer getHeight() { return height; } public void setHeight(Integer height) { this.height = height; } public String getText() { return text; } public void setText(String text) { this.text = text; } @Override public String toString() { return "Component{" + "xPosition=" + xPosition + ", yPosition=" + yPosition + ", width=" + width + ", height=" + height + ", text='" + text + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Component component = (Component) o; return Objects.equals(xPosition, component.xPosition) && Objects.equals(yPosition, component.yPosition) && Objects.equals(width, component.width) && Objects.equals(height, component.height) && Objects.equals(text, component.text); } @Override public int hashCode() { return Objects.hash(xPosition, yPosition, width, height, text); } }
[ "kkon870@gmail.com" ]
kkon870@gmail.com
3f87db48a4bf1fc695943eb95dcbdf8908587162
f2aac5813b3f527c2efbd69cdc27474366866ea0
/src/Equipe.java
f7241f49115c8f8e7844cbb2ee498a214802f654
[]
no_license
beb97/ocr-java-cours-jeu-carte
47d95fceaac4e55d799aba0ccb3b480a53e33f8f
7f5d3a8e5611804efb3bd01c7564ea5e35fade33
refs/heads/main
2023-04-12T12:48:16.851419
2021-04-21T19:55:21
2021-04-21T19:55:21
360,289,028
0
0
null
null
null
null
UTF-8
Java
false
false
733
java
import java.util.ArrayList; import java.util.List; public class Equipe { ArrayList<Joueur> joueurs; public ArrayList<Joueur> getJoueurs() { return joueurs; } public void setJoueurs(ArrayList<Joueur> joueurs) { this.joueurs = joueurs; } public Equipe(Integer nombreDeJoueurs) { ArrayList<Joueur> nJoueurs = new ArrayList<Joueur>(); for(int i = 0; i<nombreDeJoueurs; i++) { nJoueurs.add(new Joueur("Joueur"+i)); } setJoueurs(nJoueurs); } public Equipe(List<String> noms) { ArrayList<Joueur> nJoueurs = new ArrayList<Joueur>(); noms.forEach((nom) -> nJoueurs.add(new Joueur(nom))); setJoueurs(nJoueurs); } }
[ "beb97@hotmail.com" ]
beb97@hotmail.com
de4c337db63ef22416d8378ffcc8ed32c761d634
018db2e683e606de923e74ba2c3a79997622076b
/src/main/java/com/noetic/codetest/service/impl/EmployeeServiceImpl.java
6082c83de234e5ab6a7698c1b5b8692e22b056e1
[]
no_license
kthilina/codetest-service
cd2cdaee10f347c9477e9b0d1c41c654ed5850a8
466afa5711a4191d75d3359fdc624ec705a269d5
refs/heads/master
2020-12-01T14:54:20.219275
2019-12-28T21:40:36
2019-12-28T21:40:36
230,670,020
0
0
null
null
null
null
UTF-8
Java
false
false
5,018
java
package com.noetic.codetest.service.impl; import com.noetic.codetest.domain.dto.EmployeeDto; import com.noetic.codetest.domain.model.Department; import com.noetic.codetest.domain.model.Employee; import com.noetic.codetest.repository.DepartmentRepository; import com.noetic.codetest.repository.EmployeeRepository; import com.noetic.codetest.service.EmployeeService; import com.noetic.codetest.util.CodetestMapper; import com.noetic.codetest.util.CodetestResponse; import com.noetic.codetest.util.CodetestResponseMapper; import com.noetic.codetest.util.exception.RecordAlreadyExistsException; import com.noetic.codetest.util.exception.RecordNotFoundException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; /** * @author : Kasun Thilina * Date : 12/28/2019 * Project : codetest **/ @Slf4j @Service public class EmployeeServiceImpl implements EmployeeService { @Autowired private EmployeeRepository employeeRepository; @Autowired private DepartmentRepository departmentRepository; @Override @Transactional public CodetestResponse<EmployeeDto, String> create(EmployeeDto employeeDto) throws RecordNotFoundException, RecordAlreadyExistsException { CodetestResponse<EmployeeDto, String> response = new CodetestResponse<>(); Department department = departmentRepository.findById(employeeDto.getDepartmentId()).orElseThrow(() -> new RecordNotFoundException("Department not found for this id :: " + employeeDto.getDepartmentId()) ); employeeRepository.findEmployeeByEmployeeId(employeeDto.getEmployeeId()).ifPresent(val -> { throw new RecordAlreadyExistsException("Employee already exist for this id :: " + employeeDto.getEmployeeId()); }); Employee employee = new Employee(); CodetestMapper.employeeMapper(employeeDto, employee); employee.setDepartmentId(department); CodetestMapper.employeeMapper(employeeRepository.save(employee), employeeDto); CodetestResponseMapper.build(response, 201, employeeDto, "Employee " + employeeDto.getId() + " created successfully"); log.info(response.getMessage()); return response; } @Override public CodetestResponse<EmployeeDto, String> findById(Long id) throws RecordNotFoundException { CodetestResponse<EmployeeDto, String> response = new CodetestResponse<>(); EmployeeDto employeeDto = new EmployeeDto(); Employee employee = employeeRepository.findById(id).orElseThrow(() -> new RecordNotFoundException("Employee not found for this id :: " + id) ); CodetestMapper.employeeMapper(employee, employeeDto); CodetestResponseMapper.build(response, 200, employeeDto, "Operation success."); log.info(response.getMessage()); return response; } @Override public CodetestResponse<List<EmployeeDto>, String> findAll() { CodetestResponse<List<EmployeeDto>, String> response = new CodetestResponse<>(); List<EmployeeDto> employeeDtos = new ArrayList<>(); employeeRepository.findAll().stream().forEach(employee -> { EmployeeDto employeeDto = new EmployeeDto(); CodetestMapper.employeeMapper(employee, employeeDto); employeeDtos.add(employeeDto); }); CodetestResponseMapper.build(response, 200, employeeDtos, "Operation success."); log.info(response.getMessage()); return response; } @Override @Transactional public CodetestResponse<EmployeeDto, String> update(Long id, EmployeeDto employeeDto) throws RecordNotFoundException { CodetestResponse<EmployeeDto, String> response = new CodetestResponse<>(); Employee employee = employeeRepository.findById(id).orElseThrow(() -> new RecordNotFoundException("Employee not found for this id :: " + id) ); CodetestMapper.employeeMapper(employeeDto, employee); CodetestMapper.employeeMapper(employeeRepository.save(employee), employeeDto); CodetestResponseMapper.build(response, 200, employeeDto, "Employee " + employeeDto.getId() + " update successfully"); log.info(response.getMessage()); return response; } @Override @Transactional public CodetestResponse<Object, String> delete(Long id) { CodetestResponse<Object, String> response = new CodetestResponse<>(); Employee employee = employeeRepository.findById(id).orElseThrow(() -> new RecordNotFoundException("Employee not found for this id :: " + id) ); employeeRepository.delete(employee); CodetestResponseMapper.build(response, 200, null, "Employee " + id + " deleted successfully"); log.info(response.getMessage()); return response; } }
[ "kgkasunthilina@gmail.com" ]
kgkasunthilina@gmail.com
cab65b25e033f4be1f37834715ea9ecfc6afe08d
94f6c3f900cc2e908dcfede72c81bef12952efce
/src/main/java/pl/sda/task/model/Task.java
31dc4e4c7b50ab69ce894fe152e4fbbb650b62fc
[]
no_license
WojtekHenszke/tasker-wh
e498985c782a04dbcc2d10919285d69500dfe3a9
404c956810e509cb99ab020647ffad60d1d29a7c
refs/heads/master
2022-07-08T22:42:47.900611
2019-10-06T11:13:57
2019-10-06T11:13:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
932
java
package pl.sda.task.model; import lombok.Data; import lombok.EqualsAndHashCode; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; import java.util.Optional; @Data @Entity @EqualsAndHashCode(of = "id") public class Task { @Id @GeneratedValue private Long id; private String title; private String description; @OneToOne private User user; public void setUser(User user) { this.user = user; } public void assignTo(User user) throws CannotAssignTaskException { if (user.isBusy()) { throw new UserBusyException(); } if (this.user != null) { throw new TaskAlreadyAssignedException(); } user.setBusy(true); this.user = user; } public Optional<User> assignedUser() { return Optional.ofNullable(user); } }
[ "partyka.arkadiusz@gmail.com" ]
partyka.arkadiusz@gmail.com
2fc24a7d04f470bda682b9d4c85b29eda09a8f0f
43a79c4d985eda1fabe8c05b0042fe14e3a9a117
/app/src/main/java/com/example/lab5/MainActivity.java
0b5f33b29b869173db4035d6c5fdb2b1069e800e
[]
no_license
BureKristina/SMA20-lab5
36349b85ea0315834ab2d756d9e36cf8280afc84
808d86f58bdcc6f8028c56d4677afab20f77f092
refs/heads/main
2023-02-17T08:09:33.029664
2021-01-21T10:55:26
2021-01-21T10:55:26
331,598,725
0
0
null
2021-01-21T10:54:29
2021-01-21T10:54:28
null
UTF-8
Java
false
false
2,565
java
package com.example.lab5; import androidx.appcompat.app.AppCompatActivity; import androidx.constraintlayout.widget.ConstraintLayout; import android.annotation.SuppressLint; import android.content.Intent; import android.content.IntentFilter; import android.os.BatteryManager; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private static boolean isCharging; private String chargingStatus; private TextView textView; private PowerConnectionReceiver powerConnectionReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); powerConnectionReceiver = new PowerConnectionReceiver(); IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = this.registerReceiver(null, ifilter); int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL; int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB; boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC; if(isCharging) { chargingStatus = "charging"; } else { chargingStatus = "not charging"; } textView = (TextView) findViewById(R.id.textView); textView.setText("Battery is " + chargingStatus); ConstraintLayout main = findViewById(R.id.main); main.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { finish(); startActivity(getIntent()); Toast.makeText(v.getContext(), "Refreshed status", Toast.LENGTH_SHORT).show(); return true; } }); } @Override protected void onStart() { registerReceiver(powerConnectionReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); super.onStart(); } @Override protected void onStop() { unregisterReceiver(powerConnectionReceiver); super.onStop(); } public static boolean getIsCharging() { return isCharging; } }
[ "tina.bure@gmail.com" ]
tina.bure@gmail.com
6009dd01cd066753e98f37c69846364158df5ecb
a8c651da9be20f645354e4d0609c5ec9ba1312c6
/app/src/main/java/comaladdinofatl/github/currencyconverter/CurrencyConverter.java
4f1b86d75947a6746af443b9ef02fb31d8a609a5
[]
no_license
AladdinofATL/CurrencyConverter
b838a3d4624d0febd9495ca383cb52101c45349d
cb3319a22b1225964bbe6e56e2d7dde61d58e655
refs/heads/master
2016-09-01T14:59:17.365023
2016-01-15T06:57:06
2016-01-15T06:57:06
49,702,379
0
0
null
null
null
null
UTF-8
Java
false
false
909
java
package comaladdinofatl.github.currencyconverter; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class CurrencyConverter extends AppCompatActivity { public void convert(View view) { EditText dollarField = (EditText) findViewById(R.id.dollarField); Double dollarAmount = Double.parseDouble(dollarField.getText().toString()); Double poundAmount = dollarAmount * 0.69; Log.i("dollarField", poundAmount.toString()); Toast.makeText(getApplicationContext(), poundAmount.toString() + " GPB", Toast.LENGTH_LONG).show(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_currency_converter); } }
[ "adrishhus@gmail.com" ]
adrishhus@gmail.com
10da1c10083073aae354d3ea73d44b2a40c9cb33
56c22de5b2b93c6cb6ed066e11be2cbf35abd7cd
/src/miscallaneous/AddExtension.java
b35f26673f7c7260e1546ea816c6cf90407826b8
[]
no_license
theotsiga/Handling-PopUps
e3c4e79c30faf3c5b6645a9f9fc5fd99fb2d704e
dc3e2f6b1e41bacd2b8d4cf5e73daf5afa9c0360
refs/heads/master
2022-12-22T02:54:36.071791
2020-09-25T15:40:27
2020-09-25T15:40:27
298,764,295
0
0
null
null
null
null
UTF-8
Java
false
false
582
java
package miscallaneous; import java.io.File; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; public class AddExtension { public static void main(String[] args) { ChromeOptions options = new ChromeOptions(); options.addExtensions(new File("C:\\Users\\romse\\Desktop\\Homework\\extension_6_1_7_0.crx")); System.setProperty("webdriver.chrome.driver", "C:\\Users\\romse\\Desktop\\Softwares\\chromedriver.exe"); WebDriver driver = new ChromeDriver(options); } }
[ "romse@LAPTOP-KED48LAM.Home" ]
romse@LAPTOP-KED48LAM.Home
839721561aed70ace53255b0c5b7e18f18c9ea5f
f2de2ec7dba797087f340385990430bca8ecbabe
/dataMover/kafka/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
ce18a6ce7ed31420cdbec6926a9cd04fa4c806b1
[ "BSD-2-Clause", "Apache-2.0" ]
permissive
WillCh/286proj
19e9386902075d32696c45df37e68fcb42cd7e15
ba39eda48d99de554954415f4145530ce5030906
refs/heads/master
2021-01-18T18:16:20.181621
2015-05-02T03:04:57
2015-05-02T03:04:57
34,933,849
0
1
null
2016-03-10T16:31:33
2015-05-02T03:07:27
HTML
UTF-8
Java
false
false
5,776
java
/** * 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.kafka.common.protocol; import java.util.HashMap; import java.util.Map; import org.apache.kafka.common.errors.*; /** * This class contains all the client-server errors--those errors that must be sent from the server to the client. These * are thus part of the protocol. The names can be changed but the error code cannot. * * Do not add exceptions that occur only on the client or only on the server here. */ public enum Errors { UNKNOWN(-1, new UnknownServerException("The server experienced an unexpected error when processing the request")), NONE(0, null), OFFSET_OUT_OF_RANGE(1, new OffsetOutOfRangeException("The requested offset is not within the range of offsets maintained by the server.")), CORRUPT_MESSAGE(2, new CorruptRecordException("The message contents does not match the message CRC or the message is otherwise corrupt.")), UNKNOWN_TOPIC_OR_PARTITION(3, new UnknownTopicOrPartitionException("This server does not host this topic-partition.")), // TODO: errorCode 4 for InvalidFetchSize LEADER_NOT_AVAILABLE(5, new LeaderNotAvailableException("There is no leader for this topic-partition as we are in the middle of a leadership election.")), NOT_LEADER_FOR_PARTITION(6, new NotLeaderForPartitionException("This server is not the leader for that topic-partition.")), REQUEST_TIMED_OUT(7, new TimeoutException("The request timed out.")), // TODO: errorCode 8 for BrokerNotAvailable REPLICA_NOT_AVAILABLE(9, new ApiException("The replica is not available for the requested topic-partition")), MESSAGE_TOO_LARGE(10, new RecordTooLargeException("The request included a message larger than the max message size the server will accept.")), OFFSET_METADATA_TOO_LARGE(12, new OffsetMetadataTooLarge("The metadata field of the offset request was too large.")), NETWORK_EXCEPTION(13, new NetworkException("The server disconnected before a response was received.")), OFFSET_LOAD_IN_PROGRESS(14, new ApiException("The coordinator is loading offsets and can't process requests.")), CONSUMER_COORDINATOR_NOT_AVAILABLE(15, new ApiException("The coordinator is not available.")), NOT_COORDINATOR_FOR_CONSUMER(16, new ApiException("This is not the correct co-ordinator for this consumer.")), INVALID_TOPIC_EXCEPTION(17, new InvalidTopicException("The request attempted to perform an operation on an invalid topic.")), RECORD_LIST_TOO_LARGE(18, new RecordBatchTooLargeException("The request included message batch larger than the configured segment size on the server.")), NOT_ENOUGH_REPLICAS(19, new NotEnoughReplicasException("Messages are rejected since there are fewer in-sync replicas than required.")), NOT_ENOUGH_REPLICAS_AFTER_APPEND(20, new NotEnoughReplicasAfterAppendException("Messages are written to the log, but to fewer in-sync replicas than required.")), INVALID_REQUIRED_ACKS(21, new InvalidRequiredAcksException("Produce request specified an invalid value for required acks.")), ILLEGAL_GENERATION(22, new ApiException("Specified consumer generation id is not valid.")), NO_OFFSETS_FETCHABLE(23, new ApiException("No offsets have been committed so far.")); private static Map<Class<?>, Errors> classToError = new HashMap<Class<?>, Errors>(); private static Map<Short, Errors> codeToError = new HashMap<Short, Errors>(); static { for (Errors error : Errors.values()) { codeToError.put(error.code(), error); if (error.exception != null) classToError.put(error.exception.getClass(), error); } } private final short code; private final ApiException exception; private Errors(int code, ApiException exception) { this.code = (short) code; this.exception = exception; } /** * An instance of the exception */ public ApiException exception() { return this.exception; } /** * The error code for the exception */ public short code() { return this.code; } /** * Throw the exception corresponding to this error if there is one */ public void maybeThrow() { if (exception != null) { throw this.exception; } } /** * Throw the exception if there is one */ public static Errors forCode(short code) { Errors error = codeToError.get(code); return error == null ? UNKNOWN : error; } /** * Return the error instance associated with this exception (or UKNOWN if there is none) */ public static Errors forException(Throwable t) { Errors error = classToError.get(t.getClass()); return error == null ? UNKNOWN : error; } }
[ "jguone@gmail.com" ]
jguone@gmail.com
59fd9b299da669a2a7b6356d1e3463a001def53f
91e1e5476f1a7b0b0c732645c04aed929b527a3d
/app/src/main/java/com/example/gamingrewardandroid/SmartcookieRegistration/SchoolidValidation/Post.java
4eb44f68dcab99a7b4cb104d467f92f8efe882d2
[]
no_license
prtk5436/Gaming_Reward_Android
684aadf22f7dc2521831254ce00ff9e345da4787
7c71b8f74b8b83d57bfb53dca5a7ecebf475d20f
refs/heads/master
2023-05-23T08:08:12.173621
2021-01-05T11:42:50
2021-01-05T11:42:50
370,297,636
0
0
null
null
null
null
UTF-8
Java
false
false
751
java
package com.example.gamingrewardandroid.SmartcookieRegistration.SchoolidValidation; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Post { @SerializedName("school_id") @Expose private String schoolId; @SerializedName("school_name") @Expose private String schoolName; public String getSchoolId() { return schoolId; } public void setSchoolId(String schoolId) { this.schoolId = schoolId; } public String getSchoolName() { return schoolName; } public void setSchoolName(String schoolName) { this.schoolName = schoolName; } }
[ "58257068+sakshi-coder@users.noreply.github.com" ]
58257068+sakshi-coder@users.noreply.github.com
6ba2786618b07b4237dc72923c0d023095fb2ea9
566ad8b768022a6bd931d72393ca151e6b959f46
/jAgent/src/main/java/br/com/cannoni/jagent/service/impl/MemInfoServiceImpl.java
c080176bc708e7d6509fd36ea0eaeb4ca93a5899
[]
no_license
patriziocannoni/jAgent
dc846613ae28785322b6a4e5900862b395d3456a
0ceb134ceda4454ce994ebd337f58ee977cf3c6e
refs/heads/master
2021-01-23T01:13:21.915471
2017-04-20T01:21:32
2017-04-20T01:21:32
85,891,053
0
0
null
null
null
null
UTF-8
Java
false
false
1,801
java
/** * */ package br.com.cannoni.jagent.service.impl; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.springframework.stereotype.Service; import br.com.cannoni.jagent.model.MemoryInfo; import br.com.cannoni.jagent.service.MemInfoService; /** * @author patrizio * */ @Service("memInfoService") public class MemInfoServiceImpl implements MemInfoService { @Override public List<MemoryInfo> getMemoryInfo() { List<MemoryInfo> memLines = new ArrayList<>(); try { List<String> lines = Files.readAllLines(Paths.get("/proc/meminfo")); String[] arr = lines.get(0).split(": "); memLines.add(new MemoryInfo(arr[0], arr[1])); arr = lines.get(2).split(": "); memLines.add(new MemoryInfo(arr[0], arr[1])); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return memLines; } @Override public List<String> getDiskInfo() { String s = executeCommand("df -k"); return Arrays.asList(s.split("\n")); } private String executeCommand(String command) { StringBuffer output = new StringBuffer(); Process p; try { p = Runtime.getRuntime().exec(command); p.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = reader.readLine())!= null) { output.append(line + "\n"); } } catch (Exception e) { e.printStackTrace(); } return output.toString(); } }
[ "patrizio.cannoni@gmail.com" ]
patrizio.cannoni@gmail.com
544898438ed33a707c2c1bd688e3537787fc99df
d4896a7eb2ee39cca5734585a28ca79bd6cc78da
/sources/com/google/firebase/iid/InstanceIdResultImpl.java
f595ea2413f0152fde5c17dfac2abeaeab1c120e
[]
no_license
zadweb/zadedu.apk
a235ad005829e6e34ac525cbb3aeca3164cf88be
8f89db0590333929897217631b162e39cb2fe51d
refs/heads/master
2023-08-13T03:03:37.015952
2021-10-12T21:22:59
2021-10-12T21:22:59
416,498,604
0
0
null
null
null
null
UTF-8
Java
false
false
643
java
package com.google.firebase.iid; /* access modifiers changed from: package-private */ /* compiled from: com.google.firebase:firebase-iid@@20.2.3 */ public final class InstanceIdResultImpl implements InstanceIdResult { private final String id; private final String token; InstanceIdResultImpl(String str, String str2) { this.id = str; this.token = str2; } @Override // com.google.firebase.iid.InstanceIdResult public final String getId() { return this.id; } @Override // com.google.firebase.iid.InstanceIdResult public final String getToken() { return this.token; } }
[ "midoekid@gmail.com" ]
midoekid@gmail.com
62c99b11bc246b3ef752ef496f89ca970c281319
fe40bf0ea3c491b9d9c1e4137e50a8e76cdd0395
/SocialMedia/SocialMedia/app/src/main/java/com/afroz/social/ahmad/adapters/MessageTextReplyAdapter.java
4b5f45dbbb7a72997d0be42c621d0e93f31fa9da
[ "MIT" ]
permissive
vijay7503637339/SUGORENGE
1dc22a80372a18cc49786a767ed2e8bcdb455b5d
cdb9c44b6831b682268edeca0f7a504c098a19f0
refs/heads/master
2022-09-09T08:20:41.222340
2020-05-30T17:31:06
2020-05-30T17:31:06
268,128,440
0
0
null
null
null
null
UTF-8
Java
false
false
7,114
java
package com.afroz.social.ahmad.adapters; import android.content.Context; import android.content.Intent; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.afollestad.materialdialogs.MaterialDialog; import com.afroz.social.ahmad.R; import com.afroz.social.ahmad.models.MessageReply; import com.afroz.social.ahmad.ui.activities.notification.NotificationReplyActivity; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.github.marlonlom.utilities.timeago.TimeAgo; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.FirebaseFirestore; import java.util.List; import java.util.Locale; import de.hdodenhof.circleimageview.CircleImageView; import static android.content.Context.MODE_PRIVATE; /** * Created by afroz on 22/2/18. */ public class MessageTextReplyAdapter extends RecyclerView.Adapter<MessageTextReplyAdapter.ViewHolder> { private List<MessageReply> messageList; private Context context; private FirebaseFirestore mFirestore; public MessageTextReplyAdapter(List<MessageReply> messageList, Context context) { this.messageList = messageList; this.context = context; } @NonNull @Override public MessageTextReplyAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { mFirestore=FirebaseFirestore.getInstance(); View view=null; if(parent.getContext().getSharedPreferences("theme",MODE_PRIVATE).getBoolean("dark",false)) view= LayoutInflater.from(context).inflate(R.layout.message_text_item_dark,parent,false); else view= LayoutInflater.from(context).inflate(R.layout.message_text_item,parent,false); return new ViewHolder(view); } @Override public long getItemId(int position) { return position; } @Override public int getItemViewType(int position) { return position; } @Override public void onBindViewHolder(@NonNull final MessageTextReplyAdapter.ViewHolder holder, int position) { try { if (messageList.get(position).getRead()=="true") { holder.read_icon.setImageDrawable(context.getResources().getDrawable(R.drawable.read_icon)); holder.read_icon.setVisibility(View.VISIBLE); holder.read_icon.setAlpha(0.0f); holder.read_icon.animate() .alpha(1.0f) .setDuration(300) .start(); } else { holder.read_icon.setImageDrawable(context.getResources().getDrawable(R.drawable.unread_icon)); holder.read_icon.setVisibility(View.VISIBLE); holder.read_icon.setAlpha(0.0f); holder.read_icon.animate() .alpha(1.0f) .setDuration(300) .start(); } }catch (Exception e){ e.printStackTrace(); } mFirestore.collection("Users") .document(messageList.get(position).getFrom()) .get() .addOnSuccessListener(documentSnapshot -> { Glide.with(context) .setDefaultRequestOptions(new RequestOptions().placeholder(R.drawable.default_user_art_g_2)) .load(documentSnapshot.getString("image")) .into(holder.image); holder.name.setText(documentSnapshot.getString("name")); }); holder.mView.setOnClickListener(view -> { Intent intent=new Intent(context, NotificationReplyActivity.class); intent.putExtra("doc_id", messageList.get(holder.getAdapterPosition()).msgId); intent.putExtra("read", messageList.get(holder.getAdapterPosition()).getRead()); intent.putExtra("from_id", messageList.get(holder.getAdapterPosition()).getFrom()); intent.putExtra("reply_for", messageList.get(holder.getAdapterPosition()).getReply_for()); intent.putExtra("message", messageList.get(holder.getAdapterPosition()).getMessage()); context.startActivity(intent); messageList.get(holder.getAdapterPosition()).setRead("true"); holder.read_icon.setImageDrawable(context.getResources().getDrawable(R.drawable.read_icon)); holder.read_icon.setVisibility(View.VISIBLE); holder.read_icon.setAlpha(0.0f); holder.read_icon.animate() .alpha(1.0f) .setDuration(300) .start(); }); String timeAgo = TimeAgo.using(Long.parseLong(messageList.get(holder.getAdapterPosition()).getTimestamp())); holder.time.setText(timeAgo); holder.message.setText(String.format(Locale.ENGLISH,"Reply for: %s\nMessage: %s",messageList.get(holder.getAdapterPosition()).getReply_for(),messageList.get(holder.getAdapterPosition()).getMessage())); holder.mView.setOnLongClickListener(v -> { new MaterialDialog.Builder(context) .title("Delete message") .content("Are you sure do you want to delete this message?") .positiveText("Yes") .negativeText("No") .onPositive((dialog, which) -> mFirestore.collection("Users") .document(FirebaseAuth.getInstance().getCurrentUser().getUid()) .collection("Notifications_reply") .document(messageList.get(holder.getAdapterPosition()).msgId) .delete() .addOnSuccessListener(aVoid -> { messageList.remove(holder.getAdapterPosition()); notifyItemRemoved(holder.getAdapterPosition()); notifyDataSetChanged(); }) .addOnFailureListener(e -> e.printStackTrace())) .onNegative((dialog, which) -> dialog.dismiss()) .show(); return true; }); } @Override public int getItemCount() { return messageList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { private View mView; private CircleImageView image; private TextView message,name,time; private ImageView read_icon; public ViewHolder(View itemView) { super(itemView); mView=itemView; image = mView.findViewById(R.id.image); name = mView.findViewById(R.id.name); message = mView.findViewById(R.id.message); time = mView.findViewById(R.id.time); read_icon=mView.findViewById(R.id.read); } } }
[ "vijaygupta7503637339@gmail.com" ]
vijaygupta7503637339@gmail.com
907b5c76e4b10948f88dbe4b090e538be619721e
3c0bae70339f137c8955438333942591e45731e8
/src/main/java/com/limbo/proxy/ClientProxy.java
2bed732809ebabd37f9025803962ff3c2f0c84a4
[]
no_license
MiCr2/Limbo
dcc174206fa8afe16c4cafc03c8cba3560f7fbc8
0f70ab74d09c47c327dba9aaf6d86bcb8c263895
refs/heads/master
2021-01-19T10:42:29.907256
2014-07-04T09:06:14
2014-07-04T09:06:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
487
java
package com.limbo.proxy; import net.minecraft.client.model.ModelBiped; import com.limbo.entity.EntityCursed; import com.limbo.entity.RenderCursed; import cpw.mods.fml.client.registry.RenderingRegistry; public class ClientProxy extends CommonProxy { @Override public void registerRenderers() { RenderingRegistry.registerEntityRenderingHandler(EntityCursed.class, new RenderCursed(new ModelBiped(), 0.5F)); RenderingRegistry.addNewArmourRendererPrefix("whitesoulArmor"); } }
[ "micr2minecraft@gmail.com" ]
micr2minecraft@gmail.com
0814edb9d5154a4703bd7306a8c5eadbd6c00915
b79954f682b8e158833e63567e3a903364ec3a9b
/lib/src/br/com/openpdv/inutnfe/TUfEmi.java
68a06e03235f9e21d6cc84aa039351c107aa42c1
[]
no_license
danimaribeiro/OpenPDV
64e5a318939b413e5b06ca5f3173635f38ed461c
0247c55e2d78dcb584f8aec8e5a8a6a73e92fb21
refs/heads/master
2021-01-17T16:26:43.132806
2012-11-28T03:38:44
2012-11-28T03:38:44
6,895,607
6
7
null
null
null
null
UTF-8
Java
false
false
2,245
java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.07.26 at 11:01:00 PM BRT // package br.com.openpdv.inutnfe; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for TUfEmi. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="TUfEmi"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;enumeration value="AC"/> * &lt;enumeration value="AL"/> * &lt;enumeration value="AM"/> * &lt;enumeration value="AP"/> * &lt;enumeration value="BA"/> * &lt;enumeration value="CE"/> * &lt;enumeration value="DF"/> * &lt;enumeration value="ES"/> * &lt;enumeration value="GO"/> * &lt;enumeration value="MA"/> * &lt;enumeration value="MG"/> * &lt;enumeration value="MS"/> * &lt;enumeration value="MT"/> * &lt;enumeration value="PA"/> * &lt;enumeration value="PB"/> * &lt;enumeration value="PE"/> * &lt;enumeration value="PI"/> * &lt;enumeration value="PR"/> * &lt;enumeration value="RJ"/> * &lt;enumeration value="RN"/> * &lt;enumeration value="RO"/> * &lt;enumeration value="RR"/> * &lt;enumeration value="RS"/> * &lt;enumeration value="SC"/> * &lt;enumeration value="SE"/> * &lt;enumeration value="SP"/> * &lt;enumeration value="TO"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "TUfEmi", namespace = "http://www.portalfiscal.inf.br/nfe") @XmlEnum public enum TUfEmi { AC, AL, AM, AP, BA, CE, DF, ES, GO, MA, MG, MS, MT, PA, PB, PE, PI, PR, RJ, RN, RO, RR, RS, SC, SE, SP, TO; public String value() { return name(); } public static TUfEmi fromValue(String v) { return valueOf(v); } }
[ "pedroh.lira@gmail.com" ]
pedroh.lira@gmail.com
7ea07f147c18872db9d270a374498e3ce44b22cc
abfc8a83db37575d0620770cfff6f7dae459edf6
/example/src/main/java/com/laomei/sidecar/example/Application.java
71cb642cf6a35218e5804e81050ef2f7b86feaf3
[]
no_license
wucibeideshenming/laomei-sidecar
a69260c77c22f85a214ea808dc557b949d7495b4
8236a7a31aeb3a5aadd6b64fda0aa6f962f13852
refs/heads/master
2023-04-01T07:38:07.622712
2020-11-11T12:54:53
2020-11-11T12:54:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
431
java
package com.laomei.sidecar.example; import com.laomei.sidecar.EnableEnhanceSidecar; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @author luobo.hwz on 2020/11/11 20:28 */ @EnableEnhanceSidecar @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class); } }
[ "sweatott@gmail.com" ]
sweatott@gmail.com
a0e37f4c11f935c6786f0b1448b4faa18f7c958a
92d27cdaf117c39233bd4a559cfd40acaac47746
/cland/src/main/java/edu/vinaenter/cland/configs/WebMvcConfig.java
20f2346ef10e750275ca5ab82f250f5af7a08922
[]
no_license
tranxuanhaibk/website_cland
d64fde7977957216f6e9a247b40892a5de8e3662
6359c230859d6655c9a2e0b0e7877fd3ccaa96e5
refs/heads/master
2023-07-04T20:14:00.253998
2021-08-27T12:54:47
2021-08-27T12:54:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,781
java
package edu.vinaenter.cland.configs; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.multipart.MultipartResolver; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.tiles3.TilesConfigurer; import org.springframework.web.servlet.view.tiles3.TilesViewResolver; @Configuration @ComponentScan("edu.vinaenter.cland.*") @EnableWebMvc public class WebMvcConfig implements WebMvcConfigurer { @Bean public MultipartResolver multipartResolver() { CommonsMultipartResolver resolver = new CommonsMultipartResolver(); //resolver.setMaxUploadSize(1*1024*1024); return resolver; } @Override public void configureViewResolvers(ViewResolverRegistry registry) { TilesViewResolver viewResolver = new TilesViewResolver(); registry.viewResolver(viewResolver); } @Bean public TilesConfigurer tilesConfigurer() { TilesConfigurer tilesConfigurer = new TilesConfigurer(); tilesConfigurer.setDefinitions(new String[] { "/WEB-INF/springmvc/tiles-cland.xml", "/WEB-INF/springmvc/tiles-admin.xml" }); tilesConfigurer.setCheckRefresh(true); return tilesConfigurer; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("resources/**").addResourceLocations("/WEB-INF/resources/"); } }
[ "tranxuanhai.bkdn@gmail.com" ]
tranxuanhai.bkdn@gmail.com
28575f3d117e5ec9503e7f9bb91d084f9df7c63d
584b3cc614a0d09129dc3102f1dcd491a439247e
/Online_Inventory_System/src/com/dts/core/control/UIController.java
6beb0f2ea37ee1601c32fefca643ca8f20afe7ca
[]
no_license
krishna-hitech/GAURAVCODE
889ecdba37a7239074861540635a8deddcfb6d88
1c2650649f3b620b8c227cf3c04cde81d2c7eae7
refs/heads/master
2021-01-13T14:07:32.409506
2017-11-09T11:51:33
2017-11-09T11:51:33
81,214,901
0
1
null
2017-04-21T17:27:06
2017-02-07T14:08:51
Java
UTF-8
Java
false
false
539
java
package com.dts.core.control; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.dts.core.util.LoggerManager; public class UIController extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException { try { res.sendRedirect("index.jsp"); } catch (IOException ioe) { LoggerManager.writeLogInfo(ioe); } } }
[ "sanusmile829@gmail.com" ]
sanusmile829@gmail.com
3d2a589fc9088d973fc4376d05f902fc6d5b8920
571be51b01adcf808ded3da9d7a0677cfe211cf1
/sharding-jdbc-example/src/test/java/io/shardingsphere/example/repository/api/trace/ResultAssertUtils.java
7a238f8602ec7aa2e5873093cd4eb2b32a6f5e9a
[ "Apache-2.0" ]
permissive
zwjhuhu/incubator-shardingsphere
c50d6e7949f99ffe43de4845869b1d1b3702c4cd
08138825d88d2b56ae9a94db9535b6a01d27d80b
refs/heads/master
2020-04-25T15:28:24.229963
2019-03-02T04:40:58
2019-03-02T04:40:58
172,880,240
0
0
null
2019-02-27T09:00:41
2019-02-27T09:00:40
null
UTF-8
Java
false
false
5,989
java
/* * 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.shardingsphere.example.repository.api.trace; import io.shardingsphere.example.repository.api.service.CommonService; import io.shardingsphere.example.repository.api.service.CommonServiceImpl; import io.shardingsphere.example.repository.api.service.TransactionService; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class ResultAssertUtils { public static void assertShardingDatabaseResult(final CommonService commonService) { assertShardingDatabaseResult(commonService, false); } public static void assertShardingDatabaseResult(final CommonService commonService, final boolean isRangeSharding) { MemoryLogService memoryLogService = ((CommonServiceImpl) commonService).getMemoryLogService(); assertThat(memoryLogService.getOrderData(DatabaseAccess.INSERT).size(), is(10)); assertThat(memoryLogService.getOrderData(DatabaseAccess.SELECT).size(), is(10)); assertThat(memoryLogService.getOrderItemData(DatabaseAccess.INSERT).size(), is(10)); if (isRangeSharding) { assertThat(memoryLogService.getOrderItemData(DatabaseAccess.SELECT).size(), is(2)); } else { assertThat(memoryLogService.getOrderItemData(DatabaseAccess.SELECT).size(), is(10)); } } public static void assertShardingTableResult(final CommonService commonService) { assertShardingTableResult(commonService, false); } public static void assertShardingTableResult(final CommonService commonService, final boolean isRangeSharding) { MemoryLogService memoryLogService = ((CommonServiceImpl) commonService).getMemoryLogService(); assertThat(memoryLogService.getOrderData(DatabaseAccess.INSERT).size(), is(10)); if (isRangeSharding) { assertThat(memoryLogService.getOrderData(DatabaseAccess.SELECT).size(), is(5)); } else { assertThat(memoryLogService.getOrderData(DatabaseAccess.SELECT).size(), is(10)); } assertThat(memoryLogService.getOrderItemData(DatabaseAccess.INSERT).size(), is(10)); if (isRangeSharding) { assertThat(memoryLogService.getOrderItemData(DatabaseAccess.SELECT).size(), is(5)); } else { assertThat(memoryLogService.getOrderItemData(DatabaseAccess.SELECT).size(), is(10)); } } public static void assertShardingDatabaseAndTableResult(final CommonService commonService) { assertShardingDatabaseAndTableResult(commonService, false); } public static void assertShardingDatabaseAndTableResult(final CommonService commonService, final boolean isRangeSharding) { MemoryLogService memoryLogService = ((CommonServiceImpl) commonService).getMemoryLogService(); assertThat(memoryLogService.getOrderData(DatabaseAccess.INSERT).size(), is(10)); if (isRangeSharding) { assertThat(memoryLogService.getOrderData(DatabaseAccess.SELECT).size(), is(5)); } else { assertThat(memoryLogService.getOrderData(DatabaseAccess.SELECT).size(), is(10)); } assertThat(memoryLogService.getOrderItemData(DatabaseAccess.INSERT).size(), is(10)); if (isRangeSharding) { assertThat(memoryLogService.getOrderItemData(DatabaseAccess.SELECT).size(), is(2)); } else { assertThat(memoryLogService.getOrderItemData(DatabaseAccess.SELECT).size(), is(10)); } } public static void assertMasterSlaveResult(final CommonService commonService) { MemoryLogService memoryLogService = ((CommonServiceImpl) commonService).getMemoryLogService(); assertThat(memoryLogService.getOrderData(DatabaseAccess.INSERT).size(), is(10)); assertThat(memoryLogService.getOrderData(DatabaseAccess.SELECT).size(), is(0)); assertThat(memoryLogService.getOrderItemData(DatabaseAccess.INSERT).size(), is(10)); assertThat(memoryLogService.getOrderItemData(DatabaseAccess.SELECT).size(), is(0)); } public static void assertTransactionServiceResult(final TransactionService transactionService) { MemoryLogService memoryLogService = ((CommonServiceImpl) transactionService).getMemoryLogService(); assertThat(memoryLogService.getOrderData(DatabaseAccess.INSERT).size(), is(40)); assertThat(memoryLogService.getOrderData(DatabaseAccess.SELECT).size(), is(20)); assertThat(memoryLogService.getOrderItemData(DatabaseAccess.INSERT).size(), is(40)); assertThat(memoryLogService.getOrderItemData(DatabaseAccess.SELECT).size(), is(20)); } public static void assertTransactionMasterSlaveResult(final TransactionService transactionService) { MemoryLogService memoryLogService = ((CommonServiceImpl) transactionService).getMemoryLogService(); assertThat(memoryLogService.getOrderData(DatabaseAccess.INSERT).size(), is(40)); assertThat(memoryLogService.getOrderData(DatabaseAccess.SELECT).size(), is(20)); assertThat(memoryLogService.getOrderItemData(DatabaseAccess.INSERT).size(), is(40)); assertThat(memoryLogService.getOrderItemData(DatabaseAccess.SELECT).size(), is(20)); } }
[ "zwjhuhu@126.com" ]
zwjhuhu@126.com
c2cb2b2a7cdc442a1b214ccffee5469e1f7ac2d9
1678cb31e15af1ed09c2b574be14e829fb5cebec
/api/src/main/java/api/domain/Phone.java
d65e2190166243a05c0bd39d3fc975a57147551b
[ "Apache-2.0" ]
permissive
swarmcom/webDataEngine
be386b69e12888312b4c14305a6db14035a44ed2
3c7838c8f3a142a0369a7048fb0f25cdb5365ced
refs/heads/master
2020-05-22T04:27:56.291589
2019-03-06T07:58:21
2019-03-06T07:58:21
64,225,157
1
0
null
null
null
null
UTF-8
Java
false
false
2,950
java
package api.domain; import api.type.PhoneModel; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Phone extends BeanDomain<Phone> { protected String id; protected String accountId; protected String serialNumber; protected String description; protected String firmwareVersion; protected List<String> lines = null; protected Map<String, Map<String, Object>> settings = new HashMap<String, Map<String, Object>>(); protected PhoneModel model; public Phone() { } public Phone(String accountId, String serialNumber, String description, String firmwareVersion) { this.serialNumber = serialNumber; this.firmwareVersion = firmwareVersion; this.description = description; this.accountId = accountId; } public boolean isNew() { return StringUtils.isEmpty(this.id); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } public String getFirmwareVersion() { return firmwareVersion; } public void setFirmwareVersion(String firmwareVersion) { this.firmwareVersion = firmwareVersion; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getSerialNumber() { return serialNumber; } public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; } public List<String> getLines() { return lines; } public void setLines(List<String> lines) { this.lines = lines; } public Map<String, Map<String, Object>> getSettings() { return settings; } public void setSettings(Map<String, Map<String, Object>> settings) { this.settings = settings; } public PhoneModel getModel() { return model; } public void setModel(PhoneModel model) { this.model = model; } public void merge(Phone phone) { String description = phone.getDescription(); if (description != null) { setDescription(description); } String serialNumber = phone.getSerialNumber(); if (serialNumber != null) { setSerialNumber(serialNumber); } String firmwareVersion = phone.getFirmwareVersion(); if (firmwareVersion != null) { setFirmwareVersion(firmwareVersion); } List<String> lines = phone.getLines(); if (lines != null) { setLines(lines); } mergeSettings(phone.getSettings(), this.settings); } }
[ "mirceac@ezuce.com" ]
mirceac@ezuce.com
87bdbf29580eac0113960e34525533cb31817217
917602591a60b2f98ec77402fb59937bbfdadafb
/app/src/main/java/com/hongyan/xcj/base/Error.java
a6e241625d6121a98a6ed937b3063511ff900664
[]
no_license
BlueGuys/XCJ
f748a85c971ae454781a3fd3cd8fd18af9dda137
a8a4e70d1933e5485b3897e61fc3e17afdbce94d
refs/heads/master
2021-04-12T12:31:34.533150
2018-03-23T15:05:25
2018-03-23T15:05:25
126,423,688
1
0
null
null
null
null
UTF-8
Java
false
false
1,769
java
package com.hongyan.xcj.base; import org.json.JSONObject; public class Error { public static final Error NETWORK_ERROR = new Error(); public static final Error DATA_PARSED_ERROR = new Error(); static { NETWORK_ERROR.returnCode = "-100"; NETWORK_ERROR.returnMessage = "network failed."; NETWORK_ERROR.returnUserMessage = "网络连接异常"; DATA_PARSED_ERROR.returnCode = "-200;"; DATA_PARSED_ERROR.returnMessage = "data parse failed."; DATA_PARSED_ERROR.returnUserMessage = "数据解析错误,请重试。"; } private String returnCode; private String returnMessage; private String returnUserMessage; private String detailMessage; public void parseJson(JSONObject json) { if (json == null) { return; } this.returnCode = json.optString("returnCode"); this.returnMessage = json.optString("returnMessage"); this.returnUserMessage = json.optString("returnUserMessage"); } public String getReturnCode() { return returnCode; } public void setReturnCode(String returnCode) { this.returnCode = returnCode; } public String getReturnMessage() { return returnMessage; } public void setReturnMessage(String returnMessage) { this.returnMessage = returnMessage; } public String getReturnUserMessage() { return returnUserMessage; } public void setReturnUserMessage(String returnUserMessage) { this.returnUserMessage = returnUserMessage; } public void setDetailMessage(String detailMessage) { this.detailMessage = detailMessage; } public String getDetailMessage() { return detailMessage; } }
[ "wangninga@jiedaibao.com" ]
wangninga@jiedaibao.com
13c41fc22e56fcdc9df73953b0db7eeac154ffd0
dc0c18e992dbf5676eb4f0376f09191da001ef75
/data-seeding-handover/src/main/java/ca/elecsoft/pages/NewOpportunityPage.java
ee09b0bf686a216f509eb3ad70198fdd6b7aa4f7
[]
no_license
yujd13/bell_automation
32bca87f8e170c92d84d274e966b249c7de40944
fcf0ac90fa32fddcf2aca268ec433f499f4e9efd
refs/heads/main
2023-06-17T13:12:54.835141
2021-07-14T14:49:09
2021-07-14T14:49:09
385,962,402
0
0
null
null
null
null
UTF-8
Java
false
false
15,979
java
package ca.elecsoft.pages; import ca.elecsoft.model.MarketingTabValidation; import ca.elecsoft.model.OpportunityProductLineItem; import ca.elecsoft.model.OppotunityOverview; import ca.elecsoft.util.Util; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; public class NewOpportunityPage { public WebDriver driver; public WebDriverWait wait; public Util util; private static final Logger logger = LogManager.getLogger(NewOpportunityPage.class); By serviceLocationType; By detailsTab; By productLineItemTab; By customerType; By customerSubTypeResidential; //product line item tab By workOrderType; By workOrderSubType; By responseType; By bundleName; private By getWorkOrderId; //opportunity By nextStage; By opportunityRibbon; By customerAcountInformationChecked; By readyForOrderInformation; By suggestionsButton; //validation By workOrderTypeProvisioning; By qolysosPackageName; By workOrderSubTypeInstallation; By customerAccountInformationCheckedYes; By getReadyForOrderInformationYes; public NewOpportunityPage(WebDriver driver, WebDriverWait wait, String url) { this.driver = driver; this.wait = wait; this.util = Util.getInstance(); if (url.length() > 1) { driver.get(url); } serviceLocationType = By.xpath("//select[@aria-label=\"Service Location Type\"]"); workOrderType = By.xpath("//input[@aria-label=\"Work Order Type, Lookup\"]"); workOrderSubType = By.xpath("//input[@aria-label=\"Work Order Sub-Type, Lookup\"]"); detailsTab = By.xpath("//*[@aria-label=\"Details\"]"); customerType = By.xpath("//input[@aria-label=\"Customer Type\"]"); customerSubTypeResidential = By.xpath("//select[@aria-label=\"Customer Sub-Type Residential\"]"); productLineItemTab = By.xpath("//li[@aria-label=\"Product Line Item\"]"); responseType = By.xpath("//select[@aria-label=\"Response Type\"]"); bundleName = By.xpath("//input[@aria-label=\"Bundle Name, Lookup\"]"); nextStage = By.xpath("//button[@title=\"Next Stage\"]"); opportunityRibbon = By.xpath("//div[@title=\"Opportunity\"]"); getWorkOrderId = By.xpath("//div[@data-lp-id=\"form-header-title\"]/h1"); customerAcountInformationChecked = By.xpath("//*[@data-id=\"header_process_cgi_customeraccountinformationchecked.fieldControl-checkbox-inner-first\"]"); readyForOrderInformation = By.xpath("//*[@data-id=\"header_process_cgi_readyfororderinformation.fieldControl-checkbox-containercheckbox-inner-first\"]"); workOrderTypeProvisioning = By.xpath("//*[@aria-label=\"Provisioning / Approvisionnement\"]"); workOrderSubTypeInstallation = By.xpath("//*[@aria-label=\"New Installation / Nouvelle installation\"]"); qolysosPackageName = By.xpath("//*[@aria-label=\"Qolsys Good Package\"]"); customerAccountInformationCheckedYes = By.xpath("//*[@data-id=\"header_process_cgi_customeraccountinformationchecked.fieldControl-checkbox-containercheckbox-inner-second\"]"); getReadyForOrderInformationYes = By.xpath("//*[@data-id=\"header_process_cgi_readyfororderinformation.fieldControl-checkbox-containercheckbox-inner-second\"]"); suggestionsButton = By.xpath("//*[@aria-label=\"Suggestions\"]"); } public void getProgramAndSource(MarketingTabValidation mtv) { String program = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@aria-label=\"Compensation\"]/descendant::*[@data-id=\"cgi_programid\"]/descendant::ul/li"))).getText(); String source = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@aria-label=\"Compensation\"]/descendant::*[@data-id=\"cgi_sourceid\"]/descendant::ul/li"))).getText(); mtv.setProgram(program); mtv.setSource(source); } public void switchToDetails() { wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@aria-label=\"Details\"]"))).click(); } public void getDetails(MarketingTabValidation mtv) { String B1Number = driver.findElement(By.xpath("//*[@aria-label=\"B1 Number\"]")).getAttribute("value"); String MobileTelephone = driver.findElement(By.xpath("//*[@aria-label=\"Mobile Telephone #\n\"]")).getAttribute("value"); String MobileAccount = driver.findElement(By.xpath("//*[@aria-label=\"Mobile Telephone #\n\"]")).getAttribute("value"); } int global = 0; public void openSuggestions() { try { wait.until(ExpectedConditions.elementToBeClickable(suggestionsButton)).click(); global++; } catch (Exception e) { if (global < 20) { openSuggestions(); } // e.printStackTrace(); } } public void switchTosuggestionMenu() { wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("FullPageWebResource"))); System.out.println(wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[text()='PowerG Carbon Monoxide Detector']"))).getText()); } public void switchToAddress() { wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@aria-label=\"Address\"]"))).click(); } public void clickSubmit() { wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("fullscreen-app-host"))); // wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@tabindex=\"35\"]"))).click(); } public void sendQuotation() { wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@aria-label=\"Send Quotation\"]"))).click(); } public void getAddressInformation(MarketingTabValidation mtv) { wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@aria-label=\"Province\"]"))); String streetNo = driver.findElement(By.xpath("//*[@aria-label=\"Street Number\"]")).getAttribute("value"); String streetOne = driver.findElement(By.xpath("//*[@aria-label=\"Street 1\"]")).getAttribute("value"); String streetTwo = driver.findElement(By.xpath("//*[@aria-label=\"Street 2\"]")).getAttribute("value"); String city = driver.findElement(By.xpath("//*[@aria-label=\"City\"]")).getAttribute("value"); String postalCode = driver.findElement(By.xpath("//*[@aria-label=\"Postal Code\"]")).getAttribute("value"); String province = driver.findElement(By.xpath("//*[@aria-label=\"Province\"]")).getAttribute("title"); mtv.setStreetNoOne(streetNo); mtv.setStreetOne(streetOne); mtv.setCity(city); mtv.setPostalCode(postalCode); } public void addAdditionalItem(String productName, String quanity) { System.out.println(wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[text()='" + productName + "']"))).getText()); WebElement elementQuanity = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[text()='" + productName + "']/following::input"))); WebElement elementButton = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[text()='" + productName + "']/following::button"))); System.out.println(elementQuanity.getAttribute("value")); elementQuanity.sendKeys(quanity); elementButton.click(); } public void addPromotionItems(String productName) { System.out.println(wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[text()='" + productName + "']"))).getText()); WebElement elementButton = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[text()='" + productName + "']/following::button"))); elementButton.click(); } public void closeSuggestionsMenu() { wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@aria-label=\"Close\"]"))).click(); } public Boolean checkWorkOrderType() { Boolean ans = false; try { driver.findElement(workOrderTypeProvisioning); ans = true; } catch (Exception e) { logger.debug(e.toString()); ans = false; } finally { return ans; } } public Boolean validateLookUp(By lookup) { Boolean ans = false; try { driver.findElement(lookup); ans = true; } catch (Exception e) { logger.debug(e.toString()); ans = false; } finally { return ans; } } public Boolean checkworkOrderTypeProvisioning() { Boolean ans = false; try { driver.findElement(workOrderSubTypeInstallation); ans = true; } catch (Exception e) { logger.debug(e.toString()); ans = false; } finally { return ans; } } public void fillOrderMaxNumber(String value) { util.delayInput(driver, wait, By.xpath("//*[@aria-label=\"Order Max Order Number\"]"), value); } public void checkCustomerAccount() { util.delayClick(driver, wait, customerAccountInformationCheckedYes); } public void checkReadyForOrderInformation() { util.delayClick(driver, wait, readyForOrderInformation); } public void dropDownMenu( WebElement element){ Select select = new Select(element); select.selectByVisibleText("Yes"); } public void nextStage() throws InterruptedException { Thread.sleep(3000); // WebElement element = driver.findElement(opportunityRibbon); // Actions actions = new Actions(driver); // actions.moveToElement(element).click().build().perform(); endlessClick(driver, wait, opportunityRibbon, 0); // util.delayClick(driver, wait, opportunityRibbon); // if (!isCustomerAccountChecked()) { // checkCustomerAccount(); // } Thread.sleep(3000); dropDownMenu(driver.findElement(By.xpath("//*[@aria-label=\"Customer Account information checked\"]"))); Thread.sleep(1000); dropDownMenu(driver.findElement(By.xpath("//*[@aria-label=\"Ready for Order Information\"]"))); // if (!isReadyForOrderInformation()) { // checkReadyForOrderInformation(); // } Thread.sleep(5000); util.delayClick(driver, wait, nextStage); selectWorkOrder(); } public void selectWorkOrder() { WebDriverWait quickWait = new WebDriverWait(driver, 3); // By workOrderNext = By.xpath("//li[@aria-label=\"" + getOpportunityId().trim() + "\" or @aria-label=\"" + getOpportunityId().trim()+ " \"" + "or @aria-label=\"" + getOpportunityId().trim() +" \"]"); By workOrderNext = By.xpath("//*[contains(@aria-label, '" + getOpportunityId().trim() + "')]"); quickWait.until(ExpectedConditions.presenceOfElementLocated(workOrderNext)).click(); // try { // quickWait.until(ExpectedConditions.presenceOfElementLocated(workOrderNext)).click(); // } catch (Exception e) { // } // try { // workOrderNext = By.x<path("//li[@aria-label=\"" + getOpportunityId().trim() + " \"]"); // quickWait.until(ExpectedConditions.presenceOfElementLocated(workOrderNext)).click(); // } catch (Exception e) { // // // } } public Boolean isReadyForOrderInformation() { return util.getCheckBox(wait, getReadyForOrderInformationYes); } public Boolean isCustomerAccountChecked() { return util.getCheckBox(wait, customerAccountInformationCheckedYes); } public void endlessClick(WebDriver driver, WebDriverWait wait, By link, int attempts) throws InterruptedException { if (attempts > 10) { } else { try { util.delayClick(driver, wait, opportunityRibbon); } catch (Exception e) { Thread.sleep(1000); endlessClick(driver, wait, opportunityRibbon, attempts++); } finally { } } } public String getOpportunityId() { return util.getText(driver, wait, getWorkOrderId, "title"); } public void fillProductLineItemTab(OpportunityProductLineItem opli) { util.setSelect(wait.until(ExpectedConditions.presenceOfElementLocated(responseType)), 2); if (!validateLookUp(qolysosPackageName)) { util.inputLookUp(driver, wait, bundleName, opli.getBundleName()); } } public void fillOverview(OppotunityOverview overview) { selectServiceLocationType(overview.getServiceLocationType()); logger.info(driver.getCurrentUrl()); if (!checkWorkOrderType()) { util.inputLookUp(driver, wait, workOrderType, "Provisioning"); } if (!checkworkOrderTypeProvisioning()) { util.inputLookUp(driver, wait, workOrderSubType, overview.getWorkOrderSubType()); } } public void switchDetails() { wait.until(ExpectedConditions.presenceOfElementLocated(detailsTab)).click(); } public void fillDetails(int index, String customerType) { if (customerType.equals("Residential")) { util.setSelect(wait.until(ExpectedConditions.presenceOfElementLocated(customerSubTypeResidential)), index); } else if (customerType.equals("Commercial")) { util.setSelect(wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@aria-label=\"Customer Sub-Type Commercial\"]"))), index); } } public void switchProductLineItem() { wait.until(ExpectedConditions.presenceOfElementLocated(productLineItemTab)).click(); } public void selectServiceLocationType(String type) { System.out.println("selectServiceLocationType"); WebElement caSelect = wait.until(ExpectedConditions.presenceOfElementLocated(serviceLocationType)); Select cs = new Select(caSelect); switch (type) { case "Video and Automation": cs.selectByValue("285050002"); break; case "Medical": cs.selectByValue("285050000"); break; case "Security": cs.selectByValue("285050001"); break; default: System.out.println("error"); new Exception(); break; } } public String getWorkOrderType() { return wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@data-id=\"msdyn_workordertype.fieldControl-LookupResultsDropdown_msdyn_workordertype_selected_tag_text\"]"))).getText(); } public String getWorkOrderSubType() { return wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@data-id=\"cgi_workordersubtype_new.fieldControl-LookupResultsDropdown_cgi_workordersubtype_new_selected_tag_text\"]"))).getText(); } public void readyForNextStage() throws InterruptedException { Thread.sleep(3000); driver.findElement(By.xpath("//*[@aria-label=\"Ready for Next Stage\"]")).click(); Thread.sleep(3000); } public void clickNextStage() { driver.findElement(By.xpath("//*[@aria-label=\"Next Stage\"]")).click(); } public void selectGeneratedWorkOrder() throws InterruptedException { Thread.sleep(2000); wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[text()='Select Work Order' or text()='Select Sales Order' ]/../following-sibling::div/li"))).click(); Thread.sleep(2000); } }
[ "yujd13@gmail.com" ]
yujd13@gmail.com
bcf541fb8b47264a3c4e22e677f6af2e28d4e5c4
10ad765b8c1c19b04a8b46543344c5fc3e326cbd
/app/build/generated/not_namespaced_r_class_sources/debug/processDebugResources/r/android/support/constraint/R.java
e14a58c955f3cc220fc6443782201f0b2b5aed70
[]
no_license
RenatoWSilva/goschool-tecno
0f452aa3eedf7f960391deb81f79e3aaffe001f9
260316fecefb3e2d7e4db12c67209d12e2c885a6
refs/heads/master
2020-04-09T06:22:36.768126
2018-12-06T00:42:55
2018-12-06T00:42:55
160,109,339
0
0
null
null
null
null
UTF-8
Java
false
false
19,207
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package android.support.constraint; public final class R { private R() {} public static final class attr { private attr() {} public static final int barrierAllowsGoneWidgets = 0x7f030038; public static final int barrierDirection = 0x7f030039; public static final int chainUseRtl = 0x7f030056; public static final int constraintSet = 0x7f03006d; public static final int constraint_referenced_ids = 0x7f03006e; public static final int content = 0x7f03006f; public static final int emptyVisibility = 0x7f03008e; public static final int layout_constrainedHeight = 0x7f0300d1; public static final int layout_constrainedWidth = 0x7f0300d2; public static final int layout_constraintBaseline_creator = 0x7f0300d3; public static final int layout_constraintBaseline_toBaselineOf = 0x7f0300d4; public static final int layout_constraintBottom_creator = 0x7f0300d5; public static final int layout_constraintBottom_toBottomOf = 0x7f0300d6; public static final int layout_constraintBottom_toTopOf = 0x7f0300d7; public static final int layout_constraintCircle = 0x7f0300d8; public static final int layout_constraintCircleAngle = 0x7f0300d9; public static final int layout_constraintCircleRadius = 0x7f0300da; public static final int layout_constraintDimensionRatio = 0x7f0300db; public static final int layout_constraintEnd_toEndOf = 0x7f0300dc; public static final int layout_constraintEnd_toStartOf = 0x7f0300dd; public static final int layout_constraintGuide_begin = 0x7f0300de; public static final int layout_constraintGuide_end = 0x7f0300df; public static final int layout_constraintGuide_percent = 0x7f0300e0; public static final int layout_constraintHeight_default = 0x7f0300e1; public static final int layout_constraintHeight_max = 0x7f0300e2; public static final int layout_constraintHeight_min = 0x7f0300e3; public static final int layout_constraintHeight_percent = 0x7f0300e4; public static final int layout_constraintHorizontal_bias = 0x7f0300e5; public static final int layout_constraintHorizontal_chainStyle = 0x7f0300e6; public static final int layout_constraintHorizontal_weight = 0x7f0300e7; public static final int layout_constraintLeft_creator = 0x7f0300e8; public static final int layout_constraintLeft_toLeftOf = 0x7f0300e9; public static final int layout_constraintLeft_toRightOf = 0x7f0300ea; public static final int layout_constraintRight_creator = 0x7f0300eb; public static final int layout_constraintRight_toLeftOf = 0x7f0300ec; public static final int layout_constraintRight_toRightOf = 0x7f0300ed; public static final int layout_constraintStart_toEndOf = 0x7f0300ee; public static final int layout_constraintStart_toStartOf = 0x7f0300ef; public static final int layout_constraintTop_creator = 0x7f0300f0; public static final int layout_constraintTop_toBottomOf = 0x7f0300f1; public static final int layout_constraintTop_toTopOf = 0x7f0300f2; public static final int layout_constraintVertical_bias = 0x7f0300f3; public static final int layout_constraintVertical_chainStyle = 0x7f0300f4; public static final int layout_constraintVertical_weight = 0x7f0300f5; public static final int layout_constraintWidth_default = 0x7f0300f6; public static final int layout_constraintWidth_max = 0x7f0300f7; public static final int layout_constraintWidth_min = 0x7f0300f8; public static final int layout_constraintWidth_percent = 0x7f0300f9; public static final int layout_editor_absoluteX = 0x7f0300fb; public static final int layout_editor_absoluteY = 0x7f0300fc; public static final int layout_goneMarginBottom = 0x7f0300fd; public static final int layout_goneMarginEnd = 0x7f0300fe; public static final int layout_goneMarginLeft = 0x7f0300ff; public static final int layout_goneMarginRight = 0x7f030100; public static final int layout_goneMarginStart = 0x7f030101; public static final int layout_goneMarginTop = 0x7f030102; public static final int layout_optimizationLevel = 0x7f030105; } public static final class id { private id() {} public static final int bottom = 0x7f080029; public static final int end = 0x7f08005f; public static final int gone = 0x7f08006f; public static final int invisible = 0x7f080083; public static final int left = 0x7f080087; public static final int packed = 0x7f0800a4; public static final int parent = 0x7f0800a6; public static final int percent = 0x7f0800a9; public static final int right = 0x7f0800ae; public static final int spread = 0x7f0800d0; public static final int spread_inside = 0x7f0800d1; public static final int start = 0x7f0800d6; public static final int top = 0x7f0800ea; public static final int wrap = 0x7f080108; } public static final class styleable { private styleable() {} public static final int[] ConstraintLayout_Layout = { 0x10100c4, 0x101011f, 0x1010120, 0x101013f, 0x1010140, 0x7f030038, 0x7f030039, 0x7f030056, 0x7f03006d, 0x7f03006e, 0x7f0300d1, 0x7f0300d2, 0x7f0300d3, 0x7f0300d4, 0x7f0300d5, 0x7f0300d6, 0x7f0300d7, 0x7f0300d8, 0x7f0300d9, 0x7f0300da, 0x7f0300db, 0x7f0300dc, 0x7f0300dd, 0x7f0300de, 0x7f0300df, 0x7f0300e0, 0x7f0300e1, 0x7f0300e2, 0x7f0300e3, 0x7f0300e4, 0x7f0300e5, 0x7f0300e6, 0x7f0300e7, 0x7f0300e8, 0x7f0300e9, 0x7f0300ea, 0x7f0300eb, 0x7f0300ec, 0x7f0300ed, 0x7f0300ee, 0x7f0300ef, 0x7f0300f0, 0x7f0300f1, 0x7f0300f2, 0x7f0300f3, 0x7f0300f4, 0x7f0300f5, 0x7f0300f6, 0x7f0300f7, 0x7f0300f8, 0x7f0300f9, 0x7f0300fb, 0x7f0300fc, 0x7f0300fd, 0x7f0300fe, 0x7f0300ff, 0x7f030100, 0x7f030101, 0x7f030102, 0x7f030105 }; public static final int ConstraintLayout_Layout_android_orientation = 0; public static final int ConstraintLayout_Layout_android_maxWidth = 1; public static final int ConstraintLayout_Layout_android_maxHeight = 2; public static final int ConstraintLayout_Layout_android_minWidth = 3; public static final int ConstraintLayout_Layout_android_minHeight = 4; public static final int ConstraintLayout_Layout_barrierAllowsGoneWidgets = 5; public static final int ConstraintLayout_Layout_barrierDirection = 6; public static final int ConstraintLayout_Layout_chainUseRtl = 7; public static final int ConstraintLayout_Layout_constraintSet = 8; public static final int ConstraintLayout_Layout_constraint_referenced_ids = 9; public static final int ConstraintLayout_Layout_layout_constrainedHeight = 10; public static final int ConstraintLayout_Layout_layout_constrainedWidth = 11; public static final int ConstraintLayout_Layout_layout_constraintBaseline_creator = 12; public static final int ConstraintLayout_Layout_layout_constraintBaseline_toBaselineOf = 13; public static final int ConstraintLayout_Layout_layout_constraintBottom_creator = 14; public static final int ConstraintLayout_Layout_layout_constraintBottom_toBottomOf = 15; public static final int ConstraintLayout_Layout_layout_constraintBottom_toTopOf = 16; public static final int ConstraintLayout_Layout_layout_constraintCircle = 17; public static final int ConstraintLayout_Layout_layout_constraintCircleAngle = 18; public static final int ConstraintLayout_Layout_layout_constraintCircleRadius = 19; public static final int ConstraintLayout_Layout_layout_constraintDimensionRatio = 20; public static final int ConstraintLayout_Layout_layout_constraintEnd_toEndOf = 21; public static final int ConstraintLayout_Layout_layout_constraintEnd_toStartOf = 22; public static final int ConstraintLayout_Layout_layout_constraintGuide_begin = 23; public static final int ConstraintLayout_Layout_layout_constraintGuide_end = 24; public static final int ConstraintLayout_Layout_layout_constraintGuide_percent = 25; public static final int ConstraintLayout_Layout_layout_constraintHeight_default = 26; public static final int ConstraintLayout_Layout_layout_constraintHeight_max = 27; public static final int ConstraintLayout_Layout_layout_constraintHeight_min = 28; public static final int ConstraintLayout_Layout_layout_constraintHeight_percent = 29; public static final int ConstraintLayout_Layout_layout_constraintHorizontal_bias = 30; public static final int ConstraintLayout_Layout_layout_constraintHorizontal_chainStyle = 31; public static final int ConstraintLayout_Layout_layout_constraintHorizontal_weight = 32; public static final int ConstraintLayout_Layout_layout_constraintLeft_creator = 33; public static final int ConstraintLayout_Layout_layout_constraintLeft_toLeftOf = 34; public static final int ConstraintLayout_Layout_layout_constraintLeft_toRightOf = 35; public static final int ConstraintLayout_Layout_layout_constraintRight_creator = 36; public static final int ConstraintLayout_Layout_layout_constraintRight_toLeftOf = 37; public static final int ConstraintLayout_Layout_layout_constraintRight_toRightOf = 38; public static final int ConstraintLayout_Layout_layout_constraintStart_toEndOf = 39; public static final int ConstraintLayout_Layout_layout_constraintStart_toStartOf = 40; public static final int ConstraintLayout_Layout_layout_constraintTop_creator = 41; public static final int ConstraintLayout_Layout_layout_constraintTop_toBottomOf = 42; public static final int ConstraintLayout_Layout_layout_constraintTop_toTopOf = 43; public static final int ConstraintLayout_Layout_layout_constraintVertical_bias = 44; public static final int ConstraintLayout_Layout_layout_constraintVertical_chainStyle = 45; public static final int ConstraintLayout_Layout_layout_constraintVertical_weight = 46; public static final int ConstraintLayout_Layout_layout_constraintWidth_default = 47; public static final int ConstraintLayout_Layout_layout_constraintWidth_max = 48; public static final int ConstraintLayout_Layout_layout_constraintWidth_min = 49; public static final int ConstraintLayout_Layout_layout_constraintWidth_percent = 50; public static final int ConstraintLayout_Layout_layout_editor_absoluteX = 51; public static final int ConstraintLayout_Layout_layout_editor_absoluteY = 52; public static final int ConstraintLayout_Layout_layout_goneMarginBottom = 53; public static final int ConstraintLayout_Layout_layout_goneMarginEnd = 54; public static final int ConstraintLayout_Layout_layout_goneMarginLeft = 55; public static final int ConstraintLayout_Layout_layout_goneMarginRight = 56; public static final int ConstraintLayout_Layout_layout_goneMarginStart = 57; public static final int ConstraintLayout_Layout_layout_goneMarginTop = 58; public static final int ConstraintLayout_Layout_layout_optimizationLevel = 59; public static final int[] ConstraintLayout_placeholder = { 0x7f03006f, 0x7f03008e }; public static final int ConstraintLayout_placeholder_content = 0; public static final int ConstraintLayout_placeholder_emptyVisibility = 1; public static final int[] ConstraintSet = { 0x10100c4, 0x10100d0, 0x10100dc, 0x10100f4, 0x10100f5, 0x10100f7, 0x10100f8, 0x10100f9, 0x10100fa, 0x101011f, 0x1010120, 0x101013f, 0x1010140, 0x101031f, 0x1010320, 0x1010321, 0x1010322, 0x1010323, 0x1010324, 0x1010325, 0x1010326, 0x1010327, 0x1010328, 0x10103b5, 0x10103b6, 0x10103fa, 0x1010440, 0x7f030038, 0x7f030039, 0x7f030056, 0x7f03006e, 0x7f0300d1, 0x7f0300d2, 0x7f0300d3, 0x7f0300d4, 0x7f0300d5, 0x7f0300d6, 0x7f0300d7, 0x7f0300d8, 0x7f0300d9, 0x7f0300da, 0x7f0300db, 0x7f0300dc, 0x7f0300dd, 0x7f0300de, 0x7f0300df, 0x7f0300e0, 0x7f0300e1, 0x7f0300e2, 0x7f0300e3, 0x7f0300e4, 0x7f0300e5, 0x7f0300e6, 0x7f0300e7, 0x7f0300e8, 0x7f0300e9, 0x7f0300ea, 0x7f0300eb, 0x7f0300ec, 0x7f0300ed, 0x7f0300ee, 0x7f0300ef, 0x7f0300f0, 0x7f0300f1, 0x7f0300f2, 0x7f0300f3, 0x7f0300f4, 0x7f0300f5, 0x7f0300f6, 0x7f0300f7, 0x7f0300f8, 0x7f0300f9, 0x7f0300fb, 0x7f0300fc, 0x7f0300fd, 0x7f0300fe, 0x7f0300ff, 0x7f030100, 0x7f030101, 0x7f030102 }; public static final int ConstraintSet_android_orientation = 0; public static final int ConstraintSet_android_id = 1; public static final int ConstraintSet_android_visibility = 2; public static final int ConstraintSet_android_layout_width = 3; public static final int ConstraintSet_android_layout_height = 4; public static final int ConstraintSet_android_layout_marginLeft = 5; public static final int ConstraintSet_android_layout_marginTop = 6; public static final int ConstraintSet_android_layout_marginRight = 7; public static final int ConstraintSet_android_layout_marginBottom = 8; public static final int ConstraintSet_android_maxWidth = 9; public static final int ConstraintSet_android_maxHeight = 10; public static final int ConstraintSet_android_minWidth = 11; public static final int ConstraintSet_android_minHeight = 12; public static final int ConstraintSet_android_alpha = 13; public static final int ConstraintSet_android_transformPivotX = 14; public static final int ConstraintSet_android_transformPivotY = 15; public static final int ConstraintSet_android_translationX = 16; public static final int ConstraintSet_android_translationY = 17; public static final int ConstraintSet_android_scaleX = 18; public static final int ConstraintSet_android_scaleY = 19; public static final int ConstraintSet_android_rotation = 20; public static final int ConstraintSet_android_rotationX = 21; public static final int ConstraintSet_android_rotationY = 22; public static final int ConstraintSet_android_layout_marginStart = 23; public static final int ConstraintSet_android_layout_marginEnd = 24; public static final int ConstraintSet_android_translationZ = 25; public static final int ConstraintSet_android_elevation = 26; public static final int ConstraintSet_barrierAllowsGoneWidgets = 27; public static final int ConstraintSet_barrierDirection = 28; public static final int ConstraintSet_chainUseRtl = 29; public static final int ConstraintSet_constraint_referenced_ids = 30; public static final int ConstraintSet_layout_constrainedHeight = 31; public static final int ConstraintSet_layout_constrainedWidth = 32; public static final int ConstraintSet_layout_constraintBaseline_creator = 33; public static final int ConstraintSet_layout_constraintBaseline_toBaselineOf = 34; public static final int ConstraintSet_layout_constraintBottom_creator = 35; public static final int ConstraintSet_layout_constraintBottom_toBottomOf = 36; public static final int ConstraintSet_layout_constraintBottom_toTopOf = 37; public static final int ConstraintSet_layout_constraintCircle = 38; public static final int ConstraintSet_layout_constraintCircleAngle = 39; public static final int ConstraintSet_layout_constraintCircleRadius = 40; public static final int ConstraintSet_layout_constraintDimensionRatio = 41; public static final int ConstraintSet_layout_constraintEnd_toEndOf = 42; public static final int ConstraintSet_layout_constraintEnd_toStartOf = 43; public static final int ConstraintSet_layout_constraintGuide_begin = 44; public static final int ConstraintSet_layout_constraintGuide_end = 45; public static final int ConstraintSet_layout_constraintGuide_percent = 46; public static final int ConstraintSet_layout_constraintHeight_default = 47; public static final int ConstraintSet_layout_constraintHeight_max = 48; public static final int ConstraintSet_layout_constraintHeight_min = 49; public static final int ConstraintSet_layout_constraintHeight_percent = 50; public static final int ConstraintSet_layout_constraintHorizontal_bias = 51; public static final int ConstraintSet_layout_constraintHorizontal_chainStyle = 52; public static final int ConstraintSet_layout_constraintHorizontal_weight = 53; public static final int ConstraintSet_layout_constraintLeft_creator = 54; public static final int ConstraintSet_layout_constraintLeft_toLeftOf = 55; public static final int ConstraintSet_layout_constraintLeft_toRightOf = 56; public static final int ConstraintSet_layout_constraintRight_creator = 57; public static final int ConstraintSet_layout_constraintRight_toLeftOf = 58; public static final int ConstraintSet_layout_constraintRight_toRightOf = 59; public static final int ConstraintSet_layout_constraintStart_toEndOf = 60; public static final int ConstraintSet_layout_constraintStart_toStartOf = 61; public static final int ConstraintSet_layout_constraintTop_creator = 62; public static final int ConstraintSet_layout_constraintTop_toBottomOf = 63; public static final int ConstraintSet_layout_constraintTop_toTopOf = 64; public static final int ConstraintSet_layout_constraintVertical_bias = 65; public static final int ConstraintSet_layout_constraintVertical_chainStyle = 66; public static final int ConstraintSet_layout_constraintVertical_weight = 67; public static final int ConstraintSet_layout_constraintWidth_default = 68; public static final int ConstraintSet_layout_constraintWidth_max = 69; public static final int ConstraintSet_layout_constraintWidth_min = 70; public static final int ConstraintSet_layout_constraintWidth_percent = 71; public static final int ConstraintSet_layout_editor_absoluteX = 72; public static final int ConstraintSet_layout_editor_absoluteY = 73; public static final int ConstraintSet_layout_goneMarginBottom = 74; public static final int ConstraintSet_layout_goneMarginEnd = 75; public static final int ConstraintSet_layout_goneMarginLeft = 76; public static final int ConstraintSet_layout_goneMarginRight = 77; public static final int ConstraintSet_layout_goneMarginStart = 78; public static final int ConstraintSet_layout_goneMarginTop = 79; public static final int[] LinearConstraintLayout = { 0x10100c4 }; public static final int LinearConstraintLayout_android_orientation = 0; } }
[ "skuich2009@hotmail.com" ]
skuich2009@hotmail.com
8eb5b584308569965f9ad903dd5795538753b6e3
2b51f68c8cb91cb50c6a4c73a56416d4558cb9f4
/Week_05/homwwork4/src/main/java/com/geekbang/myspringbootstarter/AutoConfiguration.java
6a6c585cb5d38067a78fddcc21ac0b7e66f31c5c
[]
no_license
FinallySays/JAVA-000
1a1993791420866d199cb79a6ff3585a4e61d36a
021e88d16d6aac9b632362bba034abcafb8d5932
refs/heads/main
2023-01-22T20:26:24.561221
2020-11-25T15:38:12
2020-11-25T15:38:12
303,080,797
0
0
null
2020-10-11T09:01:58
2020-10-11T09:01:58
null
UTF-8
Java
false
false
2,528
java
package com.geekbang.myspringbootstarter; import com.geekbang.myspringbootstarter.components.Klass; import com.geekbang.myspringbootstarter.components.School; import com.geekbang.myspringbootstarter.components.Student; import com.geekbang.myspringbootstarter.properties.KlassProperties; import com.geekbang.myspringbootstarter.properties.SchoolProperty; import com.geekbang.myspringbootstarter.properties.StudentProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import java.util.HashMap; import java.util.Random; import java.util.stream.IntStream; /** * @program: my-spring-boot-starter * @description: * @author: Shiwp * @create: 2020-11-18 20:47 **/ @Configuration @EnableConfigurationProperties(value = {SchoolProperty.class, KlassProperties.class, StudentProperties.class}) public class AutoConfiguration { @Autowired private SchoolProperty schoolProperty; @Autowired private KlassProperties klassProperties; @Autowired private StudentProperties studentProperties; @Bean @Scope("prototype") public Student student() { return Student.builder() .age(new Random().nextInt(20)) .name(studentProperties.getName()) .build(); } @Bean @Scope("prototype") public Klass klass() { Klass klass = Klass.builder() .name(klassProperties.getName()) .students(new HashMap<>()).build(); IntStream.range(1, klassProperties.getCount() + 1) .forEach(i -> { Student student = student(); student.setName("student" + i); klass.getStudents().put(student.getName(), student); }); return klass; } @Bean @Scope("prototype") public School school() { School school = School.builder() .name(schoolProperty.getName()) .klasses(new HashMap<>()).build(); IntStream.range(1, schoolProperty.getCount() + 1) .forEach(i -> { Klass klass = klass(); klass.setName(i + "班"); school.getKlasses().put(klass.getName(), klass); }); return school; } }
[ "shiwplee@gmail.com" ]
shiwplee@gmail.com
9b13fed55d01f15daa740fc5ce8b33d48f29ea1e
d3fb3544bca714fbaecec554055ee261c1558689
/hwkj/src/main/java/hwkj/hwkj/filter/FilterConfig.java
84e47d9e57572555b7c4e4495f1d66862c166964
[]
no_license
haiweikeji/test
31c8d75e8f462a4748bd7294fff08ccae1ec0146
794e21d4ba8fe6f3ceb25002ca5879203f19b37d
refs/heads/master
2022-07-01T11:52:37.615240
2019-09-16T06:34:13
2019-09-16T06:34:13
206,438,210
0
0
null
2022-06-21T01:48:56
2019-09-05T00:15:36
JavaScript
UTF-8
Java
false
false
969
java
package hwkj.hwkj.filter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class FilterConfig { @Autowired private MyFilter myFilter; @Bean public FilterRegistrationBean myFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(myFilter); registration.addUrlPatterns("*.do");//过滤所以.do的请求 //registration.addUrlPatterns("/*");//过滤所以请求 //registration.addUrlPatterns("/index.do");过滤单个请求 //registration.addUrlPatterns("/login.do"); registration.setName("myFilter"); registration.setOrder(10); System.out.println("Filter初始化"); return registration; } }
[ "425378487@qq.com" ]
425378487@qq.com
b4f863679d309788a3bbd53193d63a043de2a4a4
e11f9a9b269c87cf179b1ce6a8f87f8490803e69
/javaefex/USFLAG.java
5758458b25cd7ff5a0a964b5be0331e1e4594e50
[]
no_license
dclenden/OOP
3735024ec946221acc79e63bd2f16c097bf090e6
d631b04d5c6a1b81ba2c0a191fc50cf80474a1f7
refs/heads/master
2020-05-26T19:57:06.035615
2019-05-24T04:57:10
2019-05-24T04:57:10
188,354,452
0
0
null
null
null
null
UTF-8
Java
false
false
12,433
java
package javaefex; import javafx.application.Application; import javafx.scene.layout.BorderPane; import javafx.scene.layout.StackPane; import javafx.scene.layout.HBox; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.paint.Color; import javafx.scene.input.MouseEvent; /** * A very simple drawing program that lets the user add shapes to a drawing * area and drag them around. An abstract Shape class is used to represent * shapes in general, with subclasses to represent particular kinds of shape. * (These are implemented as nested classes inside the main class.) This * program is an illustration of class hierarchy, inheritance, polymorphism, * and abstract classes. Note that this program will fail if you add more * than 500 shapes, since it uses an array of length 500 to store the shapes. * (Note: This program draws on a JavaFX canvas, which is not the best way * to draw shapes in JavaFX. In fact, JavaFX has its own shape classes that * could be used more naturally.) */ public class USFLAG extends Application { private Shape[] shapes = new Shape[500]; // Contains shapes the user has drawn. private int shapeCount = 0; // Number of shapes that the user has drawn. private Canvas canvas; // The drawing area where the user draws. private Color currentColor = Color.RED; // Color to be used for new shapes. /** * A main routine that simply runs this application. */ public static void main(String[] args) { launch(args); } //--------------------- Methods for creating the GUI ------------------------- /** * This method is required for any JavaFX Application. It adds content to * the window (given by the parameter, stage) and shows the window. */ public void start(Stage stage) { canvas = makeCanvas(); paintCanvas(); StackPane canvasHolder = new StackPane(canvas); canvasHolder.setStyle("-fx-border-width: 2px; -fx-border-color: #444"); BorderPane root = new BorderPane(canvasHolder); root.setStyle("-fx-border-width: 1px; -fx-border-color: black"); root.setBottom(makeToolPanel(canvas)); Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle("Click buttons to add shapes; drag shapes with your mouse"); stage.setResizable(false); stage.show(); } private Canvas makeCanvas() { // Creates a canvas, and add mouse listeners to implement dragging. // The listeners are given by methods that are defined below. Canvas canvas = new Canvas(800,600); canvas.setOnMousePressed( this::mousePressed ); canvas.setOnMouseReleased( this::mouseReleased ); canvas.setOnMouseDragged( this::mouseDragged ); return canvas; } private HBox makeToolPanel(Canvas canvas) { // Make a pane containing the buttons that are used to add shapes // and the pop-up menu for selecting the current color. Button ovalButton = new Button("Add an Oval"); ovalButton.setOnAction( (e) -> addShape( new OvalShape() ) ); Button rectButton = new Button("Add a Rect"); rectButton.setOnAction( (e) -> addShape( new RectShape() ) ); Button roundRectButton = new Button("Add a RoundRect"); roundRectButton.setOnAction( (e) -> addShape( new RoundRectShape() ) ); ComboBox<String> combobox = new ComboBox<>(); combobox.setEditable(false); Color[] colors = { Color.RED, Color.GREEN, Color.BLUE, Color.CYAN, Color.MAGENTA, Color.YELLOW, Color.BLACK, Color.WHITE }; String[] colorNames = { "Red", "Green", "Blue", "Cyan", "Magenta", "Yellow", "Black", "White" }; combobox.getItems().addAll(colorNames); combobox.setValue("Red"); combobox.setOnAction( e -> currentColor = colors[combobox.getSelectionModel().getSelectedIndex()] ); HBox tools = new HBox(10); tools.getChildren().add(ovalButton); tools.getChildren().add(rectButton); tools.getChildren().add(roundRectButton); tools.getChildren().add(combobox); tools.setStyle("-fx-border-width: 5px; -fx-border-color: transparent; -fx-background-color: lightgray"); return tools; } private void paintCanvas() { // Redraw the shapes. The entire list of shapes // is redrawn whenever the user adds a new shape // or moves an existing shape. GraphicsContext g = canvas.getGraphicsContext2D(); g.setFill(Color.WHITE); // Fill with white background. g.fillRect(0,0,canvas.getWidth(),canvas.getHeight()); for (int i = 0; i < shapeCount; i++) { Shape s = shapes[i]; s.draw(g); } } private void addShape(Shape shape) { // Add the shape to the canvas, and set its size/position and color. // The shape is added at the top-left corner, with size 80-by-50. // Then redraw the canvas to show the newly added shape. This method // is used in the event listeners for the buttons in makeToolsPanel(). shape.setColor(currentColor); shape.reshape(10,10,150,100); shapes[shapeCount] = shape; shapeCount++; paintCanvas(); } // ------------ This part of the class defines methods to implement dragging ----------- // -------------- These methods are added to the canvas as event listeners ------------- private Shape shapeBeingDragged = null; // This is null unless a shape is being dragged. // A non-null value is used as a signal that dragging // is in progress, as well as indicating which shape // is being dragged. private int prevDragX; // During dragging, these record the x and y coordinates of the private int prevDragY; // previous position of the mouse. private void mousePressed(MouseEvent evt) { // User has pressed the mouse. Find the shape that the user has clicked on, if // any. If there is a shape at the position when the mouse was clicked, then // start dragging it. If the user was holding down the shift key, then bring // the dragged shape to the front, in front of all the other shapes. int x = (int)evt.getX(); // x-coordinate of point where mouse was clicked int y = (int)evt.getY(); // y-coordinate of point for ( int i = shapeCount - 1; i >= 0; i-- ) { // check shapes from front to back Shape s = shapes[i]; if (s.containsPoint(x,y)) { shapeBeingDragged = s; prevDragX = x; prevDragY = y; if (evt.isShiftDown()) { // s should be moved on top of all the other shapes for (int j = i; j < shapeCount-1; j++) { // move the shapes following s down in the list shapes[j] = shapes[j+1]; } shapes[shapeCount-1] = s; // put s at the end of the list paintCanvas(); // repaint canvas to show s in front of other shapes } return; } } } private void mouseDragged(MouseEvent evt) { // User has moved the mouse. Move the dragged shape by the same amount. int x = (int)evt.getX(); int y = (int)evt.getY(); if (shapeBeingDragged != null) { shapeBeingDragged.moveBy(x - prevDragX, y - prevDragY); prevDragX = x; prevDragY = y; paintCanvas(); // redraw canvas to show shape in new position } } private void mouseReleased(MouseEvent evt) { // User has released the mouse. Move the dragged shape, then set // shapeBeingDragged to null to indicate that dragging is over. shapeBeingDragged = null; } // ------- Nested class definitions for the abstract Shape class and three ----- // -------------------- concrete subclasses of Shape. -------------------------- static abstract class Shape { // A class representing shapes that can be displayed on a ShapeCanvas. // The subclasses of this class represent particular types of shapes. // When a shape is first constructed, it has height and width zero // and a default color of white. int left, top; // Position of top left corner of rectangle that bounds this shape. int width, height; // Size of the bounding rectangle. Color color = Color.WHITE; // Color of this shape. void reshape(int left, int top, int width, int height) { // Set the position and size of this shape. this.left = left; this.top = top; this.width = width; this.height = height; } void moveBy(int dx, int dy) { // Move the shape by dx pixels horizontally and dy pixels vertically // (by changing the position of the top-left corner of the shape). left += dx; top += dy; } void setColor(Color color) { // Set the color of this shape this.color = color; } boolean containsPoint(int x, int y) { // Check whether the shape contains the point (x,y). // By default, this just checks whether (x,y) is inside the // rectangle that bounds the shape. This method should be // overridden by a subclass if the default behavior is not // appropriate for the subclass. if (x >= left && x < left+width && y >= top && y < top+height) return true; else return false; } abstract void draw(GraphicsContext g); // Draw the shape in the graphics context g. // This must be overriden in any concrete subclass. } // end of class Shape static class RectShape extends Shape { // This class represents rectangle shapes. void draw(GraphicsContext g) { g.setFill(color); g.fillRect(left,top,width,height); g.setStroke(Color.BLACK); g.strokeRect(left,top,width,height); } } static class OvalShape extends Shape { // This class represents oval shapes. void draw(GraphicsContext g) { g.setFill(color); g.fillOval(left,top,width,height); g.setStroke(Color.BLACK); g.strokeOval(left,top,width,height); } boolean containsPoint(int x, int y) { // Check whether (x,y) is inside this oval, using the // mathematical equation of an ellipse. This replaces the // definition of containsPoint that was inherited from the // Shape class. double rx = width/2.0; // horizontal radius of ellipse double ry = height/2.0; // vertical radius of ellipse double cx = left + rx; // x-coord of center of ellipse double cy = top + ry; // y-coord of center of ellipse if ( (ry*(x-cx))*(ry*(x-cx)) + (rx*(y-cy))*(rx*(y-cy)) <= rx*rx*ry*ry ) return true; else return false; } } static class RoundRectShape extends Shape { // This class represents rectangle shapes with rounded corners. // (Note that it uses the inherited version of the // containsPoint(x,y) method, even though that is not perfectly // accurate when (x,y) is near one of the corners.) void draw(GraphicsContext g) { g.setFill(color); g.fillRoundRect(left,top,width,height,width/3,height/3); g.setStroke(Color.BLACK); g.strokeRoundRect(left,top,width,height,width/3,height/3); } } } // end class ShapeDraw
[ "David.Clendenning830@yahoo.com" ]
David.Clendenning830@yahoo.com
11495057928a048b8a7ce8492d4d86a6f0356dab
828213cc782bd4e71715a8b107e8d605b6838b0b
/src/main/java/com/antyron/AppRunner.java
246c8dad570edb2c69e983b9b9d5dac825ae2867
[]
no_license
arhitiron/sensors
162da7a3de53b954c4d5e5d02108492efd2186de
914390c5052f61358084e926833335063536bcf4
refs/heads/master
2016-08-12T04:02:20.080314
2016-01-02T12:43:53
2016-01-02T12:43:53
48,909,413
0
0
null
null
null
null
UTF-8
Java
false
false
909
java
package com.antyron; import com.antyron.sensors.factory.SensorFactory; import com.antyron.services.SensorManagerImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySources; import org.springframework.stereotype.Component; /** * @author atyron */ @Component @PropertySources({ @PropertySource("classpath:config/application.properties"), @PropertySource("file:conf/application.properties") }) public class AppRunner implements CommandLineRunner { @Autowired private SensorManagerImpl sensorManager; @Autowired private SensorFactory sensorFactory; @Override public void run(String... arg) throws Exception { sensorManager.add(sensorFactory.getDHT()); sensorManager.handle(); } }
[ "ant@nxc.no" ]
ant@nxc.no
59a3e0fa020d49e72c8114096e511bc9fb655d9a
41b0e1a060264d4b31c9792e3384ffbd5da48f3d
/app/src/main/java/com/ctao/bubbledrag/utils/Utils.java
f8d6e3133ac58c70d79dfe4aa03ac23c2dc06705
[]
no_license
namezhouyu/Bubble-Drag
b0bceb643c5068103c5cd95710da8c46b9596557
c9b8ca0a2295ae710ffc4225ca4051a5145954ac
refs/heads/master
2021-01-12T04:24:26.799787
2016-10-10T03:51:05
2016-10-10T03:51:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,777
java
package com.ctao.bubbledrag.utils; import android.app.Activity; import android.content.res.Resources; import android.view.Window; /** * Utils * Created by A Miracle on 2016/3/24. */ public class Utils { private static final float DENSITY = Resources.getSystem().getDisplayMetrics().densityDpi / 160F; /** * 获取状态栏高度+标题栏高度 * @param activity * @return */ public static int getTopBarHeight(Activity activity) { return activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); } /** * 获取两点之间的距离 * @param x1 * @param y1 * @param x2 * @param y2 * @return */ public static double distance(float x1, float y1, float x2, float y2) { return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); } /** * 判断给定字符串是否空白串 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串,返回true */ public static boolean isEmpty(CharSequence input) { if (input == null || "".equals(input)) return true; for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (c != ' ' && c != '\t' && c != '\r' && c != '\n') { return false; } } return true; } /** * !isEmpty(CharSequence input) */ public static boolean isNotEmpty(CharSequence input) { return !isEmpty(input); } public static int converDip2px(float dpValue) { return Math.round(dpValue * DENSITY); } public static int converPx2dip(float pxValue) { return Math.round(pxValue / DENSITY); } }
[ "1670562337@qq.com" ]
1670562337@qq.com
d71dd39498c90e8824dd153798c227141ea8edf7
93a070451cfe661fe2f88e37f8c65506b09ee0fb
/src/main/java/com/saalamsaifi/playground/design/pattern/di/injector/impl/EmailServiceInjector.java
b78e5cbcb9b3bb9e2827c3216a3f85df1fe56926
[]
no_license
shahdab-aalam-saifi/playground
bf0f469f9ef4a023bb9bcb3b40535dc66c7ee41d
2880153ea15f28ef1cabf6264b54d87b4e5596a6
refs/heads/master
2021-08-22T20:21:47.542535
2021-06-11T21:28:21
2021-06-11T21:28:21
212,964,802
0
0
null
2020-01-20T13:29:41
2019-10-05T08:03:30
Java
UTF-8
Java
false
false
565
java
package com.saalamsaifi.playground.design.pattern.di.injector.impl; import com.saalamsaifi.playground.design.pattern.di.DependencyInjection; import com.saalamsaifi.playground.design.pattern.di.consumer.Consumer; import com.saalamsaifi.playground.design.pattern.di.injector.MessageServiceInjector; import com.saalamsaifi.playground.design.pattern.di.service.impl.EmailServiceImpl; public class EmailServiceInjector implements MessageServiceInjector { @Override public Consumer getConsumer() { return new DependencyInjection(new EmailServiceImpl()); } }
[ "saalamsaifi@gmail.com" ]
saalamsaifi@gmail.com
2d4ef5ebe9d95e7c7a19841d69b3e2cc5a51c5f9
8736cef333c0b909a480f1fba289791f19bff1d9
/src/main/java/com/learn/practice/threads/concurrency/SelfManaged.java
5823ca9abe5ee2e745c8bd45e160b5fb4d21eb8c
[]
no_license
chika1983/java_learning
f47f548e11d22aab8c802a64dc92fcbbae85984b
7039f0931acfded4ee2d153213886bdcacaf111f
refs/heads/master
2022-03-29T01:51:19.811020
2020-01-07T02:32:13
2020-01-07T02:32:13
102,993,769
0
0
null
null
null
null
UTF-8
Java
false
false
575
java
package com.learn.practice.threads.concurrency; //: concurrency/SelfManaged.java // A Runnable containing its own driver Thread. public class SelfManaged implements Runnable { private int countDown = 5; private Thread t = new Thread(this); public SelfManaged() { t.start(); } public String toString() { return Thread.currentThread().getName() + "(" + countDown + "), "; } public void run() { while(true) { System.out.print(this); if(--countDown == 0) return; } } public static void main(String[] args) { for(int i = 0; i < 5; i++) new SelfManaged(); } }
[ "SrikanthRam@10.0.0.215" ]
SrikanthRam@10.0.0.215
598f2344859eb3a57999936337685ff8fc244088
ebb5dfe6e65b38f9fdc110cc02ca0f6ff41c2984
/src/main/java/com/dannymvp/config/YoReportoWebserverApplication.java
eca38aa6fecafb8b355acc6913e2493f5cbcf960
[]
no_license
danny9mvp/Yo-Reporto-Server
538bfe3cff5367c9ae50b0bb24b3713368676c9f
14160b102ffd3e8a3358b6676f931507382fe6b1
refs/heads/master
2022-07-21T19:30:23.938603
2019-06-11T23:49:19
2019-06-11T23:49:19
188,615,818
0
0
null
2022-05-25T23:19:16
2019-05-25T21:56:41
Java
UTF-8
Java
false
false
732
java
package com.dannymvp.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication @ComponentScan({"com.dannymvp.restful","com.dannymvp.services","com.dannymvp.controllers"}) @EntityScan("com.dannymvp.entities") @EnableJpaRepositories("com.dannymvp.repositories") public class YoReportoWebserverApplication { public static void main(String[] args) { SpringApplication.run(YoReportoWebserverApplication.class, args); } }
[ "danny9mvp@gmail.com" ]
danny9mvp@gmail.com
e614b46f34eecc3d3e46516ece7fb80c48338569
ae495c393e513f43ed17f9652f663dce5cebe76b
/For_Loop5.java
00d9167c29784342dcf61b61a3733a601c615cd1
[]
no_license
GuraasisSingh/Class9_Java
73028d47d812061c2155a67607a3754d83bb30a4
391af202b00f3fe493a175cb403013e27d6fcbd3
refs/heads/main
2023-08-22T15:59:57.928038
2021-10-08T19:19:40
2021-10-08T19:19:40
415,099,965
1
0
null
null
null
null
UTF-8
Java
false
false
138
java
public class For_Loop5 { public static void For_Loop5() { for(;;) System.out.println("infinite"); } }
[ "noreply@github.com" ]
noreply@github.com
b0db7be660d84bc582aefd473c2fe0a91de6b64d
faef6153463c9a2384c16da29b6b5444ea483d9d
/springmvc1-hello/src/main/java/zyr/learn/mvc/model/User.java
f8e8142c3cafc14fe9e1dcae0bb6ee1ad38e7386
[]
no_license
i6u/SpringMVCLearnNotes
5ca8838dd0c715809c87197eb6ff00b50187cb99
46c61d7def2789850f8b35eac862442f1360dc84
refs/heads/master
2021-06-19T06:05:45.571085
2017-06-23T03:27:06
2017-06-23T03:27:06
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,486
java
package zyr.learn.mvc.model; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; import javax.validation.constraints.Size; /** * Created by zhouweitao on 2016/11/19. * * */ public class User { private Integer id; private String username; private String password; private String email; public User(String username, String password, String email) { this.username = username; this.password = password; this.email = email; } public User() { } public User(Integer id, String username, String password, String email) { this.id = id; this.username = username; this.password = password; this.email = email; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @NotEmpty(message = "username cannot be empty") public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Size(min = 3,max = 6,message = "password Invalid format") public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Email(message = "email invalid format") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
[ "meekzhou@gmail.com" ]
meekzhou@gmail.com
acc0dc10aed4e134b8b72b52fab1a8c4d63e2f9d
cd4802766531a9ccf0fb54ca4b8ea4ddc15e31b5
/dist/game/data/scripts/quests/Q10756_AnInterdimensionalDraft/Q10756_AnInterdimensionalDraft.java
fe779004ee135c890b0ec1a1b028d4f633a4e4cf
[]
no_license
singto53/underground
8933179b0d72418f4b9dc483a8f8998ef5268e3e
94264f5168165f0b17cc040955d4afd0ba436557
refs/heads/master
2021-01-13T10:30:20.094599
2016-12-11T20:32:47
2016-12-11T20:32:47
76,455,182
0
1
null
null
null
null
UTF-8
Java
false
false
3,385
java
/* * This file is part of the L2J Mobius project. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package quests.Q10756_AnInterdimensionalDraft; import com.l2jmobius.gameserver.enums.Race; import com.l2jmobius.gameserver.model.actor.L2Npc; import com.l2jmobius.gameserver.model.actor.instance.L2PcInstance; import com.l2jmobius.gameserver.model.quest.Quest; import com.l2jmobius.gameserver.model.quest.QuestState; import com.l2jmobius.gameserver.model.quest.State; /** * An Interdimensional Draft (10756) * @author malyelfik */ public final class Q10756_AnInterdimensionalDraft extends Quest { // NPC private static final int PIO = 33963; // Monsters private static final int[] MONSTERS = { 20078, // Whispering Wind 21023, // Sobbing Wind 21024, // Babbling Wind 21025, // Giggling Wind 21026, // Singing Wind 23414, // Windima 23415, // Windima Feri 23416, // Windima Resh }; // Items private static final int UNWORLDLY_WIND = 39493; // Misc private static final int MIN_LEVEL = 20; private static final double DROP_RATE = 0.7d; public Q10756_AnInterdimensionalDraft() { super(10756); addStartNpc(PIO); addTalkId(PIO); addKillId(MONSTERS); addCondRace(Race.ERTHEIA, "33963-00.htm"); addCondMinLevel(MIN_LEVEL, "33963-00.htm"); registerQuestItems(UNWORLDLY_WIND); } @Override public String onAdvEvent(String event, L2Npc npc, L2PcInstance player) { final QuestState qs = getQuestState(player, false); if (qs == null) { return null; } String htmltext = event; switch (event) { case "33963-01.htm": case "33963-02.htm": case "33963-03.htm": case "33963-04.htm": break; case "33963-05.htm": { qs.startQuest(); break; } case "33963-08.html": { if (qs.isCond(2)) { giveStoryQuestReward(player, 8); addExpAndSp(player, 174222, 41); qs.exitQuest(false, true); } break; } default: htmltext = null; } return htmltext; } @Override public String onTalk(L2Npc npc, L2PcInstance player) { final QuestState qs = getQuestState(player, true); String htmltext = getNoQuestMsg(player); switch (qs.getState()) { case State.CREATED: htmltext = "33963-01.htm"; break; case State.STARTED: htmltext = (qs.isCond(1)) ? "33963-06.html" : "33963-07.html"; break; case State.COMPLETED: htmltext = getAlreadyCompletedMsg(player); break; } return htmltext; } @Override public String onKill(L2Npc npc, L2PcInstance killer, boolean isSummon) { final QuestState qs = getQuestState(killer, false); if ((qs != null) && qs.isCond(1) && giveItemRandomly(killer, UNWORLDLY_WIND, 1, 30, DROP_RATE, true)) { qs.setCond(2, true); } return super.onKill(npc, killer, isSummon); } }
[ "MobiusDev@7325c9f8-25fd-504a-9f63-8876acdc129b" ]
MobiusDev@7325c9f8-25fd-504a-9f63-8876acdc129b
b89272791b417acbfc344082e743dc3cf607dabc
e9379e5da7a2c3d2c632fe85352de7c6f77b90b5
/lab5/src/main/java/com/ibm/developer/hellojavaonkube101service/HelloJavaOnKube101ServiceApplication.java
05593406348384446d61d9f780660fd2e894f4db
[ "Apache-2.0" ]
permissive
cybernetics/java-on-kube-101
f370b9b7850cd6f1fb72eed2c1e00fbd7cda0553
25060c64585d018001b226996a3c162fc96f7cd0
refs/heads/main
2022-12-29T07:45:56.661329
2020-10-20T21:32:30
2020-10-20T21:32:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
898
java
package com.ibm.developer.hellojavaonkube101service; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @SpringBootApplication public class HelloJavaOnKube101ServiceApplication { public static void main(String[] args) { SpringApplication.run(HelloJavaOnKube101ServiceApplication.class, args); } @Bean public TaskExecutor taskExecutor() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(2); taskExecutor.setMaxPoolSize(2); // taskExecutor.setWaitForTasksToCompleteOnShutdown(true); // taskExecutor.setAwaitTerminationSeconds(10); taskExecutor.initialize(); return taskExecutor; } }
[ "wkorando@gmail.com" ]
wkorando@gmail.com
fdff43434600b17887fc0a31e72fee9218c58f40
660f707dd29ff5348271fbb888206d20e7db5320
/house/Square.java
a2b0327058926970accc806fe2163bbfd157fca6
[]
no_license
juancelemin/workespace
61898c2a841cca76dd3cc9b205330dedd19ee85b
da5042f52346d4f8f471ec6ed5a9e63bf7d52ecf
refs/heads/master
2020-12-18T12:51:01.681343
2016-07-26T19:06:44
2016-07-26T19:06:44
64,245,701
0
0
null
null
null
null
WINDOWS-1250
Java
false
false
3,683
java
import java.awt.*; /** * A square that can be manipulated and that draws itself on a canvas. * * @author Michael Kšlling and David J. Barnes * @version 2011.07.31 */ public class Square implements IDibujo { private int size; private int xPosition; private int yPosition; private String color; private boolean isVisible; /** * Create a new square at default position with default color. */ public Square() { size = 60; xPosition = 310; yPosition = 120; color = "red"; isVisible = false; } /** * Make this square visible. If it was already visible, do nothing. */ public void makeVisible() { isVisible = true; draw(); } /** * Make this square invisible. If it was already invisible, do nothing. */ public void makeInvisible() { erase(); isVisible = false; } /** * Move the square a few pixels to the right. */ public void moveRight() { moveHorizontal(20); } /** * Move the square a few pixels to the left. */ public void moveLeft() { moveHorizontal(-20); } /** * Move the square a few pixels up. */ public void moveUp() { moveVertical(-20); } /** * Move the square a few pixels down. */ public void moveDown() { moveVertical(20); } /** * Move the square horizontally by 'distance' pixels. */ public void moveHorizontal(int distance) { erase(); xPosition += distance; draw(); } /** * Move the square vertically by 'distance' pixels. */ public void moveVertical(int distance) { erase(); yPosition += distance; draw(); } /** * Slowly move the square horizontally by 'distance' pixels. */ public void slowMoveHorizontal(int distance) { int delta; if(distance < 0) { delta = -1; distance = -distance; } else { delta = 1; } for(int i = 0; i < distance; i++) { xPosition += delta; draw(); } } /** * Slowly move the square vertically by 'distance' pixels. */ public void slowMoveVertical(int distance) { int delta; if(distance < 0) { delta = -1; distance = -distance; } else { delta = 1; } for(int i = 0; i < distance; i++) { yPosition += delta; draw(); } } /** * Change the size to the new size (in pixels). Size must be >= 0. */ public void changeSize(int newSize) { erase(); size = newSize; draw(); } /** * Change the color. Valid colors are "red", "yellow", "blue", "green", * "magenta" and "black". */ public void changeColor(String newColor) { color = newColor; draw(); } /** * Draw the square with current specifications on screen. */ public void draw() { if(isVisible) { Canvas canvas = Canvas.getCanvas(); canvas.draw(this, color, new Rectangle(xPosition, yPosition, size, size)); canvas.wait(10); } } /** * Erase the square on screen. */ private void erase() { if(isVisible) { Canvas canvas = Canvas.getCanvas(); canvas.erase(this); } } }
[ "martinezjua00@gmail.com" ]
martinezjua00@gmail.com
04f45329cf3ad031c7f31d9ba132fa5888eace5f
8a7909586bf685770fc36f0cc5770036b18e611b
/app/src/main/java/wangzhifeng/bwie/com/login_demo/view/RegActivity.java
ca2858064bc59fe23ea81e38ba65d2a017892f2d
[]
no_license
wangzhifeng11/MyLoginDemo
f434c8b5ee67688de9dae3be9157d5ed3bf5c074
ab768d9244d25b777cde2400e3e08383ae6158b7
refs/heads/master
2020-03-16T08:37:19.003916
2018-05-08T11:33:17
2018-05-08T11:33:17
132,595,701
0
0
null
null
null
null
UTF-8
Java
false
false
1,925
java
package wangzhifeng.bwie.com.login_demo.view; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import wangzhifeng.bwie.com.login_demo.R; import wangzhifeng.bwie.com.login_demo.model.ModelImpl; import wangzhifeng.bwie.com.login_demo.presenter.PersenterImpl; public class RegActivity extends AppCompatActivity implements View.OnClickListener, IRegView { private EditText mobile; private EditText password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reg); //初始化界面 initViews(); } private void initViews() { mobile = findViewById(R.id.mobile); password = findViewById(R.id.pwd); Button reg = findViewById(R.id.reg); reg.setOnClickListener(this); } //点击事件 @Override public void onClick(View v) { switch (v.getId()) { case R.id.reg: PersenterImpl presenter = new PersenterImpl(); presenter.regPresenter(new ModelImpl(), this); break; } } //获取手机号 @Override public String getMobile() { return mobile.getText().toString(); } //密码 @Override public String getPassword() { return password.getText().toString(); } //注册成功 @Override public void regSuccess() { Toast.makeText(RegActivity.this, "注册成功---", Toast.LENGTH_SHORT).show(); startActivity(new Intent(RegActivity.this, HaActivity.class)); } //注册失败 @Override public void regError() { Toast.makeText(RegActivity.this, "注册失败---", Toast.LENGTH_SHORT).show(); } }
[ "1105083185@qq.com" ]
1105083185@qq.com
4e477321fdfc0d78801eba64083cc901e5339cab
02ceee0d5a3738195adbb481159bb25eedc4dbd3
/IteratorsAndComparatorsExercise/src/ListyIterator/ListIterator.java
36e7162b7f1c8b84cf27badb4a07f3f7ebbe864d
[]
no_license
lstamenov/JavaAdvanced
ea44251953121bc9d83c4ee39d6e08606a7166f6
d25bc22ca76ab7637e9f327984320d80c673ce28
refs/heads/master
2023-05-31T21:18:39.617238
2021-06-23T17:27:15
2021-06-23T17:27:15
351,995,123
0
0
null
null
null
null
UTF-8
Java
false
false
1,024
java
package ListyIterator; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class ListIterator implements Iterator<String>, Iterable<String>{ int index; List<String> strings; ListIterator(String... strings){ this.index = 0; this.strings = Arrays.asList(strings); } @Override public boolean hasNext() { return index < strings.size() - 1; } @Override public String next() { return strings.get(index); } public boolean move(){ if (hasNext()){ index++; return true; }else { return false; } } public void print(){ if (strings.size() == 0){ System.out.println("Invalid Operation!"); }else { System.out.println(next()); } } public void printAll(){ System.out.println(String.join(" ", strings)); } @Override public Iterator<String> iterator() { return this; } }
[ "stamenovl99@gmail.com" ]
stamenovl99@gmail.com
3328189c065d13db73751e5fc97409918dd97c03
97e76097619bfed12aff375868c5001ce0651f72
/src/main/java/com/github/c0urante/kafka/connect/reddit/stream/Reddit.java
2873c8661ec21667152fb5a507db133864de39bd
[ "WTFPL" ]
permissive
C0urante/kafka-connect-reddit
46c37664e3359721f8832bb1a22b7f0575b940e5
1810c239c79e31f3707ae512f35a8eaad550c8f0
refs/heads/master
2023-05-28T18:43:17.486648
2023-05-11T20:01:39
2023-05-11T20:01:39
145,372,623
17
5
NOASSERTION
2023-05-11T20:01:40
2018-08-20T05:59:20
Java
UTF-8
Java
false
false
3,147
java
/* Copyright © 2018 - 2018 Chris Egerton <fearthecellos@gmail.com> This work is free. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See the LICENSE file for more details. */ package com.github.c0urante.kafka.connect.reddit.stream; import com.github.c0urante.kafka.connect.reddit.version.Version; import net.dean.jraw.ApiException; import net.dean.jraw.RedditClient; import net.dean.jraw.http.OkHttpNetworkAdapter; import net.dean.jraw.http.UserAgent; import net.dean.jraw.models.Comment; import net.dean.jraw.models.Submission; import net.dean.jraw.models.SubredditSort; import net.dean.jraw.oauth.Credentials; import net.dean.jraw.oauth.OAuthHelper; import net.dean.jraw.pagination.Stream; import net.dean.jraw.references.SubredditReference; import java.util.List; import java.util.UUID; public class Reddit { private static final UserAgent userAgent = new UserAgent( "kafka", "com.github.c0urante.kafka.connect.reddit", Version.get(), "C0urante" ); private static final UUID DEVICE_ID = UUID.randomUUID(); private final int limit; private final RedditClient reddit; public Reddit(String oAuthClientId, int limit, boolean logHttpRequests) { this.limit = limit; this.reddit = createClient(oAuthClientId, logHttpRequests); } static RedditClient createClient(String oAuthClientId, boolean logHttpRequests) { RedditClient result = OAuthHelper.automatic( new OkHttpNetworkAdapter(userAgent), Credentials.userlessApp(oAuthClientId, DEVICE_ID) ); result.setLogHttp(logHttpRequests); return result; } public boolean canAccessSubreddit(String subreddit) { try { reddit.subreddit(subreddit).about(); return true; } catch (ApiException e) { return false; } } public Stream<Comment> comments(List<String> subreddits) { SubredditReference multireddit = subreddits(subreddits); return multireddit != null ? multireddit.comments().limit(limit).build().stream() : null; } public Stream<Submission> posts(List<String> subreddits) { SubredditReference multireddit = subreddits(subreddits); return multireddit != null ? multireddit.posts().limit(limit).sorting(SubredditSort.NEW).build().stream() : null; } private SubredditReference subreddits(List<String> subreddits) { switch (subreddits.size()) { case 0: return null; case 1: return reddit.subreddit(subreddits.get(0)); case 2: return reddit.subreddits(subreddits.get(0), subreddits.get(1)); default: { String[] others = subreddits.subList(2, subreddits.size()).toArray(new String[0]); return reddit.subreddits(subreddits.get(0), subreddits.get(1), others); } } } }
[ "cegerton@oberlin.edu" ]
cegerton@oberlin.edu
fe9d0fd00201b52e8e0b0f4d46f423f2b42cb67e
2e6eba1350246a8acf1139931a3969a4d3d1ed58
/programusingmethods/SphereMethodN.java
aaf687f176e20abc9ced3d2b30df13d72986945a
[]
no_license
natraj4392/core-java-practice
9b97b0122f9def622024acdedfee56de9cac81c3
8dbbc6cd8e6da4ecad0664e2b18ee43f6dc4df49
refs/heads/master
2022-06-13T20:05:26.176891
2020-05-09T08:01:21
2020-05-09T08:01:21
262,226,668
0
0
null
null
null
null
UTF-8
Java
false
false
303
java
package programusingmethods; class SphereMethodN { void volume() { final double pi = 3.142; int r = 10; double result = 1.33 * pi * r * r * r ; System.out.println(result); } public static void main(String[] args){ new SphereMethodN().volume(); } }
[ "60502111+natraj4392@users.noreply.github.com" ]
60502111+natraj4392@users.noreply.github.com
8894aba7e60000c1480231e6c0c9726a205a1d6c
2a161ae1949d089c62feabbe3ae6fa72f0fc428c
/app/src/androidTest/java/com/fpoly/dong/sevice/ExampleInstrumentedTest.java
bec8c3a150afb6efa8ac52cb02aec0d0eb4dd5e9
[]
no_license
Tienda328/Sevice
0060deaadc778471b138a8944f0ea5bf26702167
66b5ef8a27116b2e704c73fcbc6b52a4c06476bd
refs/heads/master
2020-04-03T14:46:21.351050
2018-10-30T06:24:48
2018-10-30T06:24:48
155,335,326
0
1
null
null
null
null
UTF-8
Java
false
false
726
java
package com.fpoly.dong.sevice; 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() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.fpoly.dong.sevice", appContext.getPackageName()); } }
[ "dongnqph06655@fpt.edu.vn" ]
dongnqph06655@fpt.edu.vn
dbc6d552aad864feeaf30186cf3f0528d0c3057e
3e7b7ac7aaf134a4055573008a379a47ac729ed9
/src/main/java/bbs/Funcs.java
a10b8679a968940e6cee344759b7a3fbacdd2e67
[]
no_license
soholzx/blade-bbs
5e88f448050e6ff25be0df1c5e32111628f10050
a1fb6fd0659ecbe960838208abf0f487a4cbc178
refs/heads/master
2020-04-14T20:25:25.982536
2015-09-05T06:12:46
2015-09-05T06:12:46
41,951,493
1
0
null
2015-09-05T06:23:44
2015-09-05T06:23:44
null
UTF-8
Java
false
false
2,604
java
package bbs; import java.util.Date; import javax.servlet.ServletContext; import bbs.kit.BBSKit; import blade.BladeWebContext; import blade.kit.DateKit; import blade.kit.StringKit; public class Funcs { /** * 获取相对路径 * @param path * @return */ public static String base_url(String path) { ServletContext servletContext = BladeWebContext.servletContext(); String ctx = servletContext.getContextPath(); if(StringKit.isBlank(path)){ return ctx; } String val = ctx + "/" + path; return val.replaceAll("//", "/"); } /** * 格式化日期 * @param date * @return */ public static String fmtdate(Date date) { if(null != date){ return DateKit.dateFormat(date); } return ""; } /** * 格式化日期 * @param date * @param patten * @return */ public static String fmtdate(Date date, String patten) { if(null != date){ return DateKit.dateFormat(date, patten); } return ""; } public static String today(String patten){ return fmtdate(new Date(), patten); } /** * 截取字符串个数 * @param str * @param count * @return */ public static String str_count(String str, int count){ if(StringKit.isNotBlank(str) && count > 0){ if(str.length() <= count){ return str; } return str.substring(0, count); } return ""; } /** * 显示时间,如果与当前时间差别小于一天,则自动用**秒(分,小时)前,如果大于一天则用format规定的格式显示 * * @param ctime时间 * @return */ public static String timespan(Date ctime) { String r = ""; if (ctime == null) return r; long nowtimelong = System.currentTimeMillis(); long ctimelong = ctime.getTime(); long result = Math.abs(nowtimelong - ctimelong); // 20秒内 if (result < 20000){ r = "刚刚"; } else if (result >= 20000 && result < 60000) { // 一分钟内 long seconds = result / 1000; r = seconds + "秒钟前"; } else if (result >= 60000 && result < 3600000) { // 一小时内 long seconds = result / 60000; r = seconds + "分钟前"; } else if (result >= 3600000 && result < 86400000) { // 一天内 long seconds = result / 3600000; r = seconds + "小时前"; } else { long days = result / 3600000 / 24; r = days + "天前"; } return r; } /* * markdown转html */ public static String mdTohtml(String md){ if(StringKit.isNotBlank(md)){ return BBSKit.mdToHtml(md); } return ""; } }
[ "biezhi.me@gmail.com" ]
biezhi.me@gmail.com
fb94a4b7436c1882739fea72a9609d00f85e700f
47a2aae2f4c6dbf8a4f0b8cf93d1586f78782640
/src/principal/StrategyConcreteCpp.java
17e42d542d91b127cd65abad3ef4ebc686c7a2c6
[]
no_license
yaaff/projetoMACP
cc5389c45b8a6316c3583350516533204056a669
a8e70dc455a0c8d5c6b641794f2345f20d05a137
refs/heads/master
2020-09-13T06:28:34.472916
2019-11-19T12:40:03
2019-11-19T12:40:03
222,681,518
0
0
null
null
null
null
UTF-8
Java
false
false
7,761
java
package principal; import java.awt.Color; import javax.swing.JTextPane; import javax.swing.text.AttributeSet; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import analise.Delimitadores; /** Concrete Strategy de Fazer Highlight em C++ */ public class StrategyConcreteCpp implements StrategyHighlight { /** Concrete Strategy de Fazer Highlight em C++ */ public StrategyConcreteCpp(){ } public void fazerHighlight(JTextPane aux){ areaDeTexto = aux; inPos = -1; while(inPos < areaDeTexto.getText().length()){ int inicio = inPos+1; int fim; Delimitadores delimit = new Delimitadores(); in = nextChar(); if ( inPos >= areaDeTexto.getText().length()-1 ) // arquivo terminou break; // pula espacos em brancos while ( delimit.isDelimitadorClassico( in ) ){ in = nextChar(); if ( inPos >= areaDeTexto.getText().length()-1 ) // arquivo terminou break; inicio++; } // trata a ocorrencia de aspas simples if( in == '"'){ int i = areaDeTexto.getText().indexOf( '"', inPos+1 ); if( i > inPos ){ int j = areaDeTexto.getText().indexOf( '\n', inPos+1 ); if ( j > i ){ inPos = i; colun = colun + ( inPos - inicio ); //faz highlight areaDeTexto.select(inicio+1, inPos); append(inicio+1, inPos, areaDeTexto.getSelectedText(),2); } } else{ continue; } } // trata a ocorrencia de comentario if( in == '/'){ if(inPos < areaDeTexto.getText().length() && areaDeTexto.getText().charAt(inPos+1) == '/'){ while(areaDeTexto.getText().charAt(inPos) != '\n') inPos = (inPos + 1); } areaDeTexto.select(inicio, inPos); append(inicio, inPos, areaDeTexto.getSelectedText(),3); } // faz inPos apontar para o delimitador Token if( delimit.isDelimitadorToken( in ) ){ inPos = (inPos + 1); } int testLoop = 0; // varre o token ate o final while ( ! delimit.isDelimitador( in ) ){ testLoop++; if(testLoop > 100) break; if(inPos < areaDeTexto.getText().length()-1) in = nextChar(); } fim = inPos; // decrementa inPos para realisar proxima pesquisa a partir do delinitador inPos = (inPos - 1); //setando as cores da PR String palavra = areaDeTexto.getText().substring( inicio, fim ); if(palavra.equals("int") || palavra.equals("void") || palavra.equals("float") || palavra.equals("string") || palavra.equals("double") || palavra.equals("function") || palavra.equals("for") || palavra.equals("while") || palavra.equals("repeat") || palavra.equals("do")|| palavra.equals("return")){ areaDeTexto.select(inicio, fim); append(inicio, fim, areaDeTexto.getSelectedText(),0); } if(palavra.equals("cin") || palavra.equals("cout") || palavra.equals("printf") || palavra.equals("scanf") || palavra.equals("puts") || palavra.equals("gets") || palavra.equals("if") || palavra.equals("else") || palavra.equals("unsigned") || palavra.equals("ifdef")){ areaDeTexto.select(inicio, fim); append(inicio, fim, areaDeTexto.getSelectedText(),1); } if(palavra.equals("include") || palavra.equals("define")){ areaDeTexto.select(inicio, fim); append(inicio, fim, areaDeTexto.getSelectedText(),3); } if(palavra.equals("iostream") || palavra.equals("complex")){ areaDeTexto.select(inicio, fim); append(inicio, fim, areaDeTexto.getSelectedText(),2); } if(palavra.equals("using") || palavra.equals("namespace")){ areaDeTexto.select(inicio, fim); append(inicio, fim, areaDeTexto.getSelectedText(),4); } } } /** Func��o que percorre o codigo */ public static char nextChar(){ inPos = inPos + 1; char ch = areaDeTexto.getText().charAt( inPos ); return ch; } /** Fun��o que faz aplica os tipos de cores dependendo de qual eh a palavra reservada */ public static void append( int inicio, int fim, String copiada, int flag ) { AttributeSet colorido = BOLD_BLACK; AttributeSet coloridoAzul = AZUL; AttributeSet coloridoVermelho = VERMELHO; AttributeSet coloridoVerde = VERDE; AttributeSet coloridoRoxo = ROXO; AttributeSet normal = BLACK; if(flag == 0){//variaveis,inicio,fim. areaDeTexto.setCharacterAttributes( colorido, false ); String textoColorido = areaDeTexto.getText().substring( inicio,fim ); areaDeTexto.select( inicio, fim ); areaDeTexto.replaceSelection( textoColorido ); } else if(flag == 1){//palavra reservada areaDeTexto.setCharacterAttributes( coloridoAzul, false ); String textoColoridoAzul = areaDeTexto.getText().substring( inicio,fim ); areaDeTexto.select( inicio, fim ); areaDeTexto.replaceSelection( textoColoridoAzul ); } else if(flag == 2){//String areaDeTexto.setCharacterAttributes( coloridoVermelho, false ); String textoColoridoVermelho = areaDeTexto.getText().substring( inicio,fim ); areaDeTexto.select( inicio, fim ); areaDeTexto.replaceSelection( textoColoridoVermelho ); } else if(flag == 3){//include areaDeTexto.setCharacterAttributes( coloridoVerde, false ); String textoColoridoVerde = areaDeTexto.getText().substring( inicio,fim ); areaDeTexto.select( inicio, fim ); areaDeTexto.replaceSelection( textoColoridoVerde ); } else if(flag == 4){//using namespace areaDeTexto.setCharacterAttributes( coloridoRoxo, false ); String textocoloridoRoxo = areaDeTexto.getText().substring( inicio,fim ); areaDeTexto.select( inicio, fim ); areaDeTexto.replaceSelection( textocoloridoRoxo ); } areaDeTexto.setCharacterAttributes( normal, false ); } /** Posicao de verificacao inicial do highlight*/ public static int inPos = -1; /** caracter atual*/ public static char in = '@'; /** coluna atual*/ public static int colun = 0 ; /** referecia da area de texto de Interface*/ public static JTextPane areaDeTexto; /** DEFINICAO DE ESTILOS DE DOC */ static SimpleAttributeSet BOLD_BLACK = new SimpleAttributeSet(); static SimpleAttributeSet AZUL = new SimpleAttributeSet(); static SimpleAttributeSet BLACK = new SimpleAttributeSet(); static SimpleAttributeSet VERDE = new SimpleAttributeSet(); static SimpleAttributeSet VERMELHO = new SimpleAttributeSet(); static SimpleAttributeSet ROXO = new SimpleAttributeSet(); static { StyleConstants.setForeground(BOLD_BLACK, Color.black); StyleConstants.setBold(BOLD_BLACK, true); StyleConstants.setFontFamily(BOLD_BLACK, "Courier New"); StyleConstants.setFontSize(BOLD_BLACK, 14); StyleConstants.setForeground(AZUL, Color.blue); StyleConstants.setBold(AZUL, false); StyleConstants.setFontFamily(AZUL, "Courier New"); StyleConstants.setFontSize(AZUL, 14); StyleConstants.setForeground(BLACK, Color.black); StyleConstants.setBold(BLACK, false); StyleConstants.setFontFamily(BLACK, "Courier New"); StyleConstants.setFontSize(BLACK, 14); StyleConstants.setForeground(VERDE, Color.decode("#00CC00")); StyleConstants.setBold(VERDE, true); StyleConstants.setFontFamily(VERDE, "Courier New"); StyleConstants.setFontSize(VERDE, 14); StyleConstants.setForeground(VERMELHO, Color.red); StyleConstants.setBold(VERMELHO, false); StyleConstants.setFontFamily(VERMELHO, "Courier New"); StyleConstants.setFontSize(VERMELHO, 14); StyleConstants.setForeground(ROXO, Color.decode("#6633CC")); StyleConstants.setBold(ROXO, true); StyleConstants.setFontFamily(ROXO, "Courier New"); StyleConstants.setFontSize(ROXO, 14); } }
[ "yasmin.fernandes@acad.ifma.edu.br" ]
yasmin.fernandes@acad.ifma.edu.br
ddf60e5dd0d9a4f88e28c8771216363b53018ac8
cbe6a11d6bae54e6eab3c5599abca66186d46024
/src/main/lombok/com/restfb/types/webhook/messaging/TakeThreadControlItem.java
82d3be278b27e9be44ab7d7ace730d5ddb6f97ab
[ "MIT" ]
permissive
iamdhrv/restfb
84242dc50c5ce7a7d3adaf89c6e6596b3bc7e928
fcb706a38746ed5b96b653c6bd9b25f14b076e72
refs/heads/master
2022-10-09T13:03:56.233561
2020-06-11T10:32:42
2020-06-11T10:32:42
273,152,032
1
0
MIT
2020-06-18T05:45:09
2020-06-18T05:45:05
null
UTF-8
Java
false
false
1,651
java
/** * Copyright (c) 2010-2020 Mark Allen, Norbert Bartels. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.restfb.types.webhook.messaging; import com.restfb.Facebook; import lombok.Getter; import lombok.Setter; /** * Represents the * <a href="https://developers.facebook.com/docs/messenger-platform/handover-protocol/take-thread-control">Take Thread * Control</a> Callback */ public class TakeThreadControlItem implements InnerMessagingItem { @Getter @Setter @Facebook("previous_owner_app_id") private String previousOwnerAppId; @Getter @Setter @Facebook private String metadata; }
[ "n.bartels@phpmonkeys.de" ]
n.bartels@phpmonkeys.de
ff1d5b2e45580acab3a22d8840ccdce7d69d8575
d84a1a8739e16142964467b87db55364645c9821
/src/test/java/net/ddellspe/music/bot/commands/PlayCommandTest.java
2019ea9a88519b4ed13099cfcbf1604cbd298422
[ "Apache-2.0" ]
permissive
EikeSan/music-bot
290d5d9bc2c307f4d8c14a1c7dd3f8cfab2ac7ca
e92a0c0b45ca3a518c765fe3f29b040173ea1afe
refs/heads/main
2023-08-18T12:50:57.596273
2021-10-09T19:45:52
2021-10-09T19:45:52
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,606
java
package net.ddellspe.music.bot.commands; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager; import discord4j.common.util.Snowflake; import discord4j.core.GatewayDiscordClient; import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.core.object.VoiceState; import discord4j.core.object.entity.Member; import discord4j.core.object.entity.Message; import discord4j.core.object.entity.channel.MessageChannel; import discord4j.core.spec.EmbedCreateSpec; import discord4j.core.spec.MessageCreateMono; import discord4j.core.spec.MessageCreateSpec; import discord4j.rest.util.Color; import java.util.Optional; import net.ddellspe.music.bot.audio.MusicAudioLoadResultHandler; import net.ddellspe.music.bot.audio.MusicAudioManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import reactor.core.publisher.Mono; public class PlayCommandTest { private static final Snowflake GUILD_ID = Snowflake.of("123456"); private static final Snowflake CHAT_CHANNEL_ID = Snowflake.of("666666"); private static final Snowflake VOICE_CHANNEL_ID = Snowflake.of("111111"); private MusicAudioManager mockManager; private MessageCreateEvent mockEvent; private Message mockMessage; private MessageChannel mockChatChannel; private GatewayDiscordClient mockClient; @BeforeEach public void before() { mockManager = Mockito.mock(MusicAudioManager.class); mockEvent = Mockito.mock(MessageCreateEvent.class); mockMessage = Mockito.mock(Message.class); mockChatChannel = Mockito.mock(MessageChannel.class); mockClient = Mockito.mock(GatewayDiscordClient.class); MusicAudioManager.set(GUILD_ID, mockManager); when(mockManager.getPrefix()).thenReturn("!"); when(mockEvent.getGuildId()).thenReturn(Optional.of(GUILD_ID)); when(mockEvent.getClient()).thenReturn(mockClient); when(mockEvent.getMessage()).thenReturn(mockMessage); when(mockMessage.getChannel()).thenReturn(Mono.just(mockChatChannel)); when(mockMessage.getChannelId()).thenReturn(CHAT_CHANNEL_ID); } @Test public void testGetName() { PlayCommand cmd = new PlayCommand(); assertEquals("play", cmd.getName()); } @Test public void testGetFilterChannelReturnsProperValue() { Snowflake chatChannel = Snowflake.of("111111"); when(mockManager.getChatChannel()).thenReturn(Snowflake.of("111111")); PlayCommand cmd = new PlayCommand(); assertEquals(chatChannel, cmd.getFilterChannel(GUILD_ID)); } @Test public void testInvalidQuerySendsMessageOfException() { EmbedCreateSpec expectedSpec = EmbedCreateSpec.builder().color(Color.RED).title("Invalid command: '!play'").build(); when(mockMessage.getContent()).thenReturn("!play"); when(mockChatChannel.createMessage(expectedSpec)) .thenReturn(MessageCreateMono.of(mockChatChannel).withEmbeds(expectedSpec)); // Required for internal createMessage operation when(mockChatChannel.createMessage(any(MessageCreateSpec.class))).thenReturn(Mono.empty()); PlayCommand cmd = new PlayCommand(); cmd.handle(mockEvent).block(); verify(mockChatChannel, times(1)).createMessage(expectedSpec); } @Test public void testNotInVoiceChannel() { EmbedCreateSpec expectedSpec = EmbedCreateSpec.builder() .color(Color.RED) .title("You must be in a voice channel to use the music bot.") .build(); // Quick null the voice channel output when(mockMessage.getContent()).thenReturn("!play song"); when(mockEvent.getMember()).thenReturn(Optional.empty()); when(mockChatChannel.createMessage(expectedSpec)) .thenReturn(MessageCreateMono.of(mockChatChannel).withEmbeds(expectedSpec)); // Required for internal createMessage operation when(mockChatChannel.createMessage(any(MessageCreateSpec.class))).thenReturn(Mono.empty()); PlayCommand cmd = new PlayCommand(); cmd.handle(mockEvent).block(); verify(mockChatChannel, times(1)).createMessage(expectedSpec); } @Test public void testInVoiceChannelNotStartedAndDoesNotStart() { EmbedCreateSpec expectedSpec = EmbedCreateSpec.builder() .color(Color.ORANGE) .title("Bot could not be started, check permissions of bot and voice channels.") .build(); Member mockMember = Mockito.mock(Member.class); VoiceState mockState = Mockito.mock(VoiceState.class); // Quick null the voice channel output when(mockMessage.getContent()).thenReturn("!play song"); when(mockEvent.getMember()).thenReturn(Optional.of(mockMember)); when(mockMember.getVoiceState()).thenReturn(Mono.just(mockState)); when(mockState.getChannelId()).thenReturn(Optional.of(VOICE_CHANNEL_ID)); when(mockChatChannel.createMessage(expectedSpec)) .thenReturn(MessageCreateMono.of(mockChatChannel).withEmbeds(expectedSpec)); // Required for internal createMessage operation when(mockChatChannel.createMessage(any(MessageCreateSpec.class))).thenReturn(Mono.empty()); when(mockManager.isStarted()).thenReturn(false, false); when(mockManager.start(mockClient, VOICE_CHANNEL_ID, CHAT_CHANNEL_ID)).thenReturn(false); PlayCommand cmd = new PlayCommand(); cmd.handle(mockEvent).block(); verify(mockChatChannel, times(1)).createMessage(expectedSpec); verify(mockManager, times(1)).start(mockClient, VOICE_CHANNEL_ID, CHAT_CHANNEL_ID); } @Test public void testInVoiceChannelStartedAndQueues() { Member mockMember = Mockito.mock(Member.class); VoiceState mockState = Mockito.mock(VoiceState.class); MusicAudioManager.PLAYER_MANAGER = Mockito.mock(AudioPlayerManager.class); // Quick null the voice channel output when(mockMessage.getContent()).thenReturn("!play song"); when(mockEvent.getMember()).thenReturn(Optional.of(mockMember)); when(mockMember.getVoiceState()).thenReturn(Mono.just(mockState)); when(mockState.getChannelId()).thenReturn(Optional.of(VOICE_CHANNEL_ID)); when(mockManager.isStarted()).thenReturn(true, true); PlayCommand cmd = new PlayCommand(); cmd.handle(mockEvent).block(); verify(MusicAudioManager.PLAYER_MANAGER, times(1)) .loadItemOrdered(eq(mockManager), eq("song"), any(MusicAudioLoadResultHandler.class)); } }
[ "david.dellsperger@gmail.com" ]
david.dellsperger@gmail.com
15d34ee325055c9e94736d9c5502071c426c91bc
c36d08386a88e139e6325ea7f5de64ba00a45c9f
/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/impl/pb/SCMUploaderNotifyResponsePBImpl.java
cdff06c3821c52fd31d39685b8ddccd5747bbc3f
[ "Apache-2.0", "LicenseRef-scancode-unknown", "CC0-1.0", "CC-BY-3.0", "EPL-1.0", "LicenseRef-scancode-unknown-license-reference", "Classpath-exception-2.0", "CC-PDDC", "GCC-exception-3.1", "CDDL-1.0", "MIT", "GPL-2.0-only", "BSD-3-Clause", "LicenseRef-scancode-public-domain", "LGPL-2.1-on...
permissive
dmgerman/hadoop
6197e3f3009196fb4ca528ab420d99a0cd5b9396
70c015914a8756c5440cd969d70dac04b8b6142b
refs/heads/master
2020-12-01T06:30:51.605035
2019-12-19T19:37:17
2019-12-19T19:37:17
230,528,747
0
0
Apache-2.0
2020-01-31T18:29:52
2019-12-27T22:48:25
Java
UTF-8
Java
false
false
5,125
java
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package DECL|package|org.apache.hadoop.yarn.server.api.protocolrecords.impl.pb package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|api operator|. name|protocolrecords operator|. name|impl operator|. name|pb package|; end_package begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|proto operator|. name|YarnServerCommonServiceProtos operator|. name|SCMUploaderNotifyResponseProto import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|proto operator|. name|YarnServerCommonServiceProtos operator|. name|SCMUploaderNotifyResponseProtoOrBuilder import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|server operator|. name|api operator|. name|protocolrecords operator|. name|SCMUploaderNotifyResponse import|; end_import begin_class DECL|class|SCMUploaderNotifyResponsePBImpl specifier|public class|class name|SCMUploaderNotifyResponsePBImpl extends|extends name|SCMUploaderNotifyResponse block|{ DECL|field|proto name|SCMUploaderNotifyResponseProto name|proto init|= name|SCMUploaderNotifyResponseProto operator|. name|getDefaultInstance argument_list|() decl_stmt|; DECL|field|builder name|SCMUploaderNotifyResponseProto operator|. name|Builder name|builder init|= literal|null decl_stmt|; DECL|field|viaProto name|boolean name|viaProto init|= literal|false decl_stmt|; DECL|method|SCMUploaderNotifyResponsePBImpl () specifier|public name|SCMUploaderNotifyResponsePBImpl parameter_list|() block|{ name|builder operator|= name|SCMUploaderNotifyResponseProto operator|. name|newBuilder argument_list|() expr_stmt|; block|} DECL|method|SCMUploaderNotifyResponsePBImpl (SCMUploaderNotifyResponseProto proto) specifier|public name|SCMUploaderNotifyResponsePBImpl parameter_list|( name|SCMUploaderNotifyResponseProto name|proto parameter_list|) block|{ name|this operator|. name|proto operator|= name|proto expr_stmt|; name|viaProto operator|= literal|true expr_stmt|; block|} DECL|method|getProto () specifier|public name|SCMUploaderNotifyResponseProto name|getProto parameter_list|() block|{ name|mergeLocalToProto argument_list|() expr_stmt|; name|proto operator|= name|viaProto condition|? name|proto else|: name|builder operator|. name|build argument_list|() expr_stmt|; name|viaProto operator|= literal|true expr_stmt|; return|return name|proto return|; block|} annotation|@ name|Override DECL|method|getAccepted () specifier|public name|boolean name|getAccepted parameter_list|() block|{ name|SCMUploaderNotifyResponseProtoOrBuilder name|p init|= name|viaProto condition|? name|proto else|: name|builder decl_stmt|; comment|// Default to true, when in doubt just leave the file in the cache return|return operator|( name|p operator|. name|hasAccepted argument_list|() operator|) condition|? name|p operator|. name|getAccepted argument_list|() else|: literal|true return|; block|} annotation|@ name|Override DECL|method|setAccepted (boolean b) specifier|public name|void name|setAccepted parameter_list|( name|boolean name|b parameter_list|) block|{ name|maybeInitBuilder argument_list|() expr_stmt|; name|builder operator|. name|setAccepted argument_list|( name|b argument_list|) expr_stmt|; block|} DECL|method|mergeLocalToProto () specifier|private name|void name|mergeLocalToProto parameter_list|() block|{ if|if condition|( name|viaProto condition|) name|maybeInitBuilder argument_list|() expr_stmt|; name|proto operator|= name|builder operator|. name|build argument_list|() expr_stmt|; name|viaProto operator|= literal|true expr_stmt|; block|} DECL|method|maybeInitBuilder () specifier|private name|void name|maybeInitBuilder parameter_list|() block|{ if|if condition|( name|viaProto operator||| name|builder operator|== literal|null condition|) block|{ name|builder operator|= name|SCMUploaderNotifyResponseProto operator|. name|newBuilder argument_list|( name|proto argument_list|) expr_stmt|; block|} name|viaProto operator|= literal|false expr_stmt|; block|} block|} end_class end_unit
[ "kasha@apache.org" ]
kasha@apache.org
d19462cad8c3fadb596627acb65d8e805d2c5053
577cd0fce934f6dfbb1c70f83e6cae5dcc1bdb61
/PBL_0613/PB9_2.java
bfe13ec71b7a1432a3d3c024898b87744d57f7da
[]
no_license
pyu666/PBL_2018
9ca9135ed7133668f353f420fc799b61d4047068
75e804d46f355decbb82b8b5af40c3d2ac1e9a70
refs/heads/master
2020-04-02T16:14:35.531896
2019-02-22T20:04:44
2019-02-22T20:04:44
154,604,753
0
0
null
null
null
null
UTF-8
Java
false
false
1,078
java
import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class PB9_2 { public static void main(String[] args) { List<String> lines = null; try { lines = Files.readAllLines(Paths.get("member.csv"), Charset.forName("Shift_JIS")); } catch(Exception e) { System.out.println("ex"); } List<Member> members = new ArrayList<Member>(); int sum = 0; for (String line:lines) { String[] data = line.split(","); members.add(new Member(data[0],data[1],Gender.valueOf(data[2]))); Member member = members.get(members.size()-1); member.setPoint(Integer.valueOf(data[3])); sum = sum + Integer.valueOf(data[3]); } for (Member m: members) { System.out.println(m.getName()+" " +m.getId()+" "+ m.getGender()+ " "+m.getPoint() ); } System.out.println("average : "+sum/members.size()); } }
[ "32445749+pyu666@users.noreply.github.com" ]
32445749+pyu666@users.noreply.github.com
edd1c4bbd8a197122f045ab24b40d78a253a9fc5
979629f0eee7423df3e27a8c8aafebc88b6abaa9
/quiz/src/quiz/MethodQuiz02.java
bab9c134fff05e39572585eb1b7fa6f59ce48212
[]
no_license
minseon-oh/java
4e9b651be6927972769147bf81d1e8c8cf492702
4058228c858a27b33104ab174e1c1305a77ed71d
refs/heads/master
2023-08-17T05:54:22.876643
2020-06-03T06:53:21
2020-06-03T06:53:21
269,011,696
0
0
null
null
null
null
UTF-8
Java
false
false
1,548
java
package quiz; import java.util.Arrays; public class MethodQuiz02 { public static void main(String[] args) { // (method)Quiz17 p.24 int[] arr = {1,2,3,4,5}; method01(); System.out.println(method02("잘가")); System.out.println(method03(9, 10, 30)); System.out.println(method04(5)); System.out.println(method05(10, "Hi")); System.out.println(method06(10)); System.out.println(method07(arr)); System.out.println(Arrays.toString(method08("강아지", "고양이"))); System.out.println(maxNum(10,150)); System.out.println(abs(5)); }//main static void method01() { System.out.println("안녕"); } static String method02(String s) { return s; } static double method03(int a, int b, double c) { return a+b+c; } static String method04 (int i) { if(i % 2 == 0) { return "짝수"; }else { return "홀수"; } } static String method05 (int num, String s) { String str = ""; for(int i=1; i<=num; i++) { str += s; } return str; } static int maxNum(int a, int b) { // if(a > b) { // return a; // }else { // return b; // } //쌤풀이 return a > b? a : b; } static int method06 (int a) { int total = 0; for(int i=0; i<=a; i++) { total += i; } return total; } static int method07(int[] arr) { // int a = arr.length; // return a; return arr.length; } static String[] method08(String a, String b) { String[] s = {a, b}; return s; } static int abs(int a) { if(a < 0) { return -a; }else { return a; } } }
[ "aszx8983@naver.com" ]
aszx8983@naver.com
641acf607335d991e0a4081f21aa0add6454f3cf
c155ad3b281542e9ece931ee002339f78392bed0
/android/app/src/main/java/com/airbnbclone/MainApplication.java
7abae2dc096ecc159a18a1fe37b821e6b910c40e
[]
no_license
rendystdy/AirBnbUI-clone
a2cfbf854e9d028e111e8d75a1695705fd65f29b
4e1cfadbf7bd04a6336d452653fb8699672a3e32
refs/heads/master
2023-01-06T21:30:16.644953
2019-07-31T12:36:38
2019-07-31T12:36:38
199,853,078
0
0
null
2023-01-04T05:53:58
2019-07-31T12:36:18
JavaScript
UTF-8
Java
false
false
1,469
java
package com.airbnbclone; // import com.oblador.vectoricons.VectorIconsPackage; import android.app.Application; import android.util.Log; import com.facebook.react.PackageList; import com.facebook.hermes.reactexecutor.HermesExecutorFactory; import com.facebook.react.bridge.JavaScriptExecutorFactory; import com.facebook.react.ReactApplication; import com.oblador.vectoricons.VectorIconsPackage; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.soloader.SoLoader; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { @SuppressWarnings("UnnecessaryLocalVariable") List<ReactPackage> packages = new PackageList(this).getPackages(); // Packages that cannot be autolinked yet can be added manually here, for example: // packages.add(new MyReactNativePackage()); return packages; } @Override protected String getJSMainModuleName() { return "index"; } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); } }
[ "rendysetiady8@gmail.com" ]
rendysetiady8@gmail.com
9a2b5861d971e82260321585cbdc2bdb402c3731
6e4978da76071211117a8ecbde208553c26a1087
/Portal/xmlfeed/src/classes.jar/src/atg/portal/gear/xmlfeed/XmlfeedTool.java
1112ef7258cc0de7911b970bdd47d10510d74027
[]
no_license
vkscorpio3/ATG_TASK
3b41df29898447bb4409bf46bc735045ce7d8cc6
8751d555c35a968d4d73c9e22d7f56a6c82192e7
refs/heads/master
2020-03-08T16:56:40.463816
2014-12-12T10:55:01
2014-12-12T10:55:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,430
java
/*<ATGCOPYRIGHT> * Copyright (C) 2001-2011 Art Technology Group, Inc. * All Rights Reserved. No use, copying or distribution of this * work may be made except in accordance with a valid license * agreement from Art Technology Group. This notice must be * included on all copies, modifications and derivatives of this * work. * * Art Technology Group (ATG) MAKES NO REPRESENTATIONS OR WARRANTIES * ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. ATG SHALL NOT BE * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. * * "Dynamo" is a trademark of Art Technology Group, Inc. </ATGCOPYRIGHT>*/ package atg.portal.gear.xmlfeed; import atg.servlet.*; import java.util.Map; import java.util.HashMap; import java.util.Iterator; import java.util.StringTokenizer; import java.lang.IndexOutOfBoundsException; /** * <p> * This is a utility class for the xmlfeed gear. It contains converter methods * between String and Map and queryFormat method, used to generate the dynamic * XML source URL. * </p> * * @version $Id: //app/portal/version/10.0.3/xmlfeed/classes.jar/src/atg/portal/gear/xmlfeed/XmlfeedTool.java#2 $$Change: 651448 $ * @updated $DateTime: 2011/06/07 13:55:45 $$Author: rbarbier $ */ public class XmlfeedTool { //------------------------------------- /** Class version string */ public static String CLASS_VERSION = "$Id: //app/portal/version/10.0.3/xmlfeed/classes.jar/src/atg/portal/gear/xmlfeed/XmlfeedTool.java#2 $$Change: 651448 $"; /** Separator to be used when encoding various xmlfeed user parameters. */ public static String FIELD_SEPARATOR = "&"; /** * Returns an encoded String using key-value pairs passed as a Map. * @param pMap Map cotaining key-value pairs. * @return An encoded String using key-value pairs passed as Map. */ public static String convertMapToParamString(Map pMap) { StringBuffer userParam = new StringBuffer(); Iterator kees = pMap.keySet().iterator(); while (kees.hasNext()) { String key = (String)kees.next(); String val = (String)pMap.get(key); userParam.append(key).append("=").append(val).append(FIELD_SEPARATOR); } //remove the last occurance of field separator, we don't need that if (userParam.length() > 0) { userParam.deleteCharAt(userParam.length()-1); } return userParam.toString(); } /** * Returns a Map by decoding key-value pairs from the input String. * @param pUserParam Encoded string with key-value pairs. * @return Map with key-value pairs. */ public static Map convertParamStringToMap(String pUserParam) { HashMap map = new HashMap(); StringTokenizer line = new StringTokenizer(pUserParam,FIELD_SEPARATOR); while (line.hasMoreTokens()) { String pair = line.nextToken(); int sepIndex = pair.indexOf('='); try { String key = pair.substring(0, sepIndex); String val = pair.substring(sepIndex+1, pair.length()); map.put(key, val); } catch (IndexOutOfBoundsException e) { //need to change this to proper error handling. //System.out.println("XmlfeedTool:" + e.getMessage()); } } return map; } }
[ "Andrii_Borovyk1@EPUAKHAW0679.kyiv.epam.com" ]
Andrii_Borovyk1@EPUAKHAW0679.kyiv.epam.com
11e41f6280997f504dd09f535e529e4164a0c2d3
34df134e4d1f82f72ca4b8a10b095a872d0f6bf7
/myjee/src/main/java/com/jamesfen/myjee/aop/xml/CompareInterceptor.java
2deccddd29f6e0533b97217ce32ea2d3af7d6dec
[]
no_license
belloner/myjee
090d0d6f95eae4937d39e4d7fe75338b360fd8c8
089e626370a0be4391b0206541f6462dbe6fd83d
refs/heads/master
2016-08-11T21:37:09.707680
2016-01-05T06:46:23
2016-01-05T06:46:23
44,082,954
0
0
null
null
null
null
UTF-8
Java
false
false
724
java
package com.jamesfen.myjee.aop.xml; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; public class CompareInterceptor implements MethodInterceptor{ public Object invoke(MethodInvocation invocation) throws Throwable{ Object result = null; String stu_name = invocation.getArguments()[0].toString(); if ( stu_name.equals("james")){ //如果学生是dragon时,执行目标方法, result= invocation.proceed(); } else{ System.out.println("此学生是"+stu_name+"而不是dragon,不批准其加入."); } return result; } }
[ "belloner@126.com" ]
belloner@126.com
e05a536e1d99f6a4982f3a1cd96778b825055f67
11751ff493279ba5b3d87e188ac95ab282b0b1a6
/Player.java
4858b7c126d24edf7ded8630b3c7a58bbc75ceff
[ "Apache-2.0" ]
permissive
Gillibert/Theorycraft
02a4b04775e288498e2788219401838b78ae6c98
6579ec8dcd471a978db7745664112b85d57880f2
refs/heads/master
2021-06-30T08:46:06.246227
2020-09-28T08:37:53
2020-09-28T08:37:53
172,477,195
0
0
null
null
null
null
UTF-8
Java
false
false
59,715
java
import java.util.*; import java.io.Serializable; public class Player implements Serializable { static private final long serialVersionUID = 100; static private int dsp_target[] = {0,1,2,3,4,5,6,7,9,10,24,31,53}; //*********************** public int current_class = -1; public boolean jeu_fini = false; public int nb_hits = 0; public int crit_taken = 0; public int nb_encounters = 0; public static String[] TagsName = Local.TAGS_NAME; // Tags names public static int nb_tags = TagsName.length; // Number of tags public boolean[] tags; // Player's tags public String name; // Player's name public Challenge defi; public double[] stats; // répartition des points de compétences public double[] stats_with_bonus; // For fast access public double[] item_bonus; // For fast access, used only in LevlUp public int[] auto_dist_coeff; // For auto_dist public double temperature_diff = 0.0; public double precipitation_strength = 0.0; public static String[] stats_name = Local.SKILLS_NAME; // nom des compétences public boolean disp; public boolean[] conditionToggle; public int[] conditionValues; public static int nb_stats = stats_name.length; // nombre de statistiques public double temps; // temps écoulé depuis le début du combat public double temps_total; // temps écoulé depuis le début du jeu public double orbes_investits_en_xp; public double orbes_investits_en_points_divins; public double orbes_investits_en_points_competence; public double orbes_investits_en_points_cosmiques; public double or_perdu_en_trou_noirs; public double nombre_trous_noirs; public double vie; // vie public ArrayList<Item> inventory;// inventraire public ArrayList<Item> craftInventory; //inventaire de la forge mystique public ArrayList<ObjectRule> rules; // régles et filtres d'inventaires public double charge; public double level; // niveau public double money; // argent public double cosmic_pts; public int zone; // zone public double xp_pt; // exp public Shop shop; // the shop public Monster mob; // the mob public Universe universe; // the universe public TimeStats t_stats ; public double points_haut_faits = 0.0; static class ComparateurStats implements Comparator<Item> { public int compare(Item s1, Item s2){ if (s1.nb_pts() > s2.nb_pts()) return -1; if (s1.nb_pts() < s2.nb_pts()) return 1; else return 0; } } public double class_upgrade_cost() { int cc = Math.max(0,current_class); ClassRPG theClass = universe.classList.get(cc); int nbc = 0; for(int i=0; i<nb_stats; i++) if(theClass.bonus[i] > 0) nbc++; return universe.class_upgrade_cost(nbc); } public boolean upgrade_class() { int thid, thid2; ClassRPG theClass = universe.classList.get(current_class); ArrayList<Integer> skillsId = new ArrayList<Integer>(); for(int i=0; i<nb_stats; i++) if(theClass.bonus[i] == 0 && theClass.malus[i] == 0) skillsId.add(i); if(skillsId.size() < 3) return false; thid = skillsId.get((int)(Math.random()*skillsId.size())); thid2 = skillsId.get((int)(Math.random()*skillsId.size())); for(int i=0; i<3; i++) { if(thid2!=thid) break; thid2 = skillsId.get((int)(Math.random()*skillsId.size())); } theClass.bonus[thid] = 1; if(thid2 != thid) theClass.malus[thid2] = 1; refresh_stats_with_bonus(); return true; } public void change_class(int idx) { if(idx == current_class || idx == -1) return; ClassRPG cls = universe.classList.get(idx); if(current_class == -1) { current_class = idx; if(disp) Game.MW.addLog(String.format(Local.INITIAL_CLASS_SELECTION,cls.name)); } else { current_class = idx; double bp = universe.base_penalty_for_class_change(); double pr = penalty_reduction(); personal_wait(bp*pr,TimeStats.ACTIVITY_PENALTY); if(disp) Game.MW.addLog(String.format(Local.CLASS_CHANGE,cls.name,bp*pr)); } refresh_stats_with_bonus(); } public double points_cosmiques_totaux() { return multiplicateur_points_cosmiques()*(points_de_competence_cosmique() +universe.points_cosmiques_pour_x_orbe(orbes_investits_en_points_cosmiques) +universe.points_cosmiques_pour_x_ecus(or_perdu_en_trou_noirs)); } public double heat_penalty() { return Math.min(1.0,100.0/(100+temperature_diff*heat_resistance())); } public double cold_penalty() { return Math.min(1.0,100.0/(100-temperature_diff*cold_resistance())); } public double overload_penalty() { double cm = charge_max(); if (charge <= cm) return 1.0; else return universe.base_overload_penalty((charge/cm-1.0)*overload_resistance()); } public double underload_bonus() // Base load ratio is limited to 10000 { double cm = charge_max(); if (charge >= cm) return 1.0; double cha = Math.max(charge,0.0001); return universe.base_underload_bonus(Math.min(cm/cha,10000))*underload_affinity(); } public double precipitation_penalty() { return 10.0/(10+precipitation_strength*precipitation_resistance()); } public double heat_bonus() { return Math.max(1.0,(100+temperature_diff*heat_affinity())/100.0); } public double cold_bonus() { return Math.max(1.0,(100-temperature_diff*cold_affinity())/100.0); } public double precipitation_bonus() { return (10.0+precipitation_strength*precipitation_affinity())/10.0; } public void refresh_weather_penalties() { temperature_diff = universe.get_current_temperature(zone) - universe.temperature_ideale(); } public void voyage(int zn) { if (zn != zone) { zone = zn; nb_encounters = 0; double bp = universe.base_penalty_for_travel(); double pr = penalty_reduction(); personal_wait(bp*pr,TimeStats.ACTIVITY_PENALTY); if(disp) Game.MW.addLog(String.format(Local.TRAVEL_TO,name,universe.map.zonesName.get(zone),bp*pr,pr,bp)); update_weather(); } } public void refresh_charge() { charge = 0.0; for(Item the_object : inventory) { charge += the_object.poids_final(this); } } public double points_distribues() { double res = 0; for(int i=0; i<nb_stats; i++) res += stats[i]; return res; } public double points_divins_distribues() { double res = 0; for(int i=0; i<universe.nb_universe_stats+universe.nb_universe_equations; i++) res += Math.abs(universe.points_divins[i]); return res; } public void remove_item(Item i) { i.equiped=false; refresh_stats_with_bonus(); } public void put_item(Item i) { for(Item the_object : inventory) { if(the_object.equiped && (the_object.pos == i.pos)) {the_object.equiped=false; break;} } i.equiped=true; t_stats.best_object_level = Math.max(t_stats.best_object_level,i.effectiveIlvl()); t_stats.most_expensive_object = Math.max(t_stats.most_expensive_object,i.prix()); refresh_stats_with_bonus(); } public double prix_achat(Item b) { if (b.discount) return discount_multiplier()*coeff_achat()*b.prix(); else return coeff_achat()*b.prix(); } public double prix_vente(Item b) { if (b.discount) return discount_multiplier()*coeff_vente()*b.prix(); else return coeff_vente()*b.prix(); } public boolean can_buy(Item b) { return (money - prix_achat(b) >= 0 || (b.stackable && money > 0.01)); } public void buy(Item it) { if (money<0.01) return; ArrayList<Item> tmp = new ArrayList<Item>(); tmp.add(it); buy(tmp); } public void buy(ArrayList<Item> slist) { if (slist.size()==0 || money<0.01) return; double perte_base = 0.0; double perte_mat = 0.0; double perte_orb = 0.0; double perte_other = 0.0; double total_prix = 0.0; ArrayList<Item> toAdd = new ArrayList<Item>(); ArrayList<Item> toRemove = new ArrayList<Item>(); String partial; for(Item the_object : slist) { double prix = prix_achat(the_object); if(total_prix+prix <= money) { toAdd.add(the_object); toRemove.add(the_object); total_prix += prix; } else if (the_object.stackable) { double qty_to_buy = ((money-total_prix)/prix)*the_object.qty; the_object.set_qty(the_object.qty - qty_to_buy); Item rit = new Item(); rit.copy(the_object); rit.set_qty(qty_to_buy); total_prix = money; toAdd.add(rit); break; } } for(Item the_object : toAdd) { double prix = prix_achat(the_object); if(the_object.rare == 0) perte_base += prix; else if(the_object.rare == 4 || the_object.rare == 5) perte_mat += prix; else if(the_object.rare == 6) perte_orb += prix; else perte_other += prix; charge += the_object.poids_final(this); } inventory.addAll(toAdd); shop.inventory.removeAll(toRemove); int nbitem = toAdd.size(); String buyStr=""; if(nbitem < 10) { for(Item the_object : toAdd) { if(buyStr != "") buyStr += ", "; buyStr += NameGenerator.firstCharLowercase(the_object.name); } } else { buyStr = String.format(Local.N_OBJECTS,nbitem); } if(perte_base > 0.0) money_loss(perte_base,TimeStats.LOSS_BUY_BASE); if(perte_mat > 0.0) money_loss(perte_mat,TimeStats.LOSS_BUY_MAT); if(perte_orb > 0.0) money_loss(perte_orb,TimeStats.LOSS_BUY_ORB); if(perte_other > 0.0) money_loss(perte_other,TimeStats.LOSS_BUY_OTHER); clean_list(inventory); if(disp) Game.MW.addLog(String.format(Local.BUYING_OBJECTS,buyStr,shop.name,total_prix)); } public void money_gain(double gain, int type_gain) { t_stats.addRevenue(gain, type_gain); money += gain; } public void money_loss(double loss, int type_loss) { t_stats.addRevenue(loss, type_loss); money -= loss; if (money < 0) money = 0.0; } public void sell(ArrayList<Item> slist) { int nbitem = slist.size(); if(nbitem == 0) return; get_shop(); double gain_base = 0.0; double gain_magique = 0.0; double gain_rare = 0.0; double gain_mat = 0.0; double gain_other = 0.0; double gain_total = 0.0; boolean equiped = false; String sellStr = ""; if(nbitem < 10) { for(Item the_object : slist) { if(sellStr != "") sellStr += ", "; sellStr += NameGenerator.firstCharLowercase(the_object.name); } } else { sellStr = String.format(Local.N_OBJECTS,nbitem); } for(Item the_object : slist) { double prix = prix_vente(the_object); //inventory.remove(the_object); charge -= the_object.poids_final(this); if(the_object.equiped) {equiped = true; the_object.equiped = false;} //shop.inventory.add(the_object); if(the_object.rare == 0) gain_base += prix; else if(the_object.rare == 1) gain_magique += prix; else if(the_object.rare == 2) gain_rare += prix; else if(the_object.rare == 4 || the_object.rare == 5) gain_mat += prix; else gain_other += prix; gain_total += prix; } inventory.removeAll(slist); shop.inventory.addAll(slist); if(equiped) refresh_stats_with_bonus(); if(gain_base > 0.0) money_gain(gain_base,TimeStats.GAIN_SELL_BASE); if(gain_magique > 0.0) money_gain(gain_magique,TimeStats.GAIN_SELL_MAGIC); if(gain_rare > 0.0) money_gain(gain_rare,TimeStats.GAIN_SELL_RARE); if(gain_mat > 0.0) money_gain(gain_mat,TimeStats.GAIN_SELL_MAT); if(gain_other > 0.0) money_gain(gain_other,TimeStats.GAIN_SELL_OTHER); if(disp) Game.MW.addLog(String.format(Local.SELLING_OBJECTS,sellStr,shop.name,gain_total)); if (charge<0.0) charge = 0.0; } public void sell(Item it) { ArrayList<Item> tmp = new ArrayList<Item>(); tmp.add(it); sell(tmp); } public Item get_similar(ArrayList<Item> inventory, Item i) { for(Item the_object : inventory) if (the_object.name.equals(i.name) && the_object.stackable) return the_object; return null; } public static void clean_list(ArrayList<Item> slist) { try{ ArrayList<Item> slist2; Collections.sort(slist, new Comparator<Item>() {public int compare(Item i1, Item i2) {return i1.name.compareTo(i2.name);}}); Iterator it = slist.iterator(); Item previous = (Item)it.next(); while(it.hasNext()) { Item current = (Item)it.next(); if (current.name.equals(previous.name) && previous.stackable) { previous.add_qty(current.qty); if(current.discount) previous.discount = true; it.remove(); } else { previous = current; } } } catch (Exception e) {System.out.println("clean_list fail");} } private boolean venteAutoCond(Item i) { for (ObjectRule r: rules) if(r.sell_rule && r.IsTrue(this,i,null)) return true; return false; } private boolean achatAutoCond(Item i) { for (ObjectRule r: rules) if(r.buy_rule && r.IsTrue(this,i,null)) return true; return false; } public void venteAuto() { get_shop(); ArrayList<Item> tmplst = new ArrayList<Item>(); for(Item the_object : inventory) if(venteAutoCond(the_object) && !the_object.equiped) tmplst.add(the_object); sell(tmplst); } public void achatAuto() { get_shop(); ArrayList<Item> tmplst = new ArrayList<Item>(); for(Item the_object : shop.inventory) if(achatAutoCond(the_object)) tmplst.add(the_object); buy(tmplst); } public void craftAuto() { // Vide l'inventaire de la forge int crs = craftInventory.size(); for(int i=0; i< crs; i++) get_craft(craftInventory.get(0)); clean_list(inventory); // Sélectionne les règles de craft ArrayList<ObjectRule> crrules = new ArrayList<ObjectRule> (); for (ObjectRule r: rules) if(r.meta_type == ObjectRule.CRAFT_RULE) crrules.add(r); while(!crrules.isEmpty()) for (ObjectRule r: crrules) { boolean rule_fail = false; ArrayList<Item> crlist = new ArrayList<Item> (); for (ObjectRule r2: r.ruleList) { // On peut avoir une règle sur le joueur pour une formule de craft // Elle doit être vraie pour que la règle s'applique if (r2.meta_type == ObjectRule.PLAYER_RULE) { rule_fail = r2.IsTrue(this,null,null) ; break; } boolean item_found = false; // Un objet ne peut pas être équipé for(Item the_object : inventory) if(the_object.equiped == false && r2.IsTrue(this,the_object,null) && !crlist.contains(the_object)) { item_found = true; crlist.add(the_object); break; } if(item_found == false) {rule_fail = true; break;} } /*System.out.println("rule "+ r.name + "(fail="+ rule_fail +") crrules="+crrules.size()); for(Item the_object : crlist) System.out.println(the_object.name);*/ if(!rule_fail) { //System.out.println("rule "+ r.name); /*for(Item the_object : crlist) System.out.println(the_object.name + "(" + the_object.nb_ench() +")");*/ put_craft(crlist); craft(); crs = craftInventory.size(); if(craftInventory.size() == crlist.size()) rule_fail = true; //or(Item the_object : craftInventory) // if(the_object.nb_ench() > 0) System.out.println(the_object.name + "(" + the_object.nb_ench() +")"); for(int i=0; i< crs; i++) get_craft(craftInventory.get(0)); } if(rule_fail) {crrules.remove(r); break;} } } public void put_craft(ArrayList<Item> slist) { int nbitem = slist.size(); String putStr = ""; boolean equiped=false; if(nbitem < 10) { for(Item the_object : slist) { if(putStr != "") putStr += ", "; putStr += NameGenerator.firstCharLowercase(the_object.name); } } else { putStr = String.format(Local.N_OBJECTS,nbitem); } for(Item the_object : slist) { charge -= the_object.poids_final(this); if(the_object.equiped) {equiped = true; the_object.equiped = false;} } inventory.removeAll(slist); craftInventory.addAll(slist); clean_list(craftInventory); if(equiped) refresh_stats_with_bonus(); if(disp) Game.MW.addLog(String.format(Local.DROPPING_OBJECTS,name,putStr)); if (charge<0.0) charge = 0.0; } public void put_craft(Item b) { deposit_item(b,craftInventory); if(disp) Game.MW.addLog(String.format(Local.DROPPING_OBJECTS,name,b.name)); } public void destroy_item(Item b) { inventory.remove(b); charge -= b.poids_final(this); if(b.equiped) refresh_stats_with_bonus(); if(disp) Game.MW.addLog(String.format(Local.THROW_AWAY_OBJECTS,name,b.name)); } public void invToConsole() { System.out.print("("); for(Item the_object : inventory) System.out.print(the_object.name + " "); System.out.println(")"); } public void get_item(Item b) { Item tmp; b.equiped = false; if(b.stackable) // Ressource { tmp = get_similar(inventory,b); if(tmp != null) tmp.add_qty(b.qty); else inventory.add(b); } else // Autres objets inventory.add(b); charge += b.poids_final(this); } public void deposit_item(Item b, ArrayList<Item> dest) { inventory.remove(b); charge -= b.poids_final(this); if(b.equiped) refresh_stats_with_bonus(); Item tmp; b.equiped = false; if(b.stackable) // Ressource { tmp = get_similar(dest,b); if(tmp != null) tmp.add_qty(b.qty); else dest.add(b); } else // Autres objets dest.add(b); } public void get_craft(Item b) { craftInventory.remove(b); get_item(b); if(disp) Game.MW.addLog(String.format(Local.PICKING_OBJECTS,name,b.name)); } public void refresh_stats_with_bonus() { for(int i=0; i<nb_stats; i++) { item_bonus[i]=0; if (stats[i] != stats[i]) stats[i] = 0.0; // NaN != NaN stats_with_bonus[i]=stats[i]; } for(Item the_object : inventory) { if(the_object.equiped) for(int i=0; i < nb_stats; i++) { stats_with_bonus[i]+=the_object.bonus(i); item_bonus[i]+=the_object.bonus(i); } } if(current_class >=0) { ClassRPG cls = universe.classList.get(current_class); for(int i=0; i< nb_stats; i++) { if (cls.bonus[i] == 1) stats_with_bonus[i] = (stats_with_bonus[i] + universe.class_bonus_add()) * universe.class_bonus_mult(); if (cls.malus[i] == 1) stats_with_bonus[i] = stats_with_bonus[i] * universe.class_malus_mult(); } } refresh_charge(); vie=vie_max(); } public String short_infos() { String res = String.format(Local.SHORT_INFOS, level,temps_total,money,charge,charge_max()); return res; } public String infos() { double dmpa = dmpa(); double levListShort[] = {1,3,5,10}; double levList[] = {universe.get_zone_level(zone), universe.get_zone_max_level(zone),level,level*0.75}; Arrays.sort(levList); if (level < 10) levList = levListShort; double lvl0=Math.floor(levList[0]); double lvl1=Math.floor(levList[1]); double lvl2=Math.floor(levList[2]); double lvl3=Math.floor(levList[3]); if(lvl3==lvl2) lvl3*=1.25; return String.format(Local.PLAYER_INFOS, att_per_sec(),dmg_base(),100.0*crit_proba(),multi_crit(), dmpa,att_per_sec()*dmpa, ed_versus_tag(0),ed_versus_tag(1),ed_versus_tag(2),ed_versus_tag(3),ed_versus_tag(4),ed_versus_tag(5), lvl1,100.0-universe.esquive_proba(universe.monster_points_for_level(lvl1)*Monster.coeff_std[4]*0.5,PRC())*100.0, lvl2,100.0-universe.esquive_proba(universe.monster_points_for_level(lvl2)*Monster.coeff_std[4]*0.5,PRC())*100.0, lvl3,100.0-universe.esquive_proba(universe.monster_points_for_level(lvl3)*Monster.coeff_std[4]*0.5,PRC())*100.0, lvl1,universe.esquive_proba(ESQ(),universe.monster_points_for_level(lvl1)*Monster.coeff_std[5]*0.5)*100.0, lvl2,universe.esquive_proba(ESQ(),universe.monster_points_for_level(lvl2)*Monster.coeff_std[5]*0.5)*100.0, lvl3,universe.esquive_proba(ESQ(),universe.monster_points_for_level(lvl3)*Monster.coeff_std[5]*0.5)*100.0, 100.0-(100.0*reduc()),bonus_resistance_vs_piege(),100.0-(100.0*resistance_vs_piege()),absorption(), pv_per_vita(),vie_max(),vie_max()/reduc(), regen(),vie_max()/regen(),100*vol_de_vie(), initiative(),bonus_initiative_piege(),initiative_piege(), temps_traque(),temps_shop(),temps_forge(), temps_res(),charge_max(),coeff_vente(),coeff_achat(),100*chance_fuite(),temps_fuite(), chance_magique()*100,chance_magique()*chance_rare()*100,chance_qualite()*100,multiplicateur_or(), multiplicateur_res(),quantite_drop(), quantite_drop()*universe.proba_ressource(), // Nombre de ressources quantite_drop()*(1-universe.proba_ressource()), // Nombre d'objets hors ressources quantite_drop()*universe.proba_ressource()*multiplicateur_res()*universe.quantite_ressource_base_drops(), // Quantité totale de ressources quantite_drop()*(1-universe.proba_ressource())*chance_magique(), // Nombre d'objets magiques quantite_drop()*(1-universe.proba_ressource())*chance_magique()*chance_rare(), // Nombre d'objets rares puissance_ench_inf(), puissance_ench_sup(), 100.0*proba_immunite_final(), facteur_temps(),epines(), 100*represailles(), 100*necrophagie(), temps_craft(),100*rendement(),100*economie_orbe(), multiplicateur_niveau_boutique(),niveau_boutique_base()*multiplicateur_niveau_boutique(), taille_boutique(), lvl1,100.0*proba_trouver_piege(lvl1), lvl2,100.0*proba_trouver_piege(lvl2), lvl3,100.0*proba_trouver_piege(lvl3), rente_par_rencontre(),points_par_niveau(), 100.0*(bonus_xp()-1), lvl0,100.0*modif_exp_lvl(lvl0-level)-100.0, lvl1,100.0*modif_exp_lvl(lvl1-level)-100.0, lvl2,100.0*modif_exp_lvl(lvl2-level)-100.0, lvl3,100.0*modif_exp_lvl(lvl3-level)-100.0, 100*(1.0-penalty_reduction()), max_zone_level(), universe.points_divins_multiplier(DIEU()), multi_premier_coup(), divine_cap_eq(),divine_cap_const(), resources_weight_multiplier(),equipment_weight_multiplier(), cold_resistance(), heat_resistance(), precipitation_resistance(), overload_resistance(), 100*(1-cold_penalty()), 100*(1-heat_penalty()), 100*(1-precipitation_penalty()), 100*(1-overload_penalty()), cold_affinity(), heat_affinity(), precipitation_affinity(), underload_affinity(),achievements_affinity(),bonus_vacances(), 100*(cold_bonus()-1.0), 100*(heat_bonus()-1.0), 100*(precipitation_bonus()-1.0), 100*(underload_bonus()-1.0),100*(bonus_haut_faits()-1.0), clearance_sale_inventory_multiplier(),discount_multiplier(), points_de_competence_cosmique(), multiplicateur_points_cosmiques(), 100*universe.qualite_max_drop(points_cosmiques_totaux()), 100*universe.qualite_max_craft(points_cosmiques_totaux()) ); } public double dmpa() {return dmg_base() + dmg_base()*(multi_crit()-1.0)*crit_proba();} public double IAS() {return stats_with_bonus[Universe.IAS]*cold_bonus();} public double DMG() {return stats_with_bonus[Universe.DMG];} public double REDUC() {return stats_with_bonus[Universe.REDUC]*heat_bonus();} public double ABS() {return stats_with_bonus[Universe.ABS];} public double ESQ() {return stats_with_bonus[Universe.ESQ]*precipitation_bonus();} public double PRC() {return stats_with_bonus[Universe.PRC]*precipitation_penalty();} public double LCK() {return stats_with_bonus[Universe.LCK]*precipitation_penalty();} public double CRT() {return stats_with_bonus[Universe.CRT];} public double VDV() {return stats_with_bonus[Universe.VDV];} public double VITA() {return stats_with_bonus[Universe.VITA]*cold_penalty();} public double CON() {return stats_with_bonus[Universe.CON]*cold_penalty();} public double REGEN() {return stats_with_bonus[Universe.REGEN];} public double RESUR() {return stats_with_bonus[Universe.RESUR]*heat_bonus();} public double LOAD() {return stats_with_bonus[Universe.LOAD];} public double RUN() {return stats_with_bonus[Universe.RUN]*overload_penalty();} public double RESF() {return stats_with_bonus[Universe.RESF]*underload_bonus();} public double MF() {return stats_with_bonus[Universe.MF];} public double RF() {return stats_with_bonus[Universe.RF];} public double QALF() {return stats_with_bonus[Universe.QALF];} public double QTYF() {return stats_with_bonus[Universe.QTYF];} public double POWF() {return stats_with_bonus[Universe.POWF];} public double GF() {return stats_with_bonus[Universe.GF]*bonus_haut_faits();} public double ED_MV() {return stats_with_bonus[Universe.ED_MV];} public double ED_ANI() {return stats_with_bonus[Universe.ED_ANI];} public double ED_HUM() {return stats_with_bonus[Universe.ED_HUM];} public double ED_PV() {return stats_with_bonus[Universe.ED_PV];} public double ED_DEM() {return stats_with_bonus[Universe.ED_DEM];} public double ED_CHAMP() {return stats_with_bonus[Universe.ED_CHAMP];} public double ESTI() {return stats_with_bonus[Universe.ESTI];} public double FLEE() {return stats_with_bonus[Universe.FLEE];} public double FLEE_SPD() {return stats_with_bonus[Universe.FLEE_SPD];} public double INIT() {return stats_with_bonus[Universe.INIT]*overload_penalty();} public double IMUN_FINAL() {return stats_with_bonus[Universe.IMUN_FINAL]*precipitation_bonus();} public double TIME_SPD() {return stats_with_bonus[Universe.TIME_SPD]*cold_bonus();} public double EPIN() {return stats_with_bonus[Universe.EPIN];} public double REP() {return stats_with_bonus[Universe.REP];} public double NECRO() {return stats_with_bonus[Universe.NECRO];} public double CRAFT_SPD() {return stats_with_bonus[Universe.CRAFT_SPD];} public double CRAFT_REND() {return stats_with_bonus[Universe.CRAFT_REND];} public double ECO_ORB() {return stats_with_bonus[Universe.ECO_ORB];} public double SHOP_LEVEL() {return stats_with_bonus[Universe.SHOP_LEVEL];} public double SHOP_SIZE() {return stats_with_bonus[Universe.SHOP_SIZE];} public double TRAP_DET() {return stats_with_bonus[Universe.TRAP_DET];} public double TRAP_INIT() {return stats_with_bonus[Universe.TRAP_INIT];} public double TRAP_RES() {return stats_with_bonus[Universe.TRAP_RES];} public double RENTE() {return stats_with_bonus[Universe.RENTE]*bonus_haut_faits();} public double EDUC() {return stats_with_bonus[Universe.EDUC];} public double BONUS_XP() {return stats_with_bonus[Universe.BONUS_XP]*heat_penalty();} public double BONUS_LOWLEV() {return stats_with_bonus[Universe.BONUS_LOWLEV];} public double BONUS_HLEV() {return stats_with_bonus[Universe.BONUS_HLEV];} public double REDUC_PEN() {return stats_with_bonus[Universe.REDUC_PEN];} public double ZONE_ACCESS() {return stats_with_bonus[Universe.ZONE_ACCESS];} public double DIEU() {return stats_with_bonus[Universe.DIEU];} public double FIRST_STRIKE() {return stats_with_bonus[Universe.FIRST_STRIKE];} public double EQ_MASTER() {return stats_with_bonus[Universe.EQ_MASTER];} public double CONST_MASTER() {return stats_with_bonus[Universe.CONST_MASTER];} public double LIGHTER_RES() {return stats_with_bonus[Universe.LIGHTER_RES];} public double LIGHTER_EQP() {return stats_with_bonus[Universe.LIGHTER_EQP];} public double COLD_RES() {return stats_with_bonus[Universe.COLD_RES];} public double HOT_RES() {return stats_with_bonus[Universe.HOT_RES];} public double PRECI_RES() {return stats_with_bonus[Universe.PRECI_RES];} public double COLD_BONUS() {return stats_with_bonus[Universe.COLD_BONUS];} public double HOT_BONUS() {return stats_with_bonus[Universe.HOT_BONUS];} public double PRECI_BONUS() {return stats_with_bonus[Universe.PRECI_BONUS];} public double OVERLOAD_RES() {return stats_with_bonus[Universe.OVERLOAD_RES];} public double UNDERLOAD_BONUS() {return stats_with_bonus[Universe.UNDERLOAD_BONUS];} public double ACHI_BONUS() {return stats_with_bonus[Universe.ACHI_BONUS];} public double HOLIDAY_BONUS() {return stats_with_bonus[Universe.HOLIDAY_BONUS];} public double SHOPPING_ADDICT() {return stats_with_bonus[Universe.SHOPPING_ADDICT];} public double DISCOUNT_SPEC() {return stats_with_bonus[Universe.DISCOUNT_SPEC];} public double COSMO_ADD() {return stats_with_bonus[Universe.COSMO_ADD];} public double COSMO_MUL() {return stats_with_bonus[Universe.COSMO_MUL];} public double total_skill_points() { double res=0; for(int i=0; i<nb_stats; i++) res+=stats_with_bonus[i]; return res+points_a_distribuer(); } public double proba_rencontrer_piege() {return universe.proba_rencontrer_piege()*universe.map.trap_coeff.get(zone);} public double vie() {return vie;} public double vie_max() {return universe.vie_max(VITA(),CON());} public double att_per_sec() {return universe.att_per_sec(IAS());} public double pv_per_vita() {return universe.pv_per_vita(CON());} public double crit_proba() {return universe.crit_proba(LCK());} public double multi_crit() {return universe.multi_crit(CRT());} public double dmg_base() {return universe.dmg_base(DMG());} public double reduc() {return universe.reduc(REDUC());} public double absorption() {return universe.absorption(ABS());} public double vol_de_vie() {return universe.vol_de_vie(VDV());} public double regen() {return universe.regen(REGEN());} public double charge_max() {if(Game.DEBUG_MODE_MAX_LOAD) return 10000000; else return universe.charge_max(LOAD());} public double temps_traque() {return universe.temps_traque(RUN());} public double temps_shop() {return universe.temps_shop(RUN());} public double temps_forge() {return universe.temps_forge(RUN());} public double temps_res() {return universe.temps_res(RESUR());} public double coeff_achat() {return universe.coeff_achat(ESTI());} public double coeff_vente() {return universe.coeff_vente(ESTI());} public double multiplicateur_res() {return universe.multiplicateur_res(RESF());} public double chance_magique() {return universe.chance_magique(MF());} public double chance_rare() {return universe.chance_rare(RF());} public double chance_qualite() {return universe.chance_qualite(QALF());} public double quantite_drop() {return universe.quantite_drop(QTYF());} public double multiplicateur_or() {return universe.multiplicateur_or(GF());} public double puissance_ench_inf() {return universe.puissance_ench_inf(POWF());} public double puissance_ench_sup() {return universe.puissance_ench_sup();} public double ed_versus_tag(int tag) {return universe.ed_specific_monster(stats_with_bonus[22+tag],tag);} public double chance_fuite() {return universe.chance_fuite(FLEE());} public double temps_fuite() {return universe.temps_fuite(FLEE_SPD());} public double temps_craft() {return universe.temps_craft(CRAFT_SPD());} public double initiative() {return universe.initiative(INIT());} public double proba_immunite_final() {return universe.proba_immunite_final(IMUN_FINAL());} public double facteur_temps() {return universe.facteur_temps(TIME_SPD());} public double epines() {return universe.epines(EPIN());} public double represailles() {return universe.represailles(REP());} public double necrophagie() {return universe.necrophagie(NECRO());} public double rendement() {return universe.rendement(CRAFT_REND());} public double economie_orbe() {return universe.economie_orbe(ECO_ORB());} public double multiplicateur_niveau_boutique() {return universe.multiplicateur_niveau_boutique(SHOP_LEVEL());} public double taille_boutique() {return universe.taille_boutique(SHOP_SIZE());} public double detection_piege() {return universe.detection_piege(TRAP_DET());} public double bonus_initiative_piege() {return universe.bonus_initiative_piege(TRAP_INIT());} public double initiative_piege() {return universe.initiative(INIT()*universe.bonus_initiative_piege(TRAP_INIT()));} public double bonus_resistance_vs_piege() {return universe.bonus_resistance_vs_piege(TRAP_RES());} public double resistance_vs_piege() {return universe.reduc(REDUC()*universe.bonus_resistance_vs_piege(TRAP_RES()));} public double rente_par_rencontre() {return universe.rente_par_rencontre(RENTE());} public double points_par_niveau() {return universe.points_par_niveau(EDUC());} public double points_totaux() {return points_par_niveau()*level + universe.points_initiaux() + universe.points_competence_orbes(orbes_investits_en_points_competence);} public double points_a_distribuer() {return points_totaux()-points_distribues();} public double points_divins_a_distribuer() {return points_divins_totaux()-points_divins_distribues();} public double bonus_xp() {return universe.bonus_xp(BONUS_XP());} public double modif_exp_lvl(double levdiff) {return universe.modif_exp_lvl(BONUS_LOWLEV(), BONUS_HLEV(), levdiff);} public double proba_trouver_piege(double hidden_lvl) {return universe.proba_trouver_piege(TRAP_DET(), hidden_lvl);} public double penalty_reduction() {return universe.penalty_reduction(REDUC_PEN());} public double max_zone_level() {return level*universe.zone_multiplier(ZONE_ACCESS());} public double points_divins_totaux() {return universe.points_divins_totaux(DIEU(),orbes_investits_en_points_divins,level);} public double penalty_for_bad_material() {return -penalty_reduction()*universe.penalty_for_bad_material();} public double multi_premier_coup() {return universe.multi_premier_coup(FIRST_STRIKE());} public double divine_cap_eq() {return universe.divine_cap_eq(EQ_MASTER());} public double divine_cap_const() {return universe.divine_cap_const(CONST_MASTER());} public double resources_weight_multiplier() {return universe.resources_weight_multiplier(LIGHTER_RES());} public double equipment_weight_multiplier() {return universe.equipment_weight_multiplier(LIGHTER_EQP());} public double cold_resistance() {return universe.resistance_froid(COLD_RES());} public double heat_resistance() {return universe.resistance_chaud(HOT_RES());} public double precipitation_resistance() {return universe.resistance_precipitations(PRECI_RES());} public double cold_affinity() {return universe.affinite_froid(COLD_BONUS());} public double heat_affinity() {return universe.affinite_chaud(HOT_BONUS());} public double precipitation_affinity() {return universe.affinite_precipitations(PRECI_BONUS());} public double overload_resistance() {return universe.resistance_surcharge(OVERLOAD_RES());} public double underload_affinity() {return universe.affinite_souscharge(UNDERLOAD_BONUS());} public double achievements_affinity() {return universe.affinite_hautfaits(ACHI_BONUS());} public double clearance_sale_inventory_multiplier() {return universe.clearance_sale_inventory_multiplier(SHOPPING_ADDICT());} public double discount_multiplier() {return universe.discount_multiplier(DISCOUNT_SPEC());} public double bonus_haut_faits() {return universe.bonus_haut_faits_base(points_haut_faits*achievements_affinity());} public double bonus_vacances() {return universe.affinite_vacances(HOLIDAY_BONUS());} public double points_de_competence_cosmique() {return universe.cosmologie_additive(COSMO_ADD());} public double multiplicateur_points_cosmiques() {return universe.cosmologie_multiplicative(COSMO_MUL());} public double divine_cap(int i){ if(i < universe.nb_universe_stats) return universe.divine_cap[i] * universe.divine_cap_const(CONST_MASTER()); else return universe.divine_cap[i] * universe.divine_cap_eq(EQ_MASTER()); } public void auto_dist() { double sum = 0.0; for(int i=0; i<nb_stats; i++) {sum += auto_dist_coeff[i];} if (sum<=0.0001) return; double toAdd = points_a_distribuer(); for(int i=0; i<nb_stats; i++) { stats[i] += Math.floor(toAdd*auto_dist_coeff[i]/sum); } refresh_stats_with_bonus(); } public double niveau_boutique_base() { if(zone >= 2) return universe.get_zone_max_level(zone)*universe.niveau_boutique_pour_niveau_zone(); else return 50*(zone+1); // Marchands peu puissants dans les arènes } public void auto_equip() { ArrayList<ArrayList<Item>> ai = new ArrayList<ArrayList<Item>>(); for (int i=0; i< StaticItem.nb_pos-1; i++) { ai.add(new ArrayList<Item>()); } for (Item it: inventory) { if(it.pos < StaticItem.nb_pos-1) { it.equiped = false; ai.get(it.pos).add(it); } } for (int i=0; i< StaticItem.nb_pos-1; i++) { if(ai.get(i).size() > 0) { Collections.sort(ai.get(i), new ComparateurStats()); ai.get(i).get(0).equiped = true; } } } public void personal_wait(double time_w, int ACT) { try { if (Game.MW != null) Game.MW.mustRefreshCurves = true; double adjusted_time = time_w/facteur_temps(); temps_total += adjusted_time; t_stats.addActivity(adjusted_time,ACT); if(Game.REAL_TIME) Thread.currentThread().sleep((int)(adjusted_time*1000)); } catch (Exception e) { } //Game.MW.refreshInFight(); } public void addOptimizedRules() { ObjectRule tmp; ObjectRule fus = new ObjectRule(17,0,4,ObjectRule.ITEM_RULE); fus.name = "Orbe de fusion"; rules.add(fus); for (int i=3; i< 62 ; i++) { tmp = new ObjectRule(20,0,i,ObjectRule.ITEM_RULE); tmp.name = "Nombre d'enchantements "+i; ArrayList<ObjectRule> lvlR = new ArrayList<ObjectRule>(); lvlR.add(tmp); lvlR.add(tmp); lvlR.add(fus); ObjectRule tmp2 = new ObjectRule(lvlR,0); tmp2.meta_type = ObjectRule.CRAFT_RULE; tmp2.name = "Fusion "+i; rules.add(tmp); rules.add(tmp2); } } public void addDefaultRules() { // Inventory filter rules ObjectRule tmp; tmp = new ObjectRule(4,2,0.0,ObjectRule.ITEM_RULE); tmp.name = Local.ALL; tmp.filter_rule = true; tmp.pickup_rule = true; tmp.system_rule = true; rules.add(tmp); tmp = new ObjectRule(18,0,1,ObjectRule.ITEM_RULE); tmp.name = Local.EQUIPPED; tmp.filter_rule = true; rules.add(tmp); tmp = new ObjectRule(tmp, false); tmp.name = Local.NOT_EQUIPPED; tmp.filter_rule = true; rules.add(tmp); // Monster rules tmp = new ObjectRule(0,2,5,ObjectRule.MONSTER_RULE); //tmp.avoid_rule = true; tmp.name = Local.MONSTER_TOO_STRONG; rules.add(tmp); tmp = new ObjectRule(0,1,1,ObjectRule.MONSTER_RULE); tmp.avoid_rule = true; tmp.name = Local.MONSTER_TOO_WEAK; rules.add(tmp); // Shopping and sell rules /* tmp = new ObjectRule(2,1,2,ObjectRule.PLAYER_RULE); tmp.shopping_rule = true; tmp.name = "Inventaire plein"; rules.add(tmp);*/ /* tmp = new ObjectRule(1,0,0,ObjectRule.ITEM_RULE); tmp.sell_rule = true; tmp.name = "Vente des déchets"; rules.add(tmp);*/ for (int i=0; i< StaticItem.nb_pos-1 ; i++) { tmp = new ObjectRule(2,0,i,ObjectRule.ITEM_RULE); tmp.name = Local.SLOT_NAME[i]; tmp.filter_rule = universe.slot_est_disponible(i); rules.add(tmp); } for (int i=0; i< Local.RARITY_NAME.length ; i++) { tmp = new ObjectRule(0,0,i,ObjectRule.ITEM_RULE); String name = Local.RARITY_NAME[i]; tmp.name = name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase(); tmp.filter_rule = true; rules.add(tmp); } //addOptimizedRules(); } public Player() {} public Player(Universe u, boolean light) { universe = u; if(!light) { disp=true; orbes_investits_en_xp = 0; orbes_investits_en_points_divins = 0; orbes_investits_en_points_competence = 0; orbes_investits_en_points_cosmiques = 0; or_perdu_en_trou_noirs = 0; nombre_trous_noirs = 0; temps_total = 0; t_stats = new TimeStats(); conditionToggle = new boolean[]{true,true,true,true,true}; conditionValues = new int[]{1,1,1,1,1}; shop = null; mob = null; craftInventory = new ArrayList<Item>(); inventory = new ArrayList<Item>(); rules = new ArrayList<ObjectRule>(); addDefaultRules(); zone = 2; level = 1; xp_pt = 0; refresh_weather_penalties(); tags = new boolean[nb_tags]; for(int t=0; t<nb_tags; t++) tags[t]=false; tags[2]=true; // Humain name = "Mortadelle"; stats = new double[nb_stats]; stats_with_bonus = new double[nb_stats]; item_bonus = new double[nb_stats]; auto_dist_coeff = new int[nb_stats]; for(int i=0; i<nb_stats; i++) {stats[i]=0; stats_with_bonus[i]=0; item_bonus[i]=0; auto_dist_coeff[i]=10;} refresh(); } else { shop = null; mob = null; defi = null; } } public String short_stats() { String res = String.format("%s\n",name); res += String.format(Local.LEVEL_N,level); for(int i=0; i<dsp_target.length; i++) { double bonus = stats_with_bonus[dsp_target[i]]; if(bonus > 0.01) res += String.format("%s"+ Local.COLON + " %g\n",stats_name[dsp_target[i]],bonus); } return res; } // Utilisé si DEBUG public void giveStuff() { Item it = new Item(300,this,Item.ITEM_SHOP); for (int i=1;i<500;i+=1) { it = new Item(i,this,Item.ITEM_DROP); if(it.stackable) it.set_qty(1.0e20); inventory.add(it); } for(int j=0; j<StaticItem.ORB.length; j++) { it = new Item(StaticItem.ORB[j],StaticItem.RESSOURCE_ORB); it.set_qty(1.0e20); inventory.add(it); } boolean[] posTaken = new boolean[StaticItem.nb_pos]; for(int i=0; i< StaticItem.nb_pos-1; i++) if (universe.slot_est_disponible(i)==false) posTaken[i] = true; posTaken[StaticItem.nb_pos-1]=true; for(int j=0; j<20; j++) { for(int tr=0; tr<20; tr++) { it = new Item(300,this,Item.ITEM_SHOP); if(posTaken[it.pos]==false) break; } posTaken[it.pos]=true; if (it.rare == 0) { it.elvl = 300; it.transform_magic(this); it.material = StaticItem.MA[100]; it.rare = 3; for(int i=0; i<Player.nb_stats; i++) { it.bonus[i]=puissance_ench_sup()*it.elvl; } it.quality = 10.0; it.update(); inventory.add(it); } } refresh_charge(); } public void update_encounters() { double tt = universe.plage_random()*temps_traque(); if(disp) Game.MW.addLog(String.format(Local.LOOKING_FOR_AN_ENNEMY,tt)); personal_wait(tt,TimeStats.ACTIVITY_CHERCHE_ENNEMI); shop = null; nb_encounters++; if(nb_encounters%20 == 1 ) update_weather(); if(nb_encounters%50 == 49 ) update_rente(); } public void update_rente() { double rente_par_rencontre = rente_par_rencontre(); double fric = rente_par_rencontre*50; if (fric > 0.01) { money_gain(fric, TimeStats.GAIN_RENTE); if(disp) Game.MW.addLog(String.format(Local.LIFE_ANNUITY,name,fric,50.0,rente_par_rencontre)); } } public void update_weather() { String zone_name = universe.map.zonesName.get(zone); double precipitation = universe.get_precipitation(zone); double current_precipitation = universe.get_current_precipitation(zone); double current_precipitation_modifier = universe.map.current_precipitation_modifier.get(zone); double temperature = universe.get_temperature(zone); double current_temperature = universe.get_current_temperature(zone); double current_temperature_modifier = universe.map.current_temperature_modifier.get(zone); double mdiff, tdiff, new_temperature; if(Math.abs(precipitation)<0.001) { precipitation_strength = 0.0; mdiff = 0.4*Math.random()-0.20; universe.map.current_temperature_modifier.set(zone,current_temperature_modifier+mdiff); new_temperature = universe.get_current_temperature(zone); tdiff = new_temperature - current_temperature; if(disp) { if(tdiff > 0) Game.MW.addLog(String.format(Local.NO_PRECIPITATIONS, zone_name, 100.0, tdiff, new_temperature)); else Game.MW.addLog(String.format(Local.NO_PRECIPITATIONS_NEG, zone_name, 100.0, -tdiff, new_temperature)); } } else if(Math.random()< current_precipitation) { String type=""; mdiff = 1.0*Math.random()+0.5; universe.map.current_precipitation_modifier.set(zone,current_precipitation_modifier-mdiff); universe.map.current_temperature_modifier.set(zone,current_temperature_modifier-mdiff); new_temperature = universe.get_current_temperature(zone); tdiff = new_temperature - current_temperature; if(temperature <=0.0 && Math.random() < 0.5) { precipitation_strength = 2.0+1.0*Math.random(); type = Local.SNOW; } else if (temperature <=0.0) { precipitation_strength = 2.0+2.0*Math.random(); type = Local.HAIL; } else { precipitation_strength = 1.0+0.5*Math.random(); type = Local.RAIN; } if(disp) Game.MW.addLog(String.format(type, zone_name,precipitation_strength, 100*current_precipitation, -tdiff, new_temperature)); } else { precipitation_strength = 0.0; mdiff = 1.0*Math.random()+0.5; universe.map.current_precipitation_modifier.set(zone,current_precipitation_modifier+mdiff); universe.map.current_temperature_modifier.set(zone,current_temperature_modifier+mdiff); new_temperature = universe.get_current_temperature(zone); tdiff = new_temperature - current_temperature; if(disp) Game.MW.addLog(String.format(Local.NO_PRECIPITATIONS, zone_name, 100-100*current_precipitation, tdiff, new_temperature)); } /*System.out.println("Start: temperature_modifier="+current_temperature_modifier+" precipitation_modifier="+current_precipitation_modifier); System.out.println("current_temperature="+current_temperature); System.out.println("mdiff="+mdiff +" new_temperature="+new_temperature); System.out.println("new_temperature_modifier="+universe.map.current_temperature_modifier.get(zone));*/ refresh_weather_penalties(); } public double get_mob_level() { double zl = universe.get_zone_level(zone); double diff = universe.get_zone_max_level(zone)-zl+1; double zlevel = zl + Math.floor(Math.random() * diff); return zlevel; } // rencontre aléatoire // peut être précédée par un piège public void get_mob() { double mob_level = get_mob_level(); t_stats.addEvent(1.0,TimeStats.EVENT_FIND_MONSTER); mob = new Monster(mob_level,universe,zone); } // trouver un marchand public void get_shop() { if(shop == null) { double ts = temps_shop(); double tt = universe.plage_random()*ts; if(disp) Game.MW.addLog(String.format(Local.LOOKING_FOR_A_SELLER,tt)); t_stats.addEvent(1.0,TimeStats.EVENT_FIND_SHOP); personal_wait(tt,TimeStats.ACTIVITY_CHERCHE_MARCHAND); shop = new Shop(this); if(disp) Game.MW.addLog(String.format(Local.ENCOUNTER,name,shop.name,shop.level)); } } // trouver une forge public void get_forge() { double tt = universe.plage_random()*temps_forge(); if(disp) Game.MW.addLog(String.format(Local.LOOKING_FOR_A_MYSTIC_FORGE,tt)); t_stats.addEvent(1.0,TimeStats.EVENT_FIND_FORGE); personal_wait(tt,TimeStats.ACTIVITY_CHERCHE_FORGE); } public String cogne(Player p, boolean addStat) { double t_att = universe.plage_random() * (1.0/att_per_sec()); // Durée de l'attaque temps += t_att; String res = String.format(Local.A_HITS_B,this.name,p.name,t_att,this.name,temps); double esquive, critique, multiplicateur1, multiplicateur2, percant; double dmg, dmg_base, dmg_abs, dmg_red; double dmg_base2, dmg_red2; double tmp; esquive = universe.esquive_proba(p.ESQ(),PRC()); if (Math.random() < esquive) { res+=String.format(Local.DODGES_THE_HIT,p.name,this.name,100.0*esquive); } else { if(addStat) t_stats.addEvent(1.0,TimeStats.EVENT_ATTACK_SUCCESS); multiplicateur1 = 1.0; multiplicateur2 = 1.0; String cause = ""; for(int t=0; t<nb_tags; t++) { if (p.tags[t] && (tmp = ed_versus_tag(t)) > 1.001) { multiplicateur1 = multiplicateur1 * tmp; res+=String.format(Local.MULTIPLIER,tmp,TagsName[t]); } } if(p.nb_hits == 0 && (tmp=multi_premier_coup()) > 1.001) { multiplicateur1 = multiplicateur1 * tmp; res+=String.format(Local.MULTIPLIER,tmp,Local.FIRST_STRIKE); } critique = crit_proba(); if (Math.random() < critique) { multiplicateur2 = multi_crit(); res+=String.format(Local.CRITICAL_STRIKE,multiplicateur2,100.0*critique); p.crit_taken++; } dmg_base = universe.plage_random() * dmg_base() * multiplicateur1 * multiplicateur2; dmg_red = p.reduc(); dmg_abs = p.absorption(); dmg = Math.max(dmg_base*dmg_red - dmg_abs,0.0); // pas de dégâts négatifs res+=String.format(Local.DAMAGE_INFLICTED,this.name,dmg,p.name,dmg_base,100*(1.0-dmg_red),dmg_abs); if(dmg >= p.vie && p.vie > 0.1 && Math.random() < (tmp = p.proba_immunite_final())) { res+=String.format(Local.IMMUNITY_TO_FINAL_BLOW, p.name, tmp*100.0); p.vie = 0.1; } else { p.vie -= dmg; } dmg_base2 = p.universe.plage_random() * p.epines(); dmg_red2 = reduc(); if(dmg_base2*dmg_red2 > 0.01) { res+=String.format(Local.THORNS,p.name,dmg_base2*dmg_red2,this.name,dmg_base2,100*(1.0-dmg_red2)); this.vie -= dmg_base2*dmg_red2; } double rep = p.represailles() * dmg; if(rep*dmg_red2 > 0.01) { res+=String.format(Local.REPRISALS,p.name,rep*dmg_red2,this.name,rep,100*(1.0-dmg_red2)); this.vie -= rep*dmg_red2; } double vdv = Math.min(this.vie_max()-this.vie(),dmg*vol_de_vie()); if (vdv > 0.01) { res+=String.format(Local.LIFE_LEECH_EFFECT,this.name,vdv); this.vie += vdv; } p.nb_hits++; } return res; } public void refresh() { vie=vie_max(); temps = 0; } public boolean combat(boolean real) { if(real) t_stats.addEvent(1.0,TimeStats.EVENT_FIGHT_ATTEMPT); boolean has_flee = false; crit_taken = 0; int nb_coup = 0; boolean lost; Player p2 = mob; if(disp) Game.MW.addLog(String.format(Local.A_VERSUS_B, name, p2.name,p2.level)); String tmp; Player t1,t2; double i1,i2; i1 = universe.plage_random()*initiative(); i2 = p2.universe.plage_random()*p2.initiative(); temps += i1; p2.temps += i2; double tmp_temps = temps; if(real) personal_wait(i1,TimeStats.ACTIVITY_INITIATIVE); if (i1<i2) {t1=this; t2=p2;} else {t1=p2; t2=this;} if(disp) Game.MW.addLog(String.format(Local.INITIATIVES,i1,name,i2,p2.name)); t1.nb_hits = t2.nb_hits = 0; while (vie() >0 && p2.vie() >0) { if(nb_coup >= universe.nombre_maximal_coup()) { if(disp) Game.MW.addLog(String.format(Local.MUTUAL_FLEE,nb_coup,name,p2.name)); has_flee = true; break; } if(this == t1 && real && must_flee()) { double t_att = universe.plage_random()*temps_fuite(); // Durée de la fuite temps += t_att; if(real) { personal_wait(t_att,TimeStats.ACTIVITY_FUITE); t_stats.addEvent(1.0,TimeStats.EVENT_FLEE_ATTEMPT); } if(disp) Game.MW.addLog(String.format(Local.TRY_TO_FLEE,name,p2.name,t_att)); if(Math.random() < chance_fuite()) { if(disp) Game.MW.addLog(String.format(Local.FLEE_SUCCESS,100*chance_fuite())); if(real) t_stats.addEvent(1.0,TimeStats.EVENT_FLEE_SUCCESS); has_flee = true; break; } else { if(disp) Game.MW.addLog(String.format(Local.FLEE_FAIL,100-100*chance_fuite())); } } else { tmp = t1.cogne(t2, (real && this == t1)); nb_coup++; if(disp) Game.MW.addLog(tmp); } if(real && this == t1) { personal_wait(temps-tmp_temps,TimeStats.ACTIVITY_COGNE); t_stats.addEvent(1.0,TimeStats.EVENT_ATTACK_ATTEMPT); } tmp_temps = temps; if(temps < p2.temps) {t1=this; t2=p2;} else {t1=p2; t2=this;} } if(vie() >0) // victoire ou fuite { if(has_flee){ if(disp) Game.MW.addLog(String.format(Local.END_FIGHT_FLEE,name,p2.name,temps,vie())); lost = true; } else{ if(disp) Game.MW.addLog(String.format(Local.END_FIGHT_KILL,name,p2.name,temps,vie())); if(real) { t_stats.addEvent(1.0,TimeStats.EVENT_FIGHT_SUCCESS); gain_xp(universe.xp_for_level(p2.level), TimeStats.XP_MONSTER, p2.level); if (zone >= 2) loot((Monster)p2); // NO LOOT IN ARENA } lost = false; } } else { if(disp) Game.MW.addLog(String.format(Local.END_FIGHT_DEATH,name,p2.name,p2.level,temps)); if(real) { t_stats.addEvent(1.0,TimeStats.EVENT_FIGHT_DEATH); meurt(); } lost = true; } temps = 0; return lost; } private boolean pickupCond(Item i) { for (ObjectRule r: rules) { if(r.pickup_rule && r.IsTrue(this,i,mob)) return true; } return false; } public void loot(Monster p2) { ArrayList<Item> loot = p2.drop(this); double fric = universe.plage_random() * universe.gold_drop(p2.level) * multiplicateur_or(); if(fric < 1.0) fric = 0; if (loot.isEmpty() && fric <= 0.1) {if(disp) Game.MW.addLog(String.format(Local.NO_LOOT, p2.name));} else { int initial_size = inventory.size(); money_gain(fric, TimeStats.GAIN_DROP); if(disp) Game.MW.addLog(String.format(Local.GOLD_LOOT,name, fric, p2.name)); String lootStr = ""; String dontLootStr = ""; for(Item the_object : loot) { if(the_object.rare == 0) t_stats.addEvent(1.0,TimeStats.EVENT_DROP_NORMAL); else if(the_object.rare == 1) t_stats.addEvent(1.0,TimeStats.EVENT_DROP_MAGIC); else if(the_object.rare == 2) t_stats.addEvent(1.0,TimeStats.EVENT_DROP_RARE); else if(the_object.rare == 4 || the_object.rare == 5) t_stats.addEvent(the_object.qty,TimeStats.EVENT_DROP_MAT); else if(the_object.rare == 6) t_stats.addEvent(the_object.qty,TimeStats.EVENT_DROP_ORB); if (pickupCond(the_object)) { if(lootStr != "") lootStr += ", "; lootStr += NameGenerator.firstCharLowercase(the_object.name); charge += the_object.poids_final(this); inventory.add(the_object); } else { if(dontLootStr != "") dontLootStr += ", "; dontLootStr += NameGenerator.firstCharLowercase(the_object.name); } } if(lootStr != "" && disp) Game.MW.addLog(String.format(Local.ITEMS_LOOT,name,lootStr, p2.name)); if(dontLootStr != "" && disp) Game.MW.addLog(String.format(Local.OBJECTS_LEFT_BEHIND, dontLootStr)); clean_list(inventory); // Black hole int final_size = inventory.size(); double limite_effondrement_inventaire = universe.limite_effondrement_inventaire(); if (final_size>initial_size && final_size >= limite_effondrement_inventaire) { double proba_effondrement = universe.proba_effondrement(); if (Math.random() < proba_effondrement) { double prix_total=0.0; ArrayList<Item> slist = new ArrayList<Item>(); for(Item the_object : inventory) { if(the_object.equiped == false && the_object.rare != 6) { prix_total += the_object.prix(); charge -= the_object.poids_final(this); slist.add(the_object); } } inventory.removeAll(slist); double old_cosmic_pts = universe.points_cosmiques_pour_x_ecus(or_perdu_en_trou_noirs); or_perdu_en_trou_noirs += prix_total; nombre_trous_noirs = nombre_trous_noirs+1.0; double cosmic_pts = universe.points_cosmiques_pour_x_ecus(or_perdu_en_trou_noirs); if(disp) Game.MW.addLog(String.format(Local.BLACK_HOLE, name, (int)limite_effondrement_inventaire,proba_effondrement*100.0,name,cosmic_pts-old_cosmic_pts,slist.size(),prix_total)); } } } double nec = necrophagie()*p2.vie_max(); double to_heal = Math.min(vie_max()-vie,nec); if(to_heal > 0.01) { if(disp) Game.MW.addLog(String.format(Local.NECROPHAGY, name, p2.name,to_heal)); vie = vie+to_heal; } } public void meurt() { double pen_reduc = penalty_reduction(); double res = temps_res(); double perte = money*universe.base_gold_penalty_for_death()*pen_reduc; if(disp) Game.MW.addLog(String.format(Local.DEATH_GOLD_LOSS, name, pen_reduc, 100*universe.base_gold_penalty_for_death(), perte)); money_loss(perte, TimeStats.LOSS_DEATH); double bp = universe.base_penalty_for_death(); if(disp) Game.MW.addLog(String.format(Local.DEATH_TIME_PENALTY, bp*pen_reduc, pen_reduc,bp)); personal_wait(bp*pen_reduc,TimeStats.ACTIVITY_PENALTY); if(disp) Game.MW.addLog(String.format(Local.RESURRECTION_TIME,res)); vie = vie_max(); personal_wait(res,TimeStats.ACTIVITY_RESURRECTION); } public void reset() { vie = vie_max(); temps = 0; } public void heal() { double hp_tg = vie_max()-vie; double res = hp_tg / regen(); if (hp_tg > 0.001) { vie = vie_max(); if(disp) Game.MW.addLog(String.format(Local.FULL_HEAL,hp_tg,res)); personal_wait(res,TimeStats.ACTIVITY_HEAL); } } public double next_level() { return xp_level(level+1); } public boolean must_flee() { for (ObjectRule r: rules) { if(r.flee_rule && r.IsTrue(this,null,mob)) return true; } return false; } public double xp_level(double x) { if (x<=1.1) return 0; return 1000.0+((x-1.0)*(x-2.0)*1000.0); } public double level_for_xp(double x) { if(x < 1000.0) return 1; else return Math.floor(Math.min((1.5 + (0.5/Math.sqrt(250.0)) * Math.sqrt(x - 750)),universe.niveau_max())); } public void gain_xp(double sx,int type, double gainLevel) { double x = Math.floor(sx*bonus_xp()*modif_exp_lvl(gainLevel-level)); xp_pt+=x; t_stats.addXp((double)x, type); if(disp) Game.MW.addLog(String.format(Local.EARN_EXPERIENCE,name,x,sx,bonus_xp(),modif_exp_lvl(gainLevel-level))); if (level >= universe.niveau_max()) return; double levelback=level; level = level_for_xp(xp_pt); if(levelback != level) { refresh(); if(disp) Game.MW.addLog(String.format(Local.LEVEL_UP,name,levelback,level)); if(disp) Game.MW.DistWindow.refresh(); } } public void split(Item i, ArrayList<Item> dest) { i.set_qty(i.qty/2.0); Item rit = new Item(); rit.copy(i); rit.update(); dest.add(rit); } public void craft() { if (craftInventory.size() == 0) return; ArrayList<Item> rlist = new ArrayList<Item>(); double time = Item.CraftItem(craftInventory, rlist, this); craftInventory = rlist; double tt = time*temps_craft(); personal_wait(tt,TimeStats.ACTIVITY_CRAFT); t_stats.addEvent(1.0,TimeStats.EVENT_CRAFT); } public void changer_defi() { double bp = universe.base_penalty_for_new_challenge(); double pen_reduc = penalty_reduction(); if(disp) Game.MW.addLog(String.format(Local.CHALLENGE_CHANGE, bp*pen_reduc, pen_reduc,bp)); personal_wait(bp*pen_reduc,TimeStats.ACTIVITY_PENALTY); jeu_fini = false; } public void victory() { jeu_fini = true; if(disp) Game.MW.addLog(String.format(Local.TIME_PASSED,temps_total)); Game.HI = HiScore.loadScore(); Game.HI.addScore(new Score(defi.name,name,temps_total,universe.seed),disp); } public void end_game() { if (jeu_fini) { if(disp) Game.MW.addLog(String.format(Local.YOU_HAVE_ALREADY_FINISHED_THE_GAME,name)); } else if(defi.isCond() && defi.isTrue(this,disp)) { victory(); } else if(!defi.isCond()) { if(disp) Game.MW.infight = true; Thread thread = new Thread() { public void run() { mob = new Monster(defi.boss_name, defi.boss_level, defi.boss_tag, defi.boss_p_stats, universe); if(disp) Game.MW.refreshButtons(); if(!combat(true)) { if(disp) Game.MW.addLog(String.format(Local.YOU_HAVE_DEFEATED_THE_FINAL_BOSS,name)); victory(); } heal(); if(disp) Game.MW.infight = false; if(disp) Game.MW.refreshButtons(); }}; thread.start(); } } public void changer_univers() { Universe new_u = new Universe(universe.seed+1); new_u.joueur = this; new_u.numberOfTravels = universe.numberOfTravels+1; universe = new_u; zone = 2; nb_encounters = 0; refresh_weather_penalties(); Monster.SetOptimalDistribution(universe); StaticItem.init(universe); current_class=-1; double bp = universe.base_penalty_for_dimensional_travel(); double pen_reduc = penalty_reduction(); if(disp) Game.MW.addLog(String.format(Local.UNIVERSE_CHANGE, bp*pen_reduc, pen_reduc,bp)); personal_wait(bp*pen_reduc,TimeStats.ACTIVITY_PENALTY); Game.MW.mustRefreshCurves=true; Game.MW.mustRefreshCharge=true; Game.MW.mustRefreshMonsters=true; Game.MW.mustRefreshWeather=true; Game.MW.mustRefreshStatsWithBonus=true; Game.MW.mustRefreshClassList=true; } public void reset_build() { Game.MW.addLog(Local.RESET_BUILD); for(int i=0; i<nb_stats; i++) stats[i]=0; Game.MW.DistWindow.refresh(); } }
[ "noreply@github.com" ]
noreply@github.com
20a868a2328960ee62533b7319a7604213b43e35
d26a0d58ea3deafcbc57f218d496f11401c7d91a
/WS-Galaxian/src/Personaje/Enemigo/Distraido.java
a5c2136ca6ba942cd7000d5312b8a066aee6743f
[]
no_license
joaquinmontero/Galaxian
1dc3ee9266ead7c4179d7606441be3b1bfeec577
43368b79766d8ebc4b5a4688e63660a292b9b670
refs/heads/master
2020-03-29T17:08:30.431950
2018-09-22T23:21:00
2018-09-22T23:21:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
599
java
package Personaje.Enemigo; import java.awt.Point; import javax.swing.ImageIcon; public class Distraido extends PrototipoEnemigo { public Distraido(Point pos) { super(pos); this.image[0] = new ImageIcon(this.getClass().getResource("/img/Bobo_derecha.png")); this.image[1] = new ImageIcon(this.getClass().getResource("/img/Bobo_izquierda.png")); this.image[2] = new ImageIcon(this.getClass().getResource("/img/Bobo_izquierda.png")); this.image[3] = new ImageIcon(this.getClass().getResource("/img/Bobo_derecha.png")); } public PrototipoEnemigo clone() { return this.clone(); } }
[ "areligle@gmail.com" ]
areligle@gmail.com
502fd18408b536d8ae687e0871faa4f0eb40497e
7a1733e412b34cc7713fdb4a0aa62693e5b5970f
/napoleon_smzPlatform/src/main/java/com/tenfine/napoleon/smzPlatform/service/impl/ProjectServiceImpl.java
29dfbfff730ac35f304941b97e7cb658a2897e4b
[]
no_license
ht604061765/Jane-Learn
9f4d6cd7984989489ac5c5a8b306614622d1829c
66b9f45f1bac3dd4b42bdc0ea32b0e90b336d125
refs/heads/master
2020-05-20T09:10:35.241933
2019-05-22T09:19:59
2019-05-22T09:19:59
185,494,041
0
0
null
null
null
null
UTF-8
Java
false
false
1,791
java
package com.tenfine.napoleon.smzPlatform.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.tenfine.napoleon.framework.bean.POCondition; import com.tenfine.napoleon.framework.bean.Pager; import com.tenfine.napoleon.smzPlatform.dao.ProjectDao; import com.tenfine.napoleon.smzPlatform.dao.po.Project; import com.tenfine.napoleon.smzPlatform.service.ProjectService; import java.util.List; @Service public class ProjectServiceImpl implements ProjectService { @Autowired ProjectDao projectDao; @Override public Pager<Project> getProjectListByPlatformId(int pageNo, int pageSize, String platfromId, String searchKey) { POCondition condition = new POCondition(); condition.addEQ("platformId", platfromId); if (!"".equals(platfromId)) { condition.addLike("name", searchKey); } return projectDao.pagePo(Project.class, condition, pageNo, pageSize); } @Override public Pager<Project> getProjectPage(int pageNo, int pageSize, String searchKey) { POCondition condition = new POCondition(); if(!"".equals(searchKey)) { condition.addLike("name", searchKey); } condition.addOrderDesc("syncTime"); return projectDao.pagePo(Project.class, condition, pageNo, pageSize); } @Override public Project getProjectByPlatformProjectId(String platformProjectId) { POCondition condition = new POCondition(); condition.addEQ("platformProjectId", platformProjectId); List<Project> projectList = projectDao.findPoList(Project.class, condition); if(projectList.size() != 1) { return null; } return projectList.get(0); } }
[ "15943286270@163.com" ]
15943286270@163.com
b6bf6576f5955fd57e9b9b858b6465c90ecb37e6
173458932f77860623d582cfe4fe11ca8d1ee6f3
/octopus-examples/src/main/java/com/github/linkeer8802/octopus/example/config/JacksonCustomizer.java
8cd39044e0fe270204e3e8a88d83a9355526742f
[ "Apache-2.0" ]
permissive
xuefeiwu/octopus
3e9d18f00b27d7a3cb943687e0759fd93a16bdda
1f2cb2af21a5c5380500d83769f5fc7cdef029cb
refs/heads/master
2020-12-06T00:12:49.163123
2020-01-07T08:42:43
2020-01-07T08:42:43
null
0
0
null
null
null
null
UTF-8
Java
false
false
682
java
package com.github.linkeer8802.octopus.example.config; import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.stereotype.Component; import org.zalando.jackson.datatype.money.MoneyModule; /** * @author weird * @date 2019/12/5 */ @Component public class JacksonCustomizer implements Jackson2ObjectMapperBuilderCustomizer { @Override public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) { //MoneyModule jacksonObjectMapperBuilder.modules(new MoneyModule().withDefaultFormatting()); } }
[ "weiride@do1.com.cn" ]
weiride@do1.com.cn
80daac873fe52905b3cdc29014c61b47131f174e
123f9ba128936eac397d48e0d579118b467d8e7f
/src/main/java/com/pzh/mapreduce/table/TableBean.java
3488580f4567d7f041a0f91ca311fee53537e309
[]
no_license
pzhu1015/mapreduce-job
435013f725173bee61fbd9517f5912ef152ed316
c62ff1a5064b38a2a33b3c66f97cd218515d92c4
refs/heads/master
2022-05-13T20:53:38.477391
2019-09-22T12:09:31
2019-09-22T12:09:31
210,141,071
0
0
null
2022-04-12T21:57:03
2019-09-22T12:10:13
Java
UTF-8
Java
false
false
1,801
java
/** * @Author pzh * @Date 2019年9月8日 下午4:07:45 * @Description */ package com.pzh.mapreduce.table; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.hadoop.io.Writable; public class TableBean implements Writable { private String id; private String pid; private int amount; private String pname; private String flag; public TableBean() { super(); // TODO Auto-generated constructor stub } public TableBean(String id, String pid, int amount, String pname, String flag) { super(); this.id = id; this.pid = pid; this.amount = amount; this.pname = pname; this.flag = flag; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } public String getFlag() { return flag; } public void setFlag(String flag) { this.flag = flag; } @Override public void write(DataOutput out) throws IOException { out.writeUTF(id); out.writeUTF(pid); out.writeInt(amount); out.writeUTF(pname); out.writeUTF(flag); } @Override public void readFields(DataInput in) throws IOException { id = in.readUTF(); pid = in.readUTF(); amount = in.readInt(); pname = in.readUTF(); flag = in.readUTF(); } @Override public String toString() { return id + "\t" + amount + "\t" + pname; } }
[ "pzh@pzh" ]
pzh@pzh
3f76fd52b78297149053f8209087d851053a33b4
6ac12da7bc81c9fbf8bbf844553bc46bd2746ba9
/ds4p-receiver/common-library/src/main/java/org/hl7/v3/POCDMT000040Section.java
c9e7820c1fc0250a2ff6bb45471c443b5618cce8
[]
no_license
wanghaisheng/ds4p-pilot-public
b8fd90ee5e196e0e055e250af0e3c547cfa84eaa
235cc22266868917d88332fb32d03baded2dd684
refs/heads/master
2020-04-08T03:19:53.614880
2012-12-08T10:02:38
2012-12-08T10:02:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
16,646
java
/** * This software is being provided per FARS 52.227-14 Rights in Data - General. * Any redistribution or request for copyright requires written consent by the * Department of Veterans Affairs. */ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.10.17 at 12:15:19 PM MDT // package org.hl7.v3; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for POCD_MT000040.Section complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="POCD_MT000040.Section"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="realmCode" type="{urn:hl7-org:v3}CS" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="typeId" type="{urn:hl7-org:v3}POCD_MT000040.InfrastructureRoot.typeId" minOccurs="0"/> * &lt;element name="templateId" type="{urn:hl7-org:v3}II" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="id" type="{urn:hl7-org:v3}II" minOccurs="0"/> * &lt;element name="code" type="{urn:hl7-org:v3}CE" minOccurs="0"/> * &lt;element name="title" type="{urn:hl7-org:v3}ST" minOccurs="0"/> * &lt;element name="text" type="{urn:hl7-org:v3}StrucDoc.Text" minOccurs="0"/> * &lt;element name="confidentialityCode" type="{urn:hl7-org:v3}CE" minOccurs="0"/> * &lt;element name="languageCode" type="{urn:hl7-org:v3}CS" minOccurs="0"/> * &lt;element name="subject" type="{urn:hl7-org:v3}POCD_MT000040.Subject" minOccurs="0"/> * &lt;element name="author" type="{urn:hl7-org:v3}POCD_MT000040.Author" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="informant" type="{urn:hl7-org:v3}POCD_MT000040.Informant12" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="entry" type="{urn:hl7-org:v3}POCD_MT000040.Entry" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="component" type="{urn:hl7-org:v3}POCD_MT000040.Component5" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="ID1" type="{http://www.w3.org/2001/XMLSchema}ID" /> * &lt;attribute name="nullFlavor" type="{urn:hl7-org:v3}NullFlavor" /> * &lt;attribute name="classCode" type="{urn:hl7-org:v3}ActClass" fixed="DOCSECT" /> * &lt;attribute name="moodCode" type="{urn:hl7-org:v3}ActMood" fixed="EVN" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "POCD_MT000040.Section", propOrder = { "realmCode", "typeId", "templateId", "id", "code", "title", "text", "confidentialityCode", "languageCode", "subject", "author", "informant", "entry", "component" }) public class POCDMT000040Section { protected List<CS> realmCode; protected POCDMT000040InfrastructureRootTypeId typeId; protected List<II> templateId; protected II id; protected CE code; protected ST title; protected StrucDocText text; protected CE confidentialityCode; protected CS languageCode; protected POCDMT000040Subject subject; protected List<POCDMT000040Author> author; protected List<POCDMT000040Informant12> informant; protected List<POCDMT000040Entry> entry; protected List<POCDMT000040Component5> component; @XmlAttribute(name = "ID1") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected String id1; @XmlAttribute(name = "nullFlavor") protected List<String> nullFlavor; @XmlAttribute(name = "classCode") protected List<String> classCode; @XmlAttribute(name = "moodCode") protected List<String> moodCode; /** * Gets the value of the realmCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the realmCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRealmCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CS } * * */ public List<CS> getRealmCode() { if (realmCode == null) { realmCode = new ArrayList<CS>(); } return this.realmCode; } /** * Gets the value of the typeId property. * * @return * possible object is * {@link POCDMT000040InfrastructureRootTypeId } * */ public POCDMT000040InfrastructureRootTypeId getTypeId() { return typeId; } /** * Sets the value of the typeId property. * * @param value * allowed object is * {@link POCDMT000040InfrastructureRootTypeId } * */ public void setTypeId(POCDMT000040InfrastructureRootTypeId value) { this.typeId = value; } /** * Gets the value of the templateId property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the templateId property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTemplateId().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link II } * * */ public List<II> getTemplateId() { if (templateId == null) { templateId = new ArrayList<II>(); } return this.templateId; } /** * Gets the value of the id property. * * @return * possible object is * {@link II } * */ public II getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link II } * */ public void setId(II value) { this.id = value; } /** * Gets the value of the code property. * * @return * possible object is * {@link CE } * */ public CE getCode() { return code; } /** * Sets the value of the code property. * * @param value * allowed object is * {@link CE } * */ public void setCode(CE value) { this.code = value; } /** * Gets the value of the title property. * * @return * possible object is * {@link ST } * */ public ST getTitle() { return title; } /** * Sets the value of the title property. * * @param value * allowed object is * {@link ST } * */ public void setTitle(ST value) { this.title = value; } /** * Gets the value of the text property. * * @return * possible object is * {@link StrucDocText } * */ public StrucDocText getText() { return text; } /** * Sets the value of the text property. * * @param value * allowed object is * {@link StrucDocText } * */ public void setText(StrucDocText value) { this.text = value; } /** * Gets the value of the confidentialityCode property. * * @return * possible object is * {@link CE } * */ public CE getConfidentialityCode() { return confidentialityCode; } /** * Sets the value of the confidentialityCode property. * * @param value * allowed object is * {@link CE } * */ public void setConfidentialityCode(CE value) { this.confidentialityCode = value; } /** * Gets the value of the languageCode property. * * @return * possible object is * {@link CS } * */ public CS getLanguageCode() { return languageCode; } /** * Sets the value of the languageCode property. * * @param value * allowed object is * {@link CS } * */ public void setLanguageCode(CS value) { this.languageCode = value; } /** * Gets the value of the subject property. * * @return * possible object is * {@link POCDMT000040Subject } * */ public POCDMT000040Subject getSubject() { return subject; } /** * Sets the value of the subject property. * * @param value * allowed object is * {@link POCDMT000040Subject } * */ public void setSubject(POCDMT000040Subject value) { this.subject = value; } /** * Gets the value of the author property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the author property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAuthor().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link POCDMT000040Author } * * */ public List<POCDMT000040Author> getAuthor() { if (author == null) { author = new ArrayList<POCDMT000040Author>(); } return this.author; } /** * Gets the value of the informant property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the informant property. * * <p> * For example, to add a new item, do as follows: * <pre> * getInformant().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link POCDMT000040Informant12 } * * */ public List<POCDMT000040Informant12> getInformant() { if (informant == null) { informant = new ArrayList<POCDMT000040Informant12>(); } return this.informant; } /** * Gets the value of the entry property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the entry property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEntry().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link POCDMT000040Entry } * * */ public List<POCDMT000040Entry> getEntry() { if (entry == null) { entry = new ArrayList<POCDMT000040Entry>(); } return this.entry; } /** * Gets the value of the component property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the component property. * * <p> * For example, to add a new item, do as follows: * <pre> * getComponent().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link POCDMT000040Component5 } * * */ public List<POCDMT000040Component5> getComponent() { if (component == null) { component = new ArrayList<POCDMT000040Component5>(); } return this.component; } /** * Gets the value of the id1 property. * * @return * possible object is * {@link String } * */ public String getID1() { return id1; } /** * Sets the value of the id1 property. * * @param value * allowed object is * {@link String } * */ public void setID1(String value) { this.id1 = value; } /** * Gets the value of the nullFlavor property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the nullFlavor property. * * <p> * For example, to add a new item, do as follows: * <pre> * getNullFlavor().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getNullFlavor() { if (nullFlavor == null) { nullFlavor = new ArrayList<String>(); } return this.nullFlavor; } /** * Gets the value of the classCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the classCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getClassCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getClassCode() { if (classCode == null) { classCode = new ArrayList<String>(); } return this.classCode; } /** * Gets the value of the moodCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the moodCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getMoodCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getMoodCode() { if (moodCode == null) { moodCode = new ArrayList<String>(); } return this.moodCode; } }
[ "Duane DeCouteau@Socratic5" ]
Duane DeCouteau@Socratic5
b74bfe6876f9c12e9240f1a602acc361ee10639b
e2a5680ac6ccde64c54fb36cee743ea589137285
/ReadFile.java
1caa94debc096f875713ac5de2d4b8fcde3820ac
[]
no_license
radhikareddyvelma/Home-work1
06d6fa04e1572a03be4ce47b39cfec83a6b24bf1
96a7e6cd2e84b565eb438ea2cbd01ddd29a6a7df
refs/heads/master
2021-01-23T02:10:22.983549
2017-04-04T01:26:18
2017-04-04T01:26:18
85,970,715
0
0
null
null
null
null
UTF-8
Java
false
false
562
java
package first.java; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class ReadFile { public static void main(String[] args) { BufferedReader br = null; try { br = new BufferedReader(new FileReader("filename.txt")); String line; while ((line = br.readLine()) != null) { System.out.println(line); } }catch (IOException e) { e.printStackTrace(); }finally { try { br.close(); }catch (IOException e) { e.printStackTrace(); } } } }
[ "noreply@github.com" ]
noreply@github.com
bb1631076cf5000ea1010027bcba79e5077aff5e
b22d870c70762fe4c771026d7f2ad1b8f733e702
/java8InAction/src/main/java/com/vcvinci/lambdasinaction/chap1/FilteringApples.java
8b5850cea2bc04341e9e981ed7d2ee8501d39d91
[]
no_license
vcvinci/vinci_example
103f9949dad2bfe749cf270fc2b1d68b7002aa7d
daa74043a7a86628916c6f5160cea20e77026ddd
refs/heads/master
2022-12-29T14:42:36.229434
2019-09-09T07:10:45
2019-09-09T07:10:45
203,291,266
0
0
null
2022-12-16T04:32:41
2019-08-20T03:16:59
Java
UTF-8
Java
false
false
3,385
java
package com.vcvinci.lambdasinaction.chap1; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Predicate; public class FilteringApples{ public static void main(String ... args){ List<Apple> inventory = Arrays.asList(new Apple(80,"green"), new Apple(155, "green"), new Apple(120, "red")); // [Apple{color='green', weight=80}, Apple{color='green', weight=155}] List<Apple> greenApples = filterApples(inventory, FilteringApples::isGreenApple); System.out.println(greenApples); // [Apple{color='green', weight=155}] List<Apple> heavyApples = filterApples(inventory, FilteringApples::isHeavyApple); System.out.println(heavyApples); // [Apple{color='green', weight=80}, Apple{color='green', weight=155}] List<Apple> greenApples2 = filterApples(inventory, (Apple a) -> "green".equals(a.getColor())); System.out.println(greenApples2); // [Apple{color='green', weight=155}] List<Apple> heavyApples2 = filterApples(inventory, (Apple a) -> a.getWeight() > 150); System.out.println(heavyApples2); // [] List<Apple> weirdApples = filterApples(inventory, (Apple a) -> a.getWeight() < 80 || "brown".equals(a.getColor())); System.out.println(weirdApples); } public static List<Apple> filterGreenApples(List<Apple> inventory){ List<Apple> result = new ArrayList<>(); for (Apple apple: inventory){ if ("green".equals(apple.getColor())) { result.add(apple); } } return result; } public static List<Apple> filterHeavyApples(List<Apple> inventory){ List<Apple> result = new ArrayList<>(); for (Apple apple: inventory){ if (apple.getWeight() > 150) { result.add(apple); } } return result; } public static boolean isGreenApple(Apple apple) { return "green".equals(apple.getColor()); } public static boolean isHeavyApple(Apple apple) { return apple.getWeight() > 150; } public static List<Apple> filterApples(List<Apple> inventory, Predicate<Apple> p){ List<Apple> result = new ArrayList<>(); for(Apple apple : inventory){ if(p.test(apple)){ result.add(apple); } } return result; } public static class Apple { private int weight = 0; private String color = ""; public Apple(int weight, String color){ this.weight = weight; this.color = color; } public Integer getWeight() { return weight; } public void setWeight(Integer weight) { this.weight = weight; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String toString() { return "Apple{" + "color='" + color + '\'' + ", weight=" + weight + '}'; } } }
[ "vcvinci@163.com" ]
vcvinci@163.com
0636a75804a0b3cd4b363656ffd50b35f2f493f5
ec4be8c3e3eaf864f04d911702f52928e81f4c9c
/src/main/java/org/eurekaclinical/standardapis/entity/RoleEntity.java
3fe17975cabf8f69c300db6949b789bcdd9d1a55
[ "Apache-2.0", "BSD-3-Clause", "EPL-1.0", "Classpath-exception-2.0", "EPL-2.0", "GPL-2.0-only", "CDDL-1.0", "MIT", "CDDL-1.1" ]
permissive
eurekaclinical/eurekaclinical-standard-apis
8193493ace96b849aeb8fec56ec44ca901f48737
4233712941f18d456daeca3e90577c2bc6151e5b
refs/heads/master
2021-07-10T23:44:52.722111
2020-08-10T19:17:49
2020-08-10T19:17:49
62,142,484
0
7
Apache-2.0
2020-08-10T19:13:17
2016-06-28T13:20:30
Java
UTF-8
Java
false
false
1,782
java
package org.eurekaclinical.standardapis.entity; /*- * #%L * Eureka! Clinical Standard APIs * %% * Copyright (C) 2016 Emory University * %% * 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% */ /** * * @author arpost */ public interface RoleEntity extends Entity<Long> { /** * Get the role's identification number. * * @return A {@link Long} representing the role's id. */ @Override Long getId(); /** * Get the role's name. * * @return A String containing the role's name. */ String getName(); /** * Is this role a default role? * * @return True if the role is a default role, false otherwise. */ boolean isDefaultRole(); /** * Set the role's default flag. * * @param inDefaultRole True or False, True indicating a default role, False * indicating a non-default role. */ void setDefaultRole(boolean inDefaultRole); /** * Set the role's identification number. * * @param inId The number representing the role's id. */ @Override void setId(Long inId); /** * Set the role's name. * * @param inName A string containing the role's name. */ void setName(String inName); }
[ "arpost@emory.edu" ]
arpost@emory.edu