blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
132 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
28 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
352
e0b9fdd681645bcaca3b6e35cdee377ef1d78771
4a377af1007965606623a073d9ab6841c21bb235
/s2-tiger/src/main/java/org/seasar/extension/dxo/converter/impl/EnumConverter.java
721c34ac1c897601ea2bbc334b37e48140736517
[ "Apache-2.0" ]
permissive
ngoclt-28/seasar2
52de6eee1eead3f15f063d4c9f0b2a2d96f9a32c
48b637c58b5bb777cff16595659b6f5b9d6e730a
refs/heads/master
2021-01-18T13:28:45.120427
2014-12-06T18:08:51
2014-12-06T18:08:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,680
java
/* * Copyright 2004-2014 the Seasar Foundation and the Others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.seasar.extension.dxo.converter.impl; import org.seasar.extension.dxo.converter.ConversionContext; /** * 数値または文字列から列挙定数へ変換するコンバータです。 * * @author koichik */ @SuppressWarnings("unchecked") public class EnumConverter extends AbstractConverter { public Class getDestClass() { return Enum.class; } public Class[] getSourceClasses() { return new Class[] { Object.class }; } public Object convert(Object source, Class destClass, ConversionContext context) { if (source == null) { return null; } if (source.getClass() == destClass) { return source; } if (source instanceof Number) { final int ordinal = Number.class.cast(source).intValue(); return destClass.getEnumConstants()[ordinal]; } final String name = source.toString(); return Enum.valueOf(destClass, name); } }
[ "koichik@improvement.jp" ]
koichik@improvement.jp
ce9cd3eba430c33489e5331571ca48c24aa03ad0
fb84e0e1ee8157837a7d5fa06ad8bf3c6a8fafca
/ma-contract-domain/src/main/java/com/yonyou/energy/common/domain/response/ServiceResponse.java
d22eb3fa12b253d574a673761a50582066f8a941
[]
no_license
coomia/ma-contract
05a32e42470de1cbb4a4f9dd9715ceb3fba1fb19
4ffecad8eb0b1e4b56b07ee98fe89859c0e6a6f4
refs/heads/master
2020-04-26T22:19:02.837033
2017-10-19T03:09:43
2017-10-19T03:09:43
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,833
java
package com.yonyou.energy.common.domain.response; import java.io.Serializable; public class ServiceResponse<T> implements Serializable { private static final long serialVersionUID = 2488663702267110932L; private String code; private String msg; private String detail; private T result; public static ServiceResponse successResponse() { return new ServiceResponse(BaseResponseCode.SUCCESS); } public static ServiceResponse failureResponse() { return new ServiceResponse(BaseResponseCode.FAILURE); } public ServiceResponse() { this.code = BaseResponseCode.SUCCESS.getCode(); this.msg = BaseResponseCode.SUCCESS.getMsg(); } public ServiceResponse(T result) { this.code = BaseResponseCode.SUCCESS.getCode(); this.msg = BaseResponseCode.SUCCESS.getMsg(); this.result = result; } public ServiceResponse(String code, String msg) { this.code = BaseResponseCode.SUCCESS.getCode(); this.msg = BaseResponseCode.SUCCESS.getMsg(); this.code = code; this.msg = msg; } public ServiceResponse(String code, String msg, String detail) { this.code = BaseResponseCode.SUCCESS.getCode(); this.msg = BaseResponseCode.SUCCESS.getMsg(); this.code = code; this.msg = msg; this.detail = detail; } public ServiceResponse(ResponseCode ResponseCode) { this.code = BaseResponseCode.SUCCESS.getCode(); this.msg = BaseResponseCode.SUCCESS.getMsg(); this.code = ResponseCode.getCode(); this.msg = ResponseCode.getMsg(); } public ServiceResponse(ResponseCode ResponseCode, String detail) { this.code = BaseResponseCode.SUCCESS.getCode(); this.msg = BaseResponseCode.SUCCESS.getMsg(); this.code = ResponseCode.getCode(); this.msg = ResponseCode.getMsg(); this.detail = detail; } public void setResponseCode(ResponseCode ResponseCode) { this.code = ResponseCode.getCode(); this.msg = ResponseCode.getMsg(); } public boolean isSuccess() { return BaseResponseCode.SUCCESS.getCode().equals(this.code); } public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } public String getMsg() { return this.msg; } public void setMsg(String msg) { this.msg = msg; } public void setDetail(String detail) { this.detail = detail; } public String getDetail() { return this.detail; } public void addDetail(String detail) { this.setDetail(detail); } public T getResult() { return this.result; } public void setResult(T result) { this.result = result; } }
[ "mahga@yonyou.com" ]
mahga@yonyou.com
3bcb862df7d5e9d79fc2d9aeccc6d7186f7c658a
c0e75b1da1a0b92f572133e47fe58c53667a9cd9
/BusinessAdvisor/src/businessadvisor/francia/AereopuertoFrancia.java
144c9fc3fc8bf40b771065b5b59ea8f3eb586414
[]
no_license
eduardolopezga/ingSoft
f8f5e4c233b96ac4922c661a4cddcc14500c1b4b
6a1d0e997d5c3687d83eac8160be6cc475a85e7c
refs/heads/master
2021-01-19T16:51:34.076190
2014-12-02T05:21:26
2014-12-02T05:21:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
485
java
package businessadvisor.francia; import com.example.businessadvisor.R; //import com.example.businessadvisor.R.layout; import android.os.Bundle; import android.app.Activity; public class AereopuertoFrancia extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.aereopuertofrancia); } }
[ "eduardo.lopezga@gmail.com" ]
eduardo.lopezga@gmail.com
a08cea531d37fcea95349854cba1ae4317c7599e
f1ec27267bb4807eb322220d02b7e8e9c57ca1a7
/Room4You/app/src/main/java/com/s306631/room4you/viewModels/BookingViewModel.java
9ead4c9eafcebb2b719ffe137791e8ac4f380917
[]
no_license
Ab0o0oD/DAVE3600_App_Development
cb5242ddf01d2b9a7f5645802800d087ed455f8c
f02eee0fedffa7ccc29a948e2eed3f9defd70623
refs/heads/master
2022-12-13T23:34:40.973170
2020-08-31T09:49:51
2020-08-31T09:49:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,398
java
package com.s306631.room4you.viewModels; import android.app.Application; import androidx.annotation.NonNull; import androidx.lifecycle.AndroidViewModel; import com.s306631.room4you.activities.BookRoomActivity; import com.s306631.room4you.models.Booking; import com.s306631.room4you.repository.BookingRepository; import java.util.Collections; import java.util.List; public class BookingViewModel extends AndroidViewModel { private BookingRepository bookingRepository; public BookingViewModel(@NonNull Application application) { super(application); bookingRepository = new BookingRepository(); } public List<Booking> getAllBookingsAsList() { return sortBookingListByTime(bookingRepository.getBookingsFromWebService()); } public void postBooking(BookRoomActivity context, Booking booking) { bookingRepository.postBooking(context, booking); } private List<Booking> sortBookingListByTime(List<Booking> bookingList) { Collections.sort(bookingList, (b1, b2) -> { String[] fromTimeSplit = b1.getFromTime().split(":"); int fromTime1 = Integer.parseInt(fromTimeSplit[0]); fromTimeSplit = b2.getFromTime().split(":"); int fromTime2 = Integer.parseInt(fromTimeSplit[0]); return Integer.compare(fromTime1, fromTime2); }); return bookingList; } }
[ "fredrikhp@gmail.com" ]
fredrikhp@gmail.com
bf13c81ca9a7907356c80cb39ea61e1a9831c81d
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/7/7_50b864a3743af99c6028537e0d09e49a69cea78c/TextViewEx/7_50b864a3743af99c6028537e0d09e49a69cea78c_TextViewEx_t.java
1456199ca0811a219050a6d1702581f3fad09afd
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
5,912
java
package com.example.textjustify; import com.fscz.util.TextJustifyUtils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.Paint; import android.widget.TextView; import android.util.AttributeSet; /* * * TextViewEx.java * @author Mathew Kurian * * !-- Requires -- ! * TextJustifyUtils.java * * From TextJustify-Android Library v1.0.2 * https://github.com/bluejamesbond/TextJustify-Android * * Please report any issues * https://github.com/bluejamesbond/TextJustify-Android/issues * * Date: 12/13/2013 12:28:16 PM * */ public class TextViewEx extends TextView { private Paint paint = new Paint(); private String [] blocks; private float spaceOffset = 0; private float horizontalOffset = 0; private float verticalOffset = 0; private float horizontalFontOffset = 0; private float dirtyRegionWidth = 0; private boolean wrapEnabled = false; private float strecthOffset; private float wrappedEdgeSpace; private String block; private String wrappedLine; private String [] lineAsWords; private Object[] wrappedObj; private Bitmap cache = null; private boolean cacheEnabled = false; public TextViewEx(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public TextViewEx(Context context, AttributeSet attrs) { super(context, attrs); } public TextViewEx(Context context) { super(context); } @Override public void setDrawingCacheEnabled(boolean cacheEnabled) { this.cacheEnabled = cacheEnabled; } public void setText(String st, boolean wrap) { wrapEnabled = wrap; super.setText(st); } @Override protected void onDraw(Canvas canvas) { // If wrap is disabled then, // request original onDraw if(!wrapEnabled) { super.onDraw(canvas); return; } // Active canas needs to be set // based on cacheEnabled Canvas activeCanvas = null; // Set the active canvas based on // whether cache is enabled if (cacheEnabled) { if (cache != null) { // Draw to the OS provided canvas // if the cache is not empty canvas.drawBitmap(cache, 0, 0, paint); return; } else { // Create a bitmap and set the activeCanvas // to the one derived from the bitmap cache = Bitmap.createBitmap(getWidth(), getHeight(), Config.ARGB_4444); activeCanvas = new Canvas(cache); } } else { // Active canvas is the OS // provided canvas activeCanvas = canvas; } // Pull widget properties paint.setColor(getCurrentTextColor()); paint.setTypeface(getTypeface()); paint.setTextSize(getTextSize()); dirtyRegionWidth = getWidth(); int maxLines = Integer.MAX_VALUE; int currentapiVersion = android.os.Build.VERSION.SDK_INT; if (currentapiVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN){ maxLines = getMaxLines(); } int lines = 1; blocks = getText().toString().split("((?<=\n)|(?=\n))"); verticalOffset = horizontalFontOffset = getLineHeight() - 0.5f; // Temp fix spaceOffset = paint.measureText(" "); for(int i = 0; i < blocks.length && lines <= maxLines; i++) { block = blocks[i]; horizontalOffset = 0; if(block.length() == 0) { continue; } else if(block.equals("\n")) { verticalOffset += horizontalFontOffset; continue; } block = block.trim(); if(block.length() == 0) { continue; } wrappedObj = TextJustifyUtils.createWrappedLine(block, paint, spaceOffset, dirtyRegionWidth); wrappedLine = ((String) wrappedObj[0]); wrappedEdgeSpace = (Float) wrappedObj[1]; lineAsWords = wrappedLine.split(" "); strecthOffset = wrappedEdgeSpace != Float.MIN_VALUE ? wrappedEdgeSpace/(lineAsWords.length - 1) : 0; for(int j = 0; j < lineAsWords.length; j++) { String word = lineAsWords[j]; if (lines == maxLines && j == lineAsWords.length - 1) { activeCanvas.drawText("...", horizontalOffset, verticalOffset, paint); } else { activeCanvas.drawText(word, horizontalOffset, verticalOffset, paint); } horizontalOffset += paint.measureText(word) + spaceOffset + strecthOffset; } lines++; if(blocks[i].length() > 0) { blocks[i] = blocks[i].substring(wrappedLine.length()); verticalOffset += blocks[i].length() > 0 ? horizontalFontOffset : 0; i--; } } if (cacheEnabled) { // Draw the cache onto the OS provided // canvas. canvas.drawBitmap(cache, 0, 0, paint); } } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
ee273e87b4072bfc2a9dc6d651aadb07f288bd76
3db4d064ac449c261a16525b48f91f804c4207e0
/newdeal-project-49/src/main/java/com/eomcs/lms/dao/impl/MariaDBMemberDAO.java
b131bf6b49179b40131820aa3ff81fa7584505d4
[]
no_license
zerocyber/newdeal-20181127
c94f32d4afb0030fc71f94e49aa9a39fabe0a6c2
526acdd5ab160136fc754232ca2c2e845d249ed6
refs/heads/master
2020-04-08T11:05:38.572280
2018-12-07T09:04:30
2018-12-07T09:04:30
159,293,138
0
0
null
null
null
null
UTF-8
Java
false
false
842
java
package com.eomcs.lms.dao.impl; import java.util.HashMap; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import com.eomcs.lms.dao.MemberDAO; import com.eomcs.lms.domain.Member; public class MariaDBMemberDAO implements MemberDAO{ SqlSessionFactory sqlSessionFactory; public MariaDBMemberDAO(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory = sqlSessionFactory; } @Override public Member findByEmailPassword(String email, String password) throws Exception { try(SqlSession sqlSession = sqlSessionFactory.openSession();) { HashMap<String, Object> params = new HashMap<>(); params.put("email", email); params.put("password", password); return sqlSession.selectOne( "MemberDAO.findByEmailPassword", params); } } }
[ "zeroforever@naver.com" ]
zeroforever@naver.com
8a2d86ca741170617852fd3e2f7d45fc2199d3d2
22b3ac4c80b985d3a585ddb2189dd9af90f2ff1c
/app/src/main/java/com/android/app/orquesta/agrupacionDetail/AgruPersonaRecylerViewAdapter.java
0870fbe27a0f3d4dd3bba348f269ae27ee08cd26
[]
no_license
MilSay/ORQUESTA1
0a216fa87be14c28e8e0771155a9322c7ae44f09
f89041fb854048d8024d10ce3be90779b6ede983
refs/heads/master
2022-12-28T23:41:15.511150
2020-10-13T13:47:07
2020-10-13T13:47:07
303,717,644
0
0
null
null
null
null
UTF-8
Java
false
false
2,581
java
package com.android.app.orquesta.agrupacionDetail; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.android.app.orquesta.R; import com.android.app.orquesta.Util.Constants; import com.android.app.orquesta.model.AgrupacionDetalle; import com.android.app.orquesta.model.Evento; import com.android.app.orquesta.model.User; import com.squareup.picasso.Picasso; import java.text.SimpleDateFormat; import java.util.ArrayList; public class AgruPersonaRecylerViewAdapter extends RecyclerView.Adapter<AgruPersonaRecylerViewAdapter.ViewHolder> { private ArrayList<AgrupacionDetalle> detallePersonList; //private ArrayList<User> userList; public Context context; public String variableDemo; private User user; public AgruPersonaRecylerViewAdapter(ArrayList<AgrupacionDetalle> detallePersonList, Context context) { this.detallePersonList = detallePersonList; this.context = context; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View rootView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recylerview_agru_persona_detail, parent, false); return new ViewHolder(rootView); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { AgrupacionDetalle person = detallePersonList.get(position); String imageUrl = Constants.PERSONA_IMAGEN_URL + person.getFoto(); Picasso.get().load(imageUrl).into(holder.ivImage); holder.tvNombres.setText(person.getNombres()+" "+ person.getApellidos()); holder.tvTipoPersona.setText(person.getTipoPersona()); } @Override public int getItemCount() { return detallePersonList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { public ImageView ivImage; public TextView tvNombres,tvTipoPersona; public ViewHolder(View itemView) { super(itemView); ivImage = itemView.findViewById(R.id.iv_agrup__person_image); tvNombres = itemView.findViewById(R.id.tv_agru_person_nombres); tvTipoPersona = itemView.findViewById(R.id.tv_agru_person_tipo_persona); } } }
[ "miliabanto@MacBook-Air-de-MILI.local" ]
miliabanto@MacBook-Air-de-MILI.local
f48df0f428887c036e69f5803b671665baeea986
c8f744448631767ea0663362134fc6e13b79f935
/src/pratica1/Pratica1.java
3863daaad2a5d695856f76aeb6d619aafba01e14
[]
no_license
Ingrid0601/practica-yiyi1
7f56de62c6956b1e122bd8f556f5bfc446546e34
305aa26e2cd18dd14224bb6e78ff5772501d29b5
refs/heads/master
2022-04-24T02:53:07.790709
2020-04-20T05:32:44
2020-04-20T05:32:44
257,184,090
0
0
null
null
null
null
UTF-8
Java
false
false
475
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pratica1; /** * * @author yiyi */ public class Pratica1 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here FrmPrincipal.main(args); } }
[ "JUAN@192.168.1.70" ]
JUAN@192.168.1.70
49b7122ce82af2e1b493083270faa19d131046f2
fca9311c9a05463020c9538ffd5a39ebcb6192dd
/src/permCheck/PermCheck.java
e238257f71932f1c04ead86e8b20ccd0ff3f0484
[]
no_license
jennyEckstein/Brain_Teasers
ab00a43d26173d8302d1021a9fd78b387f0ad6db
d2e9acb2a3aca816dcb21b84bf1fc6a95c0b793e
refs/heads/master
2020-12-31T05:09:48.915689
2016-05-18T22:15:14
2016-05-18T22:15:14
57,452,957
0
0
null
null
null
null
UTF-8
Java
false
false
579
java
package permCheck; import java.util.Arrays; public class PermCheck { public int solution(int [] array){ if (array.length == 1){ if(array[0] == 1){ return 1; }else{ return 0; } } Arrays.sort(array); for (int i = 1; i < array.length; i++){ if ((array[i] - array[i-1]) > 1){ return 0; } } return 1; } public static void main (String [] args){ //int [] array = {4,1,3,2}; int [] array = {4,1,3}; PermCheck permCheck = new PermCheck(); int result = permCheck.solution(array); System.out.println(result); } }
[ "ycharnetskaya@gmail.com" ]
ycharnetskaya@gmail.com
4f89b2c4c1b5bf11bd28a5bbc84080c109b68156
46b635552bbc273dd1644656a9cf743f99c3ffef
/CMIT141/week 3/CreateObjectDemo.java
270073783c343e0f241fc687f6822bb6d7ee6e70
[]
no_license
ThePhychoKid/Im-Learnding
76e2201f66b5b661a2ca2285ab040730414ed3bb
902b3823a12e32eac555f71792068be132b853ba
refs/heads/master
2023-03-30T08:08:56.592757
2021-04-16T07:06:01
2021-04-16T07:06:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
129
java
version https://git-lfs.github.com/spec/v1 oid sha256:c49ae88312d964b4adc36793bf6a450a75a78df7c7fe8fb4f43cb3c7cab48164 size 1067
[ "coreyrhodges@gmail.com" ]
coreyrhodges@gmail.com
1988840ac9bfb8411b0e69436e8695ee3f6bd8f4
2eefae8e048e87904c5c2e1844a8e5174b7257bb
/commercetools-models/src/main/java/io/sphere/sdk/products/queries/ProductProjectionByIdGetImpl.java
77e882e477541a02788e829ea9eac6966625d726
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
francescaramsey/commercetools-jvm-sdk
a475ddbd518475e45fdf93a0fb632ef75c163171
3ae0afe51ba9d30a5f63f93cdebccbb9e5df993d
refs/heads/master
2022-04-14T02:57:15.873756
2020-03-31T11:11:11
2020-03-31T11:11:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,008
java
package io.sphere.sdk.products.queries; import io.sphere.sdk.http.NameValuePair; import io.sphere.sdk.products.ProductProjection; import io.sphere.sdk.products.ProductProjectionType; import io.sphere.sdk.products.expansion.ProductProjectionExpansionModel; import io.sphere.sdk.products.search.PriceSelection; import io.sphere.sdk.queries.MetaModelGetDslBuilder; import io.sphere.sdk.queries.MetaModelGetDslImpl; import javax.annotation.Nullable; import java.util.Collections; import java.util.List; import static io.sphere.sdk.products.search.PriceSelectionQueryParameters.extractPriceSelectionFromHttpQueryParameters; import static io.sphere.sdk.products.search.PriceSelectionQueryParameters.getQueryParametersWithPriceSelection; final class ProductProjectionByIdGetImpl extends MetaModelGetDslImpl<ProductProjection, ProductProjection, ProductProjectionByIdGet, ProductProjectionExpansionModel<ProductProjection>> implements ProductProjectionByIdGet { ProductProjectionByIdGetImpl(final String id, final ProductProjectionType projectionType) { super(ProductProjectionEndpoint.ENDPOINT, id, ProductProjectionExpansionModel.of(), ProductProjectionByIdGetImpl::new, Collections.singletonList(NameValuePair.of("staged", projectionType.isStaged().toString()))); } public ProductProjectionByIdGetImpl(MetaModelGetDslBuilder<ProductProjection, ProductProjection, ProductProjectionByIdGet, ProductProjectionExpansionModel<ProductProjection>> builder) { super(builder); } @Override public ProductProjectionByIdGet withPriceSelection(@Nullable final PriceSelection priceSelection) { final List<NameValuePair> resultingParameters = getQueryParametersWithPriceSelection(priceSelection, additionalQueryParameters()); return withAdditionalQueryParameters(resultingParameters); } @Nullable @Override public PriceSelection getPriceSelection() { return extractPriceSelectionFromHttpQueryParameters(additionalQueryParameters()); } }
[ "michael.schleichardt@commercetools.de" ]
michael.schleichardt@commercetools.de
b56f88f1ec1c7319d625d113808f95ed4dff240d
fc5ee82d10fc4c424184a9328b11e782e25b4a88
/Admin/kernel/src/main/java/cn/windy/module/wechat/util/api/bean/JsapiTicket.java
2e88b339159466d71d3dd4894a0108e483f6c49a
[ "Apache-2.0" ]
permissive
gelovechen1314/zzwf-weiyun_front-master
95d9dc9d510794e110ab247485e3e5f0d7fb446f
138fcfa6a0ed4fb8a4a18a1782ba87c7835caf5c
refs/heads/master
2020-03-15T03:33:03.440752
2018-06-11T10:20:49
2018-06-11T10:20:49
131,944,823
0
0
null
null
null
null
UTF-8
Java
false
false
843
java
package cn.windy.module.wechat.util.api.bean; public class JsapiTicket { private String ticket; private int expiresIn; private long startTime; public JsapiTicket(String ticket, int expiresIn) { this.ticket = ticket; this.expiresIn = expiresIn; this.startTime = System.currentTimeMillis(); } public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public int getExpiresIn() { return expiresIn; } public void setExpiresIn(int expiresIn) { this.expiresIn = expiresIn; } public boolean isExpired(){ long interval = System.currentTimeMillis() - startTime; if(interval>=(expiresIn-100)*1000){ return true; } return false; } }
[ "chen187388@163.com" ]
chen187388@163.com
c85685108b88243f3d6524fd46ed137c7e978274
3a5985651d77a31437cfdac25e594087c27e93d6
/ojc-core/dtelse/dtelseimpl/src/com/sun/jbi/engine/dtel/DTELEngine.java
6a81dc739f9394d79a65f9ff1d9ca6e156923500
[]
no_license
vitalif/openesb-components
a37d62133d81edb3fdc091abd5c1d72dbe2fc736
560910d2a1fdf31879e3d76825edf079f76812c7
refs/heads/master
2023-09-04T14:40:55.665415
2016-01-25T13:12:22
2016-01-25T13:12:33
48,222,841
0
5
null
null
null
null
UTF-8
Java
false
false
25,185
java
/* * BEGIN_HEADER - DO NOT EDIT * * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. * If applicable add the following below this CDDL HEADER, * with the fields enclosed by brackets "[]" replaced with * your own identifying information: Portions Copyright * [year] [name of copyright owner] */ /* * @(#)DTELEngine.java * * Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved. * * END_HEADER - DO NOT EDIT */ package com.sun.jbi.engine.dtel; import java.io.File; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.dom.DOMSource; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * * @author jwaldorf */ public class DTELEngine { private static final String OUT_ROOT = "dtelOperation"; private static final String OUT_MESSAGE = "output"; private static final String OUT_ELEMENT = "outElement"; private Document mDecisionTableDocument; private Element mDecisionTableElement; private String[] mFieldNames; private String[] mFieldTypes; private Field[] mParent; private LinkedList mRoot; private String mNamespace; public class Field { private String mName; private String mExpression; private String mType; // Test || Assignment private String mExpressionType; // ExactNumber || LessThanNumber || GreaterThanNumber || NumberRange || String private double mValue; private double mValueOne; private double mValueTwo; private Date mBeginDate; private Date mEndDate; private Date mDate; private String mExpressionOne; private String mExpressionTwo; private LinkedList mSubFields; private HashMap mAssignments; public Field() { mSubFields = new LinkedList(); mAssignments = new HashMap(); } public String getName() { return mName; } public void setName(String name) { mName = name; } public String getExpression() { return mExpression; } public void setExpression(String expression) { mExpression = expression; } public String getExpressionOne() { return mExpressionOne; } public void setExpressionOne(String expression) { mExpressionOne = expression; } public String getExpressionTwo() { return mExpressionTwo; } public void setExpressionTwo(String expression) { mExpressionTwo = expression; } public String getType() { return mType; } public void setType(String type) { mType = type; } public String getExpressionType() { return mExpressionType; } public void setExpressionType(String expressionType) { mExpressionType = expressionType; } public LinkedList getSubFields() { return mSubFields; } public void addSubField(Field field) { mSubFields.add(field); } public String addAssignmentRule(String name, String value) { mAssignments.put(name, value); return "string"; } public HashMap getAssignmentRules() { return mAssignments; } public void parseData(String data) { // Check for {ExactNumber} Pattern p = Pattern.compile("[ ]*[0123456789]+[ ]*"); Matcher m = p.matcher(data); if (m.matches()) { try { String s[] = data.split("[ ]+"); mExpression = s[0]; mExpressionType = "ExactNumber"; mValue = Double.parseDouble(s[0]); mType = "double"; return; } catch (Exception e) { e.printStackTrace(); } } // Check for {LessThanNumber} p = Pattern.compile("less[ ]+than[ ]+[0123456789]+[ ]*"); m = p.matcher(data); if (m.matches()) { try { String s[] = data.split("[ ]+"); mExpression = s[2]; mExpressionType = "LessThanNumber"; mValue = Double.parseDouble(s[2]); mType = "double"; return; } catch (Exception e) { e.printStackTrace(); } } // Check for {GreaterThanNumber} p = Pattern.compile("greater[ ]+than[ ]+[0123456789]+[ ]*"); m = p.matcher(data); if (m.matches()) { try { String s[] = data.split("[ ]+"); mExpression = s[2]; mExpressionType = "GreaterThanNumber"; mValue = Double.parseDouble(s[2]); mType = "double"; return; } catch (Exception e) { e.printStackTrace(); } } // Check for {NumberRange} p = Pattern.compile("[ ]*[0123456789]+[ ]*\\.\\.[ ]*[0123456789]+[ ]*"); m = p.matcher(data); if (m.matches()) { try { String s[] = data.split("[ ]+"); mExpressionOne = s[0]; mExpressionTwo = s[2]; mExpressionType = "NumberRange"; mValueOne = Double.parseDouble(s[0]); mValueTwo = Double.parseDouble(s[2]); mType = "double"; return; } catch (Exception e) { e.printStackTrace(); } } // Check for {DateRange} p = Pattern.compile("[ ]*[^ ]+[ ]*\\.\\.[ ]*[^ ]+[ ]*"); m = p.matcher(data); if (m.matches()) { try { String s[] = data.split("\\.\\."); try { DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); mBeginDate = formatter.parse(s[0]); mEndDate = formatter.parse(s[1]); mExpressionType = "DateRange"; mType = "dateTime"; return; } catch (Exception e) { // Just continue if we cannot parse the dates. } } catch (Exception e) { e.printStackTrace(); } } // Check for {BeforeDate} p = Pattern.compile("[ ]*before[ ]*[^ ]+[ ]*"); m = p.matcher(data); if (m.matches()) { try { String s[] = data.split("[ ]+"); try { DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); mDate = formatter.parse(s[1]); mExpressionType = "BeforeDate"; mType = "dateTime"; return; } catch (Exception e) { // Just continue if we cannot parse the dates. } } catch (Exception e) { e.printStackTrace(); } } // Check for {AfterDate} p = Pattern.compile("[ ]*after[ ]*[^ ]+[ ]*"); m = p.matcher(data); if (m.matches()) { try { String s[] = data.split("[ ]+"); try { DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); mDate = formatter.parse(s[1]); mExpressionType = "AfterDate"; mType = "dateTime"; return; } catch (Exception e) { // Just continue if we cannot parse the dates. } } catch (Exception e) { e.printStackTrace(); } } try { // DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); mDate = DateFormat.getDateTimeInstance().parse(data); mExpressionType = "ExactDate"; mType = "dateTime"; return; } catch (Exception e) { // If we cannot parse the date then it must be a string } mExpressionType = "ExactString"; mExpression = data; mType = "string"; } public boolean eval(String data) { if (mExpressionType.equals("ExactNumber")) { double d = Double.parseDouble(data); return d == mValue; } else if (mExpressionType.equals("LessThanNumber")) { double d = Double.parseDouble(data); return d < mValue; } else if (mExpressionType.equals("GreaterThanNumber")) { double d = Double.parseDouble(data); return d > mValue; } else if (mExpressionType.equals("NumberRange")) { double d = Double.parseDouble(data); return d >= mValueOne && d <= mValueTwo; } else if (mExpressionType.equals("BeforeDate")) { try { DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); Date date = formatter.parse(data); return date.compareTo(mDate) < 0; } catch (Exception e) { return false; } } else if (mExpressionType.equals("AfterDate")) { try { DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); Date date = formatter.parse(data); return date.compareTo(mDate) > 0; } catch (Exception e) { return false; } } else if (mExpressionType.equals("DateRange")) { try { DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); Date date = formatter.parse(data); return date.compareTo(mBeginDate) >= 0 && date.compareTo(mEndDate) <= 0; } catch (Exception e) { return false; } } else if (mExpressionType.equals("ExactDate")) { try { DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); Date date = formatter.parse(data); return date.compareTo(mDate) == 0; } catch (Exception e) { return false; } } else if (mExpressionType.equals("ExactString")) { if (mExpression.equals("*")) { return true; } return data.equals(mExpression); } else { return false; } } public void assign(Document doc) { Set set = getAssignmentRules().entrySet(); Element outputRoot = doc.getDocumentElement(); for (Iterator i = set.iterator(); i.hasNext();) { Map.Entry me = (Map.Entry) i.next(); String outputName = (String) me.getKey(); String outputValue = (String) me.getValue(); NodeList nodeList = outputRoot.getElementsByTagNameNS(mNamespace, OUT_ELEMENT); for (int j = 0; j < nodeList.getLength(); j++) { Node node = nodeList.item(j); Element outElement = (Element) node; Element element = doc.createElement(outputName); outElement.appendChild(element); element.appendChild(doc.createTextNode(outputValue)); } } } } /** Creates a new instance of DTELEngine */ public DTELEngine() { mRoot = new LinkedList(); } private void populateFieldNames(Node node) { Element element = (Element) node; NodeList nodeList = element.getElementsByTagName("Cell"); mFieldNames = new String[nodeList.getLength() + 1]; mFieldTypes = new String[nodeList.getLength() + 1]; mParent = new Field[nodeList.getLength() + 1]; int position = 0; for (int i = 0; i < nodeList.getLength(); i++, position++) { Element e = (Element) nodeList.item(i); NodeList nl = e.getElementsByTagName("Data"); String index = e.getAttribute("ss:Index"); if (index != null && index.length() > 0) { position = Integer.parseInt(index) - 1; } if (nl.getLength() == 1) { Element dataElement = (Element) nl.item(0); String value = dataElement.getTextContent(); mFieldNames[position] = value; } } } private void processRow(Node node) { Field leafField = null; Element element = (Element) node; NodeList nodeList = element.getElementsByTagName("Cell"); int position = 0; int i; for (i = 0; i < nodeList.getLength(); i++, position++) { Element e = (Element) nodeList.item(i); NodeList nl = e.getElementsByTagName("Data"); String index = e.getAttribute("ss:Index"); if (index != null && index.length() > 0) { if (position != 0) { position = Integer.parseInt(index) - 1; break; } position = Integer.parseInt(index) - 1; } if (nl.getLength() == 1) { Field f = new Field(); leafField = f; mParent[position] = f; f.setName(mFieldNames[position]); Element dataElement = (Element) nl.item(0); String value = dataElement.getTextContent(); f.parseData(value); mFieldTypes[position] = f.getType(); if (position > 0) { mParent[position - 1].addSubField(f); } else { mRoot.add(f); } } else { break; } } for (; i < nodeList.getLength(); i++, position++) { Element e = (Element) nodeList.item(i); NodeList nl = e.getElementsByTagName("Data"); if (nl.getLength() == 1) { Element dataElement = (Element) nl.item(0); String value = dataElement.getTextContent(); if (leafField != null) { String type = leafField.addAssignmentRule(mFieldNames[position], value); mFieldTypes[position] = type; } } } } private void print(String prefix, Field field) { System.out.print(prefix + field.getName()); if (field.getExpressionType().equals("ExactNumber")) { System.out.print(": " + field.getExpression()); } if (field.getExpressionType().equals("LessThanNumber")) { System.out.print(": less than " + field.getExpression()); } if (field.getExpressionType().equals("GreaterThanNumber")) { System.out.print(": greater than " + field.getExpression()); } if (field.getExpressionType().equals("NumberRange")) { System.out.print(": " + field.getExpressionOne() + ".." + field.getExpressionTwo());; } if (field.getExpressionType().equals("ExactString")) { System.out.print(": " + field.getExpression()); } System.out.print(" -->"); Set set = field.getAssignmentRules().entrySet(); for (Iterator i = set.iterator(); i.hasNext();) { Map.Entry me = (Map.Entry) i.next(); System.out.print(" " + me.getKey() + "=" + me.getValue()); } System.out.println(""); for (int i = 0; i < field.getSubFields().size(); i++) { print(prefix + " ", (Field) field.getSubFields().get(i)); } } public void loadDecisionTable(String file) { try { File f = new File(file); mNamespace = f.getName().replace('.', '_'); mDecisionTableDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(f); mDecisionTableElement = mDecisionTableDocument.getDocumentElement(); NodeList nodeList = mDecisionTableElement.getElementsByTagName("Row"); populateFieldNames(nodeList.item(0)); for (int i = 1; i < nodeList.getLength(); i++) { processRow(nodeList.item(i)); } // Debug //for (int i = 0; i < mRoot.size(); i++) { // print("", (Field) mRoot.get(i)); //} } catch (Exception e) { e.printStackTrace(); } } private void assign(Element ruleElement, Element output) { String outputName = ruleElement.getAttribute("node"); String outputValue = ruleElement.getAttribute("value"); NodeList nodeList = output.getElementsByTagName(outputName); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); Element element = (Element) node; element.setTextContent(outputValue); } } private void recur(Field field, Element input, Document doc) { for (int i = 0; i < field.getSubFields().size(); i++) { Field f = (Field) field.getSubFields().get(i); check(f, input, doc); } if (field.getSubFields().size() == 0) { field.assign(doc); } } private boolean eval(String expression, String type, String value) { if (type.compareToIgnoreCase("int") == 0) { // Check for static check Pattern p = Pattern.compile("[0123456789]+"); Matcher m = p.matcher(expression); if (m.matches()) { return expression.compareToIgnoreCase(value) == 0; } p = Pattern.compile("<[ ]+[0123456789]+"); m = p.matcher(expression); if (m.matches()) { try { String s[] = expression.split("[ ]+"); Integer iExp = Integer.decode(s[1]); Integer iVal = Integer.decode(value); return iVal.compareTo(iExp) < 0; } catch (Exception e) { e.printStackTrace(); } } p = Pattern.compile(">[ ]+[0123456789]+"); m = p.matcher(expression); if (m.matches()) { try { String s[] = expression.split("[ ]+"); Integer iExp = Integer.decode(s[1]); Integer iVal = Integer.decode(value); return iVal.compareTo(iExp) > 0; } catch (Exception e) { e.printStackTrace(); } } p = Pattern.compile("BETWEEN[ ]+[0123456789]+[ ]+[0123456789]+[ ]*"); m = p.matcher(expression); if (m.matches()) { try { String s[] = expression.split("[ ]+"); Integer iLowExp = Integer.decode(s[1]); Integer iHighExp = Integer.decode(s[2]); Integer iVal = Integer.decode(value); return iVal.compareTo(iLowExp) > 0 && iVal.compareTo(iHighExp) < 0; } catch (Exception e) { e.printStackTrace(); } } } else if (type.compareToIgnoreCase("string") == 0) { } return false; } private void check(Field field, Element input, Document doc) { // Get the name of the input field to test. String inputTestName = field.getName(); NodeList nodeList = input.getElementsByTagName(inputTestName); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); Element element = (Element) node; String inputNodeValue = element.getTextContent(); if (field.eval(inputNodeValue)) { recur(field, input, doc); } } } public void execute(DOMSource input, DOMSource output) { Document doc = (Document) output.getNode(); Element root = doc.createElement(OUT_ROOT); Element message = doc.createElement(OUT_MESSAGE); Element element = doc.createElementNS(mNamespace, OUT_ELEMENT); element.setPrefix("ns0"); doc.appendChild(root); root.appendChild(message); message.appendChild(element); Node rn = input.getNode(); Element inputRoot = null; if (rn instanceof Document) { inputRoot = ((Document) rn).getDocumentElement(); } else if (rn instanceof Element) { inputRoot = (Element) rn; } else { return; } //Element inputRoot = ((Document)input.getNode()).getDocumentElement(); //Element outputRoot = ((Document)output.getNode()).getDocumentElement(); for (int i = 0; i < mRoot.size(); i++) { check((Field) mRoot.get(i), inputRoot, doc); } } public static void main(String[] args) { String mFile=System.getProperty("ALASKA_ROOT") + "/jbi/dtelse/jbiadapter/test/data/riskscore.dtel"; //String text="<?xml version=\"1.0\" encoding=\"UTF-8\"?><jbi:message xmlns:msgns=\"riskscore_dtel\" type=\"msgns:InputMessage\" version=\"1.0\" xmlns:jbi=\"http://java.sun.com/xml/ns/jbi/wsdl-11-wrapper\"><jbi:part><inElement xmlns=\"riskscore_dtel\"><Health>good</Health><Age>66.0</Age><Sex>Male</Sex></inElement></jbi:part></jbi:message>"; String text="<?xml version=\"1.0\" encoding=\"UTF-8\"?><jbi:message xmlns:msgns=\"riskscore_dtel\" type=\"msgns:InputMessage\" version=\"1.0\" xmlns:jbi=\"http://java.sun.com/xml/ns/jbi/wsdl-11-wrapper\"><jbi:part><ns0:inElement xmlns:ns0=\"riskscore_dtel\"><Health>good</Health><Age>66.0</Age><Sex>Male</Sex></ns0:inElement></jbi:part></jbi:message>"; //String mFile = System.getProperty("ALASKA_ROOT") + "/jbi\\test\\dtel\\src\\untitled.dtel"; //String text = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><dtelOperation><input><ns0:inElement xmlns:ns0=\"untitled_dtel\"><CreditScore>601.0</CreditScore><Sex>male</Sex><LoanAmount>601.0</LoanAmount><Income>601.0</Income></ns0:inElement></input></dtelOperation>"; try { DTELEngine mDTELEngine = new DTELEngine(); mDTELEngine.loadDecisionTable(mFile); System.out.println("---> Loaded: "+mDTELEngine); DOMSource input = new DOMSource(XmlUtil.createDocumentFromXML(true, text)); DOMSource output =new DOMSource(XmlUtil.createDocument(true)); Element rootNode = ((Document)input.getNode()).getDocumentElement(); System.out.println("InputXML: " + XmlUtil.toXml(rootNode, "UTF-8", false)); mDTELEngine.execute(input, output); System.out.println("---> Processed: "); Document xdoc2 = (Document)output.getNode(); Element rootNode2 = xdoc2.getDocumentElement(); System.out.println("OutputXML: " + XmlUtil.toXml(rootNode2, "UTF-8", false)); } catch (Exception e) { e.printStackTrace(); } } }
[ "bitbucket@bitbucket02.private.bitbucket.org" ]
bitbucket@bitbucket02.private.bitbucket.org
2ed33b100fc792ed5119d6e256fd0160a95e7084
884054cd91a1089b636129b08ca58529cdb121e9
/src/com/example/rfid/DesfireProtocol.java
61f583153392e240232b78ca282f2f47db706894
[]
no_license
Paulahu/android-nfc-rfid
f68131a50290c02555e8010517f2607c1708c522
db8f590d278795623b5c680d69930a23de564bce
refs/heads/master
2020-12-14T13:37:04.954860
2013-06-09T14:15:58
2013-06-09T14:15:58
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,023
java
/* * DesfireProtocol.java * * Copyright (C) 2011 Eric Butler * * Authors: * Eric Butler <eric@codebutler.com> * * 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 com.example.rfid; import android.nfc.tech.IsoDep; import android.util.Log; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class DesfireProtocol { /* Commands */ static final byte GET_MANUFACTURING_DATA = (byte) 0x60; static final byte GET_APPLICATION_DIRECTORY = (byte) 0x6A; static final byte GET_ADDITIONAL_FRAME = (byte) 0xAF; static final byte SELECT_APPLICATION = (byte) 0x5A; static final byte READ_DATA = (byte) 0xBD; static final byte WRITE_DATA = (byte) 0x3D; static final byte READ_RECORD = (byte) 0xBB; static final byte GET_FILES = (byte) 0x6F; static final byte GET_FILE_SETTINGS = (byte) 0xF5; static final int MAX_SEND_DATA = 47; static final byte MAX_SEND_LENGTH = (byte) 0x2F; /* Status codes */ static final byte OPERATION_OK = (byte) 0x00; static final byte PERMISSION_DENIED = (byte) 0x9D; static final byte ADDITIONAL_FRAME = (byte) 0xAF; private IsoDep mTagTech; public DesfireProtocol(IsoDep tagTech) { mTagTech = tagTech; } public int[] getAppList() throws Exception { byte[] appDirBuf = sendRequest(GET_APPLICATION_DIRECTORY); int[] appIds = new int[appDirBuf.length / 3]; for (int app = 0; app < appDirBuf.length; app += 3) { byte[] appId = new byte[3]; System.arraycopy(appDirBuf, app, appId, 0, 3); appIds[app / 3] = Utils.byteArrayToInt(appId); } return appIds; } public void selectApp(int appId) throws Exception { byte[] appIdBuff = new byte[3]; appIdBuff[0] = (byte) ((appId & 0xFF0000) >> 16); appIdBuff[1] = (byte) ((appId & 0xFF00) >> 8); appIdBuff[2] = (byte) (appId & 0xFF); sendRequest(SELECT_APPLICATION, appIdBuff); } public int[] getFileList() throws Exception { byte[] buf = sendRequest(GET_FILES); int[] fileIds = new int[buf.length]; for (int x = 0; x < buf.length; x++) { fileIds[x] = (int) buf[x]; } return fileIds; } public byte[] readFile(int fileNo) throws Exception { return sendRequest(READ_DATA, new byte[] { (byte) fileNo, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0 }); } public byte[] readRecord(int fileNum) throws Exception { return sendRequest(READ_RECORD, new byte[] { (byte) fileNum, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0 }); } public byte[] writeFile(int fileNo, String content) throws Exception { Log.i("Debut","writeFile"); int times = content.length() / MAX_SEND_DATA; int offset_start = 0; byte[] result = null; if(content.length() % MAX_SEND_DATA != 0) { times = (content.length() / MAX_SEND_DATA) + 1; } Log.i("times", times + ""); while(times > 0) { int offset_end = offset_start + MAX_SEND_DATA; if(offset_end > content.length()) offset_end = content.length(); Log.i("content", content.substring(offset_start, offset_end)); Byte[] subData = Utils.encodeISO(content.substring(offset_start, offset_end), MAX_SEND_DATA); List<Byte> rawMessage = new ArrayList<Byte>(); // FileId 1 Byte rawMessage.add((byte) fileNo); byte[] offsetByte = Utils.intToByteArray(offset_start); Log.i("Offset", Utils.getHexString(offsetByte)); // Offset 3 Bytes for(int i = 0 ; i < 3 ; i++){ rawMessage.add((byte) offsetByte[i]); } // Length 3 Bytes rawMessage.add(MAX_SEND_LENGTH); rawMessage.add((byte) 0x0); rawMessage.add((byte) 0x0); // Data 0-52 Bytes Collections.addAll(rawMessage, subData); byte[] message = new byte[rawMessage.size()]; for(int i = 0; i < message.length; i++) { message[i] = rawMessage.get(i).byteValue(); } result = sendRequest(WRITE_DATA, message); offset_start += MAX_SEND_DATA; times--; } return result; } private byte[] sendRequest(byte command) throws Exception { return sendRequest(command, null); } private byte[] sendRequest(byte command, byte[] parameters) throws Exception { ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] recvBuffer = mTagTech .transceive(wrapMessage(command, parameters)); while (true) { if (recvBuffer[recvBuffer.length - 2] != (byte) 0x91) throw new Exception("Invalid response"); output.write(recvBuffer, 0, recvBuffer.length - 2); byte status = recvBuffer[recvBuffer.length - 1]; if (status == OPERATION_OK) { break; } else if (status == ADDITIONAL_FRAME) { recvBuffer = mTagTech.transceive(wrapMessage( GET_ADDITIONAL_FRAME, null)); } else if (status == PERMISSION_DENIED) { throw new Exception("Permission denied"); } else { throw new Exception("Unknown status code: " + Integer.toHexString(status & 0xFF)); } } return output.toByteArray(); } private byte[] wrapMessage(byte command, byte[] parameters) throws Exception { ByteArrayOutputStream stream = new ByteArrayOutputStream(); stream.write((byte) 0x90); stream.write(command); stream.write((byte) 0x00); stream.write((byte) 0x00); if (parameters != null) { stream.write((byte) parameters.length); stream.write(parameters); } stream.write((byte) 0x00); return stream.toByteArray(); } }
[ "rezgui.y@gmail.com" ]
rezgui.y@gmail.com
2baa246996c9929276a02085577cba4e6b16c5dc
6ac3677b8e349859b32fdbd6fdbcf12e0a26d608
/chinesecheckers/src/chinesecheckers/gui/CCGui.java
22f92cf21486c1d7a675391f28fcd3c3a3eb616b
[]
no_license
tpepels/mcts_gameframe
a8d24c6be115ed4432365eec24f2257f94a3fc36
05d84ba1e48734418538228fe0f40df41899c47c
refs/heads/master
2021-01-21T12:46:52.369553
2020-01-02T10:53:36
2020-01-02T10:53:36
13,271,401
0
0
null
null
null
null
UTF-8
Java
false
false
4,000
java
package chinesecheckers.gui; import chinesecheckers.game.Board; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class CCGui extends JFrame { private static final long serialVersionUID = -1921481286866231418L; public static CCPanel ccPanel; private final ButtonGroup player2Group = new ButtonGroup(); private final ButtonGroup player1Group = new ButtonGroup(); private Board currentBoard; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { CCGui frame = new CCGui(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public CCGui() { setResizable(false); setBackground(Color.BLACK); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 480, 550); JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu mnFile = new JMenu("File"); menuBar.add(mnFile); currentBoard = new Board(); currentBoard.initialize(); JMenuItem mntmNewGame = new JMenuItem("New game"); mntmNewGame.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { currentBoard.initialize(); ccPanel.setBoard(currentBoard); } }); mnFile.add(mntmNewGame); JMenu mnPlayer = new JMenu("Player 1"); menuBar.add(mnPlayer); final JRadioButtonMenuItem player1Human = new JRadioButtonMenuItem("Human"); player1Human.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { ccPanel.setPlayer(1, player1Human.isSelected()); } }); player1Group.add(player1Human); player1Human.setSelected(false); mnPlayer.add(player1Human); final JRadioButtonMenuItem player1AI = new JRadioButtonMenuItem("A.I."); player1AI.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ccPanel.setPlayer(1, !player1AI.isSelected()); } }); player1Group.add(player1AI); player1AI.setSelected(true); mnPlayer.add(player1AI); JMenu mnPlayer_1 = new JMenu("Player 2"); menuBar.add(mnPlayer_1); final JRadioButtonMenuItem player2Human = new JRadioButtonMenuItem("Human"); player2Human.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ccPanel.setPlayer(2, player2Human.isSelected()); } }); player2Group.add(player2Human); mnPlayer_1.add(player2Human); final JRadioButtonMenuItem player2AI = new JRadioButtonMenuItem("A.I."); player2AI.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ccPanel.setPlayer(2, !player2AI.isSelected()); } }); player2AI.setSelected(true); player2Group.add(player2AI); mnPlayer_1.add(player2AI); JMenuItem mntmNewMenuItem = new JMenuItem("Undo"); mntmNewMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { ccPanel.undoMove(); } }); menuBar.add(mntmNewMenuItem); ccPanel = new CCPanel(currentBoard, false, false); ccPanel.setBackground(Color.BLACK); ccPanel.setLayout(null); setContentPane(ccPanel); } }
[ "tpepels@gmail.com" ]
tpepels@gmail.com
a2d24a4195f3975a13a5ade80399344048a51ba9
98961fd2b4a0b80ba574bc2595a17ae27f6fb9c1
/admin-server/src/main/java/com/mxc/server/SpringbootAdminserverApplication.java
33dddd56fd766df0809171994d24de761acff9b1
[]
no_license
ciweigg2/springboot-admin
4328753f9f286e3cd389d3a2008bf87a34aa02e3
cf9f306c575c0726660ee15c07e0241d5c880cb8
refs/heads/master
2020-04-20T05:58:22.793799
2019-02-01T09:08:14
2019-02-01T09:08:14
168,670,593
0
0
null
null
null
null
UTF-8
Java
false
false
509
java
package com.mxc.server; import de.codecentric.boot.admin.server.config.EnableAdminServer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @author 马秀成 * @date 2019/1/31 * @jdk.version 1.8 * @desc */ @SpringBootApplication @EnableAdminServer public class SpringbootAdminserverApplication { public static void main(String[] args) { SpringApplication.run(SpringbootAdminserverApplication.class, args); } }
[ "maxiucheng@example.com" ]
maxiucheng@example.com
e9da5523bd6b61d3c45f2076ca9ecae873d4adea
288b948bf8ba83a3b14e12c3c417961bd23d6e8b
/largequant-cloud-comment/src/main/java/cn/largequant/cloudcomment/service/LikeService.java
f35e12a7f4ada16964d4f4b097b4a8d567ba2ec3
[]
no_license
lareina59466/largequant-spring-cloud
40e994be11bb29bb2f1475e1486a99600a002b9e
c698d47ee50ccba87daba5a94360301a965d4ace
refs/heads/master
2020-08-03T06:47:15.279913
2019-10-22T11:47:32
2019-10-22T11:47:32
211,658,341
0
0
null
null
null
null
UTF-8
Java
false
false
425
java
package cn.largequant.cloudcomment.service; public interface LikeService { //获取某个类型的点赞数量 long getLikeCount(int typeId, int type); //获取用户是否对某个类型的点赞状态 int getLikeStatus(int userId, int typeId, int type); //用户点赞 long like(int userId, int typeId, int type); //用户取消点赞 long disLike(int userId, int typeId, int type); }
[ "731222526@qq.com" ]
731222526@qq.com
9356e88060e23b7562569387ff54cb4aa9a22fb5
bdd6e1a2db4105f3f2fa4874bc7c8a18ad75628a
/src/main/java/com/chpok/logiwebboardboot/consumer/MessageConsumer.java
bcdfe6a9024ddcb91c7153625fd5e9ee9e5f4263
[]
no_license
ChpokHead/Logiweb-Board-Boot-Back
518bf249d4549487be906481776c9686d73b41c7
b795fffed27427dc18e4e8d9b53fa37d421d825e
refs/heads/master
2023-06-05T16:07:08.332750
2021-06-21T17:32:51
2021-06-21T17:32:51
378,761,643
0
0
null
null
null
null
UTF-8
Java
false
false
295
java
package com.chpok.logiwebboardboot.consumer; import com.chpok.logiwebboardboot.model.kafka.LogiwebMessage; public interface MessageConsumer { void onMessage(LogiwebMessage message); void onUpdated(Long entityId); void onSaved(Long entityId); void onDeleted(Long entityId); }
[ "mildgeneral@gmail.com" ]
mildgeneral@gmail.com
0b865fb7cb9e4536f1c46ea747850526852d2f6b
1098a2f32e5de57cb97192f40e86f36083e67f1a
/src/Excecoes/CarrinhoException.java
e2be44853a5eb50b736eb320b151e483a7617ef3
[]
no_license
ProDoug21/Projeto_Poo
2803f3dd4b6cb254c717b25723d9bd3e8dda062c
0b69b6089ec9bebf66d3815517d8e991f536c59a
refs/heads/master
2022-04-18T17:37:31.027553
2020-04-17T04:28:56
2020-04-17T04:28:56
256,399,696
0
0
null
null
null
null
UTF-8
Java
false
false
150
java
package Excecoes; public class CarrinhoException extends Exception { public CarrinhoException(String mensagem){ super(mensagem); } }
[ "josed3851@gmail.com" ]
josed3851@gmail.com
97657d561c189c895776dd61c7cf454d3f85901f
c8a7974ebdf8c2f2e7cdc34436d667e3f1d29609
/src/main/java/com/tencentcloudapi/redis/v20180412/models/InstanceIntegerParam.java
28a6544265915f1d0b166a266f5c4efd80cc1188
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-java-en
d6f099a0de82ffd3e30d40bf7465b9469f88ffa6
ba403db7ce36255356aeeb4279d939a113352990
refs/heads/master
2023-08-23T08:54:04.686421
2022-06-28T08:03:02
2022-06-28T08:03:02
193,018,202
0
3
Apache-2.0
2022-06-28T08:03:04
2019-06-21T02:40:54
Java
UTF-8
Java
false
false
6,409
java
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.redis.v20180412.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class InstanceIntegerParam extends AbstractModel{ /** * Parameter name */ @SerializedName("ParamName") @Expose private String ParamName; /** * Parameter type: Integer */ @SerializedName("ValueType") @Expose private String ValueType; /** * Whether restart is required after a modification is made. Value range: true, false */ @SerializedName("NeedRestart") @Expose private String NeedRestart; /** * Default value of the parameter */ @SerializedName("DefaultValue") @Expose private String DefaultValue; /** * Current value of a parameter */ @SerializedName("CurrentValue") @Expose private String CurrentValue; /** * Parameter description */ @SerializedName("Tips") @Expose private String Tips; /** * Minimum value of a parameter */ @SerializedName("Min") @Expose private String Min; /** * Maximum value of a parameter */ @SerializedName("Max") @Expose private String Max; /** * Parameter status. 1: modifying; 2: modified */ @SerializedName("Status") @Expose private Long Status; /** * Get Parameter name * @return ParamName Parameter name */ public String getParamName() { return this.ParamName; } /** * Set Parameter name * @param ParamName Parameter name */ public void setParamName(String ParamName) { this.ParamName = ParamName; } /** * Get Parameter type: Integer * @return ValueType Parameter type: Integer */ public String getValueType() { return this.ValueType; } /** * Set Parameter type: Integer * @param ValueType Parameter type: Integer */ public void setValueType(String ValueType) { this.ValueType = ValueType; } /** * Get Whether restart is required after a modification is made. Value range: true, false * @return NeedRestart Whether restart is required after a modification is made. Value range: true, false */ public String getNeedRestart() { return this.NeedRestart; } /** * Set Whether restart is required after a modification is made. Value range: true, false * @param NeedRestart Whether restart is required after a modification is made. Value range: true, false */ public void setNeedRestart(String NeedRestart) { this.NeedRestart = NeedRestart; } /** * Get Default value of the parameter * @return DefaultValue Default value of the parameter */ public String getDefaultValue() { return this.DefaultValue; } /** * Set Default value of the parameter * @param DefaultValue Default value of the parameter */ public void setDefaultValue(String DefaultValue) { this.DefaultValue = DefaultValue; } /** * Get Current value of a parameter * @return CurrentValue Current value of a parameter */ public String getCurrentValue() { return this.CurrentValue; } /** * Set Current value of a parameter * @param CurrentValue Current value of a parameter */ public void setCurrentValue(String CurrentValue) { this.CurrentValue = CurrentValue; } /** * Get Parameter description * @return Tips Parameter description */ public String getTips() { return this.Tips; } /** * Set Parameter description * @param Tips Parameter description */ public void setTips(String Tips) { this.Tips = Tips; } /** * Get Minimum value of a parameter * @return Min Minimum value of a parameter */ public String getMin() { return this.Min; } /** * Set Minimum value of a parameter * @param Min Minimum value of a parameter */ public void setMin(String Min) { this.Min = Min; } /** * Get Maximum value of a parameter * @return Max Maximum value of a parameter */ public String getMax() { return this.Max; } /** * Set Maximum value of a parameter * @param Max Maximum value of a parameter */ public void setMax(String Max) { this.Max = Max; } /** * Get Parameter status. 1: modifying; 2: modified * @return Status Parameter status. 1: modifying; 2: modified */ public Long getStatus() { return this.Status; } /** * Set Parameter status. 1: modifying; 2: modified * @param Status Parameter status. 1: modifying; 2: modified */ public void setStatus(Long Status) { this.Status = Status; } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "ParamName", this.ParamName); this.setParamSimple(map, prefix + "ValueType", this.ValueType); this.setParamSimple(map, prefix + "NeedRestart", this.NeedRestart); this.setParamSimple(map, prefix + "DefaultValue", this.DefaultValue); this.setParamSimple(map, prefix + "CurrentValue", this.CurrentValue); this.setParamSimple(map, prefix + "Tips", this.Tips); this.setParamSimple(map, prefix + "Min", this.Min); this.setParamSimple(map, prefix + "Max", this.Max); this.setParamSimple(map, prefix + "Status", this.Status); } }
[ "zhiqiangfan@tencent.com" ]
zhiqiangfan@tencent.com
840dcc66f6779b4e017867ea10b7f52034bb0c8c
38b4f363117e9180da8670979ac0869b97505f6b
/ego-parent/ego-manager/ego-manager-service/src/main/java/com/ego/service/impl/BrandServiceImpl.java
86a4360cc568a219dd5fb036b7ce66bdf85d4c14
[]
no_license
FanTianHao/TestGit
710b7c371de4fd93ad6236f9b10b196b522edf4e
a9f9f8817a60e97556e5d5c7d94a416bead399ea
refs/heads/master
2022-12-22T11:43:45.409560
2019-06-15T10:24:51
2019-06-15T10:24:51
192,063,711
0
0
null
2022-12-16T10:36:46
2019-06-15T10:01:59
HTML
UTF-8
Java
false
false
615
java
package com.ego.service.impl; import com.ego.mapper.BrandMapper; import com.ego.pojo.Brand; import com.ego.pojo.BrandExample; import com.ego.service.BrandServiceI; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Created by ASUS on 2019/6/10. */ @Service public class BrandServiceImpl implements BrandServiceI{ @Autowired private BrandMapper brandMapper; //商品列表 - 品牌 @Override public List<Brand> selectBrandList() { return brandMapper.selectByExample(new BrandExample()); } }
[ "DarrenFan07@163.com" ]
DarrenFan07@163.com
d9f07093553855bce2fe6b90a51c5616a831b584
d55d17769a21ed3d0bfc41c4eaa8f60711144621
/java-advanced/src/main/java/advanced/functional/lambda/functions/DemoFunctions.java
9cc040e0135b37cb26471d74254f62e6e84e4e1c
[]
no_license
rogers1235/new-project
fc42ca0f85c1a606a4196624088230338ddba496
b9df64b6f9e2924211fe70b80c8ab923624ec817
refs/heads/main
2023-08-04T08:28:18.018401
2021-09-16T20:22:38
2021-09-16T20:22:38
407,303,470
0
0
null
null
null
null
UTF-8
Java
false
false
310
java
package advanced.functional.lambda.functions; import java.util.HashMap; import java.util.Map; public class DemoFunctions { public static void main(String[] args) { Map<String, Integer> nameMap = new HashMap<>(); Integer value = nameMap.computeIfAbsent("John", s -> s.length()); } }
[ "craiova_2006@yahoo.it" ]
craiova_2006@yahoo.it
c3144a4cec1f9f91d804642cfb56ec6ac729916a
549fb15719a9849ce6957f983e2391afccc7933f
/oopsproject/src/oopsproject/Arthimetic.java
fb7c41a8d91287a6cc96cac813aeb7792fd00eb5
[]
no_license
SrujanaDuvvuri/java
653085d40614f58812e989e67a6367387c4ef6bd
21a5aeb2b542265fe9ae292e6947db04623e5cdc
refs/heads/master
2023-03-15T10:20:40.954648
2021-03-17T14:30:45
2021-03-17T14:30:45
348,737,378
0
0
null
null
null
null
UTF-8
Java
false
false
149
java
package oopsproject; public class Arthimetic implements IArthimetic { @Override public void sum(int a, int b) { System.out.println(a+b); } }
[ "suji.duvvuri@gmail.com" ]
suji.duvvuri@gmail.com
885374df5fc67b1aedaadd054801a6aa7841cb7c
5f10c20a65961c0cd2fc4a3db2e716efe746f6e5
/app/src/main/java/snow/app/eduhub/ui/adapter/ChatDetailAdapter.java
5ca6ce72dca1a1979d49e1780587400e6ce0ad62
[]
no_license
BrandonWilson78/EduhubCode
2e1187a549a19d7909e359058afb9276d78d838e
0caeeac09588d0e399ec6c6662a4d3d7e72c2bd8
refs/heads/master
2023-03-12T03:25:26.028041
2021-03-03T12:05:33
2021-03-03T12:05:33
344,112,521
0
0
null
null
null
null
UTF-8
Java
false
false
3,308
java
package snow.app.eduhub.ui.adapter; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import java.util.List; import snow.app.eduhub.R; import snow.app.eduhub.ui.network.responses.getallchats.Datum; import snow.app.eduhub.util.AppSession; public class ChatDetailAdapter extends RecyclerView.Adapter<ChatDetailAdapter.MyViewHolder> { Context context; private List<Datum> chatUserList; private AppSession mSession; public ChatDetailAdapter(List<Datum> dataList, Context context) { this.chatUserList = dataList; this.context = context; mSession = new AppSession(context); } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate( R.layout.chat_detail_row, parent, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { final Datum chatM = chatUserList.get(position); // if (chatM.getSender_image() != null) { // Picasso.get().load(chatM.getSender_image() ) // .transform(new CircleTransform()) // .into(holder.img_detail); // }else { // // } Log.wtf("id by ", "--" + chatM.getFromUserId() + "--id--userid-" + mSession.getAppData().getData().getId()); if (String.valueOf(mSession.getAppData().getData().getId()).equals(String.valueOf(chatM.getFromUserId()))) { holder.l1.setVisibility(View.GONE); holder.l2.setVisibility(View.VISIBLE); // holder.img_detail.setVisibility(View.GONE); holder.time1.setText(chatM.getCreated_date() +" "); holder.msg1.setText(chatM.getMessage()); holder.sender.setText(""); } else { holder.l2.setVisibility(View.GONE); holder.l1.setVisibility(View.VISIBLE); // holder.img_detail.setVisibility(View.VISIBLE); holder.time.setText(chatM.getCreated_date()); holder.msg.setText(chatM.getMessage()); holder.sender.setText(chatM.getToName()); } } @Override public int getItemCount() { return chatUserList.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { TextView msg; TextView msg1; ImageView img_detail; TextView sender; TextView time1; TextView time; LinearLayout l1; LinearLayout l2; public MyViewHolder(View view) { super(view); msg = view.findViewById(R.id.msg); msg1 = view.findViewById(R.id.msg1); time1 = view.findViewById(R.id.time1); time = view.findViewById(R.id.time); sender = view.findViewById(R.id.sender); // img_detail = view.findViewById(R.id.img_detail); l1 = view.findViewById(R.id.l1); l2 = view.findViewById(R.id.l2); } } }
[ "brandonwilson78@gmail.com" ]
brandonwilson78@gmail.com
bd488875be7553171d892738664da580a19f15f5
d1e2c306fb2e24f0fc09285864d918d2f8ce3e74
/src/com/lichen/guide/AboutApp.java
2cdd24ddd4a8a635fd09ca1276bd3432b60e6af1
[]
no_license
mhks/lichen-guide-android
230f891e17b09372816f28d9d70caec5a4508ced
b469fd8f512dfd07a1736afaa7b50775b9c019ea
refs/heads/master
2021-01-19T22:13:37.221039
2014-03-07T21:28:40
2014-03-07T21:28:40
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,821
java
package com.lichen.guide; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; public class AboutApp extends Activity { static Context context; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about_menu); } //creates menu for menu button @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.layout.about_menu_menu, menu); return true; } @Override // the menu options and their on selection functions public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu: ShowMainMenu(); break; case R.id.index: ShowLichenList(); break; case R.id.startkey: StartKey(); break; // case R.id.menu_glossary: GoGlossary(); // break; } return true; } //methods linking menu to other app pages protected void ShowMainMenu(){ Intent i = new Intent(this, Start.class); startActivity(i); } protected void ShowLichenList(){ Intent i = new Intent(this, IndexList.class); startActivity(i); } protected void StartKey(){ Intent i = new Intent(this, Key_Couplet1.class); startActivity(i); } /* protected void GoGlossary(){ Intent i = new Intent(this, GlossaryList.class); startActivity(i); } */ }
[ "hicmic25@gmail.com" ]
hicmic25@gmail.com
814930e9a519c701739cbd7ec8a4e9a80986cc1c
a0725964fa2a5be4e8aa4a2d50875d218359870e
/src/main/java/sample/rsa_keys/RsaKeyPairFileManager.java
e04ee413f7b77fe868d758a1ea11076fffa76a08
[]
no_license
piotrszymanski133/BSK
7dd01ee1d9fd9728a36544c07808726243318444
4e85cb34892cfcbd86095ab4beecfa2e9c102b20
refs/heads/main
2023-05-31T04:59:15.414199
2021-03-22T15:40:11
2021-03-22T15:40:11
348,780,284
0
0
null
null
null
null
UTF-8
Java
false
false
873
java
package sample.rsa_keys; import java.io.*; public class RsaKeyPairFileManager { private String path; public RsaKeyPairFileManager(String path) { this.path = path; } public void write(RsaKeyPairEncryptedByteData byteData) { try(FileOutputStream fo = new FileOutputStream(path); ObjectOutputStream oo = new ObjectOutputStream(fo)) { oo.writeObject(byteData); } catch(IOException ex) { ex.printStackTrace(); } } public RsaKeyPairEncryptedByteData read() { try(FileInputStream fi = new FileInputStream(path); ObjectInputStream oi = new ObjectInputStream(fi)) { return (RsaKeyPairEncryptedByteData) oi.readObject(); } catch(IOException | ClassNotFoundException ex) { ex.printStackTrace(); return null; } } }
[ "63449627+piotrszymanski133@users.noreply.github.com" ]
63449627+piotrszymanski133@users.noreply.github.com
3a5b99176b90ffdbb8fdf7a1b0b25ad0bf8380fb
fcddc7ba4cb546c10a4f8466104fffee932a41d4
/app/src/main/java/com/planetsystems/weqa/Administration/Time_Attendance/TimeAttendance.java
8afc07031c958c656a85a6d236b1bc998f835f7b
[]
no_license
andy-kajeke/tela
393fa48fa2d5a9eff489a3c1fb01c536cd5e524b
0c32afd762e081cc1c5bca90f8c2fb21898ee0f3
refs/heads/master
2021-03-11T20:41:46.975460
2020-03-11T12:00:16
2020-03-11T12:00:16
246,558,669
0
0
null
null
null
null
UTF-8
Java
false
false
4,218
java
package com.planetsystems.weqa.Administration.Time_Attendance; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import com.planetsystems.weqa.R; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; public class TimeAttendance extends AppCompatActivity { ListView lstView1; TextView datetoday; String HT_Id; String checkIn_date; String checkIn_schoolId; ArrayList<attendanceModel> markList; AttendanceAdapter adapter; private static final String empFirstName = "empFirstName"; private static final String empLastName = "empLastName"; private static final String employeeNo = "employeeNo"; private static final String clockInTime = "clockInTime"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_time_attendance); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); setTitle("Time Attendance"); lstView1 = (ListView)findViewById(R.id.card_listView); datetoday = (TextView)findViewById(R.id.datetoday); Date currentTime = Calendar.getInstance().getTime(); Bundle bundle = getIntent().getExtras(); HT_Id = bundle.getString("id"); checkIn_date = bundle.getString("date"); checkIn_schoolId = bundle.getString("school"); markList = new ArrayList<>(); //Toast.makeText(this, ""+markList.size() + " "+ checkIn_schoolId, Toast.LENGTH_SHORT).show(); adapter= new AttendanceAdapter(getApplicationContext(),R.layout.time_attendance_item, markList); lstView1.setAdapter(adapter); lstView1.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //Toast.makeText(getApplicationContext(),""+markList.get(position).getStatus(),Toast.LENGTH_SHORT).show(); Intent i = new Intent(getApplicationContext(), AdminConfirmation.class); i.putExtra("admin", HT_Id); i.putExtra("id",markList.get(position).getId()); i.putExtra("name",markList.get(position).getName()); startActivity(i); } }); DisplayClockedInEmployee(); } private void DisplayClockedInEmployee(){ SQLiteDatabase db = null; Cursor cursor = null; try{ db = openOrCreateDatabase("/data/data/" + getPackageName() + "/sqlitesync.db", Context.MODE_PRIVATE, null); cursor = db.rawQuery("select * from SyncClockIns WHERE clockInDate = " + "'"+checkIn_date+"'" + " AND schoolId = " + "'"+checkIn_schoolId+"'", null); //cursor = db.rawQuery("select * from SyncClockIns", null); while(cursor.moveToNext()) { attendanceModel mark_List = new attendanceModel(); mark_List.setId(cursor.getString(cursor.getColumnIndex(employeeNo))); mark_List.setName(cursor.getString(cursor.getColumnIndex(empFirstName)) +" "+ cursor.getString(cursor.getColumnIndex(empLastName))); mark_List.setClockIn(cursor.getString(cursor.getColumnIndex(clockInTime))); markList.add(mark_List); System.out.println("#######################"); System.out.println(mark_List); System.out.println("#######################"); //Toast.makeText(getApplicationContext(), dayOfTheWeek, Toast.LENGTH_LONG).show(); } } finally { if(cursor != null && !cursor.isClosed()){ cursor.close(); } if(db != null && db.isOpen()){ db.close(); } } } }
[ "akajeke@gmail.com" ]
akajeke@gmail.com
97126822440c59ebe37e4c603288e0a8143cebc7
e993c1a4cd5a5db2d2385ee70608cd23d397f5a6
/src/main/java/cn/com/study/controller/ParamController.java
41e80ad67f8b16708e67a8699bf6c99e659a0504
[]
no_license
yyl4ever/my-springmvc
6dc5031034dca6d730e6daea6ee4450cf3f1c6f1
7c0a051501764d45cdd99aac95b97d55c8c38f94
refs/heads/master
2022-12-23T11:29:57.338315
2019-11-19T09:01:43
2019-11-19T09:01:43
219,177,819
0
0
null
2022-12-15T23:44:51
2019-11-02T16:03:26
Java
UTF-8
Java
false
false
985
java
package cn.com.study.controller; import cn.com.study.domain.Account; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 测试参数绑定 * @Author: yangyl * @Date: 2019/11/2 23:42 */ @Controller @RequestMapping("/account") public class ParamController { @RequestMapping("/saveAccount") public String saveAccount(Account account) { System.out.println(account); return "success"; } @RequestMapping("/saveAccount2") public String saveAccount(Account account, HttpServletRequest request, HttpServletResponse response) { System.out.println(account); System.out.println(request); System.out.println(request.getSession()); // 最大的域对象 System.out.println(request.getSession().getServletContext()); return "success"; } }
[ "yyl4ever@foxmail.com" ]
yyl4ever@foxmail.com
c531835fd666f33e31ce4b5d08c35cdd96375909
cb906ff6b77f75ceca42d463eca0e11b2d5b31ea
/src/controller/Test2.java
0f4e9480468eb0a10d16827773b881449a07b3ac
[]
no_license
moranke/springmvc
8aaf3e6d027330f8d43c0bd434f2b8cbd9fa57e7
a904aea4081db95c60e0302f3645eeb8bbad16fd
refs/heads/master
2020-03-19T01:52:39.139155
2018-05-31T21:41:07
2018-05-31T21:41:07
135,556,717
0
0
null
null
null
null
UTF-8
Java
false
false
1,607
java
package controller; /** * Created by lvdia on 2018/5/26. */ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/rest") public class Test2 { private static final String SUCCESS = "success"; // 该方法接受POST传值,请求url为/rest/restPost @RequestMapping(value = "restPost", method = RequestMethod.POST) public String restPost(@RequestParam(value = "id") Integer id) { System.out.println("POST ID:" + id); return SUCCESS; } // 该方法接受GET传值,请求url为/rest/restGet @RequestMapping(value = "/restGet", method = RequestMethod.GET) public String restGet(@RequestParam(value = "id") Integer id) { System.out.println("GET ID:" + id); return SUCCESS; } // 该方法接受PUT传值,请求url为/rest/restPut @RequestMapping(value = "/restPut", method = RequestMethod.PUT) @ResponseBody public String restPut(@RequestParam(value = "id") Integer id) { System.out.println("PUT ID:" + id); return SUCCESS; } // 该方法接受DELETE传值,请求url为/rest/restDelete @RequestMapping(value="/restDelete",method=RequestMethod.DELETE) @ResponseBody public String restDelete(@RequestParam(value = "id") Integer id) { System.out.println("DELETE ID:" + id); return SUCCESS; } }
[ "ldk@keranst.com" ]
ldk@keranst.com
e9b672083bfe15f5880d5b1fed68a007afe0bf50
87f940687fe93eb11f082d90e2c3cef6bb794302
/src_ores/common/net/minecraft/src/betterore/common/util/BOCIStringMap.java
5447c1bc5d3b0a4cb22a6d8e930b960ba2f28e93
[]
no_license
BioLogisch/BiomesOPlentyBTWOld
1b071a26263c028fb376d1fe83ef0b1ad3331f15
e745c5d806983797fa2e3ea38346ed00c23051d0
refs/heads/master
2021-01-01T15:25:05.953783
2013-08-23T11:31:35
2013-08-23T11:31:35
12,138,443
3
1
null
null
null
null
UTF-8
Java
false
false
3,926
java
package net.minecraft.src.betterore.common.util; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Map.Entry; public class BOCIStringMap<V> implements Map<String,V> { protected final Map<String,V> backingMap; protected final Map<String,String> keyMap; public BOCIStringMap(Map<String,V> backingMap) { this.backingMap = backingMap; this.keyMap = new HashMap(); for (Entry<String,V> entry : backingMap.entrySet()) { String key = entry.getKey(); String ukey = this.uniformKey(key); if (this.keyMap.containsKey(ukey)) { throw new IllegalArgumentException("Backing set contains duplicate key \'" + key + "\'"); } this.keyMap.put(ukey, key); } } public BOCIStringMap() { this.backingMap = new HashMap(); this.keyMap = new HashMap(); } public int size() { return this.backingMap.size(); } public boolean isEmpty() { return this.backingMap.isEmpty(); } public boolean containsKey(Object key) { if (key != null) { String ukey = this.uniformKey((String)key); key = this.keyMap.get(ukey); if (key == null) { return false; } } return this.backingMap.containsKey(key); } public String getCanonicalKey(String key) { String ukey = this.uniformKey(key); return (String)this.keyMap.get(ukey); } public boolean containsValue(Object value) { return this.backingMap.containsValue(value); } public V get(Object key) { if (key != null) { String ukey = this.uniformKey((String)key); key = this.keyMap.get(ukey); if (key == null) { return null; } } return this.backingMap.get(key); } public V put(String key, V value) { if (key != null) { String ukey = this.uniformKey(key); String oldKey = this.keyMap.get(ukey); this.keyMap.put(ukey, key); if (oldKey != null) { V oldValue = this.backingMap.remove(oldKey); this.backingMap.put(key, value); return oldValue; } } return this.backingMap.put(key, value); } public V remove(Object key) { if (key != null) { String ukey = this.uniformKey((String)key); key = this.keyMap.remove(ukey); if (key == null) { return null; } } return this.backingMap.remove(key); } public void putAll(Map<? extends String,? extends V> map) { for (Entry<? extends String, ? extends V> entry : map.entrySet()) { this.put(entry.getKey(), entry.getValue()); } } public void clear() { this.keyMap.clear(); this.backingMap.clear(); } public Set<String> keySet() { return this.backingMap.keySet(); } public Collection<V> values() { return this.backingMap.values(); } public Set<Entry<String,V>> entrySet() { return this.backingMap.entrySet(); } public int hashCode() { return this.backingMap.hashCode(); } public boolean equals(Object obj) { return obj instanceof BOCIStringMap ? this.backingMap.equals(((BOCIStringMap)obj).backingMap) : false; } public String toString() { return this.backingMap.toString(); } protected String uniformKey(String rawKey) { return rawKey == null ? null : rawKey.toLowerCase(); } }
[ "s.yasargil@gmail.com" ]
s.yasargil@gmail.com
a3f54463dbb7cbcc4db807d1ee611326f2f7ed6e
2451da7e47f705c0719e9d35efeedbae747e2324
/litho-intellij-plugin/src/main/java/com/facebook/litho/intellij/actions/OnEventGenerateAction.java
be66a051b82e9e1ef8af268600af4d23c3447c02
[ "Apache-2.0" ]
permissive
naufalprakoso/litho
69d3a55fd6db2de44cf8e2a2ce50a5591651e3b1
1cb053683e8012c699a89ef73f359ec673673a53
refs/heads/master
2022-11-28T04:00:30.450425
2020-08-09T08:45:59
2020-08-09T08:45:59
286,190,495
0
0
Apache-2.0
2020-08-09T07:41:26
2020-08-09T07:41:25
null
UTF-8
Java
false
false
7,763
java
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho.intellij.actions; import com.facebook.litho.intellij.LithoPluginUtils; import com.facebook.litho.intellij.completion.OnEventGenerateUtils; import com.facebook.litho.intellij.extensions.EventLogger; import com.facebook.litho.intellij.logging.LithoLoggerProvider; import com.facebook.litho.intellij.services.ComponentGenerateService; import com.intellij.codeInsight.CodeInsightActionHandler; import com.intellij.codeInsight.generation.ClassMember; import com.intellij.codeInsight.generation.GenerateMembersHandlerBase; import com.intellij.codeInsight.generation.GenerationInfo; import com.intellij.codeInsight.generation.PsiGenerationInfo; import com.intellij.codeInsight.generation.PsiMethodMember; import com.intellij.codeInsight.generation.actions.BaseGenerateAction; import com.intellij.ide.util.TreeJavaClassChooserDialog; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiParameter; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.IncorrectOperationException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.jetbrains.annotations.NotNull; /** * Generates a method handling Litho event in the Litho Spec. * https://fblitho.com/docs/events-overview */ public class OnEventGenerateAction extends BaseGenerateAction { public interface EventChooser { PsiClass choose(PsiClass context, Project project); } @Nullable public interface OnEventRefactorer { PsiMethod changeSignature(Project project, PsiMethod originalOnEventMethod, PsiClass context); } public interface OnEventGeneratedListener { void onGenerated(PsiMethod onEvent); } public static CodeInsightActionHandler createHandler( EventChooser eventChooser, OnEventGeneratedListener onEventGeneratedListener) { return new OnEventGenerateHandler( eventChooser, (project, originalOnEventMethod, context) -> { if (ApplicationManager.getApplication().isUnitTestMode()) { return originalOnEventMethod; } final OnEventChangeSignatureDialog onEventMethodSignatureChooser = new OnEventChangeSignatureDialog(project, originalOnEventMethod, context); onEventMethodSignatureChooser.show(); return onEventMethodSignatureChooser.getMethod(); }, onEventGeneratedListener); } public OnEventGenerateAction() { super( createHandler( (context, project) -> { // Choose event to generate method for final TreeJavaClassChooserDialog chooseEventDialog = new TreeJavaClassChooserDialog( "Choose Event", project, GlobalSearchScope.allScope(project), LithoPluginUtils::isEvent, context /* Any initial class */); chooseEventDialog.show(); return chooseEventDialog.getSelected(); }, onEventMethod -> LithoLoggerProvider.getEventLogger() .log(EventLogger.EVENT_ON_EVENT_GENERATION + ".success"))); } @Override public void update(AnActionEvent e) { // Applies visibility of the Generate Action group super.update(e); final PsiFile file = e.getData(CommonDataKeys.PSI_FILE); if (!LithoPluginUtils.isLithoSpec(file)) { e.getPresentation().setEnabledAndVisible(false); } } @Override public void actionPerformed(AnActionEvent e) { LithoLoggerProvider.getEventLogger().log(EventLogger.EVENT_ON_EVENT_GENERATION + ".invoke"); super.actionPerformed(e); final PsiFile file = e.getData(CommonDataKeys.PSI_FILE); LithoPluginUtils.getFirstLayoutSpec(file) .ifPresent(cls -> ComponentGenerateService.getInstance().updateLayoutComponentAsync(cls)); } /** * Generates Litho event method. Prompts the user for additional data: choose Event class and * method signature customisation. * * @see com.facebook.litho.intellij.completion.MethodGenerateHandler */ static class OnEventGenerateHandler extends GenerateMembersHandlerBase { private final EventChooser eventChooser; private final OnEventGeneratedListener onEventGeneratedListener; private final OnEventRefactorer onEventRefactorer; OnEventGenerateHandler( EventChooser eventChooser, OnEventRefactorer onEventRefactorer, OnEventGeneratedListener onEventGeneratedListener) { super(""); this.eventChooser = eventChooser; this.onEventGeneratedListener = onEventGeneratedListener; this.onEventRefactorer = onEventRefactorer; } /** @return method based on user choice. */ @Override protected ClassMember[] chooseOriginalMembers(PsiClass aClass, Project project) { return Optional.ofNullable(eventChooser.choose(aClass, project)) .map( eventClass -> { final List<PsiParameter> propsAndStates = LithoPluginUtils.getPsiParameterStream(null, aClass.getMethods()) .filter(LithoPluginUtils::isPropOrState) .collect(Collectors.toList()); return OnEventGenerateUtils.createOnEventMethod(aClass, eventClass, propsAndStates); }) .map(onEventMethod -> onEventRefactorer.changeSignature(project, onEventMethod, aClass)) .map( customMethod -> { OnEventGenerateUtils.addComment(aClass, customMethod); onEventGeneratedListener.onGenerated(customMethod); return new ClassMember[] {new PsiMethodMember(customMethod)}; }) .orElse(ClassMember.EMPTY_ARRAY); } @Override protected GenerationInfo[] generateMemberPrototypes(PsiClass psiClass, ClassMember classMember) throws IncorrectOperationException { return generateMemberPrototypes(psiClass, new ClassMember[] {classMember}) .toArray(GenerationInfo.EMPTY_ARRAY); } /** @return a list of objects to insert into generated code. */ @NotNull @Override protected List<? extends GenerationInfo> generateMemberPrototypes( PsiClass aClass, ClassMember[] members) throws IncorrectOperationException { final List<GenerationInfo> prototypes = new ArrayList<>(); for (ClassMember member : members) { if (member instanceof PsiMethodMember) { PsiMethodMember methodMember = (PsiMethodMember) member; prototypes.add(new PsiGenerationInfo<>(methodMember.getElement())); } } return prototypes; } @Override protected ClassMember[] getAllOriginalMembers(PsiClass psiClass) { return ClassMember.EMPTY_ARRAY; } } }
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
03a7822ac457a2632b8151b9c8142dd95c1e39b4
c145cfb648da4b5dab1d0bf7ee7a49dbeba04fa4
/src/main/java/org/ahhn/com/dao/DepartmentDao.java
b0292d56583666c5c48c106b659c26d7c45ed600
[]
no_license
TianYunZi/Hibernate4-HqlQBC
af8e5e82e1a6754f2f6e061f0b3db517f7dda2b9
eea471083846d4e7122b33ab92f5a83a8e2e358a
refs/heads/master
2021-01-10T15:10:16.518680
2016-03-13T05:26:51
2016-03-13T05:26:51
53,720,701
0
0
null
null
null
null
UTF-8
Java
false
false
387
java
package org.ahhn.com.dao; import org.ahhn.com.entity.Department; import org.ahhn.com.utils.HibernateUtils; import org.hibernate.Session; /** * Created by XJX on 2016/3/13. */ public class DepartmentDao { public void save(Department department){ Session session= HibernateUtils.getInstance().getSession(); System.out.println(session.hashCode()); session.save(department); } }
[ "zxysegh@gmail.com" ]
zxysegh@gmail.com
dc0de15400b4c058634dfbc4a55d4bbc25b4bc18
38b8983b571cb5ce4a35d1a06a2e7e0a38cdd899
/sequence/src/main/java/com/demo/sequence/datasource/info/DataSourceInfo.java
af7aad944414efee7892be2ceaf725a23f67bc2c
[]
no_license
f3031150/dubbo-demo
a4c812e9420b359abb24860a37efe34a6e944476
e0f1f7b599c22264716fc371dcfd2739a9a4e8d8
refs/heads/master
2023-07-04T21:44:42.884839
2021-08-13T13:06:26
2021-08-13T13:06:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,334
java
package com.demo.sequence.datasource.info; import javax.sql.DataSource; import java.util.Objects; /** * @Author: xiuyin.cui@abite.com * @Date: 2018/11/05 */ public class DataSourceInfo { private int dataSourceNo; private boolean status; private DataSource dataSource; public DataSourceInfo(int dataSourceNo, boolean status, DataSource dataSource) { this.dataSourceNo = dataSourceNo; this.status = status; this.dataSource = dataSource; } public int getDataSourceNo() { return dataSourceNo; } public void setDataSourceNo(int dataSourceNo) { this.dataSourceNo = dataSourceNo; } public boolean getStatus() { return status; } public void setStatus(boolean status) { this.status = status; } public DataSource getDataSource() { return dataSource; } public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DataSourceInfo that = (DataSourceInfo) o; return dataSourceNo == that.dataSourceNo; } @Override public int hashCode() { return Objects.hash(dataSourceNo); } }
[ "1099442418@qq.com" ]
1099442418@qq.com
ce06f253c603041d37b37a3f0e8e946c2dd76e8e
eb03f417b90f986b0042794a4b5285efd7de0f8c
/app/src/main/java/com/chengxinping/infocity/wxapi/WXEntryActivity.java
5c5dbc1c723a664756ee67607c50b0fb01103645
[]
no_license
chengxinping/InfoCity
8d44936347c8ee58c13879ead4a0f419da252877
e03125bdc12af7fba694d7a12a46ae8f2d775b8e
refs/heads/master
2021-01-19T23:05:12.325304
2017-11-03T04:51:02
2017-11-03T04:51:02
83,782,954
0
0
null
null
null
null
UTF-8
Java
false
false
2,101
java
/* * 官网地站:http://www.mob.com * 技术支持QQ: 4006852216 * 官方微信:ShareSDK (如果发布新版本的话,我们将会第一时间通过微信将版本更新内容推送给您。如果使用过程中有任何问题,也可以通过微信与我们取得联系,我们将会在24小时内给予回复) * * Copyright (c) 2013年 mob.com. All rights reserved. */ package com.chengxinping.infocity.wxapi; import android.content.Intent; import android.widget.Toast; import cn.sharesdk.wechat.utils.WXAppExtendObject; import cn.sharesdk.wechat.utils.WXMediaMessage; import cn.sharesdk.wechat.utils.WechatHandlerActivity; /** 微信客户端回调activity示例 */ public class WXEntryActivity extends WechatHandlerActivity { /** * 处理微信发出的向第三方应用请求app message * <p> * 在微信客户端中的聊天页面有“添加工具”,可以将本应用的图标添加到其中 * 此后点击图标,下面的代码会被执行。Demo仅仅只是打开自己而已,但你可 * 做点其他的事情,包括根本不打开任何页面 */ public void onGetMessageFromWXReq(WXMediaMessage msg) { if (msg != null) { Intent iLaunchMyself = getPackageManager().getLaunchIntentForPackage(getPackageName()); startActivity(iLaunchMyself); } } /** * 处理微信向第三方应用发起的消息 * <p> * 此处用来接收从微信发送过来的消息,比方说本demo在wechatpage里面分享 * 应用时可以不分享应用文件,而分享一段应用的自定义信息。接受方的微信 * 客户端会通过这个方法,将这个信息发送回接收方手机上的本demo中,当作 * 回调。 * <p> * 本Demo只是将信息展示出来,但你可做点其他的事情,而不仅仅只是Toast */ public void onShowMessageFromWXReq(WXMediaMessage msg) { if (msg != null && msg.mediaObject != null && (msg.mediaObject instanceof WXAppExtendObject)) { WXAppExtendObject obj = (WXAppExtendObject) msg.mediaObject; Toast.makeText(this, obj.extInfo, Toast.LENGTH_SHORT).show(); } } }
[ "972649353@qq.com" ]
972649353@qq.com
7916e3df4c0b8a5de2a6af3ecad5489629913db7
065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be
/eclipsejdt_cluster/70567/src_0.java
efb6517cf1bbbf8267c0ae31cbeb955b4b9df595
[]
no_license
martinezmatias/GenPat-data-C3
63cfe27efee2946831139747e6c20cf952f1d6f6
b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4
refs/heads/master
2022-04-25T17:59:03.905613
2020-04-15T14:41:34
2020-04-15T14:41:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
71,630
java
/******************************************************************************* * Copyright (c) 2013, 2014 GK Software AG, and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Stephan Herrmann - initial API and implementation * IBM Corporation - Bug fixes *******************************************************************************/ package org.eclipse.jdt.internal.compiler.lookup; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.jdt.core.compiler.CharOperation; import org.eclipse.jdt.internal.compiler.ast.ConditionalExpression; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.FunctionalExpression; import org.eclipse.jdt.internal.compiler.ast.Invocation; import org.eclipse.jdt.internal.compiler.ast.LambdaExpression; import org.eclipse.jdt.internal.compiler.ast.ReferenceExpression; import org.eclipse.jdt.internal.compiler.ast.Wildcard; import org.eclipse.jdt.internal.compiler.util.Sorting; /** * Main class for new type inference as per JLS8 sect 18. * Keeps contextual state and drives the algorithm. * * <h2>Inference Basics</h2> * <ul> * <li>18.1.1 Inference variables: {@link InferenceVariable}</li> * <li>18.1.2 Constraint Formulas: subclasses of {@link ConstraintFormula}</li> * <li>18.1.3 Bounds: {@link TypeBound}<br/> * Capture bounds are directly captured in {@link BoundSet#captures}, throws-bounds in {@link BoundSet#inThrows}.<br/> * Also: {@link BoundSet}: main state during inference.</li> * </ul> * Each instance of {@link InferenceContext18} manages instances of the above and coordinates the inference process. * <h3>Queries and utilities</h3> * <ul> * <li>{@link TypeBinding#isProperType(boolean)}: * used to exclude "types" that mention inference variables (18.1.1).</li> * <li>{@link TypeBinding#mentionsAny(TypeBinding[], int)}: * does the receiver type binding mention any of the given types?</li> * <li>{@link TypeBinding#substituteInferenceVariable(InferenceVariable, TypeBinding)}: * replace occurrences of an inference variable with a proper type.</li> * <li>{@link TypeBinding#collectInferenceVariables(Set)}: * collect all inference variables mentioned in the receiver type into the given set.</li> * <li>{@link TypeVariableBinding#getTypeBounds(InferenceVariable, InferenceSubstitution)}: * Compute the initial type bounds for one inference variable as per JLS8 sect 18.1.3.</li> * </ul> * <h2>Phases of Inference</h2> * <ul> * <li>18.2 <b>Reduction</b>: {@link #reduce()} with most work happening in implementations of * {@link ConstraintFormula#reduce(InferenceContext18)}: * <ul> * <li>18.2.1 Expression Compatibility Constraints: {@link ConstraintExpressionFormula#reduce(InferenceContext18)}.</li> * <li>18.2.2 Type Compatibility Constraints ff. {@link ConstraintTypeFormula#reduce(InferenceContext18)}.</li> * </ul></li> * <li>18.3 <b>Incorporation</b>: {@link BoundSet#incorporate(InferenceContext18)}; during inference new constraints * are accepted via {@link BoundSet#reduceOneConstraint(InferenceContext18, ConstraintFormula)} (combining 18.2 & 18.3)</li> * <li>18.4 <b>Resolution</b>: {@link #resolve(InferenceVariable[])}. * </ul> * Some of the above operations accumulate their results into {@link #currentBounds}, whereas * the last phase <em>returns</em> the resulting bound set while keeping the previous state in {@link #currentBounds}. * <h2>18.5. Uses of Inference</h2> * These are the main entries from the compiler into the inference engine: * <dl> * <dt>18.5.1 Invocation Applicability Inference</dt> * <dd>{@link #inferInvocationApplicability(MethodBinding, TypeBinding[], boolean)}. Prepare the initial state for * inference of a generic invocation - no target type used at this point. * Need to call {@link #solve(boolean)} with true afterwards to produce the intermediate result.<br/> * Called indirectly from {@link Scope#findMethod(ReferenceBinding, char[], TypeBinding[], InvocationSite, boolean)} et al * to select applicable methods into overload resolution.</dd> * <dt>18.5.2 Invocation Type Inference</dt> * <dd>{@link InferenceContext18#inferInvocationType(TypeBinding, InvocationSite, MethodBinding)}. After a * most specific method has been picked, and given a target type determine the final generic instantiation. * As long as a target type is still unavailable this phase keeps getting deferred.</br> * Different wrappers exist for the convenience of different callers.</dd> * <dt>18.5.3 Functional Interface Parameterization Inference</dt> * <dd>Controlled from {@link LambdaExpression#resolveType(BlockScope)}.</dd> * <dt>18.5.4 More Specific Method Inference</dt> * <dd><em>Not Yet Implemented</em></dd> * </dl> * For 18.5.1 and 18.5.2 high-level control is implemented in * {@link ParameterizedGenericMethodBinding#computeCompatibleMethod(MethodBinding, TypeBinding[], Scope, InvocationSite)}. * <h2>Inference Lifecycle</h2> * <li>Decision whether or not an invocation is a <b>variable-arity</b> invocation is made by first attempting * to solve 18.5.1 in mode {@link #CHECK_LOOSE}. Only if that fails, another attempt is made in mode {@link #CHECK_VARARG}. * Which of these two attempts was successful is stored in {@link #inferenceKind}. * This field must be consulted whenever arguments of an invocation should be further processed. * See also {@link #getParameter(TypeBinding[], int, boolean)} and its clients.</li> * </ul> */ public class InferenceContext18 { /** to conform with javac regarding https://bugs.openjdk.java.net/browse/JDK-8026527 */ static final boolean SIMULATE_BUG_JDK_8026527 = true; /** Temporary workaround until we know fully what to do with https://bugs.openjdk.java.net/browse/JDK-8054721 * It looks likely that we have a bug independent of this JLS bug in that we clear the capture bounds eagerly. */ static final boolean SHOULD_WORKAROUND_BUG_JDK_8054721 = true; // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=437444#c24 onwards /** * Detail flag to control the extent of {@link #SIMULATE_BUG_JDK_8026527}. * A setting of 'false' implements the advice from http://mail.openjdk.java.net/pipermail/lambda-spec-experts/2013-December/000447.html * i.e., raw types are not considered as compatible in constraints/bounds derived from invocation arguments, * but only for constraints derived from type variable bounds. */ static final boolean ARGUMENT_CONSTRAINTS_ARE_SOFT = false; // --- Main State of the Inference: --- /** the invocation being inferred (for 18.5.1 and 18.5.2) */ InvocationSite currentInvocation; /** arguments of #currentInvocation, if any */ Expression[] invocationArguments; /** The inference variables for which as solution is sought. */ InferenceVariable[] inferenceVariables; /** Number of inference variables. */ int variableCount = 0; /** Constraints that have not yet been reduced and incorporated. */ ConstraintFormula[] initialConstraints; ConstraintExpressionFormula[] finalConstraints; // for final revalidation at a "macroscopic" level /** The accumulated type bounds etc. */ BoundSet currentBounds; /** One of CHECK_STRICT, CHECK_LOOSE, or CHECK_VARARGS. */ int inferenceKind; /** Marks how much work has been done so far? Used to avoid performing any of these tasks more than once. */ public int stepCompleted = NOT_INFERRED; public static final int NOT_INFERRED = 0; /** Applicability Inference (18.5.1) has been completed. */ public static final int APPLICABILITY_INFERRED = 1; /** Invocation Type Inference (18.5.2) has been completed (for some target type). */ public static final int TYPE_INFERRED = 2; /** Signals whether any type compatibility makes use of unchecked conversion. */ public List<ConstraintFormula> constraintsWithUncheckedConversion; public boolean usesUncheckedConversion; public InferenceContext18 outerContext; Scope scope; LookupEnvironment environment; ReferenceBinding object; // java.lang.Object public BoundSet b2; public static final int CHECK_UNKNOWN = 0; public static final int CHECK_STRICT = 1; public static final int CHECK_LOOSE = 2; public static final int CHECK_VARARG = 3; static class SuspendedInferenceRecord { InvocationSite site; Expression[] invocationArguments; InferenceVariable[] inferenceVariables; int inferenceKind; boolean usesUncheckedConversion; SuspendedInferenceRecord(InvocationSite site, Expression[] invocationArguments, InferenceVariable[] inferenceVariables, int inferenceKind, boolean usesUncheckedConversion) { this.site = site; this.invocationArguments = invocationArguments; this.inferenceVariables = inferenceVariables; this.inferenceKind = inferenceKind; this.usesUncheckedConversion = usesUncheckedConversion; } } /** Construct an inference context for an invocation (method/constructor). */ public InferenceContext18(Scope scope, Expression[] arguments, InvocationSite site, InferenceContext18 outerContext) { this.scope = scope; this.environment = scope.environment(); this.object = scope.getJavaLangObject(); this.invocationArguments = arguments; this.currentInvocation = site; this.outerContext = outerContext; } public InferenceContext18(Scope scope) { this.scope = scope; this.environment = scope.environment(); this.object = scope.getJavaLangObject(); } /** * JLS 18.1.3: Create initial bounds from a given set of type parameters declarations. * @return the set of inference variables created for the given typeParameters */ public InferenceVariable[] createInitialBoundSet(TypeVariableBinding[] typeParameters) { // if (this.currentBounds == null) { this.currentBounds = new BoundSet(); } if (typeParameters != null) { InferenceVariable[] newInferenceVariables = addInitialTypeVariableSubstitutions(typeParameters); this.currentBounds.addBoundsFromTypeParameters(this, typeParameters, newInferenceVariables); return newInferenceVariables; } return Binding.NO_INFERENCE_VARIABLES; } /** * Substitute any type variables mentioned in 'type' by the corresponding inference variable, if one exists. */ public TypeBinding substitute(TypeBinding type) { InferenceSubstitution inferenceSubstitution = new InferenceSubstitution(this.environment, this.inferenceVariables); return inferenceSubstitution.substitute(inferenceSubstitution, type); } /** JLS 18.5.1: compute bounds from formal and actual parameters. */ public void createInitialConstraintsForParameters(TypeBinding[] parameters, boolean checkVararg, TypeBinding varArgsType, MethodBinding method) { if (this.invocationArguments == null) return; int len = checkVararg ? parameters.length - 1 : Math.min(parameters.length, this.invocationArguments.length); int maxConstraints = checkVararg ? this.invocationArguments.length : len; int numConstraints = 0; boolean ownConstraints; if (this.initialConstraints == null) { this.initialConstraints = new ConstraintFormula[maxConstraints]; ownConstraints = true; } else { numConstraints = this.initialConstraints.length; maxConstraints += numConstraints; System.arraycopy(this.initialConstraints, 0, this.initialConstraints=new ConstraintFormula[maxConstraints], 0, numConstraints); ownConstraints = false; // these are lifted from a nested poly expression. } for (int i = 0; i < len; i++) { TypeBinding thetaF = substitute(parameters[i]); if (this.invocationArguments[i].isPertinentToApplicability(parameters[i], method)) { this.initialConstraints[numConstraints++] = new ConstraintExpressionFormula(this.invocationArguments[i], thetaF, ReductionResult.COMPATIBLE, ARGUMENT_CONSTRAINTS_ARE_SOFT); } else { if (!(parameters[i] instanceof TypeVariableBinding) || this.invocationArguments[i].isPertinentToApplicability(((TypeVariableBinding)parameters[i]), method)) this.initialConstraints[numConstraints++] = new ConstraintExpressionFormula(this.invocationArguments[i], thetaF, ReductionResult.POTENTIALLY_COMPATIBLE); // else we know it is potentially compatible, no need to assert. } } if (checkVararg && varArgsType instanceof ArrayBinding) { varArgsType = ((ArrayBinding)varArgsType).elementsType(); TypeBinding thetaF = substitute(varArgsType); for (int i = len; i < this.invocationArguments.length; i++) { if (this.invocationArguments[i].isPertinentToApplicability(varArgsType, method)) { this.initialConstraints[numConstraints++] = new ConstraintExpressionFormula(this.invocationArguments[i], thetaF, ReductionResult.COMPATIBLE, ARGUMENT_CONSTRAINTS_ARE_SOFT); } else { if (!(varArgsType instanceof TypeVariableBinding) || this.invocationArguments[i].isPertinentToApplicability(((TypeVariableBinding)varArgsType), method)) this.initialConstraints[numConstraints++] = new ConstraintExpressionFormula(this.invocationArguments[i], thetaF, ReductionResult.POTENTIALLY_COMPATIBLE); // else we know it is potentially compatible, no need to assert. } } } if (numConstraints == 0) this.initialConstraints = ConstraintFormula.NO_CONSTRAINTS; else if (numConstraints < maxConstraints) System.arraycopy(this.initialConstraints, 0, this.initialConstraints = new ConstraintFormula[numConstraints], 0, numConstraints); if (ownConstraints) { // lifted constraints get validated at their own context. final int length = this.initialConstraints.length; System.arraycopy(this.initialConstraints, 0, this.finalConstraints = new ConstraintExpressionFormula[length], 0, length); } } private InferenceVariable[] addInitialTypeVariableSubstitutions(TypeBinding[] typeVariables) { int len = typeVariables.length; if (len == 0) { if (this.inferenceVariables == null) this.inferenceVariables = Binding.NO_INFERENCE_VARIABLES; return Binding.NO_INFERENCE_VARIABLES; } InferenceVariable[] newVariables = new InferenceVariable[len]; for (int i = 0; i < len; i++) newVariables[i] = new InferenceVariable(typeVariables[i], this.variableCount++, this.currentInvocation, this.environment, this.object); if (this.inferenceVariables == null || this.inferenceVariables.length == 0) { this.inferenceVariables = newVariables; } else { // merge into this.inferenceVariables: int prev = this.inferenceVariables.length; System.arraycopy(this.inferenceVariables, 0, this.inferenceVariables = new InferenceVariable[len+prev], 0, prev); System.arraycopy(newVariables, 0, this.inferenceVariables, prev, len); } return newVariables; } /** Add new inference variables for the given type variables. */ public InferenceVariable[] addTypeVariableSubstitutions(TypeBinding[] typeVariables) { int len2 = typeVariables.length; InferenceVariable[] newVariables = new InferenceVariable[len2]; InferenceVariable[] toAdd = new InferenceVariable[len2]; int numToAdd = 0; for (int i = 0; i < typeVariables.length; i++) { if (typeVariables[i] instanceof InferenceVariable) newVariables[i] = (InferenceVariable) typeVariables[i]; // prevent double substitution of an already-substituted inferenceVariable else toAdd[numToAdd++] = newVariables[i] = new InferenceVariable(typeVariables[i], this.variableCount++, this.currentInvocation, this.environment, this.object); } if (numToAdd > 0) { int start = 0; if (this.inferenceVariables != null) { int len1 = this.inferenceVariables.length; System.arraycopy(this.inferenceVariables, 0, this.inferenceVariables = new InferenceVariable[len1+numToAdd], 0, len1); start = len1; } else { this.inferenceVariables = new InferenceVariable[numToAdd]; } System.arraycopy(toAdd, 0, this.inferenceVariables, start, numToAdd); } return newVariables; } /** JLS 18.1.3 Bounds: throws α: the inference variable α appears in a throws clause */ public void addThrowsContraints(TypeBinding[] parameters, InferenceVariable[] variables, ReferenceBinding[] thrownExceptions) { for (int i = 0; i < parameters.length; i++) { TypeBinding parameter = parameters[i]; for (int j = 0; j < thrownExceptions.length; j++) { if (TypeBinding.equalsEquals(parameter, thrownExceptions[j])) { this.currentBounds.inThrows.add(variables[i].prototype()); break; } } } } /** JLS 18.5.1 Invocation Applicability Inference. */ public void inferInvocationApplicability(MethodBinding method, TypeBinding[] arguments, boolean isDiamond) { ConstraintExpressionFormula.inferInvocationApplicability(this, method, arguments, isDiamond, this.inferenceKind); } /** JLS 18.5.2 Invocation Type Inference */ public BoundSet inferInvocationType(TypeBinding expectedType, InvocationSite invocationSite, MethodBinding method) throws InferenceFailureException { // not JLS: simply ensure that null hints from the return type have been seen even in standalone contexts: if (expectedType == null && method.returnType != null) substitute(method.returnType); // result is ignore, the only effect is on InferenceVariable.nullHints this.currentBounds = this.b2.copy(); try { // bullets 1&2: definitions only. if (expectedType != null && expectedType != TypeBinding.VOID && invocationSite instanceof Expression && ((Expression)invocationSite).isPolyExpression(method)) { // 3. bullet: special treatment for poly expressions if (!ConstraintExpressionFormula.inferPolyInvocationType(this, invocationSite, expectedType, method)) { return null; } } // 4. bullet: assemble C: Set<ConstraintFormula> c = new HashSet<ConstraintFormula>(); if (!addConstraintsToC(this.invocationArguments, c, method, this.inferenceKind, false)) return null; // 5. bullet: determine B4 from C while (!c.isEmpty()) { // * Set<ConstraintFormula> bottomSet = findBottomSet(c, allOutputVariables(c)); if (bottomSet.isEmpty()) { bottomSet.add(pickFromCycle(c)); } // * c.removeAll(bottomSet); // * The union of the input variables of all the selected constraints, α1, ..., αm, ... Set<InferenceVariable> allInputs = new HashSet<InferenceVariable>(); Iterator<ConstraintFormula> bottomIt = bottomSet.iterator(); while (bottomIt.hasNext()) { allInputs.addAll(bottomIt.next().inputVariables(this)); } InferenceVariable[] variablesArray = allInputs.toArray(new InferenceVariable[allInputs.size()]); // ... is resolved if (!this.currentBounds.incorporate(this)) return null; BoundSet solution = resolve(variablesArray); // in rare cases resolving just one set of variables doesn't suffice, // don't bother with finding the necessary superset, just resolve all: if (solution == null) solution = resolve(this.inferenceVariables); // * ~ apply substitutions to all constraints: bottomIt = bottomSet.iterator(); while (bottomIt.hasNext()) { ConstraintFormula constraint = bottomIt.next(); if (solution != null) if (!constraint.applySubstitution(solution, variablesArray)) return null; // * reduce and incorporate if (!this.currentBounds.reduceOneConstraint(this, constraint)) return null; } } // 6. bullet: solve BoundSet solution = solve(); if (solution == null || !isResolved(solution)) { this.currentBounds = this.b2; // don't let bounds from unsuccessful attempt leak into subsequent attempts return null; } // we're done, start reporting: reportUncheckedConversions(solution); return this.currentBounds = solution; // this is final, keep the result: } finally { this.stepCompleted = TYPE_INFERRED; } } private boolean addConstraintsToC(Expression[] exprs, Set<ConstraintFormula> c, MethodBinding method, int inferenceKindForMethod, boolean interleaved) throws InferenceFailureException { TypeBinding[] fs; if (exprs != null) { int k = exprs.length; int p = method.parameters.length; if (k < (method.isVarargs() ? p-1 : p)) return false; // insufficient arguments for parameters! switch (inferenceKindForMethod) { case CHECK_STRICT: case CHECK_LOOSE: fs = method.parameters; break; case CHECK_VARARG: fs = varArgTypes(method.parameters, k); break; default: throw new IllegalStateException("Unexpected checkKind "+this.inferenceKind); //$NON-NLS-1$ } for (int i = 0; i < k; i++) { TypeBinding fsi = fs[Math.min(i, p-1)]; TypeBinding substF = substitute(fsi); if (!addConstraintsToC_OneExpr(exprs[i], c, fsi, substF, method, interleaved)) return false; } } return true; } private boolean addConstraintsToC_OneExpr(Expression expri, Set<ConstraintFormula> c, TypeBinding fsi, TypeBinding substF, MethodBinding method, boolean interleaved) throws InferenceFailureException { // For all i (1 ≤ i ≤ k), if ei is not pertinent to applicability, the set contains ⟨ei → θ Fi⟩. if (!expri.isPertinentToApplicability(fsi, method)) { c.add(new ConstraintExpressionFormula(expri, substF, ReductionResult.COMPATIBLE, ARGUMENT_CONSTRAINTS_ARE_SOFT)); } if (expri instanceof FunctionalExpression) { c.add(new ConstraintExceptionFormula((FunctionalExpression) expri, substF)); if (expri instanceof LambdaExpression) { // https://bugs.openjdk.java.net/browse/JDK-8038747 LambdaExpression lambda = (LambdaExpression) expri; BlockScope skope = lambda.enclosingScope; if (substF.isFunctionalInterface(skope)) { // could be an inference variable. ReferenceBinding t = (ReferenceBinding) substF; ParameterizedTypeBinding withWildCards = InferenceContext18.parameterizedWithWildcard(t); if (withWildCards != null) { t = ConstraintExpressionFormula.findGroundTargetType(this, skope, lambda, withWildCards); } MethodBinding functionType; if (t != null && (functionType = t.getSingleAbstractMethod(skope, true)) != null && (lambda = lambda.resolveExpressionExpecting(t, this.scope, this)) != null) { TypeBinding r = functionType.returnType; Expression[] resultExpressions = lambda.resultExpressions(); for (int i = 0, length = resultExpressions == null ? 0 : resultExpressions.length; i < length; i++) { Expression resultExpression = resultExpressions[i]; if (!addConstraintsToC_OneExpr(resultExpression, c, r.original(), r, method, true)) return false; } } } } } else if (expri instanceof Invocation && expri.isPolyExpression()) { if (substF.isProperType(true)) // https://bugs.openjdk.java.net/browse/JDK-8052325 return true; Invocation invocation = (Invocation) expri; MethodBinding innerMethod = invocation.binding(); if (innerMethod == null) return true; // -> proceed with no new C set elements. Expression[] arguments = invocation.arguments(); TypeBinding[] argumentTypes = arguments == null ? Binding.NO_PARAMETERS : new TypeBinding[arguments.length]; for (int i = 0; i < argumentTypes.length; i++) argumentTypes[i] = arguments[i].resolvedType; int applicabilityKind; InferenceContext18 innerContext = null; if (innerMethod instanceof ParameterizedGenericMethodBinding) innerContext = invocation.getInferenceContext((ParameterizedGenericMethodBinding) innerMethod); applicabilityKind = innerContext != null ? innerContext.inferenceKind : getInferenceKind(innerMethod, argumentTypes); if (interleaved) { MethodBinding shallowMethod = innerMethod.shallowOriginal(); SuspendedInferenceRecord prevInvocation = enterPolyInvocation(invocation, arguments); try { this.inferenceKind = applicabilityKind; if (innerContext != null) innerContext.outerContext = this; inferInvocationApplicability(shallowMethod, argumentTypes, shallowMethod.isConstructor()); if (!ConstraintExpressionFormula.inferPolyInvocationType(this, invocation, substF, shallowMethod)) return false; } finally { resumeSuspendedInference(prevInvocation); } } return addConstraintsToC(arguments, c, innerMethod.genericMethod(), applicabilityKind, interleaved); } else if (expri instanceof ConditionalExpression) { ConditionalExpression ce = (ConditionalExpression) expri; return addConstraintsToC_OneExpr(ce.valueIfTrue, c, fsi, substF, method, interleaved) && addConstraintsToC_OneExpr(ce.valueIfFalse, c, fsi, substF, method, interleaved); } return true; } protected int getInferenceKind(MethodBinding nonGenericMethod, TypeBinding[] argumentTypes) { switch (this.scope.parameterCompatibilityLevel(nonGenericMethod, argumentTypes)) { case Scope.AUTOBOX_COMPATIBLE: return CHECK_LOOSE; case Scope.VARARGS_COMPATIBLE: return CHECK_VARARG; default: return CHECK_STRICT; } } /** * 18.5.3 Functional Interface Parameterization Inference */ public ReferenceBinding inferFunctionalInterfaceParameterization(LambdaExpression lambda, BlockScope blockScope, ParameterizedTypeBinding targetTypeWithWildCards) { TypeBinding[] q = createBoundsForFunctionalInterfaceParameterizationInference(targetTypeWithWildCards); if (q == null || q.length != lambda.arguments().length) { // fail TODO: can this still happen here? } else { if (reduceWithEqualityConstraints(lambda.argumentTypes(), q)) { ReferenceBinding genericType = targetTypeWithWildCards.genericType(); TypeBinding[] a = targetTypeWithWildCards.arguments; // a is not-null by construction of parameterizedWithWildcard() TypeBinding[] aprime = getFunctionInterfaceArgumentSolutions(a); // TODO If F<A'1, ..., A'm> is a well-formed type, ... return blockScope.environment().createParameterizedType(genericType, aprime, targetTypeWithWildCards.enclosingType()); } } return targetTypeWithWildCards; } /** * Create initial bound set for 18.5.3 Functional Interface Parameterization Inference * @param functionalInterface the functional interface F<A1,..Am> * @return the parameter types Q1..Qk of the function type of the type F<α1, ..., αm>, or null */ TypeBinding[] createBoundsForFunctionalInterfaceParameterizationInference(ParameterizedTypeBinding functionalInterface) { if (this.currentBounds == null) this.currentBounds = new BoundSet(); TypeBinding[] a = functionalInterface.arguments; if (a == null) return null; InferenceVariable[] alpha = addInitialTypeVariableSubstitutions(a); for (int i = 0; i < a.length; i++) { TypeBound bound; if (a[i].kind() == Binding.WILDCARD_TYPE) { WildcardBinding wildcard = (WildcardBinding) a[i]; switch(wildcard.boundKind) { case Wildcard.EXTENDS : bound = new TypeBound(alpha[i], wildcard.allBounds(), ReductionResult.SUBTYPE); break; case Wildcard.SUPER : bound = new TypeBound(alpha[i], wildcard.bound, ReductionResult.SUPERTYPE); break; case Wildcard.UNBOUND : bound = new TypeBound(alpha[i], this.object, ReductionResult.SUBTYPE); break; default: continue; // cannot } } else { bound = new TypeBound(alpha[i], a[i], ReductionResult.SAME); } this.currentBounds.addBound(bound, this.environment); } TypeBinding falpha = substitute(functionalInterface); return falpha.getSingleAbstractMethod(this.scope, true).parameters; } public boolean reduceWithEqualityConstraints(TypeBinding[] p, TypeBinding[] q) { if (p != null) { for (int i = 0; i < p.length; i++) { try { if (!this.reduceAndIncorporate(ConstraintTypeFormula.create(p[i], q[i], ReductionResult.SAME))) return false; } catch (InferenceFailureException e) { return false; } } } return true; } /** * 18.5.4 More Specific Method Inference */ public boolean isMoreSpecificThan(MethodBinding m1, MethodBinding m2, boolean isVarArgs, boolean isVarArgs2) { // TODO: we don't yet distinguish vararg-with-passthrough from vararg-with-exactly-one-vararg-arg if (isVarArgs != isVarArgs2) { return isVarArgs2; } Expression[] arguments = this.invocationArguments; int numInvocArgs = arguments == null ? 0 : arguments.length; TypeVariableBinding[] p = m2.typeVariables(); TypeBinding[] s = m1.parameters; TypeBinding[] t = new TypeBinding[m2.parameters.length]; createInitialBoundSet(p); for (int i = 0; i < t.length; i++) t[i] = substitute(m2.parameters[i]); try { for (int i = 0; i < numInvocArgs; i++) { TypeBinding si = getParameter(s, i, isVarArgs); TypeBinding ti = getParameter(t, i, isVarArgs); Boolean result = moreSpecificMain(si, ti, this.invocationArguments[i]); if (result == Boolean.FALSE) return false; if (result == null) if (!reduceAndIncorporate(ConstraintTypeFormula.create(si, ti, ReductionResult.SUBTYPE))) return false; } if (t.length == numInvocArgs + 1) { TypeBinding skplus1 = getParameter(s, numInvocArgs, true); TypeBinding tkplus1 = getParameter(t, numInvocArgs, true); if (!reduceAndIncorporate(ConstraintTypeFormula.create(skplus1, tkplus1, ReductionResult.SUBTYPE))) return false; } return solve() != null; } catch (InferenceFailureException e) { return false; } } // FALSE: inference fails // TRUE: constraints have been incorporated // null: need the otherwise branch private Boolean moreSpecificMain(TypeBinding si, TypeBinding ti, Expression expri) throws InferenceFailureException { if (si.isProperType(true) && ti.isProperType(true)) { return expri.sIsMoreSpecific(si, ti, this.scope) ? Boolean.TRUE : Boolean.FALSE; } if (si.isFunctionalInterface(this.scope)) { TypeBinding funcI = ti.original(); if (funcI.isFunctionalInterface(this.scope)) { // "... none of the following is true:" if (siSuperI(si, funcI) || siSubI(si, funcI)) return null; if (si instanceof IntersectionTypeBinding18) { TypeBinding[] elements = ((IntersectionTypeBinding18)si).intersectingTypes; checkSuper: { for (int i = 0; i < elements.length; i++) if (!siSuperI(elements[i], funcI)) break checkSuper; return null; // each element of the intersection is a superinterface of I, or a parameterization of a superinterface of I. } for (int i = 0; i < elements.length; i++) if (siSubI(elements[i], funcI)) return null; // some element of the intersection is a subinterface of I, or a parameterization of a subinterface of I. } // all passed, time to do some work: TypeBinding siCapture = si.capture(this.scope, expri.sourceStart, expri.sourceEnd); MethodBinding sam = siCapture.getSingleAbstractMethod(this.scope, false); // no wildcards should be left needing replacement TypeBinding[] u = sam.parameters; TypeBinding r1 = sam.isConstructor() ? sam.declaringClass : sam.returnType; sam = ti.getSingleAbstractMethod(this.scope, true); // TODO TypeBinding[] v = sam.parameters; TypeBinding r2 = sam.isConstructor() ? sam.declaringClass : sam.returnType; return Boolean.valueOf(checkExpression(expri, u, r1, v, r2)); } } return null; } private boolean checkExpression(Expression expri, TypeBinding[] u, TypeBinding r1, TypeBinding[] v, TypeBinding r2) throws InferenceFailureException { if (expri instanceof LambdaExpression && !((LambdaExpression)expri).argumentsTypeElided()) { if (r2.id == TypeIds.T_void) return true; LambdaExpression lambda = (LambdaExpression) expri; Expression[] results = lambda.resultExpressions(); if (r1.isFunctionalInterface(this.scope) && r2.isFunctionalInterface(this.scope) && !(r1.isCompatibleWith(r2) || r2.isCompatibleWith(r1))) { // "these rules are applied recursively to R1 and R2, for each result expression in expi." // (what does "applied .. to R1 and R2" mean? Why mention R1/R2 and not U/V?) for (int i = 0; i < results.length; i++) { if (!checkExpression(results[i], u, r1, v, r2)) return false; } return true; } checkPrimitive1: if (r1.isPrimitiveType() && !r2.isPrimitiveType()) { // check: each result expression is a standalone expression of a primitive type for (int i = 0; i < results.length; i++) { if (results[i].isPolyExpression() || (results[i].resolvedType != null && !results[i].resolvedType.isPrimitiveType())) break checkPrimitive1; } return true; } checkPrimitive2: if (r2.isPrimitiveType() && !r1.isPrimitiveType()) { for (int i = 0; i < results.length; i++) { // for all expressions (not for any expression not) if (!( (!results[i].isPolyExpression() && (results[i].resolvedType != null && !results[i].resolvedType.isPrimitiveType())) // standalone of a referencetype || results[i].isPolyExpression())) // or a poly break checkPrimitive2; } return true; } return reduceAndIncorporate(ConstraintTypeFormula.create(r1, r2, ReductionResult.SUBTYPE)); } else if (expri instanceof ReferenceExpression && ((ReferenceExpression)expri).isExactMethodReference()) { ReferenceExpression reference = (ReferenceExpression) expri; for (int i = 0; i < u.length; i++) { if (!reduceAndIncorporate(ConstraintTypeFormula.create(u[i], v[i], ReductionResult.SAME))) return false; } if (r2.id == TypeIds.T_void) return true; MethodBinding method = reference.getExactMethod(); TypeBinding returnType = method.isConstructor() ? method.declaringClass : method.returnType; if (r1.isPrimitiveType() && !r2.isPrimitiveType() && returnType.isPrimitiveType()) return true; if (r2.isPrimitiveType() && !r1.isPrimitiveType() && !returnType.isPrimitiveType()) return true; return reduceAndIncorporate(ConstraintTypeFormula.create(r1, r2, ReductionResult.SUBTYPE)); } else if (expri instanceof ConditionalExpression) { ConditionalExpression cond = (ConditionalExpression) expri; return checkExpression(cond.valueIfTrue, u, r1, v, r2) && checkExpression(cond.valueIfFalse, u, r1, v, r2); } else { return false; } } private boolean siSuperI(TypeBinding si, TypeBinding funcI) { if (TypeBinding.equalsEquals(si, funcI) || TypeBinding.equalsEquals(si.original(), funcI)) return true; TypeBinding[] superIfcs = funcI.superInterfaces(); if (superIfcs == null) return false; for (int i = 0; i < superIfcs.length; i++) { if (siSuperI(si, superIfcs[i])) return true; } return false; } private boolean siSubI(TypeBinding si, TypeBinding funcI) { if (TypeBinding.equalsEquals(si, funcI) || TypeBinding.equalsEquals(si.original(), funcI)) return true; TypeBinding[] superIfcs = si.superInterfaces(); if (superIfcs == null) return false; for (int i = 0; i < superIfcs.length; i++) { if (siSubI(superIfcs[i], funcI)) return true; } return false; } // ========== Below this point: implementation of the generic algorithm: ========== /** * Try to solve the inference problem defined by constraints and bounds previously registered. * @return a bound set representing the solution, or null if inference failed * @throws InferenceFailureException a compile error has been detected during inference */ public /*@Nullable*/ BoundSet solve(boolean inferringApplicability) throws InferenceFailureException { if (!reduce()) return null; if (!this.currentBounds.incorporate(this)) return null; if (inferringApplicability) this.b2 = this.currentBounds.copy(); // Preserve the result after reduction, without effects of resolve() for later use in invocation type inference. BoundSet solution = resolve(this.inferenceVariables); /* If inferring applicability make a final pass over the initial constraints preserved as final constraints to make sure they hold true at a macroscopic level. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=426537#c55 onwards. */ if (inferringApplicability && solution != null && this.finalConstraints != null) { for (ConstraintExpressionFormula constraint: this.finalConstraints) { if (constraint.left.isPolyExpression()) continue; // avoid redundant re-inference, inner poly's own constraints get validated in its own context & poly invocation type inference proved compatibility against target. constraint.applySubstitution(solution, this.inferenceVariables); if (!this.currentBounds.reduceOneConstraint(this, constraint)) { return null; } } } return solution; } public /*@Nullable*/ BoundSet solve() throws InferenceFailureException { return solve(false); } public /*@Nullable*/ BoundSet solve(InferenceVariable[] toResolve) throws InferenceFailureException { if (!reduce()) return null; if (!this.currentBounds.incorporate(this)) return null; return resolve(toResolve); } /** * JLS 18.2. reduce all initial constraints * @throws InferenceFailureException */ private boolean reduce() throws InferenceFailureException { // Caution: This can be reentered recursively even as an earlier call is munching through the constraints ! for (int i = 0; this.initialConstraints != null && i < this.initialConstraints.length; i++) { final ConstraintFormula currentConstraint = this.initialConstraints[i]; if (currentConstraint == null) continue; this.initialConstraints[i] = null; if (!this.currentBounds.reduceOneConstraint(this, currentConstraint)) return false; } this.initialConstraints = null; return true; } /** * Have all inference variables been instantiated successfully? */ public boolean isResolved(BoundSet boundSet) { if (this.inferenceVariables != null) { for (int i = 0; i < this.inferenceVariables.length; i++) { if (!boundSet.isInstantiated(this.inferenceVariables[i])) return false; } } return true; } /** * Retrieve the resolved solutions for all given type variables. * @param typeParameters * @param boundSet where instantiations are to be found * @return array containing the substituted types or <code>null</code> elements for any type variable that could not be substituted. */ public TypeBinding /*@Nullable*/[] getSolutions(TypeVariableBinding[] typeParameters, InvocationSite site, BoundSet boundSet) { int len = typeParameters.length; TypeBinding[] substitutions = new TypeBinding[len]; InferenceVariable[] outerVariables = null; if (this.outerContext != null && this.outerContext.stepCompleted < TYPE_INFERRED) outerVariables = this.outerContext.inferenceVariables; for (int i = 0; i < typeParameters.length; i++) { for (int j = 0; j < this.inferenceVariables.length; j++) { InferenceVariable variable = this.inferenceVariables[j]; if (variable.site == site && TypeBinding.equalsEquals(variable.typeParameter, typeParameters[i])) { TypeBinding outerVar = null; if (outerVariables != null && (outerVar = boundSet.getEquivalentOuterVariable(variable, outerVariables)) != null) substitutions[i] = outerVar; else substitutions[i] = boundSet.getInstantiation(variable, this.environment); break; } } if (substitutions[i] == null) return null; } return substitutions; } /** When inference produces a new constraint, reduce it to a suitable type bound and add the latter to the bound set. */ public boolean reduceAndIncorporate(ConstraintFormula constraint) throws InferenceFailureException { return this.currentBounds.reduceOneConstraint(this, constraint); // TODO(SH): should we immediately call a diat incorporate, or can we simply wait for the next round? } /** * <b>JLS 18.4</b> Resolution * @return answer null if some constraint resolved to FALSE, otherwise the boundset representing the solution * @throws InferenceFailureException */ private /*@Nullable*/ BoundSet resolve(InferenceVariable[] toResolve) throws InferenceFailureException { this.captureId = 0; // NOTE: 18.5.2 ... // "(While it was necessary to demonstrate that the inference variables in B1 could be resolved // in order to establish applicability, the resulting instantiations are not considered part of B1.) // For this reason, resolve works on a temporary bound set, copied before any modification. BoundSet tmpBoundSet = this.currentBounds; if (this.inferenceVariables != null) { // find a minimal set of dependent variables: Set<InferenceVariable> variableSet; while ((variableSet = getSmallestVariableSet(tmpBoundSet, toResolve)) != null) { int oldNumUninstantiated = tmpBoundSet.numUninstantiatedVariables(this.inferenceVariables); final int numVars = variableSet.size(); if (numVars > 0) { final InferenceVariable[] variables = variableSet.toArray(new InferenceVariable[numVars]); variables: if (!tmpBoundSet.hasCaptureBound(variableSet)) { // try to instantiate this set of variables in a fresh copy of the bound set: BoundSet prevBoundSet = tmpBoundSet; tmpBoundSet = tmpBoundSet.copy(); for (int j = 0; j < variables.length; j++) { InferenceVariable variable = variables[j]; // try lower bounds: TypeBinding[] lowerBounds = tmpBoundSet.lowerBounds(variable, true/*onlyProper*/); if (lowerBounds != Binding.NO_TYPES) { TypeBinding lub = this.scope.lowerUpperBound(lowerBounds); if (lub == TypeBinding.VOID || lub == null) return null; tmpBoundSet.addBound(new TypeBound(variable, lub, ReductionResult.SAME), this.environment); } else { TypeBinding[] upperBounds = tmpBoundSet.upperBounds(variable, true/*onlyProper*/); // check exception bounds: if (tmpBoundSet.inThrows.contains(variable.prototype()) && tmpBoundSet.hasOnlyTrivialExceptionBounds(variable, upperBounds)) { TypeBinding runtimeException = this.scope.getType(TypeConstants.JAVA_LANG_RUNTIMEEXCEPTION, 3); tmpBoundSet.addBound(new TypeBound(variable, runtimeException, ReductionResult.SAME), this.environment); } else { // try upper bounds: TypeBinding glb = this.object; if (upperBounds != Binding.NO_TYPES) { if (upperBounds.length == 1) { glb = upperBounds[0]; } else { ReferenceBinding[] glbs = Scope.greaterLowerBound((ReferenceBinding[])upperBounds); if (glbs == null) { throw new UnsupportedOperationException("no glb for "+Arrays.asList(upperBounds)); //$NON-NLS-1$ } else if (glbs.length == 1) { glb = glbs[0]; } else { IntersectionTypeBinding18 intersection = (IntersectionTypeBinding18) this.environment.createIntersectionType18(glbs); if (!ReferenceBinding.isConsistentIntersection(intersection.intersectingTypes)) { tmpBoundSet = prevBoundSet; // clean up break variables; // and start over } glb = intersection; } } } tmpBoundSet.addBound(new TypeBound(variable, glb, ReductionResult.SAME), this.environment); } } } if (tmpBoundSet.incorporate(this)) continue; tmpBoundSet = prevBoundSet;// clean-up for second attempt } // Otherwise, a second attempt is made... Sorting.sortInferenceVariables(variables); // ensure stability of capture IDs final CaptureBinding18[] zs = new CaptureBinding18[numVars]; for (int j = 0; j < numVars; j++) zs[j] = freshCapture(variables[j]); final BoundSet kurrentBoundSet = tmpBoundSet; Substitution theta = new Substitution() { public LookupEnvironment environment() { return InferenceContext18.this.environment; } public boolean isRawSubstitution() { return false; } public TypeBinding substitute(TypeVariableBinding typeVariable) { for (int j = 0; j < numVars; j++) if (TypeBinding.equalsEquals(variables[j], typeVariable)) return zs[j]; /* If we have an instantiation, lower it to the instantiation. We don't want downstream abstractions to be confused about multiple versions of bounds without and with instantiations propagated by incorporation. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=430686. There is no value whatsoever in continuing to speak in two tongues. Also fixes https://bugs.eclipse.org/bugs/show_bug.cgi?id=425031. */ if (typeVariable instanceof InferenceVariable) { InferenceVariable inferenceVariable = (InferenceVariable) typeVariable; TypeBinding instantiation = kurrentBoundSet.getInstantiation(inferenceVariable, null); if (instantiation != null) return instantiation; } return typeVariable; } }; for (int j = 0; j < numVars; j++) { InferenceVariable variable = variables[j]; CaptureBinding18 zsj = zs[j]; // add lower bounds: TypeBinding[] lowerBounds = tmpBoundSet.lowerBounds(variable, true/*onlyProper*/); if (lowerBounds != Binding.NO_TYPES) { TypeBinding lub = this.scope.lowerUpperBound(lowerBounds); if (lub != TypeBinding.VOID && lub != null) zsj.lowerBound = lub; } // add upper bounds: TypeBinding[] upperBounds = tmpBoundSet.upperBounds(variable, false/*onlyProper*/); if (upperBounds != Binding.NO_TYPES) { for (int k = 0; k < upperBounds.length; k++) upperBounds[k] = Scope.substitute(theta, upperBounds[k]); if (!setUpperBounds(zsj, upperBounds)) continue; // at violation of well-formedness skip this candidate and proceed } if (tmpBoundSet == this.currentBounds) tmpBoundSet = tmpBoundSet.copy(); Iterator<ParameterizedTypeBinding> captureKeys = tmpBoundSet.captures.keySet().iterator(); Set<ParameterizedTypeBinding> toRemove = new HashSet<ParameterizedTypeBinding>(); while (captureKeys.hasNext()) { ParameterizedTypeBinding key = captureKeys.next(); int len = key.arguments.length; for (int i = 0; i < len; i++) { if (TypeBinding.equalsEquals(key.arguments[i], variable)) { toRemove.add(key); break; } } } captureKeys = toRemove.iterator(); while (captureKeys.hasNext()) tmpBoundSet.captures.remove(captureKeys.next()); tmpBoundSet.addBound(new TypeBound(variable, zsj, ReductionResult.SAME), this.environment); } if (tmpBoundSet.incorporate(this)) { if (tmpBoundSet.numUninstantiatedVariables(this.inferenceVariables) == oldNumUninstantiated) return null; // abort because we made no progress continue; } return null; } } } return tmpBoundSet; } int captureId = 0; /** For 18.4: "Let Z1, ..., Zn be fresh type variables" use capture bindings. */ private CaptureBinding18 freshCapture(InferenceVariable variable) { int id = this.captureId++; char[] sourceName = CharOperation.concat("Z".toCharArray(), '#', String.valueOf(id).toCharArray(), '-', variable.sourceName); //$NON-NLS-1$ int start = this.currentInvocation != null ? this.currentInvocation.sourceStart() : 0; int end = this.currentInvocation != null ? this.currentInvocation.sourceEnd() : 0; return new CaptureBinding18(this.scope.enclosingSourceType(), sourceName, variable.typeParameter.shortReadableName(), start, end, id, this.environment); } // === === private boolean setUpperBounds(CaptureBinding18 typeVariable, TypeBinding[] substitutedUpperBounds) { // 18.4: ... define the upper bound of Zi as glb(L1θ, ..., Lkθ) if (substitutedUpperBounds.length == 1) { typeVariable.setUpperBounds(substitutedUpperBounds, this.object); // shortcut } else { TypeBinding[] glbs = Scope.greaterLowerBound(substitutedUpperBounds, this.scope, this.environment); if (glbs == null) return false; if (typeVariable.lowerBound != null) { for (int i = 0; i < glbs.length; i++) { if (!typeVariable.lowerBound.isCompatibleWith(glbs[i])) return false; // not well-formed } } // for deterministic results sort this array by id: sortTypes(glbs); if (!typeVariable.setUpperBounds(glbs, this.object)) return false; } return true; } static void sortTypes(TypeBinding[] types) { Arrays.sort(types, new Comparator<TypeBinding>() { public int compare(TypeBinding o1, TypeBinding o2) { int i1 = o1.id, i2 = o2.id; return (i1<i2 ? -1 : (i1==i2 ? 0 : 1)); } }); } /** * Find the smallest set of uninstantiated inference variables not depending * on any uninstantiated variable outside the set. */ private Set<InferenceVariable> getSmallestVariableSet(BoundSet bounds, InferenceVariable[] subSet) { int min = Integer.MAX_VALUE; Set<InferenceVariable> result = null; for (int i = 0; i < subSet.length; i++) { InferenceVariable currentVariable = subSet[i]; if (!bounds.isInstantiated(currentVariable)) { Set<InferenceVariable> set = new HashSet<InferenceVariable>(); if (!addDependencies(bounds, set, currentVariable, min)) continue; int cur = set.size(); if (cur == 1) return set; // won't get smaller if (cur < min) { result = set; min = cur; } } } return result; } private boolean addDependencies(BoundSet boundSet, Set<InferenceVariable> variableSet, InferenceVariable currentVariable, int min) { if (variableSet.size() >= min) return false; // no improvement if (boundSet.isInstantiated(currentVariable)) return true; // not added if (!variableSet.add(currentVariable)) return true; // already present for (int j = 0; j < this.inferenceVariables.length; j++) { InferenceVariable nextVariable = this.inferenceVariables[j]; if (TypeBinding.equalsEquals(nextVariable, currentVariable)) continue; if (boundSet.dependsOnResolutionOf(currentVariable, nextVariable)) if (!addDependencies(boundSet, variableSet, nextVariable, min)) return false; // abort traversal: no improvement } return true; } private ConstraintFormula pickFromCycle(Set<ConstraintFormula> c) { // Detail from 18.5.2 bullet 6.1 // Note on performance: this implementation could quite possibly be optimized a lot. // However, we only *very rarely* reach here, // so nobody should really be affected by the performance penalty paid here. // Note on spec conformance: the spec seems to require _all_ criteria (i)-(iv) to be fulfilled // with the sole exception of (iii), which should only be used, if _any_ constraints matching (i) & (ii) // also fulfill this condition. // Experiments, however, show that strict application of the above is prone to failing to pick any constraint, // causing non-termination of the algorithm. // Since that is not acceptable, I'm *interpreting* the spec to request a search for a constraint // that "best matches" the given conditions. // collect all constraints participating in a cycle HashMap<ConstraintFormula,Set<ConstraintFormula>> dependencies = new HashMap<ConstraintFormula, Set<ConstraintFormula>>(); Set<ConstraintFormula> cycles = new HashSet<ConstraintFormula>(); for (ConstraintFormula constraint : c) { Collection<InferenceVariable> infVars = constraint.inputVariables(this); for (ConstraintFormula other : c) { if (other == constraint) continue; if (dependsOn(infVars, other.outputVariables(this))) { // found a dependency, record it: Set<ConstraintFormula> targetSet = dependencies.get(constraint); if (targetSet == null) dependencies.put(constraint, targetSet = new HashSet<ConstraintFormula>()); targetSet.add(other); // look for a cycle: Set<ConstraintFormula> nodesInCycle = new HashSet<ConstraintFormula>(); if (isReachable(dependencies, other, constraint, new HashSet<ConstraintFormula>(), nodesInCycle)) { // found a cycle, record the involved nodes: cycles.addAll(nodesInCycle); } } } } Set<ConstraintFormula> outside = new HashSet<ConstraintFormula>(c); outside.removeAll(cycles); Set<ConstraintFormula> candidatesII = new HashSet<ConstraintFormula>(); // (i): participates in a cycle: candidates: for (ConstraintFormula candidate : cycles) { Collection<InferenceVariable> infVars = candidate.inputVariables(this); // (ii) does not depend on any constraints outside the cycle for (ConstraintFormula out : outside) { if (dependsOn(infVars, out.outputVariables(this))) continue candidates; } candidatesII.add(candidate); } if (candidatesII.isEmpty()) candidatesII = c; // not spec'ed but needed to avoid returning null below, witness: java.util.stream.Collectors // tentatively: (iii) has the form ⟨Expression → T⟩ Set<ConstraintFormula> candidatesIII = new HashSet<ConstraintFormula>(); for (ConstraintFormula candidate : candidatesII) { if (candidate instanceof ConstraintExpressionFormula) candidatesIII.add(candidate); } if (candidatesIII.isEmpty()) { candidatesIII = candidatesII; // no constraint fulfills (iii) -> ignore this condition } else { // candidatesIII contains all relevant constraints ⟨Expression → T⟩ // (iv) contains an expression that appears to the left of the expression // of every other constraint satisfying the previous three requirements // collect containment info regarding all expressions in candidate constraints: // (a) find minimal enclosing expressions: Map<ConstraintExpressionFormula,ConstraintExpressionFormula> expressionContainedBy = new HashMap<ConstraintExpressionFormula, ConstraintExpressionFormula>(); for (ConstraintFormula one : candidatesIII) { ConstraintExpressionFormula oneCEF = (ConstraintExpressionFormula) one; Expression exprOne = oneCEF.left; for (ConstraintFormula two : candidatesIII) { if (one == two) continue; ConstraintExpressionFormula twoCEF = (ConstraintExpressionFormula) two; Expression exprTwo = twoCEF.left; if (doesExpressionContain(exprOne, exprTwo)) { ConstraintExpressionFormula previous = expressionContainedBy.get(two); if (previous == null || doesExpressionContain(previous.left, exprOne)) // only if improving expressionContainedBy.put(twoCEF, oneCEF); } } } // (b) build the tree from the above Map<ConstraintExpressionFormula,Set<ConstraintExpressionFormula>> containmentForest = new HashMap<ConstraintExpressionFormula, Set<ConstraintExpressionFormula>>(); for (Map.Entry<ConstraintExpressionFormula, ConstraintExpressionFormula> parentRelation : expressionContainedBy.entrySet()) { ConstraintExpressionFormula parent = parentRelation.getValue(); Set<ConstraintExpressionFormula> children = containmentForest.get(parent); if (children == null) containmentForest.put(parent, children = new HashSet<ConstraintExpressionFormula>()); children.add(parentRelation.getKey()); } // approximate the spec by searching the largest containment tree: int bestRank = -1; ConstraintExpressionFormula candidate = null; for (ConstraintExpressionFormula parent : containmentForest.keySet()) { int rank = rankNode(parent, expressionContainedBy, containmentForest); if (rank > bestRank) { bestRank = rank; candidate = parent; } } if (candidate != null) return candidate; } if (candidatesIII.isEmpty()) throw new IllegalStateException("cannot pick constraint from cyclic set"); //$NON-NLS-1$ return candidatesIII.iterator().next(); } /** * Does the first constraint depend on the other? * The first constraint is represented by its input variables and the other constraint by its output variables. */ private boolean dependsOn(Collection<InferenceVariable> inputsOfFirst, Collection<InferenceVariable> outputsOfOther) { for (InferenceVariable iv : inputsOfFirst) { for (InferenceVariable otherIV : outputsOfOther) if (this.currentBounds.dependsOnResolutionOf(iv, otherIV)) return true; } return false; } /** Does 'deps' contain a chain of dependencies leading from 'from' to 'to'? */ private boolean isReachable(Map<ConstraintFormula,Set<ConstraintFormula>> deps, ConstraintFormula from, ConstraintFormula to, Set<ConstraintFormula> nodesVisited, Set<ConstraintFormula> nodesInCycle) { if (from == to) { nodesInCycle.add(from); return true; } if (!nodesVisited.add(from)) return false; Set<ConstraintFormula> targetSet = deps.get(from); if (targetSet != null) { for (ConstraintFormula tgt : targetSet) { if (isReachable(deps, tgt, to, nodesVisited, nodesInCycle)) { nodesInCycle.add(from); return true; } } } return false; } /** Does exprOne lexically contain exprTwo? */ private boolean doesExpressionContain(Expression exprOne, Expression exprTwo) { if (exprTwo.sourceStart > exprOne.sourceStart) { return exprTwo.sourceEnd <= exprOne.sourceEnd; } else if (exprTwo.sourceStart == exprOne.sourceStart) { return exprTwo.sourceEnd < exprOne.sourceEnd; } return false; } /** non-roots answer -1, roots answer the size of the spanned tree */ private int rankNode(ConstraintExpressionFormula parent, Map<ConstraintExpressionFormula,ConstraintExpressionFormula> expressionContainedBy, Map<ConstraintExpressionFormula, Set<ConstraintExpressionFormula>> containmentForest) { if (expressionContainedBy.get(parent) != null) return -1; // not a root Set<ConstraintExpressionFormula> children = containmentForest.get(parent); if (children == null) return 1; // unconnected node or leaf int sum = 1; for (ConstraintExpressionFormula child : children) { int cRank = rankNode(child, expressionContainedBy, containmentForest); if (cRank > 0) sum += cRank; } return sum; } private Set<ConstraintFormula> findBottomSet(Set<ConstraintFormula> constraints, Set<InferenceVariable> allOutputVariables) { // 18.5.2 bullet 6.1 // A subset of constraints is selected, satisfying the property // that, for each constraint, no input variable depends on an // output variable of another constraint in C ... Set<ConstraintFormula> result = new HashSet<ConstraintFormula>(); Iterator<ConstraintFormula> it = constraints.iterator(); constraintLoop: while (it.hasNext()) { ConstraintFormula constraint = it.next(); Iterator<InferenceVariable> inputIt = constraint.inputVariables(this).iterator(); Iterator<InferenceVariable> outputIt = allOutputVariables.iterator(); while (inputIt.hasNext()) { InferenceVariable in = inputIt.next(); if (allOutputVariables.contains(in)) // not explicit in the spec, but let's assume any inference variable depends on itself continue constraintLoop; while (outputIt.hasNext()) { if (this.currentBounds.dependsOnResolutionOf(in, outputIt.next())) continue constraintLoop; } } result.add(constraint); } return result; } Set<InferenceVariable> allOutputVariables(Set<ConstraintFormula> constraints) { Set<InferenceVariable> result = new HashSet<InferenceVariable>(); Iterator<ConstraintFormula> it = constraints.iterator(); while (it.hasNext()) { result.addAll(it.next().outputVariables(this)); } return result; } private TypeBinding[] varArgTypes(TypeBinding[] parameters, int k) { TypeBinding[] types = new TypeBinding[k]; int declaredLength = parameters.length-1; System.arraycopy(parameters, 0, types, 0, declaredLength); TypeBinding last = ((ArrayBinding)parameters[declaredLength]).elementsType(); for (int i = declaredLength; i < k; i++) types[i] = last; return types; } public SuspendedInferenceRecord enterPolyInvocation(InvocationSite invocation, Expression[] innerArguments) { SuspendedInferenceRecord record = new SuspendedInferenceRecord(this.currentInvocation, this.invocationArguments, this.inferenceVariables, this.inferenceKind, this.usesUncheckedConversion); this.inferenceVariables = null; this.invocationArguments = innerArguments; this.currentInvocation = invocation; this.usesUncheckedConversion = false; return record; } public SuspendedInferenceRecord enterLambda(LambdaExpression lambda) { SuspendedInferenceRecord record = new SuspendedInferenceRecord(this.currentInvocation, this.invocationArguments, this.inferenceVariables, this.inferenceKind, this.usesUncheckedConversion); this.inferenceVariables = null; this.invocationArguments = null; this.currentInvocation = null; this.usesUncheckedConversion = false; return record; } public void resumeSuspendedInference(SuspendedInferenceRecord record) { // merge inference variables: if (this.inferenceVariables == null) { // no new ones, assume we aborted prematurely this.inferenceVariables = record.inferenceVariables; } else { int l1 = this.inferenceVariables.length; int l2 = record.inferenceVariables.length; // move to back, add previous to front: System.arraycopy(this.inferenceVariables, 0, this.inferenceVariables=new InferenceVariable[l1+l2], l2, l1); System.arraycopy(record.inferenceVariables, 0, this.inferenceVariables, 0, l2); } // replace invocation site & arguments: this.currentInvocation = record.site; this.invocationArguments = record.invocationArguments; this.inferenceKind = record.inferenceKind; this.usesUncheckedConversion = record.usesUncheckedConversion; } private Substitution getResultSubstitution(final BoundSet result) { return new Substitution() { public LookupEnvironment environment() { return InferenceContext18.this.environment; } public boolean isRawSubstitution() { return false; } public TypeBinding substitute(TypeVariableBinding typeVariable) { if (typeVariable instanceof InferenceVariable) { return result.getInstantiation((InferenceVariable) typeVariable, InferenceContext18.this.environment); } return typeVariable; } }; } public boolean isVarArgs() { return this.inferenceKind == CHECK_VARARG; } /** * Retrieve the rank'th parameter, possibly respecting varargs invocation, see 15.12.2.4. * Returns null if out of bounds and CHECK_VARARG was not requested. * Precondition: isVarArgs implies method.isVarargs() */ public static TypeBinding getParameter(TypeBinding[] parameters, int rank, boolean isVarArgs) { if (isVarArgs) { if (rank >= parameters.length-1) return ((ArrayBinding)parameters[parameters.length-1]).elementsType(); } else if (rank >= parameters.length) { return null; } return parameters[rank]; } /** * Create a problem method signaling failure of invocation type inference, * unless the given candidate is tolerable to be compatible with buggy javac. */ public MethodBinding getReturnProblemMethodIfNeeded(TypeBinding expectedType, MethodBinding method) { if (InferenceContext18.SIMULATE_BUG_JDK_8026527 && expectedType != null && method.returnType instanceof ReferenceBinding) { if (method.returnType.erasure().isCompatibleWith(expectedType)) return method; // don't count as problem. } /* We used to check if expected type is null and if so return method, but that is wrong - it injects an incompatible method into overload resolution. if we get here with expected type set to null at all, the target context does not define a target type (vanilla context), so inference has done its best and nothing more to do than to signal error. */ ProblemMethodBinding problemMethod = new ProblemMethodBinding(method, method.selector, method.parameters, ProblemReasons.InvocationTypeInferenceFailure); problemMethod.returnType = expectedType; problemMethod.inferenceContext = this; return problemMethod; } // debugging: public String toString() { StringBuffer buf = new StringBuffer("Inference Context"); //$NON-NLS-1$ switch (this.stepCompleted) { case NOT_INFERRED: buf.append(" (initial)");break; //$NON-NLS-1$ case APPLICABILITY_INFERRED: buf.append(" (applicability inferred)");break; //$NON-NLS-1$ case TYPE_INFERRED: buf.append(" (type inferred)");break; //$NON-NLS-1$ } switch (this.inferenceKind) { case CHECK_STRICT: buf.append(" (strict)");break; //$NON-NLS-1$ case CHECK_LOOSE: buf.append(" (loose)");break; //$NON-NLS-1$ case CHECK_VARARG: buf.append(" (vararg)");break; //$NON-NLS-1$ } if (this.currentBounds != null && isResolved(this.currentBounds)) buf.append(" (resolved)"); //$NON-NLS-1$ buf.append('\n'); if (this.inferenceVariables != null) { buf.append("Inference Variables:\n"); //$NON-NLS-1$ for (int i = 0; i < this.inferenceVariables.length; i++) { buf.append('\t').append(this.inferenceVariables[i].sourceName).append("\t:\t"); //$NON-NLS-1$ if (this.currentBounds != null && this.currentBounds.isInstantiated(this.inferenceVariables[i])) buf.append(this.currentBounds.getInstantiation(this.inferenceVariables[i], this.environment).readableName()); else buf.append("NOT INSTANTIATED"); //$NON-NLS-1$ buf.append('\n'); } } if (this.initialConstraints != null) { buf.append("Initial Constraints:\n"); //$NON-NLS-1$ for (int i = 0; i < this.initialConstraints.length; i++) if (this.initialConstraints[i] != null) buf.append('\t').append(this.initialConstraints[i].toString()).append('\n'); } if (this.currentBounds != null) buf.append(this.currentBounds.toString()); return buf.toString(); } /** * If 'type' is a parameterized type and one of its arguments is a wildcard answer the casted type, else null. * A nonnull answer is ensured to also have nonnull arguments. */ public static ParameterizedTypeBinding parameterizedWithWildcard(TypeBinding type) { if (type == null || type.kind() != Binding.PARAMETERIZED_TYPE) return null; ParameterizedTypeBinding parameterizedType = (ParameterizedTypeBinding) type; TypeBinding[] arguments = parameterizedType.arguments; if (arguments != null) { for (int i = 0; i < arguments.length; i++) if (arguments[i].isWildcard()) return parameterizedType; } return null; } public TypeBinding[] getFunctionInterfaceArgumentSolutions(TypeBinding[] a) { int m = a.length; TypeBinding[] aprime = new TypeBinding[m]; for (int i = 0; i < this.inferenceVariables.length; i++) { InferenceVariable alphai = this.inferenceVariables[i]; TypeBinding t = this.currentBounds.getInstantiation(alphai, this.environment); if (t != null) aprime[i] = t; else aprime[i] = a[i]; } return aprime; } /** Record the fact that the given constraint requires unchecked conversion. */ public void recordUncheckedConversion(ConstraintTypeFormula constraint) { if (this.constraintsWithUncheckedConversion == null) this.constraintsWithUncheckedConversion = new ArrayList<ConstraintFormula>(); this.constraintsWithUncheckedConversion.add(constraint); this.usesUncheckedConversion = true; } void reportUncheckedConversions(BoundSet solution) { if (this.constraintsWithUncheckedConversion != null) { int len = this.constraintsWithUncheckedConversion.size(); Substitution substitution = getResultSubstitution(solution); for (int i = 0; i < len; i++) { ConstraintTypeFormula constraint = (ConstraintTypeFormula) this.constraintsWithUncheckedConversion.get(i); TypeBinding expectedType = constraint.right; TypeBinding providedType = constraint.left; if (!expectedType.isProperType(true)) { expectedType = Scope.substitute(substitution, expectedType); } if (!providedType.isProperType(true)) { providedType = Scope.substitute(substitution, providedType); } /* FIXME(stephan): enable once we solved: (a) avoid duplication with traditional reporting (b) improve location to report against if (this.currentInvocation instanceof Expression) this.scope.problemReporter().unsafeTypeConversion((Expression) this.currentInvocation, providedType, expectedType); */ } } } /** For use by 15.12.2.6 Method Invocation Type */ public boolean usesUncheckedConversion() { return this.constraintsWithUncheckedConversion != null; } // INTERIM: infrastructure for detecting failures caused by specific known incompleteness: public static void missingImplementation(String msg) { throw new UnsupportedOperationException(msg); } public void forwardResults(BoundSet result, Invocation invocation, ParameterizedMethodBinding pmb, TypeBinding targetType) { if (targetType != null) invocation.registerResult(targetType, pmb); Expression[] arguments = invocation.arguments(); for (int i = 0, length = arguments == null ? 0 : arguments.length; i < length; i++) { Expression [] expressions = arguments[i].getPolyExpressions(); for (int j = 0, jLength = expressions.length; j < jLength; j++) { Expression expression = expressions[j]; if (!(expression instanceof Invocation)) continue; Invocation polyInvocation = (Invocation) expression; MethodBinding binding = polyInvocation.binding(); if (binding == null || !binding.isValidBinding()) continue; ParameterizedMethodBinding methodSubstitute = null; if (binding instanceof ParameterizedGenericMethodBinding) { MethodBinding shallowOriginal = binding.shallowOriginal(); TypeBinding[] solutions = getSolutions(shallowOriginal.typeVariables(), polyInvocation, result); if (solutions == null) // in CEF.reduce, we lift inner poly expressions into outer context only if their target type has inference variables. continue; methodSubstitute = this.environment.createParameterizedGenericMethod(shallowOriginal, solutions); } else { if (!binding.isConstructor() || !(binding instanceof ParameterizedMethodBinding)) continue; // throw ISE ? MethodBinding shallowOriginal = binding.shallowOriginal(); ReferenceBinding genericType = shallowOriginal.declaringClass; TypeBinding[] solutions = getSolutions(genericType.typeVariables(), polyInvocation, result); if (solutions == null) // in CEF.reduce, we lift inner poly expressions into outer context only if their target type has inference variables. continue; ParameterizedTypeBinding parameterizedType = this.environment.createParameterizedType(genericType, solutions, binding.declaringClass.enclosingType()); for (MethodBinding parameterizedMethod : parameterizedType.methods()) { if (parameterizedMethod.original() == shallowOriginal) { methodSubstitute = (ParameterizedMethodBinding) parameterizedMethod; break; } } } if (methodSubstitute == null || !methodSubstitute.isValidBinding()) continue; boolean variableArity = pmb.isVarargs(); final TypeBinding[] parameters = pmb.parameters; if (variableArity && parameters.length == arguments.length && i == length - 1) { TypeBinding returnType = methodSubstitute.returnType.capture(this.scope, expression.sourceStart, expression.sourceEnd); if (returnType.isCompatibleWith(parameters[parameters.length - 1], this.scope)) { variableArity = false; } } TypeBinding parameterType = InferenceContext18.getParameter(parameters, i, variableArity); forwardResults(result, polyInvocation, methodSubstitute, parameterType); } } } }
[ "375833274@qq.com" ]
375833274@qq.com
3eec258a0a3b946869cdfc32fdc53e5a70e3c684
3acf27d878aef9349ce4d41b5be5aec263217f14
/source/sisgepws/src/br/gov/iphan/sisgep/ws/ArrayOfDadosAfastamentoPorCpf.java
2a452803c12b71f52fae86c87df25a276fe93f87
[]
no_license
ronaldodornelles/gitflow
5fecbab3f3ada399f31377a49b1332b0b8d73464
db16af6d8a56eef3c10910a0a8c7e969251ec0dd
refs/heads/master
2021-01-23T05:44:50.331689
2017-05-31T20:04:52
2017-05-31T20:04:52
92,983,914
0
0
null
null
null
null
UTF-8
Java
false
false
2,229
java
package br.gov.iphan.sisgep.ws; 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.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ArrayOfDadosAfastamentoPorCpf complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ArrayOfDadosAfastamentoPorCpf"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="DadosAfastamentoPorCpf" type="{http://tipo.servico.wssiapenet}DadosAfastamentoPorCpf" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ArrayOfDadosAfastamentoPorCpf", propOrder = { "dadosAfastamentoPorCpf" }) public class ArrayOfDadosAfastamentoPorCpf { @XmlElement(name = "DadosAfastamentoPorCpf", nillable = true) protected List<DadosAfastamentoPorCpf> dadosAfastamentoPorCpf; /** * Gets the value of the dadosAfastamentoPorCpf 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 dadosAfastamentoPorCpf property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDadosAfastamentoPorCpf().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DadosAfastamentoPorCpf } * * */ public List<DadosAfastamentoPorCpf> getDadosAfastamentoPorCpf() { if (dadosAfastamentoPorCpf == null) { dadosAfastamentoPorCpf = new ArrayList<DadosAfastamentoPorCpf>(); } return this.dadosAfastamentoPorCpf; } }
[ "ronaldolima@FLNNOTFS021750.local" ]
ronaldolima@FLNNOTFS021750.local
ba8d307d74f045446ba7fbfa012e87e343ae927d
875d88ee9cf7b40c9712178d1ee48f0080fa0f8a
/geronimo-jpa_2.2_spec/src/main/java/javax/persistence/metamodel/EmbeddableType.java
34798acbae90f3177d9b1a7ecb2e63e1fe246cdd
[ "Apache-2.0", "W3C", "W3C-19980720" ]
permissive
jgallimore/geronimo-specs
b152164488692a7e824c73a9ba53e6fb72c6a7a3
09c09bcfc1050d60dcb4656029e957837f851857
refs/heads/trunk
2022-12-15T14:02:09.338370
2020-09-14T18:21:46
2020-09-14T18:21:46
284,994,475
0
1
Apache-2.0
2020-09-14T18:21:47
2020-08-04T13:51:47
Java
UTF-8
Java
false
false
1,109
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. */ // // This source code implements specifications defined by the Java // Community Process. In order to remain compliant with the specification // DO NOT add / change / or delete method signatures! // package javax.persistence.metamodel; public interface EmbeddableType<X> extends ManagedType<X> {}
[ "struberg@apache.org" ]
struberg@apache.org
f08eade687fb9fd55d2372badc2274494192ca18
bdd1a2aed8d8e1448f7129acdfa43133e7f86b4b
/src/main/java/urlshortener/bangladeshgreen/NotificationQueue/NotificationPeriodicCheck.java
226b73b3b66d85d0a767ccb2946ef54e6317a540
[ "Apache-2.0" ]
permissive
WallaTeam/WallaLinks
555074fe78d072e6ba4b642b5877debac6553894
71bfcaf6a9a14925f8790b9f8ef1ba69466cec9f
refs/heads/master
2020-05-29T12:30:57.610962
2016-01-15T16:34:26
2016-01-15T16:34:26
49,730,634
0
0
null
null
null
null
UTF-8
Java
false
false
2,709
java
package urlshortener.bangladeshgreen.NotificationQueue; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import urlshortener.bangladeshgreen.domain.*; import urlshortener.bangladeshgreen.repository.*; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Class for periodic check of the shorten URIs * It's scheduled and when it runs, obtains all the outdated links from the DB, checking all again. * It checks the URIs by inserting again the URIs in the queue. */ public class NotificationPeriodicCheck { // Interval that sets when a URI has to be checked again (1/4 h) @Autowired private RabbitTemplate rabbitTemplate; @Autowired private NotifyDisableRepository notifyDisableRepository; @Autowired private URIAvailableRepository availableRepository; @Autowired private ShortURLRepository shortURLRepository; @Autowired private NotifyRepository notifyRepository; @Autowired private UserRepository userRepository; @Autowired private URIDisabledRepository disabledRepository; // One hour of delay (for checking "all" URIs) @Scheduled(fixedDelay = 180000L) public void send() { // All users List<String> users = new ArrayList<String>(); List<User> us = userRepository.findAll(); List<URIAvailable> changes = availableRepository.findByChange(true); List<ShortURL> urls = new ArrayList<ShortURL>(); List<URIDisabled> disableds = new ArrayList<URIDisabled>(); // For all AvailableURI wich have a change, save all URLShort with the same target List<String> usersSend = new ArrayList<String>(); List<Notify> not = notifyRepository.findAll(); List<NotifyDisable> notd = notifyDisableRepository.findAll(); if (changes.size() >0) { for (User user: us) { urls = shortURLRepository.findByCreator(user.getUsername()); disableds = disabledRepository.findByCreator(user.getUsername()); for (URIAvailable x : changes) { for(ShortURL a: urls) { if (a.getTarget().compareTo(x.getTarget()) == 0) { Notify ab = new Notify(x.getTarget(), user.getUsername()); notifyRepository.save(ab); } } } for (URIAvailable z : changes) { for(URIDisabled n: disableds){ if(n.getTarget().compareTo(z.getTarget())==0){ NotifyDisable ab = new NotifyDisable(n.getHash(), z.getTarget()); NotifyDisable abc = notifyDisableRepository.findByHash(n.getHash()); if(abc == null){ notifyDisableRepository.save(ab); } } } } this.rabbitTemplate.convertAndSend("notificationQueue", user.getUsername()); } } } }
[ "raul.piraces@gmail.com" ]
raul.piraces@gmail.com
514c9815016fe2f1624f21c2ad8f888d520a6e02
8c3b1fc6c478a49807f643e4b3c72bb97c39022b
/SkosShopper/src/Skos/SkosBrowser/org/coode/owl/mngr/impl/OWLServerImpl.java
695b305c871df9cb2ec5b255c224fb0eb212ae3a
[ "Apache-2.0" ]
permissive
VRage/SkosShopper
3572bb771167bf65fea18fbc5f884390c5340592
cb4987e7120e750d3a6c923d7986e5595d75cdfc
refs/heads/master
2021-01-15T21:09:56.855291
2014-12-22T19:15:35
2014-12-22T19:15:35
null
0
0
null
null
null
null
UTF-8
Java
false
false
18,645
java
package Skos.SkosBrowser.org.coode.owl.mngr.impl; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.semanticweb.owlapi.apibinding.OWLManager; import org.semanticweb.owlapi.expression.OWLEntityChecker; import org.semanticweb.owlapi.expression.ShortFormEntityChecker; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLAnnotationProperty; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLDataProperty; import org.semanticweb.owlapi.model.OWLEntity; import org.semanticweb.owlapi.model.OWLImportsDeclaration; import org.semanticweb.owlapi.model.OWLObject; import org.semanticweb.owlapi.model.OWLObjectProperty; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import org.semanticweb.owlapi.model.OWLOntologyIRIMapper; import org.semanticweb.owlapi.model.OWLOntologyManager; import org.semanticweb.owlapi.model.OWLOntologySetProvider; import org.semanticweb.owlapi.model.OWLOntologyStorageException; import org.semanticweb.owlapi.reasoner.InferenceType; import org.semanticweb.owlapi.reasoner.OWLReasoner; import org.semanticweb.owlapi.util.AnnotationValueShortFormProvider; import org.semanticweb.owlapi.util.CachingBidirectionalShortFormProvider; import org.semanticweb.owlapi.util.NonMappingOntologyIRIMapper; import org.semanticweb.owlapi.util.OntologyIRIShortFormProvider; import org.semanticweb.owlapi.util.ReferencedEntitySetProvider; import org.semanticweb.owlapi.util.ShortFormProvider; import org.semanticweb.owlapi.util.SimpleIRIMapper; import org.semanticweb.owlapi.util.SimpleShortFormProvider; import org.semanticweb.owlapi.vocab.OWLRDFVocabulary; import Skos.SkosBrowser.org.coode.owl.mngr.HierarchyProvider; import Skos.SkosBrowser.org.coode.owl.mngr.OWLClassExpressionParser; import Skos.SkosBrowser.org.coode.owl.mngr.OWLEntityFinder; import Skos.SkosBrowser.org.coode.owl.mngr.OWLServer; import Skos.SkosBrowser.org.coode.owl.mngr.OWLServerListener; import Skos.SkosBrowser.org.coode.owl.mngr.ServerConstants; import Skos.SkosBrowser.org.coode.owl.mngr.ServerPropertiesAdapter; import Skos.SkosBrowser.org.coode.owl.mngr.ServerProperty; import Skos.SkosBrowser.org.coode.owl.util.OWLObjectComparator; import com.hp.hpl.jena.ontology.OntDocumentManager; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntModelSpec; import com.hp.hpl.jena.rdf.model.ModelFactory; /** * Author: drummond<br> * The University Of Manchester<br> * Medical Informatics Group<br> * Date: Jul 4, 2006<br><br> * <p/> * nick.drummond@cs.manchester.ac.uk<br> * www.cs.man.ac.uk/~drummond<br><br> */ public class OWLServerImpl implements OWLServer { private static final Logger logger = Logger.getLogger(OWLServerImpl.class.getName()); private OWLOntologyManager mngr; private OWLOntology activeOntology; private OWLReasoner reasoner; private ShortFormProvider shortFormProvider; private OntologyIRIShortFormProvider uriShortFormProvider; private OWLEntityChecker owlEntityChecker; private CachingBidirectionalShortFormProvider nameCache; private OWLEntityFinder finder; private OWLObjectComparator<OWLObject> comparator; private Map<String, OWLClassExpressionParser> parsers = new HashMap<String, OWLClassExpressionParser>(); private HierarchyProvider<OWLClass> classHierarchyProvider; private HierarchyProvider<OWLObjectProperty> objectPropertyHierarchyProvider; private HierarchyProvider<OWLDataProperty> dataPropertyHierarchyProvider; private Map<URI, OWLOntologyIRIMapper> baseMapper = new HashMap<URI, OWLOntologyIRIMapper>(); private ServerPropertiesAdapter<ServerProperty> properties; private final Set<OWLServerListener> listeners = new HashSet<OWLServerListener>(); private boolean serverIsDead = false; private PropertyChangeListener propertyChangeListener = new PropertyChangeListener(){ public void propertyChange(PropertyChangeEvent propertyChangeEvent) { try{ ServerProperty p = ServerProperty.valueOf(propertyChangeEvent.getPropertyName()); handlePropertyChange(p, propertyChangeEvent.getNewValue()); } catch(IllegalArgumentException e){ // do nothing - a user property } } }; public OWLServerImpl(OWLOntologyManager mngr) { this.mngr = mngr; // always default to trying the URI of the ontology mngr.addIRIMapper(new NonMappingOntologyIRIMapper()); if (!mngr.getOntologies().isEmpty()){ setActiveOntology(getTopOfImportsTree(mngr.getOntologies())); } } private OWLOntology getTopOfImportsTree(Set<OWLOntology> ontologies) { // @@TODO implement return ontologies.iterator().next(); } public void loadOntology(OntModel model) throws OWLOntologyCreationException { ByteArrayOutputStream out = new ByteArrayOutputStream(); model.write(out, "RDF/XML"); byte[] data = out.toByteArray(); ByteArrayInputStream in = new ByteArrayInputStream(data); OWLOntology ont = mngr.loadOntologyFromOntologyDocument(in); if (getActiveOntology() == null){ setActiveOntology(ont); // the active ontology is always the first that was loaded } } /** * Required because there are currently no listeners on the manager to tell this has happened */ public void removeOntology(OWLOntology ont) { if (getActiveOntology().equals(ont)){ setActiveOntology(null); } mngr.removeOntology(ont); if (getActiveOntology() == null){ final Set<OWLOntology> activeOntologies = getActiveOntologies(); if (!activeOntologies.isEmpty()){ setActiveOntology(activeOntologies.iterator().next()); } } clear(); } public void clearOntologies() { activeOntology = null; if (mngr != null){ for (OWLOntology ont : mngr.getOntologies()){ mngr.removeOntology(ont); } } clear(); } public void addServerListener(OWLServerListener l) { listeners.add(l); } public void removeServerListener(OWLServerListener l) { listeners.remove(l); } public ServerPropertiesAdapter<ServerProperty> getProperties() { if (properties == null){ properties = new ServerPropertiesAdapterImpl<ServerProperty>(new ServerPropertiesImpl()); // make sure the deprecated names are updated on a load properties.addDeprecatedNames(ServerProperty.generateDeprecatedNamesMap()); List<String> renderers = new ArrayList<String>(); renderers.add(ServerConstants.RENDERER_FRAG); renderers.add(ServerConstants.RENDERER_LABEL); properties.setAllowedValues(ServerProperty.optionRenderer, renderers); properties.set(ServerProperty.optionRenderer, ServerConstants.RENDERER_FRAG); properties.set(ServerProperty.optionLabelUri, OWLRDFVocabulary.RDFS_LABEL.getURI().toString()); properties.set(ServerProperty.optionReasoner, ServerConstants.PELLET); properties.set(ServerProperty.optionLabelLang, ""); properties.addPropertyChangeListener(propertyChangeListener); } return properties; } public OWLOntology getActiveOntology() { if (activeOntology == null){ String ont = getProperties().get(ServerProperty.optionActiveOnt); if (ont != null){ // @@TODO handle anonymous ontologies IRI activeOntIRI = IRI.create(ont); if (activeOntIRI != null){ activeOntology = mngr.getOntology(activeOntIRI); } } } return activeOntology; } public void setActiveOntology(OWLOntology ont) { if (getActiveOntology() == null || !getActiveOntology().equals(ont)){ activeOntology = ont; if (ont != null){ // @@TODO handle anonymous ontologies getProperties().set(ServerProperty.optionActiveOnt, ont.getOntologyID().getOntologyIRI().toString()); } else{ getProperties().remove(ServerProperty.optionActiveOnt); } clear(); resetAllowedLabels(); for (OWLServerListener l : listeners){ l.activeOntologyChanged(ont); } } } public Set<OWLOntology> getOntologies() { return mngr.getOntologies(); } public Set<OWLOntology> getActiveOntologies() { return mngr.getImportsClosure(getActiveOntology()); } public OWLOntologyManager getOWLOntologyManager() { return mngr; } public synchronized OWLReasoner getOWLReasoner() { if (reasoner == null && !this.isDead()){ try { logger.debug("Creating reasoner"); OWLReasoner reasoner = null; final String selectedReasoner = properties.get(ServerProperty.optionReasoner); /********************* * TODO -- This code is broken... */ if (ServerConstants.PELLET.equals(selectedReasoner)){ logger.debug(" pellet"); Class cls = Class.forName("org.mindswap.pellet.owlapi.Reasoner"); Constructor constructor = cls.getConstructor(OWLOntologyManager.class); reasoner = (OWLReasoner) constructor.newInstance(mngr); } else if (ServerConstants.FACTPLUSPLUS.equals(selectedReasoner)){ logger.debug(" FaCT++"); Class cls = Class.forName("uk.ac.manchester.cs.factplusplus.owlapi.Reasoner"); Constructor constructor = cls.getConstructor(OWLOntologyManager.class); reasoner = (OWLReasoner) constructor.newInstance(mngr); } else if (ServerConstants.DIG.equals(selectedReasoner)){ throw new RuntimeException("DIG not supported"); // logger.debug(" DIG"); // DIGReasonerPreferences.getInstance().setReasonerURL(new URL(properties.get(ServerProperty.optionReasonerUrl))); // reasoner = new DIGReasoner(mngr); } if (reasoner != null){ this.reasoner = new ThreadSafeOWLReasoner(reasoner); this.reasoner.precomputeInferences(InferenceType.values()); } } catch (Throwable e) { logger.error("Error trying to get reasoner", e); } } return reasoner; } public HierarchyProvider<OWLClass> getClassHierarchyProvider() { if (classHierarchyProvider == null && !this.isDead()){ classHierarchyProvider = new ClassHierarchyProvider(this); } return classHierarchyProvider; } public HierarchyProvider<OWLObjectProperty> getOWLObjectPropertyHierarchyProvider() { if (objectPropertyHierarchyProvider == null && !this.isDead()){ objectPropertyHierarchyProvider = new OWLObjectPropertyHierarchyProvider(this); } return objectPropertyHierarchyProvider; } public HierarchyProvider<OWLDataProperty> getOWLDataPropertyHierarchyProvider() { if (dataPropertyHierarchyProvider == null && !this.isDead()){ dataPropertyHierarchyProvider = new OWLDataPropertyHierarchyProvider(this); } return dataPropertyHierarchyProvider; } public Comparator<OWLObject> getComparator() { if (comparator == null && !this.isDead()){ comparator = new OWLObjectComparator<OWLObject>(this); } return comparator; } public OWLEntityFinder getFinder() { if (finder == null && !this.isDead()){ finder = new OWLEntityFinderImpl(getNameCache(), this); } return finder; } public OWLEntityChecker getOWLEntityChecker() { if (owlEntityChecker == null && !this.isDead()){ owlEntityChecker = new ShortFormEntityChecker(getNameCache()); } return owlEntityChecker; } private CachingBidirectionalShortFormProvider getNameCache(){ if (nameCache == null){ nameCache = new CachingBidirectionalShortFormProvider(){ protected String generateShortForm(OWLEntity owlEntity) { return getShortFormProvider().getShortForm(owlEntity); } }; nameCache.rebuild(new ReferencedEntitySetProvider(getActiveOntologies())); } return nameCache; } public ShortFormProvider getShortFormProvider() { if (shortFormProvider == null && !this.isDead()){ String ren = properties.get(ServerProperty.optionRenderer); if (ren.equals(ServerConstants.RENDERER_FRAG)){ shortFormProvider = new SimpleShortFormProvider(); } else if (ren.equals(ServerConstants.RENDERER_LABEL)){ String lang = properties.get(ServerProperty.optionLabelLang); if ("".equals(lang)){ lang = null; } OWLAnnotationProperty prop = mngr.getOWLDataFactory().getOWLAnnotationProperty(IRI.create(properties.get(ServerProperty.optionLabelUri))); Map<OWLAnnotationProperty, List<String>> annot2LangMap = new HashMap<OWLAnnotationProperty, List<String>>(); annot2LangMap.put(prop, Collections.singletonList(lang)); shortFormProvider = new AnnotationValueShortFormProvider(Collections.singletonList(prop), annot2LangMap, new OWLOntologySetProvider(){ public Set<OWLOntology> getOntologies() { return getActiveOntologies(); } }); } } return shortFormProvider; } public OntologyIRIShortFormProvider getOntologyShortFormProvider() { if (uriShortFormProvider == null){ uriShortFormProvider = new OntologyIRIShortFormProvider(); } return uriShortFormProvider; } public final OWLClassExpressionParser getClassExpressionParser(String type){ if (!this.isDead()){ return parsers.get(type); } return null; } public final void registerDescriptionParser(String syntax, OWLClassExpressionParser parser) { parsers.put(syntax, parser); } public Set<String> getSupportedSyntaxes() { return parsers.keySet(); } public void dispose() { clearOntologies(); mngr = null; parsers.clear(); properties.removePropertyChangeListener(propertyChangeListener); serverIsDead = true; } public boolean isDead() { return serverIsDead; } public void clear() { resetReasoner(); resetRendererCache(); comparator = null; } private void resetReasoner() { if (reasoner != null){ reasoner.dispose(); reasoner = null; } } private void resetRendererCache() { if (shortFormProvider != null){ shortFormProvider.dispose(); shortFormProvider = null; } if (finder != null){ finder.dispose(); finder = null; } if (nameCache != null){ nameCache.dispose(); nameCache = null; } } // create a set of CommonBaseURIMappers for finding ontologies // using the base of explicitly loaded ontologies as a hint private void handleCommonBaseMappers(URI physicalURI) { String baseURIStr = ""; String uriParts[] = physicalURI.toString().split("/"); for (int i=0; i<uriParts.length-1; i++){ baseURIStr += uriParts[i] + "/"; } URI baseURI = URI.create(baseURIStr); if (baseURI != null){ if (baseMapper.get(baseURI) == null){ final BaseURIMapper mapper = new BaseURIMapper(baseURI); baseMapper.put(baseURI, mapper); mngr.addIRIMapper(mapper); } } } private void handlePropertyChange(ServerProperty p, Object newValue) { switch(p){ case optionReasoner: resetReasoner(); break; case optionRenderer: // DROPTHROUGH case optionLabelLang: resetRendererCache(); break; case optionLabelUri: try { new URI((String)newValue); resetRendererCache(); } catch (URISyntaxException e) { // invalid URI - do not change the renderer } } } private void resetAllowedLabels() { List<String> uriStrings = new ArrayList<String>(); Set<OWLAnnotationProperty> annotationProps = new HashSet<OWLAnnotationProperty>(); for (OWLOntology ont : getActiveOntologies()){ annotationProps.addAll(ont.getAnnotationPropertiesInSignature()); } for (OWLAnnotationProperty prop : annotationProps){ uriStrings.add(prop.getIRI().toString()); } getProperties().setAllowedValues(ServerProperty.optionLabelUri, uriStrings); } }
[ "resit-dilek@gmx.net" ]
resit-dilek@gmx.net
406071b6ff90b41f0496983cd1f0c6c259f21f13
6a9d5c8ba49d3f89ed9a80bbb577d8cc4b66af68
/libraries/tools/kotlin-gradle-plugin/src/testData/kotlin.incremental.useClasspathSnapshot/src/original/com/example/JavaClassWithNestedClasses.java
f77d720eefc90817776d707e43172e76ed224c6f
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
devrats/kotlin
9842ff967ed7409cac4c074531ce3ac12c1d4eec
987a3460156b97c6e36d235ae7f4712c3e2979ab
refs/heads/master
2023-07-31T22:13:55.682345
2021-09-13T23:19:10
2021-09-17T15:39:49
294,596,828
0
1
null
2020-09-11T04:48:23
2020-09-11T04:48:22
null
UTF-8
Java
false
false
1,001
java
package com.example; public class JavaClassWithNestedClasses { public class InnerClass { public void publicMethod() { System.out.println("I'm in a public method"); } private void privateMethod() { System.out.println("I'm in a private method"); } public class InnerClassWithinInnerClass { } public void someMethod() { class LocalClassWithinInnerClass { } } } public static class StaticNestedClass { } public void someMethod() { class LocalClass { class InnerClassWithinLocalClass { } } Runnable objectOfAnonymousLocalClass = new Runnable() { @Override public void run() { } }; } private Runnable objectOfAnonymousNonLocalClass = new Runnable() { @Override public void run() { } }; public class InnerClassWith$Sign { } }
[ "nataliya.valtman@jetbrains.com" ]
nataliya.valtman@jetbrains.com
ac098ee1fe4fc620a00b816da386d63ad742a777
a58f3e9e35f1e891a4402e5033ffac5ea72e61e8
/src/main/java/com/elastica/driver/DriverMode.java
cabc2dc4dbaa970743cb1f979657df2a627040f4
[]
no_license
usmankec/TestProject
35281e9aa7ae674fc377252e67b5fcfa5022aa37
7414a6f7a34a4c4f481756d80960103134eaf352
refs/heads/master
2021-01-10T02:09:17.041021
2015-05-27T15:30:19
2015-05-27T15:30:19
36,374,896
0
0
null
null
null
null
UTF-8
Java
false
false
679
java
/* * Copyright 2015 www.seleniumtests.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.elastica.driver; public enum DriverMode { LOCAL, ExistingGrid, }
[ "usman.kec@gmail.com" ]
usman.kec@gmail.com
ec79afba7f0099c43ef4c62120166f1058acf566
3935dbbe3ba92e14eacaf5cfc45ab18239d88e94
/src/model/Curso.java
d7d5988f26da1186eae0b26dc02125b6a4a7a9fc
[]
no_license
danimo92/Tripulantes52444
fb961a78ce3bcc6ff25c5685deb35665f25b879b
60217552d8b3cb2bdbb2cd8c024f922efc2b6ea3
refs/heads/master
2023-06-19T07:30:13.099242
2021-07-18T15:58:50
2021-07-18T15:58:50
387,026,594
0
0
null
null
null
null
UTF-8
Java
false
false
941
java
package model; public class Curso { private int codigo; private String nombre; private char jornada;//son parámetros private Formador formador; public Curso(int pcodigo,String pnombre, char pjornada, int fCodigo, String fNombre) {//método constructor. Para poder crear objetos a través de esto super();// hace referencia a jerarquía this.codigo=pcodigo; //this es una palabra reservada this.jornada=pjornada; this.nombre=pnombre; formador= new Formador(fNombre,fCodigo);// Se hace aquí porue el objeto formador lo tiene curso } public int getCodigo() { //'get' return codigo; } public String getNombre() { return nombre; } public char getJornada() { return jornada; } public Formador getFormador() { return formador; } public void setNombre(String nombre) { this.nombre = nombre; } }
[ "daniecheverri2021@gmail.com" ]
daniecheverri2021@gmail.com
64affd22a06e1f763b8cfd1a431fc6b5da7f348e
1a414ef4498b7dfdfd8add7f90bc1c28ef2d4b8f
/Quizz/src/gui/custom_components/ComboLabelPanel.java
cde21149143bd87e14de10fd43f1b19d23889b9a
[]
no_license
logralahad/POO2_Quiz
8e228478ca52b370f4c21aa8852d71464dd21203
1bcfe14d31ad6f0f94fbdb66b061cf2ff8db1c84
refs/heads/main
2023-04-09T12:39:34.624335
2021-04-11T21:48:12
2021-04-11T21:48:12
356,422,270
0
0
null
null
null
null
UTF-8
Java
false
false
1,318
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui.custom_components; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * * @author logra */ public class ComboLabelPanel extends JPanel{ private JLabel lblNumero; private JComboBox cmbNumero; public ComboLabelPanel(String texto, Object[] es){ super.setLayout(new FlowLayout()); lblNumero = new JLabel(texto); cmbNumero = new JComboBox(es); cmbNumero.setSelectedItem(null); super.add(lblNumero); super.add(cmbNumero); } public void cambiarItems(Object[] es){ DefaultComboBoxModel<Object> model = new DefaultComboBoxModel<>(es); model.setSelectedItem(null); cmbNumero.setModel(model); } public Integer getIndice(){ return cmbNumero.getSelectedIndex(); } public void setIndice(Integer idx){ if(idx == -1){ cmbNumero.setSelectedItem(null); }else{ cmbNumero.setSelectedIndex(idx); } } public void setListener(ActionListener ae){ cmbNumero.addActionListener(ae); } }
[ "logralahad@gmail.com" ]
logralahad@gmail.com
bb560fce2c85d2be361d0246955f0172a268da7d
7b70327188df79e842214172d86434d8b1e35255
/src/main/java/com/nttdata/controller/AutoreController.java
438d1fc801c86f1b308151f81356787ae93c0e25
[]
no_license
mr-abu-tech/biblioteca
99d55a407b9c39d9de3350e2e95be4ec230b6b25
cbc129ae13933b1954964bc719bd94b6baf6167e
refs/heads/master
2023-02-03T16:56:49.410901
2017-09-29T10:19:35
2017-09-29T10:19:35
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,770
java
package com.nttdata.controller; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.nttdata.database.AutoreMapper; import com.nttdata.exception.BadRequestException; import com.nttdata.exception.NoContentException; import com.nttdata.exception.ResourceConflictException; import com.nttdata.exception.ResourceNotFoundException; import com.nttdata.model.Autore; import com.nttdata.model.Libro; @RestController public class AutoreController { @Autowired private AutoreMapper autoreMapper; @RequestMapping(method = RequestMethod.GET, value = "/autore") public List<Autore> listAutore(@RequestParam(value="nome",required=false) String nome, @RequestParam(value="cognome",required=false) String cognome, @RequestParam(value="email",required=false) String email) { Autore params = new Autore(); params.setNome(nome); params.setCognome(cognome); params.setEmail(email); List<Autore> findAll = autoreMapper.findAll(params); if (findAll != null && findAll.isEmpty()) throw new ResourceNotFoundException(); return findAll; } @RequestMapping(method = RequestMethod.GET, value = "/autore/{idAutore}") public Autore get(@PathVariable(value = "idAutore", required = true) int idAutore) { Autore autore = autoreMapper.findByIdAutore(idAutore); if (autore != null) return autore; else throw new ResourceNotFoundException(); } @RequestMapping(method = RequestMethod.POST, value = "/autore") public Autore add(@RequestBody Autore autore) { if (!validateAutore(autore)) { throw new BadRequestException(); } Autore foundAutore = autoreMapper.findByIdAutore(autore.getIdAutore()); if (foundAutore != null) throw new ResourceConflictException(); autoreMapper.add(autore); return autore; } @RequestMapping(method = RequestMethod.PUT, value = "/autore/{idAutore}") public Autore update(@RequestBody Autore autore, @PathVariable(value = "idAutore", required = true) int idAutore) { if (!validateAutore(autore)) { throw new BadRequestException(); } Autore foundAutore = autoreMapper.findByIdAutore(idAutore); if (foundAutore == null) throw new NoContentException(); autore.setIdAutore(idAutore); autoreMapper.update(autore); return autore; } @RequestMapping(method = RequestMethod.DELETE, value = "/autore/{idAutore}") public void delete(@PathVariable(value = "idAutore", required = true) int idAutore) { Autore foundAutore = autoreMapper.findByIdAutore(idAutore); if (foundAutore == null) throw new NoContentException(); autoreMapper.delete(idAutore); } @RequestMapping(method = RequestMethod.GET, value = "autore/{idAutore}/libro") public List<Libro> listLibro(@PathVariable(value = "idAutore", required = true) int idAutore) { List<Libro> findAll = autoreMapper.findLibri(idAutore); if (findAll != null && findAll.isEmpty()) throw new ResourceNotFoundException(); return findAll; } private boolean validateAutore(Autore autore) { if(StringUtils.isBlank(autore.getNome())) return false; if(StringUtils.isBlank(autore.getCognome())) return false; if(StringUtils.isBlank(autore.getEmail())) return false; return true; } }
[ "arzucastilma@vt-arzucastilma.valueteam.com" ]
arzucastilma@vt-arzucastilma.valueteam.com
f5aff31ba76a0479c1e1473aa627bb5e37b1a7a9
09832253bbd9c7837d4a380c7410bd116d9d8119
/Web Based Learning/JavaTPoint/JavaTPoint/src/Java8NewFeatures/LambdaExpressioin/LambdaExWithoutReturn.java
9268771306b3e0324f171d9097349e7f6c581f02
[]
no_license
shshetu/Java
d892ae2725f8ad0acb2d98f5fd4e6ca2b1ce171e
51bddc580432c74e0339588213ef9aa0d384169a
refs/heads/master
2020-04-11T21:25:12.588859
2019-04-02T05:41:00
2019-04-02T05:41:00
162,104,906
0
1
null
null
null
null
UTF-8
Java
false
false
732
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Java8NewFeatures.LambdaExpressioin; /** * * @author shshe */ interface Addable2{ int add(int a, int b); } public class LambdaExWithoutReturn { public static void main(String[] args) { //lambda expression without return keyword Addable2 add1 = (a,b)->(a+b); System.out.println(add1.add(10, 11));; //lambda expression with return keyword Addable2 add2 = (int a,int b)->{ return a+b; }; //call the method System.out.println(add2.add(100, 200)); } }
[ "shshetu2017@gmail.com" ]
shshetu2017@gmail.com
f29cbccd885ca045b03e33e3f3c305cc27c32e83
71975999c9d702a0883ec9038ce3e76325928549
/src2.4.0/src/main/java/com/baidu/mapapi/map/MapStatus.java
d5ad17519a35a8a0088cb4e6bc8ca5b91aa20ba9
[]
no_license
XposedRunner/PhysicalFitnessRunner
dc64179551ccd219979a6f8b9fe0614c29cd61de
cb037e59416d6c290debbed5ed84c956e705e738
refs/heads/master
2020-07-15T18:18:23.001280
2019-09-02T04:21:34
2019-09-02T04:21:34
205,620,387
3
2
null
null
null
null
UTF-8
Java
false
false
8,880
java
package com.baidu.mapapi.map; import android.graphics.Point; import android.os.Parcel; import android.os.Parcelable; import android.os.Parcelable.Creator; import com.baidu.mapapi.model.CoordUtil; import com.baidu.mapapi.model.LatLng; import com.baidu.mapapi.model.LatLngBounds; import com.baidu.mapapi.model.inner.GeoPoint; import com.baidu.mapsdkplatform.comapi.map.ab; public final class MapStatus implements Parcelable { public static final Creator<MapStatus> CREATOR = new j(); ab a; private double b; public final LatLngBounds bound; private double c; public final float overlook; public final float rotate; public final LatLng target; public final Point targetScreen; public WinRound winRound; public final float zoom; public static final class Builder { private float a = -2.14748365E9f; private LatLng b = null; private float c = -2.14748365E9f; private float d = -2.14748365E9f; private Point e = null; private LatLngBounds f = null; private double g = 0.0d; private double h = 0.0d; private final float i = 15.0f; public Builder(MapStatus mapStatus) { this.a = mapStatus.rotate; this.b = mapStatus.target; this.c = mapStatus.overlook; this.d = mapStatus.zoom; this.e = mapStatus.targetScreen; this.g = mapStatus.a(); this.h = mapStatus.b(); } private float a(float f) { return 15.0f == f ? 15.5f : f; } public MapStatus build() { return new MapStatus(this.a, this.b, this.c, this.d, this.e, this.f); } public Builder overlook(float f) { this.c = f; return this; } public Builder rotate(float f) { this.a = f; return this; } public Builder target(LatLng latLng) { this.b = latLng; return this; } public Builder targetScreen(Point point) { this.e = point; return this; } public Builder zoom(float f) { this.d = a(f); return this; } } MapStatus(float f, LatLng latLng, float f2, float f3, Point point, double d, double d2, LatLngBounds latLngBounds) { this.rotate = f; this.target = latLng; this.overlook = f2; this.zoom = f3; this.targetScreen = point; this.b = d; this.c = d2; this.bound = latLngBounds; } MapStatus(float f, LatLng latLng, float f2, float f3, Point point, LatLngBounds latLngBounds) { this.rotate = f; this.target = latLng; this.overlook = f2; this.zoom = f3; this.targetScreen = point; if (this.target != null) { this.b = CoordUtil.ll2mc(this.target).getLongitudeE6(); this.c = CoordUtil.ll2mc(this.target).getLatitudeE6(); } this.bound = latLngBounds; } MapStatus(float f, LatLng latLng, float f2, float f3, Point point, ab abVar, double d, double d2, LatLngBounds latLngBounds, WinRound winRound) { this.rotate = f; this.target = latLng; this.overlook = f2; this.zoom = f3; this.targetScreen = point; this.a = abVar; this.b = d; this.c = d2; this.bound = latLngBounds; this.winRound = winRound; } protected MapStatus(Parcel parcel) { this.rotate = parcel.readFloat(); this.target = (LatLng) parcel.readParcelable(LatLng.class.getClassLoader()); this.overlook = parcel.readFloat(); this.zoom = parcel.readFloat(); this.targetScreen = (Point) parcel.readParcelable(Point.class.getClassLoader()); this.bound = (LatLngBounds) parcel.readParcelable(LatLngBounds.class.getClassLoader()); this.b = parcel.readDouble(); this.c = parcel.readDouble(); } static MapStatus a(ab abVar) { ab abVar2 = abVar; if (abVar2 == null) { return null; } float f = (float) abVar2.b; double d = abVar2.e; double d2 = abVar2.d; LatLng mc2ll = CoordUtil.mc2ll(new GeoPoint(d, d2)); float f2 = (float) abVar2.c; float f3 = abVar2.a; Point point = new Point(abVar2.f, abVar2.g); LatLng mc2ll2 = CoordUtil.mc2ll(new GeoPoint((double) abVar2.k.e.y, (double) abVar2.k.e.x)); LatLng mc2ll3 = CoordUtil.mc2ll(new GeoPoint((double) abVar2.k.f.y, (double) abVar2.k.f.x)); double d3 = d; LatLng mc2ll4 = CoordUtil.mc2ll(new GeoPoint((double) abVar2.k.h.y, (double) abVar2.k.h.x)); LatLng mc2ll5 = CoordUtil.mc2ll(new GeoPoint((double) abVar2.k.g.y, (double) abVar2.k.g.x)); com.baidu.mapapi.model.LatLngBounds.Builder builder = new com.baidu.mapapi.model.LatLngBounds.Builder(); builder.include(mc2ll2); builder.include(mc2ll3); builder.include(mc2ll4); builder.include(mc2ll5); return new MapStatus(f, mc2ll, f2, f3, point, abVar2, d2, d3, builder.build(), abVar2.j); } /* Access modifiers changed, original: 0000 */ public double a() { return this.b; } /* Access modifiers changed, original: 0000 */ public double b() { return this.c; } /* Access modifiers changed, original: 0000 */ public ab b(ab abVar) { if (abVar == null) { return null; } if (this.rotate != -2.14748365E9f) { abVar.b = (int) this.rotate; } if (this.zoom != -2.14748365E9f) { abVar.a = this.zoom; } if (this.overlook != -2.14748365E9f) { abVar.c = (int) this.overlook; } if (this.target != null) { abVar.d = this.b; abVar.e = this.c; } if (this.targetScreen != null) { abVar.f = this.targetScreen.x; abVar.g = this.targetScreen.y; } return abVar; } /* Access modifiers changed, original: 0000 */ public ab c() { return b(new ab()); } public int describeContents() { return 0; } public String toString() { StringBuilder stringBuilder; StringBuilder stringBuilder2 = new StringBuilder(); if (this.target != null) { stringBuilder = new StringBuilder(); stringBuilder.append("target lat: "); stringBuilder.append(this.target.latitude); stringBuilder.append("\n"); stringBuilder2.append(stringBuilder.toString()); stringBuilder = new StringBuilder(); stringBuilder.append("target lng: "); stringBuilder.append(this.target.longitude); stringBuilder.append("\n"); stringBuilder2.append(stringBuilder.toString()); } if (this.targetScreen != null) { stringBuilder = new StringBuilder(); stringBuilder.append("target screen x: "); stringBuilder.append(this.targetScreen.x); stringBuilder.append("\n"); stringBuilder2.append(stringBuilder.toString()); stringBuilder = new StringBuilder(); stringBuilder.append("target screen y: "); stringBuilder.append(this.targetScreen.y); stringBuilder.append("\n"); stringBuilder2.append(stringBuilder.toString()); } stringBuilder = new StringBuilder(); stringBuilder.append("zoom: "); stringBuilder.append(this.zoom); stringBuilder.append("\n"); stringBuilder2.append(stringBuilder.toString()); stringBuilder = new StringBuilder(); stringBuilder.append("rotate: "); stringBuilder.append(this.rotate); stringBuilder.append("\n"); stringBuilder2.append(stringBuilder.toString()); stringBuilder = new StringBuilder(); stringBuilder.append("overlook: "); stringBuilder.append(this.overlook); stringBuilder.append("\n"); stringBuilder2.append(stringBuilder.toString()); return stringBuilder2.toString(); } public void writeToParcel(Parcel parcel, int i) { parcel.writeFloat(this.rotate); parcel.writeParcelable(this.target, i); parcel.writeFloat(this.overlook); parcel.writeFloat(this.zoom); parcel.writeParcelable(this.targetScreen, i); parcel.writeParcelable(this.bound, i); parcel.writeDouble(this.b); parcel.writeDouble(this.c); } }
[ "xr_master@mail.com" ]
xr_master@mail.com
d01b612e268e8ff862b21ca2667cc5c84f876819
e62f34d3a3b07247814a48f148fa0cbdfd20a708
/control-parent/control-model/src/main/java/com/came/control/model/dao/impl/EmergenciaDAOImpl.java
bfba685c43d299fe2ce1f9d54157231e2ca9cf56
[]
no_license
ca4los-palalia/c4m3-ct41-w36
ebdaf0e9d1fbd90f27417ecc0b0a5f832a561540
d4e2966e26f3e6b0ff14c42174354dabe4bb6d4b
refs/heads/master
2022-12-23T23:56:19.647337
2019-07-27T05:24:00
2019-07-27T05:24:00
198,838,127
0
0
null
2022-12-09T22:51:39
2019-07-25T13:36:18
Java
UTF-8
Java
false
false
2,188
java
package com.came.control.model.dao.impl; import java.util.List; import org.hibernate.Criteria; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.came.control.model.DatabaseMetaclas; import com.came.control.model.dao.EmergenciaDAO; import com.came.control.model.domain.Emergencia; import com.came.control.model.domain.Persona; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; @Repository public class EmergenciaDAOImpl extends DatabaseMetaclas implements EmergenciaDAO { @Transactional public void save(Emergencia entity) { sessionFactory.getCurrentSession().saveOrUpdate(entity); } @Transactional public void delete(Emergencia entity) { sessionFactory.getCurrentSession().delete(entity); } @Transactional(readOnly = true) public Emergencia getById(Long idEntity) { Criteria criteria = sessionFactory.getCurrentSession().getSessionFactory().openSession() .createCriteria(Emergencia.class); criteria.add(Restrictions.eq("idEmergencia ", idEntity)); List<Emergencia> lista = ImmutableList.copyOf(Iterables.filter(criteria.list(), Emergencia.class)); return (lista != null) && (!lista.isEmpty()) ? lista.get(0) : null; } @Transactional(readOnly = true) public List<Emergencia> getAll() { Criteria criteria = sessionFactory.getCurrentSession().getSessionFactory().openSession() .createCriteria(Emergencia.class); List<Emergencia> lista = ImmutableList.copyOf(Iterables.filter(criteria.list(), Emergencia.class)); return (lista != null) && (!lista.isEmpty()) ? lista : null; } @Transactional(readOnly = true) public Emergencia getByPersona(Persona persona) { Criteria criteria = sessionFactory.getCurrentSession().getSessionFactory().openSession() .createCriteria(Emergencia.class); criteria.add(Restrictions.eq("persona ", persona)); List<Emergencia> lista = ImmutableList.copyOf(Iterables.filter(criteria.list(), Emergencia.class)); return (lista != null) && (!lista.isEmpty()) ? lista.get(0) : null; } }
[ "Carlos Palalia@192.168.1.84" ]
Carlos Palalia@192.168.1.84
4d3e6c43505c3bc56daecf81d2002a5eaec8e841
4e2e04fa4b12e4abbc4ac0b8bb2f42e20f89f613
/ServidorAdmin/src/models/pedidos/PedidoExpress.java
3aa1660216483701624d25f7cd8181da941a2f95
[]
no_license
aguilarandress/RestauranteEnLinea
3ade178715e32cea66cca6848ecbd7d7362288c8
9a4a12092ab9591c59e0b727591f357f78db936f
refs/heads/master
2022-03-31T08:37:10.735385
2019-11-26T03:48:05
2019-11-26T03:48:05
222,770,387
3
0
null
null
null
null
UTF-8
Java
false
false
505
java
package models.pedidos; /** * * @author Kenneth Sanchez * @author Fabian Vargas * @author Andres Aguilar */ public class PedidoExpress extends Pedido{ private int numeroCelular; private String direccion; public int getNumeroCelular() { return numeroCelular; } public void setNumeroCelular(int numeroCelular) { this.numeroCelular = numeroCelular; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } }
[ "andres.aguilar10@hotmail.com" ]
andres.aguilar10@hotmail.com
c30d4bf0c1f5d4739b1308419c343df0fc489510
7bba2f81796128d08e8902ffa24df0beca1109da
/Aplicacao/src/Model/Cliente.java
7ac29072c0359c3e71c303da3043b495df716d6c
[]
no_license
Leandro-Silva-Santos/Salao
5d81f52f9a467e38330dcc9a7528b2885eb4d23a
5affde077d2271f1accea3313a5ab1fc8554dfe8
refs/heads/main
2023-07-26T13:31:07.366084
2021-08-25T20:38:12
2021-08-25T20:38:12
398,684,702
0
0
null
null
null
null
UTF-8
Java
false
false
946
java
package Model; import java.util.Date; public class Cliente extends Pessoa{ protected String endereco; protected String cep; public Cliente(int id, String nome, char sexo, String dataNascimento, String telefone, String email, String rg, String endereco, String cep) { super(id, nome, sexo, dataNascimento, telefone, email, rg); this.endereco = endereco; this.cep = cep; } public Cliente(int id, String nome, String endereco, String cep) { super(id, nome); this.endereco = endereco; this.cep = cep; } public String getEndereco() { return endereco; } public void setEndereco(String endereco) { this.endereco = endereco; } public String getCep() { return cep; } public void setCep(String cep) { this.cep = cep; } @Override public String toString(){ return getNome(); } }
[ "leandro.ls.silva.santos@gmail.com" ]
leandro.ls.silva.santos@gmail.com
8d719e91cb3a6f1afac4e7762beb83589bc9ffa5
517370861bdaf5e89981bffd8c807ae64350a9d0
/DataStructuresAndAlgorithms/src/santosh/algorithms/sorting/quick/TestQuick.java
332bd2ce8508ab0edbfabd1fdc4eac82af6baf40
[]
no_license
santoshbk/LearningAlgoNData
e0082d66745026ba25f00eb2130a3cfb0b11c7cf
e517e24ebe842e86f33e073cb3dd897fea83c95b
refs/heads/master
2021-07-13T06:11:22.172758
2021-06-22T17:23:25
2021-06-22T17:23:25
53,429,778
0
0
null
null
null
null
UTF-8
Java
false
false
568
java
package santosh.algorithms.sorting.quick; public class TestQuick { public static void main(String[] args) { int[] arr = { 12, 56, 67, 43, 1, 45, 32, 54, 67, 87, 34, 23 }; for (int i : arr) { System.out.print(i + " "); } System.out.println(); quickSortingArray(arr); for (int i : arr) { System.out.print(i + " "); } System.out.println(); } static void quickSortingArray(int[] arr) { int len = arr.length; int first = 0; int last = len - 1; } static void quickSort(int[] a, int first, int last) { System.out.println("Cool"); } }
[ "bornfree.kushi@gmail.com" ]
bornfree.kushi@gmail.com
c2952891c5f1db72cd7881b872e4ff8d09b1ece6
ac673e0d2be17cdb85fb252d500b5a13cf6faee5
/src/test/java/com/example/ejemplo03/controller/UserControllerTest.java
a3da7d286e10870c9c373be00db4278df3c2e0a3
[]
no_license
ocampo320/FlutterApp
d4bd21aff1dad873a05c670538a2ec8ec0adcd99
05c371551bf3f19997bccad24292e4b068b68317
refs/heads/master
2023-04-08T20:41:06.215902
2021-04-09T21:21:51
2021-04-09T21:21:51
356,046,643
0
0
null
null
null
null
UTF-8
Java
false
false
5,170
java
package com.example.ejemplo03.controller; import com.example.ejemplo03.model.Usuario; import com.example.ejemplo03.services.PersonaService; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; import java.util.ArrayList; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.doNothing; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @WebMvcTest(controllers = UserController.class) @ActiveProfiles("test") public class UserControllerTest { @Autowired private MockMvc mockMvc; @MockBean private PersonaService userService; @Autowired private ObjectMapper objectMapper; private List<Usuario> userList; @BeforeEach void setUp() { this.userList = new ArrayList<>(); this.userList.add(new Usuario( 1, "deivi", "lopez", "deivi320@hotmail.com", "2220718", "la sierra")); this.userList.add(new Usuario( 2, "deivi", "lopez", "deivi320@hotmail.com", "2220718", "la sierra")); this.userList.add(new Usuario( 3, "deivi", "lopez", "deivi320@hotmail.com", "2220718", "la sierra")); } @Test void shouldFetchAllUsers() throws Exception { given(userService.getUsers()).willReturn(userList); this.mockMvc.perform(get("/user")) .andExpect(status().isOk()) .andExpect(jsonPath("$.size()", is(userList.size()))); } @Test void shouldFetchOneUserById() throws Exception { final int userId = 1; final Usuario user = new Usuario( 3, "deivi", "lopez", "deivi320@hotmail.com", "2220718", "la sierra"); given(userService.getUserById(userId)).willReturn(user); this.mockMvc.perform(get("/user/{id}", userId)) .andExpect(status().isOk()) .andExpect(jsonPath("$.emailUsuario", is(user.getEmailUsuario()))) .andExpect(jsonPath("$.nombeUsuario", is(user.getNombeUsuario()))); } @Test void shouldCreateNewUser() throws Exception { given(userService.add(any(Usuario.class))).willAnswer((invocation) -> invocation.getArgument(0)); Usuario user = new Usuario( 3, "deivi", "lopez", "deivi320@hotmail.com", "2220718", "la sierra"); this.mockMvc.perform(post("/user") .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(user))) .andExpect(status().isOk()) .andExpect(jsonPath("$.nombeUsuario", is(user.getNombeUsuario()))) .andExpect(jsonPath("$.apellidoUsuario", is(user.getApellidoUsuario()))) .andExpect(jsonPath("$.emailUsuario", is(user.getEmailUsuario()))) .andExpect(jsonPath("$.telefonoUsuario", is(user.getTelefonoUsuario()))) .andExpect(jsonPath("$.direccionUsuario", is(user.getDireccionUsuario()))) ; } @Test void shouldDeleteUser() throws Exception { int userId = 1; Usuario user = new Usuario( 3, "deivi", "lopez", "deivi320@hotmail.com", "2220718", "la sierra"); given(userService.getUserById(userId)).willReturn(user); doNothing().when(userService).delete(user.getIdUsuario()); this.mockMvc.perform(delete("/user/{id}", user.getIdUsuario())) .andExpect(status().isOk()); } @Test void shouldDeleteUser2git() throws Exception { int userId = 1; Usuario user = new Usuario( 3, "deivi", "lopez", "deivi320@hotmail.com", "2220718", "la sierra"); given(userService.getUserById(userId)).willReturn(user); doNothing().when(userService).delete(user.getIdUsuario()); this.mockMvc.perform(delete("/user/{id}", user.getIdUsuario())) .andExpect(status().isOk()); } }
[ "telecentro.lasierra@gmail.com" ]
telecentro.lasierra@gmail.com
646bcea81db2f73910560d3980ad1dafec5cb10e
dcd5f995a6559bee125e843292c3adb863f8e37f
/CapOne/CapOneExSix.java
968227c9bb1c7169b527e10a9a21ca0eefa6de9f
[]
no_license
mozarthspier/McAllister---Data-Structures-and-Algorithms
2a007b26114a9046f43e1ae2f18350b348d8dfe9
8627b89547b8fbcb321bd6563a8c576d2090baff
refs/heads/master
2021-03-10T03:13:01.618412
2020-03-16T14:03:51
2020-03-16T14:03:51
246,412,012
0
0
null
null
null
null
UTF-8
Java
false
false
1,384
java
import java.util.Scanner; import java.util.Locale; public class CapOneExSix { public static void main(String[] args) { Scanner sc = new Scanner(System.in); sc.useLocale(Locale.US); int listSize; float sumOfPrices = 0; boolean averageCheck = false; String[] names, prices; System.out.println("Define size of product list: "); listSize = sc.nextInt(); names = new String[listSize]; prices = new String[listSize]; for (int i = 0; i < listSize; i++) { System.out.println("Type the name of the product: "); names[i] = sc.next(); averageCheck = names[i].toLowerCase().equals("peas") ? true : averageCheck; System.out.println("Type the price of the product: "); float price = sc.nextFloat(); sumOfPrices += price; prices[i] = String.format(Locale.US, "%.2f", price); } sc.close(); for (int i = listSize - 1; i >= 0; i--) { System.out.println(names[i] + " costs U$ " + prices[i] + " Dollars.\n"); } if (averageCheck == true) { System.out.println("The average price is: U$ " + String.format(Locale.US, "%.2f", sumOfPrices / listSize) + " Dollars."); } else { System.out.println("No average output"); } } }
[ "mozarthspier@gmail.com" ]
mozarthspier@gmail.com
e28e0acb97ddc49223295077b678096a0f0ab6b0
ec542e534dff67d1c51a1fa1933dfc5982c82c05
/app/src/main/java/com/example1/archi/assign5/Channel.java
f302300cae253ecfeba57370dd1fa53d7d691a28
[]
no_license
SFA16SCM21C/Government-Information
5dc9291a3a30ae9bb930067e9265793fff86d88f
8de8263f8bd79b32392abe9a6d9250617972c54a
refs/heads/master
2020-03-09T15:36:28.750631
2018-04-10T02:40:58
2018-04-10T02:40:58
128,863,370
0
0
null
null
null
null
UTF-8
Java
false
false
1,403
java
package com.example1.archi.assign5; import android.net.sip.SipErrorCode; import java.io.Serializable; public class Channel implements Serializable{ private String googleID; private String twitterID; private String facebookID; private String youtubeID; public Channel() { } public Channel(String googleID, String twitterID, String facebookID, String youtubeID) { this.googleID = googleID; this.twitterID = twitterID; this.facebookID = facebookID; this.youtubeID = youtubeID; } public String getGoogleID() { return googleID; } public void setGoogleID(String googleID) { this.googleID = googleID; } public String getTwitterID() { return twitterID; } public void setTwitterID(String twitterID) { this.twitterID = twitterID; } public String getFacebookID() { return facebookID; } public void setFacebookID(String facebookID) { this.facebookID = facebookID; } public String getYoutubeID() { return youtubeID; } public void setYoutubeID(String youtubeID) { this.youtubeID = youtubeID; } @Override public String toString() { return "Google ID "+googleID +"\n Facebook "+facebookID +"\n twitter "+twitterID +"\n youtube "+youtubeID; } }
[ "schauhan1@hawk.iit.edu" ]
schauhan1@hawk.iit.edu
d77d58ece610fd304eaa3b40b8e1bf2f31d47742
32da8cd9809074235cc02e90ae2671d6f6a6d83d
/ramffd-api-framework/src/main/java/com/mitch/constants/APIConstants.java
905e301f47c7b01118b8123939eb6e94e859c59f
[]
no_license
limingcheng332/ramffd
db838aa670fea60eb14e96a89ea0cd635c9955d1
10c0f3a7c247a1aaebbcae51b25b5620d0eb6d96
refs/heads/master
2022-11-21T00:27:16.007818
2020-01-18T07:43:56
2020-01-18T07:43:56
99,982,451
5
1
null
2022-11-15T23:23:47
2017-08-11T02:16:37
Java
UTF-8
Java
false
false
371
java
package com.mitch.constants; /** * Created by Administrator on 2017/8/18. */ public class APIConstants { public final static String ERRCODE_SUCC = "0000"; public final static String SYS_EXCEPTION = "9999"; public final static String BUSI_EXCEPTION = "1111"; public final static String MSG_SPLIT = "::"; public final static String MSG_END = "$"; }
[ "limingcheng_vip@163.com" ]
limingcheng_vip@163.com
7c33e375ee472f94247b174db2ce9ea81748d13d
596dd75c4d7cb9a1c3ea0eb4eb60081b96f42ddc
/app/src/main/java/com/credr/inspsheettesting/models/User.java
e5e0c8299137d06e2e468ef5fe2a894076277901
[]
no_license
vagnihotri/InspSheetTesting
47aa0a044d3b5c8497e44b79c9e65c3d0c07c0ed
3408446885583f01edb90dab08176bff3f02a458
refs/heads/master
2020-04-06T07:11:20.951987
2016-09-06T16:50:56
2016-09-06T16:50:56
65,154,395
0
0
null
null
null
null
UTF-8
Java
false
false
241
java
package com.credr.inspsheettesting.models; import java.util.ArrayList; /** * Created by vijayagnihotri on 23/06/16. */ public class User { public User() { } public String name; public ArrayList<Question> questionList; }
[ "vijaykumar@credr.in" ]
vijaykumar@credr.in
19d70797a03c06ac934ca1a7c2f3287e940f6e28
5fa014c72dce98943eda26ff58610d4928f7fb8d
/src/com/riekr/android/sdk/downloader/serve/LocalFileByteBuf.java
a81b0ca7769d3bcf3307b9f0bcbd9bd90d1454cc
[]
no_license
Riekr/Android_SDK_Downloader
9b54964313ff4a80914f3e6b6b8207653138c426
cda7db1f1011a39800d5cdc3fe3df1d157cd27d9
refs/heads/master
2020-01-23T21:40:29.915587
2016-12-30T10:48:21
2016-12-30T10:48:21
74,689,895
0
0
null
null
null
null
UTF-8
Java
false
false
21,321
java
package com.riekr.android.sdk.downloader.serve; import java.io.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.GatheringByteChannel; import java.nio.channels.ScatteringByteChannel; import java.nio.charset.Charset; import io.netty.buffer.*; @SuppressWarnings("FieldNotUsedInToString") public class LocalFileByteBuf extends ByteBuf { private final File _file; private final int _size; private final RandomAccessFile _raf; private int _mark = 0; public LocalFileByteBuf(File file) throws FileNotFoundException { _file = file; _size = (int)file.length(); _raf = new RandomAccessFile(file, "r"); } @Override public int capacity() { return _size; } @Override public ByteBuf capacity(int newCapacity) { throw new UnsupportedOperationException(); } @Override public int maxCapacity() { return _size; } @Override public ByteBufAllocator alloc() { return UnpooledByteBufAllocator.DEFAULT; } @Override public ByteOrder order() { return ByteOrder.nativeOrder(); } @Override public ByteBuf order(ByteOrder endianness) { throw new UnsupportedOperationException(); } @Override public ByteBuf unwrap() { return null; } @Override public boolean isDirect() { return true; } @Override public int readerIndex() { try { return (int)_raf.getFilePointer(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public ByteBuf readerIndex(int readerIndex) { try { _raf.seek(readerIndex); return this; } catch (IOException e) { throw new RuntimeException(e); } } @Override public int writerIndex() { return _size; } @Override public ByteBuf writerIndex(int writerIndex) { throw new UnsupportedOperationException(); } @Override public ByteBuf setIndex(int readerIndex, int writerIndex) { throw new UnsupportedOperationException(); } @Override public int readableBytes() { return _size - readerIndex(); } @Override public int writableBytes() { return 0; } @Override public int maxWritableBytes() { return 0; } @Override public boolean isReadable() { return isReadable(1); } @Override public boolean isReadable(int size) { return readableBytes() >= size; } @Override public boolean isWritable() { return false; } @Override public boolean isWritable(int size) { return false; } @Override public ByteBuf clear() { throw new UnsupportedOperationException(); } @Override public ByteBuf markReaderIndex() { _mark = readerIndex(); return this; } @Override public ByteBuf resetReaderIndex() { return readerIndex(_mark); } @Override public ByteBuf markWriterIndex() { throw new UnsupportedOperationException(); } @Override public ByteBuf resetWriterIndex() { throw new UnsupportedOperationException(); } @Override public ByteBuf discardReadBytes() { throw new UnsupportedOperationException(); } @Override public ByteBuf discardSomeReadBytes() { throw new UnsupportedOperationException(); } @Override public ByteBuf ensureWritable(int minWritableBytes) { throw new UnsupportedOperationException(); } @Override public int ensureWritable(int minWritableBytes, boolean force) { throw new UnsupportedOperationException(); } @Override public boolean getBoolean(int index) { try { final long fp = _raf.getFilePointer(); try { _raf.seek(index); return _raf.readBoolean(); } finally { _raf.seek(fp); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public byte getByte(int index) { try { final long fp = _raf.getFilePointer(); try { _raf.seek(index); return _raf.readByte(); } finally { _raf.seek(fp); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public short getUnsignedByte(int index) { try { final long fp = _raf.getFilePointer(); try { _raf.seek(index); return (short)_raf.readUnsignedByte(); } finally { _raf.seek(fp); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public short getShort(int index) { try { final long fp = _raf.getFilePointer(); try { _raf.seek(index); return _raf.readShort(); } finally { _raf.seek(fp); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public int getUnsignedShort(int index) { try { final long fp = _raf.getFilePointer(); try { _raf.seek(index); return _raf.readUnsignedShort(); } finally { _raf.seek(fp); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public int getMedium(int index) { throw new UnsupportedOperationException(); } @Override public int getUnsignedMedium(int index) { try { final long fp = _raf.getFilePointer(); try { _raf.seek(index); final byte[] buf = new byte[3]; final int len = _raf.read(buf); int sum = 0; for (byte b : buf) sum += b; return sum / len; } finally { _raf.seek(fp); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public int getInt(int index) { try { final long fp = _raf.getFilePointer(); try { _raf.seek(index); return _raf.readInt(); } finally { _raf.seek(fp); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public long getUnsignedInt(int index) { throw new UnsupportedOperationException(); } @Override public long getLong(int index) { try { final long fp = _raf.getFilePointer(); try { _raf.seek(index); return _raf.readLong(); } finally { _raf.seek(fp); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public char getChar(int index) { try { final long fp = _raf.getFilePointer(); try { _raf.seek(index); return _raf.readChar(); } finally { _raf.seek(fp); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public float getFloat(int index) { try { final long fp = _raf.getFilePointer(); try { _raf.seek(index); return _raf.readFloat(); } finally { _raf.seek(fp); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public double getDouble(int index) { try { final long fp = _raf.getFilePointer(); try { _raf.seek(index); return _raf.readDouble(); } finally { _raf.seek(fp); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public ByteBuf getBytes(int index, ByteBuf dst) { return getBytes(index, dst, dst.writableBytes()); } @Override public ByteBuf getBytes(int index, ByteBuf dst, int length) { try { final long fp = _raf.getFilePointer(); try { _raf.seek(index); final byte[] buf = new byte[length]; final int len = _raf.read(buf); dst.writeBytes(buf, 0, len); return this; } finally { _raf.seek(fp); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { try { final long fp = _raf.getFilePointer(); try { _raf.seek(index); final byte[] buf = new byte[length]; final int len = _raf.read(buf); dst.writerIndex(dstIndex); dst.writeBytes(buf, 0, len); return this; } finally { _raf.seek(fp); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public ByteBuf getBytes(int index, byte[] dst) { return getBytes(index, dst, 0, dst.length); } @Override public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { try { final long fp = _raf.getFilePointer(); try { _raf.seek(index); _raf.read(dst, dstIndex, length); return this; } finally { _raf.seek(fp); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public ByteBuf getBytes(int index, ByteBuffer dst) { try { final long fp = _raf.getFilePointer(); try { _raf.seek(index); final byte[] buf = new byte[dst.remaining()]; final int len = _raf.read(buf); dst.put(buf, 0, len); return this; } finally { _raf.seek(fp); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { try { final long fp = _raf.getFilePointer(); try { _raf.seek(index); final byte[] buf = new byte[length]; final int len = _raf.read(buf); out.write(buf, 0, len); return this; } finally { _raf.seek(fp); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { try { final long fp = _raf.getFilePointer(); try { _raf.seek(index); final byte[] buf = new byte[length]; final int len = _raf.read(buf); out.write(ByteBuffer.wrap(buf, 0, len)); return len; } finally { _raf.seek(fp); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public ByteBuf setBoolean(int index, boolean value) { throw new UnsupportedOperationException(); } @Override public ByteBuf setByte(int index, int value) { throw new UnsupportedOperationException(); } @Override public ByteBuf setShort(int index, int value) { throw new UnsupportedOperationException(); } @Override public ByteBuf setMedium(int index, int value) { throw new UnsupportedOperationException(); } @Override public ByteBuf setInt(int index, int value) { throw new UnsupportedOperationException(); } @Override public ByteBuf setLong(int index, long value) { throw new UnsupportedOperationException(); } @Override public ByteBuf setChar(int index, int value) { throw new UnsupportedOperationException(); } @Override public ByteBuf setFloat(int index, float value) { throw new UnsupportedOperationException(); } @Override public ByteBuf setDouble(int index, double value) { throw new UnsupportedOperationException(); } @Override public ByteBuf setBytes(int index, ByteBuf src) { throw new UnsupportedOperationException(); } @Override public ByteBuf setBytes(int index, ByteBuf src, int length) { throw new UnsupportedOperationException(); } @Override public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { throw new UnsupportedOperationException(); } @Override public ByteBuf setBytes(int index, byte[] src) { throw new UnsupportedOperationException(); } @Override public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { throw new UnsupportedOperationException(); } @Override public ByteBuf setBytes(int index, ByteBuffer src) { throw new UnsupportedOperationException(); } @Override public int setBytes(int index, InputStream in, int length) throws IOException { throw new UnsupportedOperationException(); } @Override public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { throw new UnsupportedOperationException(); } @Override public ByteBuf setZero(int index, int length) { throw new UnsupportedOperationException(); } @Override public boolean readBoolean() { try { return _raf.readBoolean(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public byte readByte() { try { return _raf.readByte(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public short readUnsignedByte() { try { return (short)_raf.readUnsignedByte(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public short readShort() { try { return _raf.readShort(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public int readUnsignedShort() { try { return _raf.readUnsignedShort(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public int readMedium() { throw new UnsupportedOperationException(); } @Override public int readUnsignedMedium() { try { final byte[] buf = new byte[3]; final int len = _raf.read(buf); int sum = 0; for (byte b : buf) sum += b; return sum / len; } catch (IOException e) { throw new RuntimeException(e); } } @Override public int readInt() { try { return _raf.readInt(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public long readUnsignedInt() { throw new UnsupportedOperationException(); } @Override public long readLong() { try { return _raf.readLong(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public char readChar() { try { return _raf.readChar(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public float readFloat() { try { return _raf.readFloat(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public double readDouble() { try { return _raf.readDouble(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public ByteBuf readBytes(int length) { try { final byte[] buf = new byte[length]; final int len = _raf.read(buf); return Unpooled.wrappedBuffer(buf, 0, len); } catch (IOException e) { throw new RuntimeException(e); } } @Override public ByteBuf readSlice(int length) { throw new UnsupportedOperationException(); } @Override public ByteBuf readBytes(ByteBuf dst) { return readBytes(dst, dst.writableBytes()); } @Override public ByteBuf readBytes(ByteBuf dst, int length) { try { final byte[] buf = new byte[length]; final int len = _raf.read(buf); dst.writeBytes(buf, 0, len); return this; } catch (IOException e) { throw new RuntimeException(e); } } @Override public ByteBuf readBytes(ByteBuf dst, int dstIndex, int length) { try { final byte[] buf = new byte[length]; final int len = _raf.read(buf); dst.writerIndex(dstIndex); dst.writeBytes(buf, 0, len); return this; } catch (IOException e) { throw new RuntimeException(e); } } @Override public ByteBuf readBytes(byte[] dst) { return readBytes(dst, 0, dst.length); } @Override public ByteBuf readBytes(byte[] dst, int dstIndex, int length) { try { _raf.read(dst, dstIndex, length); return this; } catch (IOException e) { throw new RuntimeException(e); } } @Override public ByteBuf readBytes(ByteBuffer dst) { try { final byte[] buf = new byte[dst.remaining()]; final int len = _raf.read(buf); dst.put(buf, 0, len); return this; } catch (IOException e) { throw new RuntimeException(e); } } @Override public ByteBuf readBytes(OutputStream out, int length) throws IOException { try { final byte[] buf = new byte[length]; final int len = _raf.read(buf); out.write(buf, 0, len); return this; } catch (IOException e) { throw new RuntimeException(e); } } @Override public int readBytes(GatheringByteChannel out, int length) throws IOException { try { final byte[] buf = new byte[length]; final int len = _raf.read(buf); out.write(ByteBuffer.wrap(buf, 0, len)); return len; } catch (IOException e) { throw new RuntimeException(e); } } @Override public ByteBuf skipBytes(int length) { writerIndex(writerIndex() + length); return this; } @Override public ByteBuf writeBoolean(boolean value) { throw new UnsupportedOperationException(); } @Override public ByteBuf writeByte(int value) { throw new UnsupportedOperationException(); } @Override public ByteBuf writeShort(int value) { throw new UnsupportedOperationException(); } @Override public ByteBuf writeMedium(int value) { throw new UnsupportedOperationException(); } @Override public ByteBuf writeInt(int value) { throw new UnsupportedOperationException(); } @Override public ByteBuf writeLong(long value) { throw new UnsupportedOperationException(); } @Override public ByteBuf writeChar(int value) { throw new UnsupportedOperationException(); } @Override public ByteBuf writeFloat(float value) { throw new UnsupportedOperationException(); } @Override public ByteBuf writeDouble(double value) { throw new UnsupportedOperationException(); } @Override public ByteBuf writeBytes(ByteBuf src) { throw new UnsupportedOperationException(); } @Override public ByteBuf writeBytes(ByteBuf src, int length) { throw new UnsupportedOperationException(); } @Override public ByteBuf writeBytes(ByteBuf src, int srcIndex, int length) { throw new UnsupportedOperationException(); } @Override public ByteBuf writeBytes(byte[] src) { throw new UnsupportedOperationException(); } @Override public ByteBuf writeBytes(byte[] src, int srcIndex, int length) { throw new UnsupportedOperationException(); } @Override public ByteBuf writeBytes(ByteBuffer src) { throw new UnsupportedOperationException(); } @Override public int writeBytes(InputStream in, int length) throws IOException { throw new UnsupportedOperationException(); } @Override public int writeBytes(ScatteringByteChannel in, int length) throws IOException { throw new UnsupportedOperationException(); } @Override public ByteBuf writeZero(int length) { throw new UnsupportedOperationException(); } @Override public int indexOf(int fromIndex, int toIndex, byte value) { throw new UnsupportedOperationException(); } @Override public int bytesBefore(byte value) { throw new UnsupportedOperationException(); } @Override public int bytesBefore(int length, byte value) { throw new UnsupportedOperationException(); } @Override public int bytesBefore(int index, int length, byte value) { throw new UnsupportedOperationException(); } @Override public int forEachByte(ByteBufProcessor processor) { throw new UnsupportedOperationException(); } @Override public int forEachByte(int index, int length, ByteBufProcessor processor) { throw new UnsupportedOperationException(); } @Override public int forEachByteDesc(ByteBufProcessor processor) { throw new UnsupportedOperationException(); } @Override public int forEachByteDesc(int index, int length, ByteBufProcessor processor) { throw new UnsupportedOperationException(); } @Override public ByteBuf copy() { throw new UnsupportedOperationException(); } @Override public ByteBuf copy(int index, int length) { throw new UnsupportedOperationException(); } @Override public ByteBuf slice() { throw new UnsupportedOperationException(); } @Override public ByteBuf slice(int index, int length) { throw new UnsupportedOperationException(); } @Override public ByteBuf duplicate() { throw new UnsupportedOperationException(); } @Override public int nioBufferCount() { return 1; // TODO } @Override public ByteBuffer nioBuffer() { throw new UnsupportedOperationException(); } @Override public ByteBuffer nioBuffer(int index, int length) { throw new UnsupportedOperationException(); } @Override public ByteBuffer internalNioBuffer(int index, int length) { try { FileChannel inChannel = _raf.getChannel(); MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, index, length); buffer.load(); return buffer; } catch (IOException e) { throw new RuntimeException(e); } } @Override public ByteBuffer[] nioBuffers() { return new ByteBuffer[]{internalNioBuffer(0, _size)}; } @Override public ByteBuffer[] nioBuffers(int index, int length) { throw new UnsupportedOperationException(); } @Override public boolean hasArray() { return false; } @Override public byte[] array() { throw new UnsupportedOperationException(); } @Override public int arrayOffset() { throw new UnsupportedOperationException(); } @Override public boolean hasMemoryAddress() { return false; } @Override public long memoryAddress() { throw new UnsupportedOperationException(); } @Override public String toString(Charset charset) { throw new UnsupportedOperationException(); } @Override public String toString(int index, int length, Charset charset) { throw new UnsupportedOperationException(); } @Override public int compareTo(ByteBuf buffer) { throw new UnsupportedOperationException(); } @Override public ByteBuf retain(int increment) { return this; } @Override public boolean release() { return false; } @Override public boolean release(int decrement) { return false; } @Override public int refCnt() { return 0; } @Override public ByteBuf retain() { return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LocalFileByteBuf that = (LocalFileByteBuf)o; return _mark == that._mark && _file.equals(that._file); } @Override public int hashCode() { int result = _file.hashCode(); result = 31 * result + _mark; return result; } @Override public String toString() { return "LocalFileByteBuf{" + "_file=" + _file + ", _mark=" + _mark + '}'; } }
[ "gparmiggiani@gmail.com" ]
gparmiggiani@gmail.com
d63226d2a21af55a194d653a81594ffa8b1784f9
10fdc3aa333ef07a180f29a4425650945c3da9c8
/zhuanbo-service/src/main/java/com/zhuanbo/service/service/impl/SeqIncrServiceImpl.java
b088081a42128880dfae8d9948cbbac4c2356f0b
[]
no_license
arvin-xiao/lexuan
4d67f4ab40243c7e6167e514d899c6cd0c3f0995
6cffeee1002bad067e6c8481a3699186351d91a8
refs/heads/master
2023-04-27T21:01:06.644131
2020-05-03T03:03:52
2020-05-03T03:03:52
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,925
java
package com.zhuanbo.service.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.zhuanbo.core.exception.ShopException; import com.zhuanbo.core.service.impl.RedissonDistributedLocker; import com.zhuanbo.core.constants.Align; import com.zhuanbo.core.constants.Constants; import com.zhuanbo.core.entity.SeqIncr; import com.zhuanbo.service.mapper.SeqIncrMapper; import com.zhuanbo.service.service.ISeqIncrService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * <p> * 序列号表 服务实现类 * </p> * * @author rome * @since 2019-06-13 */ @Service @Slf4j public class SeqIncrServiceImpl extends ServiceImpl<SeqIncrMapper, SeqIncr> implements ISeqIncrService { @Autowired private RedissonDistributedLocker redissonLocker; private static Map<String, SeqIncr> seqIncrMap = new HashMap<String, SeqIncr>(); //默认增长数 private static final int DEFAULT_INCREMENT = 1; private String padding = "00000000000000000000000000000000"; static Lock lock = new ReentrantLock(true); @Override @Transactional(propagation = Propagation.NOT_SUPPORTED) public String nextVal(String seqName, int length, Align align) { long currentValue = 0; try { lock.tryLock(Constants.LOCK_WAIT_TIME, TimeUnit.SECONDS); SeqIncr seqIncr = seqIncrMap.get(seqName); if (null == seqIncr) { seqIncr = getSeqIncr(seqName); if (null == seqIncr) { throw new ShopException("11200", "获取序列号失败,seqName=" + seqName); } //如果增长值小于等于DEFAULT_INCREMENT,直接返回 if (seqIncr.getIncrement().intValue() <= DEFAULT_INCREMENT) { return paddingVal(String.valueOf(seqIncr.getCurrentValue() + seqIncr.getIncrement()), length, align); } } long nextValue = seqIncr.getNextValue(); currentValue = seqIncr.getCurrentValue(); //当序列值超过DEFAULT_LOAD_FACTOR值,需要重新扩展 if (currentValue >= nextValue) { resize(seqName); seqIncr = seqIncrMap.get(seqName); nextValue = seqIncr.getNextValue(); currentValue = seqIncr.getCurrentValue(); } currentValue++; seqIncr.setCurrentValue(currentValue); return paddingVal(String.valueOf(currentValue), length, align); } catch (Exception e) { log.error("获取序列号失败,seqName=" + seqName); throw new ShopException("11201", "获取序列号失败", e); } finally { lock.unlock(); } } @Override public String currVal(String seqName, int length, Align align) { return this.paddingVal(String.valueOf(baseMapper.currVal(seqName)), length, align); } public String paddingVal(String value, int length, Align align) { if (length > value.length()) { if (align.equals(Align.LEFT)) { return padding.substring(0, length - value.length()) + value; } return value + padding.substring(0, length - value.length()); } else if (length < value.length()) { if (align.equals(Align.LEFT)) { return value.substring(value.length() - length, value.length()); } return value.substring(0, value.length() - length); } return value; } private SeqIncr getSeqIncr(String seqName) throws InterruptedException { try { boolean lockFlag = false; lockFlag = redissonLocker.tryLock(seqName, TimeUnit.SECONDS, Constants.LOCK_WAIT_TIME, Constants.LOCK_LEASE_TIME); if (!lockFlag) { log.error("获取分布式失败lockFlag=" + lockFlag + ",seqName=" + seqName); throw new ShopException("11201"); } SeqIncr seqIncr = seqIncrMap.get(seqName); if (null == seqIncr) { seqIncr = this.getOne(new QueryWrapper<SeqIncr>().eq("name", seqName)); if (null == seqIncr) { log.error("获取序列号失败,seqName=" + seqName); throw new ShopException("11201"); } long nextVal = baseMapper.nextVal(seqName); seqIncr.setNextValue(nextVal); seqIncr.setCurrentValue(nextVal - seqIncr.getIncrement()); //如果增长值小于等于DEFAULT_INCREMENT,直接返回 if (seqIncr.getIncrement().intValue() > DEFAULT_INCREMENT) { seqIncrMap.put(seqName, seqIncr); } } return seqIncr; } finally { redissonLocker.unlock(seqName); } } private void resize(String seqName) { try { boolean lockFlag = false; lockFlag = redissonLocker.tryLock(seqName, TimeUnit.SECONDS, Constants.LOCK_WAIT_TIME, Constants.LOCK_LEASE_TIME); if (!lockFlag) { log.error("获取分布式失败lockFlag=" + lockFlag + ",seqName=" + seqName); throw new ShopException("11201"); } SeqIncr seqIncr = this.getOne(new QueryWrapper<SeqIncr>().eq("name", seqName)); if (null == seqIncr) { log.error("获取序列号失败,seqName=" + seqName); throw new ShopException("11201"); } long nextVal = baseMapper.nextVal(seqName); seqIncr.setNextValue(nextVal); seqIncr.setCurrentValue(nextVal - seqIncr.getIncrement()); seqIncrMap.put(seqName, seqIncr); } finally { redissonLocker.unlock(seqName); } } }
[ "13509030019@163.com" ]
13509030019@163.com
b409f6b38e7998acea0e727d92d6963531d0ceb3
cbb2a3ac5ddc86c1ab0181f760f5483b484cedc1
/app/src/main/java/me/djc/gruduatedaily/view/MainActivity.java
f07b2bcc8e13545ac2f4c9d10a5bae1eb335d446
[]
no_license
JichinX/GruduateDaily
0779f6907dc523be366e93780aed9d4650c4ebd8
cb4867f77fb492140dccf225340c9ac3e242bc17
refs/heads/master
2022-10-19T04:15:18.370807
2019-05-27T16:54:18
2019-05-27T16:54:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,556
java
package me.djc.gruduatedaily.view; import android.content.Intent; import android.net.Uri; import android.util.Log; import android.view.MenuItem; import androidx.annotation.NonNull; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import com.google.android.material.bottomnavigation.BottomNavigationView; import me.djc.base.activity.BaseActivity; import me.djc.base.fragment.IFragmentInteractionListener; import me.djc.gruduatedaily.R; import me.djc.gruduatedaily.view.analysis.AnalysisFragment; import me.djc.gruduatedaily.view.ding.DingFragment; import me.djc.gruduatedaily.view.plan.PlanFragment; /** * 首页Activity */ public class MainActivity extends BaseActivity implements IFragmentInteractionListener { private static final String TAG = "MainActivity"; private BottomNavigationView mNavView; private ConstraintLayout mContainer; private Fragment mDingFragment, mPlanFragment, mAnalysisFragment; private Fragment currentFragment; private FragmentManager mManager; @Override protected void onIntentData(Intent intent) { } @Override protected void onDataInit() { mManager = getSupportFragmentManager(); initFragments(); } private void initFragments() { currentFragment = new Fragment(); mDingFragment = DingFragment.newInstance(); mPlanFragment = PlanFragment.newInstance(); mAnalysisFragment = AnalysisFragment.newInstance(); } @Override protected void onViewInit() { mNavView = findViewById(R.id.nav_view); mContainer = findViewById(R.id.container); mNavView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { changeContentFragment(menuItem.getItemId()); return true; } }); //默认初始化选中1 mNavView.setSelectedItemId(R.id.navigation_ding); } private void showFragment(Fragment eFragment) { Log.i(TAG, "will showFragment: " + eFragment); if (currentFragment != eFragment) { FragmentTransaction transaction = mManager.beginTransaction(); transaction.hide(currentFragment); Log.i(TAG, "hideFragment: " + currentFragment); currentFragment = eFragment; if (!eFragment.isAdded()) { transaction.add(R.id.fragment, eFragment).show(eFragment).commit(); Log.i(TAG, "showFragment: " + eFragment); } else { transaction.show(eFragment).commit(); } } } /** * 切换Fragment * * @param itemId */ private void changeContentFragment(int itemId) { switch (itemId) { case R.id.navigation_ding: showFragment(mDingFragment); break; case R.id.navigation_plane: showFragment(mPlanFragment); break; case R.id.navigation_static: showFragment(mAnalysisFragment); break; default: break; } } @Override protected int getContentLayoutRes() { return R.layout.activity_main; } @Override public void onFragmentInteraction(String tag, Uri uri) { } }
[ "xujichang@outlook.com" ]
xujichang@outlook.com
1dc9d54e7b8a6476b1f5d30d99ac886d0f235442
58e4b974229bf6b6ea0fb6036d941432d2ab597d
/app/src/main/java/com/scatl/uestcbbs/activities/BlackUserActivity.java
02c264999057ef96244d224e74cabfbd48c88f50
[ "Apache-2.0" ]
permissive
scatl/UestcBBS
508b47e97480fbdfc2428be15d934a46e5a5498b
bf970c12e0c600827c39f02496e46a7725feb3ac
refs/heads/master
2022-04-03T13:50:41.557261
2020-02-20T13:36:08
2020-02-20T13:36:08
220,958,682
3
0
null
null
null
null
UTF-8
Java
false
false
5,557
java
package com.scatl.uestcbbs.activities; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.CompoundButton; import android.widget.RelativeLayout; import androidx.annotation.NonNull; import androidx.appcompat.widget.SwitchCompat; import androidx.appcompat.widget.Toolbar; import androidx.coordinatorlayout.widget.CoordinatorLayout; import com.alibaba.fastjson.JSONObject; import com.scatl.uestcbbs.R; import com.scatl.uestcbbs.base.BaseActivity; import com.scatl.uestcbbs.interfaces.OnHttpRequest; import com.scatl.uestcbbs.utils.CommonUtil; import com.scatl.uestcbbs.utils.Constants; import com.scatl.uestcbbs.utils.SharePrefUtil; import com.scatl.uestcbbs.utils.ToastUtil; import com.scatl.uestcbbs.utils.httprequest.HttpRequestUtil; import java.util.HashMap; import java.util.Map; import okhttp3.Call; public class BlackUserActivity extends BaseActivity { private static final String TAG = "BlackUserActivity"; private SwitchCompat black_switch; private RelativeLayout relativeLayout; private Toolbar toolbar; private CoordinatorLayout coordinatorLayout; private int user_id; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_black_user); init(); } /** * author: TanLei * description: */ private void init() { user_id = getIntent().getIntExtra(Constants.Key.USER_ID, Integer.MAX_VALUE); coordinatorLayout = findViewById(R.id.black_user_coorlayout); black_switch = findViewById(R.id.black_user_switch); relativeLayout = findViewById(R.id.black_user_rl); relativeLayout.setVisibility(View.GONE); toolbar = findViewById(R.id.black_user_toolbar); setSupportActionBar(toolbar); toolbar.setTitle("黑名单操作"); if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); getUserData(); black_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (! compoundButton.isPressed()) return; blackUser(b ? "black" : "delblack"); } }); } /** * author: TanLei * description: 获取用户数据 */ private void getUserData() { Map<String, String> map = new HashMap<>(); map.put("userId", user_id + ""); map.put("accessToken", SharePrefUtil.getAccessToken(this)); map.put("accessSecret", SharePrefUtil.getAccessSecret(this)); map.put("apphash", CommonUtil.getAppHashValue()); HttpRequestUtil.post(Constants.Api.GET_USER_INFO, map, new OnHttpRequest() { @Override public void onRequestError(Call call, Exception e, int id) { ToastUtil.showSnackBar(coordinatorLayout, getResources().getString(R.string.request_error)); } @Override public void onRequestInProgress(float progress, long total, int id) { } @Override public void onRequestSuccess(String response, int id) { JSONObject jsonObject = JSONObject.parseObject(response); int rs = jsonObject.getIntValue("rs"); //通常 1 表示成功,0 表示失败。 if (rs == 1) { relativeLayout.setVisibility(View.VISIBLE); int is_black = jsonObject.getIntValue("is_black"); black_switch.setChecked(is_black == 1); } else { black_switch.setEnabled(false); ToastUtil.showSnackBar(coordinatorLayout, jsonObject.getString("errcode")); } } }); } /** * author: TanLei * description: 黑名单操作 */ private void blackUser(String type) { Map<String, String> map = new HashMap<>(); map.put("uid", user_id + ""); map.put("type", type); map.put("accessToken", SharePrefUtil.getAccessToken(this)); map.put("accessSecret", SharePrefUtil.getAccessSecret(this)); map.put("apphash", CommonUtil.getAppHashValue()); HttpRequestUtil.post(Constants.Api.BLACK_USER, map, new OnHttpRequest() { @Override public void onRequestError(Call call, Exception e, int id) { black_switch.setChecked(! black_switch.isChecked()); ToastUtil.showSnackBar(coordinatorLayout, "操作失败"); } @Override public void onRequestInProgress(float progress, long total, int id) { } @Override public void onRequestSuccess(String response, int id) { JSONObject jsonObject = JSONObject.parseObject(response); int rs = jsonObject.getIntValue("rs"); //通常 1 表示成功,0 表示失败。 if (rs == 1) { black_switch.setChecked(black_switch.isChecked()); } ToastUtil.showSnackBar(coordinatorLayout, jsonObject.getString("errcode")); } }); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); break; } return super.onOptionsItemSelected(item); } }
[ "sca_tl@foxmail.com" ]
sca_tl@foxmail.com
16a0a1986f56bbf42a0c38315772eb438b68594a
65eac80b75dd1e3b9f79504c25558347d79df9e7
/juc/src/main/java/ac/cn/saya/juc/print/PrintABCTest.java
2e036b0d2ddaf1f30ed27fbdddce54478f763f77
[ "Apache-2.0" ]
permissive
saya-ac-cn/java-utils
b07b4a40fa71941e5952ef415327c8839e0993ac
a49ba01e0beb3bec0e8e56ea7e55b7fb6aa1a897
refs/heads/master
2023-05-27T21:15:21.668806
2023-05-26T14:08:38
2023-05-26T14:08:38
182,410,675
0
0
Apache-2.0
2022-06-21T04:21:45
2019-04-20T13:40:41
Java
UTF-8
Java
false
false
3,443
java
package ac.cn.saya.juc.print; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * @Title: PrintABCTest * @ProjectName java-utils * @Description: TODO * @Author liunengkai * @Date: 2019-04-21 17:37 * @Description: * 编写一个程序,开启3个线程,这3个线程的ID分别为A B C ,每个线程将自己的ID在屏幕上打印10遍,要求输出的结果必须按顺序显示 * 如:ABCABC */ public class PrintABCTest { public static void main(String[] args){ PrintABC printABC = new PrintABC(); new Thread(new Runnable() { @Override public void run() { for (int i = 1; i <= 20; i++){ printABC.loopA(i); } } },"A").start(); new Thread(new Runnable() { @Override public void run() { for (int i = 1; i <= 20; i++){ printABC.loopB(i); } } },"B").start(); new Thread(new Runnable() { @Override public void run() { for (int i = 1; i <= 20; i++){ printABC.loopC(i); } } },"C").start(); } } class PrintABC{ private String number = "A"; private Lock lock = new ReentrantLock(); private Condition conditionA = lock.newCondition(); private Condition conditionB = lock.newCondition(); private Condition conditionC = lock.newCondition(); // 打印A public void loopA(int totalLoop){ lock.lock(); try{ // 1、判断 if(!number.equals("A")){ conditionA.await(); } // 2、打印 for (int i = 1; i <= 5; i++){ System.out.println(Thread.currentThread().getName()+"\t"+ i + "\t" + totalLoop); } // 3、通知唤醒,让B打印 number = "B"; conditionB.signal(); }catch (Exception e){ e.printStackTrace(); }finally { lock.unlock(); } } // 打印B public void loopB(int totalLoop){ lock.lock(); try{ // 1、判断 if(!number.equals("B")){ conditionB.await(); } // 2、打印 for (int i = 1; i <= 5; i++){ System.out.println(Thread.currentThread().getName()+"\t"+ i + "\t" + totalLoop); } // 3、唤醒,让C打印 number = "C"; conditionC.signal(); }catch (Exception e){ e.printStackTrace(); }finally { lock.unlock(); } } // 打印C public void loopC(int totalLoop){ lock.lock(); try{ // 1、判断 if(!number.equals("C")){ conditionC.await(); } // 2、打印 for (int i = 1; i <= 5; i++){ System.out.println(Thread.currentThread().getName()+"\t"+ i + "\t" + totalLoop); } System.out.println("--------"); // 3、唤醒,让A打印 number = "A"; conditionA.signal(); }catch (Exception e){ e.printStackTrace(); }finally { lock.unlock(); } } }
[ "saya@saya.ac.cn" ]
saya@saya.ac.cn
8e80e57b9ab164b1608f8921ff317efe7fe93089
ba309bbe9ee8b27e5098b60b521286e41e242bf8
/todolist-core/src/main/java/io/github/todolist/core/domain/Todo.java
c99d39b74d24503ae407b89fceb9017740e5f316
[ "MIT" ]
permissive
snyk-matt/java-goof
4aeb5b84e4adbe071301e6c9bed992d3acc86d49
4087733a1ccca91b037089ed2110eec47d48e274
refs/heads/master
2023-08-04T17:29:49.946736
2021-02-05T19:16:20
2021-02-05T19:16:20
244,911,606
0
0
Apache-2.0
2020-03-04T13:49:21
2020-03-04T13:46:44
JavaScript
UTF-8
Java
false
false
5,283
java
/* * The MIT License * * Copyright (c) 2015, Mahmoud Ben Hassine (mahmoud.benhassine@icloud.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.github.todolist.core.domain; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.Serializable; import java.nio.file.Path; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * Todo entity. * * @author Mahmoud Ben Hassine (mahmoud.benhassine@icloud.com) */ @Entity @NamedQueries({ @NamedQuery(name = "findTodosByUser", query = "SELECT t FROM Todo t where t.userId = ?1 order by t.dueDate"), @NamedQuery(name = "findTodosByTitle", query = "SELECT t FROM Todo t where t.userId = ?1 and upper(t.title) like ?2 order by t.dueDate") }) public class Todo implements Serializable { // If the JAVA_HOME isn't set, use the Heroku Java location static final String NATIVE2ASCII = System.getProperty("JAVA_HOME", "./.jdk") + File.separator + "bin" + File.separator + "native2ascii"; @Id @GeneratedValue private long id; private long userId; @Column(length = 512) private String title; private boolean done; @Enumerated(value = EnumType.ORDINAL) private Priority priority; @Temporal(TemporalType.DATE) private Date dueDate; public Todo() { priority = Priority.LOW; } public Todo(long userId, String title, boolean done, Priority priority, Date dueDate) { this.userId = userId; if (title != null) title = native2ascii(title); this.title = title; this.done = done; this.priority = priority; this.dueDate = dueDate; } private static BufferedReader getOutput(Process p) { return new BufferedReader(new InputStreamReader(p.getInputStream())); } private String native2ascii(String title) { System.out.println("Running: " + NATIVE2ASCII); try { BufferedWriter writer = new BufferedWriter(new FileWriter("title.txt")); writer.write(title); writer.close(); Process p = Runtime.getRuntime().exec(NATIVE2ASCII + " title.txt"); BufferedReader output = getOutput(p); String line = ""; while ((line = output.readLine()) != null) { if(!title.equals(line)) System.out.println("Found non-ascii title. Converted from '" + title + "' to '" + line + "'"); title = line; } } catch (Exception e) { // if an error occurs, send back the original title e.printStackTrace(); } return title; } public long getId() { return id; } public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = native2ascii(title); } public boolean isDone() { return done; } public void setDone(boolean done) { this.done = done; } public Priority getPriority() { return priority; } public void setPriority(Priority priority) { this.priority = priority; } public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; } @Override public String toString() { final StringBuilder sb = new StringBuilder("Todo{"); sb.append("id=").append(id); sb.append(", userId=").append(userId); sb.append(", title='").append(title).append('\''); sb.append(", done=").append(done); sb.append(", priority=").append(priority); sb.append(", dueDate=").append(dueDate); sb.append('}'); return sb.toString(); } }
[ "59509697+snyk-matt@users.noreply.github.com" ]
59509697+snyk-matt@users.noreply.github.com
7744c388a3717ca9dbc5f19c28fdb75ce8c7cfa7
0ce176ca3a951885a7250b7b134457cf86373e5a
/src/main/java/CreationalPattern/singletonPattern/example/main.java
d59689169aae364491154c12803011a2192a2b10
[]
no_license
tianhong92/designPatternStudy
eb7cadf19d44a44251bbafd83132dd5e10d59ae2
2cd6b533ba23ea16a62ab724326d119c7d6e2dec
refs/heads/master
2020-03-31T20:30:00.156453
2018-10-24T03:51:36
2018-10-24T03:51:36
152,543,105
0
0
null
null
null
null
UTF-8
Java
false
false
214
java
package CreationalPattern.singletonPattern.example; public class main { public static void main(String[] args) { SingleObject object = SingleObject.getInstance(); object.showMessage(); } }
[ "tianhong229@gmail.com" ]
tianhong229@gmail.com
a45200013c490e23d6e3d0cddf4a6fcd19f4a50c
1f19aec2ecfd756934898cf0ad2758ee18d9eca2
/u-1/u-11/u-11-111/u-11-111-1112/u-11-111-1112-f2075.java
99ed7dfeda340d04c8bc5dde4e9f5651d77385f1
[]
no_license
apertureatf/perftest
f6c6e69efad59265197f43af5072aa7af8393a34
584257a0c1ada22e5486052c11395858a87b20d5
refs/heads/master
2020-06-07T17:52:51.172890
2019-06-21T18:53:01
2019-06-21T18:53:01
193,039,805
0
0
null
null
null
null
UTF-8
Java
false
false
106
java
mastercard 5555555555554444 4012888888881881 4222222222222 378282246310005 6011111111111117 9588985165679
[ "jenkins@khan.paloaltonetworks.local" ]
jenkins@khan.paloaltonetworks.local
4061b55c8972fcddfa685bc639adef73d884cbfd
6ea26be2d82a74de3a726fac4aa2589334d56211
/src/main/java/io/github/jhipster/application/ApplicationWebXml.java
37fccea53cad8d1f59b77660e061f50b6314eb1d
[]
no_license
alexandrebotta/jhipster-objective-okrs
269c58cbbad122d8fdb06647acad2d7cd51f855c
4f2550eddbe0aa813f31d2dadf959f002ee57fc8
refs/heads/master
2020-05-09T22:44:47.772790
2019-04-15T12:28:10
2019-04-15T12:28:10
181,480,828
0
0
null
2019-04-15T12:28:57
2019-04-15T12:21:49
Java
UTF-8
Java
false
false
857
java
package io.github.jhipster.application; import io.github.jhipster.application.config.DefaultProfileUtil; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; /** * This is a helper Java class that provides an alternative to creating a web.xml. * This will be invoked only when the application is deployed to a Servlet container like Tomcat, JBoss etc. */ public class ApplicationWebXml extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { /** * set a default to use when no profile is configured. */ DefaultProfileUtil.addDefaultProfile(application.application()); return application.sources(ObjectiveOkrsApp.class); } }
[ "jhipster-bot@jhipster.tech" ]
jhipster-bot@jhipster.tech
d9f6a5fd6c09c3327425bae1348286f9af74bca6
f19446f2b329642f9b1d613ff593eb8802fd7fa8
/app/src/main/java/com/luosenen/huel/utils/MyUtils.java
41258e74122b7b54784c1ea4eb309b0b582b57b0
[]
no_license
luoenen/Verify-HUEL-Seat
58e2b31b2b1e8ffbd875925aa3f592180c5ec747
51b134675ecb39026b5fc03a19fee44c8560aa7f
refs/heads/master
2020-05-25T23:32:20.530263
2019-05-22T12:43:36
2019-05-22T12:43:36
188,036,670
0
0
null
null
null
null
UTF-8
Java
false
false
6,228
java
package com.luosenen.huel.utils; import android.util.Log; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MyUtils { public static String netWork(String url,String cookie, HashMap<String,String> header) throws IOException { Document doc = (Document) Jsoup.connect(url).ignoreContentType(true).headers(header).get(); return doc.body().text(); } public static String getJs(String url,HashMap<String,String> header) throws IOException { List<String> jss = new ArrayList<>(); Document doc = (Document) Jsoup.connect(url).headers(header).get(); Elements links = ((Element) doc).select("script"); for (Element link : links) { String linkHref = link.attr("src"); if(!linkHref.equals("")){ Log.i("jsss",linkHref); jss.add(linkHref); } } if(jss.size()==2){ String js[] = jss.get(1).split("/"); Log.i("7js",js[7]); return js[7]; }else { String js[] = jss.get(2).split("/"); Log.i("7js",js[7]); return js[7]; } } public static String cv(String c,Map<String,String> cv){ cv = new HashMap<>(); cv.put("XDFsK2hRQrEAMJtR","xmShQQ7SaY3"); cv.put("hSNQnPyN3zf3jbQz","pNT8tdaT"); cv.put("MGYaYRCEp5JARsBT","YS2AWje"); cv.put("knBe7batAktyw2MB","i6R5FwWwbAyH"); cv.put("XwrzkzZ5nr4w6FWi","A7hYcwdThpfXDs"); cv.put("JBQdQwZ75idj747i","sECk8n"); cv.put("kwBQ6zAazmP7fcpZ","GfrjAs"); cv.put("fJ3FeX2MWmxGP4MW","CQ2w8Kx6QitBZh7"); cv.put("APp6QpMm56RTQXFn","RAFBQsSQ8PD"); cv.put("MSeFjttBD3nTCtwH","2WMpkYnmZ5"); cv.put("PY3cN4imk5EQThnF","XSCF37jDYdz"); cv.put("PQpjAnxt68SZ7xTK","GhBikixQsJEr"); cv.put("YaSp7MxDxwweMNHc","rJh5pd8Bi6tk2Jm"); cv.put("ZphPm2MWPXaXe4wd","6F8an8GmKh2pjAN"); cv.put("QfKXDYT5MXJj6z8c","Y752kB"); cv.put("rDdQD8f8rwF7jFjz","YdNtiF"); cv.put("8rhZ5QcMMfMm5pCa","cr3bjxZAJ7AMF3y"); cv.put("b5NMSASXRKFSsBG3","Zm67%C3%86YF"); cv.put("pCMa3yDitNJ4MNxZ","Em6rya32Qs4p"); cv.put("QA8KwfM2tZRaBCKp","3mDxm5cz7Sbk"); cv.put("FkbhKtzPmHEKZa4Q","NSSJyYp53"); cv.put("w4BZ4n6jymP6CKcS","Sn6iBrnQn"); cv.put("prHnnwfSfYsprrC8","dcsBzzizpiS6Y7f"); cv.put("t3DHEF5Hxsf3NjSi","QMss78iaxK"); cv.put("7hWyFHt4pr2AF3BE","ZfZG2mSaKDC"); cv.put("SzNebPNzGbkaETnW","KzZJcpGyJe"); cv.put("HGFxTc7PYDJtB86c","BmQAzZzPxBsH7xX"); cv.put("ZcBhmx8NiWEpxerk","mRKtQBCiCenPS"); cv.put("eCAiwFMydcTrxeW5","nAx8ekydKYs"); cv.put("HGZKrGt5ABT8QfNa","ezYw3f"); cv.put("ibKXDX8dtcRTCpdZ","DeDM7aSKfmKDD8"); cv.put("dHSYWKZyEfFZFWAy","DymFXaDw"); cv.put("ZFQdjnFzRHp5n7wn","6ArCwESBD4"); cv.put("T7JiQnstDmEDihJE","tz3JpJ"); cv.put("2k3Qa2FtdtZD3T63","7GxakmDpmxz"); cv.put("FRnWXMx8Qd6akF38","fzaapfSpixhw"); cv.put("C26ze47mCCNXppxY","TKMGmdRcMmB7f"); cv.put("c8aFXkGXtStRXWCe","nym5pzyS8sTzMp"); cv.put("3PDbtG4y2EbCwXeS","p7amPiTBWMm"); cv.put("Tzj36Qe5kD3iFH4N","rb5Eij4nKJi"); cv.put("ZAh2sRExKjd6X3Kp","YKQh5M8fm8"); cv.put("wCGybQXrDHPQeM5B","PQnjzYN7nEsD"); cv.put("4bAEGCeQ5EjTWSsC","MR5CzSmKs8aK"); cv.put("AS4wt4wpk6sY4kbJ","ZpksXrYTT"); cv.put("i6aktSYrpMs2X48y","wkzAYtS"); cv.put("rTEYNRMaT7CexYZW","MERkHtxFzsZP"); cv.put("S76AAffwzXPGGYki","fj7aHyJN"); cv.put("kjmCcGchHriBrzNM","6xTahhmpymQdhH"); cv.put("PAhkcFtcXPkxMAic","mbjsGm"); cv.put("hhJKPkkPCZNmpY6C","6F7RiAJb"); cv.put("28jhHRbfHQBjsecd","xdrbtN8M%C2%A5eJpm"); cv.put("s7SYKZepdwyG8taC","p6XPNBBR"); cv.put("jxQ27QfSfWmhkGkk","Q3CXtGhwn"); cv.put("t66Dky7WDsAsbJDx","BpW47kne"); cv.put("beb7srX24CGcwr7e","FMDDs4sBymznP"); cv.put("6rQcWXfEj2aZi2Z2","n5HHWTS"); cv.put("AQyRYXe5axkbDkMz","nZNkM6irGdb"); cv.put("aR4RJnZARiijjnDA","nFDGYkYDfnca"); cv.put("7BPwQxMX7z862TFf","GDi82CGxz"); cv.put("py5zZ38pGEYi7fEr","8H7SBmmXNQN"); cv.put("Wbi7yrjtC37MCJkF","mc6hz6MN57ZX"); cv.put("HMmjr5Kj6Dn7Hjcz","MW53STa25jaSzf"); cv.put("4zBa4iHiZjMRaFGB","Q2WBATsSN"); cv.put("3bzbNSkJE7t6CcHS","3hpWAm3TzpDMK7b"); cv.put("ERZYECATnk3rpy57","Rd7mhiBe"); cv.put("5KT7Whe76jHa3M3F","iQmkpd335"); cv.put("PebyiyYahBRTxD74","7NAp7c2Qc"); cv.put("MBmMtxNjrff6DJey","FY6cCjZWZHid"); cv.put("MAzFQsYHehKRzzep","225Q5hp4"); cv.put("KRyKsS2D6ktz75fb","JZwSYP"); cv.put("neXpwwKdzSpNdfmR","QDc28PEmPeZhWcd"); cv.put("yntthnW7zGFpdnXk","YbBWtysQw78mF4D"); cv.put("3ccftFcXbSJw6F3t","aCAbA7XXEZ6"); cv.put("nHen28SZTwcf8nZm","iB7p8WNJifGM"); cv.put("bbJfKEDp4KMTsT8w","m7J6fJ7KtXRZ"); cv.put("Y4xBeJD6zXGRTnyB","5GfKr4dwk"); cv.put("DsZQTEXTNbkjMWZr","53BSbfcpDyyJFc"); cv.put("hesYDysNwKAMz5e5","Mf6wBQh7yhe"); cv.put("3PTsCdrfyYiWjkeC","BRPMH5"); cv.put("YTPhNW3a5h5nfwAk","ZmhfjkBX2f"); cv.put("YFaM4BTAeWeS6Pbh","wJWrphQp"); cv.put("z7JbNX5hJipx3wJN","RQTM52XnkdcpAKA"); cv.put("68hjEEbWxDiYn6by","sTKmM3nQBnQEx"); cv.put("NJHB5zmPtt8zHHXw","MRSmY8r3mEJe4"); cv.put("B7aZQHibD8wdAcG2","EW4dAH"); cv.put("8zieCQ2xtBYx6pEJ","fxmWAsRMwM"); cv.put("BDCDmSnKrfBGJZXE","DTb3RP6HttnwDS"); cv.put("67nYG5rSWJtmmTK8","AAywFjhHrN8ZP"); cv.put("7yAy5AbRT7RiRm43","HQsRKYa2Y"); cv.put("6hrt64i4SEsyFzfp","WYEGEY5hAD5"); cv.put("ctf4Ki8BbKsB8NpT","Q75N7RCr"); cv.put("pDbG6aHte2b3Q8iG","7GxakmDpmxz"); cv.put("rhJnmJbyTXefSKcx","KKfixBstziEJjYj"); cv.put("dABf7twxc7Efmyfm","RAFBQsSQ8PD"); cv.put("NAcyx8EyssQ4tazr","5xNxN6252p7QGT"); return cv.get(c); } }
[ "luosenen@gmail.com" ]
luosenen@gmail.com
4ada8fe83ec28c1443ed3bf5d51e4f198d522158
95c49f466673952b465e19a5ee3ae6eff76bee00
/src/main/java/com/p803ss/android/socialbase/downloader/impls/RetryScheduler.java
e090c03461741782fe3b03343ed2f3b5bb75eb00
[]
no_license
Phantoms007/zhihuAPK
58889c399ae56b16a9160a5f48b807e02c87797e
dcdbd103436a187f9c8b4be8f71bdf7813b6d201
refs/heads/main
2023-01-24T01:34:18.716323
2020-11-25T17:14:55
2020-11-25T17:14:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
24,280
java
package com.p803ss.android.socialbase.downloader.impls; import android.content.Context; import android.net.ConnectivityManager; import android.net.Network; import android.net.NetworkInfo; import android.net.NetworkRequest; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.text.TextUtils; import android.util.SparseArray; import com.alipay.sdk.data.C1594a; import com.p803ss.android.socialbase.downloader.downloader.C7189b; import com.p803ss.android.socialbase.downloader.p830a.AppStatusManager; import com.p803ss.android.socialbase.downloader.p834e.BaseException; import com.p803ss.android.socialbase.downloader.p834e.DownloadOutOfSpaceException; import com.p803ss.android.socialbase.downloader.p835f.C7200a; import com.p803ss.android.socialbase.downloader.p836g.DownloadInfo; import com.p803ss.android.socialbase.downloader.p841k.DownloadSetting; import com.p803ss.android.socialbase.downloader.p843m.DownloadUtils; import com.xiaomi.mipush.sdk.Constants; import java.util.ArrayList; import org.json.JSONObject; /* renamed from: com.ss.android.socialbase.downloader.impls.r */ /* compiled from: RetryScheduler */ public class RetryScheduler implements Handler.Callback, AppStatusManager.AbstractC7131a { /* renamed from: a */ private static volatile RetryScheduler f30582a; /* renamed from: b */ private final Context f30583b = C7189b.m43079B(); /* renamed from: c */ private final Handler f30584c = new Handler(Looper.getMainLooper(), this); /* renamed from: d */ private final SparseArray<C7240a> f30585d = new SparseArray<>(); /* renamed from: e */ private final boolean f30586e; /* renamed from: f */ private long f30587f; /* renamed from: g */ private int f30588g = 0; /* renamed from: h */ private ConnectivityManager f30589h; private RetryScheduler() { m44308f(); this.f30586e = DownloadUtils.m44538c(); AppStatusManager.m42701a().mo45559a(this); } /* renamed from: a */ public static RetryScheduler m44291a() { if (f30582a == null) { synchronized (RetryScheduler.class) { if (f30582a == null) { f30582a = new RetryScheduler(); } } } return f30582a; } /* renamed from: f */ private void m44308f() { if (DownloadSetting.m44354b().mo46461a("use_network_callback", 0) == 1) { C7189b.m43116k().execute(new Runnable() { /* class com.p803ss.android.socialbase.downloader.impls.RetryScheduler.RunnableC72361 */ public void run() { try { if (RetryScheduler.this.f30583b != null && Build.VERSION.SDK_INT >= 21) { RetryScheduler.this.f30589h = (ConnectivityManager) RetryScheduler.this.f30583b.getApplicationContext().getSystemService("connectivity"); RetryScheduler.this.f30589h.registerNetworkCallback(new NetworkRequest.Builder().build(), new ConnectivityManager.NetworkCallback() { /* class com.p803ss.android.socialbase.downloader.impls.RetryScheduler.RunnableC72361.C72371 */ public void onAvailable(Network network) { C7200a.m43495b("RetryScheduler", "network onAvailable: "); RetryScheduler.this.m44293a((RetryScheduler) 1, true); } }); } } catch (Exception e) { e.printStackTrace(); } } }); } } /* renamed from: a */ public void mo46442a(DownloadInfo cVar) { if (cVar != null && "application/vnd.android.package-archive".contains(cVar.mo46145ah())) { m44294a(cVar, cVar.mo46231x(), m44309g()); } } /* renamed from: a */ private void m44294a(DownloadInfo cVar, boolean z, int i) { BaseException aW = cVar.mo46134aW(); if (aW != null) { C7240a b = m44301b(cVar.mo46197g()); if (b.f30605i > b.f30599c) { C7200a.m43498d("RetryScheduler", "tryStartScheduleRetry, id = " + b.f30597a + ", mRetryCount = " + b.f30605i + ", maxCount = " + b.f30599c); return; } int a = aW.mo45987a(); if (!DownloadUtils.m44554g(aW) && !DownloadUtils.m44556h(aW)) { if (m44298a(b, a)) { C7200a.m43497c("RetryScheduler", "white error code, id = " + b.f30597a + ", error code = " + a); } else { return; } } b.f30606j = z; synchronized (this.f30585d) { if (!b.f30608l) { b.f30608l = true; this.f30588g++; } } int d = b.mo46455d(); C7200a.m43497c("RetryScheduler", "tryStartScheduleRetry: id = " + b.f30597a + ", delayTimeMills = " + d + ", mWaitingRetryTasks = " + this.f30588g); if (b.f30602f) { if (i == 0) { b.mo46454c(); } RetryJobSchedulerService.m43964a(cVar, (long) d, z, i); if (this.f30586e) { b.mo46451a(System.currentTimeMillis()); b.mo46453b(); b.mo46450a(); } } else if (!z) { this.f30584c.removeMessages(cVar.mo46197g()); this.f30584c.sendEmptyMessageDelayed(cVar.mo46197g(), (long) d); } } } public boolean handleMessage(Message message) { if (message.what == 0) { m44302b(message.arg1, message.arg2 == 1); } else { C7200a.m43497c("RetryScheduler", "handleMessage, doSchedulerRetry, id = " + message.what); mo46441a(message.what); } return true; } /* access modifiers changed from: private */ /* access modifiers changed from: public */ /* JADX WARNING: Code restructure failed: missing block: B:13:0x001b, code lost: com.p803ss.android.socialbase.downloader.p835f.C7200a.m43497c("RetryScheduler", "scheduleAllTaskRetry, level = [" + r8 + "], force = [" + r9 + "]"); */ /* JADX WARNING: Code restructure failed: missing block: B:14:0x0043, code lost: if (r9 == false) goto L_0x004a; */ /* JADX WARNING: Code restructure failed: missing block: B:15:0x0045, code lost: r7.f30584c.removeMessages(0); */ /* JADX WARNING: Code restructure failed: missing block: B:16:0x004a, code lost: r1 = android.os.Message.obtain(); r1.what = 0; r1.arg1 = r8; r1.arg2 = r9 ? 1 : 0; r7.f30584c.sendMessageDelayed(r1, 2000); */ /* JADX WARNING: Code restructure failed: missing block: B:17:0x005b, code lost: return; */ /* renamed from: a */ private void m44293a(int i, boolean z) { if (this.f30588g > 0) { long currentTimeMillis = System.currentTimeMillis(); synchronized (this) { if (!z) { if (currentTimeMillis - this.f30587f < 20000) { return; } } this.f30587f = currentTimeMillis; } } } /* renamed from: b */ private void m44302b(final int i, final boolean z) { C7189b.m43116k().execute(new Runnable() { /* class com.p803ss.android.socialbase.downloader.impls.RetryScheduler.RunnableC72382 */ public void run() { int g; try { if (RetryScheduler.this.f30588g > 0 && (g = RetryScheduler.this.m44309g()) != 0) { C7200a.m43497c("RetryScheduler", "doScheduleAllTaskRetry: mWaitingRetryTasksCount = " + RetryScheduler.this.f30588g); long currentTimeMillis = System.currentTimeMillis(); ArrayList<C7240a> arrayList = new ArrayList(); synchronized (RetryScheduler.this.f30585d) { for (int i = 0; i < RetryScheduler.this.f30585d.size(); i++) { C7240a aVar = (C7240a) RetryScheduler.this.f30585d.valueAt(i); if (aVar != null && aVar.mo46452a(currentTimeMillis, i, g, z)) { if (z) { aVar.mo46454c(); } arrayList.add(aVar); } } } if (arrayList.size() > 0) { for (C7240a aVar2 : arrayList) { RetryScheduler.this.m44292a((RetryScheduler) aVar2.f30597a, g, false); } } } } catch (Exception unused) { } } }); } /* access modifiers changed from: package-private */ /* renamed from: a */ public void mo46441a(final int i) { C7189b.m43116k().execute(new Runnable() { /* class com.p803ss.android.socialbase.downloader.impls.RetryScheduler.RunnableC72393 */ public void run() { try { RetryScheduler.this.m44292a((RetryScheduler) i, RetryScheduler.this.m44309g(), true); } catch (Exception e) { e.printStackTrace(); } } }); } /* access modifiers changed from: private */ /* access modifiers changed from: public */ /* JADX WARNING: Code restructure failed: missing block: B:16:0x002b, code lost: com.p803ss.android.socialbase.downloader.p835f.C7200a.m43497c("RetryScheduler", "doSchedulerRetryInSubThread: downloadId = " + r8 + ", retryCount = " + r2.f30605i + ", mWaitingRetryTasksCount = " + r7.f30588g); r1 = com.p803ss.android.socialbase.downloader.downloader.C7196f.m43215a(r0).mo45842h(r8); */ /* JADX WARNING: Code restructure failed: missing block: B:17:0x0063, code lost: if (r1 != null) goto L_0x0069; */ /* JADX WARNING: Code restructure failed: missing block: B:18:0x0065, code lost: m44304c(r8); */ /* JADX WARNING: Code restructure failed: missing block: B:19:0x0068, code lost: return; */ /* JADX WARNING: Code restructure failed: missing block: B:20:0x0069, code lost: r3 = r1.mo46229w(); */ /* JADX WARNING: Code restructure failed: missing block: B:21:0x006e, code lost: if (r3 == -3) goto L_0x00f7; */ /* JADX WARNING: Code restructure failed: missing block: B:23:0x0071, code lost: if (r3 != -4) goto L_0x0075; */ /* JADX WARNING: Code restructure failed: missing block: B:25:0x0076, code lost: if (r3 != -5) goto L_0x0089; */ /* JADX WARNING: Code restructure failed: missing block: B:26:0x0078, code lost: r9 = com.p803ss.android.socialbase.downloader.downloader.C7189b.m43120o(); */ /* JADX WARNING: Code restructure failed: missing block: B:27:0x007c, code lost: if (r9 == null) goto L_0x0085; */ /* JADX WARNING: Code restructure failed: missing block: B:28:0x007e, code lost: r9.mo45417a(java.util.Collections.singletonList(r1)); */ /* JADX WARNING: Code restructure failed: missing block: B:29:0x0085, code lost: m44304c(r8); */ /* JADX WARNING: Code restructure failed: missing block: B:30:0x0088, code lost: return; */ /* JADX WARNING: Code restructure failed: missing block: B:32:0x008a, code lost: if (r3 == -1) goto L_0x008d; */ /* JADX WARNING: Code restructure failed: missing block: B:33:0x008c, code lost: return; */ /* JADX WARNING: Code restructure failed: missing block: B:34:0x008d, code lost: if (r9 != 0) goto L_0x0096; */ /* JADX WARNING: Code restructure failed: missing block: B:36:0x0091, code lost: if (r2.f30602f == false) goto L_0x0095; */ /* JADX WARNING: Code restructure failed: missing block: B:37:0x0093, code lost: r4 = false; */ /* JADX WARNING: Code restructure failed: missing block: B:38:0x0095, code lost: return; */ /* JADX WARNING: Code restructure failed: missing block: B:39:0x0096, code lost: r3 = r1.mo46134aW(); */ /* JADX WARNING: Code restructure failed: missing block: B:40:0x009a, code lost: if (r4 == false) goto L_0x00a6; */ /* JADX WARNING: Code restructure failed: missing block: B:42:0x00a0, code lost: if (com.p803ss.android.socialbase.downloader.p843m.DownloadUtils.m44554g(r3) == false) goto L_0x00a6; */ /* JADX WARNING: Code restructure failed: missing block: B:43:0x00a2, code lost: r4 = m44297a(r1, r3); */ /* JADX WARNING: Code restructure failed: missing block: B:44:0x00a6, code lost: r2.mo46453b(); */ /* JADX WARNING: Code restructure failed: missing block: B:45:0x00a9, code lost: if (r4 == false) goto L_0x00ea; */ /* JADX WARNING: Code restructure failed: missing block: B:46:0x00ab, code lost: com.p803ss.android.socialbase.downloader.p835f.C7200a.m43497c("RetryScheduler", "doSchedulerRetry: restart task, ****** id = " + r2.f30597a); r2.mo46451a(java.lang.System.currentTimeMillis()); */ /* JADX WARNING: Code restructure failed: missing block: B:47:0x00cc, code lost: if (r10 == false) goto L_0x00d1; */ /* JADX WARNING: Code restructure failed: missing block: B:48:0x00ce, code lost: r2.mo46450a(); */ /* JADX WARNING: Code restructure failed: missing block: B:49:0x00d1, code lost: r1.mo46095a(r2.f30605i); */ /* JADX WARNING: Code restructure failed: missing block: B:50:0x00dc, code lost: if (r1.mo46222q() != -1) goto L_?; */ /* JADX WARNING: Code restructure failed: missing block: B:51:0x00de, code lost: com.p803ss.android.socialbase.downloader.downloader.C7196f.m43215a(r0).mo45839e(r1.mo46197g()); */ /* JADX WARNING: Code restructure failed: missing block: B:52:0x00ea, code lost: if (r10 == false) goto L_0x00ef; */ /* JADX WARNING: Code restructure failed: missing block: B:53:0x00ec, code lost: r2.mo46450a(); */ /* JADX WARNING: Code restructure failed: missing block: B:54:0x00ef, code lost: m44294a(r1, r1.mo46231x(), r9); */ /* JADX WARNING: Code restructure failed: missing block: B:55:0x00f7, code lost: m44304c(r8); */ /* JADX WARNING: Code restructure failed: missing block: B:56:0x00fa, code lost: return; */ /* JADX WARNING: Code restructure failed: missing block: B:60:?, code lost: return; */ /* JADX WARNING: Code restructure failed: missing block: B:61:?, code lost: return; */ /* JADX WARNING: Code restructure failed: missing block: B:62:?, code lost: return; */ /* renamed from: a */ private void m44292a(int i, int i2, boolean z) { Context context = this.f30583b; if (context != null) { synchronized (this.f30585d) { C7240a aVar = this.f30585d.get(i); if (aVar != null) { boolean z2 = true; if (aVar.f30608l) { aVar.f30608l = false; this.f30588g--; if (this.f30588g < 0) { this.f30588g = 0; } } } } } } /* renamed from: a */ private boolean m44298a(C7240a aVar, int i) { int[] iArr = aVar.f30603g; if (iArr == null || iArr.length == 0) { return false; } for (int i2 : iArr) { if (i2 == i) { return true; } } return false; } /* renamed from: b */ private C7240a m44301b(int i) { C7240a aVar = this.f30585d.get(i); if (aVar == null) { synchronized (this.f30585d) { aVar = this.f30585d.get(i); if (aVar == null) { aVar = m44306d(i); } this.f30585d.put(i, aVar); } } return aVar; } /* renamed from: c */ private void m44304c(int i) { synchronized (this.f30585d) { this.f30585d.remove(i); } } /* renamed from: d */ private C7240a m44306d(int i) { int[] iArr; boolean z; int i2; int i3; DownloadSetting a = DownloadSetting.m44347a(i); boolean z2 = false; int a2 = a.mo46461a("retry_schedule", 0); JSONObject d = a.mo46469d("retry_schedule_config"); int i4 = 60; if (d != null) { int optInt = d.optInt("max_count", 60); int optInt2 = d.optInt("interval_sec", 60); int optInt3 = d.optInt("interval_sec_acceleration", 60); if (Build.VERSION.SDK_INT >= 21 && d.optInt("use_job_scheduler", 0) == 1) { z2 = true; } iArr = m44299a(d.optString("white_error_code")); i3 = optInt3; z = z2; i2 = optInt; i4 = optInt2; } else { iArr = null; i3 = 60; i2 = 60; z = false; } return new C7240a(i, a2, i2, i4 * 1000, i3 * 1000, z, iArr); } /* renamed from: a */ private int[] m44299a(String str) { if (TextUtils.isEmpty(str)) { return null; } try { String[] split = str.split(Constants.ACCEPT_TIME_SEPARATOR_SP); if (split.length <= 0) { return null; } int[] iArr = new int[split.length]; for (int i = 0; i < split.length; i++) { iArr[i] = Integer.parseInt(split[i]); } return iArr; } catch (Throwable unused) { return null; } } @Override // com.p803ss.android.socialbase.downloader.p830a.AppStatusManager.AbstractC7131a /* renamed from: b */ public void mo45149b() { m44293a(4, false); } @Override // com.p803ss.android.socialbase.downloader.p830a.AppStatusManager.AbstractC7131a /* renamed from: c */ public void mo45151c() { m44293a(3, false); } /* renamed from: d */ public void mo46443d() { m44293a(2, false); } /* renamed from: e */ public void mo46444e() { m44293a(5, false); } /* access modifiers changed from: private */ /* access modifiers changed from: public */ /* renamed from: g */ private int m44309g() { try { if (this.f30589h == null) { this.f30589h = (ConnectivityManager) this.f30583b.getApplicationContext().getSystemService("connectivity"); } NetworkInfo activeNetworkInfo = this.f30589h.getActiveNetworkInfo(); if (activeNetworkInfo != null) { if (activeNetworkInfo.isConnected()) { return activeNetworkInfo.getType() == 1 ? 2 : 1; } } return 0; } catch (Exception unused) { return 0; } } /* renamed from: a */ private boolean m44297a(DownloadInfo cVar, BaseException aVar) { long j; long j2; try { j = DownloadUtils.m44533c(cVar.mo46214l()); } catch (BaseException e) { e.printStackTrace(); j = 0; } if (aVar instanceof DownloadOutOfSpaceException) { j2 = ((DownloadOutOfSpaceException) aVar).mo46001d(); } else { j2 = cVar.mo46139ab() - cVar.mo46094Z(); } if (j < j2) { DownloadSetting a = DownloadSetting.m44347a(cVar.mo46197g()); if (a.mo46461a("space_fill_part_download", 0) != 1) { return false; } if (j > 0) { int a2 = a.mo46461a("space_fill_min_keep_mb", 100); if (a2 > 0) { long j3 = j - (((long) a2) * 1048576); C7200a.m43497c("RetryScheduler", "retry schedule: available = " + DownloadUtils.m44484a(j) + "MB, minKeep = " + a2 + "MB, canDownload = " + DownloadUtils.m44484a(j3) + "MB"); if (j3 <= 0) { C7200a.m43498d("RetryScheduler", "doSchedulerRetryInSubThread: canDownload <= 0 , canRetry = false !!!!"); return false; } } } else if (a.mo46461a("download_when_space_negative", 0) != 1) { return false; } } return true; } /* access modifiers changed from: private */ /* renamed from: com.ss.android.socialbase.downloader.impls.r$a */ /* compiled from: RetryScheduler */ public static class C7240a { /* renamed from: a */ final int f30597a; /* renamed from: b */ final int f30598b; /* renamed from: c */ final int f30599c; /* renamed from: d */ final int f30600d; /* renamed from: e */ final int f30601e; /* renamed from: f */ final boolean f30602f; /* renamed from: g */ final int[] f30603g; /* renamed from: h */ private int f30604h; /* renamed from: i */ private int f30605i; /* renamed from: j */ private boolean f30606j; /* renamed from: k */ private long f30607k; /* renamed from: l */ private boolean f30608l; C7240a(int i, int i2, int i3, int i4, int i5, boolean z, int[] iArr) { i4 = i4 < 20000 ? C1594a.f7232d : i4; i5 = i5 < 20000 ? C1594a.f7232d : i5; this.f30597a = i; this.f30598b = i2; this.f30599c = i3; this.f30600d = i4; this.f30601e = i5; this.f30602f = z; this.f30603g = iArr; this.f30604h = i4; } /* access modifiers changed from: package-private */ /* renamed from: a */ public boolean mo46452a(long j, int i, int i2, boolean z) { if (!this.f30608l) { C7200a.m43497c("RetryScheduler", "canRetry: mIsWaitingRetry is false, return false!!!"); return false; } else if (this.f30598b < i || this.f30605i >= this.f30599c) { return false; } else { if (this.f30606j && i2 != 2) { return false; } if (z || j - this.f30607k >= ((long) this.f30600d)) { return true; } return false; } } /* access modifiers changed from: package-private */ /* renamed from: a */ public synchronized void mo46450a() { this.f30604h += this.f30601e; } /* access modifiers changed from: package-private */ /* renamed from: a */ public synchronized void mo46451a(long j) { this.f30607k = j; } /* access modifiers changed from: package-private */ /* renamed from: b */ public synchronized void mo46453b() { this.f30605i++; } /* access modifiers changed from: package-private */ /* renamed from: c */ public void mo46454c() { this.f30604h = this.f30600d; } /* access modifiers changed from: package-private */ /* renamed from: d */ public int mo46455d() { return this.f30604h; } } }
[ "seasonpplp@qq.com" ]
seasonpplp@qq.com
3c237aeb7ea3691bee12bc109c9e864b8c6d29de
23954a7d5713fbbe5e35a87c81745907cabc5462
/src/main/java/com/youedata/nncloud/modular/nanning/timer/CreationArticleTimer.java
74ed80f7ddc158772b9c1fae94ff73f21d830640
[]
no_license
lj88811498/db
410a8c5af0f2e7c34bc78996e08650b16ee966e3
fd19c30fff7a5c44ebae34dbe10a6101d67eae74
refs/heads/master
2022-10-07T05:33:43.516126
2020-01-06T09:38:16
2020-01-06T09:38:16
232,068,336
0
0
null
2022-09-01T23:18:23
2020-01-06T09:35:38
JavaScript
UTF-8
Java
false
false
4,670
java
//package com.youedata.nncloud.modular.nanning.timer; // //import com.alibaba.fastjson.JSONObject; //import com.youedata.nncloud.core.util.UrlsUtil; //import com.youedata.nncloud.modular.nanning.model.CreationArticle; //import com.youedata.nncloud.modular.nanning.model.vo.CreationArticleVo; //import com.youedata.nncloud.modular.nanning.service.ICreationArticleService; //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.stereotype.Component; // //import java.net.URLEncoder; //import java.util.ArrayList; //import java.util.List; // //@Component //public class CreationArticleTimer { // private Logger log = LoggerFactory.getLogger(this.getClass()); // // @Autowired // private ICreationArticleService service; // //// @Scheduled(cron = "0 26 10 * * ?") // public void getTech() { // try { // log.info("创新创业-技术前沿-定时器启动"); // String API_URL_TECH = "http://219.159.152.202:8081/INTERFACE.API/f/api/geii_ibdms?key=53ccff6b116740a8bb0ae9c4753a0a9c&category_name=" + URLEncoder.encode("技术前沿", "utf-8") + "&pageIndex=1&pageSize=2000"; // List<CreationArticleVo> json = JSONObject.parseArray(UrlsUtil.loadJson(API_URL_TECH).toString(), CreationArticleVo.class); // List<CreationArticle> list = new ArrayList<>(); // if (json.size() > 0) { // for (CreationArticleVo vo : json) { // //通过反射机制获取对象信息 // CreationArticle creationArticle = (CreationArticle) UrlsUtil.radiation(vo, CreationArticle.class); // list.add(creationArticle); // } // service.insertBatch(list); // } else { // log.info("创新创业-技术前沿接口信息为空或第三方接口异常"); // } // log.info("创新创业-技术前沿-定时器结束"); // } catch (Exception e) { // log.error(e.getMessage()); // } // } // //// @Scheduled(cron = "0 28 10 * * ?") // public void getProduct() { // try { // log.info("创新创业-产品推荐-定时器启动"); // String API_URL_PRODUCT = "http://219.159.152.202:8081/INTERFACE.API/f/api/geii_ibdms?key=53ccff6b116740a8bb0ae9c4753a0a9c&category_name=" + URLEncoder.encode("产品推荐", "utf-8") + "&pageIndex=1&pageSize=1000"; // List<CreationArticleVo> json = JSONObject.parseArray(UrlsUtil.loadJson(API_URL_PRODUCT).toString(), CreationArticleVo.class); // List<CreationArticle> list = new ArrayList<>(); // if (json.size() > 0) { // for (CreationArticleVo vo : json) { // //通过反射机制获取对象信息 // CreationArticle creationArticle = (CreationArticle) UrlsUtil.radiation(vo, CreationArticle.class); // list.add(creationArticle); // } // service.insertBatch(list); // } else { // log.info("创新创业-产品推荐接口信息为空或第三方接口异常"); // } // log.info("创新创业-产品推荐-定时器结束"); // } catch (Exception e) { // log.error(e.getMessage()); // } // } // //// @Scheduled(cron = "0 30 10 * * ?") // public void getReport() { // try { // log.info("创新创业-项目申报-定时器启动"); // String API_URL_REPORT = "http://219.159.152.202:8081/INTERFACE.API/f/api/geii_ibdms?key=53ccff6b116740a8bb0ae9c4753a0a9c&category_name=" + URLEncoder.encode("项目申报", "utf-8") + "&pageIndex=1&pageSize=1000"; // List<CreationArticleVo> json = JSONObject.parseArray(UrlsUtil.loadJson(API_URL_REPORT).toString(), CreationArticleVo.class); // List<CreationArticle> list = new ArrayList<>(); // if (json.size() > 0) { // for (CreationArticleVo vo : json) { // //通过反射机制获取对象信息 // CreationArticle creationArticle = (CreationArticle) UrlsUtil.radiation(vo, CreationArticle.class); // list.add(creationArticle); // } // service.insertBatch(list); // } else { // log.info("创新创业-项目申报接口信息为空或第三方接口异常"); // } // log.info("创新创业-项目申报-定时器结束"); // } catch (Exception e) { // log.error(e.getMessage()); // } // } //}
[ "450416064@qq.com" ]
450416064@qq.com
acbc8b88eab14f464c681eaca12396eb4c362171
10be5d08f7f9a421f9600636931a13e4cc179e12
/src/_08_calculator/calculatorrunner.java
2effe5caec120a9a528fcba54262c90865f02ba2
[]
no_license
League-Level1-Student/level1-module4-jessezhangsems
68731527fe900e70bb04c5d5f8d8f472699c93bc
49395165d6e665134c43ab7b664424d424f402af
refs/heads/master
2023-05-08T01:06:08.925532
2021-06-02T23:27:54
2021-06-02T23:27:54
351,247,600
0
0
null
null
null
null
UTF-8
Java
false
false
133
java
package _08_calculator; public class calculatorrunner { public static void main ( String args[]) { new calculator().setup(); } }
[ "student@ip-172-31-57-14.us-west-2.compute.internal" ]
student@ip-172-31-57-14.us-west-2.compute.internal
b1e6fc7633f7657f8ca3c4974791154dbe3b9df7
4f291ab8aeedcc8e9d6325b41f38a1bf5423163d
/project-yeti/src/yeti/stats/YetiDataTransformer.java
ceeb149fbace667505e78a1807724807ceb15d1e
[ "BSD-2-Clause" ]
permissive
Haegin/York-Extensible-Testing-Infrastructure
7b1a8e94a93d8163f4b2823e3028d6a4aa02f629
d91f17b57d237150bfd5b69dd82edeccac092424
refs/heads/master
2020-05-15T09:21:14.807283
2012-04-05T01:39:05
2012-04-05T01:39:05
3,934,011
1
0
null
null
null
null
UTF-8
Java
false
false
4,127
java
package yeti.stats; /** YETI - York Extensible Testing Infrastructure Copyright (c) 2009-2010, Manuel Oriol <manuel.oriol@gmail.com> - University of York All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by the University of York. 4. Neither the name of the University of York nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; /** * Class that represents a data transformer. * * @author Manuel Oriol (manuel@cs.york.ac.uk) * @date May 7, 2011 * */ public class YetiDataTransformer { public String []categories; public ArrayList<String[]>data = new ArrayList<String[]>(); public YetiDataTransformer(String categories) { this.categories = categories.split(","); } public int addLine(String line) { data.add(line.split(",")); return data.size(); } public void print(int x,int y,int z) { ArrayList<String> xLabels = new ArrayList<String>(); ArrayList<String> yLabels = new ArrayList<String>(); for (String []line: data) { if (!xLabels.contains(line[x])) xLabels.add(line[x]); if (!yLabels.contains(line[y])) yLabels.add(line[y]); } sort(xLabels); sort(yLabels); int xSize=xLabels.size(); int ySize=yLabels.size(); String [][]data = new String[xSize][ySize]; for (String []line: this.data) { int x0 = xLabels.indexOf(line[x]); int y0 = yLabels.indexOf(line[y]); data[x0][y0]=line[z]; } for (String xLabel: xLabels) { System.out.print(","+xLabel); } for(int i=0;i<ySize;i++) { System.out.print("\n"+yLabels.get(i)); for(int j=0;j<xSize;j++) { System.out.print(","); System.out.print(data[j][i]); } } } public ArrayList<String> sort(ArrayList<String> l){ // change if sorting is needed return l; } /** * @param args * @throws IOException, FileNotFoundException */ public static void main(String[] args) throws IOException, FileNotFoundException { if (args.length!=4) { printHelp(); return; } YetiDataTransformer ydt = null; BufferedReader br = new BufferedReader(new FileReader(args[0])); String s = null; if ((s=br.readLine())!=null) { ydt = new YetiDataTransformer(s); while((s=br.readLine())!=null) { ydt.addLine(s); } } int xcolumn = Integer.parseInt(args[1]); int ycolumn = Integer.parseInt(args[2]); int zcolumn = Integer.parseInt(args[3]); ydt.print(xcolumn,ycolumn,zcolumn); } public static void printHelp() { System.out.println("Usage: java yeti.stats.YetiDataTransformer fileName columnNumberForX columnNumberForY columnNumberForZ"); } }
[ "harry@haeg.in" ]
harry@haeg.in
d635a780add49e20d262af45a2386bdfdf8db869
10d60d95b008a16d341208132d4468e6f5a3f89a
/src/ChatEngine.java
07be2dc7f24d6fc9cbb191dcb35ccc827cce9df9
[]
no_license
karolinaSW/Chat
8ac39a42bdd1387864d2c34f68a5c6b86a2c4976
13f2ca3c1adf2680897cee2eef9ae9480df5dcec
refs/heads/master
2020-04-02T15:46:26.863604
2018-10-24T23:35:00
2018-10-24T23:35:00
154,582,551
0
0
null
null
null
null
UTF-8
Java
false
false
4,513
java
import java.util.*; public class ChatEngine { Map <Long, User> usersMapId = new HashMap<>(); Map <String, User> usersMapName = new HashMap<>(); Map <Long, User> loggedInUsersMapId = new HashMap<>(); Map <String, User> loggedInUsersMapName = new HashMap<>(); List <User> usersList = new LinkedList<>();// kolejnosc dodawania uzytkownikow sie liczy // todo: wyjątki long identityNumber = 0; // nr ktory bd przypisywany logujacemu sie userowi //int numberOfUsers = 0; long min, max; double avg; public void registerUser(User user) throws UserLoginException { // rejestracja uzytkownika... //todo: tu zmiana scenariusza if(hasUser(user.name)) { // sprawdz, czy user istnieje w mapie userow // tak - wyjatek, throw new UserLoginException("Uzytkownik o podanej nazwie juz istnieje."); } // nie: identityNumber++; // nowy uzytkownik user.id = identityNumber; usersMapId.put(user.id, user); usersMapName.put(user.name, user); usersList.add(user); } public void loginUser(User user) throws UserLoginException { if (!usersMapId.containsKey(user.id)) { // jesli user nie jest jeszcze zarejestrowany throw new UserLoginException("Nie mozna zalogowac. Uzytkownik o podanej nazwie nie istnieje."); } if (loggedInUsersMapId.containsKey(user.id)) { throw new UserLoginException("Uzytkownik juz jest zalogowany"); } else { loggedInUsersMapName.put(user.name, user); loggedInUsersMapId.put(user.id, user); } } public void logoutUser(User user) throws UserRemoveException { if(!hasUser(user.id)){ throw new UserRemoveException("Nie mozna wylogowac."); } else { loggedInUsersMapId.remove(user.id); loggedInUsersMapName.remove(user.name); } } public int getNumberOfUsers() { if(!(loggedInUsersMapId.size()==loggedInUsersMapName.size())){ System.out.println("Probleeeeemo, mapy zalogowanych sie nie zgadzaja"); } return loggedInUsersMapId.size(); } public void addUserStar(User user) { user.numberOfStars++; } public void removeUserStar(User user) { user.numberOfStars--; } public boolean hasUser(String userName) { if (usersMapName.containsKey(userName)) { return true; } else { return false; } } public boolean hasUser(long userId) { if (loggedInUsersMapId.containsKey(userId)) { return true; } else { return false; } } public boolean broadcastMessage(User user, String message) { System.out.println("Wiadomość: \n" + message + "\n\nWyslana przez " + user.getName() + " do: " ); for(User u: usersList){ // wiadomosc wysylana do wszystkich, zalogowanych czy nie! if(u == user) continue; System.out.println("@" + u.name + " (nr ID: " + u.id + ")"); } System.out.println("\n"); user.numberOfSentMessages++; // userowi, ktory wyslal wiadomosc zwiekszam licznik return true; } public void printStatistics() { List<Long> listOfMessages = new ArrayList<>(); for (Map.Entry<Long, User> entry : usersMapId.entrySet()) { listOfMessages.add(entry.getValue().getNumberOfSentMessages()); } Collections.sort(listOfMessages); min = listOfMessages.get(0); max = listOfMessages.get((listOfMessages.size() - 1)); for (long x : usersMapId.keySet()) { avg += usersMapId.get(x).numberOfSentMessages; } avg = avg / usersMapId.size(); System.out.print("Statystyki: \nNajwiecej wyslanych wiadomosci: " + max + "\nNajmniej wyslanych wiadomosci: " + min + "\nSrednia wyslanych wiadomosci: " + avg + "\n"); for (Map.Entry<Long, User> entry : usersMapId.entrySet()) { System.out.println("ID: " + entry.getKey() + " NAME: " + entry.getValue().getName() + " STARS: " + entry.getValue().getNumberOfStars()); } } public List<User> listUsers (Criteria criteria){ Collections.sort(usersList, criteria); return usersList; } }
[ "karolinaswiergala95@gmail.com" ]
karolinaswiergala95@gmail.com
438a9c8df9293d64cfabd421863868ca7587c17a
ef4f51741e485d36bc3bda40393481bdb500ff24
/TutorPackage/src/de/buffalodan/ci/Pack.java
50d72c7f059af49a80dd9ed38d9d6940ad2a8ac0
[]
no_license
BuffaloDan/CI-Tutorium
b3409f7e97c65a9fe45becb02045f2645543a3ae
24b82b43874ca85de8b05445c4f01b48b216925f
refs/heads/master
2021-01-21T10:19:58.418964
2017-07-20T10:57:41
2017-07-20T10:57:41
91,685,683
0
1
null
2017-05-26T04:20:40
2017-05-18T11:31:47
Java
UTF-8
Java
false
false
4,406
java
package de.buffalodan.ci; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.util.Scanner; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; public class Pack { private static final FilenameFilter JAVA_FILTER = (dir, name) -> { return name.endsWith(".java"); }; private static final FilenameFilter JAR_FILTER = (dir, name) -> { return name.endsWith(".jar") && !name.equals("CI-Library.jar"); }; private static void processJavaFile(File f) throws IOException { String fName = f.getName(); File folder = f.getParentFile(); File ftmp = new File(folder, fName + "_old"); f.renameTo(ftmp); f = ftmp; File newFile = new File(folder, fName); Scanner fileScanner = new Scanner(f); String s = ""; while (!s.startsWith("package")) { s = fileScanner.nextLine(); } FileWriter fileStream = new FileWriter(newFile); BufferedWriter out = new BufferedWriter(fileStream); while (fileScanner.hasNextLine()) { String next = fileScanner.nextLine(); if (next.startsWith("import de.buffalodan")) continue; if (next.equals("\n")) out.newLine(); else out.write(next); out.newLine(); } fileScanner.close(); out.close(); f.delete(); } private static void copyJavaFiles(File folder, File dest) throws IOException { for (File f : folder.listFiles()) { if (f.isDirectory()) { copyJavaFiles(f, dest); } else { if (f.getName().endsWith(".java")) { FileUtils.copyFileToDirectory(f, dest); } } } } public static void compressZipfile(File sourceDir, File outputFile) throws IOException, FileNotFoundException { ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(outputFile)); compressDirectoryToZipfile(sourceDir, zipFile); IOUtils.closeQuietly(zipFile); } private static void compressDirectoryToZipfile(File rootDir, ZipOutputStream out) throws IOException, FileNotFoundException { for (File file : rootDir.listFiles()) { ZipEntry entry = new ZipEntry(file.getName()); out.putNextEntry(entry); FileInputStream in = new FileInputStream(file); IOUtils.copy(in, out); IOUtils.closeQuietly(in); } } private static void createBuildAndRunScript(File libFolder, File tmpFolder) throws IOException { String buildBat = "javac *.java -cp \""; String buildSh = "javac *.java -cp \""; String runBat = "java -cp \""; String runSh = "java -cp \""; boolean f = true; for (String lib:libFolder.list(JAR_FILTER)) { if (f) f=false; else { buildBat += ";"; buildSh += ":"; runBat += ";"; runSh += ":"; } buildBat += lib; buildSh += lib; runBat += lib; runSh += lib; } buildBat += "\""; buildSh += "\""; runBat += ";.\" Main %1 %2"; runSh += ":.\" Main $1 $2"; FileWriter fw = new FileWriter(new File(tmpFolder, "build.bat")); FileWriter fw2 = new FileWriter(new File(tmpFolder, "build.sh")); FileWriter fw3 = new FileWriter(new File(tmpFolder, "run.bat")); FileWriter fw4 = new FileWriter(new File(tmpFolder, "run.sh")); fw.write(buildBat); fw2.write(buildSh); fw3.write(runBat); fw4.write(runSh); fw.close(); fw2.close(); fw3.close(); fw4.close(); } public static void main(String[] args) throws IOException { if (args.length != 1) { System.out.println("Usage: TutorPackage.jar <ProjectFolder>"); return; } File projectFolder = new File(args[0]); File srcFolder = new File(projectFolder, "src"); File tmpFolder = new File("../tmp"); File libFolder = new File("../lib"); File ciLibSrcFolder = new File("../CI-Library/src"); if (!tmpFolder.exists()) tmpFolder.mkdir(); // Copy Libs for (File f : libFolder.listFiles(JAR_FILTER)) { FileUtils.copyFileToDirectory(f, tmpFolder); } // Copy Java Files copyJavaFiles(ciLibSrcFolder, tmpFolder); copyJavaFiles(srcFolder, tmpFolder); // Remove Package-Tag for (File f : tmpFolder.listFiles(JAVA_FILTER)) { processJavaFile(f); } createBuildAndRunScript(libFolder, tmpFolder); // Zip compressZipfile(tmpFolder, new File(projectFolder, "tutor-src.zip")); FileUtils.deleteDirectory(tmpFolder); } }
[ "BuffaloDan@indiplex.de" ]
BuffaloDan@indiplex.de
d28a07e2c3d94b8eaf24c2998c019f993a4a7d6f
ab8c12c7fb4304d8e3b470384b93ec4e7d74577e
/src/main/java/arg/com/bioparque/domain/Zona.java
4c7b408f6574e4cee3c76d37517bda7f5d1cb8af
[]
no_license
iaraAlfaro/bio-parque
d907412d87080d46366f34d9bfe39aad2e0c1da9
19096587eb4f414bdb94dd55341a7dc42d7e9bf0
refs/heads/master
2023-07-13T13:52:37.298634
2021-08-10T20:34:08
2021-08-10T20:34:08
376,158,560
0
0
null
null
null
null
UTF-8
Java
false
false
976
java
package arg.com.bioparque.domain; import java.io.Serializable; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import lombok.Data; @Entity @Data @Table(name = "zona") public class Zona implements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id_zona") private Long idZona; private String nombre; private String extension; @OneToMany(mappedBy = "zona") private List<ItinerarioZona> itinerarioZonas; @ManyToOne @JoinColumn(name="id_itinerario", referencedColumnName="id_itinerario") private Itinerario itinerario; }
[ "alfaroasadiara@gmail.com" ]
alfaroasadiara@gmail.com
8f865c55c8fde27adc009a09c6801e6e9e7aaeb4
29f78bfb928fb6f191b08624ac81b54878b80ded
/generated_SPs_SCs/IADC/SCs/SC_helicopter1/src/main/java/SP_aircraftcarrier1/input/InputDataClassName_3_2.java
d29ba65f1781e48ca7f8dacddb818d7fbe45b926
[]
no_license
MSPL4SOA/MSPL4SOA-tool
8a78e73b4ac7123cf1815796a70f26784866f272
9f3419e416c600cba13968390ee89110446d80fb
refs/heads/master
2020-04-17T17:30:27.410359
2018-07-27T14:18:55
2018-07-27T14:18:55
66,304,158
0
1
null
null
null
null
UTF-8
Java
false
false
2,499
java
package SP_aircraftcarrier1.input; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "InputDataClassName_3_2") public class InputDataClassName_3_2 implements Serializable { private static final long serialVersionUID = 1L; @XmlElement(name = "InputName_3_2_2") protected Integer InputName_3_2_2; @XmlElement(name = "InputName_3_2_3") protected Float InputName_3_2_3; @XmlElement(name = "InputName_3_2_1") protected Float InputName_3_2_1; @XmlElement(name = "InputName_3_2_8") protected Integer InputName_3_2_8; @XmlElement(name = "InputName_3_2_9") protected String InputName_3_2_9; @XmlElement(name = "InputName_3_2_6") protected Integer InputName_3_2_6; @XmlElement(name = "InputName_3_2_7") protected String InputName_3_2_7; @XmlElement(name = "InputName_3_2_4") protected Float InputName_3_2_4; @XmlElement(name = "InputName_3_2_5") protected Integer InputName_3_2_5; public Integer getInputName_3_2_2() { return InputName_3_2_2; } public Float getInputName_3_2_3() { return InputName_3_2_3; } public Float getInputName_3_2_1() { return InputName_3_2_1; } public Integer getInputName_3_2_8() { return InputName_3_2_8; } public String getInputName_3_2_9() { return InputName_3_2_9; } public Integer getInputName_3_2_6() { return InputName_3_2_6; } public String getInputName_3_2_7() { return InputName_3_2_7; } public Float getInputName_3_2_4() { return InputName_3_2_4; } public Integer getInputName_3_2_5() { return InputName_3_2_5; } public void setInputName_3_2_2(Integer value) { this.InputName_3_2_2 = value; } public void setInputName_3_2_3(Float value) { this.InputName_3_2_3 = value; } public void setInputName_3_2_1(Float value) { this.InputName_3_2_1 = value; } public void setInputName_3_2_8(Integer value) { this.InputName_3_2_8 = value; } public void setInputName_3_2_9(String value) { this.InputName_3_2_9 = value; } public void setInputName_3_2_6(Integer value) { this.InputName_3_2_6 = value; } public void setInputName_3_2_7(String value) { this.InputName_3_2_7 = value; } public void setInputName_3_2_4(Float value) { this.InputName_3_2_4 = value; } public void setInputName_3_2_5(Integer value) { this.InputName_3_2_5 = value; } }
[ "akram.kamoun@gmail.com" ]
akram.kamoun@gmail.com
783cc7a5450c67eb2acfc28e1b7b96e8c5285050
1e9f8eabcb05a12e303cf05b709f7ad17a7758f7
/app/src/main/java/com/kotizm/instaforex/Model/User/User.java
02dde5863c6e5b1c8906a823d9049cee71fa298b
[]
no_license
jshahriyarbadalov/InstaForexTradingApp
deb25ae0e72709f588d7c581ef3c96b0a27e5267
7cbcad7a13d4fe4d3d941c8195925490d2d74c47
refs/heads/master
2021-05-21T10:25:04.193819
2020-04-03T18:33:12
2020-04-03T18:33:12
252,653,355
4
0
null
null
null
null
UTF-8
Java
false
false
663
java
package com.kotizm.instaforex.Model.User; import android.text.TextUtils; public class User implements IUser { private String login; private String password; public User(String login, String password) { this.login = login; this.password = password; } @Override public String getLogin() { return login; } @Override public String getPassword() { return password; } @Override public int validationLogin() { return TextUtils.isEmpty(getLogin())? -1:1; } @Override public int validationPassword() { return TextUtils.isEmpty(getPassword())? -1:1; } }
[ "shah.badalov91@gmail.com" ]
shah.badalov91@gmail.com
839bbd060b062bc8ca6e0f7a52f574ebb9182a87
95768d1c0eb023ad74970573cfcd8dc648b4ccac
/src/main/java/App.java
204c0e0b02ca1d259f3b84053d0cc3d5c82c5c00
[]
no_license
katebyars/codingschool
928da73436d3ad5d16eb405df1cfc0bf51d61cd5
ed2f1497468f7d8f9f00cf1992647b5416feb0cd
refs/heads/master
2021-01-18T19:43:00.657289
2017-08-16T23:29:41
2017-08-16T23:29:41
100,535,935
0
0
null
null
null
null
UTF-8
Java
false
false
4,405
java
import dao.CodeSchoolDao; import dao.Sql2oCodeSchoolDao; import models.CodeSchool; import org.sql2o.Sql2o; import spark.ModelAndView; import spark.template.handlebars.HandlebarsTemplateEngine; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import static spark.Spark.get; import static spark.Spark.post; import static spark.Spark.staticFileLocation; /** * Created by Guest on 8/16/17. */ public class App { public static void main(String[] args) { staticFileLocation("/public"); String connectionString = "jdbc:h2:~/codeschool.db;INIT=RUNSCRIPT from 'classpath:db/create.sql'"; Sql2o sql2o = new Sql2o(connectionString, "", ""); Sql2oCodeSchoolDao codeSchoolDao = new Sql2oCodeSchoolDao(sql2o); //get: delete all codeSchools get("/codeschools/delete", (req, res) -> { Map<String, Object> model = new HashMap<>(); codeSchoolDao.clearAllCodeSchools(); return new ModelAndView(model, "success.hbs"); }, new HandlebarsTemplateEngine()); //get: show all Codeschools get("/", (req, res) -> { Map<String, Object> model = new HashMap<>(); List<CodeSchool> codeSchools = codeSchoolDao.getAll(); model.put("codeSchools", codeSchools); return new ModelAndView(model, "codeSchool-index.hbs"); }, new HandlebarsTemplateEngine()); //get: show new Codeschool Form get("/codeschools/new", (req, res) -> { Map<String, Object> model = new HashMap<>(); return new ModelAndView(model, "codeSchool-form.hbs"); }, new HandlebarsTemplateEngine()); //put: process new Codeschool Form post("/codeschools/new", (request, response) -> { //URL to make new task on POST route Map<String, Object> model = new HashMap<>(); String name = request.queryParams("name"); CodeSchool newCodeSchool = new CodeSchool(name); codeSchoolDao.add(newCodeSchool); model.put("newCodeSchool", newCodeSchool); return new ModelAndView(model, "success.hbs"); }, new HandlebarsTemplateEngine()); //get: show individual codeSchool get("/codeschools/:codeschool_id", (req, res) -> { Map<String, Object> model = new HashMap<>(); int idOfCategory = Integer.parseInt(req.params("codeschool_id")); CodeSchool foundCodeSchool = codeSchoolDao.findById(idOfCategory); model.put("codeschool", foundCodeSchool); return new ModelAndView(model, "codeSchool-detail.hbs"); }, new HandlebarsTemplateEngine()); //get: show a form to update individual codeSchool get("/codeschools/:codeschool_id/update", (req, res) -> { Map<String, Object> model = new HashMap<>(); int idOfCodeSchoolToEdit = Integer.parseInt(req.params("codeschool_id")); CodeSchool editCodeSchool = codeSchoolDao.findById(idOfCodeSchoolToEdit); model.put("editCodeSchool", editCodeSchool); return new ModelAndView(model, "codeSchool-form.hbs"); }, new HandlebarsTemplateEngine()); //post: process an update to an individual codeschool post("/codeschools/:codeschool_id/update", (req, res) -> { //URL to make new task on POST route Map<String, Object> model = new HashMap<>(); String newName = req.queryParams("name"); int codeSchoolId = Integer.parseInt(req.params("codeschool_id")); codeSchoolDao.findById(codeSchoolId); codeSchoolDao.update(codeSchoolId,newName); return new ModelAndView(model, "success.hbs"); }, new HandlebarsTemplateEngine()); //get: delete individual codeschool get("/codeschools/:codeschool_id/delete", (req, res) -> { Map<String, Object> model = new HashMap<>(); int idOfCodeSchoolToDelete = Integer.parseInt(req.params("codeschool_id")); //pull id - must match route segment codeSchoolDao.findById(idOfCodeSchoolToDelete); //use it to find task codeSchoolDao.deleteById(idOfCodeSchoolToDelete); return new ModelAndView(model, "success.hbs"); }, new HandlebarsTemplateEngine()); } }
[ "jessica@" ]
jessica@
92d89a9d27614e09cbe9bbcc1ca7f27280488fc4
b97a9d99fbf4066469e64592065d6a62970d9833
/ares-core/common/src/main/java/com/aw/common/util/SystemOrLatestTime.java
18fc2b1c53bae8c151f127baa2bd008cd9ba0414
[]
no_license
analyticswarescott/ares
2bacb8eaac612e36836f7138c4398b6560468a91
5ac8d4ed50ca749b52eafc6fe95593ff68b85b54
refs/heads/master
2020-05-29T16:08:56.917029
2016-11-11T21:11:02
2016-11-11T21:11:02
59,563,723
0
0
null
null
null
null
UTF-8
Java
false
false
651
java
package com.aw.common.util; import java.time.Instant; /** * A current time equal to the current system time, or the latest time seen, whichever is later. * * * */ public class SystemOrLatestTime implements TimeSource { /** * @return The latest time seen - if greater than the system time, this will be the current time */ private Instant latest; @Override public long nowMillis() { return now().toEpochMilli(); } @Override public Instant now() { if (this.latest == null) { return TimeSource.super.now(); } else { return this.latest; } } public void updateLatest(Instant time) { this.latest = time; } }
[ "scott@analyticsware.com" ]
scott@analyticsware.com
4932d4320f1d2c74fb7706e193231f571ec149e6
54c8bd21cf395aa6891f0c38602859e749e58f65
/app/src/main/java/com/noisyninja/abheda_droid/control/SeekArc.java
03d8006ce40f8677453b1521c82f5c9231d4d918
[]
no_license
ir2pid/Abheda_droid
9a92841328cc1917a01045a0426d42d9a91d0629
dc92595d835174cb9101f224de21b49cdb04884e
refs/heads/master
2021-03-12T23:41:20.365729
2018-05-28T11:39:00
2018-05-28T11:39:00
27,233,351
0
0
null
null
null
null
UTF-8
Java
false
false
18,192
java
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2013 Triggertrap Ltd * Author Neil Davies * * 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.noisyninja.abheda_droid.control; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import com.noisyninja.abheda_droid.R; /** * * SeekArc.java * * This is a class that functions much like a SeekBar but follows a circle path * instead of a straight line. * * @author Neil Davies * */ public class SeekArc extends View { private static final String TAG = SeekArc.class.getSimpleName(); private static int INVALID_PROGRESS_VALUE = -1; // The initial rotational offset -90 means we start at 12 o'clock private final int mAngleOffset = -90; /** * The Drawable for the seek arc thumbnail */ private Drawable mThumb; /** * The Maximum value that this SeekArc can be set to */ private int mMax = 100; /** * The Current value that the SeekArc is set to */ private int mProgress = 0; /** * The width of the progress line for this SeekArc */ private int mProgressWidth = 4; /** * The Width of the background arc for the SeekArc */ private int mArcWidth = 2; /** * The Angle to start drawing this Arc from */ private int mStartAngle = 0; /** * The Angle through which to draw the arc (Max is 360) */ private int mSweepAngle = 360; /** * The rotation of the SeekArc- 0 is twelve o'clock */ private int mRotation = 0; /** * Give the SeekArc rounded edges */ private boolean mRoundedEdges = false; /** * Enable touch inside the SeekArc */ private boolean mTouchInside = true; /** * Will the progress increase clockwise or anti-clockwise */ private boolean mClockwise = true; // Internal variables private int mArcRadius = 0; private float mProgressSweep = 0; private RectF mArcRect = new RectF(); private Paint mArcPaint; private Paint mProgressPaint; private int mTranslateX; private int mTranslateY; private int mThumbXPos; private int mThumbYPos; private double mTouchAngle; private float mTouchIgnoreRadius; private OnSeekArcChangeListener mOnSeekArcChangeListener; // is the control toucale private boolean mTouchable = true; public interface OnSeekArcChangeListener { /** * Notification that the progress level has changed. Clients can use the * fromUser parameter to distinguish user-initiated changes from those * that occurred programmatically. * * @param seekArc * The SeekArc whose progress has changed * @param progress * The current progress level. This will be in the range * 0..max where max was set by * {@link ProgressArc#setMax(int)}. (The default value for * max is 100.) * @param fromUser * True if the progress change was initiated by the user. */ void onProgressChanged(SeekArc seekArc, int progress, boolean fromUser); /** * Notification that the user has started a touch gesture. Clients may * want to use this to disable advancing the seekbar. * * @param seekArc * The SeekArc in which the touch gesture began */ void onStartTrackingTouch(SeekArc seekArc); /** * Notification that the user has finished a touch gesture. Clients may * want to use this to re-enable advancing the seekarc. * * @param seekArc * The SeekArc in which the touch gesture began */ void onStopTrackingTouch(SeekArc seekArc); } public SeekArc(Context context) { super(context); init(context, null, 0); } public SeekArc(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs, R.attr.seekArcStyle); } public SeekArc(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context, attrs, defStyle); } private void init(Context context, AttributeSet attrs, int defStyle) { Log.d(TAG, "Initialising SeekArc"); final Resources res = getResources(); float density = context.getResources().getDisplayMetrics().density; // Defaults, may need to link this into theme settings int arcColor = res.getColor(R.color.progress_gray); int progressColor = res.getColor(android.R.color.holo_blue_light); int thumbHalfheight = 0; int thumbHalfWidth = 0; mThumb = res.getDrawable(R.drawable.seek_arc_control_selector); // Convert progress width to pixels for current density mProgressWidth = (int) (mProgressWidth * density); if (attrs != null) { // Attribute initialization final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SeekArc, defStyle, 0); Drawable thumb = a.getDrawable(R.styleable.SeekArc_thumb); if (thumb != null) { mThumb = thumb; } thumbHalfheight = (int) mThumb.getIntrinsicHeight() / 2; thumbHalfWidth = (int) mThumb.getIntrinsicWidth() / 2; mThumb.setBounds(-thumbHalfWidth, -thumbHalfheight, thumbHalfWidth, thumbHalfheight); mMax = a.getInteger(R.styleable.SeekArc_max, mMax); mProgress = a.getInteger(R.styleable.SeekArc_progress, mProgress); mProgressWidth = (int) a.getDimension( R.styleable.SeekArc_progressWidth, mProgressWidth); mArcWidth = (int) a.getDimension(R.styleable.SeekArc_arcWidth, mArcWidth); mStartAngle = a.getInt(R.styleable.SeekArc_startAngle, mStartAngle); mSweepAngle = a.getInt(R.styleable.SeekArc_sweepAngle, mSweepAngle); mRotation = a.getInt(R.styleable.SeekArc_rotation, mRotation); mRoundedEdges = a.getBoolean(R.styleable.SeekArc_roundEdges, mRoundedEdges); mTouchInside = a.getBoolean(R.styleable.SeekArc_touchInside, mTouchInside); mClockwise = a .getBoolean(R.styleable.SeekArc_clockwise, mClockwise); mTouchable = a .getBoolean(R.styleable.SeekArc_touchable, mTouchable); arcColor = a.getColor(R.styleable.SeekArc_arcColor, arcColor); progressColor = a.getColor(R.styleable.SeekArc_progressColor, progressColor); a.recycle(); } mProgress = (mProgress > mMax) ? mMax : mProgress; mProgress = (mProgress < 0) ? 0 : mProgress; mSweepAngle = (mSweepAngle > 360) ? 360 : mSweepAngle; mSweepAngle = (mSweepAngle < 0) ? 0 : mSweepAngle; mStartAngle = (mStartAngle > 360) ? 0 : mStartAngle; mStartAngle = (mStartAngle < 0) ? 0 : mStartAngle; mArcPaint = new Paint(); mArcPaint.setColor(arcColor); mArcPaint.setAntiAlias(true); mArcPaint.setStyle(Paint.Style.STROKE); mArcPaint.setStrokeWidth(mArcWidth); // mArcPaint.setAlpha(45); mProgressPaint = new Paint(); mProgressPaint.setColor(progressColor); mProgressPaint.setAntiAlias(true); mProgressPaint.setStyle(Paint.Style.STROKE); mProgressPaint.setStrokeWidth(mProgressWidth); if (mRoundedEdges) { mArcPaint.setStrokeCap(Paint.Cap.ROUND); mProgressPaint.setStrokeCap(Paint.Cap.ROUND); } } @Override protected void onDraw(Canvas canvas) { if (!mClockwise) { canvas.scale(-1, 1, mArcRect.centerX(), mArcRect.centerY()); } // Draw the arcs final int arcStart = mStartAngle + mAngleOffset + mRotation; final int arcSweep = mSweepAngle; canvas.drawArc(mArcRect, arcStart, arcSweep, false, mArcPaint); canvas.drawArc(mArcRect, arcStart, mProgressSweep, false, mProgressPaint); // Draw the thumb nail canvas.translate(mTranslateX - mThumbXPos, mTranslateY - mThumbYPos); mThumb.draw(canvas); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int height = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec); final int width = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec); final int min = Math.min(width, height); float top = 0; float left = 0; int arcDiameter = 0; mTranslateX = (int) (width * 0.5f); mTranslateY = (int) (height * 0.5f); arcDiameter = min - getPaddingLeft(); mArcRadius = arcDiameter / 2; top = height / 2 - (arcDiameter / 2); left = width / 2 - (arcDiameter / 2); mArcRect.set(left, top, left + arcDiameter, top + arcDiameter); int arcStart = (int) mProgressSweep + mStartAngle + mRotation + 90; mThumbXPos = (int) (mArcRadius * Math.cos(Math.toRadians(arcStart))); mThumbYPos = (int) (mArcRadius * Math.sin(Math.toRadians(arcStart))); setTouchInSide(mTouchInside); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override public boolean onTouchEvent(MotionEvent event) { if (mTouchable) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: onStartTrackingTouch(); updateOnTouch(event); break; case MotionEvent.ACTION_MOVE: updateOnTouch(event); break; case MotionEvent.ACTION_UP: onStopTrackingTouch(); setPressed(false); break; case MotionEvent.ACTION_CANCEL: onStopTrackingTouch(); setPressed(false); break; } } return true; } @Override protected void drawableStateChanged() { super.drawableStateChanged(); if (mThumb != null && mThumb.isStateful()) { int[] state = getDrawableState(); mThumb.setState(state); } invalidate(); } private void onStartTrackingTouch() { if (mOnSeekArcChangeListener != null) { mOnSeekArcChangeListener.onStartTrackingTouch(this); } } private void onStopTrackingTouch() { if (mOnSeekArcChangeListener != null) { mOnSeekArcChangeListener.onStopTrackingTouch(this); } } private void updateOnTouch(MotionEvent event) { boolean ignoreTouch = ignoreTouch(event.getX(), event.getY()); if (ignoreTouch) { return; } setPressed(true); mTouchAngle = getTouchDegrees(event.getX(), event.getY()); int progress = getProgressForAngle(mTouchAngle); onProgressRefresh(progress, true); } private boolean ignoreTouch(float xPos, float yPos) { boolean ignore = false; float x = xPos - mTranslateX; float y = yPos - mTranslateY; float touchRadius = (float) Math.sqrt(((x * x) + (y * y))); if (touchRadius < mTouchIgnoreRadius) { ignore = true; } return ignore; } private double getTouchDegrees(float xPos, float yPos) { float x = xPos - mTranslateX; float y = yPos - mTranslateY; // invert the x-coord if we are rotating anti-clockwise x = (mClockwise) ? x : -x; // convert to arc Angle double angle = Math.toDegrees(Math.atan2(y, x) + (Math.PI / 2) - Math.toRadians(mRotation)); if (angle < 0) { angle = 360 + angle; } angle -= mStartAngle; return angle; } private int getProgressForAngle(double angle) { int touchProgress = (int) Math.round(valuePerDegree() * angle); touchProgress = (touchProgress < 0) ? INVALID_PROGRESS_VALUE : touchProgress; touchProgress = (touchProgress > mMax) ? INVALID_PROGRESS_VALUE : touchProgress; return touchProgress; } private float valuePerDegree() { return (float) mMax / mSweepAngle; } private void onProgressRefresh(int progress, boolean fromUser) { updateProgress(progress, fromUser); } private void updateThumbPosition() { int thumbAngle = (int) (mStartAngle + mProgressSweep + mRotation + 90); mThumbXPos = (int) (mArcRadius * Math.cos(Math.toRadians(thumbAngle))); mThumbYPos = (int) (mArcRadius * Math.sin(Math.toRadians(thumbAngle))); } private void updateProgress(int progress, boolean fromUser) { if (progress == INVALID_PROGRESS_VALUE) { return; } if (mOnSeekArcChangeListener != null) { mOnSeekArcChangeListener .onProgressChanged(this, progress, fromUser); } progress = (progress > mMax) ? mMax : progress; progress = (mProgress < 0) ? 0 : progress; mProgress = progress; mProgressSweep = (float) progress / mMax * mSweepAngle; updateThumbPosition(); invalidate(); } /** * Sets a listener to receive notifications of changes to the SeekArc's * progress level. Also provides notifications of when the user starts and * stops a touch gesture within the SeekArc. * * @param l * The seek bar notification listener * * @see SeekArc.OnSeekBarChangeListener */ public void setOnSeekArcChangeListener(OnSeekArcChangeListener l) { mOnSeekArcChangeListener = l; } public void setProgress(int progress) { updateProgress(progress, false); } public int getProgressWidth() { return mProgressWidth; } public void setProgressWidth(int mProgressWidth) { this.mProgressWidth = mProgressWidth; mProgressPaint.setStrokeWidth(mProgressWidth); } public int getArcWidth() { return mArcWidth; } public void setArcWidth(int mArcWidth) { this.mArcWidth = mArcWidth; mArcPaint.setStrokeWidth(mArcWidth); } public int getArcRotation() { return mRotation; } public void setArcRotation(int mRotation) { this.mRotation = mRotation; updateThumbPosition(); } public int getProgressColor() { return mProgressPaint.getColor(); } public void setProgressColor(int color) { mProgressPaint.setColor(color); invalidate(); } public boolean isTouchable() { return mTouchable; } public void setTouchable(boolean mTouchable) { this.mTouchable = mTouchable; } public int getArcColor() { return mArcPaint.getColor(); } public void setArcColor(int color) { mArcPaint.setColor(color); invalidate(); } public int getStartAngle() { return mStartAngle; } public void setStartAngle(int mStartAngle) { this.mStartAngle = mStartAngle; updateThumbPosition(); } public int getSweepAngle() { return mSweepAngle; } public void setSweepAngle(int mSweepAngle) { this.mSweepAngle = mSweepAngle; updateThumbPosition(); } public void setRoundedEdges(boolean isEnabled) { mRoundedEdges = isEnabled; if (mRoundedEdges) { mArcPaint.setStrokeCap(Paint.Cap.ROUND); mProgressPaint.setStrokeCap(Paint.Cap.ROUND); } else { mArcPaint.setStrokeCap(Paint.Cap.SQUARE); mProgressPaint.setStrokeCap(Paint.Cap.SQUARE); } } public void setTouchInSide(boolean isEnabled) { int thumbHalfheight = (int) mThumb.getIntrinsicHeight() / 2; int thumbHalfWidth = (int) mThumb.getIntrinsicWidth() / 2; mTouchInside = isEnabled; if (mTouchInside) { mTouchIgnoreRadius = (float) mArcRadius / 4; } else { // Don't use the exact radius makes interaction too tricky mTouchIgnoreRadius = mArcRadius - Math.min(thumbHalfWidth, thumbHalfheight); } } public void setClockwise(boolean isClockwise) { mClockwise = isClockwise; } }
[ "ir2pid@gmail.com" ]
ir2pid@gmail.com
1dcb1ae4394d1ea50133d4417d296896b24ff7a0
cebbee727a517d4f3859ef79072878be7930327c
/src/chap06/lecture/annotation/AnnotationEx2.java
c4e8d0e9f6b2f3cacd4a975382aeffb3705d38ce
[]
no_license
pedroyoung95/java20200929
a99f72d022cfeb03862a5954f89742042cfdd7a5
b731dbe2c9b3a3d3acff4ba7991dfc2085ba8744
refs/heads/master
2023-01-10T07:18:08.073916
2020-11-03T08:46:24
2020-11-03T08:46:24
299,485,598
0
0
null
null
null
null
UTF-8
Java
false
false
415
java
package chap06.lecture.annotation; import java.lang.reflect.Method; public class AnnotationEx2 { public static void main(String[] args) throws Exception { Class clazz = MyClass.class; Method method = clazz.getMethod("method1"); boolean anno = method.isAnnotationPresent(MyAnnotation.class); //isAnnotationPresent(AnnotationName.class): 어노테이션 적용 여부 판별 System.out.println(anno); } }
[ "jty9531@gmail.com" ]
jty9531@gmail.com
2d8624df845e68f8923a09ab3382267544a63dba
6bb24530476224001cc6c17989bcc76749098f89
/flyme-system/src/main/java/com/goldencis/flyme/system/service/impl/SysMenuServiceImpl.java
c6049955dfb8e80b3d2ca02429ef1f3e8e50f43b
[ "MIT" ]
permissive
UniqueSuccess/Flyme-Vue
366218bc9981437c4272aae6a3b745aa55fba813
15eae94e833a77a458fa963ad7d756ee3fac3d7f
refs/heads/master
2023-01-07T23:22:48.459319
2020-10-29T02:53:40
2020-10-29T02:55:24
302,863,885
3
0
null
null
null
null
UTF-8
Java
false
false
12,472
java
package com.goldencis.flyme.system.service.impl; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import com.goldencis.flyme.common.utils.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.goldencis.flyme.common.constant.UserConstants; import com.goldencis.flyme.common.core.domain.TreeSelect; import com.goldencis.flyme.common.core.domain.entity.SysMenu; import com.goldencis.flyme.common.core.domain.entity.SysRole; import com.goldencis.flyme.common.core.domain.entity.SysUser; import com.goldencis.flyme.common.utils.SecurityUtils; import com.goldencis.flyme.system.domain.vo.MetaVo; import com.goldencis.flyme.system.domain.vo.RouterVo; import com.goldencis.flyme.system.mapper.SysMenuMapper; import com.goldencis.flyme.system.mapper.SysRoleMapper; import com.goldencis.flyme.system.mapper.SysRoleMenuMapper; import com.goldencis.flyme.system.service.ISysMenuService; /** * 菜单 业务层处理 * * @author flyme */ @Service public class SysMenuServiceImpl implements ISysMenuService { public static final String PREMISSION_STRING = "perms[\"{0}\"]"; @Autowired private SysMenuMapper menuMapper; @Autowired private SysRoleMapper roleMapper; @Autowired private SysRoleMenuMapper roleMenuMapper; /** * 根据用户查询系统菜单列表 * * @param userId 用户ID * @return 菜单列表 */ @Override public List<SysMenu> selectMenuList(Long userId) { return selectMenuList(new SysMenu(), userId); } /** * 查询系统菜单列表 * * @param menu 菜单信息 * @return 菜单列表 */ @Override public List<SysMenu> selectMenuList(SysMenu menu, Long userId) { List<SysMenu> menuList = null; // 管理员显示所有菜单信息 if (SysUser.isAdmin(userId)) { menuList = menuMapper.selectMenuList(menu); } else { menu.getParams().put("userId", userId); menuList = menuMapper.selectMenuListByUserId(menu); } return menuList; } /** * 根据用户ID查询权限 * * @param userId 用户ID * @return 权限列表 */ @Override public Set<String> selectMenuPermsByUserId(Long userId) { List<String> perms = menuMapper.selectMenuPermsByUserId(userId); Set<String> permsSet = new HashSet<>(); for (String perm : perms) { if (StringUtils.isNotEmpty(perm)) { permsSet.addAll(Arrays.asList(perm.trim().split(","))); } } return permsSet; } /** * 根据用户ID查询菜单 * * @param userId 用户名称 * @return 菜单列表 */ @Override public List<SysMenu> selectMenuTreeByUserId(Long userId) { List<SysMenu> menus = null; if (SecurityUtils.isAdmin(userId)) { menus = menuMapper.selectMenuTreeAll(); } else { menus = menuMapper.selectMenuTreeByUserId(userId); } return getChildPerms(menus, 0); } /** * 根据角色ID查询菜单树信息 * * @param roleId 角色ID * @return 选中菜单列表 */ @Override public List<Integer> selectMenuListByRoleId(Long roleId) { SysRole role = roleMapper.selectRoleById(roleId); return menuMapper.selectMenuListByRoleId(roleId, role.isMenuCheckStrictly()); } /** * 构建前端路由所需要的菜单 * * @param menus 菜单列表 * @return 路由列表 */ @Override public List<RouterVo> buildMenus(List<SysMenu> menus) { List<RouterVo> routers = new LinkedList<RouterVo>(); for (SysMenu menu : menus) { RouterVo router = new RouterVo(); router.setHidden("1".equals(menu.getVisible())); router.setName(getRouteName(menu)); router.setPath(getRouterPath(menu)); router.setComponent(getComponent(menu)); router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()))); List<SysMenu> cMenus = menu.getChildren(); if (!cMenus.isEmpty() && cMenus.size() > 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType())) { router.setAlwaysShow(true); router.setRedirect("noRedirect"); router.setChildren(buildMenus(cMenus)); } else if (isMeunFrame(menu)) { List<RouterVo> childrenList = new ArrayList<RouterVo>(); RouterVo children = new RouterVo(); children.setPath(menu.getPath()); children.setComponent(menu.getComponent()); children.setName(StringUtils.capitalize(menu.getPath())); children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()))); childrenList.add(children); router.setChildren(childrenList); } routers.add(router); } return routers; } /** * 构建前端所需要树结构 * * @param menus 菜单列表 * @return 树结构列表 */ @Override public List<SysMenu> buildMenuTree(List<SysMenu> menus) { List<SysMenu> returnList = new ArrayList<SysMenu>(); List<Long> tempList = new ArrayList<Long>(); for (SysMenu dept : menus) { tempList.add(dept.getMenuId()); } for (Iterator<SysMenu> iterator = menus.iterator(); iterator.hasNext();) { SysMenu menu = (SysMenu) iterator.next(); // 如果是顶级节点, 遍历该父节点的所有子节点 if (!tempList.contains(menu.getParentId())) { recursionFn(menus, menu); returnList.add(menu); } } if (returnList.isEmpty()) { returnList = menus; } return returnList; } /** * 构建前端所需要下拉树结构 * * @param menus 菜单列表 * @return 下拉树结构列表 */ @Override public List<TreeSelect> buildMenuTreeSelect(List<SysMenu> menus) { List<SysMenu> menuTrees = buildMenuTree(menus); return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList()); } /** * 根据菜单ID查询信息 * * @param menuId 菜单ID * @return 菜单信息 */ @Override public SysMenu selectMenuById(Long menuId) { return menuMapper.selectMenuById(menuId); } /** * 是否存在菜单子节点 * * @param menuId 菜单ID * @return 结果 */ @Override public boolean hasChildByMenuId(Long menuId) { int result = menuMapper.hasChildByMenuId(menuId); return result > 0 ? true : false; } /** * 查询菜单使用数量 * * @param menuId 菜单ID * @return 结果 */ @Override public boolean checkMenuExistRole(Long menuId) { int result = roleMenuMapper.checkMenuExistRole(menuId); return result > 0 ? true : false; } /** * 新增保存菜单信息 * * @param menu 菜单信息 * @return 结果 */ @Override public int insertMenu(SysMenu menu) { return menuMapper.insertMenu(menu); } /** * 修改保存菜单信息 * * @param menu 菜单信息 * @return 结果 */ @Override public int updateMenu(SysMenu menu) { return menuMapper.updateMenu(menu); } /** * 删除菜单管理信息 * * @param menuId 菜单ID * @return 结果 */ @Override public int deleteMenuById(Long menuId) { return menuMapper.deleteMenuById(menuId); } /** * 校验菜单名称是否唯一 * * @param menu 菜单信息 * @return 结果 */ @Override public String checkMenuNameUnique(SysMenu menu) { Long menuId = StringUtils.isNull(menu.getMenuId()) ? -1L : menu.getMenuId(); SysMenu info = menuMapper.checkMenuNameUnique(menu.getMenuName(), menu.getParentId()); if (StringUtils.isNotNull(info) && info.getMenuId().longValue() != menuId.longValue()) { return UserConstants.NOT_UNIQUE; } return UserConstants.UNIQUE; } /** * 获取路由名称 * * @param menu 菜单信息 * @return 路由名称 */ public String getRouteName(SysMenu menu) { String routerName = StringUtils.capitalize(menu.getPath()); // 非外链并且是一级目录(类型为目录) if (isMeunFrame(menu)) { routerName = StringUtils.EMPTY; } return routerName; } /** * 获取路由地址 * * @param menu 菜单信息 * @return 路由地址 */ public String getRouterPath(SysMenu menu) { String routerPath = menu.getPath(); // 非外链并且是一级目录(类型为目录) if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType()) && UserConstants.NO_FRAME.equals(menu.getIsFrame())) { routerPath = "/" + menu.getPath(); } // 非外链并且是一级目录(类型为菜单) else if (isMeunFrame(menu)) { routerPath = "/"; } return routerPath; } /** * 获取组件信息 * * @param menu 菜单信息 * @return 组件信息 */ public String getComponent(SysMenu menu) { String component = UserConstants.LAYOUT; if (StringUtils.isNotEmpty(menu.getComponent()) && !isMeunFrame(menu)) { component = menu.getComponent(); } return component; } /** * 是否为菜单内部跳转 * * @param menu 菜单信息 * @return 结果 */ public boolean isMeunFrame(SysMenu menu) { return menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType()) && menu.getIsFrame().equals(UserConstants.NO_FRAME); } /** * 根据父节点的ID获取所有子节点 * * @param list 分类表 * @param parentId 传入的父节点ID * @return String */ public List<SysMenu> getChildPerms(List<SysMenu> list, int parentId) { List<SysMenu> returnList = new ArrayList<SysMenu>(); for (Iterator<SysMenu> iterator = list.iterator(); iterator.hasNext();) { SysMenu t = (SysMenu) iterator.next(); // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点 if (t.getParentId() == parentId) { recursionFn(list, t); returnList.add(t); } } return returnList; } /** * 递归列表 * * @param list * @param t */ private void recursionFn(List<SysMenu> list, SysMenu t) { // 得到子节点列表 List<SysMenu> childList = getChildList(list, t); t.setChildren(childList); for (SysMenu tChild : childList) { if (hasChild(list, tChild)) { recursionFn(list, tChild); } } } /** * 得到子节点列表 */ private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t) { List<SysMenu> tlist = new ArrayList<SysMenu>(); Iterator<SysMenu> it = list.iterator(); while (it.hasNext()) { SysMenu n = (SysMenu) it.next(); if (n.getParentId().longValue() == t.getMenuId().longValue()) { tlist.add(n); } } return tlist; } /** * 判断是否有子节点 */ private boolean hasChild(List<SysMenu> list, SysMenu t) { return getChildList(list, t).size() > 0 ? true : false; } }
[ "296894988@qq.com" ]
296894988@qq.com
744158a7dd6f20fdfce87297baa5ed72a20ab73d
6d15861ac333805ac43ba3fd10cd1e1d9896af72
/kodilla-patterns2/src/main/java/com/kodilla/patterns2/observer/homework/Observable.java
ac2e314b1a448a22c870e9389ddcfd87a63a0de1
[]
no_license
blue0403/artur-lichaj-kodilla-java
a9501b32e3d1d7236bf90cbbad566cbd34e3c7a8
a712b91c73a32182fd196ab4aa24c0835c99b8ed
refs/heads/master
2021-01-25T14:34:42.889484
2018-08-22T13:29:58
2018-08-22T13:29:58
123,716,056
0
0
null
null
null
null
UTF-8
Java
false
false
200
java
package com.kodilla.patterns2.observer.homework; public interface Observable { void registerObserver(Observer observer); void notifyObservers(); void deleteObserver(Observer observer); }
[ "artur.lichaj@gmail.com" ]
artur.lichaj@gmail.com
122811e7aadee48edaf329fb831524593496a656
9d76fb1e36984a57a3f8a2908c9febbf754d6904
/src/main/java/AlexLink/HomeWork/InterfaceCosmos/Shuttle.java
d1d26b3186daa48c0f076bffdbc734039e1968ad
[]
no_license
qpuhuk/FreeIT
6ce6700df9f705642121825e330e186a12e775f7
e5142a57ba57afd62aab7ef3a2d46387e1d3d23d
refs/heads/main
2023-07-10T11:27:28.198838
2021-07-27T16:24:52
2021-07-27T16:24:52
350,076,029
0
0
null
null
null
null
UTF-8
Java
false
false
549
java
package AlexLink.HomeWork.InterfaceCosmos; public class Shuttle implements IStart { @Override public boolean checkSystem() { int random = (int) (Math.random() * 10); if (random > 3) return true; else return false; } @Override public void startEngine() { System.out.println("Двигатели Шатла запущены. Все системы в норме."); } @Override public void start() { System.out.println("Старт Шатла"); } }
[ "qpuhuk@mail.ru" ]
qpuhuk@mail.ru
410881adf4bdbddf26b7043eae272906bf841b87
1869c93d3e8af29202bc479e18957c21eb467d0e
/test/level19/lesson05/task04/Solution.java
7bd08b7958cd09595a5425834d9d11478e9c17b9
[]
no_license
Demonian/JavaRush
9682e2f85f8bf3b8bbb8b230a6f276589cf937f6
de75c9f6aba82946dcf4e3c2f680b019c7b2a111
refs/heads/master
2020-12-24T16:07:39.104600
2016-03-10T14:37:43
2016-03-10T14:37:43
24,858,101
0
0
null
null
null
null
UTF-8
Java
false
false
1,084
java
package com.javarush.test.level19.lesson05.task04; /* Замена знаков Считать с консоли 2 имени файла. Первый Файл содержит текст. Заменить все точки "." на знак "!", вывести во второй файл. Закрыть потоки ввода-вывода. */ import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStreamReader; public class Solution { public static void main(String[] args) throws Exception{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String fileName0 = reader.readLine(); String fileName1 = reader.readLine(); FileReader fileReader = new FileReader(fileName0); FileWriter fileWriter = new FileWriter(fileName1); int tmp = 0; while((tmp = fileReader.read()) != -1){ if (tmp == 46) fileWriter.write(33); else fileWriter.write(tmp); } fileReader.close(); fileWriter.close(); } }
[ "for.reg@ukr.net" ]
for.reg@ukr.net
88a5bfcb6c1f871963a0e1360958d08f3bb5bc3e
9f640b038ffa8d2193f124677f84e4c57186a0e4
/src/BTest.java
925ec2587dc3269845e92d87c1bdc0b03d366f2f
[]
no_license
sa35577/ICS4U-Binary-Tree-Assignment
7b322584c11ed4c406731320129ddc7bbdc42e62
b470e560aca36153c2b218a36be32c7fca5cd1b8
refs/heads/master
2022-12-10T15:29:45.343953
2020-09-03T16:48:59
2020-09-03T16:48:59
292,628,050
0
0
null
null
null
null
UTF-8
Java
false
false
2,194
java
public class BTest { public static void main(String[] args) {/* BTree bush = new BTree(); bush.add(50); System.out.println(bush.depth(50)); bush.add(31); System.out.println(bush.depth(31)); bush.add(105); System.out.println(bush.depth(105)); bush.add(71); System.out.println(bush.depth(71)); bush.add(4); System.out.println(bush.depth(4)); System.out.println(bush.depth(15)); bush.delete(71); System.out.println(bush.depth(71)); System.out.println(bush);*/ BTree maple=new BTree(); maple.add(45); maple.add(23); maple.add(15); maple.add(27); maple.add(39); maple.add(35); maple.add(37); maple.add(164); maple.add(73); maple.add(48); maple.add(170); BTree spruce=new BTree(); spruce.add(69); spruce.add(420); spruce.add(69); spruce.add(50); spruce.add(45); spruce.add(58); System.out.println(maple.depth(164)); System.out.println(maple.depth(102)); System.out.println(spruce.depth(69)); System.out.println(spruce.depth(45)); System.out.println(maple.countLeaves()); System.out.println(spruce.countLeaves()); System.out.println(maple.height()); System.out.println(spruce.height()); System.out.println(maple.isAncestor(23,37)); System.out.println(maple.isAncestor(103, 37)); System.out.println(maple.isAncestor(23,103)); System.out.println(maple.isAncestor(12,93)); System.out.println(spruce.isAncestor(69,69)); System.out.println(maple.isBalanced()); maple.delete(27); System.out.println(maple.isBalanced()); System.out.println(spruce.isBalanced()); spruce.delete(69); System.out.println(spruce.isBalanced()); spruce.add(69); System.out.println(spruce.isBalanced()); System.out.println(maple.display()); System.out.println(spruce.display()); spruce.add(maple); System.out.println(spruce.display()); } }
[ "satarora.1228@gmail.com" ]
satarora.1228@gmail.com
5cb046d9df89b99044fbc557c39b51c19734d2e0
35f77523f89819b05e461def5b2a8700ce518dd6
/src/test/java/net/eutkin/strategy/example/StrategyExampleApplicationTests.java
d72117a6097a70419b983643d1f7931c287bc82b
[]
no_license
appleman1/strategy-example
76a13e0fa11b6b11cab8fd4c4dbf6cccb7f4e81d
36f06ce67506317efd4fb3ab6cde42ea1bd60581
refs/heads/master
2021-08-19T14:03:15.997940
2017-11-26T14:32:43
2017-11-26T14:32:43
null
0
0
null
null
null
null
UTF-8
Java
false
false
353
java
package net.eutkin.strategy.example; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class StrategyExampleApplicationTests { @Test public void contextLoads() { } }
[ "evgeny.utkin@mediascope.net" ]
evgeny.utkin@mediascope.net
f98ff099ee2e77239c43364df159f21a4d1df824
7130e47450bd80f35c7213c88a737e639d329e6f
/wxxr-mobile-xml/src/main/java/com/wxxr/javax/ws/rs/CookieParam.java
d5e2f684f5685c515e2417f251aae2f2713feca0
[]
no_license
wxynick/framework
983be31104b360008a2d36565bc82d74b82804fc
93b5fe0c3e40ad434325b1755d0b1be5255977ac
refs/heads/master
2016-09-06T18:33:32.119410
2014-04-04T11:52:21
2014-04-04T11:52:21
9,125,521
0
1
null
null
null
null
UTF-8
Java
false
false
4,139
java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2010-2013 Oracle and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can * obtain a copy of the License at * http://glassfish.java.net/public/CDDL+GPL_1_1.html * or packager/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at packager/legal/LICENSE.txt. * * GPL Classpath Exception: * Oracle designates this particular file as subject to the "Classpath" * exception as provided by Oracle in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package com.wxxr.javax.ws.rs; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Binds the value of a HTTP cookie to a resource method parameter, * resource class field, or resource class bean property. * A default value can be specified using the {@link DefaultValue} * annotation. * * The type {@code T} of the annotated parameter, field or property must * either: * <ol> * <li>Be a primitive type</li> * <li>Be {@link com.wxxr.javax.ws.rs.core.Cookie}</li> * <li>Have a constructor that accepts a single String argument</li> * <li>Have a static method named {@code valueOf} or {@code fromString} * that accepts a single String argument (see, for example, {@link Integer#valueOf(String)})</li> * <li>Have a registered implementation of {@link com.wxxr.javax.ws.rs.ext.ParamConverterProvider} * JAX-RS extension SPI that returns a {@link com.wxxr.javax.ws.rs.ext.ParamConverter} * instance capable of a "from string" conversion for the type.</li> * <li>Be {@code List<T>}, {@code Set<T>} or * {@code SortedSet<T>}, where {@code T} satisfies 2, 3, 4 or 5 above. * The resulting collection is read-only.</li> * </ol> * * <p>Because injection occurs at object creation time, use of this annotation * on resource class fields and bean properties is only supported for the * default per-request resource class lifecycle. Resource classes using * other lifecycles should only use this annotation on resource method * parameters.</p> * * @author Paul Sandoz * @author Marc Hadley * @see DefaultValue * @see com.wxxr.javax.ws.rs.core.Cookie * @see com.wxxr.javax.ws.rs.core.HttpHeaders#getCookies * @since 1.0 */ @Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface CookieParam { /** * Defines the name of the HTTP cookie whose value will be used * to initialize the value of the annotated method argument, class field or * bean property. */ String value(); }
[ "" ]
08771e463dc178563d626a04a880eff51800dcb1
cbc1a85aa864150e20428b99370f8b2f3700976e
/Reporter/html/SAME_POSITION/68_left.java
dd667a520ccb61a9e70a2505494cfb1c6ad18a85
[]
no_license
guilhermejccavalcanti/sourcesvj
965f4d8e88ba25ff102ef54101e9eb3ca53cc8a0
9ca14a022dfe91a4a4307a9fa8196d823356b022
refs/heads/master
2020-04-24T11:58:01.645560
2019-09-07T00:35:06
2019-09-07T00:35:06
171,941,485
0
0
null
null
null
null
UTF-8
Java
false
false
20,622
java
/******************************************************************************* * * Copyright 2012 Impetus Infotech. * * * * 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.impetus.kundera.persistence; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.impetus.kundera.PersistenceUtilHelper; import com.impetus.kundera.client.Client; import com.impetus.kundera.client.EnhanceEntity; import com.impetus.kundera.metadata.KunderaMetadataManager; import com.impetus.kundera.metadata.MetadataUtils; import com.impetus.kundera.metadata.model.EntityMetadata; import com.impetus.kundera.metadata.model.Relation; import com.impetus.kundera.metadata.model.Relation.ForeignKey; import com.impetus.kundera.persistence.context.PersistenceCacheManager; import com.impetus.kundera.property.PropertyAccessException; import com.impetus.kundera.property.PropertyAccessorHelper; /** * The Class AbstractEntityReader. * * @author vivek.mishra */ public class AbstractEntityReader { /** The log. */ private static Logger log = LoggerFactory.getLogger(AbstractEntityReader.class); /** The lucene query from jpa query. */ protected String luceneQueryFromJPAQuery; private AssociationBuilder associationBuilder; /** * Retrieves an entity from ID * * @param primaryKey * @param m * @param client * @return */ protected EnhanceEntity findById(Object primaryKey, EntityMetadata m, Client client) { try { Object o = client.find(m.getEntityClazz(), primaryKey); if (o == null) { // No entity found return null; } else { return o instanceof EnhanceEntity ? (EnhanceEntity) o : new EnhanceEntity(o, getId(o, m), null); } } catch (Exception e) { throw new EntityReaderException(e); } } /** * Recursively fetches associated entities for a given <code>entity</code> * * @param entity * @param relationsMap * @param client * @param m * @param pd * @return */ public Object handleAssociation(final Object entity, final Map<String, Object> relationsMap, final EntityMetadata m, final PersistenceDelegator pd) { for (Relation relation : m.getRelations()) { ForeignKey relationType = relation.getType(); Object relationalObject = PropertyAccessorHelper.getObject(entity, relation.getProperty()); //TODO: Need to check if object is a collection instance but empty! if (relationalObject == null || PersistenceUtilHelper.instanceOfHibernateProxy(relationalObject) || PersistenceUtilHelper.instanceOfHibernatePersistentSet(relationalObject) || PersistenceUtilHelper.instanceOfHibernatePersistentCollection(relationalObject) || PersistenceUtilHelper.instanceOfHibernatePersistentBag(relationalObject)) { onRelation(entity, relationsMap, m, pd, relation, relationType); } } return entity; } private void onRelation(final Object entity, final Map<String, Object> relationsMap, final EntityMetadata m, final PersistenceDelegator pd, Relation relation, ForeignKey relationType) { // TODO: MANY TO MANY if (relation.getType().equals(ForeignKey.MANY_TO_MANY)) { // First, Save this entity to persistence cache Field f = relation.getProperty(); Object object = PropertyAccessorHelper.getObject(entity, f); final Object entityId = PropertyAccessorHelper.getId(entity, m); PersistenceCacheManager.addEntityToPersistenceCache(entity, pd, entityId); associationBuilder.populateRelationForM2M(entity, m, pd, relation, object, relationsMap); } else { onRelation(entity, relationsMap, relation, m, pd); } } /** * Method to handle one to one association relation events. * * @param entity * relation owning entity. * @param entityId * entity id of relation owning entity. * @param relationsMap * contains relation name and it's value. * @param m * entity metadata. */ private void onRelation(Object entity, Map<String, Object> relationsMap, final Relation relation, final EntityMetadata metadata, final PersistenceDelegator pd) { final Object entityId = PropertyAccessorHelper.getId(entity, metadata); // if relation map contains value, then invoke target entity with find // by id. // else invoke target entity for find by relation, pass it's entityId as // a column value and relation.getJoinColumnName as column name. Object relationValue = relationsMap != null ? relationsMap.get(relation.getJoinColumnName()) : null; // EntityMetadata targetEntityMetadata = null; EntityMetadata targetEntityMetadata = KunderaMetadataManager.getEntityMetadata(relation.getTargetEntity()); List relationalEntities = fetchRelations(relation, metadata, pd, entityId, relationValue, targetEntityMetadata); // parse for associated relation. if (relationalEntities != null) { for (Object relationEntity : relationalEntities) { onParseRelation(entity, pd, targetEntityMetadata, relationEntity, relation); } } } private void onParseRelation(Object entity, final PersistenceDelegator pd, EntityMetadata targetEntityMetadata, Object relationEntity, Relation relation) { parseRelations(entity, getEntity(relationEntity), getPersistedRelations(relationEntity), pd, targetEntityMetadata); // if relation ship is unary, no problem else we need to add setRelationToEntity(entity, relationEntity, relation); } private void setRelationToEntity(Object entity, Object relationEntity, Relation relation) { if (relation.getTargetEntity().isAssignableFrom(getEntity(relationEntity).getClass())) { if (relation.isUnary()) { PropertyAccessorHelper.set(entity, relation.getProperty(), getEntity(relationEntity)); } else { Object associationObject = PropertyAccessorHelper.getObject(entity, relation.getProperty()); if (associationObject == null || PersistenceUtilHelper.instanceOfHibernateProxy(associationObject) || PersistenceUtilHelper.instanceOfHibernatePersistentSet(associationObject) || PersistenceUtilHelper.instanceOfHibernatePersistentCollection(associationObject) || PersistenceUtilHelper.instanceOfHibernatePersistentBag(associationObject)) { associationObject = PropertyAccessorHelper.getCollectionInstance(relation.getProperty()); PropertyAccessorHelper.set(entity, relation.getProperty(), associationObject); } ((Collection) associationObject).add(getEntity(relationEntity)); } } } private void parseRelations(final Object originalEntity, final Object relationEntity, final Map<String, Object> relationsMap, final PersistenceDelegator pd, final EntityMetadata metadata) { for (Relation relation : metadata.getRelations()) { if (relation.isUnary() && relation.getTargetEntity().isAssignableFrom(originalEntity.getClass())) { // PropertyAccessorHelper.set(relationEntity, // relation.getProperty(), originalEntity); Object associationObject = PropertyAccessorHelper.getObject(relationEntity, relation.getProperty()); if (relation.getType().equals(ForeignKey.ONE_TO_ONE) || ((associationObject == null || PersistenceUtilHelper.instanceOfHibernateProxy(associationObject) || PersistenceUtilHelper.instanceOfHibernatePersistentSet(associationObject) || PersistenceUtilHelper .instanceOfHibernatePersistentCollection(associationObject)))) { PropertyAccessorHelper.set(relationEntity, relation.getProperty(), originalEntity); } else if (relationsMap != null && relationsMap.containsKey(relation.getJoinColumnName())) { PropertyAccessorHelper.set(relationEntity, relation.getProperty(), originalEntity); } } else { // Here // onRelation(relationEntity, relationsMap, metadata, pd, // relation, relationType); final Object entityId = PropertyAccessorHelper.getId(relationEntity, metadata); Object relationValue = relationsMap != null ? relationsMap.get(relation.getJoinColumnName()) : null; final EntityMetadata targetEntityMetadata = KunderaMetadataManager.getEntityMetadata(relation .getTargetEntity()); List immediateRelations = fetchRelations(relation, metadata, pd, entityId, relationValue, targetEntityMetadata); // System.out.println("dddd"); // Here in case of one-to-many/many-to-one we should skip this // relation as it if (immediateRelations != null && !immediateRelations.isEmpty()) { // immediateRelations.remove(originalEntity); // As it is // already // in process. for (Object immediateRelation : immediateRelations) { // System.out.println("Here"); if (!compareTo(getEntity(immediateRelation), originalEntity)) { onParseRelation(relationEntity, pd, targetEntityMetadata, immediateRelation, relation); } } setRelationToEntity(relationEntity, originalEntity, relation); } /** * */ } } } private List fetchRelations(final Relation relation, final EntityMetadata metadata, final PersistenceDelegator pd, final Object entityId, Object relationValue, EntityMetadata targetEntityMetadata) { List relationalEntities = new ArrayList(); if ((relationValue != null && relation.isUnary()) || (relation.isJoinedByPrimaryKey())) { // Call it Object relationEntity = pd.getClient(targetEntityMetadata).find(relation.getTargetEntity(), relationValue != null ? relationValue : entityId); if (relationEntity != null) { relationalEntities.add(relationEntity); } } else if (!relation.isUnary()) { // Now these entities may be enhance entities and may not be as // well. Client associatedClient = pd.getClient(targetEntityMetadata); if (!MetadataUtils.useSecondryIndex(targetEntityMetadata.getPersistenceUnit())) { relationalEntities = associationBuilder.getAssociatedEntitiesFromIndex(relation.getProperty().getDeclaringClass(), entityId, targetEntityMetadata.getEntityClazz(), associatedClient); } else { relationalEntities = associatedClient.findByRelation(relation.getJoinColumnName(), entityId, relation.getTargetEntity()); } } return relationalEntities; } /** * Recursively fetches associated entities for a given <code>entity</code> * * @param entity * @param relationsMap * @param client * @param m * @param pd * @return */ public Object recursivelyFindEntities(Object entity, Map<String, Object> relationsMap, EntityMetadata m, PersistenceDelegator pd) { associationBuilder = new AssociationBuilder(); /* * Object entityId = PropertyAccessorHelper.getId(entity, m); * associationBuilder = new AssociationBuilder(); * * for (Relation relation : m.getRelations()) { // validate relation * ForeignKey type = relation.getType(); Field f = * relation.getProperty(); if (isTraversalRequired(relationsMap, type)) * { // Check whether that relation is already populated or not, // * before proceeding further. Object object = * PropertyAccessorHelper.getObject(entity, f); * * // Populate Many-to-many relationships if * (relation.getType().equals(ForeignKey.MANY_TO_MANY)) { // First, Save * this entity to persistence cache * PersistenceCacheManager.addEntityToPersistenceCache(entity, pd, * entityId); associationBuilder.populateRelationForM2M(entity, m, pd, * relation, object, relationsMap); } * * // Populate other type of relationships else if (object == null || * PersistenceUtilHelper.instanceOfHibernateProxy(object) || * PersistenceUtilHelper.instanceOfHibernatePersistentSet(object) || * PersistenceUtilHelper * .instanceOfHibernatePersistentCollection(object)) { boolean * isBidirectionalRelation = relation.isBiDirectional(); * * Class<?> childClass = relation.getTargetEntity(); EntityMetadata * childMetadata = KunderaMetadataManager.getEntityMetadata(childClass); * * Object relationValue = null; String relationName = null; * * if (isBidirectionalRelation && * !StringUtils.isBlank(relation.getMappedBy()) && * (relation.getType().equals(ForeignKey.ONE_TO_ONE) || * relation.getType().equals( ForeignKey.MANY_TO_ONE))) { relationName = * ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName(); } else { * relationName = MetadataUtils.getMappedName(m, relation); } * * relationValue = relationsMap != null ? relationsMap.get(relationName) * : null; * * if (relationValue != null) { // 1-1 or M-1 relationship, because ID * is held at // this side of entity and hence // relationship entities * would be retrieved from // database based on these IDs already * available associationBuilder .populateRelationFromValue(entity, pd, * relation, relationValue, childMetadata); * * } else { // 1-M relationship, since ID is stored at other // side of * // entity and as a result relation value will be // null // This * requires running query (either Lucene or // Native // based on * secondary indexes supported by // underlying // database) // Running * query returns all those associated // entities // that // hold parent * entity ID as foreign key * associationBuilder.populateRelationViaQuery(entity, pd, entityId, * relation, relationName, childMetadata); } } * * } else if (relation.isJoinedByPrimaryKey()) { * PropertyAccessorHelper.set(entity, f, * pd.findById(relation.getTargetEntity(), entityId)); } } return * entity; */ return handleAssociation(entity, relationsMap, m, pd); } private Map<String, Object> getPersistedRelations(Object relationEntity) { return relationEntity != null && relationEntity.getClass().isAssignableFrom(EnhanceEntity.class) ? ((EnhanceEntity) relationEntity) .getRelations() : null; } private Object getEntity(Object relationEntity) { return relationEntity.getClass().isAssignableFrom(EnhanceEntity.class) ? ((EnhanceEntity) relationEntity) .getEntity() : relationEntity; } /** * @param relationsMap * @param type * @return */ private boolean isTraversalRequired(Map<String, Object> relationsMap, ForeignKey type) { return !(relationsMap == null && (type.equals(ForeignKey.ONE_TO_ONE) || type.equals(ForeignKey.MANY_TO_ONE))); } /** * On association using lucene. * * @param m * the m * @param client * the client * @param ls * the ls * @return the list */ protected List<EnhanceEntity> onAssociationUsingLucene(EntityMetadata m, Client client, List<EnhanceEntity> ls) { Set<String> rSet = fetchDataFromLucene(client); List resultList = client.findAll(m.getEntityClazz(), null, rSet.toArray(new String[] {})); return m.getRelationNames() != null && !m.getRelationNames().isEmpty() ? resultList : transform(m, ls, resultList); } /** * Transform. * * @param m * the m * @param ls * the ls * @param resultList * the result list * @return the list */ protected List<EnhanceEntity> transform(EntityMetadata m, List<EnhanceEntity> ls, List resultList) { if ((ls == null || ls.isEmpty()) && resultList != null && !resultList.isEmpty()) { ls = new ArrayList<EnhanceEntity>(resultList.size()); } for (Object r : resultList) { EnhanceEntity e = new EnhanceEntity(r, getId(r, m), null); ls.add(e); } return ls; } /** * Fetch data from lucene. * * @param client * the client * @return the sets the */ protected Set<String> fetchDataFromLucene(Client client) { // use lucene to query and get Pk's only. // go to client and get relation with values.! // populate EnhanceEntity Map<String, Object> results = client.getIndexManager().search(luceneQueryFromJPAQuery); Set rSet = new HashSet(results.values()); return rSet; } /** * Gets the id. * * @param entity * the entity * @param metadata * the metadata * @return the id */ protected Object getId(Object entity, EntityMetadata metadata) { try { return PropertyAccessorHelper.getId(entity, metadata); } catch (PropertyAccessException e) { log.error("Error while Getting ID, Caused by: ", e); throw new EntityReaderException("Error while Getting ID for entity " + entity, e); } } private boolean compareTo(Object relationalEntity, Object originalEntity) { if (relationalEntity != null && originalEntity != null && relationalEntity.getClass().isAssignableFrom(originalEntity.getClass())) { EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(originalEntity.getClass()); Object relationalEntityId = PropertyAccessorHelper.getId(relationalEntity, metadata); Object originalEntityId = PropertyAccessorHelper.getId(originalEntity, metadata); return relationalEntityId.equals(originalEntityId); } return false; } }
[ "gjcc@cin.ufpe.br" ]
gjcc@cin.ufpe.br
70946a9f17d3f302e3d1a2b0a14e629428913ced
a12a3b21a08d5bae9d9c99e4fa82ff1fc3fed16e
/src/sample/Controller.java
113a969b6f2aed38bf66eb7a5b5a2efd3facab18
[]
no_license
andriusbaltrunas/FistJavaFXExample
56270947f67e1935b8fbf755a86af190d83247b8
faeb4ed3738600eb6d3055681efc95edfef46017
refs/heads/master
2020-09-11T09:18:27.530881
2017-06-16T16:57:32
2017-06-16T16:57:32
94,454,824
0
0
null
null
null
null
UTF-8
Java
false
false
1,411
java
package sample; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import read.ReadFile; import java.util.HashMap; import java.util.List; import java.util.Map; public class Controller { @FXML private TextField input; @FXML private TextArea output; private Map<String, List<String>> engMap = new HashMap<>(); private Map<String, List<String>> ltMap = new HashMap<>(); public void translate(ActionEvent event){ if (engMap.isEmpty() || ltMap.isEmpty()){ ReadFile readFile = new ReadFile(engMap, ltMap); readFile.read(); } String word = input.getText(); List<String> words = engMap.get(word); if(words == null){ words = ltMap.get(word); } printResult(words); } private void printResult(List<String> words){ if(words!= null && !words.isEmpty()){ StringBuilder sb = new StringBuilder(); for(String w : words){ sb.append(w).append("\n"); } output.setText(sb.toString()); }else{ Alert alert = new Alert(Alert.AlertType.WARNING); alert.setContentText("Tokio zodzio juk nera!!!"); alert.show(); } } }
[ "andriusbaltrunas@yahoo.com" ]
andriusbaltrunas@yahoo.com
fe4a9e4c115f9db515c9dfec99cd3f589f5d8a1b
4dd7178ff8789472381fdc3a02ec993ef829b495
/src/main/java/com/example/springboot/repositories/UserDao.java
9144984af2f0f50f41e3788746da7d0227e73855
[]
no_license
jennypherroussell/springboot
719d1db0aaeb76ac9ff0fe80c9896e56a94fe389
02be67c89ab05f2a1ccc60c4321e3c41b119c123
refs/heads/master
2021-07-03T06:43:46.421693
2017-09-25T21:01:50
2017-09-25T21:01:50
103,234,533
0
0
null
null
null
null
UTF-8
Java
false
false
395
java
package com.example.springboot.repositories; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import com.example.springboot.model.User; public interface UserDao extends MongoRepository<User, String> { @Query("{ '_id' : ?0 }") User findById(String _id); public void delete(String id); }
[ "jroussell@BFMXNB12574.baunet.local" ]
jroussell@BFMXNB12574.baunet.local
654cd0315dad7944264cb28a7ca0c990f1bc5d69
9602f5661333f9aa0ed55d24f225bad18102daa5
/src/main/java/projet/ynov/dizifymusicapi/security/JwtTokenFilterConfigurer.java
7967b5ea6260fda84c7424d575502276498273b6
[]
no_license
Kredoa/dizifyMusic_API
180e18d3814fbb11d8564f56afbad1851161e8d0
39d1ca755afec9df345a664ef56e3edf3302cd25
refs/heads/master
2023-01-29T11:46:52.519121
2020-11-22T20:40:07
2020-11-22T20:40:07
320,705,453
0
0
null
null
null
null
UTF-8
Java
false
false
902
java
package projet.ynov.dizifymusicapi.security; import org.springframework.security.config.annotation.SecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.DefaultSecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; public class JwtTokenFilterConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> { private JwtTokenProvider jwtTokenProvider; public JwtTokenFilterConfigurer(JwtTokenProvider jwtTokenProvider) { this.jwtTokenProvider = jwtTokenProvider; } @Override public void configure(HttpSecurity http) throws Exception { JwtTokenFilter customFilter = new JwtTokenFilter(jwtTokenProvider); http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class); } }
[ "you@example.com" ]
you@example.com
bab3b229cbd9b12e0bc5fca23768f7a8b5483868
09b7f281818832efb89617d6f6cab89478d49930
/root/projects/alfresco-jlan/source/java/org/alfresco/jlan/server/auth/asn/DERBitString.java
7591001198f667e0abbe54f9524f09db24bc3273
[]
no_license
verve111/alfresco3.4.d
54611ab8371a6e644fcafc72dc37cdc3d5d8eeea
20d581984c2d22d5fae92e1c1674552c1427119b
refs/heads/master
2023-02-07T14:00:19.637248
2020-12-25T10:19:17
2020-12-25T10:19:17
323,932,520
1
1
null
null
null
null
UTF-8
Java
false
false
2,806
java
/* * Copyright (C) 2006-2010 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>. */ package org.alfresco.jlan.server.auth.asn; import java.io.IOException; /** * DER Bit String Class * * @author gkspencer */ public class DERBitString extends DERObject { // Bit flags value private long m_bits; /** * Default constructor */ public DERBitString() { } /** * Class constructor * * @param bits int */ public DERBitString( long bits) { m_bits = bits; } /** * Return the value * * @return long */ public final long getValue() { return m_bits; } /** * Return the value as an integer * * @return int */ public final int intValue() { return (int) m_bits; } /** * Decode the object * * @param buf * @throws IOException */ public void derDecode(DERBuffer buf) throws IOException { // Decode the type if ( buf.unpackType() == DER.BitString) { // Unpack the length and bytes int len = buf.unpackLength(); int lastBits = buf.unpackByte(); m_bits = 0; long curByt = 0L; len --; for ( int idx = (len - 1); idx >= 0; idx--) { // Get the value bytes curByt = (long) buf.unpackByte(); m_bits += curByt << (idx * 8); } } else throw new IOException("Wrong DER type, expected BitString"); } /** * Encode the object * * @param buf * @throws IOException */ public void derEncode(DERBuffer buf) throws IOException { // Pack the type, length and bytes buf.packByte( DER.BitString); buf.packByte( 0); buf.packLength( 8); for ( int idx = 7; idx >= 0; idx--) { long bytVal = m_bits >> ( idx * 8); buf.packByte((int) ( m_bits & 0xFF)); } } /** * Return the bit string as a string * * @return String */ public String toString() { StringBuffer str = new StringBuffer(); str.append("[BitString:0x"); str.append( Long.toHexString( m_bits)); str.append("]"); return str.toString(); } }
[ "verve111@mail.ru" ]
verve111@mail.ru
66891f77dd56ad5deaa954e4ddf7eac75f3c4a1c
409c5b1bfc6e3cf6b506e312f73adf8b1b6a7f85
/app/src/androidTest/java/com/example/admin/taskremember/ExampleInstrumentedTest.java
e03178a85ab89ed2bf24c7acee73aa8aa46e8dd5
[]
no_license
borserb/taskremember
5747599a5ccb79298f39eb7733ba31a1647f11e4
332df7c2211d75a5665acd630e5de4cfd3f83d86
refs/heads/master
2020-04-27T08:27:23.315175
2019-05-08T14:20:53
2019-05-08T14:20:53
174,172,057
0
0
null
null
null
null
UTF-8
Java
false
false
744
java
package com.example.admin.taskremember; 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.example.admin.taskremember", appContext.getPackageName()); } }
[ "borserb@gmail.com" ]
borserb@gmail.com
e9800077b667e2722fc358494311165f370d0d37
02d9b91b721a175f9239bc34fb0585c04c267036
/src/co/sprayable/sleep/pages/SprayableEnergyFountainOfYouthPage.java
47e86f2e968cd164128b4d2afc8528dfcb0136b8
[]
no_license
DaryaForest/Cubeque
a46cea00b38fbaaa5a20eadc4a74a4a181a0e3b5
3ec3ca77e2ad119201dc639ad2c62bc6a7b02447
refs/heads/master
2021-05-08T05:06:41.809236
2017-10-26T14:36:00
2017-10-26T14:36:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,398
java
package co.sprayable.sleep.pages; import qa.util.base.BasePage; import qa.util.base.Locator; import qa.util.base.LocatorTypes; public class SprayableEnergyFountainOfYouthPage extends BasePage { private Locator getSprayableEnergyButton = new Locator(LocatorTypes.XPATH, "//div[contains(@class, 'layout')][2]//div[@class='btn-container']"); private Locator getSprayableEnergyFor25OffButton = new Locator(LocatorTypes.XPATH, "//div[contains(@class, 'layout')][3]//div[@class='btn-container']"); public void waitSprayableEnergyButton(){ waitForVisibility("Wait for 'Get Sprayable energy' button to be visible", getSprayableEnergyButton); waitToBeClickable("Wait for 'Get Sprayable energy' button to be clickable", getSprayableEnergyButton); } public void clickSprayableEnergyButton() { click("click on 'Get Sprayable energy' button", getSprayableEnergyButton); } public void waitSprayableEnergyFor25OffButton(){ waitForVisibility("Wait for 'Get Sprayable energy for 25% OFF' button to be visible", getSprayableEnergyFor25OffButton); waitToBeClickable("Wait for 'Get Sprayable energy for 25% OFF' button to be clickable", getSprayableEnergyFor25OffButton); } public void clickSprayableEnergyFor25OffButton() { click("click on 'Get Sprayable energy for 25% OFF' button", getSprayableEnergyFor25OffButton); } }
[ "darya.novoselova1@gmail.com" ]
darya.novoselova1@gmail.com
33494a561c6b4256c9ef78a3b047eabb3f1cd485
3a85f2d03504efd8d2708aa10607024d57c673e6
/src/main/java/com/zhuangjieying/model/vo/Enemy.java
6baa89c492ed5a880b0ad183f5093d7de26534a1
[]
no_license
jayying007/Game_MetalSlug
b685626e7e3041aeb764261f86327a6c2a889b89
72bfd506a4aa11cdfc8ac50b747c575f0ea4551b
refs/heads/master
2023-06-18T20:41:40.655029
2021-07-14T16:28:44
2021-07-14T16:28:44
386,004,966
0
0
null
null
null
null
UTF-8
Java
false
false
12,290
java
package com.zhuangjieying.model.vo; import java.awt.Graphics; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.swing.ImageIcon; import com.zhuangjieying.model.manager.ElementManager; import com.zhuangjieying.model.manager.EnemyMoveType; public class Enemy extends SuperElement{ private Map<String,List<ImageIcon>> actMap;//�������еĶ���������ͼƬ private EnemyMoveType moveType;//���˵�ǰ״̬ private EnemyMoveType previousMoveType;//���˵���һ��״̬ private boolean towardLeft;//�����Ƿ������ private List<ImageIcon> tempList;//��ʱ�洢����������������ͼƬ private int i=0;//����ͼƬ����˳�� private int imgWidth=0,imgHeight=0;//��ǰ���ŵ�ͼƬ�Ŀ�͸� private int anger;//ŭ��ֵ�������Ϳ�ǹ private int j=0;//������������״̬�Ķ�������ΪҪ���� private int previousDieY=0; public Enemy(int x,int y,int w,int h,Map<String, List<ImageIcon>> map) { super(x,y,w,h); this.actMap=map; moveType=EnemyMoveType.stop; towardLeft=true; this.anger=30;//һ��ʼ��ŭ���ṥ�� tempList=new ArrayList<>(); previousDieY=y; } public static Enemy createEnemy(String str,Map<String, List<ImageIcon>>map){ // System.out.println(str); String [] arr=str.split(","); int x = Integer.parseInt(arr[0]); int y = Integer.parseInt(arr[1]); int w = Integer.parseInt(arr[2]); int h = Integer.parseInt(arr[3]); Map<String, List<ImageIcon>>actMap=map; return new Enemy(x, y, w, h, actMap); } @Override public void showElement(Graphics g) { if(anger<30) {//���ŭ��ֵ�������ǾͲ����� anger++; if(moveType!=EnemyMoveType.die) { this.moveType=EnemyMoveType.stop; } } switch (moveType) { case run: if(towardLeft) { tempList=actMap.get("enemyLeftRun"); i=i%(tempList.size()); g.drawImage(tempList.get(i).getImage(), getX(), getY(), getW(), getH(), null); break; }else { tempList=actMap.get("enemyRightRun"); i=i%(tempList.size()); g.drawImage(tempList.get(i).getImage(), getX(), getY(), getW(), getH(), null); break; } case stop: if(towardLeft){ tempList=actMap.get("enemyLeftStand"); i=i%(tempList.size()); g.drawImage(tempList.get(i).getImage(), getX(), getY(), getW(), getH(), null); }else { tempList=actMap.get("enemyRightStand"); i=i%(tempList.size()); g.drawImage(tempList.get(i).getImage(), getX(), getY(), getW(), getH(), null); } break; case attackKnife: if(towardLeft) { tempList=actMap.get("enemyLeftAttackKnife"); i=i%(tempList.size()); imgWidth=tempList.get(i).getIconWidth(); imgHeight=tempList.get(i).getIconHeight(); // System.out.println("i is "+i); switch (i) { case 0: g.drawImage(tempList.get(i).getImage(), getX(), getY()+10, imgWidth, imgHeight, null); break; case 1: g.drawImage(tempList.get(i).getImage(), getX()-10, getY()+10, imgWidth, imgHeight, null); break; case 2: g.drawImage(tempList.get(i).getImage(), getX()-40, getY()+10, imgWidth, imgHeight, null); break; case 3: g.drawImage(tempList.get(i).getImage(), getX()-60, getY()+10, imgWidth, imgHeight, null); break; case 4: g.drawImage(tempList.get(i).getImage(), getX()-55, getY()+2, imgWidth, imgHeight, null); anger=5; break; default: break; } }else { tempList=actMap.get("enemyRightAttackKnife"); i=i%(tempList.size()); imgWidth=tempList.get(i).getIconWidth(); imgHeight=tempList.get(i).getIconHeight(); // System.out.println("i is "+i); switch (i) { case 0: g.drawImage(tempList.get(i).getImage(), getX(), getY()+10, imgWidth, imgHeight, null); break; case 1: g.drawImage(tempList.get(i).getImage(), getX(), getY()+10, imgWidth, imgHeight, null); break; case 2: g.drawImage(tempList.get(i).getImage(), getX(), getY()+10, imgWidth, imgHeight, null); break; case 3: g.drawImage(tempList.get(i).getImage(), getX(), getY()+10, imgWidth, imgHeight, null); break; case 4: g.drawImage(tempList.get(i).getImage(), getX(), getY()+2, imgWidth, imgHeight, null); anger=5; break; default: break; } } break; case attackGun1: if(towardLeft) { tempList=actMap.get("enemyLeftAttackGun1"); i=i%(tempList.size()); imgWidth=tempList.get(i).getIconWidth(); imgHeight=tempList.get(i).getIconHeight(); switch (i) { case 0: g.drawImage(tempList.get(i).getImage(), getX()-45, getY(), imgWidth, imgHeight, null); break; case 1: addFire(); g.drawImage(tempList.get(i).getImage(), getX()-55, getY(), imgWidth, imgHeight, null); break; case 2: g.drawImage(tempList.get(i).getImage(), getX()-60, getY(), imgWidth, imgHeight, null); break; case 3: g.drawImage(tempList.get(i).getImage(), getX()-60, getY(), imgWidth, imgHeight, null); break; case 4: g.drawImage(tempList.get(i).getImage(), getX()-50, getY()-8, imgWidth, imgHeight, null); anger=0; break; default: break; } }else { tempList=actMap.get("enemyRightAttackGun1"); i=i%(tempList.size()); imgWidth=tempList.get(i).getIconWidth(); imgHeight=tempList.get(i).getIconHeight(); switch (i) { case 0: g.drawImage(tempList.get(i).getImage(), getX(), getY(), imgWidth, imgHeight, null); break; case 1: addFire(); g.drawImage(tempList.get(i).getImage(), getX(), getY(), imgWidth, imgHeight, null); break; case 2: g.drawImage(tempList.get(i).getImage(), getX(), getY(), imgWidth, imgHeight, null); break; case 3: g.drawImage(tempList.get(i).getImage(), getX(), getY(), imgWidth, imgHeight, null); break; case 4: g.drawImage(tempList.get(i).getImage(), getX(), getY()-8, imgWidth, imgHeight, null); anger=0; break; default: break; } } break; case attackGun2: if(towardLeft) { tempList=actMap.get("enemyLeftAttackGun2"); i=i%(tempList.size()); imgWidth=tempList.get(i).getIconWidth(); imgHeight=tempList.get(i).getIconHeight(); switch (i) { case 0: g.drawImage(tempList.get(i).getImage(), getX()-45, getY(), imgWidth, imgHeight, null); break; case 1: addFire(); g.drawImage(tempList.get(i).getImage(), getX()-45, getY(), imgWidth, imgHeight, null); break; case 2: g.drawImage(tempList.get(i).getImage(), getX()-40, getY()-15, imgWidth, imgHeight, null); break; case 3: g.drawImage(tempList.get(i).getImage(), getX()-30, getY()-15, imgWidth, imgHeight, null); break; case 4: g.drawImage(tempList.get(i).getImage(), getX()-40, getY()-10, imgWidth, imgHeight, null); anger=0; break; default: break; } }else { tempList=actMap.get("enemyRightAttackGun2"); i=i%(tempList.size()); imgWidth=tempList.get(i).getIconWidth(); imgHeight=tempList.get(i).getIconHeight(); switch (i) { case 0: g.drawImage(tempList.get(i).getImage(), getX(), getY(), imgWidth, imgHeight, null); break; case 1: addFire(); g.drawImage(tempList.get(i).getImage(), getX(), getY(), imgWidth, imgHeight, null); break; case 2: g.drawImage(tempList.get(i).getImage(), getX(), getY()-15, imgWidth, imgHeight, null); break; case 3: g.drawImage(tempList.get(i).getImage(), getX(), getY()-15, imgWidth, imgHeight, null); break; case 4: g.drawImage(tempList.get(i).getImage(), getX(), getY()-10, imgWidth, imgHeight, null); anger=0; break; default: break; } } break; case die: if(towardLeft) { tempList=actMap.get("enemyLeftDie1"); imgWidth=tempList.get(j).getIconWidth(); imgHeight=tempList.get(j).getIconHeight(); switch (i) { case 0: j=0; g.drawImage(tempList.get(j).getImage(), getX(), getY()+10, imgWidth, imgHeight, null);//���j*10���Գ����� previousDieY=getY()+10; break; case 2: j=1; g.drawImage(tempList.get(j).getImage(), getX(), getY()+10, imgWidth, imgHeight, null);//���j*10���Գ����� previousDieY=getY()+10; break; case 4: j=2; g.drawImage(tempList.get(j).getImage(), getX(), getY()+10, imgWidth, imgHeight, null);//���j*10���Գ����� previousDieY=getY()+15; break; case 6: j=3; g.drawImage(tempList.get(j).getImage(), getX(), getY()+20, imgWidth, imgHeight, null);//���j*10���Գ����� previousDieY=getY()+25; break; case 8: j=4; g.drawImage(tempList.get(j).getImage(), getX(), getY()+30, imgWidth, imgHeight, null);//���j*10���Գ����� previousDieY=getY()+40; break; case 14: setVisible(false); break; default: g.drawImage(tempList.get(j).getImage(), getX(), previousDieY, imgWidth, imgHeight, null);//���j*10���Գ����� break; } } else { tempList=actMap.get("enemyRightDie1"); imgWidth=tempList.get(j).getIconWidth(); imgHeight=tempList.get(j).getIconHeight(); switch (i) { case 0: j=0; g.drawImage(tempList.get(j).getImage(), getX(), getY()+10, imgWidth, imgHeight, null);//���j*10���Գ����� previousDieY=getY()+10; break; case 2: j=1; g.drawImage(tempList.get(j).getImage(), getX(), getY()+10, imgWidth, imgHeight, null);//���j*10���Գ����� previousDieY=getY()+10; break; case 4: j=2; g.drawImage(tempList.get(j).getImage(), getX(), getY()+10, imgWidth, imgHeight, null);//���j*10���Գ����� previousDieY=getY()+15; break; case 6: j=3; g.drawImage(tempList.get(j).getImage(), getX(), getY()+20, imgWidth, imgHeight, null);//���j*10���Գ����� previousDieY=getY()+25; break; case 8: j=4; g.drawImage(tempList.get(j).getImage(), getX(), getY()+30, imgWidth, imgHeight, null);//���j*10���Գ����� previousDieY=getY()+40; break; case 14: setVisible(false); break; default: g.drawImage(tempList.get(j).getImage(), getX(), previousDieY, imgWidth, imgHeight, null);//���j*10���Գ����� break; } } break; default: break; } i=i+1; } public void addFire(){ List<SuperElement> list=ElementManager.getManager().getElementList("enemyFire"); switch (moveType) { case attackGun1: if(towardLeft) { list.add(EnemyBullet.createEnemyBullet(getX(), getY(), "bullet1Left")); }else { list.add(EnemyBullet.createEnemyBullet(getX(), getY(), "bullet1Right")); } break; case attackGun2: if(towardLeft) { list.add(EnemyBullet.createEnemyBullet(getX(), getY(), "bullet2Left")); }else { list.add(EnemyBullet.createEnemyBullet(getX(), getY(), "bullet2Right")); } break; default: break; } } @Override public void move() { // TODO Auto-generated method stub switch (moveType) { case run: if(towardLeft) { setX(getX()-3); break; }else { setX(getX()+3); break; } case attackGun1: break; case attackGun2: break; case attackKnife: break; case stop: break; } } @Override public void destroy() { // TODO Auto-generated method stub } public int getAnger() { return anger; } public void setAnger(int anger) { this.anger = anger; } public EnemyMoveType getMoveType() { return moveType; } public void setMoveType(EnemyMoveType moveType) { this.moveType = moveType; } public boolean isTowardLeft() { return towardLeft; } public void setTowardLeft(boolean towardLeft) { this.towardLeft = towardLeft; } public void setI(int i) { this.i = i; } public EnemyMoveType getPreviousMoveType() { return previousMoveType; } public void setPreviousMoveType(EnemyMoveType previousMoveType) { this.previousMoveType = previousMoveType; } }
[ "1172510964@qq.com" ]
1172510964@qq.com
a617b48a43b59ddcae07fc3ec2f467e667c6a182
daaf7747c19e1c14681e82b90c7a42413a38be32
/app/src/main/java/com/open9527/code/lib/module/im/ChatListActivity.java
c998cc07b3f950ae0ea2569142e2fe970c0bb7b9
[]
no_license
sengeiou/openLib
f2b29998004e54582c8235a34ef15a7565604853
8fca7c115b239ecda2bacbc43661f5acc41be111
refs/heads/master
2022-07-31T14:24:45.846325
2020-05-22T10:10:54
2020-05-22T10:10:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
823
java
package com.open9527.code.lib.module.im; import android.os.Bundle; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.open9527.code.common.activity.CommonScreenActivity; /** * Created by : open9527 * Created times : on 2019/8/29 17:22. * E-Mail Address :open_9527@163.com. * DESC :聊天列表. */ public class ChatListActivity extends CommonScreenActivity { @Override public void initData(@Nullable Bundle bundle) { } @Override public int bindLayout() { return 0; } @Override public void initView(@Nullable Bundle savedInstanceState, @Nullable View contentView) { } @Override public void doBusiness() { } @Override public void onDebouncingClick(@NonNull View view) { } }
[ "open_9527@163.com" ]
open_9527@163.com
3fbd274e620ce119284548b4e7364eee13720106
9a0ad6c850275e0e3ec7a378bd6b042c6854b15f
/Aksheya/OnlineCourierManagementApplication/src/test/java/com/cg/mts/OnlineCourierManagementApplicationTests.java
3737225115c49cee0d98fb06bfd2604a82dce0ec
[]
no_license
CapG-Courier/OnlineCourierManagementApplication
dc15f2f77ce0f6af960ef860daba9121c68bfb90
c61b523e00e3a6f1382958ddb51c4bd3fb290a92
refs/heads/main
2023-04-12T19:45:31.744111
2021-04-27T15:26:12
2021-04-27T15:26:12
349,689,099
0
0
null
null
null
null
UTF-8
Java
false
false
219
java
package com.cg.mts; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class OnlineCourierManagementApplicationTests { @Test void contextLoads() { } }
[ "ksaksheya@gmail.com" ]
ksaksheya@gmail.com
b64b15b343a012dbaed45484157dd44f006335f3
73fd7cf535b476ed2238ca42cb5e79d440a92f06
/app/src/main/java/com/cn/uca/view/datepicker/DatePickDialog.java
71861876971db8249691176787026fed284fc18f
[]
no_license
WengYihao/UCA
f4c5ee5d8624aa89aa23eb0558062d80902a576b
2b83b0550db9b44c73015f17e1e0e3a7287768a6
refs/heads/master
2021-01-02T22:28:49.469304
2018-03-29T12:38:11
2018-03-29T12:38:11
99,201,955
0
0
null
null
null
null
UTF-8
Java
false
false
4,520
java
package com.cn.uca.view.datepicker; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.text.TextUtils; import android.view.Gravity; import android.view.View; import android.view.WindowManager; import android.widget.FrameLayout; import android.widget.TextView; import com.cn.uca.R; import com.cn.uca.bean.datepicker.DateType; import com.cn.uca.impl.datepicker.OnChangeLisener; import com.cn.uca.impl.datepicker.OnSureLisener; import com.cn.uca.util.datepicker.DateUtils; import java.text.SimpleDateFormat; import java.util.Date; /** * 自定义日期选择器 */ public class DatePickDialog extends Dialog implements OnChangeLisener { private TextView titleTv; private FrameLayout wheelLayout; private TextView cancel; private TextView sure; private TextView messgeTv; private String title; private String format; private DateType type = DateType.TYPE_ALL; //开始时间 private Date startDate = new Date(); //年分限制,默认上下5年 private int yearLimt = 5; private OnChangeLisener onChangeLisener; private OnSureLisener onSureLisener; private DatePicker mDatePicker; private TextView view; public void setView(TextView view){ this.view = view; } //设置标题 public void setTitle(String title) { this.title=title; } //设置模式 public void setType(DateType type) { this.type = type; } //设置选择日期显示格式,设置显示message,不设置不显示message public void setMessageFormat(String format) { this.format = format; } //设置开始时间 public void setStartDate(Date startDate) { this.startDate = startDate; } //设置年份限制,上下年份 public void setYearLimt(int yearLimt) { this.yearLimt = yearLimt; } //设置选择回调 public void setOnChangeLisener(OnChangeLisener onChangeLisener) { this.onChangeLisener = onChangeLisener; } //设置点击确定按钮,回调 public void setOnSureLisener(OnSureLisener onSureLisener) { this.onSureLisener = onSureLisener; this.view = view; } public DatePickDialog(Context context) { super(context, R.style.dialog_style); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dialog_pick_time); initView(); initParas(); } private DatePicker getDatePicker() { DatePicker picker = new DatePicker(getContext(),type); picker.setStartDate(startDate); picker.setYearLimt(yearLimt); picker.setOnChangeLisener(this); picker.init(); return picker; } private void initView() { this.sure = (TextView) findViewById(R.id.sure); this.cancel = (TextView) findViewById(R.id.cancel); this.wheelLayout = (FrameLayout) findViewById(R.id.wheelLayout); this.titleTv = (TextView) findViewById(R.id.title); messgeTv = (TextView) findViewById(R.id.message); mDatePicker = getDatePicker(); this.wheelLayout.addView(mDatePicker); //setValue this.titleTv.setText(title); this.cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); this.sure.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); if (onSureLisener != null) { onSureLisener.onSure(mDatePicker.getSelectDate()); } } }); } private void initParas() { WindowManager.LayoutParams params = getWindow().getAttributes(); params.gravity = Gravity.BOTTOM; params.width = DateUtils.getScreenWidth(getContext()); getWindow().setAttributes(params); } @Override public void onChanged(Date date) { if (onChangeLisener != null) { onChangeLisener.onChanged(date); } if (!TextUtils.isEmpty(format)) { String messge = ""; try { messge = new SimpleDateFormat(format).format(date); } catch (Exception e) { e.printStackTrace(); } messgeTv.setText(messge); } } }
[ "15112360329@163.com" ]
15112360329@163.com
50ad51d31a8ad6526075aa47ca8f0c4bd64749b8
a7397709e9ff6eca5a8117b4479bcc64a4e41d4b
/components/visual-panels/core/src/java/util/com/oracle/solaris/vp/util/misc/AggregatingLoader.java
2dd160f53bd1aea35e42bd257f9cfc88f67d3ccb
[]
no_license
alhazred/userland
6fbd28d281c08cf76f59e41e1331fe49fea6bcf2
72ea01e9a0ea237c9a960b3533273dc0afe06ff2
refs/heads/master
2020-05-17T10:17:16.836583
2013-03-04T07:36:23
2013-03-04T07:36:23
8,550,473
2
0
null
null
null
null
UTF-8
Java
false
false
1,466
java
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved. */ package com.oracle.solaris.vp.util.misc; import java.io.File; import java.net.*; import java.util.*; public class AggregatingLoader extends URLClassLoader { private Set<URL> jars = new HashSet<URL>(); public AggregatingLoader(ClassLoader parent) { super(new URL[0], parent); } public void addJar(String path) { File f = new File(path); if (!f.exists()) return; URL url; try { url = f.toURI().toURL(); } catch (MalformedURLException e) { return; } if (jars.contains(url)) return; jars.add(url); addURL(url); } }
[ "a.eremin@nexenta.com" ]
a.eremin@nexenta.com
461100e66daec5b2d647eed62408e37c91cee533
107f5b5b5e50051209d29f7587a434c1ab57497e
/app/src/main/java/abdullah/elamien/worldwide/rest/ApiUtils.java
6e176567cad8424db6731e67c559165504e8cd49
[]
no_license
mars-amn/WorldWide
1cd3a32f781707dc66a10aa194e9408288f6dbab
964413218c3c0678b8e0c9d5f4aae88bdeaccf49
refs/heads/master
2021-09-25T07:31:17.908666
2018-10-19T16:46:45
2018-10-19T16:46:45
null
0
0
null
null
null
null
UTF-8
Java
false
false
329
java
package abdullah.elamien.worldwide.rest; /** * Created by AbdullahAtta on 10/17/2018. */ public class ApiUtils { private static final String BASE_URL = "https://api.printful.com/"; public static CountriesAPI getCountriesService() { return RestClient.getsRetrofit(BASE_URL).create(CountriesAPI.class); } }
[ "33333259+AbduallahAtta@users.noreply.github.com" ]
33333259+AbduallahAtta@users.noreply.github.com
c725e43d62101f161627578ea2e8c7e0304c8a04
59a9cd69f94e313174c70c955ac60cc78545380f
/src/main/java/com/thzhima/mvcblog/dao/BlogDAO.java
4e2952efa9fb871ea48801030d278764830cee97
[]
no_license
zhufengku/mvcblog
482e99f0127cf0ff9a86ba947cfd9277bf252150
fff892839248c60836e45ac28436cd27fb48ad37
refs/heads/master
2022-12-26T07:47:13.738677
2019-12-08T08:49:36
2019-12-08T08:49:36
226,639,846
0
0
null
2022-12-15T23:25:20
2019-12-08T08:57:44
Java
UTF-8
Java
false
false
1,481
java
package com.thzhima.mvcblog.dao; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.stereotype.Repository; import com.thzhima.mvcblog.beans.Blog; @Repository public class BlogDAO { @Autowired private JdbcTemplate tmp; public Blog selectOne(String sql,ResultSetExtractor<Blog> ext, Object...args) { return tmp.query(sql, ext, args); } public Blog findByUserID(int userID) { String sql = "select * from t_blogs where user_id=?"; ResultSetExtractor<Blog> ext = new ResultSetExtractor<Blog>() { @Override public Blog extractData(ResultSet rs) throws SQLException, DataAccessException { Blog b = null; if(rs.next()) { Integer blogID = rs.getInt(1); Integer userID = rs.getInt(2); String blogName = rs.getString(3); String photo = rs.getString(4); b = new Blog(blogID, userID, blogName, photo); } return b; } }; return this.selectOne(sql, ext, userID); } public int add(int userID, String blogName, String photoName) { String sql = "insert into t_blogs(blog_id, user_id,blog_name,photo)" + "values(seq_blogs.nextval,?,?,?)"; return this.tmp.update(sql, userID, blogName, photoName); } }
[ "zf18452624376@163.com" ]
zf18452624376@163.com
18b1e0059e13ed0387a38ca619148f9afe95ec90
cba543b732a9a5ad73ddb2e9b20125159f0e1b2e
/sikuli/API/src/main/java/org/sikuli/script/RunTime.java
ea5c7eb18790d5bbd272ded29638d85369586764
[]
no_license
wsh231314/IntelligentOperation
e6266e1ae79fe93f132d8900ee484a4db0da3b24
a12aca5c5c67e6a2dddcd2d8420ca8a64af476f2
refs/heads/master
2020-04-05T13:31:55.376669
2017-07-28T05:59:05
2017-07-28T05:59:05
94,863,918
1
2
null
2017-07-27T02:44:17
2017-06-20T07:45:10
Java
UTF-8
Java
false
false
97,664
java
/* * Copyright (c) 2010-2016, Sikuli.org, sikulix.com * Released under the MIT License. * */ package org.sikuli.script; import edu.unh.iol.dlc.VNCScreen; import org.sikuli.basics.Debug; import org.sikuli.basics.FileManager; import org.sikuli.basics.Settings; import org.sikuli.util.JythonHelper; import org.sikuli.util.LinuxSupport; import org.sikuli.util.SysJNA; import java.awt.*; import java.io.*; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.security.CodeSource; import java.util.*; import java.util.List; import java.util.prefs.Preferences; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** * INTERNAL USE --- NOT official API<br> * not as is in version 2 * * Intended to concentrate all, that is needed at startup of sikulix or sikulixapi and may be at runtime by SikuliX or * any caller */ public class RunTime { public static File scriptProject = null; public static URL uScriptProject = null; public static boolean shouldRunServer = false; private static boolean isTerminating = false; public static void resetProject() { scriptProject = null; uScriptProject = null; } public static String appDataMsg = ""; public static void pause(int time) { try { Thread.sleep(time * 1000); } catch (InterruptedException ex) { } } public static void pause(float time) { try { Thread.sleep((int) (time * 1000)); } catch (InterruptedException ex) { } } protected void abortScripting(String msg1, String msg2) { Thread current = Thread.currentThread(); String where = "unknown"; if (Region.runTime.isJythonReady) { where = JythonHelper.get().getCurrentLine(); } log(-1, msg1 + " %s", where); log(-1, msg2); current.interrupt(); current.stop(); } //<editor-fold defaultstate="collapsed" desc="logging"> private final String me = "RunTime%s: "; private int lvl = 3; private int minLvl = lvl; private static String preLogMessages = ""; public final static String runCmdError = "*****error*****"; public static String NL = "\n"; public boolean runningInteractive = false; public boolean runningTests = false; public String interactiveRunner; public File fLibsProvided; public File fLibsLocal; public boolean useLibsProvided = false; private String lastResult = ""; public boolean shouldCleanDownloads = false; public boolean isJythonReady = false; private boolean shouldExport = false; private void log(int level, String message, Object... args) { Debug.logx(level, String.format(me, runType) + message, args); } private void logp(String message, Object... args) { Debug.logx(-3, message, args); } private void logp(int level, String message, Object... args) { if (level <= Debug.getDebugLevel()) { logp(message, args); } } public void terminate(int retval, String message, Object... args) { log(-1, " *** terminating: " + message, args); System.exit(retval); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="instance"> /** * INTERNAL USE */ private RunTime() { } public static synchronized RunTime get(Type typ) { return get(typ, null); } /** * INTERNAL USE to initialize the runtime environment for SikuliX<br> * for public use: use RunTime.get() to get the existing instance * * @param typ IDE or API * @return the RunTime singleton instance */ public static synchronized RunTime get(Type typ, String[] clArgs) { if (runTime == null) { runTime = new RunTime(); int debugLevel = 0; if (null != clArgs) { debugLevel = checkArgs(clArgs, typ); if (Type.IDE.equals(typ)) { if (debugLevel == -1) { Debug.on(3); Debug.log(3, "RunTime: option -d detected --- log goes to SikulixLog.txt"); Debug.setLogFile(""); Settings.LogTime = true; System.setProperty("sikuli.console", "false"); } else if (debugLevel == 999) { runTime.runningScripts = true; } else if (debugLevel == -3) { //if (Type.IDE.equals(typ) && "runserver".equals(opt)) { shouldRunServer = true; } } } if (Type.API.equals(typ)) { Debug.init(); } //<editor-fold defaultstate="collapsed" desc="versions"> String vJava = System.getProperty("java.runtime.version"); String vVM = System.getProperty("java.vm.version"); String vClass = System.getProperty("java.class.version"); String vSysArch = System.getProperty("sikuli.arch"); if (null == vSysArch) { vSysArch = System.getProperty("os.arch"); } else { runTime.log(runTime.lvl, "SystemProperty given: sikuli.arch=%s", vSysArch); } if (vSysArch != null) { if (vSysArch.contains("64")) { runTime.javaArch = 64; } } else { runTime.log(runTime.lvl, "Java arch (32 or 64 Bit) not detected nor given - using %d Bit", runTime.javaArch); } try { runTime.javaVersion = Integer.parseInt(vJava.substring(2, 3)); runTime.javaShow = String.format("java %d-%d version %s vm %s class %s arch %s", runTime.javaVersion, runTime.javaArch, vJava, vVM, vClass, vSysArch); } catch (Exception ex) { runTime.log(-1, "Java version not detected (using 7): %s", vJava); runTime.javaVersion = 7; runTime.javaShow = String.format("java ?7?-%d version %s vm %s class %s arch %s", runTime.javaArch, vJava, vVM, vClass, vSysArch); runTime.logp(runTime.javaShow); runTime.dumpSysProps(); } if (Debug.getDebugLevel() > runTime.minLvl) { runTime.dumpSysProps(); } if (!runTime.isJava7()) { runTime.terminate(-1, "Java version must be 1.7 or later!"); } runTime.osVersion = runTime.osVersionSysProp; String os = runTime.osNameSysProp.toLowerCase(); if (os.startsWith("windows")) { runTime.runningOn = theSystem.WIN; runTime.sysName = "windows"; runTime.osName = "Windows"; runTime.runningWindows = true; runTime.NL = "\r\n"; } else if (os.startsWith("mac")) { runTime.runningOn = theSystem.MAC; runTime.sysName = "mac"; runTime.osName = "Mac OSX"; runTime.runningMac = true; } else if (os.startsWith("linux")) { runTime.runningOn = theSystem.LUX; runTime.sysName = "linux"; runTime.osName = "Linux"; runTime.runningLinux = true; String result = runTime.runcmd("lsb_release -i -r -s"); if (result.contains("*** error ***")) { runTime.log(-1, "command returns error: lsb_release -i -r -s\n%s", result); } else { runTime.linuxDistro = result.replaceAll("\n", " ").trim(); } } else { // Presume Unix -- pretend to be Linux runTime.runningOn = theSystem.LUX; runTime.sysName = os; runTime.osName = runTime.osNameSysProp; runTime.runningLinux = true; runTime.linuxDistro = runTime.osNameSysProp; } runTime.fpJarLibs += runTime.sysName + "/libs" + runTime.javaArch; runTime.fpSysLibs = runTime.fpJarLibs.substring(1); String aFolder = System.getProperty("user.home"); if (aFolder == null || aFolder.isEmpty() || !(runTime.fUserDir = new File(aFolder)).exists()) { runTime.terminate(-1, "JavaSystemProperty::user.home not valid"); } aFolder = System.getProperty("user.dir"); if (aFolder == null || aFolder.isEmpty() || !(runTime.fWorkDir = new File(aFolder)).exists()) { runTime.terminate(-1, "JavaSystemProperty::user.dir not valid"); } runTime.fSikulixAppPath = new File("SikulixAppDataNotAvailable"); if (runTime.runningWindows) { appDataMsg = "init: Windows: %APPDATA% not valid (null or empty) or is not accessible:\n%s"; String tmpdir = System.getenv("APPDATA"); if (tmpdir != null && !tmpdir.isEmpty()) { runTime.fAppPath = new File(tmpdir); runTime.fSikulixAppPath = new File(runTime.fAppPath, "Sikulix"); } } else if (runTime.runningMac) { appDataMsg = "init: Mac: SikulxAppData does not exist or is not accessible:\n%s"; runTime.fAppPath = new File(runTime.fUserDir, "Library/Application Support"); runTime.fSikulixAppPath = new File(runTime.fAppPath, "Sikulix"); } else if (runTime.runningLinux) { runTime.fAppPath = runTime.fUserDir; runTime.fSikulixAppPath = new File(runTime.fAppPath, ".Sikulix"); appDataMsg = "init: Linux: SikulxAppData does not exist or is not accessible:\n%s"; } runTime.fSikulixStore = new File(runTime.fSikulixAppPath, "SikulixStore"); runTime.fSikulixStore.mkdirs(); //</editor-fold> debugLevelSaved = Debug.getDebugLevel(); debugLogfileSaved = Debug.logfile; File fDebug = new File(runTime.fSikulixStore, "SikulixDebug.txt"); if (fDebug.exists()) { if (Debug.getDebugLevel() == 0) { Debug.setDebugLevel(3); } Debug.setLogFile(fDebug.getAbsolutePath()); if (Type.IDE.equals(typ)) { System.setProperty("sikuli.console", "false"); } runTime.logp("auto-debugging with level %d into:\n%s", Debug.getDebugLevel(), fDebug); } runTime.fTestFolder = new File(runTime.fUserDir, "SikulixTest"); runTime.fTestFile = new File(runTime.fTestFolder, "SikulixTest.txt"); runTime.loadOptions(typ); int dl = runTime.getOptionNumber("Debug.level"); if (dl > 0 && Debug.getDebugLevel() < 2) { Debug.setDebugLevel(dl); } if (Debug.getDebugLevel() == 2) { runTime.dumpOptions(); } if (Type.SETUP.equals(typ) && debugLevel != -2) { Debug.setDebugLevel(3); } Settings.init(); // force Settings initialization runTime.initSikulixOptions(); runTime.init(typ); if (Type.IDE.equals(typ)) { runTime.initIDEbefore(); runTime.initAPI(); runTime.initIDEafter(); } else { runTime.initAPI(); if (Type.SETUP.equals(typ)) { runTime.initSetup(); } } } if (testingWinApp && !runTime.runningWindows) { runTime.terminate(1, "***** for testing winapp: not running on Windows"); } return runTime; } /** * get the initialized RunTime singleton instance * * @return */ public static synchronized RunTime get() { if (runTime == null) { return get(Type.API); } return runTime; } /** * INTERNAL USE get a new initialized RunTime singleton instance * * @return */ public static synchronized RunTime reset(Type typ) { if (runTime != null) { preLogMessages += "RunTime: resetting RunTime instance;"; if (Sikulix.testNumber == 1) { Debug.setDebugLevel(debugLevelSaved); } Debug.setLogFile(debugLogfileSaved); runTime = null; } return get(typ); } /** * INTERNAL USE get a new initialized RunTime singleton instance * * @return */ public static synchronized RunTime reset() { return reset(Type.API); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="variables"> public enum Type { IDE, API, SETUP, INIT } private enum theSystem { WIN, MAC, LUX, FOO } private static RunTime runTime = null; private static int debugLevelSaved; private static String debugLogfileSaved; public static boolean testing = false; public static boolean testingWinApp = false; public Type runType = Type.INIT; public String sxBuild = ""; public String sxBuildStamp = ""; public String jreVersion = java.lang.System.getProperty("java.runtime.version"); public Preferences optionsIDE = null; public ClassLoader classLoader = RunTime.class.getClassLoader(); public String baseJar = ""; public String userName = ""; public String fpBaseTempPath = ""; private Class clsRef = RunTime.class; private Class clsRefBase = clsRef; private List<URL> classPath = new ArrayList<URL>(); public File fTempPath = null; public File fBaseTempPath = null; public File fLibsFolder = null; public String fpJarLibs = "/sikulixlibs/"; public String fpSysLibs = null; boolean areLibsExported = false; private Map<String, Boolean> libsLoaded = new HashMap<String, Boolean>(); public File fUserDir = null; public File fWorkDir = null; public File fTestFolder = null; public File fTestFile = null; public File fAppPath = null; public File fSikulixAppPath = null; public File fSikulixExtensions = null; public String[] standardExtensions = new String[]{"selenium4sikulix"}; public File fSikulixLib = null; public File fSikulixStore; public File fSikulixDownloadsGeneric = null; public File fSikulixDownloadsBuild = null; public File fSikulixSetup; private File fOptions = null; private Properties options = null; private String fnOptions = "SikulixOptions.txt"; private String fnPrefs = "SikulixPreferences.txt"; public File fSxBase = null; public File fSxBaseJar = null; public File fSxProject = null; public File fSxProjectTestScriptsJS = null; public File fSxProjectTestScripts = null; public String fpContent = "sikulixcontent"; public boolean runningJar = true; public boolean runningInProject = false; public boolean runningWindows = false; public boolean runningMac = false; public boolean runningLinux = false; public boolean runningWinApp = false; public boolean runningMacApp = false; private theSystem runningOn = theSystem.FOO; private final String osNameSysProp = System.getProperty("os.name"); private final String osVersionSysProp = System.getProperty("os.version"); public String javaShow = "not-set"; public int javaArch = 32; public int javaVersion = 0; public String javahome = FileManager.slashify(System.getProperty("java.home"), false); public String osName = "NotKnown"; public String sysName = "NotKnown"; public String osVersion = ""; private String appType = null; public int debuglevelAPI = -1; private boolean runningScripts = false; public String linuxDistro = "???LINUX???"; public String linuxNeededLibs = ""; //</editor-fold> GraphicsEnvironment genv = null; GraphicsDevice[] gdevs; public Rectangle[] monitorBounds = null; Rectangle rAllMonitors; int mainMonitor = -1; int nMonitors = 0; Point pNull = new Point(0, 0); //<editor-fold defaultstate="collapsed" desc="global init"> private void init(Type typ) { //<editor-fold defaultstate="collapsed" desc="general"> if ("winapp".equals(getOption("testing"))) { log(lvl, "***** for testing: simulating WinApp"); testingWinApp = true; } for (String line : preLogMessages.split(";")) { if (!line.isEmpty()) { log(lvl, line); } } log(lvl, "global init: entering as: %s", typ); sxBuild = SikuliVersionBuild; sxBuildStamp = sxBuild.replace("_", "").replace("-", "").replace(":", "").substring(0, 12); if (System.getProperty("user.name") != null) { userName = System.getProperty("user.name"); } if (userName.isEmpty()) { userName = "unknown"; } String tmpdir = System.getProperty("java.io.tmpdir"); if (tmpdir != null && !tmpdir.isEmpty()) { fTempPath = new File(tmpdir); } else { terminate(1, "init: java.io.tmpdir not valid (null or empty"); } fBaseTempPath = new File(fTempPath, String.format("Sikulix_%d", FileManager.getRandomInt())); fpBaseTempPath = fBaseTempPath.getAbsolutePath(); fBaseTempPath.mkdirs(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { isTerminating = true; log(lvl, "final cleanup"); if (isRunning != null) { try { isRunningFile.close(); } catch (IOException ex) { } isRunning.delete(); } VNCScreen.cleanUp(); if (shouldCleanDownloads) { FileManager.deleteFileOrFolder(fSikulixDownloadsBuild); } for (File f : fTempPath.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { File aFile = new File(dir, name); boolean isObsolete = false; long lastTime = aFile.lastModified(); if (lastTime == 0) { return false; } if (lastTime < ((new Date().getTime()) - 7 * 24 * 60 * 60 * 1000)) { isObsolete = true; } if (name.contains("BridJExtractedLibraries") && isObsolete) { return true; } if (name.toLowerCase().contains("sikuli")) { if (name.contains("Sikulix_")) { if (isObsolete || aFile.equals(fBaseTempPath)) { return true; } } else { return true; } } return false; } })) { Debug.log(4, "cleanTemp: " + f.getName()); FileManager.deleteFileOrFolder(f.getAbsolutePath()); } } }); if (Type.IDE.equals(typ) && !runningScripts) { isRunning = new File(fTempPath, isRunningFilename); boolean shouldTerminate = false; try { isRunning.createNewFile(); isRunningFile = new FileOutputStream(isRunning); if (null == isRunningFile.getChannel().tryLock()) { Sikulix.popError("Terminating: IDE already running"); shouldTerminate = true; } } catch (Exception ex) { Sikulix.popError("Terminating on FatalError: cannot access IDE lock for/n" + isRunning); shouldTerminate = true; } if (shouldTerminate) { System.exit(1); } } for (String aFile : fTempPath.list()) { if ((aFile.startsWith("Sikulix") && (new File(aFile).isFile())) || (aFile.startsWith("jffi") && aFile.endsWith(".tmp"))) { FileManager.deleteFileOrFolder(new File(fTempPath, aFile)); } } try { if (!fSikulixAppPath.exists()) { fSikulixAppPath.mkdirs(); } if (!fSikulixAppPath.exists()) { terminate(1, appDataMsg, fSikulixAppPath); } fSikulixExtensions = new File(fSikulixAppPath, "Extensions"); fSikulixLib = new File(fSikulixAppPath, "Lib"); fSikulixDownloadsGeneric = new File(fSikulixAppPath, "SikulixDownloads"); fSikulixSetup = new File(fSikulixAppPath, "SikulixSetup"); fLibsProvided = new File(fSikulixAppPath, fpSysLibs); fLibsLocal = fLibsProvided.getParentFile().getParentFile(); fSikulixExtensions.mkdir(); fSikulixDownloadsGeneric.mkdir(); } catch (Exception ex) { terminate(1, appDataMsg + "\n" + ex.toString(), fSikulixAppPath); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="monitors"> if (!isHeadless()) { genv = GraphicsEnvironment.getLocalGraphicsEnvironment(); gdevs = genv.getScreenDevices(); nMonitors = gdevs.length; if (nMonitors == 0) { terminate(1, "GraphicsEnvironment has no ScreenDevices"); } monitorBounds = new Rectangle[nMonitors]; rAllMonitors = null; Rectangle currentBounds; for (int i = 0; i < nMonitors; i++) { currentBounds = gdevs[i].getDefaultConfiguration().getBounds(); if (null != rAllMonitors) { rAllMonitors = rAllMonitors.union(currentBounds); } else { rAllMonitors = currentBounds; } if (currentBounds.contains(pNull)) { if (mainMonitor < 0) { mainMonitor = i; log(lvl, "ScreenDevice %d has (0,0) --- will be primary Screen(0)", i); } else { log(lvl, "ScreenDevice %d too contains (0,0)!", i); } } log(lvl, "Monitor %d: (%d, %d) %d x %d", i, currentBounds.x, currentBounds.y, currentBounds.width, currentBounds.height); monitorBounds[i] = currentBounds; } if (mainMonitor < 0) { log(lvl, "No ScreenDevice has (0,0) --- using 0 as primary: %s", monitorBounds[0]); mainMonitor = 0; } } else { log(lvl, "running in headless environment"); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="classpath"> try { if (Type.IDE.equals(typ)) { clsRef = Class.forName("org.sikuli.ide.SikuliIDE"); } else if (Type.SETUP.equals(typ)) { clsRef = Class.forName("org.sikuli.setup.RunSetup"); } } catch (Exception ex) { } CodeSource codeSrc = clsRef.getProtectionDomain().getCodeSource(); String base = null; if (codeSrc != null && codeSrc.getLocation() != null) { base = FileManager.slashify(codeSrc.getLocation().getPath(), false); } appType = "from a jar"; if (base != null) { fSxBaseJar = new File(base); String jn = fSxBaseJar.getName(); fSxBase = fSxBaseJar.getParentFile(); log(lvl, "runs as %s in: %s", jn, fSxBase.getAbsolutePath()); if (jn.contains("classes")) { runningJar = false; fSxProject = fSxBase.getParentFile().getParentFile(); log(lvl, "not jar - supposing Maven project: %s", fSxProject); appType = "in Maven project from classes"; runningInProject = true; } else if ("target".equals(fSxBase.getName())) { fSxProject = fSxBase.getParentFile().getParentFile(); log(lvl, "folder target detected - supposing Maven project: %s", fSxProject); appType = "in Maven project from some jar"; runningInProject = true; } else { if (runningWindows) { if (jn.endsWith(".exe")) { runningWinApp = true; runningJar = false; appType = "as application .exe"; } } else if (runningMac) { if (fSxBase.getAbsolutePath().contains("SikuliX.app/Content")) { runningMacApp = true; appType = "as application .app"; if (!fSxBase.getAbsolutePath().startsWith("/Applications")) { appType += " (not from /Applications folder)"; } } } } } else { terminate(1, "no valid Java context for SikuliX available " + "(java.security.CodeSource.getLocation() is null)"); } if (runningInProject) { fSxProjectTestScriptsJS = new File(fSxProject, "StuffContainer/testScripts/testJavaScript"); fSxProjectTestScripts = new File(fSxProject, "StuffContainer/testScripts"); } List<String> items = new ArrayList<String>(); if (Type.API.equals(typ)) { String optJython = getOption("jython"); if (!optJython.isEmpty()) { items.add(optJython); } } if (!Type.SETUP.equals(typ)) { String optClasspath = getOption("classpath"); if (!optClasspath.isEmpty()) { items.addAll(Arrays.asList(optClasspath.split(System.getProperty("path.separator")))); } items.addAll(Arrays.asList(standardExtensions)); if (items.size() > 0) { String[] fList = fSikulixExtensions.list(); for (String item : items) { item = item.trim(); if (new File(item).isAbsolute()) { addToClasspath(item); } else { for (String fpFile : fList) { File fFile = new File(fSikulixExtensions, fpFile); if (fFile.length() > 0) { if (fpFile.startsWith(item)) { addToClasspath(fFile.getAbsolutePath()); break; } } else { fFile.delete(); } } } } } } //</editor-fold> if (runningWinApp || testingWinApp) { runTime.fpJarLibs += "windows"; runTime.fpSysLibs = runTime.fpJarLibs.substring(1) + "/libs" + runTime.javaArch; } if (!Type.SETUP.equals(typ)) { libsExport(typ); } else { fSikulixDownloadsBuild = new File(fSikulixAppPath, "SikulixDownloads_" + sxBuildStamp); String[] fpList = fSikulixAppPath.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (name.contains("SikulixDownloads_")) { if (name.contains(sxBuildStamp)) { return false; } return true; } return false; } }); if (fpList.length > 0) { log(lvl, "deleting versioned downloads folder in AppPath (%s)", fSikulixDownloadsBuild.getName()); for (String entry : fpList) { //new File(fSikulixAppPath, entry).renameTo(fSikulixDownloadsBuild); FileManager.deleteFileOrFolder(new File(fSikulixAppPath, entry)); } } } runType = typ; if (Debug.getDebugLevel() == minLvl) { show(); } log(lvl, "global init: leaving"); } class LibsFilter implements FilenameFilter { String sAccept = ""; public LibsFilter(String toAccept) { sAccept = toAccept; } @Override public boolean accept(File dir, String name) { if (dir.getPath().contains(sAccept)) { return true; } return false; } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="libs export"> public void makeFolders() { fLibsFolder = new File(fSikulixAppPath, "SikulixLibs_" + sxBuildStamp); if (testing) { logp("***** for testing: delete folders SikulixLibs/ and Lib/"); FileManager.deleteFileOrFolder(fLibsFolder); FileManager.deleteFileOrFolder(fSikulixLib); } if (!fLibsFolder.exists()) { fLibsFolder.mkdirs(); if (!fLibsFolder.exists()) { terminate(1, "libs folder not available: " + fLibsFolder.toString()); } log(lvl, "new libs folder at: %s", fLibsFolder); } else { log(lvl, "exists libs folder at: %s", fLibsFolder); } String[] fpList = fTempPath.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (name.contains("SikulixLibs")) { return true; } return false; } }); if (fpList.length > 0) { log(lvl, "deleting obsolete libs folders in Temp"); for (String entry : fpList) { if (entry.endsWith(sxBuildStamp)) { continue; } FileManager.deleteFileOrFolder(new File(fTempPath, entry)); } } fpList = fSikulixAppPath.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (name.contains("SikulixLibs")) { return true; } return false; } }); if (fpList.length > 1) { log(lvl, "deleting obsolete libs folders in AppPath"); for (String entry : fpList) { if (entry.endsWith(sxBuildStamp)) { continue; } FileManager.deleteFileOrFolder(new File(fSikulixAppPath, entry)); } } } private boolean libsLoad(String libName) { if (!areLibsExported) { libsExport(runType); } if (!areLibsExported) { terminate(1, "loadLib: deferred exporting of libs did not work"); } if (runningWindows) { libName += ".dll"; } else if (runningMac) { libName = "lib" + libName + ".dylib"; } else if (runningLinux) { libName = "lib" + libName + ".so"; } File fLib = new File(fLibsFolder, libName); Boolean vLib = libsLoaded.get(libName); if (vLib == null || !fLib.exists()) { terminate(1, String.format("loadlib: %s not available in %s", libName, fLibsFolder)); } String msg = "loadLib: %s"; int level = lvl; if (vLib) { level++; msg += " already loaded"; } if (vLib) { log(level, msg, libName); return true; } boolean shouldTerminate = false; Error loadError = null; while (!shouldTerminate) { shouldTerminate = true; loadError = null; try { System.load(new File(fLibsFolder, libName).getAbsolutePath()); } catch (Error e) { loadError = e; if (runningLinux) { log(-1, msg + " not usable: \n%s", libName, loadError); shouldTerminate = !LinuxSupport.checkAllLibs(); } } } if (loadError != null) { log(-1, "Problematic lib: %s (...TEMP...)", fLib); log(-1, "%s loaded, but it might be a problem with needed dependent libraries\nERROR: %s", libName, loadError.getMessage().replace(fLib.getAbsolutePath(), "...TEMP...")); if (Settings.runningSetup) { return false; } else { terminate(1, "problem with native library: " + libName); } } libsLoaded.put(libName, true); log(level, msg, libName); return true; } private boolean libsCheck(File flibsFolder) { // 1.1-MadeForSikuliX64M.txt String name = String.format("1.1-MadeForSikuliX%d%s.txt", javaArch, runningOn.toString().substring(0, 1)); if (!new File(flibsFolder, name).exists()) { log(lvl, "libs folder empty or has wrong content"); return false; } return true; } private void libsExport(Type typ) { shouldExport = false; makeFolders(); URL uLibsFrom = null; if (!libsCheck(fLibsFolder)) { FileManager.deleteFileOrFolder(fLibsFolder); fLibsFolder.mkdirs(); shouldExport = true; if (!fLibsFolder.exists()) { terminate(1, "libs folder not available: " + fLibsFolder.toString()); } } if (shouldExport) { String sysShort = "win"; boolean shouldAddLibsJar = false; if (!runningWinApp && !testingWinApp) { sysShort = runningOn.toString().toLowerCase(); } String fpLibsFrom = ""; if (runningJar) { fpLibsFrom = fSxBaseJar.getAbsolutePath(); if (fpLibsFrom.contains("forsetup")) { shouldAddLibsJar = true; } } else { String fSrcFolder = typ.toString(); if (Type.SETUP.toString().equals(fSrcFolder)) { fSrcFolder = "Setup"; } fpLibsFrom = fSxBaseJar.getPath().replace(fSrcFolder, "Libs" + sysShort) + "/"; } if (testing && !runningJar) { if (testingWinApp || testSwitch()) { logp("***** for testing: exporting from classes"); } else { logp("***** for testing: exporting from jar"); shouldAddLibsJar = true; } } if (!shouldAddLibsJar && (null != isJarOnClasspath("sikulix.jar") || null != isJarOnClasspath("sikulixapi.jar"))) { shouldAddLibsJar = false; fpLibsFrom = ""; } if (shouldAddLibsJar) { fpLibsFrom = new File(fSxProject, String.format("Libs%s/target/sikulixlibs%s-1.1.1.jar", sysShort, sysShort)).getAbsolutePath(); } log(lvl, "now exporting libs"); if (!fpLibsFrom.isEmpty()) { addToClasspath(fpLibsFrom); } uLibsFrom = clsRef.getResource(fpJarLibs); if (testing || uLibsFrom == null) { dumpClassPath(); } if (uLibsFrom == null) { terminate(1, "libs to export not found on above classpath: " + fpJarLibs); } log(lvl, "libs to export are at:\n%s", uLibsFrom); if (runningWinApp || testingWinApp) { String libsAccepted = "libs" + javaArch; extractResourcesToFolder(fpJarLibs, fLibsFolder, new LibsFilter(libsAccepted)); File fCurrentLibs = new File(fLibsFolder, libsAccepted); if (FileManager.xcopy(fCurrentLibs, fLibsFolder)) { FileManager.deleteFileOrFolder(fCurrentLibs); } else { terminate(1, "could not create libs folder for Windows --- see log"); } } else { extractResourcesToFolder(fpJarLibs, fLibsFolder, null); } } for (String aFile : fLibsFolder.list()) { libsLoaded.put(aFile, false); } if (useLibsProvided) { log(lvl, "Linux: requested to use provided libs - copying"); LinuxSupport.copyProvidedLibs(fLibsFolder); } if (runningWindows) { addToWindowsSystemPath(fLibsFolder); if (!checkJavaUsrPath(fLibsFolder)) { log(-1, "Problems setting up on Windows - see errors - might not work and crash later"); } String lib = "jawt.dll"; File fJawtDll = new File(fLibsFolder, lib); FileManager.deleteFileOrFolder(fJawtDll); FileManager.xcopy(new File(javahome + "/bin/" + lib), fJawtDll); if (!fJawtDll.exists()) { terminate(1, "problem copying %s", fJawtDll); } } areLibsExported = true; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="native libs handling"> /** * INTERNAL USE: load a native library from the libs folder * * @param libname name of library without prefix/suffix/ending */ public static void loadLibrary(String libname) { if (isTerminating) { return; } RunTime.get().libsLoad(libname); } /** * INTERNAL USE: load a native library from the libs folder * * @param libname name of library without prefix/suffix/ending */ public static boolean loadLibrary(String libname, boolean useLibsProvided) { RunTime rt = RunTime.get(); rt.useLibsProvided = useLibsProvided; return rt.libsLoad(libname); } private void addToWindowsSystemPath(File fLibsFolder) { String syspath = SysJNA.WinKernel32.getEnvironmentVariable("PATH"); if (syspath == null) { terminate(1, "addToWindowsSystemPath: cannot access system path"); } else { String libsPath = (fLibsFolder.getAbsolutePath()).replaceAll("/", "\\"); if (!syspath.toUpperCase().contains(libsPath.toUpperCase())) { if (SysJNA.WinKernel32.setEnvironmentVariable("PATH", libsPath + ";" + syspath)) { syspath = SysJNA.WinKernel32.getEnvironmentVariable("PATH"); if (!syspath.toUpperCase().contains(libsPath.toUpperCase())) { log(-1, "addToWindowsSystemPath: adding to system path did not work:\n%s", syspath); terminate(1, "addToWindowsSystemPath: did not work - see error"); } } log(lvl, "addToWindowsSystemPath: added to systempath:\n%s", libsPath); } } } private boolean checkJavaUsrPath(File fLibsFolder) { String fpLibsFolder = fLibsFolder.getAbsolutePath(); Field usrPathsField = null; boolean contained = false; try { usrPathsField = ClassLoader.class.getDeclaredField("usr_paths"); } catch (NoSuchFieldException ex) { log(-1, "checkJavaUsrPath: get\n%s", ex); } catch (SecurityException ex) { log(-1, "checkJavaUsrPath: get\n%s", ex); } if (usrPathsField != null) { usrPathsField.setAccessible(true); try { //get array of paths String[] javapaths = (String[]) usrPathsField.get(null); //check if the path to add is already present for (String p : javapaths) { if (new File(p).equals(fLibsFolder)) { contained = true; break; } } //add the new path if (!contained) { final String[] newPaths = Arrays.copyOf(javapaths, javapaths.length + 1); newPaths[newPaths.length - 1] = fpLibsFolder; usrPathsField.set(null, newPaths); log(lvl, "checkJavaUsrPath: added to ClassLoader.usrPaths"); contained = true; } } catch (IllegalAccessException ex) { log(-1, "checkJavaUsrPath: set\n%s", ex); } catch (IllegalArgumentException ex) { log(-1, "checkJavaUsrPath: set\n%s", ex); } return contained; } return false; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="init for IDE"> File isRunning = null; FileOutputStream isRunningFile = null; String isRunningFilename = "s_i_k_u_l_i-ide-isrunning"; private void initIDEbefore() { log(lvl, "initIDEbefore: entering"); optionsIDE = Preferences.userNodeForPackage(Sikulix.class); if (jreVersion.startsWith("1.6")) { String jyversion = ""; Properties prop = new Properties(); String fp = "org/python/version.properties"; InputStream ifp = null; try { ifp = classLoader.getResourceAsStream(fp); if (ifp != null) { prop.load(ifp); ifp.close(); jyversion = prop.getProperty("jython.version"); } } catch (IOException ex) { } if (!jyversion.isEmpty() && !jyversion.startsWith("2.5")) { Sikulix.popError(String.format("The bundled Jython %s\n" + "cannot be used on Java 6!\n" + "Run setup again in this environment.\n" + "Click OK to terminate now", jyversion)); System.exit(1); } } Settings.isRunningIDE = true; if (runningMac) { System.setProperty("apple.laf.useScreenMenuBar", "true"); if (!runningMacApp && !runningInProject) { if (!Sikulix.popAsk("This use of SikuliX is not supported\n" + "and might lead to misbehavior!\n" + "Click YES to continue (you should be sure)\n" + "Click NO to terminate and check the situation.")) { System.exit(1); } } } log(lvl, "initIDEbefore: leaving"); } private void initIDEafter() { // log(lvl, "initIDEafter: entering"); // log(lvl, "initIDEafter: leaving"); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="init for API"> private void initAPI() { log(lvl, "initAPI: entering"); if (shouldExport || !fSikulixLib.exists() || !new File(fSikulixLib, "robot").exists() || !new File(fSikulixLib, "sikuli").exists()) { fSikulixLib.mkdir(); extractResourcesToFolder("Lib", fSikulixLib, null); } else { extractResourcesToFolder("Lib/sikuli", new File(fSikulixLib, "sikuli"), null); } log(lvl, "initAPI: leaving"); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="init for Setup"> private void initSetup() { // log(lvl, "initSetup: entering"); // log(lvl, "initSetup: leaving"); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="helpers"> /** * INTERNAL USE: to check whether we are running in compiled classes context * * @return true if the code source location is a folder ending with classes (Maven convention) */ public boolean isRunningFromJar() { return runningJar; } /** * @return return true if Java version > 7 */ public boolean isJava8() { return javaVersion > 7; } /** * @return return true if Java version > 6 */ public boolean isJava7() { return javaVersion > 6; } public boolean isOSX10() { return osVersion.startsWith("10.10.") || osVersion.startsWith("10.11.") || osVersion.startsWith("10.12."); } public boolean needsRobotFake() { return !Settings.ClickFast && runningMac && isOSX10(); } /** * print out some basic information about the current runtime environment */ public void show() { if (hasOptions()) { dumpOptions(); } logp("***** show environment for %s (build %s)", runType, sxBuildStamp); logp("user.home: %s", fUserDir); logp("user.dir (work dir): %s", fWorkDir); logp("user.name: %s", userName); logp("java.io.tmpdir: %s", fTempPath); logp("running %dBit on %s (%s) %s", javaArch, osName, (linuxDistro.contains("???") ? osVersion : linuxDistro), appType); logp(javaShow); logp("app data folder: %s", fSikulixAppPath); logp("libs folder: %s", fLibsFolder); if (runningJar) { logp("executing jar: %s", fSxBaseJar); } if (Debug.getDebugLevel() > minLvl - 1 || isJythonReady) { dumpClassPath("sikulix"); if (isJythonReady) { int saveLvl = Debug.getDebugLevel(); Debug.setDebugLevel(lvl); JythonHelper.get().showSysPath(); Screen.showMonitors(); Debug.setDebugLevel(saveLvl); } } logp("***** show environment end"); } public boolean testSwitch() { if (0 == (new Date().getTime() / 10000) % 2) { return true; } return false; } public String getVersionShortBasic() { return sversion.substring(0, 3); } public String getVersionShort() { if (SikuliVersionBetaN > 0 && SikuliVersionBetaN < 99) { return bversion; } else { return sversion; } } public String getSystemInfo() { return String.format("%s/%s/%s", SikuliVersionLong, SikuliSystemVersion, SikuliJavaVersion); } public boolean isVersionRelease() { return SikuliVersionType.isEmpty(); } public String getVersion() { return SikuliVersion; } public void getStatus() { System.out.println("***** System Information Dump *****"); System.out.println(String.format("*** SystemInfo\n%s", getSystemInfo())); System.getProperties().list(System.out); System.out.println("*** System Environment"); for (String key : System.getenv().keySet()) { System.out.println(String.format("%s = %s", key, System.getenv(key))); } System.out.println("*** Java Class Path"); URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); URL[] urls = sysLoader.getURLs(); for (int i = 0; i < urls.length; i++) { System.out.println(String.format("%d: %s", i, urls[i])); } System.out.println("***** System Information Dump ***** end *****"); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="internal options handling"> private void loadOptions(Type typ) { for (File aFile : new File[]{fWorkDir, fUserDir, fSikulixStore}) { log(lvl, "loadOptions: check: %s", aFile); fOptions = new File(aFile, fnOptions); if (fOptions.exists()) { break; } else { fOptions = null; } } if (fOptions != null) { options = new Properties(); try { InputStream is; is = new FileInputStream(fOptions); options.load(is); is.close(); } catch (Exception ex) { log(-1, "while checking Options file:\n%s", fOptions); fOptions = null; options = null; } testing = isOption("testing", false); if (testing) { Debug.setDebugLevel(3); } log(lvl, "found Options file at: %s", fOptions); } if (hasOptions()) { for (Object oKey : options.keySet()) { String sKey = (String) oKey; String[] parts = sKey.split("\\."); if (parts.length == 1) { continue; } String sClass = parts[0]; String sAttr = parts[1]; Class cClass = null; Field cField = null; Class ccField = null; if (sClass.contains("Settings")) { try { cClass = Class.forName("org.sikuli.basics.Settings"); cField = cClass.getField(sAttr); ccField = cField.getType(); if (ccField.getName() == "boolean") { cField.setBoolean(null, isOption(sKey)); } else if (ccField.getName() == "int") { cField.setInt(null, getOptionNumber(sKey)); } else if (ccField.getName() == "float") { cField.setInt(null, getOptionNumber(sKey)); } else if (ccField.getName() == "double") { cField.setInt(null, getOptionNumber(sKey)); } else if (ccField.getName() == "String") { cField.set(null, getOption(sKey)); } } catch (Exception ex) { log(-1, "loadOptions: not possible: %s = %s", sKey, options.getProperty(sKey)); } } } } } /** * CONVENIENCE: look into the option file if any (if no option file is found, the option is taken as not existing) * * @param pName the option key (case-sensitive) * @return true only if option exists and has yes or true (not case-sensitive), in all other cases false */ public boolean isOption(String pName) { return isOption(pName, false); } /** * CONVENIENCE: look into the option file if any (if no option file is found, the option is taken as not existing) * * @param pName the option key (case-sensitive) * @param bDefault the default to be returned if option absent or empty * @return true if option has yes or no, false for no or false (not case-sensitive) */ public boolean isOption(String pName, Boolean bDefault) { if (options == null) { return bDefault; } String pVal = options.getProperty(pName, bDefault.toString()).toLowerCase(); if (pVal.isEmpty()) { return bDefault; } else if (pVal.contains("yes") || pVal.contains("true") || pVal.contains("on")) { return true; } else if (pVal.contains("no") || pVal.contains("false") || pVal.contains("off")) { return false; } return true; } /** * look into the option file if any (if no option file is found, the option is taken as not existing) * * @param pName the option key (case-sensitive) * @return the associated value, empty string if absent */ public String getOption(String pName) { if (options == null) { return ""; } String pVal = options.getProperty(pName, ""); return pVal; } /** * look into the option file if any (if no option file is found, the option is taken as not existing)<br> * side-effect: if no options file is there, an options store will be created in memory<br> * in this case and when the option is absent or empty, the given default will be stored<br> * you might later save the options store to a file with storeOptions() * * @param pName the option key (case-sensitive) * @param sDefault the default to be returned if option absent or empty * @return the associated value, the default value if absent or empty */ public String getOption(String pName, String sDefault) { if (options == null) { options = new Properties(); options.setProperty(pName, sDefault); return sDefault; } String pVal = options.getProperty(pName, sDefault); if (pVal.isEmpty()) { options.setProperty(pName, sDefault); return sDefault; } return pVal; } /** * store an option key-value pair, overwrites existing value<br> * new option store is created if necessary and can later be saved to a file * * @param pName * @param sValue */ public void setOption(String pName, String sValue) { if (options == null) { options = new Properties(); } options.setProperty(pName, sValue); } /** * CONVENIENCE: look into the option file if any (if no option file is found, the option is taken as not existing)<br> * tries to convert the stored string value into an integer number (gives 0 if not possible)<br> * * @param pName the option key (case-sensitive) * @return the converted integer number, 0 if absent or not possible */ public int getOptionNumber(String pName) { if (options == null) { return 0; } String pVal = options.getProperty(pName, "0"); int nVal = 0; try { nVal = Integer.decode(pVal); } catch (Exception ex) { } return nVal; } /** * CONVENIENCE: look into the option file if any (if no option file is found, the option is taken as not existing)<br> * tries to convert the stored string value into an integer number (gives 0 if not possible)<br> * * @param pName the option key (case-sensitive) * @param nDefault the default to be returned if option absent, empty or not convertable * @return the converted integer number, default if absent, empty or not possible */ public int getOptionNumber(String pName, Integer nDefault) { if (options == null) { return nDefault; } String pVal = options.getProperty(pName, nDefault.toString()); int nVal = nDefault; try { nVal = Integer.decode(pVal); } catch (Exception ex) { } return nVal; } /** * all options and their values * * @return a map of key-value pairs containing the found options, empty if no options file found */ public Map<String, String> getOptions() { Map<String, String> mapOptions = new HashMap<String, String>(); if (options != null) { Enumeration<?> optionNames = options.propertyNames(); String optionName; while (optionNames.hasMoreElements()) { optionName = (String) optionNames.nextElement(); mapOptions.put(optionName, getOption(optionName)); } } return mapOptions; } /** * check whether options are defined * * @return true if at lest one option defined else false */ public boolean hasOptions() { return options != null && options.size() > 0; } /** * all options and their values written to sysout as key = value */ public void dumpOptions() { if (hasOptions()) { logp("*** options dump:\n%s", (fOptions == null ? "" : fOptions)); for (String sOpt : getOptions().keySet()) { logp("%s = %s", sOpt, getOption(sOpt)); } logp("*** options dump end"); } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Sikulix options handling"> public int SikuliVersionMajor; public int SikuliVersionMinor; public int SikuliVersionSub; public int SikuliVersionBetaN; public String SikuliProjectVersionUsed = ""; public String SikuliProjectVersion = ""; public String SikuliVersionBuild; public String SikuliVersionType; public String SikuliVersionTypeText; public String downloadBaseDirBase; public String downloadBaseDirWeb; public String downloadBaseDir; // used for download of production versions private final String dlProdLink = "https://launchpad.net/raiman/sikulix2013+/"; private final String dlProdLink1 = ".0"; private final String dlProdLink2 = "/+download/"; // used for download of development versions (nightly builds) private final String dlDevLink = "http://nightly.sikuli.de/"; public String SikuliRepo; public String SikuliLocalRepo = ""; public String[] ServerList = {}; private String sversion; private String bversion; public String SikuliVersionDefault; public String SikuliVersionBeta; public String SikuliVersionDefaultIDE; public String SikuliVersionBetaIDE; public String SikuliVersionDefaultScript; public String SikuliVersionBetaScript; public String SikuliVersion; public String SikuliVersionIDE; public String SikuliVersionScript; public String SikuliJythonVersion; public String SikuliJythonVersion25 = "2.5.4-rc1"; public String SikuliJythonMaven; public String SikuliJythonMaven25; public String SikuliJython; public String SikuliJython25; public String SikuliJRubyVersion; public String SikuliJRuby; public String SikuliJRubyMaven; public String dlMavenRelease = "https://repo1.maven.org/maven2/"; public String dlMavenSnapshot = "https://oss.sonatype.org/content/groups/public/"; public Map<String, String> tessData = new HashMap<String, String>(); //TODO needed ??? public final String libOpenCV = "libopencv_java248"; public String SikuliVersionLong; public String SikuliSystemVersion; public String SikuliJavaVersion; private void initSikulixOptions() { SikuliRepo = null; Properties prop = new Properties(); String svf = "sikulixversion.txt"; try { InputStream is; is = clsRef.getClassLoader().getResourceAsStream("Settings/" + svf); if (is == null) { terminate(1, "initSikulixOptions: not found on classpath: %s", "Settings/" + svf); } prop.load(is); is.close(); String svt = prop.getProperty("sikulixdev"); SikuliVersionMajor = Integer.decode(prop.getProperty("sikulixvmaj")); SikuliVersionMinor = Integer.decode(prop.getProperty("sikulixvmin")); SikuliVersionSub = Integer.decode(prop.getProperty("sikulixvsub")); SikuliVersionBetaN = Integer.decode(prop.getProperty("sikulixbeta")); String ssxbeta = ""; if (SikuliVersionBetaN > 0) { ssxbeta = String.format("-Beta%d", SikuliVersionBetaN); } SikuliVersionBuild = prop.getProperty("sikulixbuild"); log(lvl + 1, "%s version from %s: %d.%d.%d%s build: %s", svf, SikuliVersionMajor, SikuliVersionMinor, SikuliVersionSub, ssxbeta, SikuliVersionBuild, svt); sversion = String.format("%d.%d.%d", SikuliVersionMajor, SikuliVersionMinor, SikuliVersionSub); bversion = String.format("%d.%d.%d-Beta%d", SikuliVersionMajor, SikuliVersionMinor, SikuliVersionSub, SikuliVersionBetaN); SikuliVersionDefault = "SikuliX " + sversion; SikuliVersionBeta = "Sikuli " + bversion; SikuliVersionDefaultIDE = "SikulixIDE " + sversion; SikuliVersionBetaIDE = "SikulixIDE " + bversion; SikuliVersionDefaultScript = "SikulixScript " + sversion; SikuliVersionBetaScript = "SikulixScript " + bversion; if ("release".equals(svt)) { downloadBaseDirBase = dlProdLink; downloadBaseDirWeb = downloadBaseDirBase + getVersionShortBasic() + dlProdLink1; downloadBaseDir = downloadBaseDirWeb + dlProdLink2; SikuliVersionType = ""; SikuliVersionTypeText = ""; } else { downloadBaseDirBase = dlDevLink; downloadBaseDirWeb = dlDevLink; downloadBaseDir = dlDevLink; SikuliVersionTypeText = "nightly"; SikuliVersionBuild += SikuliVersionTypeText; SikuliVersionType = svt; } if (SikuliVersionBetaN > 0) { SikuliVersion = SikuliVersionBeta; SikuliVersionIDE = SikuliVersionBetaIDE; SikuliVersionScript = SikuliVersionBetaScript; SikuliVersionLong = bversion + "(" + SikuliVersionBuild + ")"; } else { SikuliVersion = SikuliVersionDefault; SikuliVersionIDE = SikuliVersionDefaultIDE; SikuliVersionScript = SikuliVersionDefaultScript; SikuliVersionLong = sversion + "(" + SikuliVersionBuild + ")"; } SikuliProjectVersionUsed = prop.getProperty("sikulixvused"); SikuliProjectVersion = prop.getProperty("sikulixvproject"); String osn = "UnKnown"; String os = System.getProperty("os.name").toLowerCase(); if (os.startsWith("mac")) { osn = "Mac"; } else if (os.startsWith("windows")) { osn = "Windows"; } else if (os.startsWith("linux")) { osn = "Linux"; } SikuliLocalRepo = FileManager.slashify(prop.getProperty("sikulixlocalrepo"), true); SikuliJythonVersion = prop.getProperty("sikulixvjython"); SikuliJythonMaven = "org/python/jython-standalone/" + SikuliJythonVersion + "/jython-standalone-" + SikuliJythonVersion + ".jar"; SikuliJythonMaven25 = "org/python/jython-standalone/" + SikuliJythonVersion25 + "/jython-standalone-" + SikuliJythonVersion25 + ".jar"; SikuliJython = SikuliLocalRepo + SikuliJythonMaven; SikuliJython25 = SikuliLocalRepo + SikuliJythonMaven25; SikuliJRubyVersion = prop.getProperty("sikulixvjruby"); SikuliJRubyMaven = "org/jruby/jruby-complete/" + SikuliJRubyVersion + "/jruby-complete-" + SikuliJRubyVersion + ".jar"; SikuliJRuby = SikuliLocalRepo + SikuliJRubyMaven; SikuliSystemVersion = osn + System.getProperty("os.version"); SikuliJavaVersion = "Java" + javaVersion + "(" + javaArch + ")" + jreVersion; //TODO this should be in RunSetup only //TODO debug version: where to do in sikulixapi.jar //TODO need a function: reveal all environment and system information // log(lvl, "%s version: downloading from %s", svt, downloadBaseDir); } catch (Exception e) { Debug.error("Settings: load version file %s did not work", svf); Sikulix.endError(999); } // tessData.put("eng", "http://tesseract-ocr.googlecode.com/files/tesseract-ocr-3.02.eng.tar.gz"); tessData.put("eng", "http://download.sikulix.com/tesseract-ocr-3.02.eng.tar.gz"); Env.setSikuliVersion(SikuliVersion); } //</editor-fold> //<editor-fold desc="user public options support"> private static String optThisComingFromFile = "thisOptions.comingFromWhatFile"; private static String optThisWhatIsANumber = "thisOptions.whatIsAnumber"; private static String whatIsANumber = "#"; private static boolean optIsNumber(Properties props, String pName) { String prefix = getOpt(props, pName, whatIsANumber); if (pName.contains(prefix)) { return true; } return false; } /** * load a properties file * * @param fpOptions path to a file containing options * @return the Properties store or null */ public Properties loadOpts(String fpOptions) { if (fpOptions == null) { log(-1, "loadOptions: (error: no file)"); return null; } File fOptions = new File(fpOptions); if (!fOptions.isFile()) { log(-1, "loadOptions: (error: not found) %s", fOptions); return null; } Properties pOptions = new Properties(); try { fpOptions = fOptions.getCanonicalPath(); InputStream is; is = new FileInputStream(fOptions); pOptions.load(is); is.close(); } catch (Exception ex) { log(-1, "loadOptions: %s (error %s)", fOptions, ex.getMessage()); return null; } log(lvl, "loadOptions: ok (%d): %s", pOptions.size(), fOptions.getName()); pOptions.setProperty(optThisComingFromFile, fpOptions); return pOptions; } public static Properties makeOpts() { return new Properties(); } /** * save a properties store to a file (prop: this.comingfrom = abs. filepath) * * @param pOptions the prop store * @return success */ public boolean saveOpts(Properties pOptions) { String fpOptions = pOptions.getProperty(optThisComingFromFile); if (null == fpOptions) { log(-1, "saveOptions: no prop %s", optThisComingFromFile); return false; } return saveOpts(pOptions, fpOptions); } /** * save a properties store to the given file * * @param pOptions the prop store * @param fpOptions path to a file * @return success */ public boolean saveOpts(Properties pOptions, String fpOptions) { pOptions.remove(optThisComingFromFile); File fOptions = new File(fpOptions); try { fpOptions = fOptions.getCanonicalPath(); OutputStream os; os = new FileOutputStream(fOptions); pOptions.store(os, ""); os.close(); } catch (Exception ex) { log(-1, "saveOptions: %s (error %s)", fOptions, ex.getMessage()); return false; } log(lvl, "saveOptions: saved: %s", fpOptions); return true; } public static boolean hasOpt(Properties props, String pName) { return null != props && null != props.getProperty(pName); } public static String getOpt(Properties props, String pName) { return getOpt(props, pName, ""); } public static String getOpt(Properties props, String pName, String deflt) { String retVal = deflt; if (hasOpt(props, pName)) { retVal = props.getProperty(pName); } return retVal; } public static String setOpt(Properties props, String pName, String pVal) { String retVal = ""; if (hasOpt(props, pName)) { retVal = props.getProperty(pName); } props.setProperty(pName, pVal); return retVal; } public static double getOptNum(Properties props, String pName) { return getOptNum(props, pName, 0d); } public static double getOptNum(Properties props, String pName, double deflt) { double retVal = deflt; if (hasOpt(props, pName)) { try { retVal = Double.parseDouble(props.getProperty(pName)); } catch (Exception ex) { } } return retVal; } public static double setOptNum(Properties props, String pName, double pVal) { double retVal = 0d; if (hasOpt(props, pName)) { try { retVal = Double.parseDouble(props.getProperty(pName)); } catch (Exception ex) { } } props.setProperty(pName, ((Double) pVal).toString()); return retVal; } public static String delOpt(Properties props, String pName) { String retVal = ""; if (hasOpt(props, pName)) { retVal = props.getProperty(pName); } props.remove(pName); return retVal; } public static Map<String, String> getOpts(Properties props) { Map<String, String> mapOptions = new HashMap<String, String>(); if (props != null) { Enumeration<?> optionNames = props.propertyNames(); String optionName; while (optionNames.hasMoreElements()) { optionName = (String) optionNames.nextElement(); mapOptions.put(optionName, props.getProperty(optionName)); } } return mapOptions; } public static int setOpts(Properties props, Map<String, String> aMap) { int n = 0; for (String key : aMap.keySet()) { props.setProperty(key, aMap.get(key)); n++; } return n; } public static boolean delOpts(Properties props) { if (null != props) { props.clear(); return true; } return false; } public static int hasOpts(Properties props) { if (null != props) { return props.size(); } return 0; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="handling resources from classpath"> protected List<String> extractTessData(File folder) { List<String> files = new ArrayList<String>(); String tessdata = "/sikulixtessdata"; URL uContentList = clsRef.getResource(tessdata + "/" + fpContent); if (uContentList != null) { files = doResourceListWithList(tessdata, files, null); if (files.size() > 0) { files = doExtractToFolderWithList(tessdata, folder, files); } } else { files = extractResourcesToFolder("/sikulixtessdata", folder, null); } return (files.size() == 0 ? null : files); } /** * export all resource files from the given subtree on classpath to the given folder retaining the subtree<br> * to export a specific file from classpath use extractResourceToFile or extractResourceToString * * @param fpRessources path of the subtree relative to root * @param fFolder folder where to export (if null, only list - no export) * @param filter implementation of interface FilenameFilter or null for no filtering * @return the filtered list of files (compact sikulixcontent format) */ public List<String> extractResourcesToFolder(String fpRessources, File fFolder, FilenameFilter filter) { List<String> content = null; content = resourceList(fpRessources, filter); if (content == null) { return null; } if (fFolder == null) { return content; } return doExtractToFolderWithList(fpRessources, fFolder, content); } private List<String> doExtractToFolderWithList(String fpRessources, File fFolder, List<String> content) { int count = 0; int ecount = 0; String subFolder = ""; if (content != null && content.size() > 0) { for (String eFile : content) { if (eFile == null) { continue; } if (eFile.endsWith("/")) { subFolder = eFile.substring(0, eFile.length() - 1); continue; } if (!subFolder.isEmpty()) { eFile = new File(subFolder, eFile).getPath(); } if (extractResourceToFile(fpRessources, eFile, fFolder)) { log(lvl + 1, "extractResourceToFile done: %s", eFile); count++; } else { ecount++; } } } if (ecount > 0) { log(lvl, "files exported: %d - skipped: %d from %s to:\n %s", count, ecount, fpRessources, fFolder); } else { log(lvl, "files exported: %d from: %s to:\n %s", count, fpRessources, fFolder); } return content; } /** * export all resource files from the given subtree in given jar to the given folder retaining the subtree * * @param aJar absolute path to an existing jar or a string identifying the jar on classpath (no leading /) * @param fpRessources path of the subtree or file relative to root * @param fFolder folder where to export (if null, only list - no export) * @param filter implementation of interface FilenameFilter or null for no filtering * @return the filtered list of files (compact sikulixcontent format) */ public List<String> extractResourcesToFolderFromJar(String aJar, String fpRessources, File fFolder, FilenameFilter filter) { List<String> content = new ArrayList<String>(); File faJar = new File(aJar); URL uaJar = null; fpRessources = FileManager.slashify(fpRessources, false); if (faJar.isAbsolute()) { if (!faJar.exists()) { log(-1, "extractResourcesToFolderFromJar: does not exist:\n%s", faJar); return null; } try { uaJar = new URL("jar", null, "file:" + aJar); logp("%s", uaJar); } catch (MalformedURLException ex) { log(-1, "extractResourcesToFolderFromJar: bad URL for:\n%s", faJar); return null; } } else { uaJar = fromClasspath(aJar); if (uaJar == null) { log(-1, "extractResourcesToFolderFromJar: not on classpath: %s", aJar); return null; } try { String sJar = "file:" + uaJar.getPath() + "!/"; uaJar = new URL("jar", null, sJar); } catch (MalformedURLException ex) { log(-1, "extractResourcesToFolderFromJar: bad URL for:\n%s", uaJar); return null; } } content = doResourceListJar(uaJar, fpRessources, content, filter); if (fFolder == null) { return content; } copyFromJarToFolderWithList(uaJar, fpRessources, content, fFolder); return content; } /** * store a resource found on classpath to a file in the given folder with same filename * * @param inPrefix a subtree found in classpath * @param inFile the filename combined with the prefix on classpath * @param outDir a folder where to export * @return success */ public boolean extractResourceToFile(String inPrefix, String inFile, File outDir) { return extractResourceToFile(inPrefix, inFile, outDir, ""); } /** * store a resource found on classpath to a file in the given folder * * @param inPrefix a subtree found in classpath * @param inFile the filename combined with the prefix on classpath * @param outDir a folder where to export * @param outFile the filename for export * @return success */ public boolean extractResourceToFile(String inPrefix, String inFile, File outDir, String outFile) { InputStream aIS; FileOutputStream aFileOS; String content = inPrefix + "/" + inFile; try { content = runningWindows ? content.replace("\\", "/") : content; if (!content.startsWith("/")) { content = "/" + content; } aIS = (InputStream) clsRef.getResourceAsStream(content); if (aIS == null) { throw new IOException("resource not accessible"); } File out = outFile.isEmpty() ? new File(outDir, inFile) : new File(outDir, inFile); if (!out.getParentFile().exists()) { out.getParentFile().mkdirs(); } aFileOS = new FileOutputStream(out); copy(aIS, aFileOS); aIS.close(); aFileOS.close(); } catch (Exception ex) { log(-1, "extractResourceToFile: %s\n%s", content, ex); return false; } return true; } /** * store the content of a resource found on classpath in the returned string * * @param inPrefix a subtree from root found in classpath (leading /) * @param inFile the filename combined with the prefix on classpath * @param encoding * @return file content */ public String extractResourceToString(String inPrefix, String inFile, String encoding) { InputStream aIS = null; String out = null; String content = inPrefix + "/" + inFile; if (!content.startsWith("/")) { content = "/" + content; } try { content = runningWindows ? content.replace("\\", "/") : content; aIS = (InputStream) clsRef.getResourceAsStream(content); if (aIS == null) { throw new IOException("resource not accessible"); } if (encoding == null) { encoding = "UTF-8"; out = new String(copy(aIS)); } else if (encoding.isEmpty()) { out = new String(copy(aIS), "UTF-8"); } else { out = new String(copy(aIS), encoding); } aIS.close(); aIS = null; } catch (Exception ex) { log(-1, "extractResourceToString as %s from:\n%s\n%s", encoding, content, ex); } try { if (aIS != null) { aIS.close(); } } catch (Exception ex) { } return out; } public URL resourceLocation(String folderOrFile) { log(lvl, "resourceLocation: (%s) %s", clsRef, folderOrFile); if (!folderOrFile.startsWith("/")) { folderOrFile = "/" + folderOrFile; } return clsRef.getResource(folderOrFile); } private List<String> resourceList(String folder, FilenameFilter filter) { log(lvl, "resourceList: enter"); List<String> files = new ArrayList<String>(); if (!folder.startsWith("/")) { folder = "/" + folder; } URL uFolder = resourceLocation(folder); if (uFolder == null) { log(lvl, "resourceList: not found: %s", folder); return files; } try { uFolder = new URL(uFolder.toExternalForm().replaceAll(" ", "%20")); } catch (Exception ex) { } URL uContentList = clsRef.getResource(folder + "/" + fpContent); if (uContentList != null) { return doResourceListWithList(folder, files, filter); } File fFolder = null; try { fFolder = new File(uFolder.toURI()); log(lvl, "resourceList: having folder: %s", fFolder); String sFolder = FileManager.normalizeAbsolute(fFolder.getPath(), false); if (":".equals(sFolder.substring(2, 3))) { sFolder = sFolder.substring(1); } files.add(sFolder); files = doResourceListFolder(new File(sFolder), files, filter); files.remove(0); return files; } catch (Exception ex) { if (!"jar".equals(uFolder.getProtocol())) { log(lvl, "resourceList:\n%s", folder); log(-1, "resourceList: URL neither folder nor jar:\n%s", ex); return null; } } String[] parts = uFolder.getPath().split("!"); if (parts.length < 2 || !parts[0].startsWith("file:")) { log(lvl, "resourceList:\n%s", folder); log(-1, "resourceList: not a valid jar URL: " + uFolder.getPath()); return null; } String fpFolder = parts[1]; log(lvl, "resourceList: having jar: %s", uFolder); return doResourceListJar(uFolder, fpFolder, files, filter); } /** * write the list as it is produced by calling extractResourcesToFolder to the given file with system line * separator<br> * non-compact format: every file with full path * * @param folder path of the subtree relative to root with leading / * @param target the file to write the list (if null, only list - no file) * @param filter implementation of interface FilenameFilter or null for no filtering * @return success */ public String[] resourceListAsFile(String folder, File target, FilenameFilter filter) { String content = resourceListAsString(folder, filter); if (content == null) { log(-1, "resourceListAsFile: did not work: %s", folder); return null; } if (target != null) { try { FileManager.deleteFileOrFolder(target.getAbsolutePath()); target.getParentFile().mkdirs(); PrintWriter aPW = new PrintWriter(target); aPW.write(content); aPW.close(); } catch (Exception ex) { log(-1, "resourceListAsFile: %s:\n%s", target, ex); } } return content.split(System.getProperty("line.separator")); } /** * write the list as it is produced by calling extractResourcesToFolder to the given file with system line * separator<br> * compact sikulixcontent format * * @param folder path of the subtree relative to root with leading / * @param targetFolder the folder where to store the file sikulixcontent (if null, only list - no export) * @param filter implementation of interface FilenameFilter or null for no filtering * @return success */ public String[] resourceListAsSikulixContent(String folder, File targetFolder, FilenameFilter filter) { List<String> contentList = resourceList(folder, filter); if (contentList == null) { log(-1, "resourceListAsSikulixContent: did not work: %s", folder); return null; } File target = null; String arrString[] = new String[contentList.size()]; try { PrintWriter aPW = null; if (targetFolder != null) { target = new File(targetFolder, fpContent); FileManager.deleteFileOrFolder(target); target.getParentFile().mkdirs(); aPW = new PrintWriter(target); } int n = 0; for (String line : contentList) { arrString[n++] = line; if (targetFolder != null) { aPW.println(line); } } if (targetFolder != null) { aPW.close(); } } catch (Exception ex) { log(-1, "resourceListAsFile: %s:\n%s", target, ex); } return arrString; } /** * write the list as it is produced by calling extractResourcesToFolder to the given file with system line * separator<br> * compact sikulixcontent format * * @param aJar absolute path to an existing jar or a string identifying the jar on classpath (no leading /) * @param folder path of the subtree relative to root with leading / * @param targetFolder the folder where to store the file sikulixcontent (if null, only list - no export) * @param filter implementation of interface FilenameFilter or null for no filtering * @return success */ public String[] resourceListAsSikulixContentFromJar(String aJar, String folder, File targetFolder, FilenameFilter filter) { List<String> contentList = extractResourcesToFolderFromJar(aJar, folder, null, filter); if (contentList == null || contentList.size() == 0) { log(-1, "resourceListAsSikulixContentFromJar: did not work: %s", folder); return null; } File target = null; String arrString[] = new String[contentList.size()]; try { PrintWriter aPW = null; if (targetFolder != null) { target = new File(targetFolder, fpContent); FileManager.deleteFileOrFolder(target); target.getParentFile().mkdirs(); aPW = new PrintWriter(target); } int n = 0; for (String line : contentList) { arrString[n++] = line; if (targetFolder != null) { aPW.println(line); } } if (targetFolder != null) { aPW.close(); } } catch (Exception ex) { log(-1, "resourceListAsFile: %s:\n%s", target, ex); } return arrString; } /** * write the list produced by calling extractResourcesToFolder to the returned string with system line separator<br> * non-compact format: every file with full path * * @param folder path of the subtree relative to root with leading / * @param filter implementation of interface FilenameFilter or null for no filtering * @return the resulting string */ public String resourceListAsString(String folder, FilenameFilter filter) { return resourceListAsString(folder, filter, null); } /** * write the list produced by calling extractResourcesToFolder to the returned string with given separator<br> * non-compact format: every file with full path * * @param folder path of the subtree relative to root with leading / * @param filter implementation of interface FilenameFilter or null for no filtering * @param separator to be used to separate the entries * @return the resulting string */ public String resourceListAsString(String folder, FilenameFilter filter, String separator) { List<String> aList = resourceList(folder, filter); if (aList == null) { return null; } if (separator == null) { separator = System.getProperty("line.separator"); } String out = ""; String subFolder = ""; if (aList != null && aList.size() > 0) { for (String eFile : aList) { if (eFile == null) { continue; } if (eFile.endsWith("/")) { subFolder = eFile.substring(0, eFile.length() - 1); continue; } if (!subFolder.isEmpty()) { eFile = new File(subFolder, eFile).getPath(); } out += eFile.replace("\\", "/") + separator; } } return out; } private List<String> doResourceListFolder(File fFolder, List<String> files, FilenameFilter filter) { int localLevel = testing ? lvl : lvl + 1; String subFolder = ""; if (fFolder.isDirectory()) { if (!FileManager.pathEquals(fFolder.getPath(), files.get(0))) { subFolder = fFolder.getPath().substring(files.get(0).length() + 1).replace("\\", "/") + "/"; if (filter != null && !filter.accept(new File(files.get(0), subFolder), "")) { return files; } } else { logp(localLevel, "scanning folder:\n%s", fFolder); subFolder = "/"; files.add(subFolder); } String[] subList = fFolder.list(); for (String entry : subList) { File fEntry = new File(fFolder, entry); if (fEntry.isDirectory()) { files.add(fEntry.getAbsolutePath().substring(1 + files.get(0).length()).replace("\\", "/") + "/"); doResourceListFolder(fEntry, files, filter); files.add(subFolder); } else { if (filter != null && !filter.accept(fFolder, entry)) { continue; } logp(localLevel, "from %s adding: %s", (subFolder.isEmpty() ? "." : subFolder), entry); files.add(fEntry.getAbsolutePath().substring(1 + fFolder.getPath().length())); } } } return files; } private List<String> doResourceListWithList(String folder, List<String> files, FilenameFilter filter) { String content = extractResourceToString(folder, fpContent, ""); String[] contentList = content.split(content.indexOf("\r") != -1 ? "\r\n" : "\n"); if (filter == null) { files.addAll(Arrays.asList(contentList)); } else { for (String fpFile : contentList) { if (filter.accept(new File(fpFile), "")) { files.add(fpFile); } } } return files; } private List<String> doResourceListJar(URL uJar, String fpResource, List<String> files, FilenameFilter filter) { ZipInputStream zJar; String fpJar = uJar.getPath().split("!")[0]; int localLevel = testing ? lvl : lvl + 1; String fileSep = "/"; if (!fpJar.endsWith(".jar")) { return files; } logp(localLevel, "scanning jar:\n%s", uJar); fpResource = (fpResource.startsWith("/") ? fpResource.substring(1) : fpResource) + "/"; File fFolder = new File(fpResource); File fSubFolder = null; ZipEntry zEntry; String subFolder = ""; boolean skip = false; try { zJar = new ZipInputStream(new URL(fpJar).openStream()); while ((zEntry = zJar.getNextEntry()) != null) { if (zEntry.getName().endsWith("/")) { continue; } String zePath = zEntry.getName(); if (zePath.startsWith(fpResource)) { // if (fpResource.length() == zePath.length()) { // files.add(zePath); // return files; // } String zeName = zePath.substring(fpResource.length()); int nSep = zeName.lastIndexOf(fileSep); String zefName = zeName.substring(nSep + 1, zeName.length()); String zeSub = ""; if (nSep > -1) { zeSub = zeName.substring(0, nSep + 1); if (!subFolder.equals(zeSub)) { subFolder = zeSub; fSubFolder = new File(fFolder, subFolder); skip = false; if (filter != null && !filter.accept(fSubFolder, "")) { skip = true; continue; } files.add(zeSub); } if (skip) { continue; } } else { if (!subFolder.isEmpty()) { subFolder = ""; fSubFolder = fFolder; files.add("/"); } } if (filter != null && !filter.accept(fSubFolder, zefName)) { continue; } files.add(zefName); logp(localLevel, "from %s adding: %s", (zeSub.isEmpty() ? "." : zeSub), zefName); } } } catch (Exception ex) { log(-1, "doResourceListJar: %s", ex); return files; } return files; } private boolean copyFromJarToFolderWithList(URL uJar, String fpRessource, List<String> files, File fFolder) { if (files == null || files.isEmpty()) { log(lvl, "copyFromJarToFolderWithList: list of files is empty"); return false; } String fpJar = uJar.getPath().split("!")[0]; if (!fpJar.endsWith(".jar")) { return false; } int localLevel = testing ? lvl : lvl + 1; logp(localLevel, "scanning jar:\n%s", uJar); fpRessource = fpRessource.startsWith("/") ? fpRessource.substring(1) : fpRessource; String subFolder = ""; int maxFiles = files.size() - 1; int nFiles = 0; ZipEntry zEntry; ZipInputStream zJar; String zPath; int prefix = fpRessource.length(); fpRessource += !fpRessource.isEmpty() ? "/" : ""; String current = "/"; boolean shouldStop = false; try { zJar = new ZipInputStream(new URL(fpJar).openStream()); while ((zEntry = zJar.getNextEntry()) != null) { zPath = zEntry.getName(); if (zPath.endsWith("/")) { continue; } while (current.endsWith("/")) { if (nFiles > maxFiles) { shouldStop = true; break; } subFolder = current.length() == 1 ? "" : current; current = files.get(nFiles++); if (!current.endsWith("/")) { current = fpRessource + subFolder + current; break; } } if (shouldStop) { break; } if (zPath.startsWith(current)) { if (zPath.length() == fpRessource.length() - 1) { log(-1, "extractResourcesToFolderFromJar: only ressource folders allowed - use filter"); return false; } logp(localLevel, "copying: %s", zPath); File out = new File(fFolder, zPath.substring(prefix)); if (!out.getParentFile().exists()) { out.getParentFile().mkdirs(); } FileOutputStream aFileOS = new FileOutputStream(out); copy(zJar, aFileOS); aFileOS.close(); if (nFiles > maxFiles) { break; } current = files.get(nFiles++); if (!current.endsWith("/")) { current = fpRessource + subFolder + current; } } } zJar.close(); } catch (Exception ex) { log(-1, "doResourceListJar: %s", ex); return false; } return true; } private void copy(InputStream in, OutputStream out) throws IOException { byte[] tmp = new byte[8192]; int len; while (true) { len = in.read(tmp); if (len <= 0) { break; } out.write(tmp, 0, len); } out.flush(); } private byte[] copy(InputStream inputStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length = 0; while ((length = inputStream.read(buffer)) != -1) { baos.write(buffer, 0, length); } return baos.toByteArray(); } public class oneFileFilter implements FilenameFilter { String aFile; public oneFileFilter(String aFileGiven) { aFile = aFileGiven; } @Override public boolean accept(File dir, String name) { if (name.contains(aFile)) { return true; } return false; } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="classpath handling"> private void storeClassPath() { //TODO Java9 URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); classPath = Arrays.asList(sysLoader.getURLs()); } /** * print the current classpath entries to sysout */ public void dumpClassPath() { dumpClassPath(null); } /** * print the current classpath entries to sysout whose path name contain the given string * * @param filter the fileter string */ public void dumpClassPath(String filter) { filter = filter == null ? "" : filter; logp("*** classpath dump %s", filter); storeClassPath(); String sEntry; filter = filter.toUpperCase(); int n = 0; for (URL uEntry : classPath) { sEntry = uEntry.getPath(); if (!filter.isEmpty()) { if (!sEntry.toUpperCase().contains(filter)) { n++; continue; } } logp("%3d: %s", n, sEntry); n++; } logp("*** classpath dump end"); } /** * check whether a classpath entry contains the given identifying string, stops on first match * * @param artefact the identifying string * @return the absolute path of the entry found - null if not found */ private String isOnClasspath(String artefact, boolean isJar) { artefact = FileManager.slashify(artefact, false); String cpe = null; if (classPath.isEmpty()) { storeClassPath(); } for (URL entry : classPath) { String sEntry = FileManager.slashify(new File(entry.getPath()).getPath(), false); if (sEntry.contains(artefact)) { if (isJar) { if (!sEntry.endsWith(".jar")) { continue; } if (!new File(sEntry).getName().contains(artefact)) { continue; } if (new File(sEntry).getName().contains("4" + artefact)) { continue; } } cpe = new File(entry.getPath()).getPath(); break; } } return cpe; } public String isJarOnClasspath(String artefact) { return isOnClasspath(artefact, true); } public String isOnClasspath(String artefact) { return isOnClasspath(artefact, false); } public URL fromClasspath(String artefact) { artefact = FileManager.slashify(artefact, false).toUpperCase(); URL cpe = null; if (classPath.isEmpty()) { storeClassPath(); } for (URL entry : classPath) { String sEntry = FileManager.slashify(new File(entry.getPath()).getPath(), false); if (sEntry.toUpperCase().contains(artefact)) { return entry; } } return cpe; } /** * check wether a the given URL is on classpath * * @param path URL to look for * @return true if found else otherwise */ public boolean isOnClasspath(URL path) { if (classPath.isEmpty()) { storeClassPath(); } for (URL entry : classPath) { if (new File(path.getPath()).equals(new File(entry.getPath()))) { return true; } } return false; } /** * adds the given folder or jar to the end of the current classpath * * @param jarOrFolder absolute path to a folder or jar * @return success */ public boolean addToClasspath(String jarOrFolder) { URL uJarOrFolder = FileManager.makeURL(jarOrFolder); if (!new File(jarOrFolder).exists()) { log(-1, "addToClasspath: does not exist - not added:\n%s", jarOrFolder); return false; } if (isOnClasspath(uJarOrFolder)) { return true; } log(lvl, "addToClasspath:\n%s", uJarOrFolder); Method method; URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Class sysclass = URLClassLoader.class; try { method = sysclass.getDeclaredMethod("addURL", new Class[]{URL.class}); method.setAccessible(true); method.invoke(sysLoader, new Object[]{uJarOrFolder}); } catch (Exception ex) { log(-1, "Did not work: %s", ex.getMessage()); return false; } storeClassPath(); return true; } public File asExtension(String fpJar) { File fJarFound = new File(FileManager.normalizeAbsolute(fpJar, false)); if (!fJarFound.exists()) { String fpCPEntry = runTime.isOnClasspath(fJarFound.getName()); if (fpCPEntry == null) { fJarFound = new File(runTime.fSikulixExtensions, fpJar); if (!fJarFound.exists()) { fJarFound = new File(runTime.fSikulixLib, fpJar); if (!fJarFound.exists()) { fJarFound = null; } } } else { fJarFound = new File(fpCPEntry, fJarFound.getName()); } } else { return null; } return fJarFound; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="system enviroment"> /** * print the current java system properties key-value pairs sorted by key */ public void dumpSysProps() { dumpSysProps(null); } /** * print the current java system properties key-value pairs sorted by key but only keys containing filter * * @param filter the filter string */ public void dumpSysProps(String filter) { filter = filter == null ? "" : filter; logp("*** system properties dump " + filter); Properties sysProps = System.getProperties(); ArrayList<String> keysProp = new ArrayList<String>(); Integer nL = 0; String entry; for (Object e : sysProps.keySet()) { entry = (String) e; if (entry.length() > nL) { nL = entry.length(); } if (filter.isEmpty() || !filter.isEmpty() && entry.contains(filter)) { keysProp.add(entry); } } Collections.sort(keysProp); String form = "%-" + nL.toString() + "s = %s"; for (Object e : keysProp) { logp(form, e, sysProps.get(e)); } logp("*** system properties dump end" + filter); } /** * checks, whether Java runs with a valid GraphicsEnvironment (usually means real screens connected) * * @return false if Java thinks it has access to screen(s), true otherwise */ public boolean isHeadless() { return GraphicsEnvironment.isHeadless(); } public boolean isMultiMonitor() { return nMonitors > 1; } public Rectangle getMonitor(int n) { if (isHeadless()) { return new Rectangle(0, 0, 1, 1); } if (null == monitorBounds) { return null; } n = (n < 0 || n >= nMonitors) ? mainMonitor : n; return monitorBounds[n]; } public Rectangle getAllMonitors() { if (isHeadless()) { return new Rectangle(0, 0, 1, 1); } return rAllMonitors; } public Rectangle hasPoint(Point aPoint) { if (isHeadless()) { return new Rectangle(0, 0, 1, 1); } for (Rectangle rMon : monitorBounds) { if (rMon.contains(aPoint)) { return rMon; } } return null; } public Rectangle hasRectangle(Rectangle aRect) { if (isHeadless()) { return new Rectangle(0, 0, 1, 1); } return hasPoint(aRect.getLocation()); } public GraphicsDevice getGraphicsDevice(int id) { return gdevs[id]; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="runcmd"> /** * run a system command finally using Java::Runtime.getRuntime().exec(args) and waiting for completion * * @param cmd the command as it would be given on command line, quoting is preserved * @return the output produced by the command (sysout [+ "*** error ***" + syserr] if the syserr part is present, the * command might have failed */ public String runcmd(String cmd) { return runcmd(new String[]{cmd}); } /** * run a system command finally using Java::Runtime.getRuntime().exec(args) and waiting for completion * * @param args the command as it would be given on command line splitted into the space devided parts, first part is * the command, the rest are parameters and their values * @return the output produced by the command (sysout [+ "*** error ***" + syserr] if the syserr part is present, the * command might have failed */ public String runcmd(String args[]) { if (args.length == 0) { return ""; } boolean silent = false; if (args.length == 1) { String separator = "\""; ArrayList<String> argsx = new ArrayList<String>(); StringTokenizer toks; String tok; String cmd = args[0]; if (Settings.isWindows()) { cmd = cmd.replaceAll("\\\\ ", "%20;"); } toks = new StringTokenizer(cmd); while (toks.hasMoreTokens()) { tok = toks.nextToken(" "); if (tok.length() == 0) { continue; } if (separator.equals(tok)) { continue; } if (tok.startsWith(separator)) { if (tok.endsWith(separator)) { tok = tok.substring(1, tok.length() - 1); } else { tok = tok.substring(1); tok += toks.nextToken(separator); } } argsx.add(tok.replaceAll("%20;", " ")); } args = argsx.toArray(new String[0]); } if (args[0].startsWith("!")) { silent = true; args[0] = args[0].substring(1); } if (args[0].startsWith("#")) { String pgm = args[0].substring(1); args[0] = (new File(pgm)).getAbsolutePath(); runcmd(new String[]{"chmod", "ugo+x", args[0]}); } String result = ""; String error = runCmdError + NL; String errorOut = ""; boolean hasError = false; int retVal; try { if (!silent) { if (lvl <= Debug.getDebugLevel()) { log(lvl, Sikulix.arrayToString(args)); } else { Debug.info("runcmd: " + Sikulix.arrayToString(args)); } } Process process = Runtime.getRuntime().exec(args); BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream())); String s; while ((s = stdInput.readLine()) != null) { if (!s.isEmpty()) { result += s + NL; } } while ((s = stdError.readLine()) != null) { if (!s.isEmpty()) { errorOut += s + NL; } } if (!errorOut.isEmpty()) { error = error + errorOut; hasError = true; } process.waitFor(); retVal = process.exitValue(); process.destroy(); } catch (Exception e) { log(-1, "fatal error: " + e); result = String.format(error + "%s", e); retVal = 9999; hasError = true; } if (hasError) { result += error; } lastResult = result; return String.format("%d%s%s", retVal, NL, result); } public String getLastCommandResult() { return lastResult; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="args handling for scriptrunner"> private String[] args = new String[0]; private String[] sargs = new String[0]; public void setArgs(String[] args, String[] sargs) { this.args = args; this.sargs = sargs; } public String[] getSikuliArgs() { return sargs; } public String[] getArgs() { return args; } public void printArgs() { if (Debug.getDebugLevel() < lvl) { return; } String[] xargs = getSikuliArgs(); if (xargs.length > 0) { Debug.log(lvl, "--- Sikuli parameters ---"); for (int i = 0; i < xargs.length; i++) { Debug.log(lvl, "%d: %s", i + 1, xargs[i]); } } xargs = getArgs(); if (xargs.length > 0) { Debug.log(lvl, "--- User parameters ---"); for (int i = 0; i < xargs.length; i++) { Debug.log(lvl, "%d: %s", i + 1, xargs[i]); } } } public static int checkArgs(String[] args, Type typ) { int debugLevel = -99; boolean runningScripts = false; List<String> options = new ArrayList<String>(); options.addAll(Arrays.asList(args)); for (int n = 0; n < options.size(); n++) { String opt = options.get(n); if ("nodebug".equals(opt)) { return -2; } if (Type.IDE.equals(typ) && "-s".equals(opt.toLowerCase())) { return -3; } if (!opt.startsWith("-")) { continue; } if (opt.startsWith("-d")) { debugLevel = -1; try { debugLevel = n + 1 == options.size() ? -1 : Integer.decode(options.get(n + 1)); } catch (Exception ex) { debugLevel = -1; } if (debugLevel > -1) { Debug.on(debugLevel); } } else if (opt.startsWith("-r") || opt.startsWith("-t") || opt.startsWith("-s") || opt.startsWith("-i")) { runningScripts = true; } } if (runningScripts) { return 999; } return debugLevel; } //</editor-fold> }
[ "hjpq0@163.com" ]
hjpq0@163.com