text
stringlengths
7
1.01M
// Exp 10 - UDP Client (Sender) import java.io.*; import java.net.*; public class lab10client { public static void main(String[] args) throws IOException { InetAddress saddr = null; int sport = 0; DatagramSocket sock = new DatagramSocket(); BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in)); byte[] sendbuf = new byte[1024]; byte[] recvbuf = new byte[1024]; // extract the server IP Address and port number from command line arguments saddr = InetAddress.getByName(args[0]); sport = Integer.parseInt(args[1]); while (true) { System.out.println("Enter chat data: "); // read user input String sentence = userIn.readLine(); // exit the client when user enters "Exit" if (sentence.equals("Exit")) { break; } // convert the input data to byte sequence sendbuf = sentence.getBytes(); // prepare the packet to be sent to server. DatagramPacket sendpkt = new DatagramPacket(sendbuf, sendbuf.length,saddr,sport); // send the packet sock.send(sendpkt); // prepare a packet to received the response DatagramPacket recvpkt = new DatagramPacket(recvbuf,recvbuf.length); sock.receive(recvpkt); // convert the received UDP data to string text and display the same. String recvdata = new String(recvpkt.getData()); System.out.println("Recd from Server: " + recvdata); // initialize the send and receive buffer for (int i=0; i< sendbuf.length; i++) { sendbuf[i] = 0; } for (int i=0; i< recvbuf.length; i++) { recvbuf[i] = 0; } } System.out.println("Closing the chat. Exiting"); sock.close(); } }
package com.javanorth.spring.springbootsecurity.filter; import com.google.gson.Gson; import com.javanorth.spring.springbootsecurity.service.impl.TokenServiceImpl; import com.javanorth.spring.springbootsecurity.service.impl.UserDetailsServiceImpl; import com.javanorth.spring.springbootsecurity.util.LogUtil; import io.jsonwebtoken.Claims; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import javax.annotation.PostConstruct; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Optional; @Component public class JwtTokenFilter extends OncePerRequestFilter { private static JwtTokenFilter jwtTokenFilter; /** * 存放Token的Header Key */ private static final String HEADER_STRING = "Authorization"; @Autowired TokenServiceImpl tokenService; @Autowired UserDetailsServiceImpl userDetailsService; @PostConstruct public void init() { jwtTokenFilter = this; } @Override protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { Gson gson = new Gson(); // 校验jwt String header = httpServletRequest.getHeader(HEADER_STRING); LogUtil.info(this.getClass(), "current header: {}", header); // 判空 boolean optional = Optional.ofNullable(header).isPresent(); if (optional) { // 1.header不为空则解析header中的username Claims claims = jwtTokenFilter.tokenService.parseToken(header); String username = jwtTokenFilter.tokenService.getUsernameFromToken(claims); // 2.通过查询出来的username对该用户判断是否首授权访问 if (Optional.ofNullable(username).isPresent() && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = jwtTokenFilter.userDetailsService.loadUserByUsername(username); LogUtil.info(this.getClass(), "user details: {}", userDetails.toString()); // 3.如果未授权则进行授权 UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities()); authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails( httpServletRequest)); SecurityContextHolder.getContext().setAuthentication(authenticationToken); } // 如果用户存在并且该接口未授权,则对该接口授权 } filterChain.doFilter(httpServletRequest, httpServletResponse); } }
/* * Copyright (C) 2012 Zach Melamed * * Latest version available online at https://github.com/zach-m/jonix * Contact me at zach@tectonica.co.il * * 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.tectonica.jonix.onix3; import java.io.Serializable; import java.util.List; import com.tectonica.jonix.JPU; import com.tectonica.jonix.OnixComposite.OnixSuperComposite; import com.tectonica.jonix.codelist.RecordSourceTypes; /* * NOTE: THIS IS AN AUTO-GENERATED FILE, DON'T EDIT MANUALLY */ /** * <h1>null</h1><h4 class="nobreak">Related material composite</h4> * <p> * The related material block covers data element Groups P.22 and P.23, providing links to related works and related * products. The block as a whole is optional and non-repeating. * </p> * <table border='1' cellpadding='3'> * <tr> * <td>Reference name</td> * <td>&lt;RelatedMaterial&gt;</td> * </tr> * <tr> * <td>Short tag</td> * <td>&lt;relatedmaterial&gt;</td> * </tr> * <tr> * <td>Cardinality</td> * <td>0&#8230;1</td> * </tr> * </table> */ public class RelatedMaterial implements OnixSuperComposite, Serializable { private static final long serialVersionUID = 1L; public static final String refname = "RelatedMaterial"; public static final String shortname = "relatedmaterial"; // /////////////////////////////////////////////////////////////////////////////// // ATTRIBUTES // /////////////////////////////////////////////////////////////////////////////// /** * (type: dt.DateOrDateTime) */ public String datestamp; public RecordSourceTypes sourcetype; public String sourcename; // /////////////////////////////////////////////////////////////////////////////// // MEMBERS // /////////////////////////////////////////////////////////////////////////////// /** * (this list may be empty) */ public List<RelatedWork> relatedWorks; /** * (this list may be empty) */ public List<RelatedProduct> relatedProducts; // /////////////////////////////////////////////////////////////////////////////// // SERVICES // /////////////////////////////////////////////////////////////////////////////// public RelatedMaterial() {} public RelatedMaterial(org.w3c.dom.Element element) { datestamp = JPU.getAttribute(element, "datestamp"); sourcetype = RecordSourceTypes.byCode(JPU.getAttribute(element, "sourcetype")); sourcename = JPU.getAttribute(element, "sourcename"); JPU.forElementsOf(element, new JPU.ElementListener() { @Override public void onElement(org.w3c.dom.Element element) { final String name = element.getNodeName(); if (name.equals(RelatedWork.refname) || name.equals(RelatedWork.shortname)) relatedWorks = JPU.addToList(relatedWorks, new RelatedWork(element)); else if (name.equals(RelatedProduct.refname) || name.equals(RelatedProduct.shortname)) relatedProducts = JPU.addToList(relatedProducts, new RelatedProduct(element)); } }); } }
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.messaging.handler.invocation.reactive; import org.springframework.core.*; import org.springframework.lang.Nullable; import org.springframework.messaging.Message; import org.springframework.messaging.handler.HandlerMethod; import org.springframework.messaging.handler.invocation.MethodArgumentResolutionException; import org.springframework.util.ObjectUtils; import org.springframework.util.ReflectionUtils; import reactor.core.publisher.Mono; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; /** * Extension of {@link HandlerMethod} that invokes the underlying method with * argument values resolved from the current HTTP request through a list of * {@link HandlerMethodArgumentResolver}. * * @author Rossen Stoyanchev * @since 5.2 */ public class InvocableHandlerMethod extends HandlerMethod { private static final Mono<Object[]> EMPTY_ARGS = Mono.just(new Object[0]); private static final Object NO_ARG_VALUE = new Object(); private HandlerMethodArgumentResolverComposite resolvers = new HandlerMethodArgumentResolverComposite(); private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer(); private ReactiveAdapterRegistry reactiveAdapterRegistry = ReactiveAdapterRegistry.getSharedInstance(); /** * Create an instance from a {@code HandlerMethod}. */ public InvocableHandlerMethod(HandlerMethod handlerMethod) { super(handlerMethod); } /** * Create an instance from a bean instance and a method. */ public InvocableHandlerMethod(Object bean, Method method) { super(bean, method); } /** * Configure the argument resolvers to use to use for resolving method * argument values against a {@code ServerWebExchange}. */ public void setArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { this.resolvers.addResolvers(resolvers); } /** * Return the configured argument resolvers. */ public List<HandlerMethodArgumentResolver> getResolvers() { return this.resolvers.getResolvers(); } /** * Return the configured parameter name discoverer. */ public ParameterNameDiscoverer getParameterNameDiscoverer() { return this.parameterNameDiscoverer; } /** * Set the ParameterNameDiscoverer for resolving parameter names when needed * (e.g. default request attribute name). * <p>Default is a {@link DefaultParameterNameDiscoverer}. */ public void setParameterNameDiscoverer(ParameterNameDiscoverer nameDiscoverer) { this.parameterNameDiscoverer = nameDiscoverer; } /** * Configure a reactive adapter registry. This is needed for async return values. * <p>By default this is a {@link ReactiveAdapterRegistry} with default settings. */ public void setReactiveAdapterRegistry(ReactiveAdapterRegistry registry) { this.reactiveAdapterRegistry = registry; } /** * Invoke the method for the given exchange. * * @param message the current message * @param providedArgs optional list of argument values to match by type * @return a Mono with the result from the invocation */ @SuppressWarnings("KotlinInternalInJava") public Mono<Object> invoke(Message<?> message, Object... providedArgs) { return getMethodArgumentValues(message, providedArgs).flatMap(args -> { Object value; try { Method method = getBridgedMethod(); ReflectionUtils.makeAccessible(method); if (KotlinDetector.isKotlinReflectPresent() && KotlinDetector.isKotlinType(method.getDeclaringClass())) { value = CoroutinesUtils.invokeHandlerMethod(method, getBean(), args); } else { value = method.invoke(getBean(), args); } } catch (IllegalArgumentException ex) { assertTargetBean(getBridgedMethod(), getBean(), args); String text = (ex.getMessage() != null ? ex.getMessage() : "Illegal argument"); return Mono.error(new IllegalStateException(formatInvokeError(text, args), ex)); } catch (InvocationTargetException ex) { return Mono.error(ex.getTargetException()); } catch (Throwable ex) { // Unlikely to ever get here, but it must be handled... return Mono.error(new IllegalStateException(formatInvokeError("Invocation failure", args), ex)); } MethodParameter returnType = getReturnType(); ReactiveAdapter adapter = this.reactiveAdapterRegistry.getAdapter(returnType.getParameterType()); return (isAsyncVoidReturnType(returnType, adapter) ? Mono.from(adapter.toPublisher(value)) : Mono.justOrEmpty(value)); }); } private Mono<Object[]> getMethodArgumentValues(Message<?> message, Object... providedArgs) { MethodParameter[] parameters = getMethodParameters(); if (ObjectUtils.isEmpty(getMethodParameters())) { return EMPTY_ARGS; } List<Mono<Object>> argMonos = new ArrayList<>(parameters.length); for (MethodParameter parameter : parameters) { parameter.initParameterNameDiscovery(this.parameterNameDiscoverer); Object providedArg = findProvidedArgument(parameter, providedArgs); if (providedArg != null) { argMonos.add(Mono.just(providedArg)); continue; } if (!this.resolvers.supportsParameter(parameter)) { return Mono.error(new MethodArgumentResolutionException( message, parameter, formatArgumentError(parameter, "No suitable resolver"))); } try { argMonos.add(this.resolvers.resolveArgument(parameter, message) .defaultIfEmpty(NO_ARG_VALUE) .doOnError(ex -> logArgumentErrorIfNecessary(parameter, ex))); } catch (Exception ex) { logArgumentErrorIfNecessary(parameter, ex); argMonos.add(Mono.error(ex)); } } return Mono.zip(argMonos, values -> Stream.of(values).map(value -> value != NO_ARG_VALUE ? value : null).toArray()); } private void logArgumentErrorIfNecessary(MethodParameter parameter, Throwable ex) { // Leave stack trace for later, if error is not handled... String exMsg = ex.getMessage(); if (exMsg != null && !exMsg.contains(parameter.getExecutable().toGenericString())) { if (logger.isDebugEnabled()) { logger.debug(formatArgumentError(parameter, exMsg)); } } } private boolean isAsyncVoidReturnType(MethodParameter returnType, @Nullable ReactiveAdapter reactiveAdapter) { if (reactiveAdapter != null && reactiveAdapter.supportsEmpty()) { if (reactiveAdapter.isNoValue()) { return true; } Type parameterType = returnType.getGenericParameterType(); if (parameterType instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) parameterType; if (type.getActualTypeArguments().length == 1) { return Void.class.equals(type.getActualTypeArguments()[0]); } } } return false; } }
package org.meteogroup.griblibrary.grib1; import org.meteogroup.griblibrary.exception.BinaryNumberConversionException; import org.meteogroup.griblibrary.grib1.model.Grib1PDS; import org.meteogroup.griblibrary.util.BitChecker; import org.meteogroup.griblibrary.util.BytesToPrimitiveHelper; import java.util.ArrayList; /** * Created by roijen on 21-Oct-15. */ public class Grib1PDSReader { private static final int POSITION_PDS_LENGTH_1 = 0; private static final int POSITION_PDS_LENGTH_2 = 1; private static final int POSITION_PDS_LENGTH_3 = 2; private static final int POSITION_PDS_TABLE_VERSION_NUMBER = 3; private static final int POSITION_PDS_IDENTIFICATION_OF_CENTRE = 4; private static final int POSITION_PDS_GENERATING_PROCESS_NUMBER = 5; private static final int POSITION_PDS_GRIB_IDENTIFICATION = 6; private static final int POSITION_PDS_BMS_GDS_FLAGS = 7; private static final int FLAG_GDS = 1; private static final int FLAG_BMS = 2; private static final int POSITION_PDS_IDENTICATOR_OF_PARAMETER_AND_UNIT = 8; private static final int POSITION_PDS_IDENTICATOR_OF_TYPE_OF_LEVEL_OR_LAYER = 9; private static final ArrayList<Integer> HEIGHT_LAYERS_WITH_DOUBLE_OCTET_VALUES = new ArrayList<Integer>(){{add(100);add(103);add(105);add(107);add(109);add(111);add(113);add(125);add(160);add(200);add(201);}}; private static final int POSITION_PDS_LEVEL_OR_LAYER_VALUE_1 = 10; private static final int POSITION_PDS_LEVEL_OR_LAYER_VALUE_2 = 11; private static final int POSITION_PDS_ISSUE_TIME_YEAR_OF_CENTURY = 12; private static final int POSITION_PDS_ISSUE_TIME_MONTH = 13; private static final int POSITION_PDS_ISSUE_TIME_DAY = 14; private static final int POSITION_PDS_ISSUE_TIME_HOUR = 15; private static final int POSITION_PDS_ISSUE_TIME_MINUTE = 16; private static final int POSITION_PDS_FORECAST_TIME_UNITE = 17; private static final int POSITION_PDS_FORECAST_PERIOD_OF_TIME_1 = 18; private static final int POSITION_PDS_FORECAST_PERIOD_OF_TIME_2 = 19; private static final int POSITION_PDS_TIME_RANGE_INDICATOR = 20; private static final int POSITION_PDS_NUMBER_INCLUDED_IN_AVERAGE_OR_ACCUMULATION_1 = 21; private static final int POSITION_PDS_NUMBER_INCLUDED_IN_AVERAGE_OR_ACCUMULATION_2 = 22; private static final int POSITION_PDS_NUMBER_OF_MISSING_FROM_AVERAGE_OR_ACCUMULATION = 23; private static final int POSITION_PDS_ISSUE_TIME_CENTURY = 24; private static final int POSITION_PDS_IDENTIFICATION_OF_SUBCENTRE = 25; private static final int POSITION_PDS_DECIMAL_SCALE_FACTOR_1 = 26; private static final int POSITION_PDS_DECIMAL_SCALE_FACTOR_2 = 27; public int readPDSLength(byte[] values, int headerOffSet) throws BinaryNumberConversionException { return BytesToPrimitiveHelper.bytesToInteger(values[POSITION_PDS_LENGTH_1 + headerOffSet], values[POSITION_PDS_LENGTH_2 + headerOffSet], values[POSITION_PDS_LENGTH_3 + headerOffSet]); } public Grib1PDS readPDSValues(byte[] values, int headerOffSet) throws BinaryNumberConversionException { Grib1PDS objectToReadInto = new Grib1PDS(); objectToReadInto.setPdsLenght(this.readPDSLength(values,headerOffSet)); objectToReadInto.setParameterTableVersionNumber((short) (values[POSITION_PDS_TABLE_VERSION_NUMBER + headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK)); objectToReadInto.setIdentificationOfCentre((short)(values[POSITION_PDS_IDENTIFICATION_OF_CENTRE+headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK)); objectToReadInto.setGeneratingProcessIdNumber((short)(values[POSITION_PDS_GENERATING_PROCESS_NUMBER+headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK)); objectToReadInto.setGridIdentification((short)(values[POSITION_PDS_GRIB_IDENTIFICATION+headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK)); objectToReadInto.setHasGDS(BitChecker.testBit(values[POSITION_PDS_BMS_GDS_FLAGS+headerOffSet], FLAG_GDS)); objectToReadInto.setHasBMS(BitChecker.testBit(values[POSITION_PDS_BMS_GDS_FLAGS+headerOffSet], FLAG_BMS)); objectToReadInto.setIdenticatorOfParameterAndUnit((short)(values[POSITION_PDS_IDENTICATOR_OF_PARAMETER_AND_UNIT+headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK)); objectToReadInto.setIdenticatorOfTypeOfLevelOrLayer((short)(values[POSITION_PDS_IDENTICATOR_OF_TYPE_OF_LEVEL_OR_LAYER+headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK)); if(HEIGHT_LAYERS_WITH_DOUBLE_OCTET_VALUES.contains(objectToReadInto.getIdenticatorOfTypeOfLevelOrLayer())){ objectToReadInto.setHasOnlyOneLevelOrLayerValue(true); objectToReadInto.setLevelOrLayerValue1(BytesToPrimitiveHelper.bytesToInteger(values[POSITION_PDS_LEVEL_OR_LAYER_VALUE_1+headerOffSet], values[POSITION_PDS_LEVEL_OR_LAYER_VALUE_2+headerOffSet])); } else{ objectToReadInto.setHasOnlyOneLevelOrLayerValue(false); objectToReadInto.setLevelOrLayerValue1((short)(values[POSITION_PDS_LEVEL_OR_LAYER_VALUE_1+headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK)); objectToReadInto.setLevelOrLayerValue2((short) (values[POSITION_PDS_LEVEL_OR_LAYER_VALUE_2 + headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK)); } objectToReadInto.setIssueTimeYearOfCentury((short)(values[POSITION_PDS_ISSUE_TIME_YEAR_OF_CENTURY+headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK)); objectToReadInto.setIssueTimeMonth((short)(values[POSITION_PDS_ISSUE_TIME_MONTH+headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK)); objectToReadInto.setIssueTimeDay((short)(values[POSITION_PDS_ISSUE_TIME_DAY+headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK)); objectToReadInto.setIssueTimeHour((short)(values[POSITION_PDS_ISSUE_TIME_HOUR+headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK)); objectToReadInto.setIssueTimeMinute((short)(values[POSITION_PDS_ISSUE_TIME_MINUTE+headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK)); objectToReadInto.setForecastTimeUnit((short)(values[POSITION_PDS_FORECAST_TIME_UNITE+headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK)); objectToReadInto.setForecastPeriodOfTime1((short)(values[POSITION_PDS_FORECAST_PERIOD_OF_TIME_1+headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK)); objectToReadInto.setForecastPeriodOfTime2((short)(values[POSITION_PDS_FORECAST_PERIOD_OF_TIME_2+headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK)); objectToReadInto.setTimeRangeIndicator((short)(values[POSITION_PDS_TIME_RANGE_INDICATOR+headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK)); objectToReadInto.setNumberIncludedInAverageOrAccumulation(BytesToPrimitiveHelper.bytesToInteger(values[POSITION_PDS_NUMBER_INCLUDED_IN_AVERAGE_OR_ACCUMULATION_1+headerOffSet], values[POSITION_PDS_NUMBER_INCLUDED_IN_AVERAGE_OR_ACCUMULATION_2+headerOffSet])); objectToReadInto.setNumberOfMissingFromAverageOrAcummulation((short) (values[POSITION_PDS_NUMBER_OF_MISSING_FROM_AVERAGE_OR_ACCUMULATION + headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK)); objectToReadInto.setIssueTimeCentury((short)(values[POSITION_PDS_ISSUE_TIME_CENTURY+headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK)); objectToReadInto.setIdentificationOfSubCentre((short)(values[POSITION_PDS_IDENTIFICATION_OF_SUBCENTRE+headerOffSet] & BytesToPrimitiveHelper.BYTE_MASK)); objectToReadInto.setDecimalScaleFactor(BytesToPrimitiveHelper.bytesToInteger(values[POSITION_PDS_DECIMAL_SCALE_FACTOR_1+headerOffSet], values[POSITION_PDS_DECIMAL_SCALE_FACTOR_2+headerOffSet])); return objectToReadInto; } }
package com.itanelse.mobileguard.activities; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.os.Handler; import android.text.TextUtils; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.ScaleAnimation; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.itanelse.mobileguard.R; import com.itanelse.mobileguard.dao.BlackDao; import com.itanelse.mobileguard.domain.BlackBean; import com.itanelse.mobileguard.domain.BlackTable; import com.itanelse.mobileguard.utils.MyConstants; public class TelSmsSafeActivity extends Activity { protected static final int LOADING = 1;// 正在加载数据 protected static final int FINISH = 2;// 数据加载完成 private ListView lv_safenumbers; private Button bt_addSafeNumber; private TextView tv_nodata; private ProgressBar pb_loading; private BlackDao dao;// 黑名单的数据封装对象 private MyAdapter adapter; private final int MOREDATASCOUNTS = 7;// 分批加载的数据个数 private List<BlackBean> moreDatas; private PopupWindow pw; private View contentView; private ScaleAnimation sa; // 存放黑名单数据的容器 private List<BlackBean> datas = new ArrayList<BlackBean>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initView(); initData(); initEvent();// 初始化事件 initPopupWindow();// 弹出窗体,功能:让用户可以从联系人,电话记录,短信记录中添加黑名单数据 } private void showPopupWindow() { if (pw != null && pw.isShowing()) { pw.dismiss();// 关闭 } else { int[] location = new int[2]; // 获取添加按钮的坐标 bt_addSafeNumber.getLocationInWindow(location); // 显示动画 contentView.startAnimation(sa); // 设置右上角对齐 pw.showAtLocation(bt_addSafeNumber, Gravity.RIGHT | Gravity.TOP, location[0] - (getWindowManager().getDefaultDisplay() .getWidth() - bt_addSafeNumber.getWidth()), location[1] + bt_addSafeNumber.getHeight()); } } private void closePopupWindow() { if (pw != null && pw.isShowing()) { pw.dismiss();// 关闭 } } private void initPopupWindow() { // 弹出窗体显示的布局 contentView = View.inflate(getApplicationContext(), R.layout.popup_blacknumber_item, null); // 手动添加 TextView tv_shoudong = (TextView) contentView .findViewById(R.id.tv_popup_black_shoudong); // 联系人添加 TextView tv_contact = (TextView) contentView .findViewById(R.id.tv_popup_black_contacts); // 电话添加 TextView tv_phonelog = (TextView) contentView .findViewById(R.id.tv_popup_black_phonelog); // 短信添加 TextView tv_smslog = (TextView) contentView .findViewById(R.id.tv_popup_black_smslog); View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.tv_popup_black_contacts:// 从联系人导入 // System.out.println("从联系人导入"); { Intent intent = new Intent(TelSmsSafeActivity.this, FriendsActivity.class); // 启动联系人的界面,并获取结果 startActivityForResult(intent, 1); } break; case R.id.tv_popup_black_phonelog:// 从电话日志导入 System.out.println("从电话日志导入"); { Intent intent = new Intent(TelSmsSafeActivity.this, CalllogsActivity.class); // 启动联系人的界面,并获取结果 startActivityForResult(intent, 1); } break; case R.id.tv_popup_black_shoudong:// 手动导入 // System.out.println("手动导入"); showInputBlacknumberDialog(""); break; case R.id.tv_popup_black_smslog:// 从短信导入 System.out.println("从短信导入"); Intent intent = new Intent(TelSmsSafeActivity.this, SmslogsActivity.class); // 启动联系人的界面,并获取结果 startActivityForResult(intent, 1); break; default: break; } // 关闭popupwindow closePopupWindow(); } }; // 给四个组件添加事件 tv_smslog.setOnClickListener(listener); tv_contact.setOnClickListener(listener); tv_phonelog.setOnClickListener(listener); tv_shoudong.setOnClickListener(listener); pw = new PopupWindow(contentView, -2, -2); // 显示动画要有背景 pw.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); sa = new ScaleAnimation(1, 1, 0, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0f); sa.setDuration(1000); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // 获取联系人,电话记录,短信记录等的电话 if (data != null) { // 用户点击条目获取结果 String phone = data.getStringExtra(MyConstants.SAFENUMBER); // 显示输入黑名单的对话框 showInputBlacknumberDialog(phone); } else { // 用户点击返回键 事件处理 } super.onActivityResult(requestCode, resultCode, data); } /** * 手动导入 */ protected void showInputBlacknumberDialog(String phone) { AlertDialog.Builder ab = new AlertDialog.Builder(this); View view = View.inflate(getApplicationContext(), R.layout.dialog_addblacknumber, null); // 黑名单号码编辑框 final EditText et_blackNumber = (EditText) view .findViewById(R.id.et_telsmssafe_blacknumber); // 设置初始的黑名单号码 et_blackNumber.setText(phone); // 短信拦截复选框 final CheckBox cb_sms = (CheckBox) view .findViewById(R.id.cb_telsmssafe_smsmode); // 短信拦截复选框 final CheckBox cb_phone = (CheckBox) view .findViewById(R.id.cb_telsmssafe_phonemode); // 添加黑名单号码按钮 Button bt_add = (Button) view.findViewById(R.id.bt_telsmssafe_add); // 取消添加黑名单号码按钮 Button bt_cancel = (Button) view .findViewById(R.id.bt_telsmssafe_cancel); bt_cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); bt_add.setOnClickListener(new OnClickListener() { private MyAdapter myAdapter; @Override public void onClick(View v) { // 添加黑名单数据 String phone = et_blackNumber.getText().toString().trim(); if (TextUtils.isEmpty(phone)) { Toast.makeText(getApplicationContext(), "黑名单号码不能为空", 1) .show(); return; } if (!cb_phone.isChecked() && !cb_sms.isChecked()) { // 两个拦截都没选 Toast.makeText(getApplicationContext(), "至少选择一种拦截模式", 1) .show(); return; } int mode = 0; if (cb_phone.isChecked()) { mode |= BlackTable.TEL;// 设置电话拦截模式 } if (cb_sms.isChecked()) { mode |= BlackTable.SMS;// 设置电话拦截模式 } // dao.add(phone, mode);//添加数据到黑名单表中 // 界面看到用户新增的数据 BlackBean bean = new BlackBean(); bean.setMode(mode); bean.setPhone(phone); dao.add(bean);// 添加数据到黑名单表中 // 如果新增的数据已经存在 datas.remove(bean);// 该删除方法要靠equals和hashCode两个方法共同判断数据是否一致 datas.add(0, bean);// 添加数据到List中 myAdapter = new MyAdapter(); lv_safenumbers.setAdapter(myAdapter); dialog.dismiss(); // 有数据 // 隐藏progressbar pb_loading.setVisibility(View.GONE); // 显示listView lv_safenumbers.setVisibility(View.VISIBLE); // 隐藏没有数据 tv_nodata.setVisibility(View.GONE); } }); ab.setView(view); dialog = ab.create(); dialog.show();// 显示对话框 } private void initEvent() { // 给listview设置滑动时间 lv_safenumbers.setOnScrollListener(new OnScrollListener() { /* * (non-Javadoc) onScrollStateChanged 状态改变调用此方法 SCROLL_STATE_FLING: * 惯性滑动 SCROLL_STATE_IDLE: 滑动停止 SCROLL_STATE_TOUCH_SCROLL: 按住滑动 * 三种状态,每种状态改变都会触发此方法 * * @see * android.widget.AbsListView.OnScrollListener#onScrollStateChanged * (android.widget.AbsListView, int) */ @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // 监控静止状态SCROLL_STATE_IDLE // 当出现SCROLL_STATE_IDLE的状态时候,判断是否显示最后一条数据,如果显示最后一条数据,那就加载更多的数据 if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) { // 当出现SCROLL_STATE_IDLE的状态时候 // 判断是否显示最后一条数据,如果显示最后一条数据,那就加载更多的数据 // 获取最后显示的数据位置 int lastVisiblePosition = lv_safenumbers .getLastVisiblePosition(); if (lastVisiblePosition == datas.size() - 1) { // 加载更多的数据 initData(); } } } /* * (non-Javadoc) onScroll 按住滑动触发事件 * * @see * android.widget.AbsListView.OnScrollListener#onScroll(android. * widget.AbsListView, int, int, int) */ @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // TODO Auto-generated method stub } }); } private Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case LOADING:// 正在加载数据 // 显示progressbar pb_loading.setVisibility(View.VISIBLE); // 隐藏listView lv_safenumbers.setVisibility(View.GONE); // 隐藏没有数据 tv_nodata.setVisibility(View.GONE); break; case FINISH: // 数据加载完成,判断是否有数据 if (moreDatas.size() != 0) { // 有数据 // 隐藏progressbar pb_loading.setVisibility(View.GONE); // 显示listView lv_safenumbers.setVisibility(View.VISIBLE); // 隐藏没有数据 tv_nodata.setVisibility(View.GONE); adapter.notifyDataSetChanged(); } else { if (datas.size() != 0) {// 分批加载数据,没有更多数据 Toast.makeText(getApplicationContext(), "没有更多数据", 1) .show(); // 隐藏progressbar pb_loading.setVisibility(View.GONE); // 显示listView lv_safenumbers.setVisibility(View.VISIBLE); // 隐藏没有数据 tv_nodata.setVisibility(View.GONE); return; } // 没有数据 // 显示没有数据 tv_nodata.setVisibility(View.VISIBLE); // 隐藏progressbar pb_loading.setVisibility(View.GONE); // 隐藏listView lv_safenumbers.setVisibility(View.GONE); } break; default: break; } }; }; private AlertDialog dialog; private class MyAdapter extends BaseAdapter { private int size; @Override public int getCount() { // TODO Auto-generated method stub size = datas.size(); if (size == 0) { // 显示没有数据 // 没有数据 tv_nodata.setVisibility(View.VISIBLE); // 隐藏progressbar pb_loading.setVisibility(View.GONE); // 隐藏listView lv_safenumbers.setVisibility(View.GONE); return size; } else { // 显示数据 return size; } } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ItemView itemView = null;// 声明组件封装对象 初始为null if (convertView == null) { convertView = View.inflate(getApplicationContext(), R.layout.item_telsmssafe_listview, null); itemView = new ItemView(); itemView.tv_phone = (TextView) convertView .findViewById(R.id.tv_telsmssafe_listview_item_number); itemView.tv_mode = (TextView) convertView .findViewById(R.id.tv_telsmssafe_listview_item_mode); itemView.iv_delete = (ImageView) convertView .findViewById(R.id.iv_telsmssafe_listview_item_delete); // 设置标记给convertView convertView.setTag(itemView); } else { itemView = (ItemView) convertView.getTag(); } // 获取当前位置的数据 final BlackBean bean = datas.get(position); // 显示黑名单号码 itemView.tv_phone.setText(bean.getPhone()); // 拦截模式进行判断,设置黑名单模式 switch (bean.getMode()) { case BlackTable.SMS: itemView.tv_mode.setText("短信拦截"); break; case BlackTable.TEL: itemView.tv_mode.setText("电话拦截"); break; case BlackTable.ALL: itemView.tv_mode.setText("全部拦截"); break; default: break; } // 设置删除数据的事件 itemView.iv_delete.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder ab = new AlertDialog.Builder( TelSmsSafeActivity.this); ab.setTitle("注意"); ab.setMessage("是否真的删除该数据?"); ab.setPositiveButton("真删", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 从数据库中删除当前数据 dao.delete(bean.getPhone());// 取出当前行数据里的黑名单号码 // 删除容器中对应的数据 datas.remove(position);// 20的position为19 if (datas.size() < 7) { initData();// 分批加载更多的数据 } else { // 通知界面更新数据,让用户看到删除数据不存在 adapter.notifyDataSetChanged();// 只是让listview // 重新去当前显示位置的数据 } } }); ab.setNegativeButton("点错了", null);// 自动关闭对话框 ab.show(); } }); return convertView; } } private class ItemView { // 显示黑名单号码 TextView tv_phone; // 显示黑名单号码拦截模式 TextView tv_mode; // 删除黑名单数据的 按钮 ImageView iv_delete; } /** * 初始化数据 加载更多数据 */ private void initData() { // 从db中取黑名单数据,子线程取 new Thread() { public void run() { // 取数据之前,发个消息显示正在加载数据的进度条 mHandler.obtainMessage(LOADING).sendToTarget(); moreDatas = dao.getMoreDatas(MOREDATASCOUNTS, datas.size()); datas.addAll(moreDatas);// 把一个容器的所有数据加进来 // 取完数据,发个消息告诉数据显加载已经完成 mHandler.obtainMessage(FINISH).sendToTarget(); }; }.start(); } /** * 添加黑名单号码 * * @param v */ public void addBlackNumber(View v) { // showInputBlacknumberDialog(); showPopupWindow(); } /** * 初始化界面 */ private void initView() { setContentView(R.layout.activity_telsmssafe); // 显示安全号码listview lv_safenumbers = (ListView) findViewById(R.id.lv_telsms_safenumbers); // 添加黑名单数据的按钮 bt_addSafeNumber = (Button) findViewById(R.id.bt_telsms_addsafenumber); // 没有数据显示的文本 tv_nodata = (TextView) findViewById(R.id.tv_telsms_nodata); // 正在加载数据的进度 pb_loading = (ProgressBar) findViewById(R.id.pb_telsms_loading); // 黑名单的业务对象 dao = new BlackDao(getApplicationContext()); // 给Listview设置适配器,取适配器的数据显示 // 首先 调用adapter的getCount方法来获取多少条数据,如果为0,不显示任何数据,否则调用getView方法依次取出显示位置的数据 adapter = new MyAdapter(); lv_safenumbers.setAdapter(adapter); } }
/** * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.ai.platform.modules.sys.web; import javax.servlet.http.HttpServletRequest; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.ai.platform.common.web.BaseController; /** * 标签Controller * @author ThinkGem * @version 2013-3-23 */ @Controller @RequestMapping(value = "${adminPath}/tag") public class TagController extends BaseController { /** * 树结构选择标签(treeselect.tag) */ @RequiresPermissions("user") @RequestMapping(value = "treeselect") public String treeselect(HttpServletRequest request, Model model) { model.addAttribute("url", request.getParameter("url")); // 树结构数据URL model.addAttribute("extId", request.getParameter("extId")); // 排除的编号ID model.addAttribute("checked", request.getParameter("checked")); // 是否可复选 model.addAttribute("selectIds", request.getParameter("selectIds")); // 指定默认选中的ID model.addAttribute("isAll", request.getParameter("isAll")); // 是否读取全部数据,不进行权限过滤 model.addAttribute("module", request.getParameter("module")); // 过滤栏目模型(仅针对CMS的Category树) return "modules/sys/tagTreeselect"; } /** * 人员树结构选择标签(usertree.tag) */ @RequiresPermissions("user") @RequestMapping(value = "usertree") public String usertree(HttpServletRequest request, Model model) { model.addAttribute("url", request.getParameter("url")); // 树结构数据URL model.addAttribute("extId", request.getParameter("extId")); // 排除的编号ID model.addAttribute("checked", request.getParameter("checked")); // 是否可复选 model.addAttribute("selectIds", request.getParameter("selectIds")); // 指定默认选中的ID model.addAttribute("isAll", request.getParameter("isAll")); // 是否读取全部数据,不进行权限过滤 model.addAttribute("module", request.getParameter("module")); // 过滤栏目模型(仅针对CMS的Category树) return "modules/sys/tagTreeuser"; } /** * 地区树结构选择标签(treeselect.tag) */ @RequiresPermissions("user") @RequestMapping(value = "treeasync") public String treeasync(HttpServletRequest request, Model model) { model.addAttribute("url", request.getParameter("url")); // 树结构数据URL model.addAttribute("extId", request.getParameter("extId")); // 排除的编号ID model.addAttribute("checked", request.getParameter("checked")); // 是否可复选 model.addAttribute("selectIds", request.getParameter("selectIds")); // 指定默认选中的ID model.addAttribute("isAll", request.getParameter("isAll")); // 是否读取全部数据,不进行权限过滤 model.addAttribute("module", request.getParameter("module")); // 过滤栏目模型(仅针对CMS的Category树) return "modules/sys/tagTreeAsync"; } /** * 图标选择标签(iconselect.tag) */ @RequiresPermissions("user") @RequestMapping(value = "iconselect") public String iconselect(HttpServletRequest request, Model model) { model.addAttribute("value", request.getParameter("value")); return "modules/sys/tagIconselect"; } }
/** * generated by Xtext 2.16.0 */ package in.handyman.dsl.impl; import in.handyman.dsl.Abort; import in.handyman.dsl.Action; import in.handyman.dsl.Callprocess; import in.handyman.dsl.Catch; import in.handyman.dsl.Checksum; import in.handyman.dsl.Copydata; import in.handyman.dsl.DeleteFolder; import in.handyman.dsl.DeleteSql; import in.handyman.dsl.Doozle; import in.handyman.dsl.DropSql; import in.handyman.dsl.Dropfile; import in.handyman.dsl.DslFactory; import in.handyman.dsl.DslPackage; import in.handyman.dsl.ExecJava; import in.handyman.dsl.Expression; import in.handyman.dsl.FTP; import in.handyman.dsl.Fetch; import in.handyman.dsl.Finally; import in.handyman.dsl.Forkprocess; import in.handyman.dsl.InsertSql; import in.handyman.dsl.JsonDeserialize; import in.handyman.dsl.JsonTransform; import in.handyman.dsl.ListFiles; import in.handyman.dsl.LoadCsv; import in.handyman.dsl.Mongo2Db; import in.handyman.dsl.Python; import in.handyman.dsl.Rest; import in.handyman.dsl.RestApi; import in.handyman.dsl.RestPart; import in.handyman.dsl.SendEMail; import in.handyman.dsl.Terminal; import in.handyman.dsl.Transform; import in.handyman.dsl.TruncateSql; import in.handyman.dsl.Try; import in.handyman.dsl.Unzip; import in.handyman.dsl.UpdateSql; import in.handyman.dsl.WriteCsv; import in.handyman.dsl.Zip; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.impl.EFactoryImpl; import org.eclipse.emf.ecore.plugin.EcorePlugin; /** * <!-- begin-user-doc --> * An implementation of the model <b>Factory</b>. * <!-- end-user-doc --> * @generated */ public class DslFactoryImpl extends EFactoryImpl implements DslFactory { /** * Creates the default factory implementation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static DslFactory init() { try { DslFactory theDslFactory = (DslFactory)EPackage.Registry.INSTANCE.getEFactory(DslPackage.eNS_URI); if (theDslFactory != null) { return theDslFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new DslFactoryImpl(); } /** * Creates an instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DslFactoryImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case DslPackage.PROCESS: return createProcess(); case DslPackage.TRY: return createTry(); case DslPackage.FINALLY: return createFinally(); case DslPackage.CATCH: return createCatch(); case DslPackage.ACTION: return createAction(); case DslPackage.SEND_EMAIL: return createSendEMail(); case DslPackage.DELETE_FOLDER: return createDeleteFolder(); case DslPackage.TERMINAL: return createTerminal(); case DslPackage.EXEC_JAVA: return createExecJava(); case DslPackage.ABORT: return createAbort(); case DslPackage.DROPFILE: return createDropfile(); case DslPackage.DOOZLE: return createDoozle(); case DslPackage.FETCH: return createFetch(); case DslPackage.CALLPROCESS: return createCallprocess(); case DslPackage.FORKPROCESS: return createForkprocess(); case DslPackage.COPYDATA: return createCopydata(); case DslPackage.WRITE_CSV: return createWriteCsv(); case DslPackage.LOAD_CSV: return createLoadCsv(); case DslPackage.TRANSFORM: return createTransform(); case DslPackage.DELETE_SQL: return createDeleteSql(); case DslPackage.UPDATE_SQL: return createUpdateSql(); case DslPackage.INSERT_SQL: return createInsertSql(); case DslPackage.TRUNCATE_SQL: return createTruncateSql(); case DslPackage.DROP_SQL: return createDropSql(); case DslPackage.LIST_FILES: return createListFiles(); case DslPackage.MONGO2_DB: return createMongo2Db(); case DslPackage.FTP: return createFTP(); case DslPackage.ZIP: return createZip(); case DslPackage.UNZIP: return createUnzip(); case DslPackage.CHECKSUM: return createChecksum(); case DslPackage.JSON_TRANSFORM: return createJsonTransform(); case DslPackage.JSON_DESERIALIZE: return createJsonDeserialize(); case DslPackage.REST_API: return createRestApi(); case DslPackage.PYTHON: return createPython(); case DslPackage.REST: return createRest(); case DslPackage.REST_PART: return createRestPart(); case DslPackage.EXPRESSION: return createExpression(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public in.handyman.dsl.Process createProcess() { ProcessImpl process = new ProcessImpl(); return process; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Try createTry() { TryImpl try_ = new TryImpl(); return try_; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Finally createFinally() { FinallyImpl finally_ = new FinallyImpl(); return finally_; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Catch createCatch() { CatchImpl catch_ = new CatchImpl(); return catch_; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Action createAction() { ActionImpl action = new ActionImpl(); return action; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SendEMail createSendEMail() { SendEMailImpl sendEMail = new SendEMailImpl(); return sendEMail; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DeleteFolder createDeleteFolder() { DeleteFolderImpl deleteFolder = new DeleteFolderImpl(); return deleteFolder; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Terminal createTerminal() { TerminalImpl terminal = new TerminalImpl(); return terminal; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ExecJava createExecJava() { ExecJavaImpl execJava = new ExecJavaImpl(); return execJava; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Abort createAbort() { AbortImpl abort = new AbortImpl(); return abort; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Dropfile createDropfile() { DropfileImpl dropfile = new DropfileImpl(); return dropfile; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Doozle createDoozle() { DoozleImpl doozle = new DoozleImpl(); return doozle; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Fetch createFetch() { FetchImpl fetch = new FetchImpl(); return fetch; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Callprocess createCallprocess() { CallprocessImpl callprocess = new CallprocessImpl(); return callprocess; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Forkprocess createForkprocess() { ForkprocessImpl forkprocess = new ForkprocessImpl(); return forkprocess; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Copydata createCopydata() { CopydataImpl copydata = new CopydataImpl(); return copydata; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public WriteCsv createWriteCsv() { WriteCsvImpl writeCsv = new WriteCsvImpl(); return writeCsv; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LoadCsv createLoadCsv() { LoadCsvImpl loadCsv = new LoadCsvImpl(); return loadCsv; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Transform createTransform() { TransformImpl transform = new TransformImpl(); return transform; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DeleteSql createDeleteSql() { DeleteSqlImpl deleteSql = new DeleteSqlImpl(); return deleteSql; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public UpdateSql createUpdateSql() { UpdateSqlImpl updateSql = new UpdateSqlImpl(); return updateSql; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public InsertSql createInsertSql() { InsertSqlImpl insertSql = new InsertSqlImpl(); return insertSql; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public TruncateSql createTruncateSql() { TruncateSqlImpl truncateSql = new TruncateSqlImpl(); return truncateSql; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DropSql createDropSql() { DropSqlImpl dropSql = new DropSqlImpl(); return dropSql; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ListFiles createListFiles() { ListFilesImpl listFiles = new ListFilesImpl(); return listFiles; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Mongo2Db createMongo2Db() { Mongo2DbImpl mongo2Db = new Mongo2DbImpl(); return mongo2Db; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public FTP createFTP() { FTPImpl ftp = new FTPImpl(); return ftp; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Zip createZip() { ZipImpl zip = new ZipImpl(); return zip; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Unzip createUnzip() { UnzipImpl unzip = new UnzipImpl(); return unzip; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Checksum createChecksum() { ChecksumImpl checksum = new ChecksumImpl(); return checksum; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public JsonTransform createJsonTransform() { JsonTransformImpl jsonTransform = new JsonTransformImpl(); return jsonTransform; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public JsonDeserialize createJsonDeserialize() { JsonDeserializeImpl jsonDeserialize = new JsonDeserializeImpl(); return jsonDeserialize; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public RestApi createRestApi() { RestApiImpl restApi = new RestApiImpl(); return restApi; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Python createPython() { PythonImpl python = new PythonImpl(); return python; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Rest createRest() { RestImpl rest = new RestImpl(); return rest; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public RestPart createRestPart() { RestPartImpl restPart = new RestPartImpl(); return restPart; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Expression createExpression() { ExpressionImpl expression = new ExpressionImpl(); return expression; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DslPackage getDslPackage() { return (DslPackage)getEPackage(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @deprecated * @generated */ @Deprecated public static DslPackage getPackage() { return DslPackage.eINSTANCE; } } //DslFactoryImpl
package dswork.web; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 扩展Cookie */ public class MyCookie { private HttpServletResponse response; private HttpServletRequest request; /** * 初始化cookie * @param request HttpServletRequest * @param response HttpServletResponse */ public MyCookie(HttpServletRequest request, HttpServletResponse response) { this.request = request; this.response = response; } /** * 往客户端写入Cookie,当页面关闭时删除cookie,当前应用所有页面有效 * @param name cookie参数名 * @param value cookie参数值 */ public void addCookie(String name, String value) { addCookie(name, value, -1, "/", null, false, false); } /** * 往客户端写入Cookie,当前应用所有页面有效 * @param name cookie参数名 * @param value cookie参数值 * @param maxAge 有效时间,int(单位秒),0:删除Cookie,-1:页面关闭时删除cookie */ public void addCookie(String name, String value, int maxAge) { addCookie(name, value, maxAge, "/", null, false, false); } /** * 往客户端写入Cookie * @param name cookie参数名 * @param value cookie参数值 * @param maxAge 有效时间,int(单位秒),0:删除Cookie,-1:页面关闭时删除cookie * @param path 与cookie一起传输的虚拟路径,即有效范围 */ public void addCookie(String name, String value, int maxAge, String path) { addCookie(name, value, maxAge, path, null, false, false); } /** * 往客户端写入Cookie * @param name cookie参数名 * @param value cookie参数值 * @param maxAge 有效时间,int(单位秒),0:删除Cookie,-1:页面关闭时删除cookie * @param path 与cookie一起传输的虚拟路径 * @param domain 与cookie关联的域 */ public void addCookie(String name, String value, int maxAge, String path, String domain) { addCookie(name, value, maxAge, path, domain, false, false); } /** * 往客户端写入Cookie * @param name cookie参数名 * @param value cookie参数值 * @param maxAge 有效时间,int(单位秒),0:删除Cookie,-1:页面关闭时删除cookie * @param path 与cookie一起传输的虚拟路径 * @param domain 与cookie关联的域 * @param isSecure 是否在https请求时才进行传输 * @param isHttpOnly 是否只能通过http访问 */ public void addCookie(String name, String value, int maxAge, String path, String domain, boolean isSecure, boolean isHttpOnly) { Cookie cookie = new Cookie(name, value); cookie.setMaxAge(maxAge); cookie.setPath(path); if(domain != null) { cookie.setDomain(domain); } cookie.setSecure(isSecure); try { Cookie.class.getMethod("setHttpOnly", boolean.class); cookie.setHttpOnly(isHttpOnly); } catch(Exception e) { System.out.println("MyCookie ignore setHttpOnly Method"); } response.addCookie(cookie); } /** * 删除cookie * @param name cookie参数名 */ public void delCookie(String name) { // Cookie cookies[] = request.getCookies(); // if(cookies != null) // { // Cookie cookie = null; // for(int i = 0; i < cookies.length; i++) // { // cookie = cookies[i]; // if(cookie.getName().equals(name)) // { // addCookie(name, "", 0, cookie.getPath(), cookie.getDomain());// 按原cookie属性删除 // } // } // } addCookie(name, "", 0, "/", null); } /** * 根据cookie名称取得参数值 * @param name cookie参数名 * @return 存在返回String,不存在返回null */ public String getValue(String name) { Cookie cookies[] = request.getCookies(); String value = null; if(cookies != null) { Cookie cookie = null; for(int i = 0; i < cookies.length; i++) { cookie = cookies[i]; if(cookie.getName().equals(name)) { value = cookie.getValue(); break; } } } return value; } /** * 根据Cookie参数名判断Cookie是否存在该值 * @param name cookie参数名 * @return 存在返回true,不存在返回false */ public boolean isExist(String name) { Cookie cookies[] = request.getCookies(); if(cookies == null) { return false; } boolean isExist = false; for(int i = 0; i < cookies.length; i++) { if(cookies[i].getName().equals(name)) { isExist = true; break; } } return isExist; } }
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.config.subscription; /** * Thrown when {@link ConfigSubscriber} is closed * * @author bjorncs * @deprecated Will be removed in Vespa 8. Only for internal use. */ @Deprecated(forRemoval = true, since = "7") public class SubscriberClosedException extends RuntimeException {}
package com.example.android.sunshine.app; import android.annotation.TargetApi; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; public class SettingsActivity extends PreferenceActivity implements Preference.OnPreferenceChangeListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Add 'general' preferences, defined in the XML file addPreferencesFromResource(R.xml.pref_general); // For all preferences, attach an OnPreferenceChangeListener so the UI summary can be // updated when the preference changes. bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key))); bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_units_key))); } private void bindPreferenceSummaryToValue(Preference preference) { // Set the listener to watch for value changes. preference.setOnPreferenceChangeListener(this); onPreferenceChange(preference, PreferenceManager .getDefaultSharedPreferences(preference.getContext()) .getString(preference.getKey(), "")); } @Override public boolean onPreferenceChange(Preference preference, Object value) { String stringValue = value.toString(); if (preference instanceof ListPreference) { ListPreference listPreference = (ListPreference) preference; int prefIndex = listPreference.findIndexOfValue(stringValue); if (prefIndex >= 0) { preference.setSummary(listPreference.getEntries()[prefIndex]); } } else { // For other preferences, set the summary to the value's simple string representation. preference.setSummary(stringValue); } return true; } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public Intent getParentActivityIntent() { return super.getParentActivityIntent().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); } }
/* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.j2objc.gen; import com.google.common.collect.Lists; import com.google.devtools.j2objc.GenerationTest; import com.google.devtools.j2objc.Options; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.Map; /** * Tests for {@link ObjectiveCHeaderGenerator}. * * @author Tom Ball */ public class ObjectiveCHeaderGeneratorTest extends GenerationTest { @Override protected void tearDown() throws Exception { Options.resetDeprecatedDeclarations(); Options.setDocCommentsEnabled(false); super.tearDown(); } public void testInnerEnumWithPackage() throws IOException { String translation = translateSourceFile( "package mypackage;" + "public class Example { MyClass myclass = new MyClass(); }" + "enum Abcd { A, B, C; }" + "class MyClass {}", "Example", "mypackage/Example.h"); assertTranslation(translation, "@interface MypackageExample"); // enum declaration assertTranslation(translation, "typedef NS_ENUM(NSUInteger, MypackageAbcd) {"); assertTranslation(translation, "@interface MypackageAbcdEnum"); assertTranslation(translation, "@interface MypackageMyClass"); assertTranslation(translation, "MypackageMyClass *myclass_;"); } public void testTypeNameTranslation() throws IOException { String translation = translateSourceFile( "public class Example {}", "Example", "Example.h"); assertTranslation(translation, "@interface Example "); } public void testDeprecatedTypeNameTranslation() throws IOException { Options.enableDeprecatedDeclarations(); String translation = translateSourceFile( "public @Deprecated class Example {}", "Example", "Example.h"); assertTranslation(translation, "__attribute__((deprecated))\n@interface Example "); } public void testDeprecatedTypeNameTranslationIsTurnedOff() throws IOException { String translation = translateSourceFile( "public @Deprecated class Example {}", "Example", "Example.h"); assertFalse(translation.contains("__attribute__((deprecated))")); } public void testFullyQualifiedDeprecatedTypeNameTranslation() throws IOException { Options.enableDeprecatedDeclarations(); String translation = translateSourceFile( "public @java.lang.Deprecated class Example {}", "Example", "Example.h"); assertTranslation(translation, "__attribute__((deprecated))\n@interface Example "); } public void testPackageTypeNameTranslation() throws IOException { String translation = translateSourceFile( "package unit.test; public class Example {}", "Example", "unit/test/Example.h"); assertTranslation(translation, "@interface UnitTestExample "); } public void testPackageTypeNameTranslationWithInnerClass() throws IOException { String translation = translateSourceFile( "package unit.test; public class Example { class Inner {}}", "Example", "unit/test/Example.h"); assertTranslation(translation, "@interface UnitTestExample "); assertTranslation(translation, "Example_Inner"); assertTranslation(translation, "@interface UnitTestExample_Inner "); } public void testSuperclassTypeTranslation() throws IOException { String translation = translateSourceFile( "public class MyException extends Exception {}", "MyException", "MyException.h"); assertTranslation(translation, "@interface MyException : JavaLangException"); } public void testImplementsTypeTranslation() throws IOException { String translation = translateSourceFile( "import java.io.Serializable; public class Example implements Serializable {}", "Example", "Example.h"); assertTranslation(translation, "@interface Example : NSObject < JavaIoSerializable >"); } public void testImportTranslation() throws IOException { String translation = translateSourceFile( "public class MyException extends Exception { MyException(Throwable t) {super(t);}}", "MyException", "MyException.h"); assertTranslation(translation, "@class JavaLangThrowable;"); assertTranslation(translation, "#include \"java/lang/Exception.h\""); } public void testHeaderFileMapping() throws IOException { Options.setHeaderMappingFiles(Lists.newArrayList("testMappings.j2objc")); addSourceFile("package unit.mapping.custom; public class Test { }", "unit/mapping/custom/Test.java"); loadHeaderMappings(); String translation = translateSourceFile( "import unit.mapping.custom.Test; " + "public class MyTest extends Test { MyTest() {}}", "MyTest", "MyTest.h"); assertTranslation(translation, "#include \"my/mapping/custom/Test.h\""); } public void testHeaderDefaultFileMapping() throws IOException { addSourceFile("package unit.mapping; public class Test { }", "unit/mapping/Test.java"); loadHeaderMappings(); String translation = translateSourceFile( "import unit.mapping.Test; " + "public class MyTest extends Test { MyTest() {}}", "MyTest", "MyTest.h"); assertTranslation(translation, "#include \"my/mapping/Test.h\""); } public void testNoHeaderMapping() throws IOException { // Should be able to turn off header mappings by passing empty collection Options.setHeaderMappingFiles(Collections.<String>emptyList()); addSourceFile("package unit.mapping; public class Test { }", "unit/mapping/Test.java"); loadHeaderMappings(); String translation = translateSourceFile( "import unit.mapping.Test; " + "public class MyTest extends Test { MyTest() {}}", "MyTest", "MyTest.h"); assertTranslation(translation, "#include \"unit/mapping/Test.h\""); } public void testOutputHeaderFileMapping() throws IOException { Options.setHeaderMappingFiles(Lists.newArrayList("testMappings.j2objc")); Options.setOutputHeaderMappingFile(new File("path/to/Dummy")); Options.setPackageDirectories(Options.OutputStyleOption.SOURCE); addSourceFile("package unit.test; public class Dummy {}", "unit/test/Dummy.java"); addSourceFile( "package unit.test;" + "public class AnotherDummy extends Dummy { " + " public AnotherDummy() {}" + "}", "unit/test/AnotherDummy.java"); loadSourceFileHeaderMappings("unit/test/Dummy.java", "unit/test/AnotherDummy.java"); loadHeaderMappings(); String translation = translateSourceFile(getTranslatedFile("unit/test/AnotherDummy.java"), "AnotherDummy", "AnotherDummy.h"); assertTranslation(translation, "#include \"" + getTempDir() + "/unit/test/Dummy.h\""); Map<String, String> outputMapping = Options.getHeaderMappings(); assertEquals(getTempDir() + "/unit/test/AnotherDummy.h", outputMapping.get("unit.test.AnotherDummy")); assertEquals(getTempDir() + "/unit/test/Dummy.h", outputMapping.get("unit.test.Dummy")); assertEquals("my/mapping/custom/Test.h", outputMapping.get("unit.mapping.custom.Test")); } public void testOutputHeaderFileMappingWithMultipleClassesInOneHeader() throws IOException { Options.setHeaderMappingFiles(Lists.newArrayList("testMappings.j2objc")); Options.setOutputHeaderMappingFile(new File("path/to/Dummy")); Options.setPackageDirectories(Options.OutputStyleOption.SOURCE); addSourceFile("package unit.mapping.custom; public class Test { }", "unit/mapping/custom/Test.java"); addSourceFile("package unit.mapping.custom; public class AnotherTest { }", "unit/mapping/custom/AnotherTest.java"); addSourceFile( "package unit.test;" + "import unit.mapping.custom.Test;" + "public class Dummy extends Test { " + " public Dummy() {}" + "}", "unit/test/Dummy.java"); addSourceFile( "package unit.test;" + "import unit.mapping.custom.AnotherTest;" + "public class AnotherDummy extends AnotherTest { " + " public AnotherDummy() {}" + "}", "unit/test/AnotherDummy.java"); loadSourceFileHeaderMappings("unit/test/Dummy.java", "unit/test/AnotherDummy.java"); loadHeaderMappings(); String translationForDummy = translateSourceFile(getTranslatedFile("unit/test/Dummy.java"), "Dummy", "Dummy.h"); String translationForAnotherDummy = translateSourceFile( getTranslatedFile("unit/test/AnotherDummy.java"), "AnotherDummy", "AnotherDummy.h"); assertTranslation(translationForDummy, "#include \"my/mapping/custom/Test.h\""); assertTranslation(translationForAnotherDummy, "#include \"my/mapping/custom/Test.h\""); Map<String, String> outputMapping = Options.getHeaderMappings(); assertEquals(getTempDir() + "/unit/test/AnotherDummy.h", outputMapping.get("unit.test.AnotherDummy")); assertEquals(getTempDir() + "/unit/test/Dummy.h", outputMapping.get("unit.test.Dummy")); assertEquals("my/mapping/custom/Test.h", outputMapping.get("unit.mapping.custom.Test")); assertEquals("my/mapping/custom/Test.h", outputMapping.get("unit.mapping.custom.AnotherTest")); } public void testForwardDeclarationTranslation() throws IOException { String translation = translateSourceFile( "public class MyException extends Exception { MyException(Throwable t) {super(t);}}", "MyException", "MyException.h"); assertTranslation(translation, "@class JavaLangThrowable;"); } public void testInstanceVariableTranslation() throws IOException { String translation = translateSourceFile( "public class Example { Exception testException; }", "Example", "Example.h"); assertTranslation(translation, "JavaLangException *testException_;"); } public void testInterfaceTranslation() throws IOException { String translation = translateSourceFile( "package unit.test; public interface Example {}", "Example", "unit/test/Example.h"); assertTranslation(translation, "@protocol UnitTestExample"); } public void testDeprecatedInterfaceTranslation() throws IOException { Options.enableDeprecatedDeclarations(); String translation = translateSourceFile( "package unit.test; public @Deprecated interface Example {}", "Example", "unit/test/Example.h"); assertTranslation(translation, "__attribute__((deprecated))\n@protocol UnitTestExample"); } public void testInterfaceWithMethodTranslation() throws IOException { String translation = translateSourceFile( "package unit.test; public interface Example { Example getExample(); }", "Example", "unit/test/Example.h"); assertTranslation(translation, "(id<UnitTestExample>)getExample;"); } public void testInterfaceWithDeprecatedMethodTranslation() throws IOException { Options.enableDeprecatedDeclarations(); String translation = translateSourceFile( "package unit.test; public interface Example { @Deprecated Example getExample(); }", "Example", "unit/test/Example.h"); assertTranslation(translation, "- (id<UnitTestExample>)getExample __attribute__((deprecated));"); } public void testSuperInterfaceTranslation() throws IOException { String translation = translateSourceFile( "package unit.test; public interface Example extends Bar {} interface Bar {}", "Example", "unit/test/Example.h"); assertTranslation(translation, "@protocol UnitTestExample < UnitTestBar, NSObject, JavaObject >"); } public void testConstTranslation() throws IOException { String translation = translateSourceFile( "package unit.test; public class Example { public static final int FOO=1; }", "Example", "unit/test/Example.h"); assertTranslation(translation, "#define UnitTestExample_FOO 1"); assertFalse(translation.contains("initialize")); } public void testStaticVariableTranslation() throws IOException { String translation = translateSourceFile( "public class Example { public static java.util.Date today; }", "Example", "Example.h"); assertTranslatedLines(translation, "FOUNDATION_EXPORT JavaUtilDate *Example_today_;", "J2OBJC_STATIC_FIELD_GETTER(Example, today_, JavaUtilDate *)", "J2OBJC_STATIC_FIELD_SETTER(Example, today_, JavaUtilDate *)"); assertFalse(translation.contains("initialize")); assertFalse(translation.contains("dealloc")); } public void testStaticVariableWithInitTranslation() throws IOException { String translation = translateSourceFile( "public class Example { public static java.util.Date today = new java.util.Date(); }", "Example", "Example.h"); assertTranslatedLines(translation, "FOUNDATION_EXPORT JavaUtilDate *Example_today_;", "J2OBJC_STATIC_FIELD_GETTER(Example, today_, JavaUtilDate *)", "J2OBJC_STATIC_FIELD_SETTER(Example, today_, JavaUtilDate *)"); assertFalse(translation.contains("+ (void)initialize;")); assertFalse(translation.contains("dealloc")); } public void testInitMessageTranslation() throws IOException { String translation = translateSourceFile( "public class Example { void init() {} }", "Example", "Example.h"); assertTranslation(translation, "- (void)init__ OBJC_METHOD_FAMILY_NONE;"); } public void testInitializeMessageTranslation() throws IOException { String translation = translateSourceFile( "public class Example { void initialize() {} }", "Example", "Example.h"); assertTranslation(translation, "- (void)initialize__ OBJC_METHOD_FAMILY_NONE;"); } public void testToStringRenaming() throws IOException { String translation = translateSourceFile( "public class Example { public String toString() { return super.toString(); } }", "Example", "Example.h"); assertTranslation(translation, "- (NSString *)description;"); } public void testMultipleObjectDeclaration() throws IOException { String translation = translateSourceFile( "public class Example { String one, two, three; }", "Example", "Example.h"); assertTranslation(translation, "NSString *one_, *two_, *three_;"); } public void testMultiplePrimitiveDeclaration() throws IOException { String translation = translateSourceFile( "public class Example { int one, two, three; }", "Example", "Example.h"); assertTranslation(translation, "int one_, two_, three_;"); } public void testMultipleInterfaceDeclaration() throws IOException { String translation = translateSourceFile( "public class Example { Comparable one, two, three; }", "Example", "Example.h"); assertTranslation(translation, "id<JavaLangComparable> one_, two_, three_;"); } public void testMultipleClassDeclaration() throws IOException { String translation = translateSourceFile( "public class Example { Class<?> one, two, three; }", "Example", "Example.h"); assertTranslation(translation, "IOSClass *one_, *two_, *three_;"); } public void testInnerClassDeclaration() throws IOException { String translation = translateSourceFile( "public class Example { class Inner {} }", "Example", "Example.h"); assertTranslation(translation, "@interface Example_Inner : NSObject"); assertNotInTranslation(translation, "Example *this"); assertTranslation(translation, "- (instancetype)initWithExample:(Example *)outer$;"); } public void testInnerClassDeclarationWithOuterReference() throws IOException { String translation = translateSourceFile( "public class Example { int i; class Inner { void test() { int j = i; } } }", "Example", "Example.h"); assertTranslation(translation, "@interface Example_Inner : NSObject"); assertTranslation(translation, "- (instancetype)initWithExample:(Example *)outer$;"); translation = getTranslatedFile("Example.m"); assertTranslation(translation, "Example *this$0_;"); } public void testAnonymousClassDeclaration() throws IOException { String translation = translateSourceFile( "public class Example { Runnable run = new Runnable() { public void run() {} }; }", "Example", "Example.h"); assertTranslation(translation, "@interface Example_$1 : NSObject < JavaLangRunnable >"); assertTranslation(translation, "- (void)run;"); // Outer reference is not required. assertNotInTranslation(translation, "Example *this"); assertNotInTranslation(translation, "- (id)initWithExample:"); } public void testEnum() throws IOException { String translation = translateSourceFile( "public enum Color { RED, WHITE, BLUE }", "Color", "Color.h"); assertTranslatedLines(translation, "typedef NS_ENUM(NSUInteger, Color) {", " Color_RED = 0,", " Color_WHITE = 1,", " Color_BLUE = 2,", "};"); assertTranslation(translation, "@interface ColorEnum : JavaLangEnum < NSCopying > {"); assertTranslation(translation, "+ (IOSObjectArray *)values;"); assertTranslation(translation, "+ (ColorEnum *)valueOfWithNSString:(NSString *)name;"); assertTranslation(translation, "FOUNDATION_EXPORT ColorEnum *ColorEnum_values_[];"); assertTranslatedLines(translation, "#define ColorEnum_RED ColorEnum_values_[Color_RED]", "J2OBJC_ENUM_CONSTANT_GETTER(ColorEnum, RED)"); assertTranslatedLines(translation, "#define ColorEnum_WHITE ColorEnum_values_[Color_WHITE]", "J2OBJC_ENUM_CONSTANT_GETTER(ColorEnum, WHITE)"); assertTranslatedLines(translation, "#define ColorEnum_BLUE ColorEnum_values_[Color_BLUE]", "J2OBJC_ENUM_CONSTANT_GETTER(ColorEnum, BLUE)"); } public void testEnumWithParameters() throws IOException { String translation = translateSourceFile( "public enum Color { RED(0xff0000), WHITE(0xffffff), BLUE(0x0000ff); " + "private int rgb; private Color(int rgb) { this.rgb = rgb; } " + "public int getRgb() { return rgb; }}", "Color", "Color.h"); assertTranslation(translation, "@interface ColorEnum : JavaLangEnum"); translation = getTranslatedFile("Color.m"); assertTranslation(translation, "int rgb_;"); assertTranslatedLines(translation, "- (instancetype)initWithInt:(jint)rgb", "withNSString:(NSString *)__name", "withInt:(jint)__ordinal;"); } public void testEnumWithMultipleConstructors() throws IOException { String translation = translateSourceFile( "public enum Color { RED(0xff0000), WHITE(0xffffff, false), BLUE(0x0000ff); " + "private int rgb; private boolean primary;" + "private Color(int rgb, boolean primary) { this.rgb = rgb; this.primary = primary; } " + "private Color(int rgb) { this(rgb, true); } " + "public int getRgb() { return rgb; }" + "public boolean isPrimaryColor() { return primary; }}", "Color", "Color.h"); assertTranslation(translation, "@interface ColorEnum : JavaLangEnum"); translation = getTranslatedFile("Color.m"); assertTranslation(translation, "jboolean primary_;"); assertTranslatedLines(translation, "- (instancetype)initWithInt:(jint)rgb", "withNSString:(NSString *)__name", "withInt:(jint)__ordinal;"); assertTranslatedLines(translation, "- (instancetype)initWithInt:(jint)rgb", "withBoolean:(jboolean)primary", "withNSString:(NSString *)__name", "withInt:(jint)__ordinal;"); assertTranslation(translation, "[self initColorEnumWithInt:rgb withBoolean:YES withNSString:__name withInt:__ordinal]"); assertTranslatedLines(translation, "if (self = [super initWithNSString:__name withInt:__ordinal]) {", "self->rgb_ = rgb;", "self->primary_ = primary;"); } public void testArrayFieldDeclaration() throws IOException { String translation = translateSourceFile( "public class Example { char[] before; char after[]; }", "Example", "Example.h"); assertTranslation(translation, "IOSCharArray *before_;"); assertTranslation(translation, "IOSCharArray *after_;"); } public void testForwardDeclarationOfInnerType() throws IOException { String translation = translateSourceFile( "public class Example { Foo foo; class Foo {} }", "Example", "Example.h"); // Test that Foo is forward declared because Example contains a field of // type Foo and Foo is declared after Example. assertTranslation(translation, "@class Example_Foo;"); } public void testAnnotationGeneration() throws IOException { String translation = translateSourceFile( "package foo; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) " + "public @interface Compatible { boolean fooable() default false; }", "Compatible", "foo/Compatible.h"); // Test that the annotation was declared as a protocol and a value class. assertTranslation(translation, "@protocol FooCompatible < JavaLangAnnotationAnnotation >"); assertTranslation(translation, "@interface FooCompatible : NSObject < FooCompatible >"); // Verify that the value is defined as a property instead of a method. assertTranslation(translation, "@private\n jboolean fooable_;"); assertTranslation(translation, "@property (readonly) jboolean fooable;"); // Verify default value accessor is generated for property. assertTranslation(translation, "+ (jboolean)fooableDefault;"); // Check that constructor was created with the property as parameter. assertTranslation(translation, "- (instancetype)initWithFooable:(jboolean)fooable__;"); } public void testCharacterEdgeValues() throws IOException { String translation = translateSourceFile( "public class Test { " + " public static final char MIN = 0; " + " public static final char MAX = '\uffff'; " + "}", "Test", "Test.h"); assertTranslation(translation, "x00"); assertTranslation(translation, "0xffff"); } public void testEnumNaming() throws IOException { String translation = translateSourceFile( "public enum MyEnum { ONE, TWO, THREE }", "MyEnum", "MyEnum.h"); assertTranslation(translation, "typedef NS_ENUM(NSUInteger, MyEnum) {"); assertTranslation(translation, "@interface MyEnumEnum : JavaLangEnum"); assertTranslation(translation, "FOUNDATION_EXPORT MyEnumEnum *MyEnumEnum_values_[];"); assertTranslation(translation, "#define MyEnumEnum_ONE MyEnumEnum_values_[MyEnum_ONE]"); } public void testNoImportForMappedTypes() throws IOException { String translation = translateSourceFile( "public class Test extends Object implements Cloneable { " + " public String toString() { return \"\"; }" + " public Class<?> myClass() { return getClass(); }}", "Test", "Test.h"); assertFalse(translation.contains("#include \"java/lang/Class.h\"")); assertFalse(translation.contains("#include \"java/lang/Cloneable.h\"")); assertFalse(translation.contains("#include \"java/lang/Object.h\"")); assertFalse(translation.contains("#include \"java/lang/String.h\"")); assertFalse(translation.contains("#include \"Class.h\"")); assertFalse(translation.contains("#include \"NSCopying.h\"")); assertFalse(translation.contains("#include \"NSObject.h\"")); assertFalse(translation.contains("#include \"NSString.h\"")); assertTranslation(translation, "NSCopying"); } public void testAnonymousConcreteSubclassOfGenericAbstractType() throws IOException { String translation = translateSourceFile( "public class Test {" + " interface FooInterface<T> { public void foo1(T t); public void foo2(); }" + " abstract static class Foo<T> implements FooInterface<T> { public void foo2() { } }" + " Foo<Integer> foo = new Foo<Integer>() {" + " public void foo1(Integer i) { } }; }", "Test", "Test.h"); assertTranslation(translation, "foo1WithId:(JavaLangInteger *)i"); } // Verify that an empty Java enum doesn't define an empty C enum, // which is illegal. public void testEmptyEnum() throws IOException { String header = translateSourceFile("public class A { enum Foo {} }", "A", "A.h"); String impl = getTranslatedFile("A.m"); // Verify there's no C enum. assertFalse(header.contains("typedef enum {\n} A_Foo;")); // Verify there's still a Java enum type. assertTranslation(header, "@interface A_FooEnum : JavaLangEnum"); assertTranslation(impl, "@implementation A_FooEnum"); } public void testEnumWithInterfaces() throws IOException { String translation = translateSourceFile( "public class A { interface I {} " + "enum Foo implements I, Runnable, Cloneable { " + "A, B, C; public void run() {}}}", "A", "A.h"); assertTranslation(translation, "@interface A_FooEnum : JavaLangEnum < NSCopying, A_I, JavaLangRunnable >"); assertTranslation(translation, "#include \"java/lang/Runnable.h\""); } public void testExternalNativeMethod() throws IOException { String translation = translateSourceFile( "package foo; class Example { native void external(String s); " + " void test(String str) { external(str); }}", "Example", "foo/Example.h"); // Verify external() and test() are in main interface. assertTranslation(translation, "- (void)externalWithNSString:(NSString *)s;"); assertTranslation(translation, "- (void)testWithNSString:(NSString *)str;"); // Verify category method is invoked. translation = getTranslatedFile("foo/Example.m"); assertTranslation(translation, "@implementation FooExample\n"); assertTranslation(translation, "void FooExample_externalWithNSString_(FooExample *self, NSString *s);"); assertTranslatedLines(translation, "- (void)externalWithNSString:(NSString *)s {", " FooExample_externalWithNSString_(self, s);", "}"); assertTranslation(translation, "[self externalWithNSString:str];"); } public void testPropertiesOfTypeWeakOuter() throws IOException { String sourceContent = " import com.google.j2objc.annotations.Weak;" + "import com.google.j2objc.annotations.WeakOuter;" + "public class FooBar {" + " @Weak private Internal fieldBar;" + " private Internal fieldFoo;" + " @WeakOuter" + " private class Internal {" + " }" + "}"; String translation = translateSourceFile(sourceContent, "FooBar", "FooBar.m"); assertTranslatedLines(translation, "__weak FooBar_Internal *fieldBar_;", "FooBar_Internal *fieldFoo_;"); } public void testAddIgnoreDeprecationWarningsPragmaIfDeprecatedDeclarationsIsEnabled() throws IOException { Options.enableDeprecatedDeclarations(); String sourceContent = "class Test {}"; String translation = translateSourceFile(sourceContent, "FooBar", "FooBar.h"); assertTranslation(translation, "#pragma clang diagnostic push"); assertTranslation(translation, "#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\""); assertTranslation(translation, "#pragma clang diagnostic pop"); } public void testDoNotAddIgnoreDeprecationWarningsPragmaIfDeprecatedDeclarationsIsDisabled() throws IOException { String sourceContent = "class Test {}"; String translation = translateSourceFile(sourceContent, "FooBar", "FooBar.h"); assertNotInTranslation(translation, "#pragma clang diagnostic push"); assertNotInTranslation(translation, "#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\""); assertNotInTranslation(translation, "#pragma clang diagnostic pop"); } public void testInnerAnnotationGeneration() throws IOException { String source = "import java.lang.annotation.*; public abstract class Test { " + "@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) " + "public @interface Initialize {}}"; String translation = translateSourceFile(source, "Test", "Test.h"); assertTranslation(translation, "@protocol Test_Initialize < JavaLangAnnotationAnnotation >"); assertTranslation(translation, "@interface Test_Initialize : NSObject < Test_Initialize >"); } public void testFieldSetterGeneration() throws IOException { String translation = translateSourceFile( "import com.google.j2objc.annotations.Weak;" + "class Test { Object o; @Weak String s; static Integer i; }", "Test", "Test.h"); assertTranslation(translation, "J2OBJC_FIELD_SETTER(Test, o_, id)"); // Make sure the @Weak and static fields don't generate setters. assertOccurrences(translation, "J2OBJC_FIELD_SETTER", 1); } public void testEnumWithNameAndOrdinalParameters() throws IOException { String translation = translateSourceFile( "public enum Test { FOO(\"foo\", 3), BAR(\"bar\", 5); " + "private String name; private int ordinal; " + "private Test(String name, int ordinal) { this.name = name; this.ordinal = ordinal; }" + "public String getName() { return name; }}", "Test", "Test.h"); assertTranslation(translation, "@interface TestEnum : JavaLangEnum"); translation = getTranslatedFile("Test.m"); assertTranslation(translation, "NSString *name_Test_;"); assertTranslation(translation, "int ordinal_Test_;"); assertTranslatedLines(translation, "- (instancetype)initWithNSString:(NSString *)name", "withInt:(jint)ordinal", "withNSString:(NSString *)__name", "withInt:(jint)__ordinal;"); } public void testDeprecatedEnumType() throws IOException { Options.enableDeprecatedDeclarations(); String translation = translateSourceFile( "@Deprecated public enum Test { A, B }", "Test", "Test.h"); assertTranslation(translation, "__attribute__((deprecated))\n@interface TestEnum"); } public void testLongConstants() throws IOException { String translation = translateSourceFile( "class Test { static final long FOO = 123; }", "Test", "Test.h"); assertTranslation(translation, "123LL"); } public void testDocComments() throws IOException { Options.setDocCommentsEnabled(true); String translation = translateSourceFile( "/** Class javadoc for {@link Test}. */ class Test { \n" + "/** Field javadoc. */\n" + "int i;" + "/** Method javadoc.\n" + " * @param foo Unused.\n" + " * @return always false.\n" + " */\n" + "boolean test(int foo) { return false; } }", "Test", "Test.h"); assertTranslation(translation, "@brief Class javadoc for Test ."); assertTranslation(translation, "@brief Field javadoc."); assertTranslatedLines(translation, "@brief Method javadoc.", "@param foo Unused.", "@return always false."); } public void testCustomWeakAnnotations() throws IOException { String translation = translateSourceFile( "class Test { @interface Weak {} @interface WeakOuter {}" + " void foo() {}" + " @WeakOuter public class Inner { void bar() { foo(); } }" + " @Weak public Object obj; }", "Test", "Test.h"); assertTranslation(translation, "__weak id obj_;"); translation = getTranslatedFile("Test.m"); assertTranslation(translation, "__weak Test *this$0_;"); } public void testReservedWordAsAnnotationPropertyName() throws IOException { String translation = translateSourceFile( "package foo; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) " + "public @interface Bar { String namespace() default \"\"; }", "Bar", "foo/Bar.h"); assertTranslation(translation, "@property (readonly) NSString *namespace__;"); assertTranslatedLines(translation, "@interface FooBar : NSObject < FooBar > {", "@private", "NSString *namespace___;", "}"); assertTranslation(translation, "- (instancetype)initWithNamespace__:(NSString *)namespace____;"); assertTranslation(translation, "+ (NSString *)namespace__Default;"); } }
package data; import java.io.Serializable; /** * Created by Administrator on 2016/11/10. */ public class Arragementdata implements Serializable { private String place,time_go,time_back; private String day; private String amount; private int id; private int t_year,t_month,t_day; public boolean check; public void setT_day(int t_day) { this.t_day = t_day; } public void setT_month(int t_month) { this.t_month = t_month; } public void setT_year(int t_year) { this.t_year = t_year; } public int getT_day() { return t_day; } public int getT_month() { return t_month; } public int getT_year() { return t_year; } public String getTime_back() { return time_back; } public String getTime_go() { return time_go; } public void setTime_back(String time_back) { this.time_back = time_back; } public void setTime_go(String time_go) { this.time_go = time_go; } public void setAmount(String amount) { this.amount = amount; } public void setDay(String day) { this.day = day; } public void setPlace(String place) { this.place = place; } public String getAmount() { return amount; } public String getDay() { return day; } public String getPlace() { return place; } public int getId() { return id; } public void setId(int id) { this.id = id; } public boolean isCheck() { return check; } public void setCheck(boolean check) { this.check = check; } }
package com.smartbear.readyapi4j.testengine.execution.textrecipe; import com.smartbear.readyapi4j.HttpBasicAuth; import com.smartbear.readyapi4j.TestRecipe; import com.smartbear.readyapi4j.TestRecipeBuilder; import com.smartbear.readyapi4j.client.model.TestJobReport; import com.smartbear.readyapi4j.execution.Execution; import com.smartbear.readyapi4j.testengine.execution.ExecutionTestHelper; import com.smartbear.readyapi4j.testengine.execution.ProjectExecutionTestBase; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.when; @RunWith(Parameterized.class) public class JsonTextRecipeExecutorTest extends ProjectExecutionTestBase { private final File file; @Parameterized.Parameters(name = "{1}") public static Collection<Object[]> data() throws IOException { File recipeDir = new File(JsonTextRecipeExecutorTest.class.getResource("/recipes").getFile()); File[] listFiles = recipeDir.listFiles(); assertThat("Json recipe directory not found", listFiles, is(notNullValue())); List<Object[]> recipeFiles = new ArrayList<>(); for (File file : listFiles) { recipeFiles.add(new Object[]{file, file.getName()}); } return recipeFiles; } @Test public void executesJsonTextRecipe() throws IOException { TestJobReport report = ExecutionTestHelper.makeFinishedReport("execution_ID"); when(apiWrapper.postTestRecipe(any(TestRecipe.class), eq(false), any(HttpBasicAuth.class))).thenReturn(report); String recipeJsonText = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); //Mainly it tests that the text recipe is successfully deserialized into TestCase object and submitted to the server TestRecipe testRecipe = TestRecipeBuilder.createFrom(recipeJsonText); Execution execution = recipeExecutor.executeRecipe(testRecipe); assertThat(execution.getCurrentReport(), is(report)); } public JsonTextRecipeExecutorTest(File file, String name) { this.file = file; } }
package com.tuya.smart.rnsdk.camera.activity; import android.app.DatePickerDialog; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.tuya.smart.home.sdk.TuyaHomeSdk; import com.tuya.smart.rnsdk.R; import com.tuya.smart.rnsdk.camera.bean.CameraMessageBean; import com.tuya.smart.rnsdk.core.TuyaCoreModule; import com.tuya.smart.rnsdk.utils.MessageUtil; import com.tuya.smart.rnsdk.camera.adapter.AlarmDetectionAdapter; import com.tuya.smart.rnsdk.utils.DateUtils; import com.tuya.smart.rnsdk.utils.TimeZoneUtils; import com.tuya.smart.android.network.Business; import com.tuya.smart.android.network.http.BusinessResponse; import com.tuya.smart.ipc.messagecenter.bean.CameraMessageClassifyBean; import com.tuya.smart.ipc.messagecenter.business.CameraMessageBusiness; import com.tuya.smart.utils.ToastUtil; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.TimeZone; //import static com.tuya.smart.rnsdk.device.common.CommonDeviceDebugPresenter.INTENT_DEVID; import static com.tuya.smart.rnsdk.utils.Constant.ALARM_DETECTION_DATE_MONTH_FAILED; import static com.tuya.smart.rnsdk.utils.Constant.ALARM_DETECTION_DATE_MONTH_SUCCESS; import static com.tuya.smart.rnsdk.utils.Constant.ARG1_OPERATE_FAIL; import static com.tuya.smart.rnsdk.utils.Constant.ARG1_OPERATE_SUCCESS; import static com.tuya.smart.rnsdk.utils.Constant.MOTION_CLASSIFY_FAILED; import static com.tuya.smart.rnsdk.utils.Constant.MOTION_CLASSIFY_SUCCESS; import static com.tuya.smart.rnsdk.utils.Constant.MSG_DELETE_ALARM_DETECTION; import static com.tuya.smart.rnsdk.utils.Constant.MSG_GET_ALARM_DETECTION; /** * huangdaju * 2019-11-19 **/ public class AlarmDetectionActivity extends AppCompatActivity implements View.OnClickListener { private Toolbar toolbar; private String devId; private List<CameraMessageBean> mWaitingDeleteCameraMessageList; protected List<CameraMessageBean> mCameraMessageList; private CameraMessageBusiness messageBusiness; private CameraMessageClassifyBean selectClassify; private EditText dateInputEdt; private RecyclerView queryRv; private Button queryBtn; private TextView txt_NoData; private AlarmDetectionAdapter adapter; private int day, year, month; private int offset = 1, limit = 20; Calendar myCalendar; String TAG = "AlarmDetectionActivity"; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case ALARM_DETECTION_DATE_MONTH_FAILED: handlAlarmDetectionDateFail(msg); break; case ALARM_DETECTION_DATE_MONTH_SUCCESS: handlAlarmDetectionDateSuccess(msg); break; case MSG_GET_ALARM_DETECTION: handleAlarmDetection(); break; case MSG_DELETE_ALARM_DETECTION: handleDeleteAlarmDetection(); break; default: break; } super.handleMessage(msg); } }; private void handleDeleteAlarmDetection() { mCameraMessageList.removeAll(mWaitingDeleteCameraMessageList); adapter.updateAlarmDetectionMessage(mCameraMessageList); adapter.notifyDataSetChanged(); } private void handleAlarmDetection() { adapter.updateAlarmDetectionMessage(mCameraMessageList); adapter.notifyDataSetChanged(); if(mCameraMessageList != null && mCameraMessageList.size() > 0) { queryRv.setVisibility(View.VISIBLE); txt_NoData.setVisibility(View.GONE); } else { queryRv.setVisibility(View.GONE); txt_NoData.setVisibility(View.VISIBLE); } } private void handlAlarmDetectionDateFail(Message msg) { } private void handlAlarmDetectionDateSuccess(final Message msg) { if (null != messageBusiness) { long time = DateUtils.getCurrentTime(year, month, day); //long startTime = DateUtils.getTodayStart(time); long startTime = DateUtils.getDate1YearMinus(time); //long endTime = DateUtils.getTodayEnd(time) - 1L; Date date = new Date(System.currentTimeMillis()); long endTime = date.getTime(); // fixed current date messages missing issue JSONObject object = new JSONObject(); object.put("msgSrcId", devId); object.put("startTime", startTime); object.put("endTime", endTime); object.put("msgType", 4); object.put("limit", limit); object.put("offset", offset); //object.put("keepOrig", true); // encrypted image will receive. not able to decrypt in android if (null != selectClassify) { object.put("msgCodes", selectClassify.getMsgCode()); } Log.d(TAG, "elango-messages : " + object); messageBusiness.getAlarmDetectionMessageList(object.toJSONString(), new Business.ResultListener<JSONObject>() { @Override public void onFailure(BusinessResponse businessResponse, JSONObject jsonObject, String s) { Log.d(TAG, "elango-messages - onFailure : " + s + ", " + jsonObject + ", " + businessResponse); mHandler.sendMessage(MessageUtil.getMessage(MSG_GET_ALARM_DETECTION, ARG1_OPERATE_FAIL)); } @Override public void onSuccess(BusinessResponse businessResponse, JSONObject jsonObject, String s) { Log.d(TAG, "elango-messages - onSuccess : " + s + ", " + jsonObject + ", " + businessResponse); List<CameraMessageBean> msgList; try { msgList = JSONArray.parseArray(jsonObject.getString("datas"), CameraMessageBean.class); } catch (Exception e) { msgList = null; } Log.d("elango-onSuccess", msgList.size()+", offset:" +offset+", msgList:"+msgList ); if (msgList != null) { if(offset > 1) { //remove loading view mCameraMessageList.remove(mCameraMessageList.size()-1); if(msgList.size()>0){ //add loaded data mCameraMessageList.addAll(msgList); }else{//result size 0 means there is no more data available at server adapter.setMoreDataAvailable(false); //telling adapter to stop calling load more as no more server data available //Toast.makeText(context,"No More Data Available",Toast.LENGTH_LONG).show(); } offset += msgList.size(); adapter.notifyDataChanged(); } else { offset += msgList.size(); //mCameraMessageList = msgList; mCameraMessageList.addAll(msgList); //mHandler.sendMessage(MessageUtil.getMessage(MSG_GET_ALARM_DETECTION, ARG1_OPERATE_SUCCESS)); adapter.notifyDataChanged(); if(mCameraMessageList != null && mCameraMessageList.size() > 0) { queryRv.setVisibility(View.VISIBLE); txt_NoData.setVisibility(View.GONE); } else { queryRv.setVisibility(View.GONE); txt_NoData.setVisibility(View.VISIBLE); } } } else { mHandler.sendMessage(MessageUtil.getMessage(MSG_GET_ALARM_DETECTION, ARG1_OPERATE_FAIL)); } } }); } } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camera_message); //devId = getIntent().getStringExtra(INTENT_DEVID); devId = getIntent().getStringExtra("intent_devId"); initView(); initData(); initListener(); queryAlarmDetectionByMonth(); } private void initListener() { queryBtn.setOnClickListener(this); } private void initView() { toolbar = findViewById(R.id.toolbar_view); setSupportActionBar(toolbar); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); dateInputEdt = findViewById(R.id.date_input_edt); queryBtn = findViewById(R.id.query_btn); queryRv = findViewById(R.id.query_list); txt_NoData = findViewById(R.id.txt_NoData); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd"); Date date = new Date(System.currentTimeMillis()); dateInputEdt.setHint(simpleDateFormat.format(date)); dateInputEdt.setText(simpleDateFormat.format(date)); } private void initData() { mWaitingDeleteCameraMessageList = new ArrayList<>(); mCameraMessageList = new ArrayList<>(); messageBusiness = new CameraMessageBusiness(); queryCameraMessageClassify(devId); LinearLayoutManager mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); queryRv.setLayoutManager(mLayoutManager); queryRv.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); adapter = new AlarmDetectionAdapter(this, mCameraMessageList); adapter.setListener(new AlarmDetectionAdapter.OnItemListener() { @Override public void onLongClick(CameraMessageBean o) { //deleteCameraMessageClassify(o); } @Override public void onItemClick(CameraMessageBean o) { Intent intent = new Intent(AlarmDetectionActivity.this, ImageFullViewActivity.class); String attachPics = o.getAttachPics(); /*String playUrl = attachPics.substring(0, attachPics.lastIndexOf('@')); String encryptKey = attachPics.substring(attachPics.lastIndexOf('@') + 1); intent.putExtra("imageUrl", playUrl); intent.putExtra("encryptKey", encryptKey);*/ intent.putExtra("image", attachPics); startActivity(intent); } }); adapter.setLoadMoreListener(new AlarmDetectionAdapter.OnLoadMoreListener() { @Override public void onLoadMore() { queryRv.post(new Runnable() { @Override public void run() { Log.d("elango-onLoadMore",mCameraMessageList.size() +", limit:" +limit); if(mCameraMessageList.size() >= limit) { CameraMessageBean item = new CameraMessageBean(); item.setLoader(true); mCameraMessageList.add(item); adapter.notifyItemInserted(mCameraMessageList.size()-1); mHandler.sendEmptyMessage(ALARM_DETECTION_DATE_MONTH_SUCCESS); } } }); //Calling loadMore function in Runnable to fix the // java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling error } }); queryRv.setAdapter(adapter); myCalendar = Calendar.getInstance(); } DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { myCalendar.set(Calendar.YEAR, year); myCalendar.set(Calendar.MONTH, monthOfYear); myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); updateLabel(); queryAlarmDetectionByMonth(); } }; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. //getMenuInflater().inflate(R.menu.menu_messages, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.menu_playback_date) { //Toast.makeText(this, "Action clicked", Toast.LENGTH_LONG).show(); new DatePickerDialog(AlarmDetectionActivity.this, dateSetListener, myCalendar .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show(); return true; } return super.onOptionsItemSelected(item); } private void updateLabel() { String myFormat = "yyyy/MM/dd"; //In which you need put here SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US); dateInputEdt.setText(sdf.format(myCalendar.getTime())); } public void queryCameraMessageClassify(String devId) { if (messageBusiness != null) { messageBusiness.queryAlarmDetectionClassify(devId, new Business.ResultListener<ArrayList<CameraMessageClassifyBean>>() { @Override public void onFailure(BusinessResponse businessResponse, ArrayList<CameraMessageClassifyBean> cameraMessageClassifyBeans, String s) { mHandler.sendEmptyMessage(MOTION_CLASSIFY_FAILED); } @Override public void onSuccess(BusinessResponse businessResponse, ArrayList<CameraMessageClassifyBean> cameraMessageClassifyBeans, String s) { if(cameraMessageClassifyBeans != null && cameraMessageClassifyBeans.size() > 0) { selectClassify = cameraMessageClassifyBeans.get(0); mHandler.sendEmptyMessage(MOTION_CLASSIFY_SUCCESS); } } }); } } public void deleteCameraMessageClassify(CameraMessageBean cameraMessageBean) { mWaitingDeleteCameraMessageList.add(cameraMessageBean); // StringBuilder ids = new StringBuilder(); if (messageBusiness != null) { // for (int i = 0; i < mWaitingDeleteCameraMessageList.size(); i++) { // ids.append(mWaitingDeleteCameraMessageList.get(i).getId()); // if (i != mWaitingDeleteCameraMessageList.size() - 1) { // ids.append(","); // } // } messageBusiness.deleteAlarmDetectionMessageList(cameraMessageBean.getId(), new Business.ResultListener<Boolean>() { @Override public void onFailure(BusinessResponse businessResponse, Boolean aBoolean, String s) { mHandler.sendMessage(MessageUtil.getMessage(MSG_DELETE_ALARM_DETECTION, ARG1_OPERATE_FAIL)); } @Override public void onSuccess(BusinessResponse businessResponse, Boolean aBoolean, String s) { mCameraMessageList.removeAll(mWaitingDeleteCameraMessageList); mWaitingDeleteCameraMessageList.clear(); mHandler.sendMessage(MessageUtil.getMessage(MSG_DELETE_ALARM_DETECTION, ARG1_OPERATE_SUCCESS)); } }); } } @Override public void onClick(View v) { if (v.getId() == R.id.query_btn) { queryAlarmDetectionByMonth(); } } private void queryAlarmDetectionByMonth() { String inputStr = dateInputEdt.getText().toString(); if (TextUtils.isEmpty(inputStr)) { ToastUtil.shortToast(this, "input query date"); return; } String[] substring = inputStr.split("/"); year = Integer.parseInt(substring[0]); month = Integer.parseInt(substring[1]); //day = Integer.parseInt(substring[2]); final JSONObject object = new JSONObject(); object.put("msgSrcId", devId); object.put("timeZone", TimeZoneUtils.getTimezoneGCMById(TimeZone.getDefault().getID())); object.put("month", year + "-" + month); Log.d(TAG, "elango-messages : queryAlarmDetectionDaysByMonth - " + object); messageBusiness.queryAlarmDetectionDaysByMonth(object.toJSONString(), new Business.ResultListener<JSONArray>() { @Override public void onFailure(BusinessResponse businessResponse, JSONArray objects, String s) { Log.d(TAG, "elango-messages - queryAlarmDetectionDaysByMonth - onFailure : " + s + ", " + objects + ", " + businessResponse); mHandler.sendEmptyMessage(ALARM_DETECTION_DATE_MONTH_FAILED); } @Override public void onSuccess(BusinessResponse businessResponse, JSONArray objects, String s) { Log.d(TAG, "elango-messages - queryAlarmDetectionDaysByMonth - onSuccess : " + s + ", " + objects + ", " + businessResponse); List<Integer> dates = JSONArray.parseArray(objects.toJSONString(), Integer.class); if (dates.size() > 0) { day = dates.get(0); } mHandler.sendEmptyMessage(ALARM_DETECTION_DATE_MONTH_SUCCESS); } }); } @Override protected void onDestroy() { super.onDestroy(); if (null != mHandler) { mHandler.removeCallbacksAndMessages(null); } if (null != messageBusiness) { messageBusiness.onDestroy(); } } }
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * 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.fantasy.nacos.config.server.model; /** * SameConfigPolicy. * * @author klw */ public enum SameConfigPolicy { /** * Abort import on duplicate. */ ABORT, /** * Skipping on duplicate. */ SKIP, /** * Overwrite on duplicate. */ OVERWRITE }
public boolean equals(Object o) { Pair ob = (Pair) o; int ff; int ss; if (o != null) { ff = ob.f; ss = ob.s; if ((ff == this.f) && (ss == this.s)) return true; } return false; }
package com.devteam.module.account.data.db.sample; import java.util.Arrays; import org.junit.jupiter.api.Assertions; import org.springframework.beans.factory.annotation.Autowired; import com.devteam.module.account.service.AccountService; import com.devteam.module.account.model.NewAccountModel; import com.devteam.module.account.entity.AccountContact; import com.devteam.module.account.entity.AccountGroup; import com.devteam.module.account.entity.AccountType; import com.devteam.module.account.entity.UserProfile; import com.devteam.module.common.ClientInfo; import com.devteam.module.data.db.sample.EntityDB; import com.devteam.util.dataformat.DataSerializer; public class UserData extends AccountData { static AccountType USER = AccountType.USER; @Autowired private AccountService accountService; public UserProfile THIEN; public void initialize(ClientInfo client) { GroupData GROUP_DATA = EntityDB.getInstance().getData(GroupData.class); THIEN = new UserProfile("Thien", "Thien Dinh", "thien@devteam.com"). withMobile("0337303666"); THIEN = createAccount(THIEN, GROUP_DATA.ACCOUNTS); } private UserProfile createAccount(UserProfile profile, AccountGroup ... group) { NewAccountModel model = new NewAccountModel().withUserProfile(profile, profile.getLoginId()); profile = accountService.createNewAccount(ClientInfo.DEFAULT, model).getUserProfile(); for(AccountGroup sel : group) { accountService.createMembership(ClientInfo.DEFAULT, sel, profile.getLoginId()); } AccountContact contact = new AccountContact() .withLabel("My contact") .withLoginId(profile.getLoginId()) .withMobile(profile.getMobile()) .withEmail(profile.getEmail()).withCountry("VietNam"); accountService.saveAccountContacts(ClientInfo.DEFAULT, profile.getLoginId(), Arrays.asList(contact)); return profile; } public void assertAll(ClientInfo client) throws Exception { UserProfile modifiedFullName = DataSerializer.JSON.clone(THIEN); modifiedFullName.setFullName("Thien Update"); new UserProfileAssert(client, THIEN) .assertEntityUpdate() .assertSave(modifiedFullName, (updateProfile) -> { Assertions.assertEquals("Thien Update", updateProfile.getFullName()); }); } }
/*! * Copyright 2010 - 2013 Pentaho Corporation. 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 org.apache.hadoop.hive.ql.udf.generic; import org.apache.hadoop.hive.ql.parse.SemanticException; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo; /** * A Generic User-defined aggregation function (GenericUDAF) for the use with * Hive. * * GenericUDAFResolver is used at compile time. We use GenericUDAFResolver to * find out the GenericUDAFEvaluator for the parameter types. * * @deprecated Use {@link GenericUDAFResolver2} instead. */ @Deprecated public interface GenericUDAFResolver { /** * Get the evaluator for the parameter types. * * The reason that this function returns an object instead of a class is * because it is possible that the object needs some configuration (that can * be serialized). In that case the class of the object has to implement the * Serializable interface. At execution time, we will deserialize the object * from the plan and use it to evaluate the aggregations. * <p> * If the class of the object does not implement Serializable, then we will * create a new instance of the class at execution time. * </p> * @param parameters * The types of the parameters. We need the type information to know * which evaluator class to use. * @throws SemanticException */ GenericUDAFEvaluator getEvaluator(TypeInfo[] parameters) throws SemanticException; }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.config; import java.util.Collections; import java.util.Map; import com.google.common.collect.ImmutableMap; import org.junit.Test; import static org.junit.Assert.assertEquals; public class YamlConfigurationLoaderTest { @Test public void fromMapTest() { int storagePort = 123; Config.CommitLogSync commitLogSync = Config.CommitLogSync.batch; ParameterizedClass seedProvider = new ParameterizedClass("org.apache.cassandra.locator.SimpleSeedProvider", Collections.emptyMap()); EncryptionOptions encryptionOptions = new EncryptionOptions() .withKeyStore("myNewKeystore") .withCipherSuites("SomeCipher") .withOptional(false); Map<String,Object> map = ImmutableMap.of("storage_port", storagePort, "commitlog_sync", commitLogSync, "seed_provider", seedProvider, "client_encryption_options", encryptionOptions); Config config = YamlConfigurationLoader.fromMap(map, Config.class); assertEquals(storagePort, config.storage_port); // Check a simple integer assertEquals(commitLogSync, config.commitlog_sync); // Check an enum assertEquals(seedProvider, config.seed_provider); // Check a parameterized class assertEquals(encryptionOptions, config.client_encryption_options); // Check a nested object } }
package fjord.ast.pat; import fjord.ast.NodeVisitor; import fjord.ast.NodeWithChildren; public class RecordPattern extends NodeWithChildren<FieldPattern> implements Pat { @Override public void accept(NodeVisitor visitor) { visitor.visit(this); } }
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.admanager.jaxws.v202011; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for CustomCreativeError.Reason. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="CustomCreativeError.Reason"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="DUPLICATE_MACRO_NAME_FOR_CREATIVE"/> * &lt;enumeration value="SNIPPET_REFERENCES_MISSING_MACRO"/> * &lt;enumeration value="UNRECOGNIZED_MACRO"/> * &lt;enumeration value="CUSTOM_CREATIVE_NOT_ALLOWED"/> * &lt;enumeration value="MISSING_INTERSTITIAL_MACRO"/> * &lt;enumeration value="DUPLICATE_ASSET_IN_MACROS"/> * &lt;enumeration value="UNKNOWN"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "CustomCreativeError.Reason") @XmlEnum public enum CustomCreativeErrorReason { /** * * Macros associated with a single custom creative must have unique names. * * */ DUPLICATE_MACRO_NAME_FOR_CREATIVE, /** * * The file macro referenced in the snippet does not exist. * * */ SNIPPET_REFERENCES_MISSING_MACRO, /** * * The macro referenced in the snippet is not valid. * * */ UNRECOGNIZED_MACRO, /** * * Custom creatives are not allowed in this context. * * */ CUSTOM_CREATIVE_NOT_ALLOWED, /** * * The custom creative is an interstitial, but the snippet is missing an * interstitial macro. * * */ MISSING_INTERSTITIAL_MACRO, /** * * Macros associated with the same custom creative cannot share the same * asset. * * */ DUPLICATE_ASSET_IN_MACROS, /** * * The value returned if the actual value is not exposed by the requested API version. * * */ UNKNOWN; public String value() { return name(); } public static CustomCreativeErrorReason fromValue(String v) { return valueOf(v); } }
/* * Copyright 2015-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.intellij.plugin.ui; import com.intellij.execution.impl.ConsoleViewImpl; import com.intellij.execution.ui.ConsoleView; import com.intellij.execution.ui.RunnerLayoutUi; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.project.Project; import javax.swing.tree.DefaultTreeModel; public class BuckUIManager { private ConsoleView outputConsole; private RunnerLayoutUi runnerLayoutUi; public static synchronized BuckUIManager getInstance(Project project) { return ServiceManager.getService(project, BuckUIManager.class); } public ConsoleView getConsoleWindow(Project project) { if (outputConsole == null) { outputConsole = new ConsoleViewImpl(project, false); } return outputConsole; } public RunnerLayoutUi getLayoutUi(Project project) { if (runnerLayoutUi == null) { runnerLayoutUi = RunnerLayoutUi.Factory.getInstance(project).create( "buck", "buck", "buck", project); } return runnerLayoutUi; } private DefaultTreeModel mTreeModel; public DefaultTreeModel getTreeModel() { if (mTreeModel == null) { mTreeModel = new DefaultTreeModel(null); } return mTreeModel; } }
package com.mber.javarush.task.task16.task1602; /* My second thread */ public class Solution { public static void main(String[] args) { TestThread thread = new TestThread(); thread.start(); } public static class TestThread extends Thread { static { System.out.println("it's a static block inside TestThread"); } public void run() { System.out.println("it's a run method"); } } }
package com.dust.core.task.tick; import com.dust.core.axis.TickAxis; import com.dust.core.task.AbstractRepeatTask; import com.dust.core.task.Task; public abstract class AbstractTickRepeatTask extends AbstractRepeatTask { public AbstractTickRepeatTask(Task task, long initDelayFrame, long delayFrame, int repeatMaxCount) { super(task, initDelayFrame, delayFrame, repeatMaxCount, TickAxis.getInstance()); } }
// Copyright (c) Microsoft. All rights reserved. package com.microsoft.azure.iotsolutions.uiconfig.services.external; import com.google.inject.ImplementedBy; import com.microsoft.azure.iotsolutions.uiconfig.services.exceptions.ExternalDependencyException; import java.util.concurrent.CompletionStage; @ImplementedBy(DeviceSimulationClient.class) public interface IDeviceSimulationClient { CompletionStage<SimulationApiModel> getSimulationAsync() throws ExternalDependencyException; CompletionStage updateSimulationAsync(SimulationApiModel model) throws ExternalDependencyException; }
package gov.nih.nci.cananolab.security.service; import gov.nih.nci.cananolab.security.CananoUserDetails; import gov.nih.nci.cananolab.security.dao.UserDao; import gov.nih.nci.cananolab.security.enums.CaNanoRoleEnum; import gov.nih.nci.cananolab.security.utils.SpringSecurityUtil; import gov.nih.nci.cananolab.util.StringUtils; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Component; //@Transactional(readOnly=false, propagation=Propagation.REQUIRED) @Component("userService") public class UserServiceImpl implements UserService { protected Logger logger = LogManager.getLogger(UserServiceImpl.class); @Autowired private UserDao userDao; @Autowired private BCryptPasswordEncoder passwordEncoder; @Override public List<CananoUserDetails> loadUsers(String matchStr) { List<CananoUserDetails> userList = userDao.getUsers(matchStr); for (CananoUserDetails userDetails: userList) { if (userDetails != null) { userDetails.setGroups(userDao.getUserGroups(userDetails.getUsername())); userDetails.setRoles(userDao.getUserRoles(userDetails.getUsername())); } } Collections.sort(userList, CananoUserDetails::compareTo); return userList; } @Override public List<String> getGroupsAccessibleToUser(String matchStr) { CananoUserDetails userDetails = SpringSecurityUtil.getPrincipal(); List<String> groups = new ArrayList<String>(); if (userDetails != null) { if (!StringUtils.isEmpty(matchStr)) { for (String group : userDetails.getGroups()) if (group.contains(matchStr)) groups.add(group); } else groups.addAll(userDetails.getGroups()); } return groups; } @Override public void createUserAccount(CananoUserDetails userDetails) { String username = userDetails.getUsername(); if (userDetails != null && !StringUtils.isEmpty(username)) { String encryptedString = passwordEncoder.encode(username); userDetails.setPassword(encryptedString); int status = userDao.insertUser(userDetails); userDao.insertUserAuthority(username, CaNanoRoleEnum.ROLE_ANONYMOUS.toString()); for (String role : userDetails.getRoles()) { if (!role.equals(CaNanoRoleEnum.ROLE_ANONYMOUS)) userDao.insertUserAuthority(username, role); } } } @Override public int resetPasswordForUser(String oldPassword, String newPassword, String userName) throws Exception { int status = 0; if (!StringUtils.isEmpty(userName) && !StringUtils.isEmpty(newPassword)) { String encodedPassword = userDao.readPassword(userName); //verify oldPassword, else throw exception boolean match = passwordEncoder.matches(oldPassword, encodedPassword); //update to new Password if (match) { String encryptedPassword = passwordEncoder.encode(newPassword); status = userDao.resetPassword(userName, encryptedPassword); } else throw new Exception("Incorrect old password."); } return status; } @Override public void updateUserAccount(CananoUserDetails userDetails) { String username = userDetails.getUsername(); if (userDetails != null && !StringUtils.isEmpty(username)) { int status = userDao.updateUser(userDetails); status = userDao.deleteUserAssignedRoles(username); //update user roles for (String role : userDetails.getRoles()) { if (!role.equals(CaNanoRoleEnum.ROLE_ANONYMOUS)) userDao.insertUserAuthority(username, role); } } } }
package gopherdoc.buttercoin.trader; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; import gopherdoc.buttercoin.trader.Buttercoin.ObjCollectionHistoryOrderRecord; import gopherdoc.buttercoin.trader.Buttercoin.ObjOrderRecord; public class PagerHistorySection extends Fragment { public static PagerHistorySection init() { return new PagerHistorySection(); } private ArrayList<ObjOrderRecord> collection; private MyAdapter myAdapter; private ListView lv; public PagerHistorySection(){ } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.pager_history, null); assert rootView != null; lv = (ListView) rootView.findViewById(R.id.lv_tradehistory); Bundle args = getArguments(); if (args != null) { ObjCollectionHistoryOrderRecord myTrades = args.getParcelable("TradeList"); collection = myTrades.collection; } else { collection = new ArrayList<ObjOrderRecord>(); } if (savedInstanceState != null){ if (savedInstanceState.getParcelableArrayList("history") != null){ collection = savedInstanceState.getParcelableArrayList("history"); } } myAdapter = new MyAdapter(getActivity(), collection); lv.setAdapter(myAdapter); return rootView; } @Override public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); outState.putParcelableArrayList("history",collection); } private class MyAdapter extends ArrayAdapter<ObjOrderRecord> { private final Context context; private final ArrayList<ObjOrderRecord> trades; public MyAdapter(Context context, ArrayList<ObjOrderRecord> trades) { super(context, R.layout.lvitem_history, trades); this.context = context; this.trades = trades; } @Override public View getView(int position, View convertView, ViewGroup parent) { ListItemHistory rowView = new ListItemHistory(context); rowView.setDate(trades.get(position).getTimestamp()); rowView.setPosition(trades.get(position).getPosition()); rowView.setPrice(trades.get(position).getPrice()); rowView.setAmount(trades.get(position).getVolume()); return rowView; } } public void updateHistory(ObjCollectionHistoryOrderRecord tradeHistory){ if (myAdapter != null) { collection = tradeHistory.collection; myAdapter.clear(); for (ObjOrderRecord order : tradeHistory.collection) { myAdapter.add(order); } myAdapter.notifyDataSetChanged(); } } public void clearHistory(){ updateHistory(new ObjCollectionHistoryOrderRecord()); } }
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2020, Arnaud Roques * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of PlantUML. * * 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. * * * Original Author: Arnaud Roques */ package net.sourceforge.plantuml.stats; import java.io.IOException; import net.sourceforge.plantuml.PlainStringsDiagram; import net.sourceforge.plantuml.core.DiagramDescription; import net.sourceforge.plantuml.core.UmlSource; public class PSystemStats extends PlainStringsDiagram { PSystemStats(UmlSource source) { super(source); final StatsImpl stats = (StatsImpl) StatsUtils.getStats(); strings.addAll(new CreoleConverter(stats).toCreole()); } public static PSystemStats create(UmlSource source) throws IOException { return new PSystemStats(source); } public DiagramDescription getDescription() { return new DiagramDescription("(Stats)"); } }
package duelistmod.cards.pools.aqua; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.localization.CardStrings; import com.megacrit.cardcrawl.monsters.AbstractMonster; import duelistmod.DuelistMod; import duelistmod.abstracts.DuelistCard; import duelistmod.patches.AbstractCardEnum; import duelistmod.powers.*; import duelistmod.powers.duelistPowers.ToadallyAwesomePower; import duelistmod.variables.Tags; public class ToadallyAwesome extends DuelistCard { // TEXT DECLARATION public static final String ID = DuelistMod.makeID("ToadallyAwesome"); private static final CardStrings cardStrings = CardCrawlGame.languagePack.getCardStrings(ID); public static final String IMG = DuelistMod.makeCardPath("ToadallyAwesome.png"); public static final String NAME = cardStrings.NAME; public static final String DESCRIPTION = cardStrings.DESCRIPTION; public static final String UPGRADE_DESCRIPTION = cardStrings.UPGRADE_DESCRIPTION; // /TEXT DECLARATION/ // STAT DECLARATION private static final CardRarity RARITY = CardRarity.UNCOMMON; private static final CardTarget TARGET = CardTarget.SELF; private static final CardType TYPE = CardType.POWER; public static final CardColor COLOR = AbstractCardEnum.DUELIST_MONSTERS; private static final int COST = 2; // /STAT DECLARATION/ public ToadallyAwesome() { super(ID, NAME, IMG, COST, DESCRIPTION, TYPE, COLOR, RARITY, TARGET); this.tags.add(Tags.MONSTER); this.tags.add(Tags.AQUA); this.tributes = this.baseTributes = 2; this.originalName = this.name; this.magicNumber = this.baseMagicNumber = 1; } // Actions the card should do. @Override public void use(AbstractPlayer p, AbstractMonster m) { tribute(); applyPowerToSelf(new ToadallyAwesomePower(this.magicNumber)); } // Which card to return when making a copy of this card. @Override public AbstractCard makeCopy() { return new ToadallyAwesome(); } // Upgraded stats. @Override public void upgrade() { if (!this.upgraded) { this.upgradeName(); this.upgradeBaseCost(1); this.rawDescription = UPGRADE_DESCRIPTION; this.initializeDescription(); } } @Override public void onTribute(DuelistCard tributingCard) { aquaSynTrib(tributingCard); } @Override public void onResummon(int summons) { // TODO Auto-generated method stub } @Override public void summonThis(int summons, DuelistCard c, int var) { } @Override public void summonThis(int summons, DuelistCard c, int var, AbstractMonster m) { } @Override public String getID() { return ID; } @Override public void optionSelected(AbstractPlayer arg0, AbstractMonster arg1, int arg2) { // TODO Auto-generated method stub } }
package com.gx0c.topdownshooter.core.game.systems.render; import com.badlogic.ashley.core.EntitySystem; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.maps.MapObject; import com.badlogic.gdx.maps.MapProperties; import com.badlogic.gdx.maps.objects.PolygonMapObject; import com.badlogic.gdx.maps.objects.RectangleMapObject; import com.badlogic.gdx.maps.tiled.TiledMap; import com.badlogic.gdx.maps.tiled.TmxMapLoader; import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; import com.badlogic.gdx.utils.Disposable; import com.gx0c.topdownshooter.core.Game; import java.util.ArrayList; public class TiledMapRendererSystem extends EntitySystem implements Disposable { private OrthographicCamera camera; private TiledMap map; private OrthogonalTiledMapRenderer mapRenderer; private int tileWidth, tileHeight; private int mapWidth, mapHeight; private float transformedMapWidth, transformedMapHeight; public TiledMapRendererSystem(OrthographicCamera camera) { this.camera = camera; map = new TmxMapLoader().load("maps/map.tmx"); mapRenderer = new OrthogonalTiledMapRenderer(map, 1 / Game.PPM); MapProperties properties = map.getProperties(); tileWidth = properties.get("tilewidth", Integer.class); tileHeight = properties.get("tileheight", Integer.class); mapWidth = tileWidth * properties.get("width", Integer.class); mapHeight = tileHeight * properties.get("height", Integer.class); transformedMapWidth = mapWidth / Game.PPM; transformedMapHeight = mapHeight / Game.PPM; } @Override public void update(float deltaTime) { mapRenderer.setView(camera); mapRenderer.render(); } public void getCollidable(World world) { for (MapObject object : map.getLayers().get("collidable").getObjects()) { float[] vertices = ((PolygonMapObject) object).getPolygon().getTransformedVertices(); float[] worldVertices = new float[vertices.length]; for (int i = 0; i < vertices.length; i++) worldVertices[i] = vertices[i] / Game.PPM; PolygonShape shape = new PolygonShape(); shape.set(worldVertices); BodyDef bodyDef = new BodyDef(); bodyDef.type = BodyDef.BodyType.StaticBody; FixtureDef fixtureDef = new FixtureDef(); fixtureDef.shape = shape; fixtureDef.density = 1000f; fixtureDef.filter.categoryBits = Game.COLLIDABLE_BIT; fixtureDef.filter.maskBits = Game.PLAYER_BIT | Game.BULLET_BIT | Game.ENEMY_BIT; Body body = world.createBody(bodyDef); body.createFixture(fixtureDef); shape.dispose(); } } public void getBulletCollidable(World world) { for (MapObject object : map.getLayers().get("bullet_collidable").getObjects()) { float[] vertices = ((PolygonMapObject) object).getPolygon().getTransformedVertices(); float[] worldVertices = new float[vertices.length]; for (int i = 0; i < vertices.length; i++) worldVertices[i] = vertices[i] / Game.PPM; PolygonShape shape = new PolygonShape(); shape.set(worldVertices); BodyDef bodyDef = new BodyDef(); bodyDef.type = BodyDef.BodyType.StaticBody; FixtureDef fixtureDef = new FixtureDef(); fixtureDef.shape = shape; fixtureDef.density = 1000f; fixtureDef.filter.categoryBits = Game.BULLET_COLLIDABLE_BIT; fixtureDef.filter.maskBits = Game.BULLET_BIT; Body body = world.createBody(bodyDef); body.createFixture(fixtureDef); shape.dispose(); } } public Vector2 getPlayerSpawn() { for (MapObject object : map.getLayers().get("player_spawn").getObjects()) { Rectangle rectangle = ((RectangleMapObject) object).getRectangle(); return new Vector2(rectangle.x / Game.PPM, rectangle.y / Game.PPM); } return new Vector2(0, 0); } public ArrayList<Vector2> getEnemySpawns() { ArrayList<Vector2> spawns = new ArrayList<Vector2>(); for (MapObject object : map.getLayers().get("enemy_spawn").getObjects()) { Rectangle rectangle = ((RectangleMapObject) object).getRectangle(); spawns.add(new Vector2(rectangle.x / Game.PPM, rectangle.y / Game.PPM)); } return spawns; } public ArrayList<Rectangle> getCameraInfos() { ArrayList<Rectangle> infos = new ArrayList<Rectangle>(); for (MapObject object : map.getLayers().get("camera").getObjects()) { Rectangle rectangle = ((RectangleMapObject) object).getRectangle(); infos.add(new Rectangle(rectangle.x / Game.PPM, rectangle.y / Game.PPM, rectangle.width / Game.PPM, rectangle.height / Game.PPM)); } return infos; } @Override public void dispose() { map.dispose(); mapRenderer.dispose(); } public int getTileWidth() { return tileWidth; } public int getTileHeight() { return tileHeight; } public int getMapWidth() { return mapWidth; } public int getMapHeight() { return mapHeight; } public float getTransformedMapWidth() { return transformedMapWidth; } public float getTransformedMapHeight() { return transformedMapHeight; } }
// Copyright 2020 The Bazel Authors. 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 net.starlark.java.eval; import com.google.common.collect.ImmutableMap; import com.sun.management.ThreadMXBean; import java.io.File; import java.lang.management.ManagementFactory; import java.util.Map; import java.util.TreeMap; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import net.starlark.java.annot.StarlarkBuiltin; import net.starlark.java.annot.StarlarkMethod; import net.starlark.java.lib.json.Json; import net.starlark.java.syntax.FileOptions; import net.starlark.java.syntax.ParserInput; import net.starlark.java.syntax.SyntaxError; // TODO(adonovan): document how to obtain a Java CPU profile. // TODO(adonovan): mitigate the effects of JVM warmup. // (See Oracle's JMH; we can't use it directly because it // seems to be entirely driven by Java annotations, // which is no good for a dynamic suite.) /** * Script-based benchmarks of the Starlark evaluator. * * <p>Scripts in testdata/bench_*.star are executed, and then each function named {@code bench_*} is * repeatedly called and measured. The function has one parameter, b, a Benchmark, that provides * b.n, the number of iterations to execute. The function must have resource costs linear in b.n. * Typically, the function body is a loop of the form {@code for _ in range(b.n): ...}. Using b.n * for other purposes leads to meaningless results. For example, it would be a mistake to use it as * the length of a random list to be sorted, because sorting does not run in linear time. * * <p>A benchmark with significant set-up costs may reset the timer ({@code b.restart()}) before * entering its loop. Example: * * <pre> * def bench_my_func(b): * """Description goes here.""" * my_setup() * b.restart() * for _ in range(b.n): * my_func() * </pre> */ public final class Benchmarks { private static final String HELP = "Usage: Benchmarks [--help] [--filter regex] [--seconds float]\n" + "Runs Starlark benchmarks matching the filter for the specified (approximate) time,\n" + "and reports various performance measures.\n" + "The optional filter is a regular expression applied to the string FILE:FUNC,\n" + "where FILE is the base name of the file and FUNC is the name of the function,\n" + "for example 'bench_int.star:bench_add32'.\n"; private static boolean ok = true; public static void main(String[] args) throws Exception { Pattern filter = null; // default: all long budgetNanos = 1_000_000_000; // parse flags int i; for (i = 0; i < args.length; i++) { if (args[i].equals("--")) { i++; break; } else if (args[i].equals("--help")) { System.out.println(HELP); System.exit(0); } else if (args[i].equals("--filter")) { if (++i == args.length) { fail("--filter needs an argument"); } try { filter = Pattern.compile(args[i]); } catch (PatternSyntaxException ex) { fail("for --filter, invalid regexp: %s", ex.getMessage()); } } else if (args[i].equals("--seconds")) { if (++i == args.length) { fail("--seconds needs an argument"); } try { budgetNanos = (long) (1e9 * Double.parseDouble(args[i])); } catch (NumberFormatException unused) { fail("for --seconds, got '%s', want floating-point number of seconds", args[i]); } if (!(0 <= budgetNanos && budgetNanos <= 1e13)) { fail("--seconds out of range"); } } else { fail("unknown flag: %s", args[i]); } } if (i < args.length) { fail("unexpected arguments"); } // Read testdata/bench_* files. File src = new File("third_party/bazel/src"); // blaze if (!src.exists()) { src = new File("src"); // bazel } File testdata = new File(src, "test/java/net/starlark/java/eval/testdata"); for (File file : testdata.listFiles()) { String basename = file.getName(); if (!(basename.startsWith("bench_") && basename.endsWith(".star"))) { continue; } // parse & execute ParserInput input = ParserInput.readFile(file.toString()); ImmutableMap.Builder<String, Object> predeclared = ImmutableMap.builder(); predeclared.put("json", Json.INSTANCE); Module module = Module.withPredeclared(semantics, predeclared.build()); try (Mutability mu = Mutability.create("test")) { StarlarkThread thread = new StarlarkThread(mu, semantics); Starlark.execFile(input, FileOptions.DEFAULT, module, thread); } catch (SyntaxError.Exception ex) { for (SyntaxError err : ex.errors()) { System.err.println(err); // includes location ok = false; continue; } } catch (EvalException ex) { System.err.println(ex.getMessageWithStack()); ok = false; continue; } catch ( @SuppressWarnings("InterruptedExceptionSwallowed") Throwable ex) { // unhandled exception (incl. InterruptedException) System.err.printf("in %s: %s\n", file, ex.getMessage()); ex.printStackTrace(); ok = false; continue; } // Sort bench_* functions by name. TreeMap<String, StarlarkFunction> benchmarks = new TreeMap<>(); for (Map.Entry<String, Object> e : module.getExportedGlobals().entrySet()) { if (e.getKey().startsWith("bench_") && e.getValue() instanceof StarlarkFunction) { String name = e.getKey(); if (filter == null || filter.matcher(basename + ":" + name).find()) { benchmarks.put(name, (StarlarkFunction) e.getValue()); } } } if (benchmarks.isEmpty()) { if (filter == null) { System.err.printf("File %s: no bench_* functions\n", file); ok = false; } continue; } // Run benchmarks. System.out.printf("File %s:\n", file); System.out.printf( "%-20s %10s %10s %10s %10s %10s\n", // "benchmark", "ops", "cpu/op", "wall/op", "steps/op", "alloc/op"); for (Map.Entry<String, StarlarkFunction> e : benchmarks.entrySet()) { String name = e.getKey(); System.out.flush(); // help user identify a slow benchmark Benchmark b = run(name, e.getValue(), budgetNanos); if (b == null) { ok = false; continue; } System.out.printf( "%-20s %10d %10s %10s %10d %10s\n", name, b.count, formatDuration(((double) b.time) / b.count), formatDuration(((double) b.cpu) / b.count), b.steps / b.count, formatBytes(b.alloc / b.count)); } System.out.println(); } if (!ok) { System.exit(1); } } private static void fail(String format, Object... args) { System.err.printf(format, args); System.err.println(); System.exit(1); } // Runs benchmark function f for the specified time budget // (which we may exceed by a factor of two). private static Benchmark run(String name, StarlarkFunction f, long budgetNanos) { Mutability mu = Mutability.create("test"); StarlarkThread thread = new StarlarkThread(mu, semantics); Benchmark b = new Benchmark(); // Keep doubling the number of iterations until we exceed the deadline. // TODO(adonovan): opt: extrapolate and predict the number of iterations // in the remaining time budget, being wary of extrapolation error. for (b.n = 1; b.time < budgetNanos; b.n <<= 1) { if (b.n <= 0) { System.err.printf( "In %s: function is too fast; likely a loop over `range(b.n)` is missing\n", name); return null; } try { b.start(thread); Starlark.fastcall(thread, f, new Object[] {b}, new Object[0]); b.stop(thread); } catch (EvalException ex) { System.err.println(ex.getMessageWithStack()); return null; } catch ( @SuppressWarnings("InterruptedExceptionSwallowed") Throwable ex) { // unhandled exception (incl. InterruptedException) System.err.printf("In %s: %s\n", name, ex.getMessage()); ex.printStackTrace(); return null; } } return b; } // The type of the parameter to each bench(b) function. // Provides n, the number of iterations. @StarlarkBuiltin(name = "Benchmark") private static class Benchmark implements StarlarkValue { // The cast assumes we use the "Sun" JVM, which measures per-thread allocation and CPU. private final ThreadMXBean threadMX = (ThreadMXBean) ManagementFactory.getThreadMXBean(); // Starlark attributes private int n; // requested number of iterations // current span (time0 != 0 => started) private long cpu0; private long alloc0; private long time0; private long steps0; // accumulators private int count; // iterations private long cpu; // CPU time (ns) in this thread private long alloc; // bytes allocated by this thread private long time; // wall time (ns) private long steps; // Starlark computation steps @StarlarkMethod(name = "n", doc = "Requested number of iterations.", structField = true) public int n() { return n; } @StarlarkMethod(name = "start", doc = "Starts the timer.", useStarlarkThread = true) public void start(StarlarkThread thread) throws EvalException { if (time0 != 0) { throw Starlark.errorf("timer already started"); } this.cpu0 = threadMX.getCurrentThreadCpuTime(); this.alloc0 = threadMX.getThreadAllocatedBytes(Thread.currentThread().getId()); this.steps0 = thread.getExecutedSteps(); this.time0 = System.nanoTime(); } @StarlarkMethod(name = "stop", doc = "Starts the timer.", useStarlarkThread = true) public void stop(StarlarkThread thread) throws EvalException { if (time0 == 0) { throw Starlark.errorf("timer already stopped"); } long time1 = System.nanoTime(); long steps1 = thread.getExecutedSteps(); long alloc1 = threadMX.getThreadAllocatedBytes(Thread.currentThread().getId()); long cpu1 = threadMX.getCurrentThreadCpuTime(); this.time += time1 - this.time0; this.steps += steps1 - this.steps0; this.alloc += alloc1 - this.alloc0; this.cpu += cpu1 - this.cpu0; this.count += this.n; time0 = 0; // stopped } @StarlarkMethod(name = "restart", doc = "Restarts the timer.", useStarlarkThread = true) public void restart(StarlarkThread thread) throws EvalException { time0 = 0; // stop, and discard current span start(thread); } @Override public void repr(Printer p) { p.append("<Benchmark>"); } } private static String formatDuration(double ns) { // (Similar format to Go's time.Duration.) if (ns == 0) { return "0s"; } else if (ns < 1e3) { return String.format("%dns", (long) ns); } else if (ns < 1e6) { return String.format("%.3gµs", ns / 1e3); } else if (ns < 1e9) { return String.format("%.6gms", ns / 1e6); } else { return String.format("%.3gs", ns / 1e9); } } private static String formatBytes(long bytes) { if (bytes == 0) { return "0B"; } else if (bytes < 1e3) { return String.format("%dB", bytes); } else if (bytes < 1e6) { return String.format("%.3gKB", bytes / 1e3); } else if (bytes < 1e9) { return String.format("%.6gMB", bytes / 1e6); } else { return String.format("%.3gGB", bytes / 1e9); } } private static final StarlarkSemantics semantics = StarlarkSemantics.DEFAULT; private Benchmarks() {} }
/* * Copyright 2019 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.qa.query; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.ignite.internal.processors.query.SqlMergeTest; /** * Tests SQL MERGE command via JDBC thin driver. */ public class JdbcThinSqlMergeTest extends SqlMergeTest { /** JDBC thin URL. */ private static final String JDBC_THIN_URL = "jdbc:ignite:thin://127.0.0.1"; /** Connection. */ private static Connection conn; /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { super.beforeTestsStarted(); conn = DriverManager.getConnection(JDBC_THIN_URL); } /** {@inheritDoc} */ @Override protected void afterTestsStopped() throws Exception { conn.close(); super.afterTestsStopped(); } /** {@inheritDoc} */ @Override protected List<List<?>> sql(String sql) throws Exception { try (Statement stmt = conn.createStatement()) { stmt.execute(sql); int updCnt = stmt.getUpdateCount(); if (updCnt == -1) { ResultSet rs = stmt.getResultSet(); int cols = rs.getMetaData().getColumnCount(); List<List<?>> res = new ArrayList<>(); while (rs.next()) { List<Object> row = new ArrayList<>(); for (int i = 0; i < cols; ++i) row.add(rs.getObject(i + 1)); res.add(row); } return res; } else return Collections.singletonList(Collections.singletonList((long)updCnt)); } } }
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * User: anna * Date: 01-Feb-2008 */ package com.intellij.codeInsight.hint; import com.intellij.lang.LanguageExtension; public class LanguageImplementationTextSelectioner extends LanguageExtension<ImplementationTextSelectioner>{ public static final LanguageImplementationTextSelectioner INSTANCE = new LanguageImplementationTextSelectioner(); public LanguageImplementationTextSelectioner() { super("com.intellij.lang.implementationTextSelectioner", new DefaultImplementationTextSelectioner()); } }
package net.minestom.server.entity.type.ambient; import net.minestom.server.entity.EntityCreature; import net.minestom.server.entity.EntityType; import net.minestom.server.entity.type.Animal; import net.minestom.server.utils.Position; import net.minestom.server.utils.binary.BinaryWriter; import org.jetbrains.annotations.NotNull; import java.util.function.Consumer; public class EntityBat extends EntityCreature implements Animal { private boolean hanging; public EntityBat(Position spawnPosition) { super(EntityType.BAT, spawnPosition); setBoundingBox(0.5f, 0.9f, 0.5f); } @NotNull @Override public Consumer<BinaryWriter> getMetadataConsumer() { return packet -> { super.getMetadataConsumer().accept(packet); fillMetadataIndex(packet, 15); }; } @Override protected void fillMetadataIndex(@NotNull BinaryWriter packet, int index) { super.fillMetadataIndex(packet, index); if (index == 15) { packet.writeByte((byte) 15); packet.writeByte(METADATA_BYTE); packet.writeByte((byte) (hanging ? 1 : 0)); } } /** * Gets if the bat is hanging. * * @return true if the bat is hanging, false otherwise */ public boolean isHanging() { return hanging; } /** * Makes the bat hanging or cancel. * * @param hanging true to make the bat hanging, false otherwise */ public void setHanging(boolean hanging) { this.hanging = hanging; } }
package com.zzz.wifiview; import android.app.*; import android.os.*; import java.util.*; import java.io.*; import android.content.*; import android.widget.*; import android.view.*; import java.text.*; import android.text.*; import android.net.*; public class FileActivity extends Activity { ArrayList<Map<String, String>> list; ArrayList<File> fileList; String backupParentPath; // /AppData/Backup/ Context context = this; PopupMenu popup; String wifiPath; // /data/misc/wifi/xxx.xml String backupPath; int num; //String wifiFileName; // xxx.xml //String pickerFilePath; java.util.Date utilDate = new java.util.Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //getSupportActionBar().setDisplayHomeAsUpEnabled(true); setContentView(R.layout.list); backupParentPath = context.getExternalFilesDir("Backup").getPath(); if (android.os.Build.VERSION.SDK_INT >= 26) wifiPath = "/data/misc/wifi/WifiConfigStore.xml"; else wifiPath = "/data/misc/wifi/wpa_supplicant.conf"; work(); } private void work() { fileList = new ArrayList<File>(); getAllFiles(new File(backupParentPath)); List<String> data = new ArrayList<String>(); for(int i=0;i<fileList.size();i++) { String name = fileList.get(i).toString().substring(fileList.get(i).toString().lastIndexOf("/")+1,fileList.get(i).toString().length()); data.add(name); } final String[] strings = new String[data.size()]; data.toArray(strings); num = data.size(); final ListView lv = (ListView) findViewById(R.id.lv); ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strings); lv.setAdapter(adapter); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, final int position, long id) { //Toast.makeText(FileActivity.this, backupParentPath + "/" + strings[position], 0).show(); popup = new PopupMenu(FileActivity.this, view); getMenuInflater().inflate(R.menu.wifi,popup.getMenu()); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch(item.getItemId()) { case R.id.menu_recovery: showRestoreDialog(backupParentPath + "/" + strings[position]); break; case R.id.menu_read: Intent intent1 = new Intent(); intent1.setClass(FileActivity.this, ViewActivity.class); intent1.putExtra("path", backupParentPath + "/" + strings[position]); startActivity(intent1); break; case R.id.menu_delete1: try { Runtime.getRuntime().exec("su /n rm -f " + backupParentPath + "/" + strings[position]); Toast.makeText(FileActivity.this, "已删除备份", Toast.LENGTH_SHORT).show(); Intent intent = getIntent(); finish(); startActivity(intent); } catch (IOException e) { Toast.makeText(FileActivity.this, "删除备份:" + e, Toast.LENGTH_LONG).show(); } break; default: return false; } return true; } }); popup.show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0,0,0,"添加备份"); menu.add(0,1,0,"Notice"); menu.getItem(1).setEnabled(false); menu.getItem(1).setTitle("共 " + num + " 条备份"); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 0: showBackupDialog(); return true; default: return super.onOptionsItemSelected(item); } } private void showBackupDialog() { final EditText et = new EditText(this); AlertDialog.Builder BackupDialog = new AlertDialog.Builder(this); BackupDialog.setTitle("备份名称"); BackupDialog.setView(et); et.setText(formatter.format(utilDate)); et.setFilters(new InputFilter[] { new InputFilter() { public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) { if ( !Character.isLetterOrDigit(source.charAt(i)) && !Character.toString(source.charAt(i)) .equals("_") && !Character.toString(source.charAt(i)) .equals("-")) { return ""; } } return null; }}}); BackupDialog.setPositiveButton("开始",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog,int which) { backupPath = backupParentPath + "/" + et.getText().toString(); try { Runtime.getRuntime().exec("su /n cp -f " + wifiPath + " " + backupPath); Toast.makeText(FileActivity.this, "备份完成", Toast.LENGTH_SHORT).show(); } catch (IOException e){ Toast.makeText(FileActivity.this, "备份:" + e, Toast.LENGTH_LONG).show(); } Intent intent = getIntent(); finish(); startActivity(intent); } }); BackupDialog.setNegativeButton("取消", null); BackupDialog.setNeutralButton("分享",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog,int which) { backupPath = backupParentPath + "/" + et.getText().toString(); try { Runtime.getRuntime().exec("su /n cp -f " + wifiPath + " " + backupPath); } catch (IOException e) { Toast.makeText(FileActivity.this, "备份:" + e, Toast.LENGTH_LONG).show(); } File sendFile = new File(backupPath); Intent share = new Intent(Intent.ACTION_SEND); share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(sendFile)); share.setType("*/*"); startActivity(Intent.createChooser(share, "分享")); } }); BackupDialog.show(); } private void showRestoreDialog(final String path) { AlertDialog.Builder RestoreDialog = new AlertDialog.Builder(this); RestoreDialog.setTitle("警告"); RestoreDialog.setMessage("此操作将会替换设备中的WiFi密码文件。是否继续?\n\n" + "当前文件:\n" + path); RestoreDialog.setPositiveButton("继续",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog,int which) { try { Runtime.getRuntime().exec("su /n cp -f " + path + " " + wifiPath + " /n " + "chmod 660 " + wifiPath); } catch (IOException e) { Toast.makeText(FileActivity.this, "恢复覆盖:" + e, Toast.LENGTH_LONG).show(); } } }); RestoreDialog.setNegativeButton("取消", null); RestoreDialog.show(); } public ArrayList<Map<String, String>> get(String path) { try { ReadFile file = new ReadFile(path); return file.getList(this.context); } catch (Exception e) { Toast.makeText(this, "ReadFile:" + e.getMessage(), Toast.LENGTH_LONG).show(); return null; } } private void getAllFiles(File root) { File files[] = root.listFiles(); if(files != null) for(File f:files) { if(f.isDirectory()) { getAllFiles(f); } else{ this.fileList.add(f); } } } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.portfolio.savings.domain; import static org.apache.fineract.portfolio.savings.SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME; import static org.apache.fineract.portfolio.savings.SavingsApiConstants.allowOverdraftParamName; import static org.apache.fineract.portfolio.savings.SavingsApiConstants.dueAsOfDateParamName; import static org.apache.fineract.portfolio.savings.SavingsApiConstants.enforceMinRequiredBalanceParamName; import static org.apache.fineract.portfolio.savings.SavingsApiConstants.localeParamName; import static org.apache.fineract.portfolio.savings.SavingsApiConstants.lockinPeriodFrequencyParamName; import static org.apache.fineract.portfolio.savings.SavingsApiConstants.lockinPeriodFrequencyTypeParamName; import static org.apache.fineract.portfolio.savings.SavingsApiConstants.minOverdraftForInterestCalculationParamName; import static org.apache.fineract.portfolio.savings.SavingsApiConstants.minRequiredBalanceParamName; import static org.apache.fineract.portfolio.savings.SavingsApiConstants.nominalAnnualInterestRateOverdraftParamName; import static org.apache.fineract.portfolio.savings.SavingsApiConstants.overdraftLimitParamName; import static org.apache.fineract.portfolio.savings.SavingsApiConstants.withHoldTaxParamName; import static org.apache.fineract.portfolio.savings.SavingsApiConstants.withdrawalFeeForTransfersParamName; import com.google.gson.JsonArray; import java.math.BigDecimal; import java.math.MathContext; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.DiscriminatorColumn; import javax.persistence.DiscriminatorType; import javax.persistence.DiscriminatorValue; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OrderBy; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import javax.persistence.UniqueConstraint; import javax.persistence.Version; import org.apache.commons.lang3.StringUtils; import org.apache.fineract.infrastructure.core.api.JsonCommand; import org.apache.fineract.infrastructure.core.data.ApiParameterError; import org.apache.fineract.infrastructure.core.data.DataValidatorBuilder; import org.apache.fineract.infrastructure.core.domain.AbstractPersistableCustom; import org.apache.fineract.infrastructure.core.domain.LocalDateInterval; import org.apache.fineract.infrastructure.core.exception.PlatformApiDataValidationException; import org.apache.fineract.infrastructure.core.service.DateUtils; import org.apache.fineract.infrastructure.security.service.RandomPasswordGenerator; import org.apache.fineract.interoperation.domain.InteropIdentifier; import org.apache.fineract.organisation.monetary.data.CurrencyData; import org.apache.fineract.organisation.monetary.domain.MonetaryCurrency; import org.apache.fineract.organisation.monetary.domain.Money; import org.apache.fineract.organisation.monetary.domain.MoneyHelper; import org.apache.fineract.organisation.office.domain.Office; import org.apache.fineract.organisation.staff.domain.Staff; import org.apache.fineract.portfolio.accountdetails.domain.AccountType; import org.apache.fineract.portfolio.charge.domain.Charge; import org.apache.fineract.portfolio.charge.exception.SavingsAccountChargeNotFoundException; import org.apache.fineract.portfolio.client.domain.Client; import org.apache.fineract.portfolio.common.domain.PeriodFrequencyType; import org.apache.fineract.portfolio.group.domain.Group; import org.apache.fineract.portfolio.savings.DepositAccountType; import org.apache.fineract.portfolio.savings.SavingsAccountTransactionType; import org.apache.fineract.portfolio.savings.SavingsApiConstants; import org.apache.fineract.portfolio.savings.SavingsCompoundingInterestPeriodType; import org.apache.fineract.portfolio.savings.SavingsInterestCalculationDaysInYearType; import org.apache.fineract.portfolio.savings.SavingsInterestCalculationType; import org.apache.fineract.portfolio.savings.SavingsPeriodFrequencyType; import org.apache.fineract.portfolio.savings.SavingsPostingInterestPeriodType; import org.apache.fineract.portfolio.savings.data.SavingsAccountTransactionDTO; import org.apache.fineract.portfolio.savings.domain.interest.PostingPeriod; import org.apache.fineract.portfolio.savings.exception.InsufficientAccountBalanceException; import org.apache.fineract.portfolio.savings.exception.SavingsAccountBlockedException; import org.apache.fineract.portfolio.savings.exception.SavingsAccountCreditsBlockedException; import org.apache.fineract.portfolio.savings.exception.SavingsAccountDebitsBlockedException; import org.apache.fineract.portfolio.savings.exception.SavingsAccountTransactionNotFoundException; import org.apache.fineract.portfolio.savings.exception.SavingsActivityPriorToClientTransferException; import org.apache.fineract.portfolio.savings.exception.SavingsOfficerAssignmentDateException; import org.apache.fineract.portfolio.savings.exception.SavingsOfficerUnassignmentDateException; import org.apache.fineract.portfolio.savings.exception.SavingsTransferTransactionsCannotBeUndoneException; import org.apache.fineract.portfolio.savings.service.SavingsEnumerations; import org.apache.fineract.portfolio.tax.domain.TaxComponent; import org.apache.fineract.portfolio.tax.domain.TaxGroup; import org.apache.fineract.portfolio.tax.service.TaxUtils; import org.apache.fineract.useradministration.domain.AppUser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.CollectionUtils; @Entity @Table(name = "m_savings_account", uniqueConstraints = { @UniqueConstraint(columnNames = { "account_no" }, name = "sa_account_no_UNIQUE"), @UniqueConstraint(columnNames = { "external_id" }, name = "sa_external_id_UNIQUE") }) @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "deposit_type_enum", discriminatorType = DiscriminatorType.INTEGER) @DiscriminatorValue("100") @SuppressWarnings({ "MemberName" }) public class SavingsAccount extends AbstractPersistableCustom { private static final Logger LOG = LoggerFactory.getLogger(SavingsAccount.class); @Version int version; @Column(name = "account_no", length = 20, unique = true, nullable = false) protected String accountNumber; @Column(name = "external_id", nullable = true) protected String externalId; @ManyToOne(optional = true) @JoinColumn(name = "client_id", nullable = true) protected Client client; @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "group_id", nullable = true) protected Group group; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "gsim_id", nullable = true) private GroupSavingsIndividualMonitoring gsim; @ManyToOne @JoinColumn(name = "product_id", nullable = false) protected SavingsProduct product; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "field_officer_id", nullable = true) protected Staff savingsOfficer; @Column(name = "status_enum", nullable = false) protected Integer status; @Column(name = "sub_status_enum", nullable = false) protected Integer sub_status = 0; @Column(name = "account_type_enum", nullable = false) protected Integer accountType; @Temporal(TemporalType.DATE) @Column(name = "submittedon_date", nullable = true) protected Date submittedOnDate; @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "submittedon_userid", nullable = true) protected AppUser submittedBy; @Temporal(TemporalType.DATE) @Column(name = "rejectedon_date") protected Date rejectedOnDate; @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "rejectedon_userid", nullable = true) protected AppUser rejectedBy; @Temporal(TemporalType.DATE) @Column(name = "withdrawnon_date") protected Date withdrawnOnDate; @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "withdrawnon_userid", nullable = true) protected AppUser withdrawnBy; @Temporal(TemporalType.DATE) @Column(name = "approvedon_date") protected Date approvedOnDate; @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "approvedon_userid", nullable = true) protected AppUser approvedBy; @Temporal(TemporalType.DATE) @Column(name = "activatedon_date", nullable = true) protected Date activatedOnDate; @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "activatedon_userid", nullable = true) protected AppUser activatedBy; @Temporal(TemporalType.DATE) @Column(name = "closedon_date") protected Date closedOnDate; @ManyToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "closedon_userid", nullable = true) protected AppUser closedBy; @Embedded protected MonetaryCurrency currency; @Column(name = "nominal_annual_interest_rate", scale = 6, precision = 19, nullable = false) protected BigDecimal nominalAnnualInterestRate; /** * The interest period is the span of time at the end of which savings in a client's account earn interest. * * A value from the {@link SavingsCompoundingInterestPeriodType} enumeration. */ @Column(name = "interest_compounding_period_enum", nullable = false) protected Integer interestCompoundingPeriodType; /** * A value from the {@link SavingsPostingInterestPeriodType} enumeration. */ @Column(name = "interest_posting_period_enum", nullable = false) protected Integer interestPostingPeriodType; /** * A value from the {@link SavingsInterestCalculationType} enumeration. */ @Column(name = "interest_calculation_type_enum", nullable = false) protected Integer interestCalculationType; /** * A value from the {@link SavingsInterestCalculationDaysInYearType} enumeration. */ @Column(name = "interest_calculation_days_in_year_type_enum", nullable = false) protected Integer interestCalculationDaysInYearType; @Column(name = "min_required_opening_balance", scale = 6, precision = 19, nullable = true) protected BigDecimal minRequiredOpeningBalance; @Column(name = "lockin_period_frequency", nullable = true) protected Integer lockinPeriodFrequency; @Column(name = "lockin_period_frequency_enum", nullable = true) protected Integer lockinPeriodFrequencyType; /** * When account becomes <code>active</code> this field is derived if <code>lockinPeriodFrequency</code> and * <code>lockinPeriodFrequencyType</code> details are present. */ @Temporal(TemporalType.DATE) @Column(name = "lockedin_until_date_derived", nullable = true) protected Date lockedInUntilDate; @Column(name = "withdrawal_fee_for_transfer", nullable = true) protected boolean withdrawalFeeApplicableForTransfer; @Column(name = "allow_overdraft") private boolean allowOverdraft; @Column(name = "overdraft_limit", scale = 6, precision = 19, nullable = true) private BigDecimal overdraftLimit; @Column(name = "nominal_annual_interest_rate_overdraft", scale = 6, precision = 19, nullable = true) protected BigDecimal nominalAnnualInterestRateOverdraft; @Column(name = "min_overdraft_for_interest_calculation", scale = 6, precision = 19, nullable = true) private BigDecimal minOverdraftForInterestCalculation; @Column(name = "enforce_min_required_balance") private boolean enforceMinRequiredBalance; @Column(name = "min_required_balance", scale = 6, precision = 19, nullable = true) private BigDecimal minRequiredBalance; @Column(name = "on_hold_funds_derived", scale = 6, precision = 19, nullable = true) private BigDecimal onHoldFunds; @Temporal(TemporalType.DATE) @Column(name = "start_interest_calculation_date") protected Date startInterestCalculationDate; @Embedded protected SavingsAccountSummary summary; @OrderBy(value = "dateOf, createdDate, id") @OneToMany(cascade = CascadeType.ALL, mappedBy = "savingsAccount", orphanRemoval = true, fetch = FetchType.LAZY) protected List<SavingsAccountTransaction> transactions = new ArrayList<>(); @OneToMany(cascade = CascadeType.ALL, mappedBy = "savingsAccount", orphanRemoval = true, fetch = FetchType.LAZY) protected Set<SavingsAccountCharge> charges = new HashSet<>(); @OneToMany(cascade = CascadeType.ALL, mappedBy = "savingsAccount", orphanRemoval = true, fetch = FetchType.LAZY) private Set<SavingsOfficerAssignmentHistory> savingsOfficerHistory = new HashSet<>(); @Transient protected boolean accountNumberRequiresAutoGeneration = false; @Transient protected SavingsAccountTransactionSummaryWrapper savingsAccountTransactionSummaryWrapper; @Transient protected SavingsHelper savingsHelper; @Column(name = "deposit_type_enum", insertable = false, updatable = false) private Integer depositType; @Column(name = "min_balance_for_interest_calculation", scale = 6, precision = 19, nullable = true) private BigDecimal minBalanceForInterestCalculation; @Column(name = "withhold_tax", nullable = false) protected boolean withHoldTax; @ManyToOne @JoinColumn(name = "tax_group_id") private TaxGroup taxGroup; @Column(name = "total_savings_amount_on_hold", scale = 6, precision = 19, nullable = true) private BigDecimal savingsOnHoldAmount; @OneToMany(cascade = CascadeType.ALL, mappedBy = "account", orphanRemoval = true, fetch = FetchType.LAZY) protected List<InteropIdentifier> identifiers = new ArrayList<>(); protected SavingsAccount() { // } public static SavingsAccount createNewApplicationForSubmittal(final Client client, final Group group, final SavingsProduct product, final Staff fieldOfficer, final String accountNo, final String externalId, final AccountType accountType, final LocalDate submittedOnDate, final AppUser submittedBy, final BigDecimal interestRate, final SavingsCompoundingInterestPeriodType interestCompoundingPeriodType, final SavingsPostingInterestPeriodType interestPostingPeriodType, final SavingsInterestCalculationType interestCalculationType, final SavingsInterestCalculationDaysInYearType interestCalculationDaysInYearType, final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, final SavingsPeriodFrequencyType lockinPeriodFrequencyType, final boolean withdrawalFeeApplicableForTransfer, final Set<SavingsAccountCharge> savingsAccountCharges, final boolean allowOverdraft, final BigDecimal overdraftLimit, final boolean enforceMinRequiredBalance, final BigDecimal minRequiredBalance, final BigDecimal nominalAnnualInterestRateOverdraft, final BigDecimal minOverdraftForInterestCalculation, final boolean withHoldTax) { final SavingsAccountStatusType status = SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL; return new SavingsAccount(client, group, product, fieldOfficer, accountNo, externalId, status, accountType, submittedOnDate, submittedBy, interestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeApplicableForTransfer, savingsAccountCharges, allowOverdraft, overdraftLimit, enforceMinRequiredBalance, minRequiredBalance, nominalAnnualInterestRateOverdraft, minOverdraftForInterestCalculation, withHoldTax); } protected SavingsAccount(final Client client, final Group group, final SavingsProduct product, final Staff fieldOfficer, final String accountNo, final String externalId, final SavingsAccountStatusType status, final AccountType accountType, final LocalDate submittedOnDate, final AppUser submittedBy, final BigDecimal nominalAnnualInterestRate, final SavingsCompoundingInterestPeriodType interestCompoundingPeriodType, final SavingsPostingInterestPeriodType interestPostingPeriodType, final SavingsInterestCalculationType interestCalculationType, final SavingsInterestCalculationDaysInYearType interestCalculationDaysInYearType, final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, final SavingsPeriodFrequencyType lockinPeriodFrequencyType, final boolean withdrawalFeeApplicableForTransfer, final Set<SavingsAccountCharge> savingsAccountCharges, final boolean allowOverdraft, final BigDecimal overdraftLimit, boolean withHoldTax) { this(client, group, product, fieldOfficer, accountNo, externalId, status, accountType, submittedOnDate, submittedBy, nominalAnnualInterestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeApplicableForTransfer, savingsAccountCharges, allowOverdraft, overdraftLimit, false, null, null, null, withHoldTax); } protected SavingsAccount(final Client client, final Group group, final SavingsProduct product, final Staff savingsOfficer, final String accountNo, final String externalId, final SavingsAccountStatusType status, final AccountType accountType, final LocalDate submittedOnDate, final AppUser submittedBy, final BigDecimal nominalAnnualInterestRate, final SavingsCompoundingInterestPeriodType interestCompoundingPeriodType, final SavingsPostingInterestPeriodType interestPostingPeriodType, final SavingsInterestCalculationType interestCalculationType, final SavingsInterestCalculationDaysInYearType interestCalculationDaysInYearType, final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, final SavingsPeriodFrequencyType lockinPeriodFrequencyType, final boolean withdrawalFeeApplicableForTransfer, final Set<SavingsAccountCharge> savingsAccountCharges, final boolean allowOverdraft, final BigDecimal overdraftLimit, final boolean enforceMinRequiredBalance, final BigDecimal minRequiredBalance, final BigDecimal nominalAnnualInterestRateOverdraft, final BigDecimal minOverdraftForInterestCalculation, boolean withHoldTax) { this.client = client; this.group = group; this.product = product; this.savingsOfficer = savingsOfficer; if (StringUtils.isBlank(accountNo)) { this.accountNumber = new RandomPasswordGenerator(19).generate(); this.accountNumberRequiresAutoGeneration = true; } else { this.accountNumber = accountNo; } this.currency = product.currency(); this.externalId = externalId; this.status = status.getValue(); this.accountType = accountType.getValue(); this.submittedOnDate = Date.from(submittedOnDate.atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()); this.submittedBy = submittedBy; this.nominalAnnualInterestRate = nominalAnnualInterestRate; this.interestCompoundingPeriodType = interestCompoundingPeriodType.getValue(); this.interestPostingPeriodType = interestPostingPeriodType.getValue(); this.interestCalculationType = interestCalculationType.getValue(); this.interestCalculationDaysInYearType = interestCalculationDaysInYearType.getValue(); this.minRequiredOpeningBalance = minRequiredOpeningBalance; this.lockinPeriodFrequency = lockinPeriodFrequency; if (lockinPeriodFrequencyType != null) { this.lockinPeriodFrequencyType = lockinPeriodFrequencyType.getValue(); } this.withdrawalFeeApplicableForTransfer = withdrawalFeeApplicableForTransfer; if (!CollectionUtils.isEmpty(savingsAccountCharges)) { this.charges = associateChargesWithThisSavingsAccount(savingsAccountCharges); } this.summary = new SavingsAccountSummary(); this.allowOverdraft = allowOverdraft; this.overdraftLimit = overdraftLimit; this.nominalAnnualInterestRateOverdraft = nominalAnnualInterestRateOverdraft; this.minOverdraftForInterestCalculation = minOverdraftForInterestCalculation; esnureOverdraftLimitsSetForOverdraftAccounts(); this.enforceMinRequiredBalance = enforceMinRequiredBalance; this.minRequiredBalance = minRequiredBalance; this.minBalanceForInterestCalculation = product.minBalanceForInterestCalculation(); // this.savingsOfficerHistory = null; this.withHoldTax = withHoldTax; this.taxGroup = product.getTaxGroup(); } /** * Used after fetching/hydrating a {@link SavingsAccount} object to inject helper services/components used for * update summary details after events/transactions on a {@link SavingsAccount}. */ public void setHelpers(final SavingsAccountTransactionSummaryWrapper savingsAccountTransactionSummaryWrapper, final SavingsHelper savingsHelper) { this.savingsAccountTransactionSummaryWrapper = savingsAccountTransactionSummaryWrapper; this.savingsHelper = savingsHelper; } public String getExternalId() { return externalId; } public boolean isNotActive() { return !isActive(); } public boolean isActive() { return SavingsAccountStatusType.fromInt(this.status).isActive(); } public boolean isNotSubmittedAndPendingApproval() { return !isSubmittedAndPendingApproval(); } public boolean isSubmittedAndPendingApproval() { return SavingsAccountStatusType.fromInt(this.status).isSubmittedAndPendingApproval(); } public boolean isApproved() { return SavingsAccountStatusType.fromInt(this.status).isApproved(); } public boolean isActivated() { boolean isActive = false; if (this.activatedOnDate != null) { isActive = true; } return isActive; } public boolean isClosed() { return SavingsAccountStatusType.fromInt(this.status).isClosed(); } public List<InteropIdentifier> getIdentifiers() { return identifiers; } public void postInterest(final MathContext mc, final LocalDate interestPostingUpToDate, final boolean isInterestTransfer, final boolean isSavingsInterestPostingAtCurrentPeriodEnd, final Integer financialYearBeginningMonth, final LocalDate postInterestOnDate) { final List<PostingPeriod> postingPeriods = calculateInterestUsing(mc, interestPostingUpToDate, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, postInterestOnDate); Money interestPostedToDate = Money.zero(this.currency); boolean recalucateDailyBalanceDetails = false; boolean applyWithHoldTax = isWithHoldTaxApplicableForInterestPosting(); final List<SavingsAccountTransaction> withholdTransactions = new ArrayList<>(); withholdTransactions.addAll(findWithHoldTransactions()); for (final PostingPeriod interestPostingPeriod : postingPeriods) { final LocalDate interestPostingTransactionDate = interestPostingPeriod.dateOfPostingTransaction(); final Money interestEarnedToBePostedForPeriod = interestPostingPeriod.getInterestEarned(); if (!interestPostingTransactionDate.isAfter(interestPostingUpToDate)) { interestPostedToDate = interestPostedToDate.plus(interestEarnedToBePostedForPeriod); final SavingsAccountTransaction postingTransaction = findInterestPostingTransactionFor(interestPostingTransactionDate); if (postingTransaction == null) { SavingsAccountTransaction newPostingTransaction; if (interestEarnedToBePostedForPeriod.isGreaterThanOrEqualTo(Money.zero(currency))) { newPostingTransaction = SavingsAccountTransaction.interestPosting(this, office(), interestPostingTransactionDate, interestEarnedToBePostedForPeriod, interestPostingPeriod.isUserPosting()); } else { newPostingTransaction = SavingsAccountTransaction.overdraftInterest(this, office(), interestPostingTransactionDate, interestEarnedToBePostedForPeriod.negated(), interestPostingPeriod.isUserPosting()); } addTransaction(newPostingTransaction); if (applyWithHoldTax) { createWithHoldTransaction(interestEarnedToBePostedForPeriod.getAmount(), interestPostingTransactionDate); } recalucateDailyBalanceDetails = true; } else { boolean correctionRequired = false; if (postingTransaction.isInterestPostingAndNotReversed()) { correctionRequired = postingTransaction.hasNotAmount(interestEarnedToBePostedForPeriod); } else { correctionRequired = postingTransaction.hasNotAmount(interestEarnedToBePostedForPeriod.negated()); } if (correctionRequired) { boolean applyWithHoldTaxForOldTransaction = false; postingTransaction.reverse(); final SavingsAccountTransaction withholdTransaction = findTransactionFor(interestPostingTransactionDate, withholdTransactions); if (withholdTransaction != null) { withholdTransaction.reverse(); applyWithHoldTaxForOldTransaction = true; } SavingsAccountTransaction newPostingTransaction; if (interestEarnedToBePostedForPeriod.isGreaterThanOrEqualTo(Money.zero(currency))) { newPostingTransaction = SavingsAccountTransaction.interestPosting(this, office(), interestPostingTransactionDate, interestEarnedToBePostedForPeriod, interestPostingPeriod.isUserPosting()); } else { newPostingTransaction = SavingsAccountTransaction.overdraftInterest(this, office(), interestPostingTransactionDate, interestEarnedToBePostedForPeriod.negated(), interestPostingPeriod.isUserPosting()); } addTransaction(newPostingTransaction); if (applyWithHoldTaxForOldTransaction) { createWithHoldTransaction(interestEarnedToBePostedForPeriod.getAmount(), interestPostingTransactionDate); } recalucateDailyBalanceDetails = true; } } } } if (recalucateDailyBalanceDetails) { // no openingBalance concept supported yet but probably will to // allow // for migrations. final Money openingAccountBalance = Money.zero(this.currency); // update existing transactions so derived balance fields are // correct. recalculateDailyBalances(openingAccountBalance, interestPostingUpToDate); } this.summary.updateSummary(this.currency, this.savingsAccountTransactionSummaryWrapper, this.transactions); } protected List<SavingsAccountTransaction> findWithHoldTransactions() { final List<SavingsAccountTransaction> withholdTransactions = new ArrayList<>(); List<SavingsAccountTransaction> trans = getTransactions(); for (final SavingsAccountTransaction transaction : trans) { if (transaction.isWithHoldTaxAndNotReversed()) { withholdTransactions.add(transaction); } } return withholdTransactions; } private boolean isWithHoldTaxApplicableForInterestPosting() { return this.withHoldTax() && this.depositAccountType().isSavingsDeposit(); } protected SavingsAccountTransaction findInterestPostingTransactionFor(final LocalDate postingDate) { SavingsAccountTransaction postingTransation = null; List<SavingsAccountTransaction> trans = getTransactions(); for (final SavingsAccountTransaction transaction : trans) { if ((transaction.isInterestPostingAndNotReversed() || transaction.isOverdraftInterestAndNotReversed()) && transaction.occursOn(postingDate)) { postingTransation = transaction; break; } } return postingTransation; } protected SavingsAccountTransaction findTransactionFor(final LocalDate postingDate, final List<SavingsAccountTransaction> transactions) { SavingsAccountTransaction transaction = null; for (final SavingsAccountTransaction savingsAccountTransaction : transactions) { if (savingsAccountTransaction.occursOn(postingDate)) { transaction = savingsAccountTransaction; break; } } return transaction; } protected boolean createWithHoldTransaction(final BigDecimal amount, final LocalDate date) { boolean isTaxAdded = false; if (this.taxGroup != null && amount.compareTo(BigDecimal.ZERO) > 0) { Map<TaxComponent, BigDecimal> taxSplit = TaxUtils.splitTax(amount, date, this.taxGroup.getTaxGroupMappings(), amount.scale()); BigDecimal totalTax = TaxUtils.totalTaxAmount(taxSplit); if (totalTax.compareTo(BigDecimal.ZERO) > 0) { SavingsAccountTransaction withholdTransaction = SavingsAccountTransaction.withHoldTax(this, office(), date, Money.of(currency, totalTax), taxSplit); addTransaction(withholdTransaction); isTaxAdded = true; } } return isTaxAdded; } protected boolean updateWithHoldTransaction(final BigDecimal amount, final SavingsAccountTransaction withholdTransaction) { boolean isTaxAdded = false; if (this.taxGroup != null && amount.compareTo(BigDecimal.ZERO) > 0) { Map<TaxComponent, BigDecimal> taxSplit = TaxUtils.splitTax(amount, withholdTransaction.transactionLocalDate(), this.taxGroup.getTaxGroupMappings(), amount.scale()); BigDecimal totalTax = TaxUtils.totalTaxAmount(taxSplit); if (totalTax.compareTo(BigDecimal.ZERO) > 0) { if (withholdTransaction.getId() == null) { withholdTransaction.updateAmount(Money.of(currency, totalTax)); withholdTransaction.getTaxDetails().clear(); SavingsAccountTransaction.updateTaxDetails(taxSplit, withholdTransaction); isTaxAdded = true; } else if (totalTax.compareTo(withholdTransaction.getAmount()) != 0) { withholdTransaction.reverse(); SavingsAccountTransaction newWithholdTransaction = SavingsAccountTransaction.withHoldTax(this, office(), withholdTransaction.transactionLocalDate(), Money.of(currency, totalTax), taxSplit); addTransaction(newWithholdTransaction); isTaxAdded = true; } } } return isTaxAdded; } // Determine the last transaction for given day protected SavingsAccountTransaction findLastTransaction(final LocalDate date) { SavingsAccountTransaction savingsTransaction = null; List<SavingsAccountTransaction> trans = getTransactions(); for (final SavingsAccountTransaction transaction : trans) { if (transaction.isNotReversed() && transaction.occursOn(date)) { savingsTransaction = transaction; break; } } return savingsTransaction; } public List<LocalDate> getManualPostingDates() { List<LocalDate> transactions = new ArrayList<>(); for (SavingsAccountTransaction trans : this.transactions) { if (trans.isInterestPosting() && trans.isNotReversed() && trans.isManualTransaction()) { transactions.add(trans.getTransactionLocalDate()); } } return transactions; } /** * All interest calculation based on END-OF-DAY-BALANCE. * * Interest calculation is performed on-the-fly over all account transactions. * * * 1. Calculate Interest From Beginning Of Account 1a. determine the 'crediting' periods that exist for this savings * acccount 1b. determine the 'compounding' periods that exist within each 'crediting' period calculate the amount * of interest due at the end of each 'crediting' period check if an existing 'interest posting' transaction exists * for date and matches the amount posted * * @param isInterestTransfer * TODO */ public List<PostingPeriod> calculateInterestUsing(final MathContext mc, final LocalDate upToInterestCalculationDate, boolean isInterestTransfer, final boolean isSavingsInterestPostingAtCurrentPeriodEnd, final Integer financialYearBeginningMonth, final LocalDate postInterestOnDate) { // no openingBalance concept supported yet but probably will to allow // for migrations. final Money openingAccountBalance = Money.zero(this.currency); // update existing transactions so derived balance fields are // correct. recalculateDailyBalances(openingAccountBalance, upToInterestCalculationDate); // 1. default to calculate interest based on entire history OR // 2. determine latest 'posting period' and find interest credited to // that period // A generate list of EndOfDayBalances (not including interest postings) final SavingsPostingInterestPeriodType postingPeriodType = SavingsPostingInterestPeriodType.fromInt(this.interestPostingPeriodType); final SavingsCompoundingInterestPeriodType compoundingPeriodType = SavingsCompoundingInterestPeriodType .fromInt(this.interestCompoundingPeriodType); final SavingsInterestCalculationDaysInYearType daysInYearType = SavingsInterestCalculationDaysInYearType .fromInt(this.interestCalculationDaysInYearType); List<LocalDate> postedAsOnDates = getManualPostingDates(); if (postInterestOnDate != null) { postedAsOnDates.add(postInterestOnDate); } final List<LocalDateInterval> postingPeriodIntervals = this.savingsHelper.determineInterestPostingPeriods( getStartInterestCalculationDate(), upToInterestCalculationDate, postingPeriodType, financialYearBeginningMonth, postedAsOnDates); final List<PostingPeriod> allPostingPeriods = new ArrayList<>(); Money periodStartingBalance; if (this.startInterestCalculationDate != null) { LocalDate startInterestCalculationDate = LocalDate.ofInstant(this.startInterestCalculationDate.toInstant(), DateUtils.getDateTimeZoneOfTenant()); final SavingsAccountTransaction transaction = findLastTransaction(startInterestCalculationDate); if (transaction == null) { final String defaultUserMessage = "No transactions were found on the specified date " + getStartInterestCalculationDate().toString() + " for account number " + this.accountNumber.toString() + " and resource id " + getId(); final ApiParameterError error = ApiParameterError.parameterError( "error.msg.savingsaccount.transaction.incorrect.start.interest.calculation.date", defaultUserMessage, "transactionDate", getStartInterestCalculationDate().toString()); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); dataValidationErrors.add(error); throw new PlatformApiDataValidationException(dataValidationErrors); } periodStartingBalance = transaction.getRunningBalance(this.currency); } else { periodStartingBalance = Money.zero(this.currency); } final SavingsInterestCalculationType interestCalculationType = SavingsInterestCalculationType.fromInt(this.interestCalculationType); final BigDecimal interestRateAsFraction = getEffectiveInterestRateAsFraction(mc, upToInterestCalculationDate); final BigDecimal overdraftInterestRateAsFraction = getEffectiveOverdraftInterestRateAsFraction(mc); final Collection<Long> interestPostTransactions = this.savingsHelper.fetchPostInterestTransactionIds(getId()); final Money minBalanceForInterestCalculation = Money.of(getCurrency(), minBalanceForInterestCalculation()); final Money minOverdraftForInterestCalculation = Money.of(getCurrency(), this.minOverdraftForInterestCalculation); for (final LocalDateInterval periodInterval : postingPeriodIntervals) { boolean isUserPosting = false; if (postedAsOnDates.contains(periodInterval.endDate().plusDays(1))) { isUserPosting = true; } final PostingPeriod postingPeriod = PostingPeriod.createFrom(periodInterval, periodStartingBalance, retreiveOrderedNonInterestPostingTransactions(), this.currency, compoundingPeriodType, interestCalculationType, interestRateAsFraction, daysInYearType.getValue(), upToInterestCalculationDate, interestPostTransactions, isInterestTransfer, minBalanceForInterestCalculation, isSavingsInterestPostingAtCurrentPeriodEnd, overdraftInterestRateAsFraction, minOverdraftForInterestCalculation, isUserPosting, financialYearBeginningMonth); periodStartingBalance = postingPeriod.closingBalance(); allPostingPeriods.add(postingPeriod); } this.savingsHelper.calculateInterestForAllPostingPeriods(this.currency, allPostingPeriods, getLockedInUntilLocalDate(), isTransferInterestToOtherAccount()); this.summary.updateFromInterestPeriodSummaries(this.currency, allPostingPeriods); this.summary.updateSummary(this.currency, this.savingsAccountTransactionSummaryWrapper, this.transactions); return allPostingPeriods; } private BigDecimal getEffectiveOverdraftInterestRateAsFraction(MathContext mc) { return this.nominalAnnualInterestRateOverdraft.divide(BigDecimal.valueOf(100L), mc); } @SuppressWarnings("unused") protected BigDecimal getEffectiveInterestRateAsFraction(final MathContext mc, final LocalDate upToInterestCalculationDate) { return this.nominalAnnualInterestRate.divide(BigDecimal.valueOf(100L), mc); } protected List<SavingsAccountTransaction> retreiveOrderedNonInterestPostingTransactions() { final List<SavingsAccountTransaction> listOfTransactionsSorted = retreiveListOfTransactions(); final List<SavingsAccountTransaction> orderedNonInterestPostingTransactions = new ArrayList<>(); for (final SavingsAccountTransaction transaction : listOfTransactionsSorted) { if (!(transaction.isInterestPostingAndNotReversed() || transaction.isOverdraftInterestAndNotReversed()) && transaction.isNotReversed()) { orderedNonInterestPostingTransactions.add(transaction); } } orderedNonInterestPostingTransactions.sort(new SavingsAccountTransactionComparator()); return orderedNonInterestPostingTransactions; } protected List<SavingsAccountTransaction> retreiveListOfTransactions() { final List<SavingsAccountTransaction> listOfTransactionsSorted = new ArrayList<>(); listOfTransactionsSorted.addAll(this.transactions); final SavingsAccountTransactionComparator transactionComparator = new SavingsAccountTransactionComparator(); Collections.sort(listOfTransactionsSorted, transactionComparator); return listOfTransactionsSorted; } protected void recalculateDailyBalances(final Money openingAccountBalance, final LocalDate interestPostingUpToDate) { Money runningBalance = openingAccountBalance.copy(); List<SavingsAccountTransaction> accountTransactionsSorted = retreiveListOfTransactions(); boolean isTransactionsModified = false; for (final SavingsAccountTransaction transaction : accountTransactionsSorted) { if (transaction.isReversed()) { transaction.zeroBalanceFields(); } else { Money overdraftAmount = Money.zero(this.currency); Money transactionAmount = Money.zero(this.currency); if (transaction.isCredit() || transaction.isAmountRelease()) { if (runningBalance.isLessThanZero()) { Money diffAmount = transaction.getAmount(this.currency).plus(runningBalance); if (diffAmount.isGreaterThanZero()) { overdraftAmount = transaction.getAmount(this.currency).minus(diffAmount); } else { overdraftAmount = transaction.getAmount(this.currency); } } transactionAmount = transactionAmount.plus(transaction.getAmount(this.currency)); } else if (transaction.isDebit() || transaction.isAmountOnHold()) { if (runningBalance.isLessThanZero()) { overdraftAmount = transaction.getAmount(this.currency); } transactionAmount = transactionAmount.minus(transaction.getAmount(this.currency)); } runningBalance = runningBalance.plus(transactionAmount); transaction.updateRunningBalance(runningBalance); if (overdraftAmount.isZero() && runningBalance.isLessThanZero()) { overdraftAmount = overdraftAmount.plus(runningBalance.getAmount().negate()); } if (transaction.getId() == null && overdraftAmount.isGreaterThanZero()) { transaction.updateOverdraftAmount(overdraftAmount.getAmount()); } else if (overdraftAmount.isNotEqualTo(transaction.getOverdraftAmount(getCurrency()))) { SavingsAccountTransaction accountTransaction = SavingsAccountTransaction.copyTransaction(transaction); if (transaction.isChargeTransaction()) { Set<SavingsAccountChargePaidBy> chargesPaidBy = transaction.getSavingsAccountChargesPaid(); final Set<SavingsAccountChargePaidBy> newChargePaidBy = new HashSet<>(); chargesPaidBy.forEach(x -> newChargePaidBy .add(SavingsAccountChargePaidBy.instance(accountTransaction, x.getSavingsAccountCharge(), x.getAmount()))); accountTransaction.getSavingsAccountChargesPaid().addAll(newChargePaidBy); } transaction.reverse(); if (overdraftAmount.isGreaterThanZero()) { accountTransaction.updateOverdraftAmount(overdraftAmount.getAmount()); } accountTransaction.updateRunningBalance(runningBalance); addTransaction(accountTransaction); isTransactionsModified = true; } } } if (isTransactionsModified) { accountTransactionsSorted = retreiveListOfTransactions(); } resetAccountTransactionsEndOfDayBalances(accountTransactionsSorted, interestPostingUpToDate); } protected void resetAccountTransactionsEndOfDayBalances(final List<SavingsAccountTransaction> accountTransactionsSorted, final LocalDate interestPostingUpToDate) { // loop over transactions in reverse LocalDate endOfBalanceDate = interestPostingUpToDate; for (int i = accountTransactionsSorted.size() - 1; i >= 0; i--) { final SavingsAccountTransaction transaction = accountTransactionsSorted.get(i); if (transaction.isNotReversed() && !(transaction.isInterestPostingAndNotReversed() || transaction.isOverdraftInterestAndNotReversed())) { transaction.updateCumulativeBalanceAndDates(this.currency, endOfBalanceDate); // this transactions transaction date is end of balance date for // previous transaction. endOfBalanceDate = transaction.transactionLocalDate().minusDays(1); } } } public SavingsAccountTransaction deposit(final SavingsAccountTransactionDTO transactionDTO) { return deposit(transactionDTO, SavingsAccountTransactionType.DEPOSIT); } public SavingsAccountTransaction dividendPayout(final SavingsAccountTransactionDTO transactionDTO) { return deposit(transactionDTO, SavingsAccountTransactionType.DIVIDEND_PAYOUT); } public SavingsAccountTransaction deposit(final SavingsAccountTransactionDTO transactionDTO, final SavingsAccountTransactionType savingsAccountTransactionType) { final String resourceTypeName = depositAccountType().resourceName(); if (isNotActive()) { final String defaultUserMessage = "Transaction is not allowed. Account is not active."; final ApiParameterError error = ApiParameterError.parameterError( "error.msg." + resourceTypeName + ".transaction.account.is.not.active", defaultUserMessage, "transactionDate", transactionDTO.getTransactionDate().format(transactionDTO.getFormatter())); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); dataValidationErrors.add(error); throw new PlatformApiDataValidationException(dataValidationErrors); } if (isDateInTheFuture(transactionDTO.getTransactionDate())) { final String defaultUserMessage = "Transaction date cannot be in the future."; final ApiParameterError error = ApiParameterError.parameterError("error.msg." + resourceTypeName + ".transaction.in.the.future", defaultUserMessage, "transactionDate", transactionDTO.getTransactionDate().format(transactionDTO.getFormatter())); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); dataValidationErrors.add(error); throw new PlatformApiDataValidationException(dataValidationErrors); } if (transactionDTO.getTransactionDate().isBefore(getActivationLocalDate())) { final Object[] defaultUserArgs = Arrays.asList(transactionDTO.getTransactionDate().format(transactionDTO.getFormatter()), getActivationLocalDate().format(transactionDTO.getFormatter())).toArray(); final String defaultUserMessage = "Transaction date cannot be before accounts activation date."; final ApiParameterError error = ApiParameterError.parameterError( "error.msg." + resourceTypeName + ".transaction.before.activation.date", defaultUserMessage, "transactionDate", defaultUserArgs); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); dataValidationErrors.add(error); throw new PlatformApiDataValidationException(dataValidationErrors); } validateActivityNotBeforeClientOrGroupTransferDate(SavingsEvent.SAVINGS_DEPOSIT, transactionDTO.getTransactionDate()); final Money amount = Money.of(this.currency, transactionDTO.getTransactionAmount()); final SavingsAccountTransaction transaction = SavingsAccountTransaction.deposit(this, office(), transactionDTO.getPaymentDetail(), transactionDTO.getTransactionDate(), amount, transactionDTO.getCreatedDate(), transactionDTO.getAppUser(), savingsAccountTransactionType); addTransaction(transaction); this.summary.updateSummary(this.currency, this.savingsAccountTransactionSummaryWrapper, this.transactions); if (this.sub_status.equals(SavingsAccountSubStatusEnum.INACTIVE.getValue()) || this.sub_status.equals(SavingsAccountSubStatusEnum.DORMANT.getValue())) { this.sub_status = SavingsAccountSubStatusEnum.NONE.getValue(); } return transaction; } public LocalDate getActivationLocalDate() { LocalDate activationLocalDate = null; if (this.activatedOnDate != null) { activationLocalDate = LocalDate.ofInstant(this.activatedOnDate.toInstant(), DateUtils.getDateTimeZoneOfTenant()); } return activationLocalDate; } public LocalDate getWithdrawnOnDate() { return withdrawnOnDate == null ? null : LocalDate.ofInstant(withdrawnOnDate.toInstant(), DateUtils.getDateTimeZoneOfTenant()); } // startInterestCalculationDate is set during migration so that there is no // interference with interest posting of previous system public LocalDate getStartInterestCalculationDate() { LocalDate startInterestCalculationLocalDate = null; if (this.startInterestCalculationDate != null) { startInterestCalculationLocalDate = LocalDate.ofInstant(this.startInterestCalculationDate.toInstant(), DateUtils.getDateTimeZoneOfTenant()); } else { startInterestCalculationLocalDate = getActivationLocalDate(); } return startInterestCalculationLocalDate; } public SavingsAccountTransaction withdraw(final SavingsAccountTransactionDTO transactionDTO, final boolean applyWithdrawFee) { if (!isTransactionsAllowed()) { final String defaultUserMessage = "Transaction is not allowed. Account is not active."; final ApiParameterError error = ApiParameterError.parameterError("error.msg.savingsaccount.transaction.account.is.not.active", defaultUserMessage, "transactionDate", transactionDTO.getTransactionDate().format(transactionDTO.getFormatter())); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); dataValidationErrors.add(error); throw new PlatformApiDataValidationException(dataValidationErrors); } if (isDateInTheFuture(transactionDTO.getTransactionDate())) { final String defaultUserMessage = "Transaction date cannot be in the future."; final ApiParameterError error = ApiParameterError.parameterError("error.msg.savingsaccount.transaction.in.the.future", defaultUserMessage, "transactionDate", transactionDTO.getTransactionDate().format(transactionDTO.getFormatter())); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); dataValidationErrors.add(error); throw new PlatformApiDataValidationException(dataValidationErrors); } if (transactionDTO.getTransactionDate().isBefore(getActivationLocalDate())) { final Object[] defaultUserArgs = Arrays.asList(transactionDTO.getTransactionDate().format(transactionDTO.getFormatter()), getActivationLocalDate().format(transactionDTO.getFormatter())).toArray(); final String defaultUserMessage = "Transaction date cannot be before accounts activation date."; final ApiParameterError error = ApiParameterError.parameterError("error.msg.savingsaccount.transaction.before.activation.date", defaultUserMessage, "transactionDate", defaultUserArgs); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); dataValidationErrors.add(error); throw new PlatformApiDataValidationException(dataValidationErrors); } if (isAccountLocked(transactionDTO.getTransactionDate())) { final String defaultUserMessage = "Withdrawal is not allowed. No withdrawals are allowed until after " + getLockedInUntilLocalDate().format(transactionDTO.getFormatter()); final ApiParameterError error = ApiParameterError.parameterError( "error.msg.savingsaccount.transaction.withdrawals.blocked.during.lockin.period", defaultUserMessage, "transactionDate", transactionDTO.getTransactionDate().format(transactionDTO.getFormatter()), getLockedInUntilLocalDate().format(transactionDTO.getFormatter())); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); dataValidationErrors.add(error); throw new PlatformApiDataValidationException(dataValidationErrors); } validateActivityNotBeforeClientOrGroupTransferDate(SavingsEvent.SAVINGS_WITHDRAWAL, transactionDTO.getTransactionDate()); if (applyWithdrawFee) { // auto pay withdrawal fee payWithdrawalFee(transactionDTO.getTransactionAmount(), transactionDTO.getTransactionDate(), transactionDTO.getAppUser()); } final Money transactionAmountMoney = Money.of(this.currency, transactionDTO.getTransactionAmount()); final SavingsAccountTransaction transaction = SavingsAccountTransaction.withdrawal(this, office(), transactionDTO.getPaymentDetail(), transactionDTO.getTransactionDate(), transactionAmountMoney, transactionDTO.getCreatedDate(), transactionDTO.getAppUser()); addTransaction(transaction); if (this.sub_status.equals(SavingsAccountSubStatusEnum.INACTIVE.getValue()) || this.sub_status.equals(SavingsAccountSubStatusEnum.DORMANT.getValue())) { this.sub_status = SavingsAccountSubStatusEnum.NONE.getValue(); } return transaction; } public BigDecimal calculateWithdrawalFee(final BigDecimal transactionAmount) { BigDecimal result = BigDecimal.ZERO; if (isWithdrawalFeeApplicableForTransfer()) { for (SavingsAccountCharge charge : this.charges()) { if (charge.isWithdrawalFee() && charge.isActive()) { result = result.add(charge.calculateWithdralFeeAmount(transactionAmount), MoneyHelper.getMathContext()); } } } return result; } private void payWithdrawalFee(final BigDecimal transactionAmount, final LocalDate transactionDate, final AppUser user) { for (SavingsAccountCharge charge : this.charges()) { if (charge.isWithdrawalFee() && charge.isActive()) { charge.updateWithdralFeeAmount(transactionAmount); this.payCharge(charge, charge.getAmountOutstanding(this.getCurrency()), transactionDate, user); } } } public boolean isBeforeLastPostingPeriod(final LocalDate transactionDate) { boolean transactionBeforeLastInterestPosting = false; for (final SavingsAccountTransaction transaction : retreiveListOfTransactions()) { if ((transaction.isInterestPostingAndNotReversed() || transaction.isOverdraftInterestAndNotReversed()) && transaction.isAfter(transactionDate)) { transactionBeforeLastInterestPosting = true; break; } } return transactionBeforeLastInterestPosting; } public void validateAccountBalanceDoesNotBecomeNegative(final BigDecimal transactionAmount, final boolean isException, final List<DepositAccountOnHoldTransaction> depositAccountOnHoldTransactions) { final List<SavingsAccountTransaction> transactionsSortedByDate = retreiveListOfTransactions(); Money runningBalance = Money.zero(this.currency); Money minRequiredBalance = minRequiredBalanceDerived(getCurrency()); LocalDate lastSavingsDate = null; final BigDecimal withdrawalFee = null; for (final SavingsAccountTransaction transaction : transactionsSortedByDate) { if (transaction.isNotReversed() && transaction.isCredit()) { runningBalance = runningBalance.plus(transaction.getAmount(this.currency)); } else if (transaction.isNotReversed() && transaction.isDebit()) { runningBalance = runningBalance.minus(transaction.getAmount(this.currency)); } else { continue; } /* * Loop through the onHold funds and see if we need to deduct or add to minimum required balance and the * point in time the transaction was made: */ if (depositAccountOnHoldTransactions != null) { for (final DepositAccountOnHoldTransaction onHoldTransaction : depositAccountOnHoldTransactions) { // Compare the balance of the on hold: if ((onHoldTransaction.getTransactionDate().isBefore(transaction.transactionLocalDate()) || onHoldTransaction.getTransactionDate().isEqual(transaction.transactionLocalDate())) && (lastSavingsDate == null || onHoldTransaction.getTransactionDate().isAfter(lastSavingsDate))) { if (onHoldTransaction.getTransactionType().isHold()) { minRequiredBalance = minRequiredBalance.plus(onHoldTransaction.getAmountMoney(this.currency)); } else { minRequiredBalance = minRequiredBalance.minus(onHoldTransaction.getAmountMoney(this.currency)); } } } } // deal with potential minRequiredBalance and // enforceMinRequiredBalance if (!isException && transaction.canProcessBalanceCheck() && !isOverdraft()) { if (runningBalance.minus(minRequiredBalance).isLessThanZero()) { throw new InsufficientAccountBalanceException("transactionAmount", getAccountBalance(), withdrawalFee, transactionAmount); } } lastSavingsDate = transaction.transactionLocalDate(); } // In overdraft cases, minRequiredBalance can be in violation after // interest posting // and should be checked after processing all transactions if (isOverdraft()) { if (runningBalance.minus(minRequiredBalance).isLessThanZero()) { throw new InsufficientAccountBalanceException("transactionAmount", getAccountBalance(), withdrawalFee, transactionAmount); } } if (this.getSavingsHoldAmount().compareTo(BigDecimal.ZERO) > 0) { if (runningBalance.minus(this.getSavingsHoldAmount()).isLessThanZero()) { throw new InsufficientAccountBalanceException("transactionAmount", getAccountBalance(), withdrawalFee, transactionAmount); } } } public void validateAccountBalanceDoesNotBecomeNegative(final String transactionAction, final List<DepositAccountOnHoldTransaction> depositAccountOnHoldTransactions) { final List<SavingsAccountTransaction> transactionsSortedByDate = retreiveListOfTransactions(); Money runningBalance = Money.zero(this.currency); Money minRequiredBalance = minRequiredBalanceDerived(getCurrency()); LocalDate lastSavingsDate = null; for (final SavingsAccountTransaction transaction : transactionsSortedByDate) { if (transaction.isNotReversed() && transaction.isCredit()) { runningBalance = runningBalance.plus(transaction.getAmount(this.currency)); } else if (transaction.isNotReversed() && transaction.isDebit()) { runningBalance = runningBalance.minus(transaction.getAmount(this.currency)); } /* * Loop through the onHold funds and see if we need to deduct or add to minimum required balance and the * point in time the transaction was made: */ if (depositAccountOnHoldTransactions != null) { for (final DepositAccountOnHoldTransaction onHoldTransaction : depositAccountOnHoldTransactions) { // Compare the balance of the on hold: if ((onHoldTransaction.getTransactionDate().isBefore(transaction.transactionLocalDate()) || onHoldTransaction.getTransactionDate().isEqual(transaction.transactionLocalDate())) && (lastSavingsDate == null || onHoldTransaction.getTransactionDate().isAfter(lastSavingsDate))) { if (onHoldTransaction.getTransactionType().isHold()) { minRequiredBalance = minRequiredBalance.plus(onHoldTransaction.getAmountMoney(this.currency)); } else { minRequiredBalance = minRequiredBalance.minus(onHoldTransaction.getAmountMoney(this.currency)); } } } } // enforceMinRequiredBalance if (transaction.canProcessBalanceCheck()) { if (runningBalance.minus(minRequiredBalance).isLessThanZero()) { final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(depositAccountType().resourceName() + transactionAction); if (!this.allowOverdraft) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("results.in.balance.going.negative"); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } } lastSavingsDate = transaction.transactionLocalDate(); } BigDecimal withdrawalFee = null; BigDecimal transactionAmount = null; if (isOverdraft()) { if (runningBalance.minus(minRequiredBalance).isLessThanZero()) { throw new InsufficientAccountBalanceException("transactionAmount", getAccountBalance(), withdrawalFee, transactionAmount); } } } protected boolean isAccountLocked(final LocalDate transactionDate) { boolean isLocked = false; final boolean accountHasLockedInSetting = this.lockedInUntilDate != null; if (accountHasLockedInSetting) { isLocked = getLockedInUntilLocalDate().isAfter(transactionDate); } return isLocked; } protected LocalDate getLockedInUntilLocalDate() { LocalDate lockedInUntilLocalDate = null; if (this.lockedInUntilDate != null) { lockedInUntilLocalDate = LocalDate.ofInstant(this.lockedInUntilDate.toInstant(), DateUtils.getDateTimeZoneOfTenant()); } return lockedInUntilLocalDate; } private boolean isDateInTheFuture(final LocalDate transactionDate) { return transactionDate.isAfter(DateUtils.getLocalDateOfTenant()); } public BigDecimal getAccountBalance() { return this.summary.getAccountBalance(this.currency).getAmount(); } public void modifyApplication(final JsonCommand command, final Map<String, Object> actualChanges) { final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.modifyApplicationAction); this.modifyApplication(command, actualChanges, baseDataValidator); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } public void modifyApplication(final JsonCommand command, final Map<String, Object> actualChanges, final DataValidatorBuilder baseDataValidator) { final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status); if (!SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.hasStateOf(currentStatus)) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("not.in.submittedandpendingapproval.state"); return; } final String localeAsInput = command.locale(); final String dateFormat = command.dateFormat(); if (command.isChangeInLocalDateParameterNamed(SavingsApiConstants.submittedOnDateParamName, getSubmittedOnLocalDate())) { final LocalDate newValue = command.localDateValueOfParameterNamed(SavingsApiConstants.submittedOnDateParamName); final String newValueAsString = command.stringValueOfParameterNamed(SavingsApiConstants.submittedOnDateParamName); actualChanges.put(SavingsApiConstants.submittedOnDateParamName, newValueAsString); actualChanges.put(SavingsApiConstants.localeParamName, localeAsInput); actualChanges.put(SavingsApiConstants.dateFormatParamName, dateFormat); this.submittedOnDate = Date.from(newValue.atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()); } if (command.isChangeInStringParameterNamed(SavingsApiConstants.accountNoParamName, this.accountNumber)) { final String newValue = command.stringValueOfParameterNamed(SavingsApiConstants.accountNoParamName); actualChanges.put(SavingsApiConstants.accountNoParamName, newValue); this.accountNumber = StringUtils.defaultIfEmpty(newValue, null); } if (command.isChangeInStringParameterNamed(SavingsApiConstants.externalIdParamName, this.externalId)) { final String newValue = command.stringValueOfParameterNamed(SavingsApiConstants.externalIdParamName); actualChanges.put(SavingsApiConstants.externalIdParamName, newValue); this.externalId = StringUtils.defaultIfEmpty(newValue, null); } if (command.isChangeInLongParameterNamed(SavingsApiConstants.clientIdParamName, clientId())) { final Long newValue = command.longValueOfParameterNamed(SavingsApiConstants.clientIdParamName); actualChanges.put(SavingsApiConstants.clientIdParamName, newValue); } if (command.isChangeInLongParameterNamed(SavingsApiConstants.groupIdParamName, groupId())) { final Long newValue = command.longValueOfParameterNamed(SavingsApiConstants.groupIdParamName); actualChanges.put(SavingsApiConstants.groupIdParamName, newValue); } if (command.isChangeInLongParameterNamed(SavingsApiConstants.productIdParamName, this.product.getId())) { final Long newValue = command.longValueOfParameterNamed(SavingsApiConstants.productIdParamName); actualChanges.put(SavingsApiConstants.productIdParamName, newValue); } if (command.isChangeInLongParameterNamed(SavingsApiConstants.fieldOfficerIdParamName, hasSavingsOfficerId())) { final Long newValue = command.longValueOfParameterNamed(SavingsApiConstants.fieldOfficerIdParamName); actualChanges.put(SavingsApiConstants.fieldOfficerIdParamName, newValue); } if (command.isChangeInBigDecimalParameterNamed(SavingsApiConstants.nominalAnnualInterestRateParamName, this.nominalAnnualInterestRate)) { final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(SavingsApiConstants.nominalAnnualInterestRateParamName); actualChanges.put(SavingsApiConstants.nominalAnnualInterestRateParamName, newValue); actualChanges.put("locale", localeAsInput); this.nominalAnnualInterestRate = newValue; } if (command.isChangeInIntegerParameterNamed(SavingsApiConstants.interestCompoundingPeriodTypeParamName, this.interestCompoundingPeriodType)) { final Integer newValue = command.integerValueOfParameterNamed(SavingsApiConstants.interestCompoundingPeriodTypeParamName); this.interestCompoundingPeriodType = newValue != null ? SavingsCompoundingInterestPeriodType.fromInt(newValue).getValue() : newValue; actualChanges.put(SavingsApiConstants.interestCompoundingPeriodTypeParamName, this.interestCompoundingPeriodType); } if (command.isChangeInIntegerParameterNamed(SavingsApiConstants.interestPostingPeriodTypeParamName, this.interestPostingPeriodType)) { final Integer newValue = command.integerValueOfParameterNamed(SavingsApiConstants.interestPostingPeriodTypeParamName); this.interestPostingPeriodType = newValue != null ? SavingsPostingInterestPeriodType.fromInt(newValue).getValue() : newValue; actualChanges.put(SavingsApiConstants.interestPostingPeriodTypeParamName, this.interestPostingPeriodType); } if (command.isChangeInIntegerParameterNamed(SavingsApiConstants.interestCalculationTypeParamName, this.interestCalculationType)) { final Integer newValue = command.integerValueOfParameterNamed(SavingsApiConstants.interestCalculationTypeParamName); this.interestCalculationType = newValue != null ? SavingsInterestCalculationType.fromInt(newValue).getValue() : newValue; actualChanges.put(SavingsApiConstants.interestCalculationTypeParamName, this.interestCalculationType); } if (command.isChangeInIntegerParameterNamed(SavingsApiConstants.interestCalculationDaysInYearTypeParamName, this.interestCalculationDaysInYearType)) { final Integer newValue = command.integerValueOfParameterNamed(SavingsApiConstants.interestCalculationDaysInYearTypeParamName); this.interestCalculationDaysInYearType = newValue != null ? SavingsInterestCalculationDaysInYearType.fromInt(newValue).getValue() : newValue; actualChanges.put(SavingsApiConstants.interestCalculationDaysInYearTypeParamName, this.interestCalculationDaysInYearType); } if (command.isChangeInBigDecimalParameterNamedDefaultingZeroToNull(SavingsApiConstants.minRequiredOpeningBalanceParamName, this.minRequiredOpeningBalance)) { final BigDecimal newValue = command .bigDecimalValueOfParameterNamedDefaultToNullIfZero(SavingsApiConstants.minRequiredOpeningBalanceParamName); actualChanges.put(SavingsApiConstants.minRequiredOpeningBalanceParamName, newValue); actualChanges.put("locale", localeAsInput); this.minRequiredOpeningBalance = Money.of(this.currency, newValue).getAmount(); } if (command.isChangeInIntegerParameterNamedDefaultingZeroToNull(SavingsApiConstants.lockinPeriodFrequencyParamName, this.lockinPeriodFrequency)) { final Integer newValue = command .integerValueOfParameterNamedDefaultToNullIfZero(SavingsApiConstants.lockinPeriodFrequencyParamName); actualChanges.put(SavingsApiConstants.lockinPeriodFrequencyParamName, newValue); actualChanges.put("locale", localeAsInput); this.lockinPeriodFrequency = newValue; } if (command.isChangeInIntegerParameterNamed(SavingsApiConstants.lockinPeriodFrequencyTypeParamName, this.lockinPeriodFrequencyType)) { final Integer newValue = command.integerValueOfParameterNamed(SavingsApiConstants.lockinPeriodFrequencyTypeParamName); actualChanges.put(SavingsApiConstants.lockinPeriodFrequencyTypeParamName, newValue); this.lockinPeriodFrequencyType = newValue != null ? SavingsPeriodFrequencyType.fromInt(newValue).getValue() : newValue; } // set period type to null if frequency is null if (this.lockinPeriodFrequency == null) { this.lockinPeriodFrequencyType = null; } if (command.isChangeInBooleanParameterNamed(withdrawalFeeForTransfersParamName, this.withdrawalFeeApplicableForTransfer)) { final boolean newValue = command.booleanPrimitiveValueOfParameterNamed(withdrawalFeeForTransfersParamName); actualChanges.put(withdrawalFeeForTransfersParamName, newValue); this.withdrawalFeeApplicableForTransfer = newValue; } // charges final String chargesParamName = "charges"; if (command.hasParameter(chargesParamName)) { final JsonArray jsonArray = command.arrayOfParameterNamed(chargesParamName); if (jsonArray != null) { actualChanges.put(chargesParamName, command.jsonFragment(chargesParamName)); } } if (command.isChangeInBooleanParameterNamed(allowOverdraftParamName, this.allowOverdraft)) { final boolean newValue = command.booleanPrimitiveValueOfParameterNamed(allowOverdraftParamName); actualChanges.put(allowOverdraftParamName, newValue); this.allowOverdraft = newValue; } if (command.isChangeInBigDecimalParameterNamedDefaultingZeroToNull(overdraftLimitParamName, this.overdraftLimit)) { final BigDecimal newValue = command.bigDecimalValueOfParameterNamedDefaultToNullIfZero(overdraftLimitParamName); actualChanges.put(overdraftLimitParamName, newValue); actualChanges.put(localeParamName, localeAsInput); this.overdraftLimit = newValue; } if (command.isChangeInBigDecimalParameterNamedDefaultingZeroToNull(nominalAnnualInterestRateOverdraftParamName, this.nominalAnnualInterestRateOverdraft)) { final BigDecimal newValue = command .bigDecimalValueOfParameterNamedDefaultToNullIfZero(nominalAnnualInterestRateOverdraftParamName); actualChanges.put(nominalAnnualInterestRateOverdraftParamName, newValue); actualChanges.put(localeParamName, localeAsInput); this.nominalAnnualInterestRateOverdraft = newValue; } if (command.isChangeInBigDecimalParameterNamedDefaultingZeroToNull(minOverdraftForInterestCalculationParamName, this.minOverdraftForInterestCalculation)) { final BigDecimal newValue = command .bigDecimalValueOfParameterNamedDefaultToNullIfZero(minOverdraftForInterestCalculationParamName); actualChanges.put(minOverdraftForInterestCalculationParamName, newValue); actualChanges.put(localeParamName, localeAsInput); this.minOverdraftForInterestCalculation = newValue; } if (!this.allowOverdraft) { this.overdraftLimit = null; this.nominalAnnualInterestRateOverdraft = null; this.minOverdraftForInterestCalculation = null; } if (command.isChangeInBooleanParameterNamed(enforceMinRequiredBalanceParamName, this.enforceMinRequiredBalance)) { final boolean newValue = command.booleanPrimitiveValueOfParameterNamed(enforceMinRequiredBalanceParamName); actualChanges.put(enforceMinRequiredBalanceParamName, newValue); this.enforceMinRequiredBalance = newValue; } if (command.isChangeInBigDecimalParameterNamedDefaultingZeroToNull(minRequiredBalanceParamName, this.minRequiredBalance)) { final BigDecimal newValue = command.bigDecimalValueOfParameterNamedDefaultToNullIfZero(minRequiredBalanceParamName); actualChanges.put(minRequiredBalanceParamName, newValue); actualChanges.put(localeParamName, localeAsInput); this.minRequiredBalance = newValue; } if (command.isChangeInBooleanParameterNamed(withHoldTaxParamName, this.withHoldTax)) { final boolean newValue = command.booleanPrimitiveValueOfParameterNamed(withHoldTaxParamName); actualChanges.put(withHoldTaxParamName, newValue); this.withHoldTax = newValue; if (this.withHoldTax && this.taxGroup == null) { baseDataValidator.reset().parameter(withHoldTaxParamName).failWithCode("not.supported.for.this.account"); } } validateLockinDetails(baseDataValidator); esnureOverdraftLimitsSetForOverdraftAccounts(); } /** * If overdrafts are allowed and the overdraft limit is not set, set the same to Zero **/ private void esnureOverdraftLimitsSetForOverdraftAccounts() { this.overdraftLimit = this.overdraftLimit == null ? BigDecimal.ZERO : this.overdraftLimit; this.nominalAnnualInterestRateOverdraft = this.nominalAnnualInterestRateOverdraft == null ? BigDecimal.ZERO : this.nominalAnnualInterestRateOverdraft; this.minOverdraftForInterestCalculation = this.minOverdraftForInterestCalculation == null ? BigDecimal.ZERO : this.minOverdraftForInterestCalculation; } private void validateLockinDetails(final DataValidatorBuilder baseDataValidator) { /* * final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); final * DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) * .resource(resourceName); */ if (this.lockinPeriodFrequency == null) { baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(this.lockinPeriodFrequencyType).ignoreIfNull() .inMinMaxRange(0, 3); if (this.lockinPeriodFrequencyType != null) { baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(this.lockinPeriodFrequency).notNull() .integerZeroOrGreater(); } } else { baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(this.lockinPeriodFrequencyType) .integerZeroOrGreater(); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(this.lockinPeriodFrequencyType).notNull() .inMinMaxRange(0, 3); } } public Map<String, Object> deriveAccountingBridgeData(final CurrencyData currencyData, final Set<Long> existingTransactionIds, final Set<Long> existingReversedTransactionIds, boolean isAccountTransfer) { final Map<String, Object> accountingBridgeData = new LinkedHashMap<>(); accountingBridgeData.put("savingsId", getId()); accountingBridgeData.put("savingsProductId", productId()); accountingBridgeData.put("currency", currencyData); accountingBridgeData.put("officeId", officeId()); accountingBridgeData.put("cashBasedAccountingEnabled", isCashBasedAccountingEnabledOnSavingsProduct()); accountingBridgeData.put("accrualBasedAccountingEnabled", isAccrualBasedAccountingEnabledOnSavingsProduct()); accountingBridgeData.put("isAccountTransfer", isAccountTransfer); final List<Map<String, Object>> newSavingsTransactions = new ArrayList<>(); List<SavingsAccountTransaction> trans = getTransactions(); for (final SavingsAccountTransaction transaction : trans) { if (transaction.isReversed() && !existingReversedTransactionIds.contains(transaction.getId())) { newSavingsTransactions.add(transaction.toMapData(currencyData)); } else if (!existingTransactionIds.contains(transaction.getId())) { newSavingsTransactions.add(transaction.toMapData(currencyData)); } } accountingBridgeData.put("newSavingsTransactions", newSavingsTransactions); return accountingBridgeData; } public Collection<Long> findExistingTransactionIds() { final Collection<Long> ids = new ArrayList<>(); List<SavingsAccountTransaction> trans = getTransactions(); for (final SavingsAccountTransaction transaction : trans) { ids.add(transaction.getId()); } return ids; } public Collection<Long> findExistingReversedTransactionIds() { final Collection<Long> ids = new ArrayList<>(); List<SavingsAccountTransaction> trans = getTransactions(); for (final SavingsAccountTransaction transaction : trans) { if (transaction.isReversed()) { ids.add(transaction.getId()); } } return ids; } public void update(final Client client) { this.client = client; } public void update(final Group group) { this.group = group; } public void update(final SavingsProduct product) { this.product = product; this.minBalanceForInterestCalculation = product.minBalanceForInterestCalculation(); } public void update(final Staff savingsOfficer) { this.savingsOfficer = savingsOfficer; } public void updateAccountNo(final String newAccountNo) { this.accountNumber = newAccountNo; this.accountNumberRequiresAutoGeneration = false; } public boolean isAccountNumberRequiresAutoGeneration() { return this.accountNumberRequiresAutoGeneration; } public Long productId() { return this.product.getId(); } public SavingsProduct savingsProduct() { return this.product; } private Boolean isCashBasedAccountingEnabledOnSavingsProduct() { return this.product.isCashBasedAccountingEnabled(); } private Boolean isAccrualBasedAccountingEnabledOnSavingsProduct() { return this.product.isAccrualBasedAccountingEnabled(); } public Long officeId() { Long officeId = null; if (this.client != null) { officeId = this.client.officeId(); } else if (this.group != null) { officeId = this.group.officeId(); } return officeId; } public Office office() { Office office = null; if (this.client != null) { office = this.client.getOffice(); } else if (this.group != null) { office = this.group.getOffice(); } return office; } public Staff getSavingsOfficer() { return this.savingsOfficer; } public void unassignSavingsOfficer() { this.savingsOfficer = null; } public void assignSavingsOfficer(final Staff fieldOfficer) { this.savingsOfficer = fieldOfficer; } public Long clientId() { Long id = null; if (this.client != null) { id = this.client.getId(); } return id; } public Long groupId() { Long id = null; if (this.group != null) { id = this.group.getId(); } return id; } public GroupSavingsIndividualMonitoring getGsim() { return gsim; } public void setGsim(GroupSavingsIndividualMonitoring gsim) { this.gsim = gsim; } public Long hasSavingsOfficerId() { Long id = null; if (this.savingsOfficer != null) { id = this.savingsOfficer.getId(); } return id; } public boolean hasSavingsOfficer(final Staff fromSavingsOfficer) { boolean matchesCurrentSavingsOfficer = false; if (this.savingsOfficer != null) { matchesCurrentSavingsOfficer = this.savingsOfficer.identifiedBy(fromSavingsOfficer); } else { matchesCurrentSavingsOfficer = fromSavingsOfficer == null; } return matchesCurrentSavingsOfficer; } public void reassignSavingsOfficer(final Staff newSavingsOfficer, final LocalDate assignmentDate) { final SavingsOfficerAssignmentHistory latestHistoryRecord = findLatestIncompleteHistoryRecord(); final SavingsOfficerAssignmentHistory lastAssignmentRecord = findLastAssignmentHistoryRecord(newSavingsOfficer); // assignment date should not be less than savings account submitted // date if (isSubmittedOnDateAfter(assignmentDate)) { final String errorMessage = "The Savings Officer assignment date (" + assignmentDate.toString() + ") cannot be before savings submitted date (" + getSubmittedOnDate().toString() + ")."; throw new SavingsOfficerAssignmentDateException("cannot.be.before.savings.submitted.date", errorMessage, assignmentDate, getSubmittedOnDate()); } else if (lastAssignmentRecord != null && lastAssignmentRecord.isEndDateAfter(assignmentDate)) { final String errorMessage = "The Savings Officer assignment date (" + assignmentDate + ") cannot be before previous Savings Officer unassigned date (" + lastAssignmentRecord.getEndDate() + ")."; throw new SavingsOfficerAssignmentDateException("cannot.be.before.previous.unassignement.date", errorMessage, assignmentDate, lastAssignmentRecord.getEndDate()); } else if (DateUtils.getLocalDateOfTenant().isBefore(assignmentDate)) { final String errorMessage = "The Savings Officer assignment date (" + assignmentDate + ") cannot be in the future."; throw new SavingsOfficerAssignmentDateException("cannot.be.a.future.date", errorMessage, assignmentDate); } else if (latestHistoryRecord != null && this.savingsOfficer.identifiedBy(newSavingsOfficer)) { latestHistoryRecord.updateStartDate(assignmentDate); } else if (latestHistoryRecord != null && latestHistoryRecord.matchesStartDateOf(assignmentDate)) { latestHistoryRecord.updateSavingsOfficer(newSavingsOfficer); this.savingsOfficer = newSavingsOfficer; } else if (latestHistoryRecord != null && latestHistoryRecord.hasStartDateBefore(assignmentDate)) { final String errorMessage = "Savings account with identifier " + getId() + " was already assigned before date " + assignmentDate; throw new SavingsOfficerAssignmentDateException("is.before.last.assignment.date", errorMessage, getId(), assignmentDate); } else { if (latestHistoryRecord != null) { // savings officer correctly changed from previous savings // officer to // new savings officer latestHistoryRecord.updateEndDate(assignmentDate); } this.savingsOfficer = newSavingsOfficer; if (isNotSubmittedAndPendingApproval()) { final SavingsOfficerAssignmentHistory savingsOfficerAssignmentHistory = SavingsOfficerAssignmentHistory.createNew(this, this.savingsOfficer, assignmentDate); this.savingsOfficerHistory.add(savingsOfficerAssignmentHistory); } } } private SavingsOfficerAssignmentHistory findLastAssignmentHistoryRecord(final Staff newSavingsOfficer) { SavingsOfficerAssignmentHistory lastAssignmentRecordLatestEndDate = null; for (final SavingsOfficerAssignmentHistory historyRecord : this.savingsOfficerHistory) { if (historyRecord.isCurrentRecord() && !historyRecord.isSameSavingsOfficer(newSavingsOfficer)) { lastAssignmentRecordLatestEndDate = historyRecord; break; } if (lastAssignmentRecordLatestEndDate == null) { lastAssignmentRecordLatestEndDate = historyRecord; } else if (historyRecord.isEndDateAfter(lastAssignmentRecordLatestEndDate.getEndDate()) && !historyRecord.isSameSavingsOfficer(newSavingsOfficer)) { lastAssignmentRecordLatestEndDate = historyRecord; } } return lastAssignmentRecordLatestEndDate; } public boolean isSubmittedOnDateAfter(final LocalDate compareDate) { return this.submittedOnDate == null ? false : LocalDate.ofInstant(this.submittedOnDate.toInstant(), DateUtils.getDateTimeZoneOfTenant()).isAfter(compareDate); } public LocalDate getSubmittedOnDate() { return submittedOnDate == null ? null : LocalDate.ofInstant(submittedOnDate.toInstant(), DateUtils.getDateTimeZoneOfTenant()); } public LocalDate getApprovedOnDate() { return approvedOnDate == null ? null : LocalDate.ofInstant(approvedOnDate.toInstant(), DateUtils.getDateTimeZoneOfTenant()); } public LocalDate getRejectedOnDate() { return rejectedOnDate == null ? null : LocalDate.ofInstant(rejectedOnDate.toInstant(), DateUtils.getDateTimeZoneOfTenant()); } public void removeSavingsOfficer(final LocalDate unassignDate) { final SavingsOfficerAssignmentHistory latestHistoryRecord = findLatestIncompleteHistoryRecord(); if (latestHistoryRecord != null) { validateUnassignDate(latestHistoryRecord, unassignDate); latestHistoryRecord.updateEndDate(unassignDate); } this.savingsOfficer = null; } private SavingsOfficerAssignmentHistory findLatestIncompleteHistoryRecord() { SavingsOfficerAssignmentHistory latestRecordWithNoEndDate = null; for (final SavingsOfficerAssignmentHistory historyRecord : this.savingsOfficerHistory) { if (historyRecord.isCurrentRecord()) { latestRecordWithNoEndDate = historyRecord; break; } } return latestRecordWithNoEndDate; } private void validateUnassignDate(final SavingsOfficerAssignmentHistory latestHistoryRecord, final LocalDate unassignDate) { final LocalDate today = DateUtils.getLocalDateOfTenant(); if (latestHistoryRecord.getStartDate().isAfter(unassignDate)) { final String errorMessage = "The Savings officer Unassign date(" + unassignDate + ") cannot be before its assignment date (" + latestHistoryRecord.getStartDate() + ")."; throw new SavingsOfficerUnassignmentDateException("cannot.be.before.assignment.date", errorMessage, getId(), getSavingsOfficer().getId(), latestHistoryRecord.getStartDate(), unassignDate); } else if (unassignDate.isAfter(today)) { final String errorMessage = "The Savings Officer Unassign date (" + unassignDate + ") cannot be in the future."; throw new SavingsOfficerUnassignmentDateException("cannot.be.a.future.date", errorMessage, unassignDate); } } public MonetaryCurrency getCurrency() { return this.currency; } public void validateNewApplicationState(final LocalDate todayDateOfTenant, final String resourceName) { // validateWithdrawalFeeDetails(); // validateAnnualFeeDetails(); final LocalDate submittedOn = getSubmittedOnLocalDate(); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(resourceName + SavingsApiConstants.summitalAction); validateLockinDetails(baseDataValidator); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } if (submittedOn.isAfter(todayDateOfTenant)) { baseDataValidator.reset().parameter(SavingsApiConstants.submittedOnDateParamName).value(submittedOn) .failWithCodeNoParameterAddedToErrorCode("cannot.be.a.future.date"); } if (this.client != null && this.client.isActivatedAfter(submittedOn)) { baseDataValidator.reset().parameter(SavingsApiConstants.submittedOnDateParamName).value(this.client.getActivationLocalDate()) .failWithCodeNoParameterAddedToErrorCode("cannot.be.before.client.activation.date"); } else if (this.group != null && this.group.isActivatedAfter(submittedOn)) { baseDataValidator.reset().parameter(SavingsApiConstants.submittedOnDateParamName).value(this.group.getActivationLocalDate()) .failWithCodeNoParameterAddedToErrorCode("cannot.be.before.client.activation.date"); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } protected LocalDate getSubmittedOnLocalDate() { LocalDate submittedOn = null; if (this.submittedOnDate != null) { submittedOn = LocalDate.ofInstant(this.submittedOnDate.toInstant(), DateUtils.getDateTimeZoneOfTenant()); } return submittedOn; } private LocalDate getApprovedOnLocalDate() { LocalDate approvedOnLocalDate = null; if (this.approvedOnDate != null) { approvedOnLocalDate = LocalDate.ofInstant(this.approvedOnDate.toInstant(), DateUtils.getDateTimeZoneOfTenant()); } return approvedOnLocalDate; } public Client getClient() { return this.client; } public BigDecimal getNominalAnnualInterestRate() { return this.nominalAnnualInterestRate; } public BigDecimal getNominalAnnualInterestRateOverdraft() { return this.nominalAnnualInterestRateOverdraft; } public Map<String, Object> approveApplication(final AppUser currentUser, final JsonCommand command, final LocalDate tenantsTodayDate) { final Map<String, Object> actualChanges = new LinkedHashMap<>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.approvalAction); final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status); if (!SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.hasStateOf(currentStatus)) { baseDataValidator.reset().parameter(SavingsApiConstants.approvedOnDateParamName) .failWithCodeNoParameterAddedToErrorCode("not.in.submittedandpendingapproval.state"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } this.status = SavingsAccountStatusType.APPROVED.getValue(); actualChanges.put(SavingsApiConstants.statusParamName, SavingsEnumerations.status(this.status)); // only do below if status has changed in the 'approval' case final LocalDate approvedOn = command.localDateValueOfParameterNamed(SavingsApiConstants.approvedOnDateParamName); final String approvedOnDateChange = command.stringValueOfParameterNamed(SavingsApiConstants.approvedOnDateParamName); this.approvedOnDate = Date.from(approvedOn.atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()); this.approvedBy = currentUser; actualChanges.put(SavingsApiConstants.localeParamName, command.locale()); actualChanges.put(SavingsApiConstants.dateFormatParamName, command.dateFormat()); actualChanges.put(SavingsApiConstants.approvedOnDateParamName, approvedOnDateChange); final LocalDate submittalDate = getSubmittedOnLocalDate(); if (approvedOn.isBefore(submittalDate)) { final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(command.dateFormat()).withLocale(command.extractLocale()); final String submittalDateAsString = formatter.format(submittalDate); baseDataValidator.reset().parameter(SavingsApiConstants.approvedOnDateParamName).value(submittalDateAsString) .failWithCodeNoParameterAddedToErrorCode("cannot.be.before.submittal.date"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } if (approvedOn.isAfter(tenantsTodayDate)) { baseDataValidator.reset().parameter(SavingsApiConstants.approvedOnDateParamName) .failWithCodeNoParameterAddedToErrorCode("cannot.be.a.future.date"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } validateActivityNotBeforeClientOrGroupTransferDate(SavingsEvent.SAVINGS_APPLICATION_APPROVED, approvedOn); // FIXME - kw - support field officer history for savings accounts // if (this.fieldOfficer != null) { // final LoanOfficerAssignmentHistory loanOfficerAssignmentHistory = // LoanOfficerAssignmentHistory.createNew(this, // this.fieldOfficer, approvedOn); // this.loanOfficerHistory.add(loanOfficerAssignmentHistory); // } if (this.savingsOfficer != null) { final SavingsOfficerAssignmentHistory savingsOfficerAssignmentHistory = SavingsOfficerAssignmentHistory.createNew(this, this.savingsOfficer, approvedOn); this.savingsOfficerHistory.add(savingsOfficerAssignmentHistory); } return actualChanges; } public Map<String, Object> undoApplicationApproval() { final Map<String, Object> actualChanges = new LinkedHashMap<>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.undoApprovalAction); final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status); if (!SavingsAccountStatusType.APPROVED.hasStateOf(currentStatus)) { baseDataValidator.reset().parameter(SavingsApiConstants.approvedOnDateParamName) .failWithCodeNoParameterAddedToErrorCode("not.in.approved.state"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } this.status = SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.getValue(); actualChanges.put(SavingsApiConstants.statusParamName, SavingsEnumerations.status(this.status)); this.approvedOnDate = null; this.approvedBy = null; this.rejectedOnDate = null; this.rejectedBy = null; this.withdrawnOnDate = null; this.withdrawnBy = null; this.closedOnDate = null; this.closedBy = null; actualChanges.put(SavingsApiConstants.approvedOnDateParamName, ""); // FIXME - kw - support field officer history for savings accounts // this.loanOfficerHistory.clear(); return actualChanges; } public void undoTransaction(final Long transactionId) { SavingsAccountTransaction transactionToUndo = null; for (final SavingsAccountTransaction transaction : this.transactions) { if (transaction.isIdentifiedBy(transactionId)) { transactionToUndo = transaction; } } if (transactionToUndo == null) { throw new SavingsAccountTransactionNotFoundException(this.getId(), transactionId); } validateAttemptToUndoTransferRelatedTransactions(transactionToUndo); validateActivityNotBeforeClientOrGroupTransferDate(SavingsEvent.SAVINGS_UNDO_TRANSACTION, transactionToUndo.transactionLocalDate()); transactionToUndo.reverse(); if (transactionToUndo.isChargeTransaction() || transactionToUndo.isWaiveCharge()) { // undo charge final Set<SavingsAccountChargePaidBy> chargesPaidBy = transactionToUndo.getSavingsAccountChargesPaid(); for (final SavingsAccountChargePaidBy savingsAccountChargePaidBy : chargesPaidBy) { final SavingsAccountCharge chargeToUndo = savingsAccountChargePaidBy.getSavingsAccountCharge(); if (transactionToUndo.isChargeTransaction()) { chargeToUndo.undoPayment(this.getCurrency(), transactionToUndo.getAmount(this.getCurrency())); } else if (transactionToUndo.isWaiveCharge()) { chargeToUndo.undoWaiver(this.getCurrency(), transactionToUndo.getAmount(this.getCurrency())); } } } } private Date findLatestAnnualFeeTransactionDueDate() { Date nextDueDate = null; LocalDate lastAnnualFeeTransactionDate = null; for (final SavingsAccountTransaction transaction : retreiveOrderedNonInterestPostingTransactions()) { if (transaction.isAnnualFeeAndNotReversed()) { if (lastAnnualFeeTransactionDate == null) { lastAnnualFeeTransactionDate = transaction.transactionLocalDate(); nextDueDate = Date.from(lastAnnualFeeTransactionDate.atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()); } if (transaction.transactionLocalDate().isAfter(lastAnnualFeeTransactionDate)) { lastAnnualFeeTransactionDate = transaction.transactionLocalDate(); nextDueDate = Date.from(lastAnnualFeeTransactionDate.atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()); } } } return nextDueDate; } public Map<String, Object> rejectApplication(final AppUser currentUser, final JsonCommand command, final LocalDate tenantsTodayDate) { final Map<String, Object> actualChanges = new LinkedHashMap<>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.rejectAction); final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status); if (!SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.hasStateOf(currentStatus)) { baseDataValidator.reset().parameter(SavingsApiConstants.rejectedOnDateParamName) .failWithCodeNoParameterAddedToErrorCode("not.in.submittedandpendingapproval.state"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } this.status = SavingsAccountStatusType.REJECTED.getValue(); actualChanges.put(SavingsApiConstants.statusParamName, SavingsEnumerations.status(this.status)); final LocalDate rejectedOn = command.localDateValueOfParameterNamed(SavingsApiConstants.rejectedOnDateParamName); final String rejectedOnAsString = command.stringValueOfParameterNamed(SavingsApiConstants.rejectedOnDateParamName); this.rejectedOnDate = Date.from(rejectedOn.atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()); this.rejectedBy = currentUser; this.withdrawnOnDate = null; this.withdrawnBy = null; this.closedOnDate = Date.from(rejectedOn.atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()); this.closedBy = currentUser; actualChanges.put(SavingsApiConstants.localeParamName, command.locale()); actualChanges.put(SavingsApiConstants.dateFormatParamName, command.dateFormat()); actualChanges.put(SavingsApiConstants.rejectedOnDateParamName, rejectedOnAsString); actualChanges.put(SavingsApiConstants.closedOnDateParamName, rejectedOnAsString); final LocalDate submittalDate = getSubmittedOnLocalDate(); if (rejectedOn.isBefore(submittalDate)) { final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(command.dateFormat()).withLocale(command.extractLocale()); final String submittalDateAsString = formatter.format(submittalDate); baseDataValidator.reset().parameter(SavingsApiConstants.rejectedOnDateParamName).value(submittalDateAsString) .failWithCodeNoParameterAddedToErrorCode("cannot.be.before.submittal.date"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } if (rejectedOn.isAfter(tenantsTodayDate)) { baseDataValidator.reset().parameter(SavingsApiConstants.rejectedOnDateParamName).value(rejectedOn) .failWithCodeNoParameterAddedToErrorCode("cannot.be.a.future.date"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } validateActivityNotBeforeClientOrGroupTransferDate(SavingsEvent.SAVINGS_APPLICATION_REJECTED, rejectedOn); return actualChanges; } public Map<String, Object> applicantWithdrawsFromApplication(final AppUser currentUser, final JsonCommand command, final LocalDate tenantsTodayDate) { final Map<String, Object> actualChanges = new LinkedHashMap<>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.withdrawnByApplicantAction); final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status); if (!SavingsAccountStatusType.SUBMITTED_AND_PENDING_APPROVAL.hasStateOf(currentStatus)) { baseDataValidator.reset().parameter(SavingsApiConstants.withdrawnOnDateParamName) .failWithCodeNoParameterAddedToErrorCode("not.in.submittedandpendingapproval.state"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } this.status = SavingsAccountStatusType.WITHDRAWN_BY_APPLICANT.getValue(); actualChanges.put(SavingsApiConstants.statusParamName, SavingsEnumerations.status(this.status)); final LocalDate withdrawnOn = command.localDateValueOfParameterNamed(SavingsApiConstants.withdrawnOnDateParamName); final String withdrawnOnAsString = command.stringValueOfParameterNamed(SavingsApiConstants.withdrawnOnDateParamName); this.rejectedOnDate = null; this.rejectedBy = null; this.withdrawnOnDate = Date.from(withdrawnOn.atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()); this.withdrawnBy = currentUser; this.closedOnDate = Date.from(withdrawnOn.atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()); this.closedBy = currentUser; actualChanges.put(SavingsApiConstants.localeParamName, command.locale()); actualChanges.put(SavingsApiConstants.dateFormatParamName, command.dateFormat()); actualChanges.put(SavingsApiConstants.withdrawnOnDateParamName, withdrawnOnAsString); actualChanges.put(SavingsApiConstants.closedOnDateParamName, withdrawnOnAsString); final LocalDate submittalDate = getSubmittedOnLocalDate(); if (withdrawnOn.isBefore(submittalDate)) { final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(command.dateFormat()).withLocale(command.extractLocale()); final String submittalDateAsString = formatter.format(submittalDate); baseDataValidator.reset().parameter(SavingsApiConstants.withdrawnOnDateParamName).value(submittalDateAsString) .failWithCodeNoParameterAddedToErrorCode("cannot.be.before.submittal.date"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } if (withdrawnOn.isAfter(tenantsTodayDate)) { baseDataValidator.reset().parameter(SavingsApiConstants.withdrawnOnDateParamName).value(withdrawnOn) .failWithCodeNoParameterAddedToErrorCode("cannot.be.a.future.date"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } validateActivityNotBeforeClientOrGroupTransferDate(SavingsEvent.SAVINGS_APPLICATION_WITHDRAWAL_BY_CUSTOMER, withdrawnOn); return actualChanges; } public Map<String, Object> activate(final AppUser currentUser, final JsonCommand command, final LocalDate tenantsTodayDate) { final Map<String, Object> actualChanges = new LinkedHashMap<>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(depositAccountType().resourceName() + SavingsApiConstants.activateAction); final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status); if (!SavingsAccountStatusType.APPROVED.hasStateOf(currentStatus)) { baseDataValidator.reset().parameter(SavingsApiConstants.activatedOnDateParamName) .failWithCodeNoParameterAddedToErrorCode("not.in.approved.state"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } final Locale locale = command.extractLocale(); final DateTimeFormatter fmt = DateTimeFormatter.ofPattern(command.dateFormat()).withLocale(locale); final LocalDate activationDate = command.localDateValueOfParameterNamed(SavingsApiConstants.activatedOnDateParamName); this.status = SavingsAccountStatusType.ACTIVE.getValue(); actualChanges.put(SavingsApiConstants.statusParamName, SavingsEnumerations.status(this.status)); actualChanges.put(SavingsApiConstants.localeParamName, command.locale()); actualChanges.put(SavingsApiConstants.dateFormatParamName, command.dateFormat()); actualChanges.put(SavingsApiConstants.activatedOnDateParamName, activationDate.format(fmt)); this.rejectedOnDate = null; this.rejectedBy = null; this.withdrawnOnDate = null; this.withdrawnBy = null; this.closedOnDate = null; this.closedBy = null; this.activatedOnDate = Date.from(activationDate.atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()); this.activatedBy = currentUser; this.lockedInUntilDate = calculateDateAccountIsLockedUntil(getActivationLocalDate()); /* * if (annualFeeSettingsSet()) { updateToNextAnnualFeeDueDateFrom(getActivationLocalDate()); } */ if (this.client != null && this.client.isActivatedAfter(activationDate)) { final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(command.dateFormat()).withLocale(command.extractLocale()); final String dateAsString = formatter.format(this.client.getActivationLocalDate()); baseDataValidator.reset().parameter(SavingsApiConstants.activatedOnDateParamName).value(dateAsString) .failWithCodeNoParameterAddedToErrorCode("cannot.be.before.client.activation.date"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } if (this.group != null && this.group.isActivatedAfter(activationDate)) { final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(command.dateFormat()).withLocale(command.extractLocale()); final String dateAsString = formatter.format(this.client.getActivationLocalDate()); baseDataValidator.reset().parameter(SavingsApiConstants.activatedOnDateParamName).value(dateAsString) .failWithCodeNoParameterAddedToErrorCode("cannot.be.before.group.activation.date"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } final LocalDate approvalDate = getApprovedOnLocalDate(); if (activationDate.isBefore(approvalDate)) { final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(command.dateFormat()).withLocale(command.extractLocale()); final String dateAsString = formatter.format(approvalDate); baseDataValidator.reset().parameter(SavingsApiConstants.activatedOnDateParamName).value(dateAsString) .failWithCodeNoParameterAddedToErrorCode("cannot.be.before.approval.date"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } if (activationDate.isAfter(tenantsTodayDate)) { baseDataValidator.reset().parameter(SavingsApiConstants.activatedOnDateParamName).value(activationDate) .failWithCodeNoParameterAddedToErrorCode("cannot.be.a.future.date"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } validateActivityNotBeforeClientOrGroupTransferDate(SavingsEvent.SAVINGS_ACTIVATE, activationDate); return actualChanges; } public void processAccountUponActivation(final boolean isSavingsInterestPostingAtCurrentPeriodEnd, final Integer financialYearBeginningMonth, final AppUser user) { // update annual fee due date for (SavingsAccountCharge charge : this.charges()) { charge.updateToNextDueDateFrom(getActivationLocalDate()); } // auto pay the activation time charges this.payActivationCharges(isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, user); // TODO : AA add activation charges to actual changes list } public Money activateWithBalance() { return Money.of(this.currency, this.minRequiredOpeningBalance); } public void approveAndActivateApplication(final Date appliedonDate, final AppUser appliedBy) { this.status = SavingsAccountStatusType.ACTIVE.getValue(); this.approvedOnDate = appliedonDate; this.approvedBy = appliedBy; this.rejectedOnDate = null; this.rejectedBy = null; this.withdrawnOnDate = null; this.withdrawnBy = null; this.closedOnDate = null; this.closedBy = null; this.activatedOnDate = appliedonDate; this.activatedBy = appliedBy; this.lockedInUntilDate = calculateDateAccountIsLockedUntil(getActivationLocalDate()); } private void payActivationCharges(final boolean isSavingsInterestPostingAtCurrentPeriodEnd, final Integer financialYearBeginningMonth, final AppUser user) { boolean isSavingsChargeApplied = false; for (SavingsAccountCharge savingsAccountCharge : this.charges()) { if (savingsAccountCharge.isSavingsActivation()) { isSavingsChargeApplied = true; payCharge(savingsAccountCharge, savingsAccountCharge.getAmountOutstanding(getCurrency()), getActivationLocalDate(), user); } } if (isSavingsChargeApplied) { final MathContext mc = MathContext.DECIMAL64; boolean isInterestTransfer = false; LocalDate postInterestAsOnDate = null; if (this.isBeforeLastPostingPeriod(getActivationLocalDate())) { final LocalDate today = DateUtils.getLocalDateOfTenant(); this.postInterest(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, postInterestAsOnDate); } else { final LocalDate today = DateUtils.getLocalDateOfTenant(); this.calculateInterestUsing(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, postInterestAsOnDate); } } } public Map<String, Object> close(final AppUser currentUser, final JsonCommand command, final LocalDate tenantsTodayDate) { final Map<String, Object> actualChanges = new LinkedHashMap<>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.closeAction); final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status); if (!SavingsAccountStatusType.ACTIVE.hasStateOf(currentStatus)) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("not.in.active.state"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } final Locale locale = command.extractLocale(); final DateTimeFormatter fmt = DateTimeFormatter.ofPattern(command.dateFormat()).withLocale(locale); final LocalDate closedDate = command.localDateValueOfParameterNamed(SavingsApiConstants.closedOnDateParamName); if (closedDate.isBefore(getActivationLocalDate())) { baseDataValidator.reset().parameter(SavingsApiConstants.closedOnDateParamName).value(closedDate) .failWithCode("must.be.after.activation.date"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } if (closedDate.isAfter(tenantsTodayDate)) { baseDataValidator.reset().parameter(SavingsApiConstants.closedOnDateParamName).value(closedDate) .failWithCode("cannot.be.a.future.date"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } final List<SavingsAccountTransaction> savingsAccountTransactions = retreiveListOfTransactions(); if (savingsAccountTransactions.size() > 0) { final SavingsAccountTransaction accountTransaction = savingsAccountTransactions.get(savingsAccountTransactions.size() - 1); if (accountTransaction.isAfter(closedDate)) { baseDataValidator.reset().parameter(SavingsApiConstants.closedOnDateParamName).value(closedDate) .failWithCode("must.be.after.last.transaction.date"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } } if (getAccountBalance().doubleValue() != 0) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("results.in.balance.not.zero"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } validateActivityNotBeforeClientOrGroupTransferDate(SavingsEvent.SAVINGS_CLOSE_ACCOUNT, closedDate); this.status = SavingsAccountStatusType.CLOSED.getValue(); actualChanges.put(SavingsApiConstants.statusParamName, SavingsEnumerations.status(this.status)); actualChanges.put(SavingsApiConstants.localeParamName, command.locale()); actualChanges.put(SavingsApiConstants.dateFormatParamName, command.dateFormat()); actualChanges.put(SavingsApiConstants.closedOnDateParamName, closedDate.format(fmt)); this.rejectedOnDate = null; this.rejectedBy = null; this.withdrawnOnDate = null; this.withdrawnBy = null; this.closedOnDate = Date.from(closedDate.atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()); this.closedBy = currentUser; return actualChanges; } protected void validateActivityNotBeforeClientOrGroupTransferDate(final SavingsEvent event, final LocalDate activityDate) { if (this.client != null && this.client.getOfficeJoiningLocalDate() != null) { final LocalDate clientOfficeJoiningDate = this.client.getOfficeJoiningLocalDate(); if (activityDate.isBefore(clientOfficeJoiningDate)) { throw new SavingsActivityPriorToClientTransferException(event.toString(), clientOfficeJoiningDate); } } } private void validateAttemptToUndoTransferRelatedTransactions(final SavingsAccountTransaction savingsAccountTransaction) { if (savingsAccountTransaction.isTransferRelatedTransaction()) { throw new SavingsTransferTransactionsCannotBeUndoneException(savingsAccountTransaction.getId()); } } private Date calculateDateAccountIsLockedUntil(final LocalDate activationLocalDate) { Date lockedInUntilLocalDate = null; final PeriodFrequencyType lockinPeriodFrequencyType = PeriodFrequencyType.fromInt(this.lockinPeriodFrequencyType); switch (lockinPeriodFrequencyType) { case INVALID: break; case DAYS: lockedInUntilLocalDate = Date.from(activationLocalDate.plusDays(this.lockinPeriodFrequency) .atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()); break; case WEEKS: lockedInUntilLocalDate = Date.from(activationLocalDate.plusWeeks(this.lockinPeriodFrequency) .atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()); break; case MONTHS: lockedInUntilLocalDate = Date.from(activationLocalDate.plusMonths(this.lockinPeriodFrequency) .atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()); break; case YEARS: lockedInUntilLocalDate = Date.from(activationLocalDate.plusYears(this.lockinPeriodFrequency) .atStartOfDay(DateUtils.getDateTimeZoneOfTenant()).toInstant()); break; case WHOLE_TERM: LOG.error("TODO Implement calculateDateAccountIsLockedUntil for WHOLE_TERM"); break; } return lockedInUntilLocalDate; } public Group group() { return this.group; } public boolean isWithdrawalFeeApplicableForTransfer() { return this.withdrawalFeeApplicableForTransfer; } public void activateAccountBasedOnBalance() { if (SavingsAccountStatusType.fromInt(this.status).isClosed() && !this.summary.getAccountBalance(getCurrency()).isZero()) { this.status = SavingsAccountStatusType.ACTIVE.getValue(); } } public LocalDate getClosedOnDate() { return this.closedOnDate == null ? null : LocalDate.ofInstant(this.closedOnDate.toInstant(), DateUtils.getDateTimeZoneOfTenant()); } public SavingsAccountSummary getSummary() { return this.summary; } public List<SavingsAccountTransaction> getTransactions() { return this.transactions; } public void addTransaction(final SavingsAccountTransaction transaction) { this.transactions.add(transaction); } public void setStatus(final Integer status) { this.status = status; } private Set<SavingsAccountCharge> associateChargesWithThisSavingsAccount(final Set<SavingsAccountCharge> savingsAccountCharges) { for (final SavingsAccountCharge savingsAccountCharge : savingsAccountCharges) { savingsAccountCharge.update(this); } return savingsAccountCharges; } public boolean update(final Set<SavingsAccountCharge> newSavingsAccountCharges) { if (newSavingsAccountCharges == null) { return false; } if (this.charges == null) { this.charges = new HashSet<>(); } this.charges.clear(); this.charges.addAll(associateChargesWithThisSavingsAccount(newSavingsAccountCharges)); return true; } public boolean hasCurrencyCodeOf(final String matchingCurrencyCode) { if (this.currency == null) { return false; } return this.currency.getCode().equalsIgnoreCase(matchingCurrencyCode); } public void removeCharge(final SavingsAccountCharge charge) { final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(SAVINGS_ACCOUNT_RESOURCE_NAME); if (isClosed()) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("delete.transaction.invalid.account.is.closed"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } if (isActive() || isApproved()) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("delete.transaction.invalid.account.is.active"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } this.charges.remove(charge); } public void waiveCharge(final Long savingsAccountChargeId, final AppUser user) { final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(SAVINGS_ACCOUNT_RESOURCE_NAME); if (isClosed()) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.is.closed"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } if (isNotActive()) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.is.not.active"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } final SavingsAccountCharge savingsAccountCharge = getCharge(savingsAccountChargeId); if (savingsAccountCharge.isNotActive()) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("charge.is.not.active"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } if (savingsAccountCharge.isWithdrawalFee()) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("transaction.invalid.waiver.of.withdrawal.fee.not.supported"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } // validate charge is not already paid or waived if (savingsAccountCharge.isWaived()) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.charge.is.already.waived"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } else if (savingsAccountCharge.isPaid()) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.charge.is.paid"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } // waive charge final Money amountWaived = savingsAccountCharge.waive(getCurrency()); handleWaiverChargeTransactions(savingsAccountCharge, amountWaived, user); } public void addCharge(final DateTimeFormatter formatter, final SavingsAccountCharge savingsAccountCharge, final Charge chargeDefinition) { final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(SAVINGS_ACCOUNT_RESOURCE_NAME); if (isClosed()) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.is.closed"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } if (!hasCurrencyCodeOf(chargeDefinition.getCurrencyCode())) { baseDataValidator.reset() .failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.currency.and.charge.currency.not.same"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } final LocalDate chargeDueDate = savingsAccountCharge.getDueLocalDate(); if (savingsAccountCharge.isOnSpecifiedDueDate()) { if (getActivationLocalDate() != null && chargeDueDate.isBefore(getActivationLocalDate())) { baseDataValidator.reset().parameter(dueAsOfDateParamName).value(getActivationLocalDate().format(formatter)) .failWithCodeNoParameterAddedToErrorCode("before.activationDate"); throw new PlatformApiDataValidationException(dataValidationErrors); } else if (getSubmittedOnLocalDate() != null && chargeDueDate.isBefore(getSubmittedOnLocalDate())) { baseDataValidator.reset().parameter(dueAsOfDateParamName).value(getSubmittedOnLocalDate().format(formatter)) .failWithCodeNoParameterAddedToErrorCode("before.submittedOnDate"); throw new PlatformApiDataValidationException(dataValidationErrors); } } if (savingsAccountCharge.isSavingsActivation() && !(isSubmittedAndPendingApproval() || (isApproved() && isNotActive()))) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("not.valid.account.status.cannot.add.activation.time.charge"); throw new PlatformApiDataValidationException(dataValidationErrors); } // Only one withdrawal fee is supported per account if (savingsAccountCharge.isWithdrawalFee()) { if (this.isWithDrawalFeeExists()) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("multiple.withdrawal.fee.per.account.not.supported"); throw new PlatformApiDataValidationException(dataValidationErrors); } } // Only one annual fee is supported per account if (savingsAccountCharge.isAnnualFee()) { if (this.isAnnualFeeExists()) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("multiple.annual.fee.per.account.not.supported"); throw new PlatformApiDataValidationException(dataValidationErrors); } } if (savingsAccountCharge.isAnnualFee() || savingsAccountCharge.isMonthlyFee() || savingsAccountCharge.isWeeklyFee()) { // update due date if (isActive()) { savingsAccountCharge.updateToNextDueDateFrom(getActivationLocalDate()); } else if (isApproved()) { savingsAccountCharge.updateToNextDueDateFrom(getApprovedOnLocalDate()); } } // activation charge and withdrawal charges not required this validation if (savingsAccountCharge.isOnSpecifiedDueDate()) { validateActivityNotBeforeClientOrGroupTransferDate(SavingsEvent.SAVINGS_APPLY_CHARGE, chargeDueDate); } // add new charge to savings account this.charges.add(savingsAccountCharge); } private boolean isWithDrawalFeeExists() { for (SavingsAccountCharge charge : this.charges()) { if (charge.isWithdrawalFee()) { return true; } } return false; } private boolean isAnnualFeeExists() { for (SavingsAccountCharge charge : this.charges()) { if (charge.isAnnualFee()) { return true; } } return false; } public void payCharge(final SavingsAccountCharge savingsAccountCharge, final BigDecimal amountPaid, final LocalDate transactionDate, final DateTimeFormatter formatter, final AppUser user) { final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(SAVINGS_ACCOUNT_RESOURCE_NAME); if (isClosed()) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.is.closed"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } if (isNotActive()) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.is.not.active"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } if (savingsAccountCharge.isNotActive()) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("charge.is.not.active"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } if (getActivationLocalDate() != null && transactionDate.isBefore(getActivationLocalDate())) { baseDataValidator.reset().parameter(dueAsOfDateParamName).value(getActivationLocalDate().format(formatter)) .failWithCodeNoParameterAddedToErrorCode("transaction.before.activationDate"); throw new PlatformApiDataValidationException(dataValidationErrors); } if (DateUtils.isDateInTheFuture(transactionDate)) { baseDataValidator.reset().parameter(dueAsOfDateParamName).value(transactionDate.format(formatter)) .failWithCodeNoParameterAddedToErrorCode("transaction.is.futureDate"); throw new PlatformApiDataValidationException(dataValidationErrors); } if (savingsAccountCharge.isSavingsActivation()) { baseDataValidator.reset() .failWithCodeNoParameterAddedToErrorCode("transaction.not.valid.cannot.pay.activation.time.charge.is.automated"); throw new PlatformApiDataValidationException(dataValidationErrors); } if (savingsAccountCharge.isAnnualFee()) { final LocalDate annualFeeDueDate = savingsAccountCharge.getDueLocalDate(); if (annualFeeDueDate == null) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("no.annualfee.settings"); throw new PlatformApiDataValidationException(dataValidationErrors); } if (!annualFeeDueDate.equals(transactionDate)) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("invalid.date"); throw new PlatformApiDataValidationException(dataValidationErrors); } Date currentAnnualFeeNextDueDate = findLatestAnnualFeeTransactionDueDate(); if (currentAnnualFeeNextDueDate != null && LocalDate .ofInstant(currentAnnualFeeNextDueDate.toInstant(), DateUtils.getDateTimeZoneOfTenant()).isEqual(transactionDate)) { baseDataValidator.reset().parameter("dueDate").value(transactionDate.format(formatter)) .failWithCodeNoParameterAddedToErrorCode("transaction.exists.on.date"); throw new PlatformApiDataValidationException(dataValidationErrors); } } // validate charge is not already paid or waived if (savingsAccountCharge.isWaived()) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.charge.is.already.waived"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } else if (savingsAccountCharge.isPaid()) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.charge.is.paid"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } final Money chargePaid = Money.of(currency, amountPaid); if (!savingsAccountCharge.getAmountOutstanding(getCurrency()).isGreaterThanOrEqualTo(chargePaid)) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("transaction.invalid.charge.amount.paid.in.access"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } this.payCharge(savingsAccountCharge, chargePaid, transactionDate, user); } public void payCharge(final SavingsAccountCharge savingsAccountCharge, final Money amountPaid, final LocalDate transactionDate, final AppUser user) { savingsAccountCharge.pay(getCurrency(), amountPaid); handlePayChargeTransactions(savingsAccountCharge, amountPaid, transactionDate, user); } private void handlePayChargeTransactions(SavingsAccountCharge savingsAccountCharge, Money transactionAmount, final LocalDate transactionDate, final AppUser user) { SavingsAccountTransaction chargeTransaction = null; if (savingsAccountCharge.isWithdrawalFee()) { chargeTransaction = SavingsAccountTransaction.withdrawalFee(this, office(), transactionDate, transactionAmount, user); } else if (savingsAccountCharge.isAnnualFee()) { chargeTransaction = SavingsAccountTransaction.annualFee(this, office(), transactionDate, transactionAmount, user); } else { chargeTransaction = SavingsAccountTransaction.charge(this, office(), transactionDate, transactionAmount, user); } handleChargeTransactions(savingsAccountCharge, chargeTransaction); } private void handleWaiverChargeTransactions(SavingsAccountCharge savingsAccountCharge, Money transactionAmount, AppUser user) { final SavingsAccountTransaction chargeTransaction = SavingsAccountTransaction.waiver(this, office(), DateUtils.getLocalDateOfTenant(), transactionAmount, user); handleChargeTransactions(savingsAccountCharge, chargeTransaction); } private void handleChargeTransactions(final SavingsAccountCharge savingsAccountCharge, final SavingsAccountTransaction transaction) { // Provide a link between transaction and savings charge for which // amount is waived. final SavingsAccountChargePaidBy chargePaidBy = SavingsAccountChargePaidBy.instance(transaction, savingsAccountCharge, transaction.getAmount(this.getCurrency()).getAmount()); transaction.getSavingsAccountChargesPaid().add(chargePaidBy); this.transactions.add(transaction); } private SavingsAccountCharge getCharge(final Long savingsAccountChargeId) { SavingsAccountCharge charge = null; for (final SavingsAccountCharge existingCharge : this.charges) { if (existingCharge.getId().equals(savingsAccountChargeId)) { charge = existingCharge; break; } } if (charge == null) { throw new SavingsAccountChargeNotFoundException(savingsAccountChargeId, getId()); } return charge; } public Set<SavingsAccountCharge> charges() { return (this.charges == null) ? new HashSet<SavingsAccountCharge>() : this.charges; } public void validateAccountValuesWithProduct() { final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(SAVINGS_ACCOUNT_RESOURCE_NAME); if (this.overdraftLimit != null && this.product.overdraftLimit() != null && this.overdraftLimit.compareTo(this.product.overdraftLimit()) > 0) { baseDataValidator.reset().parameter(SavingsApiConstants.overdraftLimitParamName).value(this.overdraftLimit) .failWithCode("cannot.exceed.product.value"); } validateInterestPostingAndCompoundingPeriodTypes(baseDataValidator); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } public boolean allowOverdraft() { return this.allowOverdraft; } public LocalDate accountSubmittedOrActivationDate() { return getActivationLocalDate() == null ? getSubmittedOnLocalDate() : getActivationLocalDate(); } public DepositAccountType depositAccountType() { return DepositAccountType.fromInt(depositType); } protected boolean isTransferInterestToOtherAccount() { return false; } public boolean accountSubmittedAndActivationOnSameDate() { if (getSubmittedOnLocalDate() == null || getActivationLocalDate() == null) { return false; } return getActivationLocalDate().isEqual(getSubmittedOnLocalDate()); } public void validateInterestPostingAndCompoundingPeriodTypes(final DataValidatorBuilder baseDataValidator) { Map<SavingsPostingInterestPeriodType, List<SavingsCompoundingInterestPeriodType>> postingtoCompoundMap = new HashMap<>(); postingtoCompoundMap.put(SavingsPostingInterestPeriodType.MONTHLY, Arrays.asList(new SavingsCompoundingInterestPeriodType[] { SavingsCompoundingInterestPeriodType.DAILY, SavingsCompoundingInterestPeriodType.MONTHLY })); postingtoCompoundMap.put(SavingsPostingInterestPeriodType.QUATERLY, Arrays.asList(new SavingsCompoundingInterestPeriodType[] { SavingsCompoundingInterestPeriodType.DAILY, SavingsCompoundingInterestPeriodType.MONTHLY, SavingsCompoundingInterestPeriodType.QUATERLY })); postingtoCompoundMap.put(SavingsPostingInterestPeriodType.BIANNUAL, Arrays.asList(new SavingsCompoundingInterestPeriodType[] { SavingsCompoundingInterestPeriodType.DAILY, SavingsCompoundingInterestPeriodType.MONTHLY, SavingsCompoundingInterestPeriodType.QUATERLY, SavingsCompoundingInterestPeriodType.BI_ANNUAL })); postingtoCompoundMap.put(SavingsPostingInterestPeriodType.ANNUAL, Arrays.asList(new SavingsCompoundingInterestPeriodType[] { SavingsCompoundingInterestPeriodType.DAILY, SavingsCompoundingInterestPeriodType.MONTHLY, SavingsCompoundingInterestPeriodType.QUATERLY, SavingsCompoundingInterestPeriodType.BI_ANNUAL, SavingsCompoundingInterestPeriodType.ANNUAL })); SavingsPostingInterestPeriodType savingsPostingInterestPeriodType = SavingsPostingInterestPeriodType .fromInt(interestPostingPeriodType); SavingsCompoundingInterestPeriodType savingsCompoundingInterestPeriodType = SavingsCompoundingInterestPeriodType .fromInt(interestCompoundingPeriodType); if (postingtoCompoundMap.get(savingsPostingInterestPeriodType) == null) { baseDataValidator.failWithCodeNoParameterAddedToErrorCode("posting.period.type.is.less.than.compound.period.type", savingsPostingInterestPeriodType.name(), savingsCompoundingInterestPeriodType.name()); } } public boolean allowDeposit() { return true; } public boolean allowWithdrawal() { return true; } public boolean allowModify() { return true; } public boolean isTransactionsAllowed() { return isActive(); } public boolean isTransactionAllowed(SavingsAccountTransactionType transactionType, LocalDate transactionDate) { if (!isTransactionsAllowed()) { return false; } Client client = getClient(); if (client != null && !client.isActive()) { return false; } Group group = group(); if (group != null && !group.isActive()) { return false; } if (transactionDate == null) { return true; } if (DateUtils.isDateInTheFuture(transactionDate) || transactionDate.isBefore(getActivationLocalDate())) { return false; } if (transactionType.isCredit()) { return true; } return !isAccountLocked(transactionDate); } public BigDecimal minBalanceForInterestCalculation() { return this.minBalanceForInterestCalculation; } public void inactivateCharge(SavingsAccountCharge savingsAccountCharge, LocalDate inactivationOnDate) { final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(SAVINGS_ACCOUNT_RESOURCE_NAME); if (isClosed()) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.is.closed"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } if (isNotActive()) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.is.not.active"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } savingsAccountCharge.inactiavateCharge(inactivationOnDate); } public SavingsAccountCharge getUpdatedChargeDetails(SavingsAccountCharge savingsAccountCharge) { for (final SavingsAccountCharge charge : this.charges) { if (charge.equals(savingsAccountCharge)) { savingsAccountCharge = charge; break; } } return savingsAccountCharge; } public String getAccountNumber() { return this.accountNumber; } private Money minRequiredBalanceDerived(final MonetaryCurrency currency) { Money minReqBalance = Money.zero(currency); if (this.enforceMinRequiredBalance) { minReqBalance = minReqBalance.plus(this.minRequiredBalance); } if (this.allowOverdraft) { minReqBalance = minReqBalance.minus(this.overdraftLimit); } return minReqBalance; } public BigDecimal getOnHoldFunds() { return this.onHoldFunds == null ? BigDecimal.ZERO : this.onHoldFunds; } public void holdFunds(BigDecimal onHoldFunds) { this.onHoldFunds = getOnHoldFunds().add(onHoldFunds); } public void releaseFunds(BigDecimal onHoldFunds) { this.onHoldFunds = getOnHoldFunds().subtract(onHoldFunds); } public BigDecimal getWithdrawableBalance() { return getAccountBalance().subtract(minRequiredBalanceDerived(getCurrency()).getAmount()).subtract(this.getOnHoldFunds()) .subtract(this.getSavingsHoldAmount()); } public TaxGroup getTaxGroup() { return this.taxGroup; } public boolean withHoldTax() { return this.withHoldTax; } public void setWithHoldTax(boolean withHoldTax) { this.withHoldTax = withHoldTax; } protected boolean applyWithholdTaxForDepositAccounts(final LocalDate interestPostingUpToDate, boolean recalucateDailyBalance) { final List<SavingsAccountTransaction> withholdTransactions = findWithHoldTransactions(); SavingsAccountTransaction withholdTransaction = findTransactionFor(interestPostingUpToDate, withholdTransactions); final BigDecimal totalInterestPosted = this.savingsAccountTransactionSummaryWrapper.calculateTotalInterestPosted(this.currency, this.transactions); if (withholdTransaction == null && this.withHoldTax()) { boolean isWithholdTaxAdded = createWithHoldTransaction(totalInterestPosted, interestPostingUpToDate); recalucateDailyBalance = recalucateDailyBalance || isWithholdTaxAdded; } else { boolean isWithholdTaxAdded = updateWithHoldTransaction(totalInterestPosted, withholdTransaction); recalucateDailyBalance = recalucateDailyBalance || isWithholdTaxAdded; } return recalucateDailyBalance; } public void setSubStatusInactive(AppUser appUser) { this.sub_status = SavingsAccountSubStatusEnum.INACTIVE.getValue(); LocalDate transactionDate = DateUtils.getLocalDateOfTenant(); for (SavingsAccountCharge charge : this.charges()) { if (charge.isSavingsNoActivity() && charge.isActive()) { charge.updateWithdralFeeAmount(this.getAccountBalance()); this.payCharge(charge, charge.getAmountOutstanding(this.getCurrency()), transactionDate, appUser); } } recalculateDailyBalances(Money.zero(this.currency), transactionDate); this.summary.updateSummary(this.currency, this.savingsAccountTransactionSummaryWrapper, this.transactions); } public void setSubStatusDormant() { this.sub_status = SavingsAccountSubStatusEnum.DORMANT.getValue(); } public void escheat(AppUser appUser) { this.status = SavingsAccountStatusType.CLOSED.getValue(); this.sub_status = SavingsAccountSubStatusEnum.ESCHEAT.getValue(); this.closedOnDate = DateUtils.getDateOfTenant(); this.closedBy = appUser; boolean postInterestAsOnDate = false; LocalDate transactionDate = DateUtils.getLocalDateOfTenant(); if (this.getSummary().getAccountBalance(this.getCurrency()).isGreaterThanZero()) { SavingsAccountTransaction transaction = SavingsAccountTransaction.escheat(this, transactionDate, appUser, postInterestAsOnDate); this.transactions.add(transaction); } recalculateDailyBalances(Money.zero(this.currency), transactionDate); this.summary.updateSummary(this.currency, this.savingsAccountTransactionSummaryWrapper, this.transactions); } public void loadLazyCollections() { transactions.size(); charges.size(); savingsOfficerHistory.size(); if (group != null) { Office dummyOffice = group.getOffice(); } // Ensure lazy loading of group if set } public void updateSavingsAccountSummary(final List<SavingsAccountTransaction> transactions) { this.summary.updateSummary(this.currency, this.savingsAccountTransactionSummaryWrapper, transactions); } public Map<String, Object> block() { final Map<String, Object> actualChanges = new LinkedHashMap<>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(depositAccountType().resourceName() + SavingsApiConstants.blockAction); final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status); if (!SavingsAccountStatusType.ACTIVE.hasStateOf(currentStatus)) { baseDataValidator.reset().parameter(SavingsApiConstants.statusParamName) .failWithCodeNoParameterAddedToErrorCode(SavingsApiConstants.ERROR_MSG_SAVINGS_ACCOUNT_NOT_ACTIVE); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } this.sub_status = SavingsAccountSubStatusEnum.BLOCK.getValue(); actualChanges.put(SavingsApiConstants.subStatusParamName, SavingsEnumerations.subStatus(this.sub_status)); return actualChanges; } public Map<String, Object> unblock() { final Map<String, Object> actualChanges = new LinkedHashMap<>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(depositAccountType().resourceName() + SavingsApiConstants.unblockAction); final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status); if (!SavingsAccountStatusType.ACTIVE.hasStateOf(currentStatus)) { baseDataValidator.reset().parameter(SavingsApiConstants.statusParamName) .failWithCodeNoParameterAddedToErrorCode(SavingsApiConstants.ERROR_MSG_SAVINGS_ACCOUNT_NOT_ACTIVE); } final SavingsAccountSubStatusEnum currentSubStatus = SavingsAccountSubStatusEnum.fromInt(this.sub_status); if (!SavingsAccountSubStatusEnum.BLOCK.hasStateOf(currentSubStatus)) { baseDataValidator.reset().parameter(SavingsApiConstants.subStatusParamName) .failWithCodeNoParameterAddedToErrorCode("not.in.blocked.state"); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } this.sub_status = SavingsAccountSubStatusEnum.NONE.getValue(); actualChanges.put(SavingsApiConstants.subStatusParamName, SavingsEnumerations.subStatus(this.sub_status)); return actualChanges; } public Map<String, Object> blockCredits(Integer currentSubstatus) { final Map<String, Object> actualChanges = new LinkedHashMap<>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(depositAccountType().resourceName() + SavingsApiConstants.blockCreditsAction); final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status); if (!SavingsAccountStatusType.ACTIVE.hasStateOf(currentStatus)) { baseDataValidator.reset().parameter(SavingsApiConstants.statusParamName) .failWithCodeNoParameterAddedToErrorCode(SavingsApiConstants.ERROR_MSG_SAVINGS_ACCOUNT_NOT_ACTIVE); } if (SavingsAccountSubStatusEnum.BLOCK.hasStateOf(SavingsAccountSubStatusEnum.fromInt(currentSubstatus))) { baseDataValidator.reset().parameter(SavingsApiConstants.subStatusParamName) .value(SavingsAccountSubStatusEnum.fromInt(currentSubstatus)).failWithCodeNoParameterAddedToErrorCode("currently.set"); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } if (SavingsAccountSubStatusEnum.BLOCK_DEBIT.hasStateOf(SavingsAccountSubStatusEnum.fromInt(currentSubstatus))) { this.sub_status = SavingsAccountSubStatusEnum.BLOCK.getValue(); } else { this.sub_status = SavingsAccountSubStatusEnum.BLOCK_CREDIT.getValue(); } actualChanges.put(SavingsApiConstants.subStatusParamName, SavingsEnumerations.subStatus(this.sub_status)); return actualChanges; } public Map<String, Object> unblockCredits() { final Map<String, Object> actualChanges = new LinkedHashMap<>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(depositAccountType().resourceName() + SavingsApiConstants.unblockCreditsAction); final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status); if (!SavingsAccountStatusType.ACTIVE.hasStateOf(currentStatus)) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(SavingsApiConstants.ERROR_MSG_SAVINGS_ACCOUNT_NOT_ACTIVE); } final SavingsAccountSubStatusEnum currentSubStatus = SavingsAccountSubStatusEnum.fromInt(this.sub_status); if (!(SavingsAccountSubStatusEnum.BLOCK_CREDIT.hasStateOf(currentSubStatus) || SavingsAccountSubStatusEnum.BLOCK.hasStateOf(currentSubStatus))) { baseDataValidator.reset().parameter(SavingsApiConstants.statusParamName) .failWithCodeNoParameterAddedToErrorCode("credits.are.not.blocked"); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } if (SavingsAccountSubStatusEnum.BLOCK.hasStateOf(currentSubStatus)) { this.sub_status = SavingsAccountSubStatusEnum.BLOCK_DEBIT.getValue(); } else { this.sub_status = SavingsAccountSubStatusEnum.NONE.getValue(); } actualChanges.put(SavingsApiConstants.subStatusParamName, SavingsEnumerations.subStatus(this.sub_status)); return actualChanges; } public Map<String, Object> blockDebits(Integer currentSubstatus) { final Map<String, Object> actualChanges = new LinkedHashMap<>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(depositAccountType().resourceName() + SavingsApiConstants.blockDebitsAction); final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status); if (!SavingsAccountStatusType.ACTIVE.hasStateOf(currentStatus)) { baseDataValidator.reset().parameter(SavingsApiConstants.statusParamName) .failWithCodeNoParameterAddedToErrorCode(SavingsApiConstants.ERROR_MSG_SAVINGS_ACCOUNT_NOT_ACTIVE); } if (SavingsAccountSubStatusEnum.BLOCK.hasStateOf(SavingsAccountSubStatusEnum.fromInt(currentSubstatus))) { baseDataValidator.reset().parameter(SavingsApiConstants.subStatusParamName) .value(SavingsAccountSubStatusEnum.fromInt(currentSubstatus)).failWithCodeNoParameterAddedToErrorCode("currently.set"); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } if (SavingsAccountSubStatusEnum.BLOCK_CREDIT.hasStateOf(SavingsAccountSubStatusEnum.fromInt(currentSubstatus))) { this.sub_status = SavingsAccountSubStatusEnum.BLOCK.getValue(); } else { this.sub_status = SavingsAccountSubStatusEnum.BLOCK_DEBIT.getValue(); } actualChanges.put(SavingsApiConstants.subStatusParamName, SavingsEnumerations.subStatus(this.sub_status)); return actualChanges; } public Map<String, Object> unblockDebits() { final Map<String, Object> actualChanges = new LinkedHashMap<>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(depositAccountType().resourceName() + SavingsApiConstants.unblockDebitsAction); final SavingsAccountStatusType currentStatus = SavingsAccountStatusType.fromInt(this.status); if (!SavingsAccountStatusType.ACTIVE.hasStateOf(currentStatus)) { baseDataValidator.reset().parameter(SavingsApiConstants.statusParamName) .failWithCodeNoParameterAddedToErrorCode(SavingsApiConstants.ERROR_MSG_SAVINGS_ACCOUNT_NOT_ACTIVE); } final SavingsAccountSubStatusEnum currentSubStatus = SavingsAccountSubStatusEnum.fromInt(this.sub_status); if (!(SavingsAccountSubStatusEnum.BLOCK_DEBIT.hasStateOf(currentSubStatus) || SavingsAccountSubStatusEnum.BLOCK.hasStateOf(currentSubStatus))) { baseDataValidator.reset().parameter(SavingsApiConstants.subStatusParamName) .failWithCodeNoParameterAddedToErrorCode("debits.are.not.blocked"); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } if (SavingsAccountSubStatusEnum.BLOCK.hasStateOf(currentSubStatus)) { this.sub_status = SavingsAccountSubStatusEnum.BLOCK_CREDIT.getValue(); } else { this.sub_status = SavingsAccountSubStatusEnum.NONE.getValue(); } actualChanges.put(SavingsApiConstants.subStatusParamName, SavingsEnumerations.subStatus(this.sub_status)); return actualChanges; } public SavingsAccountStatusType getStatus() { return SavingsAccountStatusType.fromInt(status); } public Integer getSubStatus() { return this.sub_status; } public void validateForAccountBlock() { final SavingsAccountSubStatusEnum currentSubStatus = SavingsAccountSubStatusEnum.fromInt(this.getSubStatus()); if (SavingsAccountSubStatusEnum.BLOCK.hasStateOf(currentSubStatus)) { throw new SavingsAccountBlockedException(this.getId()); } } public void validateForDebitBlock() { final SavingsAccountSubStatusEnum currentSubStatus = SavingsAccountSubStatusEnum.fromInt(this.getSubStatus()); if (SavingsAccountSubStatusEnum.BLOCK_DEBIT.hasStateOf(currentSubStatus)) { throw new SavingsAccountDebitsBlockedException(this.getId()); } } public void validateForCreditBlock() { final SavingsAccountSubStatusEnum currentSubStatus = SavingsAccountSubStatusEnum.fromInt(this.getSubStatus()); if (SavingsAccountSubStatusEnum.BLOCK_CREDIT.hasStateOf(currentSubStatus)) { throw new SavingsAccountCreditsBlockedException(this.getId()); } } public LocalDate retrieveLastTransactionDate() { final List<SavingsAccountTransaction> transactionsSortedByDate = retreiveListOfTransactions(); SavingsAccountTransaction lastTransaction = null; if (transactionsSortedByDate.size() > 0) { lastTransaction = transactionsSortedByDate.get(transactionsSortedByDate.size() - 1); } LocalDate lastransactionDate = null; if (lastTransaction != null) { lastransactionDate = lastTransaction.transactionLocalDate(); } return lastransactionDate; } public BigDecimal getSavingsHoldAmount() { return this.savingsOnHoldAmount == null ? BigDecimal.ZERO : this.savingsOnHoldAmount; } public void holdAmount(BigDecimal amount) { this.savingsOnHoldAmount = getSavingsHoldAmount().add(amount); } public void releaseOnHoldAmount(BigDecimal amount) { this.savingsOnHoldAmount = getSavingsHoldAmount().subtract(amount); } public AccountType getAccountType() { return AccountType.fromInt(accountType); } public Integer getAccountTypes() { return accountType; } public void setAccountType(Integer accountType) { this.accountType = accountType; } private boolean isOverdraft() { return allowOverdraft; } }
package DP; import java.util.*; import javax.swing.Box.Filler; public class unique_paths_62 { //1. 分治:最优子结构(重复性) //f(i,j) = f(i-1,j) + f(i,j-1) //2. 状态数组/DP表 //3. 状态转移方程 public int uniquePaths(int m, int n) { int[] dp = new int[n]; Arrays.fill(dp, 1); for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { //此时dp[i-1]已经被计算为新值,当前dp[i]为上一行的值 dp[j]+=dp[j-1]; } } return dp[m-1]; } public int uniquePaths2(int m, int n) { int dp[][] = new int[m][n]; //第一列为1 for (int i = 0; i < m; i++) { dp[i][0] = 1; } //第一行为1 for (int i = 0; i < n; i++) { dp[0][i] = 1; } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { dp[i][j] = dp[i-1][j] + dp[i][j-1]; } } return dp[m-1][n-1]; } Integer res = 0; public int uniquePathsBackTrack(int m, int n) { if(m == 0 || n == 0) return 0; _backtrack(1,1,m,n); return res; } private void _backtrack(int mi, int nj, int m, int n) { //1. terminator if(mi > m || nj > n) return; if(mi == m && nj == n) { res++; return; } //2 process cur logic //3. drill down //right++ _backtrack(mi+1, nj, m, n); //down++ _backtrack(mi, nj+1, m, n); //4. clear state } public int uniquePathsDivide(int m, int n) {//递归 return uniquePathsHelper(m, n, new HashMap<String, Integer>()); } public int uniquePathsHelper(int m, int n, HashMap<String, Integer> map) { if (m<=1||n<=1) return 1; String key = m +"s"+ n; if (map.containsKey(key))return map.get(key); int right = uniquePathsHelper( m, n-1, map); int down = uniquePathsHelper( m-1, n, map); int total = right + down; map.put(key, total); return total; } public static void main(String[] args) { unique_paths_62 instance = new unique_paths_62(); instance.uniquePathsBackTrack(3, 2); System.out.println(instance.res); //System.out.println(instance.uniquePathsBackTrack(3, 7)); } }
package com.example.maguoqing.androiddemo.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.example.maguoqing.androiddemo.R; import com.example.maguoqing.androiddemo.fragment.CalendarFragment; import com.example.maguoqing.androiddemo.model.ClipItem; import com.example.maguoqing.androiddemo.utils.Utils; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * Created by magq on 16/4/19. */ public class CalendarAdapter extends RecyclerView.Adapter<CalendarAdapter.Itemholder> { private int mPageNumber; private List<ClipItem> datas; private Context mContext; private CalendarFragment.OnDayClickListener onDayClickListener; private Calendar calStartDate = Calendar.getInstance(); private int iMonthViewCurrentMonth = 0; private Calendar today = Calendar.getInstance(); public CalendarAdapter(CalendarFragment.OnDayClickListener onDayClickListener) { this.onDayClickListener = onDayClickListener; } public void setPageNumber(int pageNumber) { this.mPageNumber = pageNumber; this.datas = getDatas(); } public ArrayList<ClipItem> getDatas() { ArrayList<ClipItem> items = new ArrayList<>(); UpdateStartDateForMonth(); for (int i = 1; i <= 42; i++) { items.add(new ClipItem(calStartDate.getTime())); calStartDate.add(Calendar.DAY_OF_MONTH, 1); } return items; } private void UpdateStartDateForMonth() { calStartDate = Utils.getSelectCalendar(mPageNumber); calStartDate.set(Calendar.DATE, 1); iMonthViewCurrentMonth = calStartDate.get(Calendar.MONTH); int iDay = 0; int iFirstDayOfWeek = Calendar.MONDAY; int iStartDay = iFirstDayOfWeek; if (iStartDay == Calendar.MONDAY) { iDay = calStartDate.get(Calendar.DAY_OF_WEEK) - Calendar.MONDAY; if (iDay < 0) iDay = 6; } if (iStartDay == Calendar.SUNDAY) { iDay = calStartDate.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY; if (iDay < 0) iDay = 6; } calStartDate.add(Calendar.DAY_OF_WEEK, -iDay); calStartDate.add(Calendar.DAY_OF_MONTH, -1); } @Override public Itemholder onCreateViewHolder(ViewGroup parent, int viewType) { mContext = parent.getContext(); View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.viewholder_calendar_month, parent, false); v.setMinimumHeight(parent.getHeight() / 6); return new Itemholder(v); } @Override public void onBindViewHolder(Itemholder holder, int position) { ClipItem item = datas.get(position); int day = item.getDate().getDate(); holder.tvDay.setText(String.valueOf(day)); if (equalsDate(item.getDate(), today.getTime())) { holder.tvDay.setBackgroundColor(mContext.getResources().getColor(R.color.answer_blue)); holder.tvDay.setTextColor(mContext.getResources().getColor(R.color.white)); TextView txtToDay = new TextView(mContext); txtToDay.setGravity(Gravity.CENTER_HORIZONTAL); txtToDay.setBackgroundResource(R.color.answer_green); txtToDay.setTextColor(mContext.getResources().getColor(R.color.white)); txtToDay.setTextSize(10); txtToDay.setText("TODAY!"); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp.setMargins(0, 2, 0, 0); holder.llContent.addView(txtToDay, 0, lp); TextView test = new TextView(mContext); test.setGravity(Gravity.CENTER_HORIZONTAL); test.setBackgroundResource(R.color.answer_red); test.setTextColor(mContext.getResources().getColor(R.color.white)); test.setTextSize(10); test.setText("TEST"); holder.llContent.addView(test, 1, lp); } if (item.getDate().getMonth() != iMonthViewCurrentMonth) { holder.llContainer.setBackgroundResource(R.drawable.layout_divider_gray); } holder.llContainer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onDayClickListener.onClick(); } }); } private Boolean equalsDate(Date date1, Date date2) { if (date1.getYear() == date2.getYear() && date1.getMonth() == date2.getMonth() && date1.getDate() == date2.getDate()) { return true; } else { return false; } } @Override public int getItemCount() { return datas == null ? 0 : datas.size(); } public class Itemholder extends RecyclerView.ViewHolder { private LinearLayout llContainer; private TextView tvDay; private LinearLayout llContent; public Itemholder(View itemView) { super(itemView); llContainer = (LinearLayout) itemView.findViewById(R.id.ll_container); tvDay = (TextView) itemView.findViewById(R.id.tv_day); llContent = (LinearLayout) itemView.findViewById(R.id.ll_content); } } }
// This is a generated file. Not intended for manual editing. package io.github.sof3.libglocal.intellij.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static io.github.sof3.libglocal.intellij.parser.LgcElements.*; import com.intellij.extapi.psi.ASTWrapperPsiElement; import io.github.sof3.libglocal.intellij.psi.*; public class LgcSpanComponentImpl extends ASTWrapperPsiElement implements LgcSpanComponent { public LgcSpanComponentImpl(@NotNull ASTNode node) { super(node); } public void accept(@NotNull LgcVisitor visitor) { visitor.visitSpanComponent(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof LgcVisitor) accept((LgcVisitor)visitor); else super.accept(visitor); } @Override @NotNull public LgcFullLiteral getFullLiteral() { return findNotNullChildByClass(LgcFullLiteral.class); } @Override @NotNull public PsiElement getCloseBrace() { return findNotNullChildByType(CLOSE_BRACE); } @Override @NotNull public PsiElement getSpanName() { return findNotNullChildByType(SPAN_NAME); } @Override @NotNull public PsiElement getSpanStart() { return findNotNullChildByType(SPAN_START); } }
package ru.job4j.tracker; import java.util.List; /** * @author Konstantin Kazakov (plan.05.87@gmail.com). * @version $Id$ * @since 0.1 */ public interface Input { String ask(String question); int ask(String question, List<Integer> range); }
/* * Copyright 2015 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Run this file with the `java_sample.sh` script. import MyGame.Sample.Color; import MyGame.Sample.Equipment; import MyGame.Sample.Monster; import MyGame.Sample.Vec3; import MyGame.Sample.Weapon; import com.google.flatbuffers.FlatBufferBuilder; import java.nio.ByteBuffer; class SampleBinary { // Example how to use FlatBuffers to create and read binary buffers. public static void main(String[] args) { FlatBufferBuilder builder = new FlatBufferBuilder(0); // Create some weapons for our Monster ('Sword' and 'Axe'). int weaponOneName = builder.createString("Sword"); short weaponOneDamage = 3; int weaponTwoName = builder.createString("Axe"); short weaponTwoDamage = 5; // Use the `createWeapon()` helper function to create the weapons, since we set every field. int[] weaps = new int[2]; weaps[0] = Weapon.createWeapon(builder, weaponOneName, weaponOneDamage); weaps[1] = Weapon.createWeapon(builder, weaponTwoName, weaponTwoDamage); // Serialize the FlatBuffer data. int name = builder.createString("Orc"); byte[] treasure = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int inv = Monster.createInventoryVector(builder, treasure); int weapons = Monster.createWeaponsVector(builder, weaps); int pos = Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f); Monster.startMonster(builder); Monster.addPos(builder, pos); Monster.addName(builder, name); Monster.addColor(builder, Color.Red); Monster.addHp(builder, (short)300); Monster.addInventory(builder, inv); Monster.addWeapons(builder, weapons); Monster.addEquippedType(builder, Equipment.Weapon); Monster.addEquipped(builder, weaps[1]); int orc = Monster.endMonster(builder); builder.finish(orc); // You could also call `Monster.finishMonsterBuffer(builder, orc);`. // We now have a FlatBuffer that can be stored on disk or sent over a network. // ...Code to store to disk or send over a network goes here... // Instead, we are going to access it right away, as if we just received it. ByteBuffer buf = builder.dataBuffer(); // Get access to the root: Monster monster = Monster.getRootAsMonster(buf); // Note: We did not set the `mana` field explicitly, so we get back the default value. assert monster.mana() == (short)150; assert monster.hp() == (short)300; assert monster.name().equals("Orc"); assert monster.color() == Color.Red; assert monster.pos().x() == 1.0f; assert monster.pos().y() == 2.0f; assert monster.pos().z() == 3.0f; // Get and test the `inventory` FlatBuffer `vector`. for (int i = 0; i < monster.inventoryLength(); i++) { assert monster.inventory(i) == (byte)i; } // Get and test the `weapons` FlatBuffer `vector` of `table`s. String[] expectedWeaponNames = {"Sword", "Axe"}; int[] expectedWeaponDamages = {3, 5}; for (int i = 0; i < monster.weaponsLength(); i++) { assert monster.weapons(i).name().equals(expectedWeaponNames[i]); assert monster.weapons(i).damage() == expectedWeaponDamages[i]; } Weapon.Vector weaponsVector = monster.weaponsVector(); for (int i = 0; i < weaponsVector.length(); i++) { assert weaponsVector.get(i).name().equals(expectedWeaponNames[i]); assert weaponsVector.get(i).damage() == expectedWeaponDamages[i]; } // Get and test the `equipped` FlatBuffer `union`. assert monster.equippedType() == Equipment.Weapon; Weapon equipped = (Weapon)monster.equipped(new Weapon()); assert equipped.name().equals("Axe"); assert equipped.damage() == 5; System.out.println("The FlatBuffer was successfully created and verified!"); } }
package com.github.jinahya.bit.io; /*- * #%L * bit-io2 * %% * Copyright (C) 2020 Jinahya, Inc. * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.io.IOException; class LongArrayWriter extends PrimitiveArrayWriter<long[]> { public static class Unsigned extends LongArrayWriter { public Unsigned(final int lengthSize, final int elementSize) { super(lengthSize, BitIoConstraints.requireValidSizeForUnsignedLong(elementSize)); } @Override void writeElement(final BitOutput output, final long value) throws IOException { output.writeUnsignedLong(elementSize, value); } } public LongArrayWriter(final int lengthSize, final int elementSize) { super(lengthSize); this.elementSize = BitIoConstraints.requireValidSizeForLong(elementSize); } @Override public void write(final BitOutput output, final long[] value) throws IOException { writeLength(output, value.length); writeElements(output, value); } void writeElements(final BitOutput output, final long[] elements) throws IOException { for (final long element : elements) { writeElement(output, element); } } void writeElement(final BitOutput output, final long element) throws IOException { output.writeLong(elementSize, element); } final int elementSize; }
/* * Copyright (c) 2019 Aman Nougrahiya, V Krishna Nandivada, IIT Madras. * This file is a part of the project IMOP, licensed under the MIT license. * See LICENSE.md for the full text of the license. * * The above notice shall be included in all copies or substantial * portions of this file. */ package imop.ast.annotation; import imop.ast.node.external.*; public class PragmaImop extends Annotation { private String pragmaString; private Node annotatedNode; public PragmaImop(String pragmaString) { this.pragmaString = pragmaString; } public PragmaImop(String pragmaString, Node annotatedNode) { assert (annotatedNode != null); this.pragmaString = pragmaString; this.annotatedNode = annotatedNode; } public String getPragmaString() { return pragmaString; } public Node getAnnotatedNode() { return annotatedNode; } @Override public String toString() { return "\n#pragma imop " + this.pragmaString + "\n"; } }
/* * Copyright (C) 2010-2101 Alibaba Group Holding Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.otter.shared.arbitrate.impl.setl.rpc; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import org.apache.commons.lang.ClassUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.CollectionUtils; import com.alibaba.otter.shared.arbitrate.exception.ArbitrateException; import com.alibaba.otter.shared.arbitrate.impl.config.ArbitrateConfigUtils; import com.alibaba.otter.shared.arbitrate.impl.setl.ArbitrateFactory; import com.alibaba.otter.shared.arbitrate.impl.setl.ArbitrateLifeCycle; import com.alibaba.otter.shared.arbitrate.impl.setl.helper.ReplyProcessQueue; import com.alibaba.otter.shared.arbitrate.impl.setl.helper.StageProgress; import com.alibaba.otter.shared.arbitrate.impl.setl.rpc.monitor.ProcessListener; import com.alibaba.otter.shared.arbitrate.impl.setl.rpc.monitor.ProcessMonitor; import com.alibaba.otter.shared.arbitrate.model.EtlEventData; import com.alibaba.otter.shared.common.model.config.enums.StageType; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.MapMaker; /** * 基于rpc的stage调度控制器,排除select调度,主要控制e/t/l的调度控制 * * @author jianghang 2012-9-28 下午10:05:26 * @version 4.1.0 */ public class RpcStageController extends ArbitrateLifeCycle implements ProcessListener { private static final Logger logger = LoggerFactory.getLogger(RpcStageController.class); private LoadingCache<StageType, ReplyProcessQueue> replys; private Map<Long, StageProgress> progress; private ProcessMonitor processMonitor; private volatile Long lastestLoadedProcessId = -1L; // 最近一次同步成功的processId public RpcStageController(Long pipelineId) { super(pipelineId); replys = CacheBuilder.newBuilder().maximumSize(1000).build(new CacheLoader<StageType, ReplyProcessQueue>() { public ReplyProcessQueue load(StageType input) { int size = ArbitrateConfigUtils.getParallelism(getPipelineId()) * 10; if (size < 100) { size = 100; } return new ReplyProcessQueue(size); } }); progress = new MapMaker().makeMap(); // 注册一下监听事件变化 processMonitor = ArbitrateFactory.getInstance(pipelineId, ProcessMonitor.class); processMonitor.addListener(this); processMonitor.reload(); } public Long waitForProcess(StageType stage) throws InterruptedException { if (stage.isSelect()) { throw new ArbitrateException("not support"); } try { return replys.get(stage).take(); } catch (ExecutionException e) { e.printStackTrace(); return null; } } /** * 获取上一个stage传递的数据信息 */ public EtlEventData getLastData(Long processId) { return progress.get(processId).getData(); } public void destory() { processMonitor.removeListener(this); replys.invalidateAll(); replys.cleanUp(); progress.clear(); } public synchronized boolean single(StageType stage, EtlEventData etlEventData) { boolean result = true; try { switch (stage) { case SELECT: progress.put(etlEventData.getProcessId(), new StageProgress(StageType.SELECT, etlEventData)); replys.get(StageType.EXTRACT).offer(etlEventData.getProcessId()); break; case EXTRACT: progress.put(etlEventData.getProcessId(), new StageProgress(StageType.EXTRACT, etlEventData)); replys.get(StageType.TRANSFORM).offer(etlEventData.getProcessId()); break; case TRANSFORM: progress.put(etlEventData.getProcessId(), new StageProgress(StageType.TRANSFORM, etlEventData)); // 并不是立即触发,通知最小的一个process启动 computeNextLoad(); break; case LOAD: Object removed = progress.remove(etlEventData.getProcessId()); // 并不是立即触发,通知下一个最小的一个process启动 if (removed == null) { result = false; } else { // 如果2个process 1和2, // 1先执行完了load,此时2还不符合条件,等2到了Transform时,还需要依赖zookeeper的process列表变化进行判断 // 记录一下上一次同步成功的processId,提升load响应速度,方便在内存中直接判断 lastestLoadedProcessId = etlEventData.getProcessId(); computeNextLoad(); // 通知load processId,触发下一个 } break; default: break; } } catch (ExecutionException e) { e.printStackTrace(); } return result; } /** * 计算下一个load的processId */ private void computeNextLoad() { // 针对上一个id为本地load成功的,直接忽略,触发下一个id Long processId = getMinTransformedProcessId(lastestLoadedProcessId); if (processId != null) { try { replys.get(StageType.LOAD).offer(processId); } catch (ExecutionException e) { e.printStackTrace(); } } } /** * 获取最小一个符合条件的processId,排除loadedProcessId */ private Long getMinTransformedProcessId(Long loadedProcessId) { ProcessMonitor processMonitor = ArbitrateFactory.getInstance(getPipelineId(), ProcessMonitor.class); List<Long> processIds = processMonitor.getCurrentProcessIds(); // 如果需要当前node处理当前process的load时,rpc请求一定会将对应的stage状态发到这机器上,并保存到progress中 if (!CollectionUtils.isEmpty(processIds) && !CollectionUtils.isEmpty(progress)) { // 上一次load成功的在当前的processId中不存在,可能有两种情况: // 1. zk还未将数据通知过来,当前current processIds还是为老版本的值 // 2. processId已经被删除,比如好久没有数据同步了,定时触发时发觉列表一直为空 // if (loadedProcessId != null && // !processIds.contains(loadedProcessId)) { // // 强制刷新一次,不过也可能是刷到老版本的值,杭州leader还没同步到美国 // processIds = processMonitor.getCurrentProcessIds(true); // } Long result = null; // 做的一个优化,如果上一个processId load成功是在本机,直接忽略 // 因为存在一个问题:比如两个process,都先完成了T模块,然后逐个触发L模块,此时第二个process需要等zookeeper回调watcher时才会被触发 for (Long processId : processIds) { if (loadedProcessId == null || processId > loadedProcessId) { result = processId; break; } } // 如果不存在符合>loadedProcessId的记录,直接假设下一个processId就是上一个id+1 // 因为processId目前的机制永远只会递增 if (result == null) { result = loadedProcessId + 1; } if (result != null) { StageProgress stage = progress.get(result); if (stage != null && stage.getStage().isTransform()) { return result; } else { logger.info("rpc compute [{}] but stage [{}]", result, stage == null ? null : stage.getStage()); return null; } } } return null; } public void processChanged(List<Long> processIds) { compareProgress(processIds); for (ReplyProcessQueue replyProcessIds : replys.asMap().values()) { compareReply(processIds, replyProcessIds); } // process发生变化,可能是process load完成,需要触发下一个process进行load computeNextLoad(); } /** * 删除已经被废弃的processId */ private synchronized void compareProgress(List<Long> processIds) { if (CollectionUtils.isEmpty(processIds) == false) { Long minProcessId = processIds.get(0); // 对比一下progress中的记录,如果小于当前最小的processId,直接删除内存中的记录 // 因为发生跨机器调用或者出现restart指令,对应的process记录不会被删除 for (Long processId : progress.keySet()) { if (processId < minProcessId) { progress.remove(processId); } } } } /** * 将当前的符合条件的processIds和当前的reply queue进行校对,剔除不在processIds里的内容 */ private synchronized void compareReply(List<Long> processIds, ReplyProcessQueue replyProcessIds) { Object[] replyIds = replyProcessIds.toArray(); for (Object replyId : replyIds) { if (processIds.contains((Long) replyId) == false) { // 判断reply // id是否在当前processId列表中 // 因为存在并发问题,如在执行Listener事件的同时,可能触发了process的创建,这时新建的processId会进入到reply队列中 // 此时接受到的processIds变量为上一个版本的内容,所以会删除新建的process,导致整个通道被挂住 if (CollectionUtils.isEmpty(processIds) == false) { Long processId = processIds.get(0); if (processId > (Long) replyId) { // 如果当前最小的processId都大于replyId, // processId都是递增创建的 logger.info("## {} remove reply id [{}]", ClassUtils.getShortClassName(this.getClass()), (Long) replyId); replyProcessIds.remove((Long) replyId); progress.remove((Long) replyId); } } } } } }
package org.myrobotlab.gp; /** * A GP object sends this message to its observers whenever the genetic * algorithm has found a new best individual. * * @version 1.0 * @author Hans U. Gerber (<a * href="mailto:gerber@ifh.ee.ethz.ch">gerber@ifh.ee.ethz.ch</a>) */ public class GPMessageBestFound extends GPMessage { public int generation; public String program; public RealPoint[] data; public double fitness; public double standardFitness; GPMessageBestFound(int generation, String program, RealPoint[] data, double fitness, double standardFitness) { this.generation = generation; this.program = program; this.data = data; this.fitness = fitness; this.standardFitness = standardFitness; } }
package cn.enilu.flash.bean.entity.front; import javax.persistence.MappedSuperclass; /** * @author :enilu * @date :Created in 2019/9/4 14:31 */ /**这个注解表示在父类上面的,用来标识父类。 基于代码复用和模型分离的思想,在项目开发中使用JPA的@MappedSuperclass注解将实体类的多个属性分别封装到不同的非实体类中。例如,数据库表中都需要id来表示编号,id是这些映射实体类的通用的属性,交给jpa统一生成主键id编号,那么使用一个父类来封装这些通用属性,并用@MappedSuperclas标识。 注意: 1.标注为@MappedSuperclass的类将不是一个完整的实体类,他将不会映射到数据库表,但是他的属性都将映射到其子类的数据库字段中。 2.标注为@MappedSuperclass的类不能再标注@Entity或@Table注解,也无需实现序列化接口*/ @MappedSuperclass public class BaseMongoEntity { }
/** * Copyright (c) 2011-2014, hubin (jobob@qq.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.baomidou.kisso.service; import com.baomidou.kisso.*; import com.baomidou.kisso.common.Browser; import com.baomidou.kisso.common.CookieHelper; import com.baomidou.kisso.common.IpHelper; import com.baomidou.kisso.common.encrypt.SSOEncrypt; import com.baomidou.kisso.common.util.RandomUtil; import com.baomidou.kisso.exception.KissoException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; import java.util.logging.Logger; /** * <p> * SSO 单点登录服务支持类 * </p> * * @author hubin * @Date 2015-12-03 */ public class KissoServiceSupport { protected final Logger logger = Logger.getLogger("KissoServiceSupport"); protected SSOConfig config; public SSOConfig getConfig() { return config; } public void setConfig( SSOConfig config ) { this.config = config; } /** * ------------------------------- 客户端相关方法 ------------------------------- */ /** * 获取当前请求 Token * <p> * 此属性在过滤器拦截器中设置,业务系统中调用有效 * </p> * * @param request * @return * @return Token {@link Token} */ @SuppressWarnings("unchecked") public <T extends Token> T attrToken(HttpServletRequest request ) { return (T) request.getAttribute(SSOConfig.SSO_TOKEN_ATTR); } /** * <p> * 获取当前请求 Token * </p> * * @param request * @param encrypt * 对称加密算法类 * @return Token {@link Token} */ protected Token getToken(HttpServletRequest request, SSOEncrypt encrypt, SSOCache cache ) { if ( encrypt == null ) { throw new KissoException(" Encrypt not for null."); } Token tk = checkIp(request, cacheToken(request, encrypt, cache)); /** * 执行插件逻辑 */ List<SSOPlugin> pluginList = config.getPluginList(); if ( pluginList != null ) { for ( SSOPlugin plugin : pluginList ) { boolean valid = plugin.validateToken(tk); if (!valid) { return null; } } } return tk; } /** * <p> * Token 是否缓存处理逻辑 * </p> * <p> * 判断 Token 是否缓存 , 如果缓存不存退出登录 * </p> * * @param request * @param encrypt * 对称加密算法类 * @return Token {@link Token} */ private Token cacheToken(HttpServletRequest request, SSOEncrypt encrypt, SSOCache cache ) { /** * 如果缓存不存退出登录 */ if ( cache != null ) { Token cookieToken = getTokenFromCookie(request); if ( cookieToken == null ) { /* 未登录 */ return null; } Token cacheToken = cache.get(cookieToken.toCacheKey(), config.getCacheExpires()); if ( cacheToken == null ) { /* 开启缓存且失效,返回 null 清除 Cookie 退出 */ logger.fine("cacheToken token is null."); return null; } else { /* * 开启缓存,判断是否宕机: * 1、缓存正常,返回 tk * 2、缓存宕机,执行读取 Cookie 逻辑 */ if ( cacheToken.getFlag() != Token.FLAG_CACHE_SHUT ) { /* * 验证 cookie 与 cache 中 token 登录时间是否<br> * 不一致返回 null */ if(cookieToken.getTime() == cacheToken.getTime()){ return cacheToken; } else { logger.severe("Login time is not consistent or kicked out."); request.setAttribute(SSOConfig.SSO_KICK_FLAG, SSOConfig.SSO_KICK_USER); return null; } } } } /** * Token 为 null 执行以下逻辑 */ return getToken(request, encrypt, config.getCookieName()); } /** * <p> * 获取当前请求 Token * </p> * * @param request * @param encrypt * 对称加密算法类 * @param cookieName * Cookie名称 * @return Token ${Token} */ protected Token getToken(HttpServletRequest request, SSOEncrypt encrypt, String cookieName ) { String jsonToken = this.getJsonToken(request, encrypt, cookieName); if ( jsonToken == null || "".equals(jsonToken) ) { /** * 未登录请求 */ logger.fine("jsonToken is null."); return null; } else { return config.getToken().parseToken(jsonToken); } } /** * <p> * 获取当前请求 JsonToken * </p> * * @param request * @param encrypt * 对称加密算法类 * @param cookieName * Cookie名称 * @return String 当前Token的json格式值 */ protected String getJsonToken(HttpServletRequest request, SSOEncrypt encrypt, String cookieName ) { Cookie uid = CookieHelper.findCookieByName(request, cookieName); if ( uid != null ) { String jsonToken = uid.getValue(); String[] tokenAttr = new String[2]; try { jsonToken = encrypt.decrypt(jsonToken, config.getSecretkey()); tokenAttr = jsonToken.split(SSOConfig.CUT_SYMBOL); } catch ( Exception e ) { logger.severe("jsonToken decrypt error, may be fake login. IP = " + IpHelper.getIpAddr(request)); } /** * 判断是否认证浏览器 混淆信息 */ if ( config.getCookieBrowser() ) { if ( Browser.isLegalUserAgent(request, tokenAttr[0], tokenAttr[1]) ) { return tokenAttr[0]; } else { /** * 签名验证码失败 */ logger.severe("SSOHelper getToken, find Browser is illegal."); } } else { /** * 不需要认证浏览器信息混淆 返回JsonToken */ return tokenAttr[0]; } } return null; } /** * <p> * 校验Token IP 与登录 IP 是否一致 * </p> * * @param request * @param token * 登录票据 * @return Token {@link Token} */ protected Token checkIp(HttpServletRequest request, Token token ) { /** * 判断是否检查 IP 一致性 */ if ( config.getCookieCheckip() ) { String ip = IpHelper.getIpAddr(request); if ( token != null && ip != null && !ip.equals(token.getIp()) ) { /** * 检查 IP 与登录IP 不一致返回 null */ logger.info(String.format("ip inconsistent! return token null, token userIp:%s, reqIp:%s", token.getIp(), ip)); return null; } } return token; } /** * * cookie 中获取 Token, 该方法未验证 IP 等其他信息。 * * <p> * 1、自动设置 * 2、拦截器 request 中获取 * 3、解密 Cookie 获取 * </p> * * @param request * HTTP 请求 * @param token * SSO 票据 * @return */ public Token getTokenFromCookie(HttpServletRequest request) { Token tk = this.attrToken(request); if (tk == null) { tk = this.getToken(request, config.getEncrypt(), config.getCookieName()); } return tk; } /** * ------------------------------- 登录相关方法 ------------------------------- */ /** * <p> * 根据Token生成登录信息Cookie * </p> * * @param request * @param token * SSO 登录信息票据 * @param encrypt * 对称加密算法类 * @return Cookie 登录信息Cookie {@link Cookie} */ private Cookie generateCookie(HttpServletRequest request, Token token, SSOEncrypt encrypt ) { try { Cookie cookie = new Cookie(config.getCookieName(), encryptCookie(request, token, encrypt)); cookie.setPath(config.getCookiePath()); cookie.setSecure(config.getCookieSecure()); /** * domain 提示 * <p> * 有些浏览器 localhost 无法设置 cookie * </p> */ String domain = config.getCookieDomain(); cookie.setDomain(domain); if ( "".equals(domain) || domain.contains("localhost") ) { logger.warning("if you can't login, please enter normal domain. instead:" + domain); } /** * 设置Cookie超时时间 */ int maxAge = config.getCookieMaxage(); Integer attrMaxAge = (Integer) request.getAttribute(SSOConfig.SSO_COOKIE_MAXAGE); if (attrMaxAge != null) { maxAge = attrMaxAge; } if ( maxAge >= 0 ) { cookie.setMaxAge(maxAge); } return cookie; } catch ( Exception e ) { logger.severe("generateCookie is exception!" + e.toString()); return null; } } /** * <p> * 加密Token信息 * </p> * * @param request * @param token * SSO 登录信息票据 * @param encrypt * 对称加密算法类 * @return Cookie 登录信息Cookie {@link Cookie} */ protected String encryptCookie(HttpServletRequest request, Token token, SSOEncrypt encrypt ) throws Exception { if ( token == null ) { throw new KissoException(" Token not for null."); } /** * token加密混淆 */ String jt = token.jsonToken(); StringBuffer sf = new StringBuffer(); sf.append(jt); sf.append(SSOConfig.CUT_SYMBOL); /** * 判断是否认证浏览器信息 否取8位随机数混淆 */ if ( config.getCookieBrowser() ) { sf.append(Browser.getUserAgent(request, jt)); } else { sf.append(RandomUtil.getCharacterAndNumber(8)); } return encrypt.encrypt(sf.toString(), config.getSecretkey()); } /** * <p> * 当前访问域下设置登录Cookie * </p> * * @param request * @param response * @param encrypt * 对称加密算法类 */ protected void setSSOCookie( HttpServletRequest request, HttpServletResponse response, Token token, SSOEncrypt encrypt ) { if ( encrypt == null ) { throw new KissoException(" Encrypt not for null."); } try { /** * 设置加密 Cookie */ Cookie ck = generateCookie(request, token, encrypt); /** * 判断 Token 是否缓存处理失效 * <p> * cache 缓存宕机,flag 设置为失效 * </p> */ SSOCache cache = config.getCache(); if ( cache != null ) { boolean rlt = cache.set(token.toCacheKey(), token, config.getCacheExpires()); if ( !rlt ) { token.setFlag(Token.FLAG_CACHE_SHUT); } } /** * 在线人数统计 +1 */ SSOStatistic statistic = config.getStatistic(); if ( statistic != null ) { boolean rlt = statistic.increase(request); if ( !rlt ) { statistic.increase(request); } } /** * 执行插件逻辑 */ List<SSOPlugin> pluginList = config.getPluginList(); if ( pluginList != null ) { for ( SSOPlugin plugin : pluginList ) { boolean login = plugin.login(request, response); if ( !login ) { plugin.login(request, response); } } } /** * Cookie设置HttpOnly */ if ( config.getCookieHttponly() ) { CookieHelper.addHttpOnlyCookie(response, ck); } else { response.addCookie(ck); } } catch ( Exception e ) { logger.severe("set HTTPOnly cookie createAUID is exception! " + e.toString()); } } /** * <p> * 退出当前登录状态 * </p> * * @param request * @param response * @param SSOCache * @return boolean true 成功, false 失败 */ protected boolean logout( HttpServletRequest request, HttpServletResponse response, SSOCache cache ) { /** * Token 如果开启了缓存,删除缓存记录 */ if ( cache != null && !SSOConfig.SSO_KICK_USER.equals(request.getAttribute(SSOConfig.SSO_KICK_FLAG)) ) { Token tk = getTokenFromCookie(request); if ( tk != null ) { boolean rlt = cache.delete(tk.toCacheKey()); if ( !rlt ) { cache.delete(tk.toCacheKey()); } } } /** * 在线人数统计 -1 */ SSOStatistic statistic = config.getStatistic(); if ( statistic != null ) { boolean rlt = statistic.decrease(request); if ( !rlt ) { statistic.decrease(request); } } /** * 执行插件逻辑 */ List<SSOPlugin> pluginList = config.getPluginList(); if ( pluginList != null ) { for ( SSOPlugin plugin : pluginList ) { boolean logout = plugin.logout(request, response); if ( !logout ) { plugin.logout(request, response); } } } /** * 删除登录 Cookie */ return CookieHelper.clearCookieByName(request, response, config.getCookieName(), config.getCookieDomain(), config.getCookiePath()); } }
/* * $Id$ * * SARL is an general-purpose agent programming language. * More details on http://www.sarl.io * * Copyright (C) 2014-2020 the original authors or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.sarl.maven.bootiqueapp.lang; import com.google.inject.Module; import io.bootique.BQModule; import io.bootique.BQModuleProvider; import io.sarl.lang.SARLRuntimeModule; /** Provider of the module for the SARL compiler runtime. * * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ * @since 0.8 */ public class SARLRuntimeModuleProvider implements BQModuleProvider { @Override public Module module() { return new SARLRuntimeModule(); } @Override public BQModule.Builder moduleBuilder() { return BQModule .builder(module()) .overrides(overrides()) .providerName(name()) .configs(configs()) .description(Messages.SARLRuntimeModuleProvider_0); } }
/** * Copyright 2000-present Liferay, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.liferay.blade.samples.servicebuilder.service.persistence; import aQute.bnd.annotation.ProviderType; import com.liferay.blade.samples.servicebuilder.exception.NoSuchFooException; import com.liferay.blade.samples.servicebuilder.model.Foo; import com.liferay.portal.kernel.service.persistence.BasePersistence; import java.io.Serializable; import java.util.Map; import java.util.Set; /** * The persistence interface for the foo service. * * <p> * Caching information and settings can be found in <code>portal.properties</code> * </p> * * @author Brian Wing Shun Chan * @see FooUtil * @generated */ @ProviderType public interface FooPersistence extends BasePersistence<Foo> { /* * NOTE FOR DEVELOPERS: * * Never modify or reference this interface directly. Always use {@link FooUtil} to access the foo persistence. Modify <code>service.xml</code> and rerun ServiceBuilder to regenerate this interface. */ @Override public Map<Serializable, Foo> fetchByPrimaryKeys( Set<Serializable> primaryKeys); /** * Returns all the foos where uuid = &#63;. * * @param uuid the uuid * @return the matching foos */ public java.util.List<Foo> findByUuid(String uuid); /** * Returns a range of all the foos where uuid = &#63;. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to <code>QueryUtil#ALL_POS</code> will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not <code>QueryUtil#ALL_POS</code>), then the query will include the default ORDER BY logic from <code>FooModelImpl</code>. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. * </p> * * @param uuid the uuid * @param start the lower bound of the range of foos * @param end the upper bound of the range of foos (not inclusive) * @return the range of matching foos */ public java.util.List<Foo> findByUuid(String uuid, int start, int end); /** * Returns an ordered range of all the foos where uuid = &#63;. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to <code>QueryUtil#ALL_POS</code> will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not <code>QueryUtil#ALL_POS</code>), then the query will include the default ORDER BY logic from <code>FooModelImpl</code>. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. * </p> * * @param uuid the uuid * @param start the lower bound of the range of foos * @param end the upper bound of the range of foos (not inclusive) * @param orderByComparator the comparator to order the results by (optionally <code>null</code>) * @return the ordered range of matching foos */ public java.util.List<Foo> findByUuid( String uuid, int start, int end, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator); /** * Returns an ordered range of all the foos where uuid = &#63;. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to <code>QueryUtil#ALL_POS</code> will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not <code>QueryUtil#ALL_POS</code>), then the query will include the default ORDER BY logic from <code>FooModelImpl</code>. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. * </p> * * @param uuid the uuid * @param start the lower bound of the range of foos * @param end the upper bound of the range of foos (not inclusive) * @param orderByComparator the comparator to order the results by (optionally <code>null</code>) * @param retrieveFromCache whether to retrieve from the finder cache * @return the ordered range of matching foos */ public java.util.List<Foo> findByUuid( String uuid, int start, int end, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator, boolean retrieveFromCache); /** * Returns the first foo in the ordered set where uuid = &#63;. * * @param uuid the uuid * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the first matching foo * @throws NoSuchFooException if a matching foo could not be found */ public Foo findByUuid_First( String uuid, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator) throws NoSuchFooException; /** * Returns the first foo in the ordered set where uuid = &#63;. * * @param uuid the uuid * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the first matching foo, or <code>null</code> if a matching foo could not be found */ public Foo fetchByUuid_First( String uuid, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator); /** * Returns the last foo in the ordered set where uuid = &#63;. * * @param uuid the uuid * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the last matching foo * @throws NoSuchFooException if a matching foo could not be found */ public Foo findByUuid_Last( String uuid, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator) throws NoSuchFooException; /** * Returns the last foo in the ordered set where uuid = &#63;. * * @param uuid the uuid * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the last matching foo, or <code>null</code> if a matching foo could not be found */ public Foo fetchByUuid_Last( String uuid, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator); /** * Returns the foos before and after the current foo in the ordered set where uuid = &#63;. * * @param fooId the primary key of the current foo * @param uuid the uuid * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the previous, current, and next foo * @throws NoSuchFooException if a foo with the primary key could not be found */ public Foo[] findByUuid_PrevAndNext( long fooId, String uuid, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator) throws NoSuchFooException; /** * Removes all the foos where uuid = &#63; from the database. * * @param uuid the uuid */ public void removeByUuid(String uuid); /** * Returns the number of foos where uuid = &#63;. * * @param uuid the uuid * @return the number of matching foos */ public int countByUuid(String uuid); /** * Returns the foo where uuid = &#63; and groupId = &#63; or throws a <code>NoSuchFooException</code> if it could not be found. * * @param uuid the uuid * @param groupId the group ID * @return the matching foo * @throws NoSuchFooException if a matching foo could not be found */ public Foo findByUUID_G(String uuid, long groupId) throws NoSuchFooException; /** * Returns the foo where uuid = &#63; and groupId = &#63; or returns <code>null</code> if it could not be found. Uses the finder cache. * * @param uuid the uuid * @param groupId the group ID * @return the matching foo, or <code>null</code> if a matching foo could not be found */ public Foo fetchByUUID_G(String uuid, long groupId); /** * Returns the foo where uuid = &#63; and groupId = &#63; or returns <code>null</code> if it could not be found, optionally using the finder cache. * * @param uuid the uuid * @param groupId the group ID * @param retrieveFromCache whether to retrieve from the finder cache * @return the matching foo, or <code>null</code> if a matching foo could not be found */ public Foo fetchByUUID_G( String uuid, long groupId, boolean retrieveFromCache); /** * Removes the foo where uuid = &#63; and groupId = &#63; from the database. * * @param uuid the uuid * @param groupId the group ID * @return the foo that was removed */ public Foo removeByUUID_G(String uuid, long groupId) throws NoSuchFooException; /** * Returns the number of foos where uuid = &#63; and groupId = &#63;. * * @param uuid the uuid * @param groupId the group ID * @return the number of matching foos */ public int countByUUID_G(String uuid, long groupId); /** * Returns all the foos where uuid = &#63; and companyId = &#63;. * * @param uuid the uuid * @param companyId the company ID * @return the matching foos */ public java.util.List<Foo> findByUuid_C(String uuid, long companyId); /** * Returns a range of all the foos where uuid = &#63; and companyId = &#63;. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to <code>QueryUtil#ALL_POS</code> will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not <code>QueryUtil#ALL_POS</code>), then the query will include the default ORDER BY logic from <code>FooModelImpl</code>. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. * </p> * * @param uuid the uuid * @param companyId the company ID * @param start the lower bound of the range of foos * @param end the upper bound of the range of foos (not inclusive) * @return the range of matching foos */ public java.util.List<Foo> findByUuid_C( String uuid, long companyId, int start, int end); /** * Returns an ordered range of all the foos where uuid = &#63; and companyId = &#63;. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to <code>QueryUtil#ALL_POS</code> will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not <code>QueryUtil#ALL_POS</code>), then the query will include the default ORDER BY logic from <code>FooModelImpl</code>. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. * </p> * * @param uuid the uuid * @param companyId the company ID * @param start the lower bound of the range of foos * @param end the upper bound of the range of foos (not inclusive) * @param orderByComparator the comparator to order the results by (optionally <code>null</code>) * @return the ordered range of matching foos */ public java.util.List<Foo> findByUuid_C( String uuid, long companyId, int start, int end, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator); /** * Returns an ordered range of all the foos where uuid = &#63; and companyId = &#63;. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to <code>QueryUtil#ALL_POS</code> will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not <code>QueryUtil#ALL_POS</code>), then the query will include the default ORDER BY logic from <code>FooModelImpl</code>. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. * </p> * * @param uuid the uuid * @param companyId the company ID * @param start the lower bound of the range of foos * @param end the upper bound of the range of foos (not inclusive) * @param orderByComparator the comparator to order the results by (optionally <code>null</code>) * @param retrieveFromCache whether to retrieve from the finder cache * @return the ordered range of matching foos */ public java.util.List<Foo> findByUuid_C( String uuid, long companyId, int start, int end, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator, boolean retrieveFromCache); /** * Returns the first foo in the ordered set where uuid = &#63; and companyId = &#63;. * * @param uuid the uuid * @param companyId the company ID * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the first matching foo * @throws NoSuchFooException if a matching foo could not be found */ public Foo findByUuid_C_First( String uuid, long companyId, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator) throws NoSuchFooException; /** * Returns the first foo in the ordered set where uuid = &#63; and companyId = &#63;. * * @param uuid the uuid * @param companyId the company ID * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the first matching foo, or <code>null</code> if a matching foo could not be found */ public Foo fetchByUuid_C_First( String uuid, long companyId, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator); /** * Returns the last foo in the ordered set where uuid = &#63; and companyId = &#63;. * * @param uuid the uuid * @param companyId the company ID * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the last matching foo * @throws NoSuchFooException if a matching foo could not be found */ public Foo findByUuid_C_Last( String uuid, long companyId, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator) throws NoSuchFooException; /** * Returns the last foo in the ordered set where uuid = &#63; and companyId = &#63;. * * @param uuid the uuid * @param companyId the company ID * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the last matching foo, or <code>null</code> if a matching foo could not be found */ public Foo fetchByUuid_C_Last( String uuid, long companyId, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator); /** * Returns the foos before and after the current foo in the ordered set where uuid = &#63; and companyId = &#63;. * * @param fooId the primary key of the current foo * @param uuid the uuid * @param companyId the company ID * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the previous, current, and next foo * @throws NoSuchFooException if a foo with the primary key could not be found */ public Foo[] findByUuid_C_PrevAndNext( long fooId, String uuid, long companyId, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator) throws NoSuchFooException; /** * Removes all the foos where uuid = &#63; and companyId = &#63; from the database. * * @param uuid the uuid * @param companyId the company ID */ public void removeByUuid_C(String uuid, long companyId); /** * Returns the number of foos where uuid = &#63; and companyId = &#63;. * * @param uuid the uuid * @param companyId the company ID * @return the number of matching foos */ public int countByUuid_C(String uuid, long companyId); /** * Returns all the foos where field2 = &#63;. * * @param field2 the field2 * @return the matching foos */ public java.util.List<Foo> findByField2(boolean field2); /** * Returns a range of all the foos where field2 = &#63;. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to <code>QueryUtil#ALL_POS</code> will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not <code>QueryUtil#ALL_POS</code>), then the query will include the default ORDER BY logic from <code>FooModelImpl</code>. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. * </p> * * @param field2 the field2 * @param start the lower bound of the range of foos * @param end the upper bound of the range of foos (not inclusive) * @return the range of matching foos */ public java.util.List<Foo> findByField2(boolean field2, int start, int end); /** * Returns an ordered range of all the foos where field2 = &#63;. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to <code>QueryUtil#ALL_POS</code> will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not <code>QueryUtil#ALL_POS</code>), then the query will include the default ORDER BY logic from <code>FooModelImpl</code>. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. * </p> * * @param field2 the field2 * @param start the lower bound of the range of foos * @param end the upper bound of the range of foos (not inclusive) * @param orderByComparator the comparator to order the results by (optionally <code>null</code>) * @return the ordered range of matching foos */ public java.util.List<Foo> findByField2( boolean field2, int start, int end, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator); /** * Returns an ordered range of all the foos where field2 = &#63;. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to <code>QueryUtil#ALL_POS</code> will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not <code>QueryUtil#ALL_POS</code>), then the query will include the default ORDER BY logic from <code>FooModelImpl</code>. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. * </p> * * @param field2 the field2 * @param start the lower bound of the range of foos * @param end the upper bound of the range of foos (not inclusive) * @param orderByComparator the comparator to order the results by (optionally <code>null</code>) * @param retrieveFromCache whether to retrieve from the finder cache * @return the ordered range of matching foos */ public java.util.List<Foo> findByField2( boolean field2, int start, int end, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator, boolean retrieveFromCache); /** * Returns the first foo in the ordered set where field2 = &#63;. * * @param field2 the field2 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the first matching foo * @throws NoSuchFooException if a matching foo could not be found */ public Foo findByField2_First( boolean field2, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator) throws NoSuchFooException; /** * Returns the first foo in the ordered set where field2 = &#63;. * * @param field2 the field2 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the first matching foo, or <code>null</code> if a matching foo could not be found */ public Foo fetchByField2_First( boolean field2, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator); /** * Returns the last foo in the ordered set where field2 = &#63;. * * @param field2 the field2 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the last matching foo * @throws NoSuchFooException if a matching foo could not be found */ public Foo findByField2_Last( boolean field2, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator) throws NoSuchFooException; /** * Returns the last foo in the ordered set where field2 = &#63;. * * @param field2 the field2 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the last matching foo, or <code>null</code> if a matching foo could not be found */ public Foo fetchByField2_Last( boolean field2, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator); /** * Returns the foos before and after the current foo in the ordered set where field2 = &#63;. * * @param fooId the primary key of the current foo * @param field2 the field2 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the previous, current, and next foo * @throws NoSuchFooException if a foo with the primary key could not be found */ public Foo[] findByField2_PrevAndNext( long fooId, boolean field2, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator) throws NoSuchFooException; /** * Removes all the foos where field2 = &#63; from the database. * * @param field2 the field2 */ public void removeByField2(boolean field2); /** * Returns the number of foos where field2 = &#63;. * * @param field2 the field2 * @return the number of matching foos */ public int countByField2(boolean field2); /** * Caches the foo in the entity cache if it is enabled. * * @param foo the foo */ public void cacheResult(Foo foo); /** * Caches the foos in the entity cache if it is enabled. * * @param foos the foos */ public void cacheResult(java.util.List<Foo> foos); /** * Creates a new foo with the primary key. Does not add the foo to the database. * * @param fooId the primary key for the new foo * @return the new foo */ public Foo create(long fooId); /** * Removes the foo with the primary key from the database. Also notifies the appropriate model listeners. * * @param fooId the primary key of the foo * @return the foo that was removed * @throws NoSuchFooException if a foo with the primary key could not be found */ public Foo remove(long fooId) throws NoSuchFooException; public Foo updateImpl(Foo foo); /** * Returns the foo with the primary key or throws a <code>NoSuchFooException</code> if it could not be found. * * @param fooId the primary key of the foo * @return the foo * @throws NoSuchFooException if a foo with the primary key could not be found */ public Foo findByPrimaryKey(long fooId) throws NoSuchFooException; /** * Returns the foo with the primary key or returns <code>null</code> if it could not be found. * * @param fooId the primary key of the foo * @return the foo, or <code>null</code> if a foo with the primary key could not be found */ public Foo fetchByPrimaryKey(long fooId); /** * Returns all the foos. * * @return the foos */ public java.util.List<Foo> findAll(); /** * Returns a range of all the foos. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to <code>QueryUtil#ALL_POS</code> will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not <code>QueryUtil#ALL_POS</code>), then the query will include the default ORDER BY logic from <code>FooModelImpl</code>. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. * </p> * * @param start the lower bound of the range of foos * @param end the upper bound of the range of foos (not inclusive) * @return the range of foos */ public java.util.List<Foo> findAll(int start, int end); /** * Returns an ordered range of all the foos. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to <code>QueryUtil#ALL_POS</code> will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not <code>QueryUtil#ALL_POS</code>), then the query will include the default ORDER BY logic from <code>FooModelImpl</code>. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. * </p> * * @param start the lower bound of the range of foos * @param end the upper bound of the range of foos (not inclusive) * @param orderByComparator the comparator to order the results by (optionally <code>null</code>) * @return the ordered range of foos */ public java.util.List<Foo> findAll( int start, int end, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator); /** * Returns an ordered range of all the foos. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to <code>QueryUtil#ALL_POS</code> will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not <code>QueryUtil#ALL_POS</code>), then the query will include the default ORDER BY logic from <code>FooModelImpl</code>. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. * </p> * * @param start the lower bound of the range of foos * @param end the upper bound of the range of foos (not inclusive) * @param orderByComparator the comparator to order the results by (optionally <code>null</code>) * @param retrieveFromCache whether to retrieve from the finder cache * @return the ordered range of foos */ public java.util.List<Foo> findAll( int start, int end, com.liferay.portal.kernel.util.OrderByComparator<Foo> orderByComparator, boolean retrieveFromCache); /** * Removes all the foos from the database. */ public void removeAll(); /** * Returns the number of foos. * * @return the number of foos */ public int countAll(); @Override public Set<String> getBadColumnNames(); }
/** * Classes that are filtered using groups */ package com.rationaleemotions.scenarios.three;
package com.am.bp.innovations; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2).select() .apis(RequestHandlerSelectors.basePackage("com.am.bp.innovations")).build(); } }
package eu.mhsl.openquiz.screen; import eu.mhsl.openquiz.OpenQuiz; import eu.mhsl.openquiz.out.Logger; import java.util.TreeMap; /** * Implements the Main or Home-Screen */ public class ScreenOpening implements Screen { public final TreeMap<Integer, String> items = new TreeMap<>(); public ScreenOpening() { items.put(1, "Spielen"); items.put(2, "Erstellen"); items.put(3, "Importieren"); items.put(4, "Hosten"); items.put(5, "Beenden"); } public Screen display() { int command = OpenQuiz.getTerminal().choice("OpenQuiz", items); switch (command) { case 1: return new ScreenQuizList(); case 2: return new ScreenQuizCreator(); case 3: return new ScreenImport(); case 4: return new ScreenProvide(); case 5: Logger.info("Thanks for Playing <3"); default: return null; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.kalumet.model; import org.apache.xerces.dom.CoreDocumentImpl; import org.apache.xerces.dom.ElementImpl; import org.w3c.dom.Element; import java.io.Serializable; /** * Represent the <code>jndibinding</code> tag in the Kalumet configuration DOM. */ public class JNDIBinding implements Serializable, Cloneable, Comparable { private static final long serialVersionUID = -2336476111740231781L; private String name; private String jndiname; private String jndialias; private String providerurl; private boolean active; private boolean blocker; public JNDIBinding() { } public String getName() { return this.name; } public void setName( String name ) { this.name = name; } public String getJndiname() { return this.jndiname; } public void setJndiname( String jndiname ) { this.jndiname = jndiname; } public String getJndialias() { return this.jndialias; } public void setJndialias( String jndialias ) { this.jndialias = jndialias; } public String getProviderurl() { return this.providerurl; } public void setProviderurl( String providerurl ) { this.providerurl = providerurl; } public boolean isActive() { return this.active; } public void setActive( boolean active ) { this.active = active; } public boolean isBlocker() { return this.blocker; } public void setBlocker( boolean blocker ) { this.blocker = blocker; } /** * @see java.lang.Object#clone() */ public Object clone() throws CloneNotSupportedException { JNDIBinding clone = new JNDIBinding(); clone.setName( this.getName() ); clone.setJndiname( this.getJndiname() ); clone.setJndialias( this.getJndialias() ); clone.setProviderurl( this.getProviderurl() ); clone.setActive( this.isActive() ); clone.setBlocker( this.isBlocker() ); return clone; } /** * Transform the <code>JNDIBinding</code> POJO to a DOM element. * * @param document the DOM document. * @return the DOM element. */ protected Element toDOMElement( CoreDocumentImpl document ) { ElementImpl element = new ElementImpl( document, "jndibinding" ); element.setAttribute( "name", this.getName() ); element.setAttribute( "jndiname", this.getJndiname() ); element.setAttribute( "jndialias", this.getJndialias() ); element.setAttribute( "providerurl", this.getProviderurl() ); element.setAttribute( "active", new Boolean( this.isActive() ).toString() ); element.setAttribute( "blocker", new Boolean( this.isBlocker() ).toString() ); return element; } /** * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo( Object anotherNameSpaceBinding ) { return this.getName().compareTo( ( (JNDIBinding) anotherNameSpaceBinding ).getName() ); } }
/** * ============================== Header ============================== * file: HTTPRequest.java * project: FIT4Green/Manager * created: 13 sep. 2011 by vicky@almende.org * * $LastChangedDate: 2011-11-09 12:42:17 +0100 (mié, 09 nov 2011) $ * $LastChangedBy: vicky@almende.org $ * $LastChangedRevision: 1085 $ * * short description: * Utility class for HTTP requests * ============================= /Header ============================== */ package f4g.manager.couchDB; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; /** * Utility class for HTTP requests * * @author Vasiliki Georgiadou */ public class HTTPRequest { private final int TIME_OUT = 10000; // max is 10 sec private int returnCode; private String contentType; public HTTPRequest() { this.returnCode = 0; this.contentType = null; } public HTTPRequest(String contentType) { this.returnCode = 0; this.contentType = contentType; } public int getReturnCode() { return returnCode; } /** * Sends an HTTP GET request to a url. * Content-Type may be specified by means of the constructor. * * @param url The url * @param data (optional) The parameters to the request, for example * "param1=val1&param2=val2"; "?" added internally * @return The response string * @throws Exception */ public String sendGetRequest(String url, String data) throws Exception { String response = null; try { if (data != null){ url += "?" + data; } HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT); if (this.contentType != null) { conn.setRequestProperty("Content-Type", this.contentType); } this.returnCode = conn.getResponseCode(); if (this.returnCode == HttpURLConnection.HTTP_OK) { InputStream is = conn.getInputStream(); response = streamToString(is); is.close(); } else { response = "return code: " + this.returnCode; } } catch( IOException e ){ e.printStackTrace(); } return response; } /** * Sends an HTTP PUT request to a url. * Content-Type may be specified by means of the constructor. * * @param url The url * @param data The body of the request * @return The response string * @throws Exception */ public String sendPutRequest(String url, String data) throws Exception { String response = null; try { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setUseCaches(false); conn.setDoOutput(true); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT); conn.setRequestMethod("PUT"); if (this.contentType != null) { conn.setRequestProperty("Content-Type", this.contentType); } if (data != null) { OutputStreamWriter os = new OutputStreamWriter (conn.getOutputStream()); os.write(data); os.flush(); os.close(); } this.returnCode = conn.getResponseCode(); if (this.returnCode == HttpURLConnection.HTTP_OK) { InputStream is = conn.getInputStream(); response = streamToString(is); is.close(); } else { response = "return code: " + this.returnCode; } } catch( IOException e ){ e.printStackTrace(); } return response; } /** * Sends an HTTP DELETE request to a url. * Overriding Content-Type with "application/x-www-form-urlencoded". * * @param url The url * @param data (optional) The parameters to the request, for example * "param1=val1&param2=val2"; "?" added internally * @return The response string * @throws Exception */ public String sendDeleteRequest(String url, String data) throws Exception { String response = null; try { if (data != null){ url += "?" + data; } HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setUseCaches(false); conn.setDoOutput(true); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT); // Overriding content type!!! conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded" ); conn.setRequestMethod("DELETE"); conn.connect(); this.returnCode= conn.getResponseCode(); if (this.returnCode == HttpURLConnection.HTTP_OK) { InputStream is = conn.getInputStream(); response = streamToString(is); is.close(); } else { response = "return code: " + this.returnCode; } } catch( IOException e ){ e.printStackTrace(); } return response; } /** * Sends an HTTP POST request to a url. * Content-Type may be specified by means of the constructor. * * @param url The url * @param data (optional) The body of the request * @return The response string * @throws Exception */ public String sendPostRequest(String url, String data) throws Exception{ String response = null; try { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setUseCaches(false); conn.setDoOutput(true); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT); if (this.contentType != null) { conn.setRequestProperty("Content-Type", this.contentType); } conn.setRequestMethod("POST"); if (data != null ){ OutputStream os = conn.getOutputStream(); os.write( data.getBytes() ); os.flush(); os.close(); } this.returnCode = conn.getResponseCode(); if (this.returnCode == HttpURLConnection.HTTP_OK) { InputStream is = conn.getInputStream(); response = streamToString(is); is.close(); } else { response = "return code: " + this.returnCode; } } catch( IOException e ){ e.printStackTrace(); } return response; } /** * Converts a stream to a string; UTF8 encoding * * @param in The InputStream * @return The String * @throws Exception */ private String streamToString(InputStream in) throws Exception { InputStreamReader inreader = new InputStreamReader(in, "UTF8"); BufferedReader reader = new BufferedReader(inreader); StringBuilder out = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { out.append(line + "\n"); } return out.toString(); } }
package com.gooddata.connector; import com.gooddata.GoodDataException; import com.gooddata.project.Project; import static java.lang.String.format; /** * Integration for given project and connector type doesn't exist */ public class IntegrationNotFoundException extends GoodDataException { private final String projectUri; private final ConnectorType connectorType; public IntegrationNotFoundException(Project project, ConnectorType connectorType, Throwable e) { super(format("Integration %s was not found for project %s", connectorType.getName(), project.getUri()), e); this.projectUri = project.getUri(); this.connectorType = connectorType; } public String getProjectUri() { return projectUri; } public ConnectorType getConnectorType() { return connectorType; } }
/* * Copyright 2017-2018, Société Générale 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.societegenerale.commons.amqp.core.processor; import org.springframework.amqp.core.MessagePostProcessor; /** * Created by Anand Manissery on 8/3/2017. */ public interface CorrelationPostProcessor extends MessagePostProcessor{ }
package io.spinor.ig.api.rest.dto.workingorders.otc.createOTCWorkingOrderV1; /* Working order type */ public enum Type { /* Limit working order */ LIMIT, /* Stop working order */ STOP }
package br.com.srportto.dtos.request; import br.com.srportto.dtos.general.UserDTO; import br.com.srportto.services.validation.criacao.UserInsertValid; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.NotBlank; @NoArgsConstructor @Data @UserInsertValid public class UserInsertRequestDTO extends UserDTO { @NotBlank(message = "Campo password é obrigatório") private String password; }
/* * YAGetBooleanStaticTest2.java * Copyright 2008, 2009, 2010, 2011, 2012, 2013 Fiji Systems Inc. * This file is part of the FIJI VM Software licensed under the FIJI PUBLIC * LICENSE Version 3 or any later version. A copy of the FIJI PUBLIC LICENSE is * available at fivm/LEGAL and can also be found at * http://www.fiji-systems.com/FPL3.txt * * By installing, reproducing, distributing, and/or using the FIJI VM Software * you agree to the terms of the FIJI PUBLIC LICENSE. You may exercise the * rights granted under the FIJI PUBLIC LICENSE subject to the conditions and * restrictions stated therein. Among other conditions and restrictions, the * FIJI PUBLIC LICENSE states that: * * a. You may only make non-commercial use of the FIJI VM Software. * * b. Any adaptation you make must be licensed under the same terms * of the FIJI PUBLIC LICENSE. * * c. You must include a copy of the FIJI PUBLIC LICENSE in every copy of any * file, adaptation or output code that you distribute and cause the output code * to provide a notice of the FIJI PUBLIC LICENSE. * * d. You must not impose any additional conditions. * * e. You must not assert or imply any connection, sponsorship or endorsement by * the author of the FIJI VM Software * * f. You must take no derogatory action in relation to the FIJI VM Software * which would be prejudicial to the FIJI VM Software author's honor or * reputation. * * * The FIJI VM Software is provided as-is. FIJI SYSTEMS INC does not make any * representation and provides no warranty of any kind concerning the software. * * The FIJI PUBLIC LICENSE and any rights granted therein terminate * automatically upon any breach by you of the terms of the FIJI PUBLIC LICENSE. */ package com.fiji.fivm.test; public class YAGetBooleanStaticTest2 { public static void main(String[] v) { System.out.println(YetAnotherClass.sfpredicate); } }
package com.furquan.ecommerce.security; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import com.furquan.ecommerce.service.SecurityService; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * JWT Authentication Filter * If an 'Authorization' header is found in the HTTP Request then the token is being retrieved. * That token will be validated and, if successful, then user will be authenticated. * * @author furquan */ @Component public class JWTAuthenticationFilter extends OncePerRequestFilter { private static final Logger logger = LoggerFactory.getLogger(JWTAuthenticationFilter.class); private static final String HEADER_STRING = "Authorization"; @Autowired private SecurityService securityService; @Override protected void doFilterInternal(HttpServletRequest httpRequest, HttpServletResponse httpResponse, FilterChain filterChain) throws ServletException, IOException { final String token = httpRequest.getHeader(HEADER_STRING); if (token != null && SecurityContextHolder.getContext().getAuthentication() == null) { try { securityService.authenticate(token); } catch (Exception e) { logger.debug("Failed when authenticating token '{}'. Error: '{}'", token, e.getMessage()); } } filterChain.doFilter(httpRequest, httpResponse); } }
/** * This package contains the core-logic of the 'scenarios' or 'benchmarks' which are the heart of our client. New {@link org.polypheny.client.scenarios.Scenario} should create their own package and add themselves to the protobuf-file and add a generator to the {@link * org.polypheny.client.scenarios.ScenarioFactory}. For a Reference Implementation see {@link org.polypheny.client.scenarios.tpcc.TPCCScenario}. The master should implement the {@link org.polypheny.client.scenarios.Scenario} interface, while the * worker should implement the {@link org.polypheny.client.scenarios.Worker} interface. * * @author Silvan Heller */ package org.polypheny.client.scenarios;
package org.contentmine.ami.wordutil; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import org.contentmine.ami.dictionary.TermPhrase; import org.junit.Assert; import org.junit.Test; public class TermPhraseTest { private static final Logger LOG = LogManager.getLogger(TermPhraseTest.class); @Test public void testPhrase() { TermPhrase phrase = TermPhrase.createTermPhrase("acid"); Assert.assertEquals(1, phrase.getWords().size()); Assert.assertEquals("acid", phrase.getWords().get(0)); } @Test public void testPhrase1() { TermPhrase phrase = TermPhrase.createTermPhrase("amino acid"); Assert.assertEquals(2, phrase.getWords().size()); Assert.assertEquals("amino", phrase.getWords().get(0)); Assert.assertEquals("acid", phrase.getWords().get(1)); } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.05.08 at 12:16:10 PM EDT // package edu.emory.cci.bindaas.datasource.provider.aime4.jaxb; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for COLL_TS complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="COLL_TS"> * &lt;complexContent> * &lt;extension base="{uri:iso.org:21090}ANY"> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "COLL_TS") @XmlSeeAlso({ BAGTS.class, DSETTS.class }) public abstract class COLLTS extends ANY { }
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.management.internal.cli.remote; import java.util.Collections; import java.util.List; import java.util.Map; import org.apache.geode.management.internal.cli.GfshParser; import org.apache.geode.management.internal.cli.shell.Gfsh; /** * * @since GemFire 7.0 */ public class CommandExecutionContext { // ThreadLocal variables that can be uses by commands private static final ThreadLocal<Map<String, String>> ENV = new ThreadLocal<>(); private static final ThreadLocal<Boolean> FROM_SHELL = new ThreadLocal<>(); private static final ThreadLocal<List<String>> SHELL_FILEPATH = new ThreadLocal<>(); public static String getShellEnvProperty(String propertyName, String defaultValue) { String propertyValue = null; Map<String, String> gfshEnv = ENV.get(); if (gfshEnv != null) { propertyValue = gfshEnv.get(propertyName); } return propertyValue != null ? propertyValue : defaultValue; } public static int getShellFetchSize() { int fetchSize = Gfsh.DEFAULT_APP_FETCH_SIZE; String fetchSizeStr = getShellEnvProperty(Gfsh.ENV_APP_FETCH_SIZE, null); if (fetchSizeStr != null) { fetchSize = Integer.parseInt(fetchSizeStr); } return fetchSize; } public static String getShellLineSeparator() { return getShellEnvProperty(Gfsh.ENV_SYS_OS_LINE_SEPARATOR, GfshParser.LINE_SEPARATOR); } public static Map<String, String> getShellEnv() { Map<String, String> envMap = ENV.get(); if (envMap != null) { return Collections.unmodifiableMap(envMap); } else { return Collections.emptyMap(); } } public static void setShellEnv(Map<String, String> env) { ENV.set(env); } public static List<String> getFilePathFromShell() { return SHELL_FILEPATH.get(); } public static void setFilePathToShell(List<String> data) { SHELL_FILEPATH.set(data); } public static boolean isShellRequest() { return FROM_SHELL.get() != null && FROM_SHELL.get(); } public static void setShellRequest() { FROM_SHELL.set(true); } public static void clear() { Map<String, String> map = ENV.get(); if (map != null) { map.clear(); } ENV.set(null); FROM_SHELL.set(false); SHELL_FILEPATH.set(null); } }
package com.hedera.services.fees.calculation.token.txns; /*- * ‌ * Hedera Services Node * ​ * Copyright (C) 2018 - 2020 Hedera Hashgraph, LLC * ​ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ‍ */ import com.hedera.services.context.primitives.StateView; import com.hedera.services.fees.calculation.UsageEstimatorUtils; import com.hedera.services.state.merkle.MerkleAccount; import com.hedera.services.state.merkle.MerkleEntityId; import com.hedera.services.usage.SigUsage; import com.hedera.services.usage.token.TokenDissociateUsage; import com.hedera.test.utils.IdUtils; import com.hederahashgraph.api.proto.java.AccountID; import com.hederahashgraph.api.proto.java.FeeComponents; import com.hederahashgraph.api.proto.java.FeeData; import com.hederahashgraph.api.proto.java.TokenDissociateTransactionBody; import com.hederahashgraph.api.proto.java.TokenID; import com.hederahashgraph.api.proto.java.TransactionBody; import com.hederahashgraph.fee.SigValueObj; import com.swirlds.fcmap.FCMap; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.util.function.BiFunction; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.mock; import static org.mockito.Mockito.verify; @RunWith(JUnitPlatform.class) class TokenDissociateResourceUsageTest { private TokenDissociateResourceUsage subject; AccountID target = IdUtils.asAccount("1.2.3"); MerkleAccount account; FCMap<MerkleEntityId, MerkleAccount> accounts; private TransactionBody nonTokenDissociateTxn; private TransactionBody tokenDissociateTxn; StateView view; int numSigs = 10, sigsSize = 100, numPayerKeys = 3; SigValueObj obj = new SigValueObj(numSigs, numPayerKeys, sigsSize); SigUsage sigUsage = new SigUsage(numSigs, sigsSize, numPayerKeys); TokenDissociateUsage usage; BiFunction<TransactionBody, SigUsage, TokenDissociateUsage> factory; long expiry = 1_234_567L; TokenID firstToken = IdUtils.asToken("0.0.123"); TokenID secondToken = IdUtils.asToken("0.0.124"); @BeforeEach private void setup() throws Throwable { account = mock(MerkleAccount.class); given(account.getExpiry()).willReturn(expiry); accounts = mock(FCMap.class); given(accounts.get(MerkleEntityId.fromAccountId(target))).willReturn(account); view = mock(StateView.class); given(view.accounts()).willReturn(accounts); tokenDissociateTxn = mock(TransactionBody.class); given(tokenDissociateTxn.hasTokenDissociate()).willReturn(true); given(tokenDissociateTxn.getTokenDissociate()) .willReturn(TokenDissociateTransactionBody.newBuilder() .setAccount(IdUtils.asAccount("1.2.3")) .addTokens(firstToken) .addTokens(secondToken) .build()); nonTokenDissociateTxn = mock(TransactionBody.class); given(nonTokenDissociateTxn.hasTokenAssociate()).willReturn(false); factory = (BiFunction<TransactionBody, SigUsage, TokenDissociateUsage>) mock(BiFunction.class); given(factory.apply(tokenDissociateTxn, sigUsage)).willReturn(usage); usage = mock(TokenDissociateUsage.class); given(usage.get()).willReturn(MOCK_TOKEN_DISSOCIATE_USAGE); TokenDissociateResourceUsage.factory = factory; given(factory.apply(tokenDissociateTxn, sigUsage)).willReturn(usage); subject = new TokenDissociateResourceUsage(); } @Test public void recognizesApplicability() { // expect: assertTrue(subject.applicableTo(tokenDissociateTxn)); assertFalse(subject.applicableTo(nonTokenDissociateTxn)); } @Test public void delegatesToCorrectEstimate() throws Exception { // expect: assertEquals( MOCK_TOKEN_DISSOCIATE_USAGE, subject.usageGiven(tokenDissociateTxn, obj, view)); } @Test public void returnsDefaultIfInfoMissing() throws Exception { given(accounts.get(MerkleEntityId.fromAccountId(target))).willReturn(null); // expect: assertEquals( FeeData.getDefaultInstance(), subject.usageGiven(tokenDissociateTxn, obj, view)); } public static final FeeData MOCK_TOKEN_DISSOCIATE_USAGE = UsageEstimatorUtils.defaultPartitioning( FeeComponents.newBuilder() .setMin(1) .setMax(1_000_000) .setConstant(3) .setBpt(3) .setVpt(3) .setRbh(3) .setSbh(3) .setGas(3) .setTv(3) .setBpr(3) .setSbpr(3) .build(), 3); }
package com.flechow.pinboard.service; import io.github.jhipster.config.JHipsterProperties; import com.flechow.pinboard.config.audit.AuditEventConverter; import com.flechow.pinboard.repository.PersistenceAuditEventRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Optional; /** * Service for managing audit events. * <p> * This is the default implementation to support SpringBoot Actuator {@code AuditEventRepository}. */ @Service @Transactional public class AuditEventService { private final Logger log = LoggerFactory.getLogger(AuditEventService.class); private final JHipsterProperties jHipsterProperties; private final PersistenceAuditEventRepository persistenceAuditEventRepository; private final AuditEventConverter auditEventConverter; public AuditEventService( PersistenceAuditEventRepository persistenceAuditEventRepository, AuditEventConverter auditEventConverter, JHipsterProperties jhipsterProperties) { this.persistenceAuditEventRepository = persistenceAuditEventRepository; this.auditEventConverter = auditEventConverter; this.jHipsterProperties = jhipsterProperties; } /** * Old audit events should be automatically deleted after 30 days. * * This is scheduled to get fired at 12:00 (am). */ @Scheduled(cron = "0 0 12 * * ?") public void removeOldAuditEvents() { persistenceAuditEventRepository .findByAuditEventDateBefore(Instant.now().minus(jHipsterProperties.getAuditEvents().getRetentionPeriod(), ChronoUnit.DAYS)) .forEach(auditEvent -> { log.debug("Deleting audit data {}", auditEvent); persistenceAuditEventRepository.delete(auditEvent); }); } @Transactional(readOnly = true) public Page<AuditEvent> findAll(Pageable pageable) { return persistenceAuditEventRepository.findAll(pageable) .map(auditEventConverter::convertToAuditEvent); } @Transactional(readOnly = true) public Page<AuditEvent> findByDates(Instant fromDate, Instant toDate, Pageable pageable) { return persistenceAuditEventRepository.findAllByAuditEventDateBetween(fromDate, toDate, pageable) .map(auditEventConverter::convertToAuditEvent); } @Transactional(readOnly = true) public Optional<AuditEvent> find(Long id) { return persistenceAuditEventRepository.findById(id) .map(auditEventConverter::convertToAuditEvent); } }
/* * Copyright 2013-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.elastictranscoder.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * The <code>Permission</code> structure. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class Permission implements Serializable, Cloneable, StructuredPojo { /** * <p> * The type of value that appears in the Grantee object: * </p> * <ul> * <li> * <p> * <code>Canonical</code>: Either the canonical user ID for an AWS account or an origin access identity for an * Amazon CloudFront distribution. * </p> * <important> * <p> * A canonical user ID is not the same as an AWS account number. * </p> * </important></li> * <li> * <p> * <code>Email</code>: The registered email address of an AWS account. * </p> * </li> * <li> * <p> * <code>Group</code>: One of the following predefined Amazon S3 groups: <code>AllUsers</code>, * <code>AuthenticatedUsers</code>, or <code>LogDelivery</code>. * </p> * </li> * </ul> */ private String granteeType; /** * <p> * The AWS user or group that you want to have access to transcoded files and playlists. To identify the user or * group, you can specify the canonical user ID for an AWS account, an origin access identity for a CloudFront * distribution, the registered email address of an AWS account, or a predefined Amazon S3 group. * </p> */ private String grantee; /** * <p> * The permission that you want to give to the AWS user that is listed in Grantee. Valid values include: * </p> * <ul> * <li> * <p> * <code>READ</code>: The grantee can read the thumbnails and metadata for thumbnails that Elastic Transcoder adds * to the Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>READ_ACP</code>: The grantee can read the object ACL for thumbnails that Elastic Transcoder adds to the * Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>WRITE_ACP</code>: The grantee can write the ACL for the thumbnails that Elastic Transcoder adds to the * Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>FULL_CONTROL</code>: The grantee has READ, READ_ACP, and WRITE_ACP permissions for the thumbnails that * Elastic Transcoder adds to the Amazon S3 bucket. * </p> * </li> * </ul> */ private com.amazonaws.internal.SdkInternalList<String> access; /** * <p> * The type of value that appears in the Grantee object: * </p> * <ul> * <li> * <p> * <code>Canonical</code>: Either the canonical user ID for an AWS account or an origin access identity for an * Amazon CloudFront distribution. * </p> * <important> * <p> * A canonical user ID is not the same as an AWS account number. * </p> * </important></li> * <li> * <p> * <code>Email</code>: The registered email address of an AWS account. * </p> * </li> * <li> * <p> * <code>Group</code>: One of the following predefined Amazon S3 groups: <code>AllUsers</code>, * <code>AuthenticatedUsers</code>, or <code>LogDelivery</code>. * </p> * </li> * </ul> * * @param granteeType * The type of value that appears in the Grantee object:</p> * <ul> * <li> * <p> * <code>Canonical</code>: Either the canonical user ID for an AWS account or an origin access identity for * an Amazon CloudFront distribution. * </p> * <important> * <p> * A canonical user ID is not the same as an AWS account number. * </p> * </important></li> * <li> * <p> * <code>Email</code>: The registered email address of an AWS account. * </p> * </li> * <li> * <p> * <code>Group</code>: One of the following predefined Amazon S3 groups: <code>AllUsers</code>, * <code>AuthenticatedUsers</code>, or <code>LogDelivery</code>. * </p> * </li> */ public void setGranteeType(String granteeType) { this.granteeType = granteeType; } /** * <p> * The type of value that appears in the Grantee object: * </p> * <ul> * <li> * <p> * <code>Canonical</code>: Either the canonical user ID for an AWS account or an origin access identity for an * Amazon CloudFront distribution. * </p> * <important> * <p> * A canonical user ID is not the same as an AWS account number. * </p> * </important></li> * <li> * <p> * <code>Email</code>: The registered email address of an AWS account. * </p> * </li> * <li> * <p> * <code>Group</code>: One of the following predefined Amazon S3 groups: <code>AllUsers</code>, * <code>AuthenticatedUsers</code>, or <code>LogDelivery</code>. * </p> * </li> * </ul> * * @return The type of value that appears in the Grantee object:</p> * <ul> * <li> * <p> * <code>Canonical</code>: Either the canonical user ID for an AWS account or an origin access identity for * an Amazon CloudFront distribution. * </p> * <important> * <p> * A canonical user ID is not the same as an AWS account number. * </p> * </important></li> * <li> * <p> * <code>Email</code>: The registered email address of an AWS account. * </p> * </li> * <li> * <p> * <code>Group</code>: One of the following predefined Amazon S3 groups: <code>AllUsers</code>, * <code>AuthenticatedUsers</code>, or <code>LogDelivery</code>. * </p> * </li> */ public String getGranteeType() { return this.granteeType; } /** * <p> * The type of value that appears in the Grantee object: * </p> * <ul> * <li> * <p> * <code>Canonical</code>: Either the canonical user ID for an AWS account or an origin access identity for an * Amazon CloudFront distribution. * </p> * <important> * <p> * A canonical user ID is not the same as an AWS account number. * </p> * </important></li> * <li> * <p> * <code>Email</code>: The registered email address of an AWS account. * </p> * </li> * <li> * <p> * <code>Group</code>: One of the following predefined Amazon S3 groups: <code>AllUsers</code>, * <code>AuthenticatedUsers</code>, or <code>LogDelivery</code>. * </p> * </li> * </ul> * * @param granteeType * The type of value that appears in the Grantee object:</p> * <ul> * <li> * <p> * <code>Canonical</code>: Either the canonical user ID for an AWS account or an origin access identity for * an Amazon CloudFront distribution. * </p> * <important> * <p> * A canonical user ID is not the same as an AWS account number. * </p> * </important></li> * <li> * <p> * <code>Email</code>: The registered email address of an AWS account. * </p> * </li> * <li> * <p> * <code>Group</code>: One of the following predefined Amazon S3 groups: <code>AllUsers</code>, * <code>AuthenticatedUsers</code>, or <code>LogDelivery</code>. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. */ public Permission withGranteeType(String granteeType) { setGranteeType(granteeType); return this; } /** * <p> * The AWS user or group that you want to have access to transcoded files and playlists. To identify the user or * group, you can specify the canonical user ID for an AWS account, an origin access identity for a CloudFront * distribution, the registered email address of an AWS account, or a predefined Amazon S3 group. * </p> * * @param grantee * The AWS user or group that you want to have access to transcoded files and playlists. To identify the user * or group, you can specify the canonical user ID for an AWS account, an origin access identity for a * CloudFront distribution, the registered email address of an AWS account, or a predefined Amazon S3 group. */ public void setGrantee(String grantee) { this.grantee = grantee; } /** * <p> * The AWS user or group that you want to have access to transcoded files and playlists. To identify the user or * group, you can specify the canonical user ID for an AWS account, an origin access identity for a CloudFront * distribution, the registered email address of an AWS account, or a predefined Amazon S3 group. * </p> * * @return The AWS user or group that you want to have access to transcoded files and playlists. To identify the * user or group, you can specify the canonical user ID for an AWS account, an origin access identity for a * CloudFront distribution, the registered email address of an AWS account, or a predefined Amazon S3 group. */ public String getGrantee() { return this.grantee; } /** * <p> * The AWS user or group that you want to have access to transcoded files and playlists. To identify the user or * group, you can specify the canonical user ID for an AWS account, an origin access identity for a CloudFront * distribution, the registered email address of an AWS account, or a predefined Amazon S3 group. * </p> * * @param grantee * The AWS user or group that you want to have access to transcoded files and playlists. To identify the user * or group, you can specify the canonical user ID for an AWS account, an origin access identity for a * CloudFront distribution, the registered email address of an AWS account, or a predefined Amazon S3 group. * @return Returns a reference to this object so that method calls can be chained together. */ public Permission withGrantee(String grantee) { setGrantee(grantee); return this; } /** * <p> * The permission that you want to give to the AWS user that is listed in Grantee. Valid values include: * </p> * <ul> * <li> * <p> * <code>READ</code>: The grantee can read the thumbnails and metadata for thumbnails that Elastic Transcoder adds * to the Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>READ_ACP</code>: The grantee can read the object ACL for thumbnails that Elastic Transcoder adds to the * Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>WRITE_ACP</code>: The grantee can write the ACL for the thumbnails that Elastic Transcoder adds to the * Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>FULL_CONTROL</code>: The grantee has READ, READ_ACP, and WRITE_ACP permissions for the thumbnails that * Elastic Transcoder adds to the Amazon S3 bucket. * </p> * </li> * </ul> * * @return The permission that you want to give to the AWS user that is listed in Grantee. Valid values include: * </p> * <ul> * <li> * <p> * <code>READ</code>: The grantee can read the thumbnails and metadata for thumbnails that Elastic * Transcoder adds to the Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>READ_ACP</code>: The grantee can read the object ACL for thumbnails that Elastic Transcoder adds to * the Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>WRITE_ACP</code>: The grantee can write the ACL for the thumbnails that Elastic Transcoder adds to * the Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>FULL_CONTROL</code>: The grantee has READ, READ_ACP, and WRITE_ACP permissions for the thumbnails * that Elastic Transcoder adds to the Amazon S3 bucket. * </p> * </li> */ public java.util.List<String> getAccess() { if (access == null) { access = new com.amazonaws.internal.SdkInternalList<String>(); } return access; } /** * <p> * The permission that you want to give to the AWS user that is listed in Grantee. Valid values include: * </p> * <ul> * <li> * <p> * <code>READ</code>: The grantee can read the thumbnails and metadata for thumbnails that Elastic Transcoder adds * to the Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>READ_ACP</code>: The grantee can read the object ACL for thumbnails that Elastic Transcoder adds to the * Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>WRITE_ACP</code>: The grantee can write the ACL for the thumbnails that Elastic Transcoder adds to the * Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>FULL_CONTROL</code>: The grantee has READ, READ_ACP, and WRITE_ACP permissions for the thumbnails that * Elastic Transcoder adds to the Amazon S3 bucket. * </p> * </li> * </ul> * * @param access * The permission that you want to give to the AWS user that is listed in Grantee. Valid values include: </p> * <ul> * <li> * <p> * <code>READ</code>: The grantee can read the thumbnails and metadata for thumbnails that Elastic Transcoder * adds to the Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>READ_ACP</code>: The grantee can read the object ACL for thumbnails that Elastic Transcoder adds to * the Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>WRITE_ACP</code>: The grantee can write the ACL for the thumbnails that Elastic Transcoder adds to * the Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>FULL_CONTROL</code>: The grantee has READ, READ_ACP, and WRITE_ACP permissions for the thumbnails * that Elastic Transcoder adds to the Amazon S3 bucket. * </p> * </li> */ public void setAccess(java.util.Collection<String> access) { if (access == null) { this.access = null; return; } this.access = new com.amazonaws.internal.SdkInternalList<String>(access); } /** * <p> * The permission that you want to give to the AWS user that is listed in Grantee. Valid values include: * </p> * <ul> * <li> * <p> * <code>READ</code>: The grantee can read the thumbnails and metadata for thumbnails that Elastic Transcoder adds * to the Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>READ_ACP</code>: The grantee can read the object ACL for thumbnails that Elastic Transcoder adds to the * Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>WRITE_ACP</code>: The grantee can write the ACL for the thumbnails that Elastic Transcoder adds to the * Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>FULL_CONTROL</code>: The grantee has READ, READ_ACP, and WRITE_ACP permissions for the thumbnails that * Elastic Transcoder adds to the Amazon S3 bucket. * </p> * </li> * </ul> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setAccess(java.util.Collection)} or {@link #withAccess(java.util.Collection)} if you want to override the * existing values. * </p> * * @param access * The permission that you want to give to the AWS user that is listed in Grantee. Valid values include: </p> * <ul> * <li> * <p> * <code>READ</code>: The grantee can read the thumbnails and metadata for thumbnails that Elastic Transcoder * adds to the Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>READ_ACP</code>: The grantee can read the object ACL for thumbnails that Elastic Transcoder adds to * the Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>WRITE_ACP</code>: The grantee can write the ACL for the thumbnails that Elastic Transcoder adds to * the Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>FULL_CONTROL</code>: The grantee has READ, READ_ACP, and WRITE_ACP permissions for the thumbnails * that Elastic Transcoder adds to the Amazon S3 bucket. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. */ public Permission withAccess(String... access) { if (this.access == null) { setAccess(new com.amazonaws.internal.SdkInternalList<String>(access.length)); } for (String ele : access) { this.access.add(ele); } return this; } /** * <p> * The permission that you want to give to the AWS user that is listed in Grantee. Valid values include: * </p> * <ul> * <li> * <p> * <code>READ</code>: The grantee can read the thumbnails and metadata for thumbnails that Elastic Transcoder adds * to the Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>READ_ACP</code>: The grantee can read the object ACL for thumbnails that Elastic Transcoder adds to the * Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>WRITE_ACP</code>: The grantee can write the ACL for the thumbnails that Elastic Transcoder adds to the * Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>FULL_CONTROL</code>: The grantee has READ, READ_ACP, and WRITE_ACP permissions for the thumbnails that * Elastic Transcoder adds to the Amazon S3 bucket. * </p> * </li> * </ul> * * @param access * The permission that you want to give to the AWS user that is listed in Grantee. Valid values include: </p> * <ul> * <li> * <p> * <code>READ</code>: The grantee can read the thumbnails and metadata for thumbnails that Elastic Transcoder * adds to the Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>READ_ACP</code>: The grantee can read the object ACL for thumbnails that Elastic Transcoder adds to * the Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>WRITE_ACP</code>: The grantee can write the ACL for the thumbnails that Elastic Transcoder adds to * the Amazon S3 bucket. * </p> * </li> * <li> * <p> * <code>FULL_CONTROL</code>: The grantee has READ, READ_ACP, and WRITE_ACP permissions for the thumbnails * that Elastic Transcoder adds to the Amazon S3 bucket. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. */ public Permission withAccess(java.util.Collection<String> access) { setAccess(access); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getGranteeType() != null) sb.append("GranteeType: ").append(getGranteeType()).append(","); if (getGrantee() != null) sb.append("Grantee: ").append(getGrantee()).append(","); if (getAccess() != null) sb.append("Access: ").append(getAccess()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof Permission == false) return false; Permission other = (Permission) obj; if (other.getGranteeType() == null ^ this.getGranteeType() == null) return false; if (other.getGranteeType() != null && other.getGranteeType().equals(this.getGranteeType()) == false) return false; if (other.getGrantee() == null ^ this.getGrantee() == null) return false; if (other.getGrantee() != null && other.getGrantee().equals(this.getGrantee()) == false) return false; if (other.getAccess() == null ^ this.getAccess() == null) return false; if (other.getAccess() != null && other.getAccess().equals(this.getAccess()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getGranteeType() == null) ? 0 : getGranteeType().hashCode()); hashCode = prime * hashCode + ((getGrantee() == null) ? 0 : getGrantee().hashCode()); hashCode = prime * hashCode + ((getAccess() == null) ? 0 : getAccess().hashCode()); return hashCode; } @Override public Permission clone() { try { return (Permission) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.elastictranscoder.model.transform.PermissionMarshaller.getInstance().marshall(this, protocolMarshaller); } }
/* * Copyright (C) 2017 Dremio Corporation * * 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. */ <@pp.dropOutputFile /> <@pp.changeOutputFile name="//com/dremio/exec/expr/fn/impl/hive/ObjectInspectorHelper.java" /> <#include "/@includes/license.ftl" /> package com.dremio.exec.expr.fn.impl.hive; import com.sun.codemodel.*; import com.dremio.common.types.TypeProtos.DataMode; import com.dremio.common.types.TypeProtos.MinorType; import com.dremio.exec.expr.ClassGenerator; import com.dremio.exec.expr.DirectExpression; import com.dremio.exec.expr.TypeHelper; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory; import org.apache.hadoop.hive.serde2.objectinspector.primitive.*; import java.lang.UnsupportedOperationException; import java.sql.Timestamp; import java.util.HashMap; import java.util.Map; import com.google.common.collect.Multimap; import com.google.common.collect.ArrayListMultimap; public class ObjectInspectorHelper { static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ObjectInspectorHelper.class); private static Multimap<MinorType, Class> OIMAP_REQUIRED = ArrayListMultimap.create(); private static Multimap<MinorType, Class> OIMAP_OPTIONAL = ArrayListMultimap.create(); static { <#list typesOI.map as entry> <#if entry.needOIForType == true> <#assign minorType = entry.minorType!entry.type?upper_case> OIMAP_REQUIRED.put(MinorType.${minorType}, ${entry.type}${entry.hiveOI}.Required.class); OIMAP_OPTIONAL.put(MinorType.${minorType}, ${entry.type}${entry.hiveOI}.Optional.class); </#if> </#list> } public static ObjectInspector getObjectInspector(DataMode mode, MinorType minorType, boolean varCharToStringReplacement) { try { if (mode == DataMode.REQUIRED) { if (OIMAP_REQUIRED.containsKey(minorType)) { if (varCharToStringReplacement && minorType == MinorType.VARCHAR) { return (ObjectInspector) ((Class) OIMAP_REQUIRED.get(minorType).toArray()[1]).newInstance(); } else { return (ObjectInspector) ((Class) OIMAP_REQUIRED.get(minorType).toArray()[0]).newInstance(); } } } else if (mode == DataMode.OPTIONAL) { if (OIMAP_OPTIONAL.containsKey(minorType)) { if (varCharToStringReplacement && minorType == MinorType.VARCHAR) { return (ObjectInspector) ((Class) OIMAP_OPTIONAL.get(minorType).toArray()[1]).newInstance(); } else { return (ObjectInspector) ((Class) OIMAP_OPTIONAL.get(minorType).toArray()[0]).newInstance(); } } } else { throw new UnsupportedOperationException("Repeated types are not supported as arguement to Hive UDFs"); } } catch(InstantiationException | IllegalAccessException e) { throw new RuntimeException("Failed to instantiate ObjectInspector", e); } throw new UnsupportedOperationException( String.format("Type %s[%s] not supported as arguement to Hive UDFs", minorType.toString(), mode.toString())); } public static JBlock initReturnValueHolder(ClassGenerator<?> g, JCodeModel m, JVar returnValueHolder, ObjectInspector oi, MinorType returnType) { JBlock block = new JBlock(false, false); switch(oi.getCategory()) { case PRIMITIVE: { PrimitiveObjectInspector poi = (PrimitiveObjectInspector)oi; switch(poi.getPrimitiveCategory()) { <#list typesOI.map as entry> case ${entry.hiveType}:{ JType holderClass = TypeHelper.getHolderType(m, returnType, DataMode.OPTIONAL); block.assign(returnValueHolder, JExpr._new(holderClass)); <#if entry.hiveType == "VARCHAR" || entry.hiveType == "STRING" || entry.hiveType == "BINARY" || entry.hiveType == "CHAR"> block.assign( // returnValueHolder.ref("buffer"), // JExpr .direct("context") .invoke("getManagedBuffer") .invoke("reallocIfNeeded") .arg(JExpr.lit(1024)) ); </#if> return block; } </#list> default: throw new UnsupportedOperationException(String.format("Received unknown/unsupported type '%s'", poi.getPrimitiveCategory().toString())); } } case MAP: case LIST: case STRUCT: default: throw new UnsupportedOperationException(String.format("Received unknown/unsupported type '%s'", oi.getCategory().toString())); } } private static Map<PrimitiveCategory, MinorType> TYPE_HIVE2MINOR = new HashMap<>(); static { <#list typesOI.map as entry> <#assign minorType = entry.minorType!entry.type?upper_case> TYPE_HIVE2MINOR.put(PrimitiveCategory.${entry.hiveType}, MinorType.${minorType}); </#list> } public static MinorType getMinorType(ObjectInspector oi) { switch(oi.getCategory()) { case PRIMITIVE: { PrimitiveObjectInspector poi = (PrimitiveObjectInspector)oi; if (TYPE_HIVE2MINOR.containsKey(poi.getPrimitiveCategory())) { return TYPE_HIVE2MINOR.get(poi.getPrimitiveCategory()); } throw new UnsupportedOperationException(); } case MAP: case LIST: case STRUCT: default: throw new UnsupportedOperationException(); } } public static JBlock getObject(JCodeModel m, ObjectInspector oi, JVar returnOI, JVar returnValueHolder, JVar returnValue) { JBlock block = new JBlock(false, false); switch(oi.getCategory()) { case PRIMITIVE: { PrimitiveObjectInspector poi = (PrimitiveObjectInspector)oi; switch(poi.getPrimitiveCategory()) { <#list typesOI.map as entry> case ${entry.hiveType}:{ JConditional jc = block._if(returnValue.eq(JExpr._null())); jc._then().assign(returnValueHolder.ref("isSet"), JExpr.lit(0)); jc._else().assign(returnValueHolder.ref("isSet"), JExpr.lit(1)); JVar castedOI = jc._else().decl( m.directClass(${entry.hiveOI}.class.getCanonicalName()), "castOI", JExpr._null()); jc._else().assign(castedOI, JExpr.cast(m.directClass(${entry.hiveOI}.class.getCanonicalName()), returnOI)); <#if entry.hiveType == "BOOLEAN"> JConditional booleanJC = jc._else()._if(castedOI.invoke("get").arg(returnValue)); booleanJC._then().assign(returnValueHolder.ref("value"), JExpr.lit(1)); booleanJC._else().assign(returnValueHolder.ref("value"), JExpr.lit(0)); <#elseif entry.hiveType == "VARCHAR" || entry.hiveType == "CHAR" || entry.hiveType == "STRING" || entry.hiveType == "BINARY"> <#if entry.hiveType == "VARCHAR"> JVar data = jc._else().decl(m.directClass(byte[].class.getCanonicalName()), "data", castedOI.invoke("getPrimitiveJavaObject").arg(returnValue) .invoke("getValue") .invoke("getBytes")); <#elseif entry.hiveType == "CHAR"> JVar data = jc._else().decl(m.directClass(byte[].class.getCanonicalName()), "data", castedOI.invoke("getPrimitiveJavaObject").arg(returnValue) .invoke("getStrippedValue") .invoke("getBytes")); <#elseif entry.hiveType == "STRING"> JVar data = jc._else().decl(m.directClass(byte[].class.getCanonicalName()), "data", castedOI.invoke("getPrimitiveJavaObject").arg(returnValue) .invoke("getBytes")); <#elseif entry.hiveType == "BINARY"> JVar data = jc._else().decl(m.directClass(byte[].class.getCanonicalName()), "data", castedOI.invoke("getPrimitiveJavaObject").arg(returnValue)); </#if> JConditional jnullif = jc._else()._if(data.eq(JExpr._null())); jnullif._then().assign(returnValueHolder.ref("isSet"), JExpr.lit(0)); jnullif._else().assign(returnValueHolder.ref("buffer"), returnValueHolder.ref("buffer").invoke("reallocIfNeeded").arg(data.ref("length"))); jnullif._else().add(returnValueHolder.ref("buffer") .invoke("setBytes").arg(JExpr.lit(0)).arg(data)); jnullif._else().assign(returnValueHolder.ref("start"), JExpr.lit(0)); jnullif._else().assign(returnValueHolder.ref("end"), data.ref("length")); jnullif._else().add(returnValueHolder.ref("buffer").invoke("setIndex").arg(JExpr.lit(0)).arg(data.ref("length"))); <#elseif entry.hiveType == "TIMESTAMP"> JVar tsVar = jc._else().decl(m.directClass(java.sql.Timestamp.class.getCanonicalName()), "ts", castedOI.invoke("getPrimitiveJavaObject").arg(returnValue)); jc._else().assign(returnValueHolder.ref("value"), tsVar.invoke("getTime")); <#elseif entry.hiveType == "DATE"> JVar dVar = jc._else().decl(m.directClass(java.sql.Date.class.getCanonicalName()), "d", castedOI.invoke("getPrimitiveJavaObject").arg(returnValue)); jc._else().assign(returnValueHolder.ref("value"), dVar.invoke("getTime")); <#else> jc._else().assign(returnValueHolder.ref("value"), castedOI.invoke("get").arg(returnValue)); </#if> return block; } </#list> default: throw new UnsupportedOperationException(String.format("Received unknown/unsupported type '%s'", poi.getPrimitiveCategory().toString())); } } case MAP: case LIST: case STRUCT: default: throw new UnsupportedOperationException(String.format("Received unknown/unsupported type '%s'", oi.getCategory().toString())); } } }
package me.lotabout.codegenerator; import com.intellij.openapi.components.ApplicationComponent; import me.lotabout.codegenerator.ext.Doc; import org.jetbrains.annotations.NotNull; public class CodeGenerator implements ApplicationComponent { public CodeGenerator() { } @Override public void initComponent() {} @Override public void disposeComponent() { } @Override @NotNull public String getComponentName() { return "me.lotabout.codegenerator.CodeGenerator"; } }
/* * ==================================================================== * 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 software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package com.epam.reportportal.apache.http.testserver; import java.io.IOException; import java.io.OutputStream; class LoggingOutputStream extends OutputStream { private final OutputStream out; private final Wire wire; public LoggingOutputStream(final OutputStream out, final Wire wire) { super(); this.out = out; this.wire = wire; } @Override public void write(final int b) throws IOException { wire.output(b); } @Override public void write(final byte[] b) throws IOException { wire.output(b); out.write(b); } @Override public void write(final byte[] b, final int off, final int len) throws IOException { wire.output(b, off, len); out.write(b, off, len); } @Override public void flush() throws IOException { out.flush(); } @Override public void close() throws IOException { out.close(); } }
/* * The Apache License * * Copyright 2009 Marcelo Guimaraes <ataxexe@backpackcloud.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.backpackcloud.trugger.reflection; import java.lang.reflect.AnnotatedType; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; /** * Interface that defines a method reflected with the use of this framework. * * @since 7.0 */ public interface ReflectedMethod extends ReflectedObject<Method> { /** * Invokes the reflected method passing the given args. * * @param args the args to pass * @return the result of the method call */ <E> E invoke(Object... args); /** * @see Method#getTypeParameters() */ TypeVariable<Method>[] getTypeParameters(); /** * @see Method#getReturnType() */ Class<?> getReturnType(); /** * @see Method#getGenericReturnType() */ Type getGenericReturnType(); /** * @see Method#getParameterTypes() */ Class<?>[] getParameterTypes(); /** * @see Method#getParameterCount() */ int getParameterCount(); /** * @see Method#getGenericParameterTypes() */ Type[] getGenericParameterTypes(); /** * @see Method#getExceptionTypes() */ Class<?>[] getExceptionTypes(); /** * @see Method#getGenericExceptionTypes() */ Type[] getGenericExceptionTypes(); /** * @see Method#isBridge() */ boolean isBridge(); /** * @see Method#isVarArgs() */ boolean isVarArgs(); /** * @see Method#isDefault() */ boolean isDefault(); /** * @see Method#getDefaultValue() */ Object getDefaultValue(); /** * @see Method#getParameters() */ Parameter[] getParameters(); /** * @see Method#getAnnotatedReceiverType() */ AnnotatedType getAnnotatedReceiverType(); /** * @see Method#getAnnotatedParameterTypes() */ AnnotatedType[] getAnnotatedParameterTypes(); }
package prefuse.visual.tuple; import prefuse.data.Graph; import prefuse.data.Table; import prefuse.visual.DecoratorItem; import prefuse.visual.VisualItem; import prefuse.visual.VisualTable; /** * DecoratorItem implementation that uses data values from a backing * VisualTable. * * @author <a href="http://jheer.org">jeffrey heer</a> */ public class TableDecoratorItem extends TableVisualItem implements DecoratorItem { /** * Initialize a new TableDecoratorItem for the given table and row. This * method is used by the appropriate TupleManager instance, and should * not be called directly by client code, unless by a client-supplied * custom TupleManager. * * @param table the data Table * @param graph ignored by this class * @param row the table row index */ protected void init(Table table, Graph graph, int row) { m_table = table; m_row = m_table.isValidRow(row) ? row : -1; } /** * @see prefuse.visual.DecoratorItem#getDecoratedItem() */ public VisualItem getDecoratedItem() { VisualTable vt = (VisualTable) getTable(); int prow = vt.getParentRow(getRow()); return (VisualItem) vt.getParentTable().getTuple(prow); } } // end of class TableDecoratorItem
package org.gradle.test.performance.mediummonolithicjavaproject.p77; public class Production1549 { private Production1540 property0; public Production1540 getProperty0() { return property0; } public void setProperty0(Production1540 value) { property0 = value; } private Production1544 property1; public Production1544 getProperty1() { return property1; } public void setProperty1(Production1544 value) { property1 = value; } private Production1548 property2; public Production1548 getProperty2() { return property2; } public void setProperty2(Production1548 value) { property2 = value; } private String property3; public String getProperty3() { return property3; } public void setProperty3(String value) { property3 = value; } private String property4; public String getProperty4() { return property4; } public void setProperty4(String value) { property4 = value; } private String property5; public String getProperty5() { return property5; } public void setProperty5(String value) { property5 = value; } private String property6; public String getProperty6() { return property6; } public void setProperty6(String value) { property6 = value; } private String property7; public String getProperty7() { return property7; } public void setProperty7(String value) { property7 = value; } private String property8; public String getProperty8() { return property8; } public void setProperty8(String value) { property8 = value; } private String property9; public String getProperty9() { return property9; } public void setProperty9(String value) { property9 = value; } }
package scripting.neg.assertNotTitle; import org.junit.Test; import org.junit.After; import com.xceptance.xlt.api.engine.scripting.AbstractWebDriverScriptTestCase; import com.xceptance.xlt.api.webdriver.XltDriver; import scripting.util.PageOpener; /** * */ public class AssertNotTitle_glob_title extends AbstractWebDriverScriptTestCase { /** * Constructor. */ public AssertNotTitle_glob_title() { super(new XltDriver(true), null); } @Test(expected = AssertionError.class) public void test() throws Throwable { PageOpener.examplePage( this ); assertNotTitle( "glob:example page" ); } @After public void after() { getWebDriver().quit(); } }
/* * Adapted from the Wizardry License * * Copyright (c) 2016-2020 larryTheCoder and contributors * * Permission is hereby granted to any persons and/or organizations * using this software to copy, modify, merge, publish, and distribute it. * Said persons and/or organizations are not allowed to use the software or * any derivatives of the work for commercial use or any other means to generate * income, nor are they allowed to claim this software as their own. * * The persons and/or organizations are also disallowed from sub-licensing * and/or trademarking this software without explicit permission from larryTheCoder. * * Any persons and/or organizations using this software must disclose their * source code and have it publicly available, include this license, * provide sufficient credit to the original authors of the project (IE: larryTheCoder), * as well as provide a link to the original project. * * 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 NON INFRINGEMENT. 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.larryTheCoder.utils.json; /** * Kim makes immutable eight bit Unicode strings. If the MSB of a byte is set, then the next byte is a continuation * byte. The last byte of a character never has the MSB reset. Every byte that is not the last byte has the MSB set. Kim * stands for "Keep it minimal". A Unicode character is never longer than 3 bytes. Every byte contributes 7 bits to the * character. ASCII is unmodified. * <p> * Kim UTF-8 one byte U+007F U+007F two bytes U+3FFF U+07FF three bytes U+10FFF U+FFFF four bytes U+10FFFF * <p> * Characters in the ranges U+0800..U+3FFF and U+10000..U+10FFFF will be one byte smaller when encoded in Kim compared * to UTF-8. * <p> * Kim is beneficial when using scripts such as Old South Arabian, Aramaic, Avestan, Balinese, Batak, Bopomofo, * Buginese, Buhid, Carian, Cherokee, Coptic, Cyrillic, Deseret, Egyptian Hieroglyphs, Ethiopic, Georgian, Glagolitic, * Gothic, Hangul Jamo, Hanunoo, Hiragana, Kanbun, Kaithi, Kannada, Katakana, Kharoshthi, Khmer, Lao, Lepcha, Limbu, * Lycian, Lydian, Malayalam, Mandaic, Meroitic, Miao, Mongolian, Myanmar, New Tai Lue, Ol Chiki, Old Turkic, Oriya, * Osmanya, Pahlavi, Parthian, Phags-Pa, Phoenician, Samaritan, Sharada, Sinhala, Sora Sompeng, Tagalog, Tagbanwa, * Takri, Tai Le, Tai Tham, Tamil, Telugu, Thai, Tibetan, Tifinagh, UCAS. * <p> * A kim object can be constructed from an ordinary UTF-16 string, or from a byte array. A kim object can produce a * UTF-16 string. * <p> * As with UTF-8, it is possible to detect character boundaries within a byte sequence. UTF-8 is one of the world's * great inventions. While Kim is more efficient, it is not clear that it is worth the expense of transition. * * @version 2013-04-18 */ class Kim { /** * The number of bytes in the kim. The number of bytes can be as much as three times the number of characters. */ private int length = 0; /** * The byte array containing the kim's content. */ private byte[] bytes = null; /** * The kim's hashcode, conforming to Java's hashcode conventions. */ private int hashcode = 0; /** * The memoization of toString(). */ private String string = null; /** * Make a kim from a portion of a byte array. * * @param bytes A byte array. * @param from The index of the first byte. * @param thru The index of the last byte plus one. */ private Kim(final byte[] bytes, final int from, final int thru) { // As the bytes are copied into the new kim, a hashcode is computed // using a // modified Fletcher code. int sum = 1; int value; hashcode = 0; length = thru - from; if (length > 0) { this.bytes = new byte[length]; for (int at = 0; at < length; at += 1) { value = bytes[at + from] & 0xFF; sum += value; hashcode += sum; this.bytes[at] = (byte) value; } hashcode += sum << 16; } } /** * Make a kim from a byte array. * * @param bytes The byte array. * @param length The number of bytes. */ public Kim(final byte[] bytes, final int length) { this(bytes, 0, length); } /** * Make a new kim from a substring of an existing kim. The coordinates are in byte units, not character units. * * @param kim The source of bytes. * @param from The point at which to take bytes. * @param thru The point at which to stop taking bytes. */ public Kim(final Kim kim, final int from, final int thru) { this(kim.bytes, from, thru); } /** * Make a kim from a string. * * @param string The string. * @throws JSONException if surrogate pair mismatch. */ public Kim(final String string) throws JSONException { final int stringLength = string.length(); hashcode = 0; length = 0; // First pass: Determine the length of the kim, allowing for the UTF-16 // to UTF-32 conversion, and then the UTF-32 to Kim conversion. if (stringLength > 0) { for (int i = 0; i < stringLength; i += 1) { final int c = string.charAt(i); if (c <= 0x7F) { length += 1; } else if (c <= 0x3FFF) { length += 2; } else { if ((c >= 0xD800) && (c <= 0xDFFF)) { i += 1; final int d = string.charAt(i); if ((c > 0xDBFF) || (d < 0xDC00) || (d > 0xDFFF)) { throw new JSONException("Bad UTF16"); } } length += 3; } } // Second pass: Allocate a byte array and fill that array with the // conversion // while computing the hashcode. bytes = new byte[length]; int at = 0; int b; int sum = 1; for (int i = 0; i < stringLength; i += 1) { int character = string.charAt(i); if (character <= 0x7F) { bytes[at] = (byte) character; sum += character; hashcode += sum; at += 1; } else if (character <= 0x3FFF) { b = 0x80 | (character >>> 7); bytes[at] = (byte) b; sum += b; hashcode += sum; at += 1; b = character & 0x7F; bytes[at] = (byte) b; sum += b; hashcode += sum; at += 1; } else { if ((character >= 0xD800) && (character <= 0xDBFF)) { i += 1; character = (((character & 0x3FF) << 10) | (string.charAt(i) & 0x3FF)) + 65536; } b = 0x80 | (character >>> 14); bytes[at] = (byte) b; sum += b; hashcode += sum; at += 1; b = 0x80 | ((character >>> 7) & 0xFF); bytes[at] = (byte) b; sum += b; hashcode += sum; at += 1; b = character & 0x7F; bytes[at] = (byte) b; sum += b; hashcode += sum; at += 1; } } hashcode += sum << 16; } } /** * Returns the number of bytes needed to contain the character in Kim format. * * @param character a Unicode character between 0 and 0x10FFFF. * @return 1, 2, or 3 * @throws JSONException if the character is not representable in a kim. */ private static int characterSize(final int character) throws JSONException { if ((character < 0) || (character > 0x10FFFF)) { throw new JSONException("Bad character " + character); } return character <= 0x7F ? 1 : character <= 0x3FFF ? 2 : 3; } /** * Returns the character at the specified index. The index refers to byte values and ranges from 0 to length - 1. * The index of the next character is at index + Kim.characterSize(kim.characterAt(index)). * * @param at the index of the char value. The first character is at 0. * @return a Unicode character between 0 and 0x10FFFF. * @throws JSONException if at does not point to a valid character. */ private int characterAt(final int at) throws JSONException { final int c = get(at); if ((c & 0x80) == 0) { return c; } int character; final int c1 = get(at + 1); if ((c1 & 0x80) == 0) { character = ((c & 0x7F) << 7) | c1; if (character > 0x7F) { return character; } } else { final int c2 = get(at + 2); character = ((c & 0x7F) << 14) | ((c1 & 0x7F) << 7) | c2; if (((c2 & 0x80) == 0) && (character > 0x3FFF) && (character <= 0x10FFFF) && ((character < 0xD800) || (character > 0xDFFF))) { return character; } } throw new JSONException("Bad character at " + at); } /** * Copy the contents of this kim to a byte array. * * @param bytes A byte array of sufficient size. * @param at The position within the byte array to take the byes. * @return The position immediately after the copy. */ public int copy(final byte[] bytes, final int at) { System.arraycopy(this.bytes, 0, bytes, at, length); return at + length; } /** * Two kim objects containing exactly the same bytes in the same order are equal to each other. * * @param obj the other kim with which to compare. * @return true if this and obj are both kim objects containing identical byte sequences. */ @Override public boolean equals(final Object obj) { if (!(obj instanceof Kim)) { return false; } final Kim that = (Kim) obj; if (this == that) { return true; } if (hashcode != that.hashcode) { return false; } return java.util.Arrays.equals(bytes, that.bytes); } /** * Get a byte from a kim. * * @param at The position of the byte. The first byte is at 0. * @return The byte. * @throws JSONException if there is no byte at that position. */ private int get(final int at) throws JSONException { if ((at < 0) || (at > length)) { throw new JSONException("Bad character at " + at); } return (bytes[at]) & 0xFF; } /** * Returns a hash code value for the kim. */ @Override public int hashCode() { return hashcode; } /** * Produce a UTF-16 String from this kim. The number of codepoints in the string will not be greater than the number * of bytes in the kim, although it could be less. * * @return The string. A kim memoizes its string representation. * @throws JSONException if the kim is not valid. */ @Override public String toString() throws JSONException { if (string == null) { int c; int length = 0; final char chars[] = new char[this.length]; for (int at = 0; at < this.length; at += characterSize(c)) { c = characterAt(at); if (c < 0x10000) { chars[length] = (char) c; length += 1; } else { chars[length] = (char) (0xD800 | ((c - 0x10000) >>> 10)); length += 1; chars[length] = (char) (0xDC00 | (c & 0x03FF)); length += 1; } } string = new String(chars, 0, length); } return string; } }
package com.github.shuaidd.dto.message; import com.fasterxml.jackson.annotation.JsonProperty; /** * 描述 * * @author ddshuai * date 2021-01-02 15:24 **/ public class MiniProgram { @JsonProperty("appid") private String appId; private String page; private String title; @JsonProperty("pic_media_id") private String picMediaId; public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getPage() { return page; } public void setPage(String page) { this.page = page; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getPicMediaId() { return picMediaId; } public void setPicMediaId(String picMediaId) { this.picMediaId = picMediaId; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.data.pipeline.opengauss.prepare.datasource; import lombok.extern.slf4j.Slf4j; import org.apache.shardingsphere.data.pipeline.api.datanode.JobDataNodeEntry; import org.apache.shardingsphere.data.pipeline.api.datasource.PipelineDataSourceWrapper; import org.apache.shardingsphere.data.pipeline.api.datasource.config.PipelineDataSourceConfigurationFactory; import org.apache.shardingsphere.data.pipeline.api.datasource.config.impl.ShardingSpherePipelineDataSourceConfiguration; import org.apache.shardingsphere.data.pipeline.api.prepare.datasource.ActualTableDefinition; import org.apache.shardingsphere.data.pipeline.api.prepare.datasource.TableDefinitionSQLType; import org.apache.shardingsphere.data.pipeline.core.datasource.PipelineDataSourceManager; import org.apache.shardingsphere.data.pipeline.core.exception.PipelineJobPrepareFailedException; import org.apache.shardingsphere.data.pipeline.core.prepare.datasource.AbstractDataSourcePreparer; import org.apache.shardingsphere.data.pipeline.core.prepare.datasource.PrepareTargetTablesParameter; import org.apache.shardingsphere.infra.datanode.DataNode; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; /** * Data source preparer for openGauss. */ @Slf4j public final class OpenGaussDataSourcePreparer extends AbstractDataSourcePreparer { private static final String WITH_OF_TABLE_EXTEND = "with ("; @Override public void prepareTargetTables(final PrepareTargetTablesParameter parameter) { Collection<ActualTableDefinition> actualTableDefinitions; try { actualTableDefinitions = getActualTableDefinitions(parameter); } catch (final SQLException ex) { throw new PipelineJobPrepareFailedException("get table definitions failed.", ex); } Map<String, Collection<String>> createLogicTableSQLs = getCreateLogicTableSQLs(actualTableDefinitions); try (Connection targetConnection = getTargetCachedDataSource(parameter.getPipelineConfiguration(), parameter.getDataSourceManager()).getConnection()) { for (Entry<String, Collection<String>> entry : createLogicTableSQLs.entrySet()) { for (String each : entry.getValue()) { executeTargetTableSQL(targetConnection, each); } log.info("create target table '{}' success", entry.getKey()); } } catch (final SQLException ex) { throw new PipelineJobPrepareFailedException("prepare target tables failed.", ex); } } private Collection<ActualTableDefinition> getActualTableDefinitions(final PrepareTargetTablesParameter parameter) throws SQLException { Collection<ActualTableDefinition> result = new ArrayList<>(); ShardingSpherePipelineDataSourceConfiguration sourceDataSourceConfig = (ShardingSpherePipelineDataSourceConfiguration) PipelineDataSourceConfigurationFactory.newInstance( parameter.getPipelineConfiguration().getSource().getType(), parameter.getPipelineConfiguration().getSource().getParameter()); // TODO reuse PipelineDataSourceManager try (PipelineDataSourceManager dataSourceManager = new PipelineDataSourceManager()) { for (JobDataNodeEntry each : parameter.getTablesFirstDataNodes().getEntries()) { DataNode dataNode = each.getDataNodes().get(0); // Keep dataSource to reuse PipelineDataSourceWrapper dataSource = dataSourceManager.getDataSource(sourceDataSourceConfig.getActualDataSourceConfig(dataNode.getDataSourceName())); try (Connection sourceConnection = dataSource.getConnection()) { String actualTableName = dataNode.getTableName(); int oid = queryTableOid(sourceConnection, actualTableName); String tableDefinition = queryTableDefinition(sourceConnection, oid); String logicTableName = each.getLogicTableName(); result.add(new ActualTableDefinition(logicTableName, actualTableName, tableDefinition)); } } } return result; } private int queryTableOid(final Connection sourceConnection, final String actualTableName) throws SQLException { String sql = "SELECT oid FROM pg_class WHERE relname = ?"; try (PreparedStatement statement = sourceConnection.prepareStatement(sql)) { statement.setString(1, actualTableName); try (ResultSet resultSet = statement.executeQuery()) { if (!resultSet.next()) { throw new PipelineJobPrepareFailedException("select oid has no result, sql: " + sql + ", actualTableName: " + actualTableName); } return resultSet.getInt(1); } } } private String queryTableDefinition(final Connection sourceConnection, final int oid) throws SQLException { String sql = String.format("SELECT * FROM pg_get_tabledef(%d)", oid); try (Statement statement = sourceConnection.createStatement(); ResultSet resultSet = statement.executeQuery(sql)) { if (!resultSet.next()) { throw new PipelineJobPrepareFailedException("table definition has no result, sql: " + sql); } return resultSet.getString(1); } } /** * Get create logic table SQLs. * * @param actualTableDefinitions actual table definitions. key is logic table name, value is actual table definition. * @return all SQLs. key is logic table name, value is collection of logic table SQLs. */ private Map<String, Collection<String>> getCreateLogicTableSQLs(final Collection<ActualTableDefinition> actualTableDefinitions) { Map<String, Collection<String>> result = new HashMap<>(); for (ActualTableDefinition each : actualTableDefinitions) { Collection<String> logicTableSQLs = splitTableDefinitionToSQLs(each).stream().map(sql -> { TableDefinitionSQLType sqlType = getTableDefinitionSQLType(sql); switch (sqlType) { //TODO replace constraint and index name case CREATE_TABLE: sql = addIfNotExistsForCreateTableSQL(sql); sql = replaceActualTableNameToLogicTableName(sql, each.getActualTableName(), each.getLogicTableName()); sql = skipCreateTableExtendSet(sql); return sql; case ALTER_TABLE: sql = replaceActualTableNameToLogicTableName(sql, each.getActualTableName(), each.getLogicTableName()); return sql; default: return ""; } }).filter(sql -> !"".equals(sql)).collect(Collectors.toList()); result.put(each.getLogicTableName(), logicTableSQLs); } return result; } @Override protected String replaceActualTableNameToLogicTableName(final String createOrAlterTableSQL, final String actualTableName, final String logicTableName) { StringBuilder logicalTableSQL = new StringBuilder(createOrAlterTableSQL); while (true) { int start = logicalTableSQL.indexOf(actualTableName); if (start <= 0) { return logicalTableSQL.toString(); } int end = start + actualTableName.length(); logicalTableSQL.replace(start, end, logicTableName); } } private String skipCreateTableExtendSet(final String createSQL) { String lowerCreateSQL = createSQL.toLowerCase(); String[] search = {WITH_OF_TABLE_EXTEND, ")"}; List<Integer> searchPos = new ArrayList<>(2); int startPos = 0; for (String each : search) { int curSearch = lowerCreateSQL.indexOf(each, startPos); if (curSearch <= 0) { break; } searchPos.add(curSearch); startPos = curSearch; } if (searchPos.size() != search.length) { return createSQL; } return createSQL.substring(0, searchPos.get(0)) + createSQL.substring(searchPos.get(1) + 1); } }
/* * ==================================================================== * 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 software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package ch.boye.httpclientandroidlib.client.methods; import java.net.URI; import ch.boye.httpclientandroidlib.annotation.NotThreadSafe; /** * HTTP POST method. * <p> * The HTTP POST method is defined in section 9.5 of * <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>: * <blockquote> * The POST method is used to request that the origin server accept the entity * enclosed in the request as a new subordinate of the resource identified by * the Request-URI in the Request-Line. POST is designed to allow a uniform * method to cover the following functions: * <ul> * <li>Annotation of existing resources</li> * <li>Posting a message to a bulletin board, newsgroup, mailing list, or * similar group of articles</li> * <li>Providing a block of data, such as the result of submitting a form, * to a data-handling process</li> * <li>Extending a database through an append operation</li> * </ul> * </blockquote> * </p> * * @since 4.0 */ @NotThreadSafe public class HttpPost extends HttpEntityEnclosingRequestBase { public final static String METHOD_NAME = "POST"; public HttpPost() { super(); } public HttpPost(final URI uri) { super(); setURI(uri); } /** * @throws IllegalArgumentException if the uri is invalid. */ public HttpPost(final String uri) { super(); setURI(URI.create(uri)); } @Override public String getMethod() { return METHOD_NAME; } }
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.data.processor.data.entity; import static org.spongepowered.common.data.util.DataUtil.getData; import com.google.common.collect.ImmutableMap; import net.minecraft.entity.Entity; import org.spongepowered.api.data.DataContainer; import org.spongepowered.api.data.DataHolder; import org.spongepowered.api.data.DataTransactionBuilder; import org.spongepowered.api.data.DataTransactionResult; import org.spongepowered.api.data.key.Key; import org.spongepowered.api.data.key.Keys; import org.spongepowered.api.data.manipulator.immutable.entity.ImmutableIgniteableData; import org.spongepowered.api.data.manipulator.mutable.entity.IgniteableData; import org.spongepowered.common.data.manipulator.mutable.entity.SpongeIgniteableData; import org.spongepowered.common.data.processor.common.AbstractEntityDataProcessor; import java.util.Map; import java.util.Optional; public class IgniteableDataProcessor extends AbstractEntityDataProcessor<Entity, IgniteableData, ImmutableIgniteableData> { public IgniteableDataProcessor() { super(Entity.class); } @Override public Optional<IgniteableData> fill(DataContainer container, IgniteableData igniteableData) { igniteableData.set(Keys.FIRE_TICKS, getData(container, Keys.FIRE_TICKS)); igniteableData.set(Keys.FIRE_DAMAGE_DELAY, getData(container, Keys.FIRE_DAMAGE_DELAY)); return Optional.of(igniteableData); } @Override public DataTransactionResult remove(DataHolder dataHolder) { if (dataHolder instanceof Entity) { if (((Entity) dataHolder).fire > 0) { final DataTransactionBuilder builder = DataTransactionBuilder.builder(); builder.replace(from(dataHolder).get().getValues()); ((Entity) dataHolder).extinguish(); return builder.result(DataTransactionResult.Type.SUCCESS).build(); } } return DataTransactionBuilder.failNoData(); } @Override protected IgniteableData createManipulator() { return new SpongeIgniteableData(); } @Override protected boolean doesDataExist(Entity entity) { return entity.fire > 0; } @Override protected boolean set(Entity entity, Map<Key<?>, Object> keyValues) { entity.fire = (Integer) keyValues.get(Keys.FIRE_TICKS); entity.fireResistance = (Integer) keyValues.get(Keys.FIRE_DAMAGE_DELAY); return true; } @Override protected Map<Key<?>, ?> getValues(Entity entity) { final int fireTicks = entity.fire; final int fireDamageDelay = entity.fireResistance; return ImmutableMap.<Key<?>, Object>of(Keys.FIRE_TICKS, fireTicks, Keys.FIRE_DAMAGE_DELAY, fireDamageDelay); } }
/**************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * ****************************************************************/ package org.apache.james.modules.server; import org.apache.james.lifecycle.api.Startable; import org.apache.james.metrics.api.GaugeRegistry; import org.apache.james.metrics.api.MetricFactory; import org.apache.james.metrics.dropwizard.DropWizardGaugeRegistry; import org.apache.james.metrics.dropwizard.DropWizardJVMMetrics; import org.apache.james.metrics.dropwizard.DropWizardMetricFactory; import org.apache.james.utils.InitialisationOperation; import com.codahale.metrics.MetricRegistry; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Scopes; import com.google.inject.Singleton; import com.google.inject.multibindings.Multibinder; public class DropWizardMetricsModule extends AbstractModule { @Override protected void configure() { bind(MetricRegistry.class).in(Scopes.SINGLETON); bind(DropWizardMetricFactory.class).in(Scopes.SINGLETON); bind(DropWizardGaugeRegistry.class).in(Scopes.SINGLETON); bind(DropWizardJVMMetrics.class).in(Scopes.SINGLETON); bind(MetricFactory.class).to(DropWizardMetricFactory.class); bind(GaugeRegistry.class).to(DropWizardGaugeRegistry.class); Multibinder.newSetBinder(binder(), InitialisationOperation.class).addBinding().to(DropWizardInitialisationOperation.class); } @Singleton public static class DropWizardInitialisationOperation implements InitialisationOperation, Startable { private final DropWizardMetricFactory dropWizardMetricFactory; private final DropWizardJVMMetrics dropWizardJVMMetrics; @Inject public DropWizardInitialisationOperation(DropWizardMetricFactory dropWizardMetricFactory, DropWizardJVMMetrics dropWizardJVMMetrics) { this.dropWizardMetricFactory = dropWizardMetricFactory; this.dropWizardJVMMetrics = dropWizardJVMMetrics; } @Override public void initModule() { dropWizardMetricFactory.start(); dropWizardJVMMetrics.start(); } @Override public Class<? extends Startable> forClass() { return DropWizardInitialisationOperation.class; } } }
package es.upm.miw.apaw_ep_javier_iglesias.exceptions; public class NotFoundException extends RuntimeException { private static final String DESCRIPTION = "Not Found Exception (404)"; public NotFoundException(String detail) { super(DESCRIPTION + ". " + detail); } }
/* $This file is distributed under the terms of the license in LICENSE$ */ package edu.cornell.mannlib.vitro.webapp.tboxreasoner; import java.util.List; import org.apache.jena.ontology.DatatypeProperty; import org.apache.jena.ontology.ObjectProperty; import org.apache.jena.ontology.Restriction; import org.apache.jena.rdf.model.Statement; /** * The functionality of a TBox reasoner. * * The reasoner will maintain its own TBox model. It will receive updates to * that model and perform reasoning on it. It will answer queries about the * contents of the model, when reasoning is complete. */ public interface TBoxReasoner { /** * Add the additions and remove the removals. */ void updateReasonerModel(TBoxChanges changes); /** * Chew on it and create the inferences. Report status. */ Status performReasoning(); /** * List all of the ObjectProperties from the reasoner model, after updating * and reasoning. */ List<ObjectProperty> listObjectProperties(); /** * List all of the DatatypeProperties from the reasoner model, after * updating and reasoning. */ List<DatatypeProperty> listDatatypeProperties(); /** * List all of the restrictions in the reasoner model, after updating and * reasoning. */ List<Restriction> listRestrictions(); /** * List all of the statements that satisfy any of these patterns, after * updating and reasoning. */ List<Statement> filterResults(List<ReasonerStatementPattern> patternList); public static class Status { public static final Status SUCCESS = new Status(true, false, ""); public static final Status ERROR = new Status(true, true, ""); public static final Status inconsistent(String explanation) { return new Status(false, false, explanation); } private final boolean consistent; private final boolean inErrorState; private final String explanation; private Status(boolean consistent, boolean inErrorState, String explanation) { this.consistent = consistent; this.inErrorState = inErrorState; this.explanation = explanation; } public boolean isConsistent() { return consistent; } public boolean isInErrorState() { return inErrorState; } public String getExplanation() { return explanation; } } }
/******************************************************************************* * Copyright 2014 United States Government as represented by the * Administrator of the National Aeronautics and Space Administration. * 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 gov.nasa.arc.spife.core.plan.editor.timeline.parts; import gov.nasa.arc.spife.core.plan.editor.timeline.PlanTimelineConstants; import gov.nasa.arc.spife.core.plan.editor.timeline.policies.PlanElementHeaderLayoutEditPolicy; import gov.nasa.arc.spife.ui.timeline.part.TreeTimelineHeaderEditPart; import gov.nasa.ensemble.core.model.plan.EPlan; import gov.nasa.ensemble.emf.util.EMFUtils; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.gef.EditPolicy; public class PlanTimelineHeaderEditPart extends TreeTimelineHeaderEditPart<EPlan> implements PlanTimelineConstants { private AdapterFactory adapterFactory = null; public PlanTimelineHeaderEditPart() { super(); } @SuppressWarnings("unchecked") public <A> A adapt(Class<A> type) { return (A) getAdapter(type); } @Override public Object getAdapter(Class type) { AdapterFactory adapterFactory = getAdapterFactory(); Object result = adapterFactory == null ? null : adapterFactory.adapt(getModel(), type); if (result == null) { result = super.getAdapter(type); } return result; } public AdapterFactory getAdapterFactory() { if (adapterFactory == null) { adapterFactory = EMFUtils.getAdapterFactory(getModel()); } return adapterFactory; } @Override protected void createEditPolicies() { super.createEditPolicies(); installEditPolicy(EditPolicy.LAYOUT_ROLE, new PlanElementHeaderLayoutEditPolicy()); } }
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.navigation.actions; import com.google.common.annotations.VisibleForTesting; import com.intellij.codeInsight.CodeInsightActionHandler; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.TargetElementUtil; import com.intellij.codeInsight.actions.BaseCodeInsightAction; import com.intellij.codeInsight.navigation.NavigationUtil; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.util.PsiUtilCore; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Set; public class GotoTypeDeclarationAction extends BaseCodeInsightAction implements CodeInsightActionHandler, DumbAware { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.navigation.actions.GotoTypeDeclarationAction"); @NotNull @Override protected CodeInsightActionHandler getHandler(){ return this; } @Override protected boolean isValidForLookup() { return true; } @Override public void update(@NotNull final AnActionEvent event) { if (TypeDeclarationProvider.EP_NAME.getExtensionList().size() == 0) { event.getPresentation().setVisible(false); return; } for (TypeDeclarationProvider provider : TypeDeclarationProvider.EP_NAME.getExtensionList()) { //noinspection Duplicates try { String text = provider.getActionText(event.getDataContext()); if (text != null) { Presentation presentation = event.getPresentation(); presentation.setText(text); break; } } catch (AbstractMethodError e) { LOG.error(provider.toString(), e); } } super.update(event); } @Override public void invoke(@NotNull final Project project, @NotNull Editor editor, @NotNull PsiFile file) { DumbService.getInstance(project).setAlternativeResolveEnabled(true); try { int offset = editor.getCaretModel().getOffset(); PsiElement[] symbolTypes = GotoDeclarationAction.underModalProgress(project, "Resolving Reference...", () -> findSymbolTypes(editor, offset)); if (symbolTypes == null || symbolTypes.length == 0) return; if (symbolTypes.length == 1) { navigate(project, symbolTypes[0]); } else { NavigationUtil.getPsiElementPopup(symbolTypes, CodeInsightBundle.message("choose.type.popup.title")).showInBestPositionFor(editor); } } catch (IndexNotReadyException e) { DumbService.getInstance(project).showDumbModeNotification("Navigation is not available here during index update"); } finally { DumbService.getInstance(project).setAlternativeResolveEnabled(false); } } private static void navigate(@NotNull Project project, @NotNull PsiElement symbolType) { PsiElement element = symbolType.getNavigationElement(); assert element != null : "SymbolType :"+symbolType+"; file: "+symbolType.getContainingFile(); VirtualFile file = element.getContainingFile().getVirtualFile(); if (file != null) { OpenFileDescriptor descriptor = new OpenFileDescriptor(project, file, element.getTextOffset()); FileEditorManager.getInstance(project).openTextEditor(descriptor, true); } } @Override public boolean startInWriteAction() { return false; } @Nullable public static PsiElement findSymbolType(@NotNull Editor editor, int offset) { final PsiElement[] psiElements = findSymbolTypes(editor, offset); if (psiElements != null && psiElements.length > 0) return psiElements[0]; return null; } @Nullable @VisibleForTesting public static PsiElement[] findSymbolTypes(@NotNull Editor editor, int offset) { PsiElement targetElement = TargetElementUtil.getInstance().findTargetElement(editor, TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED | TargetElementUtil.ELEMENT_NAME_ACCEPTED | TargetElementUtil.LOOKUP_ITEM_ACCEPTED, offset); if (targetElement != null) { final PsiElement[] symbolType = getSymbolTypeDeclarations(targetElement, editor, offset); return symbolType == null ? PsiElement.EMPTY_ARRAY : symbolType; } final PsiReference psiReference = TargetElementUtil.findReference(editor, offset); if (psiReference instanceof PsiPolyVariantReference) { final ResolveResult[] results = ((PsiPolyVariantReference)psiReference).multiResolve(false); Set<PsiElement> types = new THashSet<>(); for(ResolveResult r: results) { PsiElement element = r.getElement(); if (element == null) continue; final PsiElement[] declarations = getSymbolTypeDeclarations(element, editor, offset); if (declarations != null) { for (PsiElement declaration : declarations) { assert declaration != null; types.add(declaration); } } } if (!types.isEmpty()) return PsiUtilCore.toPsiElementArray(types); } return null; } @Nullable private static PsiElement[] getSymbolTypeDeclarations(@NotNull PsiElement targetElement, Editor editor, int offset) { for(TypeDeclarationProvider provider: TypeDeclarationProvider.EP_NAME.getExtensionList()) { PsiElement[] result; if (provider instanceof TypeDeclarationPlaceAwareProvider) { result = ((TypeDeclarationPlaceAwareProvider)provider).getSymbolTypeDeclarations(targetElement, editor, offset); } else { result = provider.getSymbolTypeDeclarations(targetElement); } if (result != null) return result; } return null; } }
package com.lufax.jijin.daixiao.dto; import com.lufax.jijin.base.dto.BaseDTO; import java.math.BigDecimal; import java.util.Date; public class JijinExManagerDTO extends BaseDTO { private String fundCode; //基金代码 private String manager;//基金经理 private String resume;// 基金经理简介 private Long batchId; //批次号 private String createdBy; private Date createdAt; private String updatedBy; private Date updatedAt; private String status; private String errorMsg; private Integer isValid; private String managerId; //基金经理ID private String pubDate; //公告日期 private String gender; //性别 private String education; //学历 private String appointDate; //任职日期 public String getManagerId() { return managerId; } public void setManagerId(String managerId) { this.managerId = managerId; } public String getPubDate() { return pubDate; } public void setPubDate(String pubDate) { this.pubDate = pubDate; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getEducation() { return education; } public void setEducation(String education) { this.education = education; } public String getAppointDate() { return appointDate; } public void setAppointDate(String appointDate) { this.appointDate = appointDate; } public String getFundCode() { return fundCode; } public void setFundCode(String fundCode) { this.fundCode = fundCode; } public String getManager() { return manager; } public void setManager(String manager) { this.manager = manager; } public String getResume() { return resume; } public void setResume(String resume) { this.resume = resume; } public Long getBatchId() { return batchId; } public void setBatchId(Long batchId) { this.batchId = batchId; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public String getUpdatedBy() { return updatedBy; } public void setUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; } public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getErrorMsg() { return errorMsg; } public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } public Integer getIsValid() { return isValid; } public void setIsValid(Integer isValid) { this.isValid = isValid; } }
package shibauth.jira.authentication.shibboleth; import java.util.Date; import com.atlassian.core.util.Clock; public class AuthClock implements com.atlassian.core.util.Clock { public Date getCurrentDate() { return new Date(); } }
package org.swtk.commons.dict.wiktionary.generated.a.l.o; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.swtk.common.dict.dto.wiktionary.Entry; import com.trimc.blogger.commons.utils.GsonUtils; public class WiktionaryALO000 { private static Map<String, Entry> map = new HashMap<String, Entry>(); static { add("aloe", "{\"term\":\"aloe\", \"etymology\":{\"influencers\":[], \"languages\":[\"old english (ca. 450-1100)\", \"English\", \"ancient greek (to 1453)\", \"Hebrew\", \"Latin\"], \"text\":\"From Old english (ca. 450-1100) \u0027alwe\u0027 (fragrant resin of an east indian tree) from Latin {{m|la|aloē}}, from Ancient greek (to 1453) \u0027ἀλόη\u0027 (aloes) from Hebrew \u0027אֲהָלִים\u0027 ultimately from a language; reinforced in Middle English by Old French \u0027aloes\u0027\"}, \"definitions\":{\"list\":[{\"upperType\":\"NOUN\", \"text\":\"The resins of the trees and , known for their fragrant aroma\", \"priority\":1},{\"upperType\":\"NOUN\", \"text\":\"A plant of the genus \u0027Aloe\", \"priority\":2},{\"upperType\":\"NOUN\", \"text\":\"A strong, bitter drink made from the juice of such plants, used as a purgative\", \"priority\":3}]}, \"synonyms\":{}}"); add("aloo", "{\"term\":\"aloo\", \"etymology\":{\"influencers\":[], \"languages\":[\"English\", \"Hindi\", \"Sanskrit\", \"Urdu\"], \"text\":\"From Hindi \u0027आलू\u0027 / Urdu \u0027الو\u0027 from Sanskrit \u0027आलू\u0027 said to mean the edible root of a variety of {{taxlink|Amorphophallus paeoniifolius|species|noshow\u003d1}}.\"}, \"definitions\":{\"list\":[{\"upperType\":\"NOUN\", \"text\":\"potato\", \"priority\":1}]}, \"synonyms\":{}}"); add("alot", "{\"term\":\"alot\", \"etymology\":{\"influencers\":[], \"languages\":[], \"text\":\"From Proto-north sarawak {{m|poz-swa-pro|*alud}}.\"}, \"definitions\":{\"list\":[{\"upperType\":\"NOUN\", \"text\":\"2000\u0027\u0027, \u0027Teaching Secondary English,\u0027 ed. Daniel Sheridan. [in a tenth-grade student\u0027s paper\", \"priority\":1},{\"upperType\":\"NOUN\", \"text\":\"There was \u0027\u0027alot\u0027\u0027 of sex discrimination in the 60’s. For one thing there was no sports for girls and in \u0027\u0027alot\u0027\u0027 of schools the female teachers were not allowed to get married or they could be fired. [http://print.google.com/print?id\u003dejtdcf-taQkC\u0026amp;pg\u003dPA346\u0026amp;lpg\u003dPA346\u0026amp;sig\u003dt0Sp87KqxsH-UGYklzl72NMUz1Q\", \"priority\":2},{\"upperType\":\"NOUN\", \"text\":\"2003\u0027\u0027, Matt Janacone, \u0027Three by the Sea\u0027 [http://print.google.com/print?id\u003dCesAE2xl68QC\u0026amp;pg\u003dPA107\u0026amp;lpg\u003dPA107\u0026amp;sig\u003dX8TjIfaBBBesXWW1E38K-BUtUPU\", \"priority\":3},{\"upperType\":\"NOUN\", \"text\":\"It was \u0027\u0027alot\u0027\u0027 of lumber, \u0027\u0027alot\u0027\u0027 of condos, and Joe did not know \u0027\u0027alot\u0027\u0027 about either of them, only that it was \u0027\u0027alot\u0027\u0027 of money; he hated to throw his money into something he did not know \u0027\u0027alot\u0027\u0027 about\", \"priority\":4},{\"upperType\":\"NOUN\", \"text\":\"2005\u0027\u0027, Aphrodite Jones, \u0027Cruel Sacrifice\u0027 [From the suicidal patient\u0027s own writing.] [http://print.google.com/print?id\u003dKtlMQCtBzygC\u0026amp;pg\u003dPA248\u0026amp;lpg\u003dPA248\u0026amp;sig\u003d2mA_bCMZr0l0dCLfhRWe4cBdmd4\", \"priority\":5},{\"upperType\":\"NOUN\", \"text\":\"She talked about death: “My philosophy on life is it could be \u0027\u0027alot\u0027\u0027 better. Like I would’ve never gotten into this mess if I wouldn’t have tried to commit suicide. Actually I was just trying to make myself sick. But then again it could be \u0027\u0027\u0027alot\u0027\u0027\u0027 worse! [...]”\", \"priority\":6}]}, \"synonyms\":{}}"); add("alocasia", "{\"term\":\"alocasia\", \"etymology\":{\"influencers\":[], \"languages\":[], \"text\":\"{{rfe|lang\u003den}}\"}, \"definitions\":{\"list\":[{\"upperType\":\"NOUN\", \"text\":\"Any of several tropical Asian plants, of the genus \u0027Alocasia\u0027, having heart- or arrowhead-shaped leaves\", \"priority\":1}]}, \"synonyms\":{}}"); add("aloesin", "{\"term\":\"aloesin\", \"etymology\":{\"influencers\":[], \"languages\":[], \"text\":\"{{suffix|aloes|in|lang\u003den}}?\"}, \"definitions\":{\"list\":[{\"upperType\":\"NOUN\", \"text\":\"A derivative of aloe vera\", \"priority\":1}]}, \"synonyms\":{}}"); add("alogia", "{\"term\":\"alogia\", \"etymology\":{\"influencers\":[], \"languages\":[\"English\", \"ancient greek (to 1453)\"], \"text\":\"From Ancient greek (to 1453) \u0027ἀλογία\u0027 (absurdity; confusion; irrationality; speechlessness)\"}, \"definitions\":{\"list\":[{\"upperType\":\"NOUN\", \"text\":\"A general lack of additional, unprompted content in normal speech, a common symptom of schizophrenia\", \"priority\":1}]}, \"synonyms\":{}}"); add("aloin", "{\"term\":\"aloin\", \"etymology\":{\"influencers\":[], \"languages\":[], \"text\":\"{{suffix|aloe|in|lang\u003den}}\"}, \"definitions\":{\"list\":[{\"upperType\":\"NOUN\", \"text\":\"A glycoside derivative of anthracene, found in aloe, that is used as a laxative\", \"priority\":1}]}, \"synonyms\":{}}"); add("aloneness", "{\"term\":\"aloneness\", \"etymology\":{\"influencers\":[], \"languages\":[], \"text\":\"{{suffix|alone|ness|lang\u003den}}\"}, \"definitions\":{\"list\":[{\"upperType\":\"NOUN\", \"text\":\"The state of being alone; solitude, isolation\", \"priority\":1}]}, \"synonyms\":{}}"); add("alopecia", "{\"term\":\"alopecia\", \"etymology\":{\"influencers\":[], \"languages\":[\"English\", \"ancient greek (to 1453)\", \"Latin\"], \"text\":\"Latin \u0027alopecia\u0027 from the Ancient greek (to 1453) \u0027ἀλωπεκία\u0027 (fox-mange) from \u0027ἀλώπηξ\u0027 (fox) + \u0027-ia\u0027, (a formative ending used in Ancient Greek, especially used in naming diseases)\"}, \"definitions\":{\"list\":[{\"upperType\":\"NOUN\", \"text\":\"Baldness\", \"priority\":1},{\"upperType\":\"NOUN\", \"text\":\"Deficiency of the hair, which may be caused by failure to grow or loss after growth\", \"priority\":2},{\"upperType\":\"NOUN\", \"text\":\"Loss of hair (especially on the head) or loss of wool or feathers, which either happens naturally or is caused by disease\", \"priority\":3}]}, \"synonyms\":{}}"); add("alosetron", "{\"term\":\"alosetron\", \"etymology\":{\"influencers\":[], \"languages\":[], \"text\":\"\"}, \"definitions\":{\"list\":[{\"upperType\":\"NOUN\", \"text\":\"A 5-HT3 antagonist used for the management of severe diarrhea-predominant irritable bowel syndrome in women\", \"priority\":1}]}, \"synonyms\":{}}"); add("aloysius", "{\"term\":\"aloysius\", \"etymology\":{\"influencers\":[], \"languages\":[\"English\", \"Occitan\"], \"text\":\"Latinization of an Occitan form of Louis.\"}, \"definitions\":{\"list\":[{\"upperType\":\"NOUN\", \"text\":\"notably of a 16th-century Italian saint\", \"priority\":1},{\"upperType\":\"NOUN\", \"text\":\"1927\u0027\u0027 w:Ernest Ernest Hemingway, \u0027The Sun Also Rises\u0027, Chapter IV\", \"priority\":2},{\"upperType\":\"NOUN\", \"text\":\"Mr and Mrs \u0027\u0027Aloysius\u0027\u0027 Kirby announced the marriage of their daughter Katherine - I knew neither the girl nor the man she was marrying. They must be circularizing the town. It was a funny name. I felt sure I could remember anybody with a name like \u0027\u0027Aloysius\u0027\u0027. It was a good Catholic name\", \"priority\":3}]}, \"synonyms\":{}}"); } private static void add(String term, String json) { map.put(term, GsonUtils.toObject(json, Entry.class)); } public static Entry get(String term) { return map.get(term); } public static boolean has(String term) { return null != get(term); } public static Collection<String> terms() { return map.keySet(); } }
package org.openapitools.virtualan.model; import java.net.URI; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.time.OffsetDateTime; import org.openapitools.jackson.nullable.JsonNullable; import java.time.OffsetDateTime; import javax.validation.Valid; import javax.validation.constraints.*; import java.util.*; /** * Order */ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class Order { @JsonProperty("id") private Long id; @JsonProperty("petId") private Long petId; @JsonProperty("quantity") private Integer quantity; @JsonProperty("shipDate") @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE_TIME) private OffsetDateTime shipDate; /** * Order Status */ public enum StatusEnum { PLACED("placed"), APPROVED("approved"), DELIVERED("delivered"); private String value; StatusEnum(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static StatusEnum fromValue(String value) { for (StatusEnum b : StatusEnum.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } } @JsonProperty("status") private StatusEnum status; @JsonProperty("complete") private Boolean complete = false; public Order id(Long id) { this.id = id; return this; } /** * Get id * @return id */ @ApiModelProperty(value = "") public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Order petId(Long petId) { this.petId = petId; return this; } /** * Get petId * @return petId */ @ApiModelProperty(value = "") public Long getPetId() { return petId; } public void setPetId(Long petId) { this.petId = petId; } public Order quantity(Integer quantity) { this.quantity = quantity; return this; } /** * Get quantity * @return quantity */ @ApiModelProperty(value = "") public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public Order shipDate(OffsetDateTime shipDate) { this.shipDate = shipDate; return this; } /** * Get shipDate * @return shipDate */ @ApiModelProperty(value = "") @Valid public OffsetDateTime getShipDate() { return shipDate; } public void setShipDate(OffsetDateTime shipDate) { this.shipDate = shipDate; } public Order status(StatusEnum status) { this.status = status; return this; } /** * Order Status * @return status */ @ApiModelProperty(value = "Order Status") public StatusEnum getStatus() { return status; } public void setStatus(StatusEnum status) { this.status = status; } public Order complete(Boolean complete) { this.complete = complete; return this; } /** * Get complete * @return complete */ @ApiModelProperty(value = "") public Boolean getComplete() { return complete; } public void setComplete(Boolean complete) { this.complete = complete; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Order order = (Order) o; return Objects.equals(this.id, order.id) && Objects.equals(this.petId, order.petId) && Objects.equals(this.quantity, order.quantity) && Objects.equals(this.shipDate, order.shipDate) && Objects.equals(this.status, order.status) && Objects.equals(this.complete, order.complete); } @Override public int hashCode() { return Objects.hash(id, petId, quantity, shipDate, status, complete); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Order {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
package controller; import java.util.List; import model.OrderUser; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; public interface OrderUserController { public OrderUser createOrderUser(@RequestBody OrderUser orderUser); public OrderUser findOrderUser(@PathVariable long orderUserKey); public List<OrderUser> findOrderUsers(); public OrderUser updateOrderUser(@RequestBody OrderUser orderUser); public void deleteOrderUser(@PathVariable long orderUserKey); /* * custom service */ public List<OrderUser> findOrderUsersByOrderKey(@PathVariable long orderKey); public List<String> findAllOrderUserNames(); }
package com.rnkit_example; import com.facebook.react.ReactActivity; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "rnkit_example"; } }
package com.redisproject.solarpower.app.resources; import com.redisproject.solarpower.app.api.MeterReading; import com.redisproject.solarpower.app.dao.FeedDao; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; @Path("/capacity") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class FeedResource { private final FeedDao feedDao; private static final Integer defaultLimit = 20; public FeedResource(FeedDao feedDao) { this.feedDao = feedDao; } @GET public Response getAllEntries(@QueryParam("limit") Integer limit) { if (limit == null) { limit = defaultLimit; } List<MeterReading> readings = feedDao.getRecentGlobal(limit); return Response.ok(readings) .build(); } @GET @Path("/{id}") public Response getSingleFeed(@PathParam("id") Long siteId, @QueryParam("limit") Integer limit) { if (limit == null) { limit = defaultLimit; } List<MeterReading> readings = feedDao.getRecentForSite(siteId, limit); return Response.ok(readings) .build(); } }
/* * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) * Copyright 2018 SmartBear Software * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openapitools.codegen.languages; import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.media.Schema; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.*; import org.openapitools.codegen.languages.features.BeanValidationFeatures; import org.openapitools.codegen.languages.features.GzipFeatures; import org.openapitools.codegen.languages.features.PerformBeanValidationFeatures; import org.openapitools.codegen.meta.features.DocumentationFeature; import org.openapitools.codegen.meta.features.GlobalFeature; import org.openapitools.codegen.templating.mustache.CaseFormatLambda; import org.openapitools.codegen.utils.ProcessUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.google.common.base.CaseFormat.LOWER_CAMEL; import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE; import static java.util.Collections.sort; import static org.openapitools.codegen.utils.StringUtils.camelize; public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValidationFeatures, PerformBeanValidationFeatures, GzipFeatures { static final String MEDIA_TYPE = "mediaType"; private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class); public static final String USE_RX_JAVA = "useRxJava"; public static final String USE_RX_JAVA2 = "useRxJava2"; public static final String USE_RX_JAVA3 = "useRxJava3"; public static final String DO_NOT_USE_RX = "doNotUseRx"; public static final String USE_PLAY_WS = "usePlayWS"; public static final String PLAY_VERSION = "playVersion"; public static final String ASYNC_NATIVE = "asyncNative"; public static final String PARCELABLE_MODEL = "parcelableModel"; public static final String USE_RUNTIME_EXCEPTION = "useRuntimeException"; public static final String USE_REFLECTION_EQUALS_HASHCODE = "useReflectionEqualsHashCode"; public static final String CASE_INSENSITIVE_RESPONSE_HEADERS = "caseInsensitiveResponseHeaders"; public static final String MICROPROFILE_FRAMEWORK = "microprofileFramework"; public static final String USE_ABSTRACTION_FOR_FILES = "useAbstractionForFiles"; public static final String DYNAMIC_OPERATIONS = "dynamicOperations"; public static final String PLAY_24 = "play24"; public static final String PLAY_25 = "play25"; public static final String PLAY_26 = "play26"; public static final String MICROPROFILE_DEFAULT = "default"; public static final String MICROPROFILE_KUMULUZEE = "kumuluzee"; public static final String FEIGN = "feign"; public static final String GOOGLE_API_CLIENT = "google-api-client"; public static final String JERSEY1 = "jersey1"; public static final String JERSEY2 = "jersey2"; public static final String NATIVE = "native"; public static final String OKHTTP_GSON = "okhttp-gson"; public static final String RESTEASY = "resteasy"; public static final String RESTTEMPLATE = "resttemplate"; public static final String WEBCLIENT = "webclient"; public static final String REST_ASSURED = "rest-assured"; public static final String RETROFIT_2 = "retrofit2"; public static final String VERTX = "vertx"; public static final String MICROPROFILE = "microprofile"; public static final String SERIALIZATION_LIBRARY_GSON = "gson"; public static final String SERIALIZATION_LIBRARY_JACKSON = "jackson"; protected String gradleWrapperPackage = "gradle.wrapper"; protected boolean useRxJava = false; protected boolean useRxJava2 = false; protected boolean useRxJava3 = false; // backwards compatibility for openapi configs that specify neither rx1 nor rx2 // (mustache does not allow for boolean operators so we need this extra field) protected boolean doNotUseRx = true; protected boolean usePlayWS = false; protected String playVersion = PLAY_26; protected String microprofileFramework = MICROPROFILE_DEFAULT; protected boolean asyncNative = false; protected boolean parcelableModel = false; protected boolean useBeanValidation = false; protected boolean performBeanValidation = false; protected boolean useGzipFeature = false; protected boolean useRuntimeException = false; protected boolean useReflectionEqualsHashCode = false; protected boolean caseInsensitiveResponseHeaders = false; protected boolean useAbstractionForFiles = false; protected boolean dynamicOperations = false; protected String authFolder; protected String serializationLibrary = null; public JavaClientCodegen() { super(); // TODO: Move GlobalFeature.ParameterizedServer to library: jersey after moving featureSet to generatorMetadata modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .includeGlobalFeatures(GlobalFeature.ParameterizedServer) ); outputFolder = "generated-code" + File.separator + "java"; embeddedTemplateDir = templateDir = "Java"; invokerPackage = "org.openapitools.client"; artifactId = "openapi-java-client"; apiPackage = "org.openapitools.client.api"; modelPackage = "org.openapitools.client.model"; // cliOptions default redefinition need to be updated updateOption(CodegenConstants.INVOKER_PACKAGE, this.getInvokerPackage()); updateOption(CodegenConstants.ARTIFACT_ID, this.getArtifactId()); updateOption(CodegenConstants.API_PACKAGE, apiPackage); updateOption(CodegenConstants.MODEL_PACKAGE, modelPackage); modelTestTemplateFiles.put("model_test.mustache", ".java"); cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library. IMPORTANT: this option has been deprecated and will be removed in the 5.x release.")); cliOptions.add(CliOption.newBoolean(USE_RX_JAVA2, "Whether to use the RxJava2 adapter with the retrofit2 library.")); cliOptions.add(CliOption.newBoolean(USE_RX_JAVA3, "Whether to use the RxJava3 adapter with the retrofit2 library.")); cliOptions.add(CliOption.newBoolean(PARCELABLE_MODEL, "Whether to generate models for Android that implement Parcelable with the okhttp-gson library.")); cliOptions.add(CliOption.newBoolean(USE_PLAY_WS, "Use Play! Async HTTP client (Play WS API)")); cliOptions.add(CliOption.newString(PLAY_VERSION, "Version of Play! Framework (possible values \"play24\" (Deprecated), \"play25\" (Deprecated), \"play26\" (Default))")); cliOptions.add(CliOption.newBoolean(SUPPORT_JAVA6, "Whether to support Java6 with the Jersey1 library. This option has been deprecated and will be removed in the 5.x release")); cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); cliOptions.add(CliOption.newBoolean(PERFORM_BEANVALIDATION, "Perform BeanValidation")); cliOptions.add(CliOption.newBoolean(USE_GZIP_FEATURE, "Send gzip-encoded requests")); cliOptions.add(CliOption.newBoolean(USE_RUNTIME_EXCEPTION, "Use RuntimeException instead of Exception")); cliOptions.add(CliOption.newBoolean(ASYNC_NATIVE, "If true, async handlers will be used, instead of the sync version")); cliOptions.add(CliOption.newBoolean(USE_REFLECTION_EQUALS_HASHCODE, "Use org.apache.commons.lang3.builder for equals and hashCode in the models. WARNING: This will fail under a security manager, unless the appropriate permissions are set up correctly and also there's potential performance impact.")); cliOptions.add(CliOption.newBoolean(CASE_INSENSITIVE_RESPONSE_HEADERS, "Make API response's headers case-insensitive. Available on " + OKHTTP_GSON + ", " + JERSEY2 + " libraries")); cliOptions.add(CliOption.newString(MICROPROFILE_FRAMEWORK, "Framework for microprofile. Possible values \"kumuluzee\"")); cliOptions.add(CliOption.newBoolean(USE_ABSTRACTION_FOR_FILES, "Use alternative types instead of java.io.File to allow passing bytes without a file on disk. Available on " + RESTTEMPLATE + " library")); cliOptions.add(CliOption.newBoolean(DYNAMIC_OPERATIONS, "Generate operations dynamically at runtime from an OAS", this.dynamicOperations)); supportedLibraries.put(JERSEY1, "HTTP client: Jersey client 1.19.x. JSON processing: Jackson 2.9.x. Enable Java6 support using '-DsupportJava6=true'. Enable gzip request encoding using '-DuseGzipFeature=true'. IMPORTANT NOTE: jersey 1.x is no longer actively maintained so please upgrade to 'jersey2' or other HTTP libaries instead."); supportedLibraries.put(JERSEY2, "HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.9.x"); supportedLibraries.put(FEIGN, "HTTP client: OpenFeign 10.x. JSON processing: Jackson 2.9.x."); supportedLibraries.put(OKHTTP_GSON, "[DEFAULT] HTTP client: OkHttp 3.x. JSON processing: Gson 2.8.x. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'."); supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 3.x. JSON processing: Gson 2.x (Retrofit 2.3.0). Enable the RxJava adapter using '-DuseRxJava[2/3]=true'. (RxJava 1.x or 2.x or 3.x)"); supportedLibraries.put(RESTTEMPLATE, "HTTP client: Spring RestTemplate 4.x. JSON processing: Jackson 2.9.x"); supportedLibraries.put(WEBCLIENT, "HTTP client: Spring WebClient 5.x. JSON processing: Jackson 2.9.x"); supportedLibraries.put(RESTEASY, "HTTP client: Resteasy client 3.x. JSON processing: Jackson 2.9.x"); supportedLibraries.put(VERTX, "HTTP client: VertX client 3.x. JSON processing: Jackson 2.9.x"); supportedLibraries.put(GOOGLE_API_CLIENT, "HTTP client: Google API client 1.x. JSON processing: Jackson 2.9.x"); supportedLibraries.put(REST_ASSURED, "HTTP client: rest-assured : 4.x. JSON processing: Gson 2.x or Jackson 2.10.x. Only for Java 8"); supportedLibraries.put(NATIVE, "HTTP client: Java native HttpClient. JSON processing: Jackson 2.9.x. Only for Java11+"); supportedLibraries.put(MICROPROFILE, "HTTP client: Microprofile client 1.x. JSON processing: Jackson 2.9.x"); CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); libraryOption.setEnum(supportedLibraries); // set okhttp-gson as the default libraryOption.setDefault(OKHTTP_GSON); cliOptions.add(libraryOption); setLibrary(OKHTTP_GSON); CliOption serializationLibrary = new CliOption(CodegenConstants.SERIALIZATION_LIBRARY, "Serialization library, default depends from the library"); Map<String, String> serializationOptions = new HashMap<>(); serializationOptions.put(SERIALIZATION_LIBRARY_GSON, "Use Gson as serialization library"); serializationOptions.put(SERIALIZATION_LIBRARY_JACKSON, "Use Jackson as serialization library"); serializationLibrary.setEnum(serializationOptions); cliOptions.add(serializationLibrary); // Ensure the OAS 3.x discriminator mappings include any descendent schemas that allOf // inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, // and the discriminator mapping schemas in the OAS document. this.setLegacyDiscriminatorBehavior(false); } @Override public CodegenType getTag() { return CodegenType.CLIENT; } @Override public String getName() { return "java"; } @Override public String getHelp() { return "Generates a Java client library (HTTP lib: Jersey (1.x, 2.x), Retrofit (2.x), OpenFeign (10.x) and more."; } @Override public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map<String, List<CodegenOperation>> operations) { super.addOperationToGroup(tag, resourcePath, operation, co, operations); if (MICROPROFILE.equals(getLibrary())) { co.subresourceOperation = !co.path.isEmpty(); } } @Override public void processOpts() { if ((WEBCLIENT.equals(getLibrary()) && "threetenbp".equals(dateLibrary)) || NATIVE.equals(getLibrary())) { dateLibrary = "java8"; } else if (MICROPROFILE.equals(getLibrary()) && "threetenbp".equals(dateLibrary)) { dateLibrary = "legacy"; } super.processOpts(); // RxJava if (additionalProperties.containsKey(USE_RX_JAVA) && additionalProperties.containsKey(USE_RX_JAVA2) && additionalProperties.containsKey(USE_RX_JAVA3)) { LOGGER.warn("You specified all RxJava versions 1, 2 and 3 but they are mutually exclusive. Defaulting to v3."); this.setUseRxJava3(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA3).toString())); } else { if (additionalProperties.containsKey(USE_RX_JAVA) && additionalProperties.containsKey(USE_RX_JAVA2)) { LOGGER.warn("You specified both RxJava versions 1 and 2 but they are mutually exclusive. Defaulting to v2."); this.setUseRxJava2(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA2).toString())); } else if (additionalProperties.containsKey(USE_RX_JAVA) && additionalProperties.containsKey(USE_RX_JAVA3)) { LOGGER.warn("You specified both RxJava versions 1 and 3 but they are mutually exclusive. Defaulting to v3."); this.setUseRxJava3(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA3).toString())); } else if (additionalProperties.containsKey(USE_RX_JAVA2) && additionalProperties.containsKey(USE_RX_JAVA3)) { LOGGER.warn("You specified both RxJava versions 2 and 3 but they are mutually exclusive. Defaulting to v3."); this.setUseRxJava3(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA3).toString())); } else { if (additionalProperties.containsKey(USE_RX_JAVA)) { this.setUseRxJava(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA).toString())); } if (additionalProperties.containsKey(USE_RX_JAVA2)) { this.setUseRxJava2(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA2).toString())); } if (additionalProperties.containsKey(USE_RX_JAVA3)) { this.setUseRxJava3(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA3).toString())); } } } if (!useRxJava && !useRxJava2 && !useRxJava3) { additionalProperties.put(DO_NOT_USE_RX, true); } // Java Play if (additionalProperties.containsKey(USE_PLAY_WS)) { this.setUsePlayWS(Boolean.valueOf(additionalProperties.get(USE_PLAY_WS).toString())); } additionalProperties.put(USE_PLAY_WS, usePlayWS); if (additionalProperties.containsKey(PLAY_VERSION)) { this.setPlayVersion(additionalProperties.get(PLAY_VERSION).toString()); } additionalProperties.put(PLAY_VERSION, playVersion); // Microprofile framework if (additionalProperties.containsKey(MICROPROFILE_FRAMEWORK)) { if (!MICROPROFILE_KUMULUZEE.equals(microprofileFramework)) { throw new RuntimeException("Invalid microprofileFramework '" + microprofileFramework + "'. Must be 'kumuluzee' or none."); } this.setMicroprofileFramework(additionalProperties.get(MICROPROFILE_FRAMEWORK).toString()); } additionalProperties.put(MICROPROFILE_FRAMEWORK, microprofileFramework); if (additionalProperties.containsKey(ASYNC_NATIVE)) { this.setAsyncNative(convertPropertyToBooleanAndWriteBack(ASYNC_NATIVE)); } if (additionalProperties.containsKey(PARCELABLE_MODEL)) { this.setParcelableModel(Boolean.valueOf(additionalProperties.get(PARCELABLE_MODEL).toString())); } // put the boolean value back to PARCELABLE_MODEL in additionalProperties additionalProperties.put(PARCELABLE_MODEL, parcelableModel); if (additionalProperties.containsKey(USE_BEANVALIDATION)) { this.setUseBeanValidation(convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION)); } if (additionalProperties.containsKey(PERFORM_BEANVALIDATION)) { this.setPerformBeanValidation(convertPropertyToBooleanAndWriteBack(PERFORM_BEANVALIDATION)); } if (additionalProperties.containsKey(USE_GZIP_FEATURE)) { this.setUseGzipFeature(convertPropertyToBooleanAndWriteBack(USE_GZIP_FEATURE)); } if (additionalProperties.containsKey(USE_RUNTIME_EXCEPTION)) { this.setUseRuntimeException(convertPropertyToBooleanAndWriteBack(USE_RUNTIME_EXCEPTION)); } if (additionalProperties.containsKey(USE_REFLECTION_EQUALS_HASHCODE)) { this.setUseReflectionEqualsHashCode(convertPropertyToBooleanAndWriteBack(USE_REFLECTION_EQUALS_HASHCODE)); } if (additionalProperties.containsKey(CASE_INSENSITIVE_RESPONSE_HEADERS)) { this.setUseReflectionEqualsHashCode(convertPropertyToBooleanAndWriteBack(CASE_INSENSITIVE_RESPONSE_HEADERS)); } if (additionalProperties.containsKey(USE_ABSTRACTION_FOR_FILES)) { this.setUseAbstractionForFiles(convertPropertyToBooleanAndWriteBack(USE_ABSTRACTION_FOR_FILES)); } if (additionalProperties.containsKey(DYNAMIC_OPERATIONS)) { this.setDynamicOperations(Boolean.valueOf(additionalProperties.get(DYNAMIC_OPERATIONS).toString())); } additionalProperties.put(DYNAMIC_OPERATIONS, dynamicOperations); final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/"); final String apiFolder = (sourceFolder + '/' + apiPackage).replace(".", "/"); authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/"); //Common files supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml").doNotOverwrite()); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md").doNotOverwrite()); supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle").doNotOverwrite()); supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt").doNotOverwrite()); supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle").doNotOverwrite()); supportingFiles.add(new SupportingFile("gradle.properties.mustache", "", "gradle.properties").doNotOverwrite()); supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml").doNotOverwrite()); supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml")); supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java")); supportingFiles.add(new SupportingFile("ServerConfiguration.mustache", invokerFolder, "ServerConfiguration.java")); supportingFiles.add(new SupportingFile("ServerVariable.mustache", invokerFolder, "ServerVariable.java")); if (dynamicOperations) { supportingFiles.add(new SupportingFile("openapi.mustache", projectFolder + "/resources/openapi", "openapi.yaml")); supportingFiles.add(new SupportingFile("apiOperation.mustache", invokerFolder, "ApiOperation.java")); } else { supportingFiles.add(new SupportingFile("openapi.mustache", "api", "openapi.yaml")); } if (dateLibrary.equals("java8") && (isLibrary(WEBCLIENT) || isLibrary(VERTX) || isLibrary(RESTTEMPLATE) || isLibrary(RESTEASY) || isLibrary(MICROPROFILE) || isLibrary(JERSEY2))) { supportingFiles.add(new SupportingFile("JavaTimeFormatter.mustache", invokerFolder, "JavaTimeFormatter.java")); } if (!(RESTTEMPLATE.equals(getLibrary()) || isLibrary(REST_ASSURED) || isLibrary(NATIVE) || isLibrary(MICROPROFILE))) { supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); } // google-api-client doesn't use the OpenAPI auth, because it uses Google Credential directly (HttpRequestInitializer) if (!(isLibrary(GOOGLE_API_CLIENT) || isLibrary(REST_ASSURED) || isLibrary(NATIVE) || isLibrary(MICROPROFILE))) { supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); supportingFiles.add(new SupportingFile("auth/HttpBearerAuth.mustache", authFolder, "HttpBearerAuth.java")); supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); } supportingFiles.add(new SupportingFile("gradlew.mustache", "", "gradlew")); supportingFiles.add(new SupportingFile("gradlew.bat.mustache", "", "gradlew.bat")); supportingFiles.add(new SupportingFile("gradle-wrapper.properties.mustache", gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.properties")); supportingFiles.add(new SupportingFile("gradle-wrapper.jar", gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.jar")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); if (performBeanValidation) { supportingFiles.add(new SupportingFile("BeanValidationException.mustache", invokerFolder, "BeanValidationException.java")); } if (additionalProperties.containsKey(CodegenConstants.SERIALIZATION_LIBRARY)) { setSerializationLibrary(additionalProperties.get(CodegenConstants.SERIALIZATION_LIBRARY).toString()); } //TODO: add auto-generated doc to feign if (FEIGN.equals(getLibrary())) { modelDocTemplateFiles.remove("model_doc.mustache"); apiDocTemplateFiles.remove("api_doc.mustache"); } if (!(FEIGN.equals(getLibrary()) || RESTTEMPLATE.equals(getLibrary()) || RETROFIT_2.equals(getLibrary()) || GOOGLE_API_CLIENT.equals(getLibrary()) || REST_ASSURED.equals(getLibrary()) || WEBCLIENT.equals(getLibrary()) || MICROPROFILE.equals(getLibrary()))) { supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java")); supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java")); supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java")); } if (!(FEIGN.equals(getLibrary()) || RESTTEMPLATE.equals(getLibrary()) || RETROFIT_2.equals(getLibrary()) || GOOGLE_API_CLIENT.equals(getLibrary()) || REST_ASSURED.equals(getLibrary()) || NATIVE.equals(getLibrary()) || MICROPROFILE.equals(getLibrary()))) { supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); } if (FEIGN.equals(getLibrary())) { forceSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON); supportingFiles.add(new SupportingFile("ParamExpander.mustache", invokerFolder, "ParamExpander.java")); supportingFiles.add(new SupportingFile("EncodingUtils.mustache", invokerFolder, "EncodingUtils.java")); supportingFiles.add(new SupportingFile("auth/DefaultApi20Impl.mustache", authFolder, "DefaultApi20Impl.java")); supportingFiles.add(new SupportingFile("auth/OauthPasswordGrant.mustache", authFolder, "OauthPasswordGrant.java")); supportingFiles.add(new SupportingFile("auth/OauthClientCredentialsGrant.mustache", authFolder, "OauthClientCredentialsGrant.java")); } else if (OKHTTP_GSON.equals(getLibrary()) || StringUtils.isEmpty(getLibrary())) { // the "okhttp-gson" library template requires "ApiCallback.mustache" for async call supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java")); supportingFiles.add(new SupportingFile("ApiResponse.mustache", invokerFolder, "ApiResponse.java")); supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); supportingFiles.add(new SupportingFile("ProgressRequestBody.mustache", invokerFolder, "ProgressRequestBody.java")); supportingFiles.add(new SupportingFile("ProgressResponseBody.mustache", invokerFolder, "ProgressResponseBody.java")); supportingFiles.add(new SupportingFile("GzipRequestInterceptor.mustache", invokerFolder, "GzipRequestInterceptor.java")); // NOTE: below moved to postProcessOperationsWithModels //supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java")); //supportingFiles.add(new SupportingFile("auth/RetryingOAuth.mustache", authFolder, "RetryingOAuth.java")); forceSerializationLibrary(SERIALIZATION_LIBRARY_GSON); } else if (RETROFIT_2.equals(getLibrary())) { supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java")); supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, "CollectionFormats.java")); forceSerializationLibrary(SERIALIZATION_LIBRARY_GSON); if (RETROFIT_2.equals(getLibrary()) && !usePlayWS) { supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); } } else if (JERSEY2.equals(getLibrary())) { additionalProperties.put("jersey2", true); supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); supportingFiles.add(new SupportingFile("ApiResponse.mustache", invokerFolder, "ApiResponse.java")); if (ProcessUtils.hasHttpSignatureMethods(openAPI)) { supportingFiles.add(new SupportingFile("auth/HttpSignatureAuth.mustache", authFolder, "HttpSignatureAuth.java")); } supportingFiles.add(new SupportingFile("AbstractOpenApiSchema.mustache", (sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar), "AbstractOpenApiSchema.java")); forceSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON); // Composed schemas can have the 'additionalProperties' keyword, as specified in JSON schema. // In principle, this should be enabled by default for all code generators. However due to limitations // in other code generators, support needs to be enabled on a case-by-case basis. // The flag below should be set for all Java libraries, but the templates need to be ported // one by one for each library. supportsAdditionalPropertiesWithComposedSchema = true; } else if (NATIVE.equals(getLibrary())) { setJava8Mode(true); additionalProperties.put("java8", "true"); supportingFiles.add(new SupportingFile("ApiResponse.mustache", invokerFolder, "ApiResponse.java")); supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); supportingFiles.add(new SupportingFile("AbstractOpenApiSchema.mustache", (sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar), "AbstractOpenApiSchema.java")); forceSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON); } else if (RESTEASY.equals(getLibrary())) { supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); forceSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON); } else if (JERSEY1.equals(getLibrary())) { forceSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON); } else if (RESTTEMPLATE.equals(getLibrary())) { forceSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON); supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); } else if (WEBCLIENT.equals(getLibrary())) { setJava8Mode(true); additionalProperties.put("java8", "true"); forceSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON); } else if (VERTX.equals(getLibrary())) { typeMapping.put("file", "AsyncFile"); importMapping.put("AsyncFile", "io.vertx.core.file.AsyncFile"); setJava8Mode(true); additionalProperties.put("java8", "true"); forceSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON); apiTemplateFiles.put("apiImpl.mustache", "Impl.java"); apiTemplateFiles.put("rxApiImpl.mustache", ".java"); supportingFiles.remove(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); } else if (GOOGLE_API_CLIENT.equals(getLibrary())) { forceSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON); } else if (REST_ASSURED.equals(getLibrary())) { if (getSerializationLibrary() == null) { LOGGER.info("No serializationLibrary configured, using '" + SERIALIZATION_LIBRARY_GSON + "' as fallback"); setSerializationLibrary(SERIALIZATION_LIBRARY_GSON); } if (SERIALIZATION_LIBRARY_JACKSON.equals(getSerializationLibrary())) { supportingFiles.add(new SupportingFile("JacksonObjectMapper.mustache", invokerFolder, "JacksonObjectMapper.java")); } else if (SERIALIZATION_LIBRARY_GSON.equals(getSerializationLibrary())) { supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); supportingFiles.add(new SupportingFile("GsonObjectMapper.mustache", invokerFolder, "GsonObjectMapper.java")); } supportingFiles.add(new SupportingFile("Oper.mustache", apiFolder, "Oper.java")); additionalProperties.put("convert", new CaseFormatLambda(LOWER_CAMEL, UPPER_UNDERSCORE)); apiTemplateFiles.put("api.mustache", ".java"); supportingFiles.add(new SupportingFile("ResponseSpecBuilders.mustache", invokerFolder, "ResponseSpecBuilders.java")); } else if (MICROPROFILE.equals(getLibrary())) { supportingFiles.clear(); // Don't need extra files provided by Java Codegen String apiExceptionFolder = (sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("api_exception.mustache", apiExceptionFolder, "ApiException.java")); supportingFiles.add(new SupportingFile("api_exception_mapper.mustache", apiExceptionFolder, "ApiExceptionMapper.java")); serializationLibrary = "none"; if (microprofileFramework.equals(MICROPROFILE_KUMULUZEE)) { supportingFiles.add(new SupportingFile("kumuluzee.pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("kumuluzee.config.yaml.mustache", "src/main/resources", "config.yaml")); supportingFiles.add(new SupportingFile("kumuluzee.beans.xml.mustache", "src/main/resources/META-INF", "beans.xml")); } } else { LOGGER.error("Unknown library option (-l/--library): " + getLibrary()); } if (usePlayWS) { // remove unsupported auth Iterator<SupportingFile> iter = supportingFiles.iterator(); while (iter.hasNext()) { SupportingFile sf = iter.next(); if (sf.getTemplateFile().startsWith("auth/")) { iter.remove(); } } apiTemplateFiles.remove("api.mustache"); if (PLAY_24.equals(playVersion)) { LOGGER.warn("`play24` option has been deprecated and will be removed in the 5.x release. Please use `play26` instead."); additionalProperties.put(PLAY_24, true); apiTemplateFiles.put("play24/api.mustache", ".java"); supportingFiles.add(new SupportingFile("play24/ApiClient.mustache", invokerFolder, "ApiClient.java")); supportingFiles.add(new SupportingFile("play24/Play24CallFactory.mustache", invokerFolder, "Play24CallFactory.java")); supportingFiles.add(new SupportingFile("play24/Play24CallAdapterFactory.mustache", invokerFolder, "Play24CallAdapterFactory.java")); } if (PLAY_25.equals(playVersion)) { LOGGER.warn("`play25` option has been deprecated and will be removed in the 5.x release. Please use `play26` instead."); additionalProperties.put(PLAY_25, true); apiTemplateFiles.put("play25/api.mustache", ".java"); supportingFiles.add(new SupportingFile("play25/ApiClient.mustache", invokerFolder, "ApiClient.java")); supportingFiles.add(new SupportingFile("play25/Play25CallFactory.mustache", invokerFolder, "Play25CallFactory.java")); supportingFiles.add(new SupportingFile("play25/Play25CallAdapterFactory.mustache", invokerFolder, "Play25CallAdapterFactory.java")); additionalProperties.put("java8", "true"); } if (PLAY_26.equals(playVersion)) { additionalProperties.put(PLAY_26, true); apiTemplateFiles.put("play26/api.mustache", ".java"); supportingFiles.add(new SupportingFile("play26/ApiClient.mustache", invokerFolder, "ApiClient.java")); supportingFiles.add(new SupportingFile("play26/Play26CallFactory.mustache", invokerFolder, "Play26CallFactory.java")); supportingFiles.add(new SupportingFile("play26/Play26CallAdapterFactory.mustache", invokerFolder, "Play26CallAdapterFactory.java")); additionalProperties.put("java8", "true"); } supportingFiles.add(new SupportingFile("play-common/auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java")); forceSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON); } if (getSerializationLibrary() == null) { LOGGER.info("No serializationLibrary configured, using '" + SERIALIZATION_LIBRARY_GSON + "' as fallback"); setSerializationLibrary(SERIALIZATION_LIBRARY_GSON); } if (SERIALIZATION_LIBRARY_JACKSON.equals(getSerializationLibrary())) { additionalProperties.put(SERIALIZATION_LIBRARY_JACKSON, "true"); additionalProperties.remove(SERIALIZATION_LIBRARY_GSON); supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", invokerFolder, "RFC3339DateFormat.java")); if (!NATIVE.equals(getLibrary())) { if ("threetenbp".equals(dateLibrary) && !usePlayWS) { supportingFiles.add(new SupportingFile("CustomInstantDeserializer.mustache", invokerFolder, "CustomInstantDeserializer.java")); } } } else if (SERIALIZATION_LIBRARY_GSON.equals(getSerializationLibrary())) { additionalProperties.put(SERIALIZATION_LIBRARY_GSON, "true"); additionalProperties.remove(SERIALIZATION_LIBRARY_JACKSON); } else { additionalProperties.remove(SERIALIZATION_LIBRARY_JACKSON); additionalProperties.remove(SERIALIZATION_LIBRARY_GSON); } // authentication related files // has OAuth defined if (ProcessUtils.hasOAuthMethods(openAPI)) { // for okhttp-gson (default), check to see if OAuth is defined and included OAuth-related files accordingly if ((OKHTTP_GSON.equals(getLibrary()) || StringUtils.isEmpty(getLibrary()))) { supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java")); supportingFiles.add(new SupportingFile("auth/RetryingOAuth.mustache", authFolder, "RetryingOAuth.java")); } // google-api-client doesn't use the OpenAPI auth, because it uses Google Credential directly (HttpRequestInitializer) if (!(GOOGLE_API_CLIENT.equals(getLibrary()) || REST_ASSURED.equals(getLibrary()) || usePlayWS || NATIVE.equals(getLibrary()) || MICROPROFILE.equals(getLibrary()))) { supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java")); } } } @SuppressWarnings("unchecked") @Override public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) { super.postProcessOperationsWithModels(objs, allModels); if (RETROFIT_2.equals(getLibrary())) { Map<String, Object> operations = (Map<String, Object>) objs.get("operations"); if (operations != null) { List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation"); for (CodegenOperation operation : ops) { if (operation.hasConsumes == Boolean.TRUE) { if (isMultipartType(operation.consumes)) { operation.isMultipart = Boolean.TRUE; } else { operation.prioritizedContentTypes = prioritizeContentTypes(operation.consumes); } } if (StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/")) { operation.path = operation.path.substring(1); } // sorting operation parameters to make sure path params are parsed before query params if (operation.allParams != null) { sort(operation.allParams, new Comparator<CodegenParameter>() { @Override public int compare(CodegenParameter one, CodegenParameter another) { if (one.isPathParam && another.isQueryParam) { return -1; } if (one.isQueryParam && another.isPathParam) { return 1; } return 0; } }); } } } } // camelize path variables for Feign client if (FEIGN.equals(getLibrary())) { Map<String, Object> operations = (Map<String, Object>) objs.get("operations"); List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation"); Pattern methodPattern = Pattern.compile("^(.*):([^:]*)$"); for (CodegenOperation op : operationList) { String path = op.path; String method = ""; // if a custom method is found at the end of the path, cut it off for later Matcher m = methodPattern.matcher(path); if (m.find()) { path = m.group(1); method = m.group(2); } String[] items = path.split("/", -1); for (int i = 0; i < items.length; ++i) { if (items[i].matches("^\\{(.*)\\}$")) { // wrap in {} // camelize path variable items[i] = "{" + camelize(items[i].substring(1, items[i].length() - 1), true) + "}"; } } op.path = StringUtils.join(items, "/"); // Replace the custom method on the path if one was found earlier if (!method.isEmpty()) { op.path += ":" + method; } } } if (MICROPROFILE.equals(getLibrary())) { objs = AbstractJavaJAXRSServerCodegen.jaxrsPostProcessOperations(objs); } return objs; } @Override public String apiFilename(String templateName, String tag) { if (VERTX.equals(getLibrary())) { String suffix = apiTemplateFiles().get(templateName); String subFolder = ""; if (templateName.startsWith("rx")) { subFolder = "/rxjava"; } return apiFileFolder() + subFolder + '/' + toApiFilename(tag) + suffix; } else { return super.apiFilename(templateName, tag); } } /** * Prioritizes consumes mime-type list by moving json-vendor and json mime-types up front, but * otherwise preserves original consumes definition order. * [application/vnd...+json,... application/json, ..as is..] * * @param consumes consumes mime-type list * @return */ static List<Map<String, String>> prioritizeContentTypes(List<Map<String, String>> consumes) { if (consumes.size() <= 1) return consumes; List<Map<String, String>> prioritizedContentTypes = new ArrayList<>(consumes.size()); List<Map<String, String>> jsonVendorMimeTypes = new ArrayList<>(consumes.size()); List<Map<String, String>> jsonMimeTypes = new ArrayList<>(consumes.size()); for (Map<String, String> consume : consumes) { if (isJsonVendorMimeType(consume.get(MEDIA_TYPE))) { jsonVendorMimeTypes.add(consume); } else if (isJsonMimeType(consume.get(MEDIA_TYPE))) { jsonMimeTypes.add(consume); } else prioritizedContentTypes.add(consume); } prioritizedContentTypes.addAll(0, jsonMimeTypes); prioritizedContentTypes.addAll(0, jsonVendorMimeTypes); return prioritizedContentTypes; } private static boolean isMultipartType(List<Map<String, String>> consumes) { Map<String, String> firstType = consumes.get(0); if (firstType != null) { if ("multipart/form-data".equals(firstType.get(MEDIA_TYPE))) { return true; } } return false; } @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); if (!BooleanUtils.toBoolean(model.isEnum)) { //final String lib = getLibrary(); //Needed imports for Jackson based libraries if (additionalProperties.containsKey(SERIALIZATION_LIBRARY_JACKSON)) { model.imports.add("JsonProperty"); model.imports.add("JsonValue"); model.imports.add("JsonInclude"); model.imports.add("JsonTypeName"); } if (additionalProperties.containsKey(SERIALIZATION_LIBRARY_GSON)) { model.imports.add("SerializedName"); model.imports.add("TypeAdapter"); model.imports.add("JsonAdapter"); model.imports.add("JsonReader"); model.imports.add("JsonWriter"); model.imports.add("IOException"); } } else { // enum class //Needed imports for Jackson's JsonCreator if (additionalProperties.containsKey(SERIALIZATION_LIBRARY_JACKSON)) { model.imports.add("JsonValue"); model.imports.add("JsonCreator"); } } if (MICROPROFILE.equals(getLibrary())) { model.imports.remove("ApiModelProperty"); model.imports.remove("ApiModel"); model.imports.remove("JsonSerialize"); model.imports.remove("ToStringSerializer"); } } @Override public CodegenModel fromModel(String name, Schema model) { CodegenModel codegenModel = super.fromModel(name, model); if (MICROPROFILE.equals(getLibrary())) { if (codegenModel.imports.contains("ApiModel")) { // Remove io.swagger.annotations.ApiModel import codegenModel.imports.remove("ApiModel"); } } return codegenModel; } @Override public Map<String, Object> postProcessModelsEnum(Map<String, Object> objs) { objs = super.postProcessModelsEnum(objs); //Needed import for Gson based libraries if (additionalProperties.containsKey(SERIALIZATION_LIBRARY_GSON)) { List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports"); List<Object> models = (List<Object>) objs.get("models"); for (Object _mo : models) { Map<String, Object> mo = (Map<String, Object>) _mo; CodegenModel cm = (CodegenModel) mo.get("model"); // for enum model if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) { cm.imports.add(importMapping.get("SerializedName")); Map<String, String> item = new HashMap<String, String>(); item.put("import", importMapping.get("SerializedName")); imports.add(item); } } } return objs; } @SuppressWarnings("unchecked") @Override public Map<String, Object> postProcessModels(Map<String, Object> objs) { objs = super.postProcessModels(objs); List<Object> models = (List<Object>) objs.get("models"); if (additionalProperties.containsKey(SERIALIZATION_LIBRARY_JACKSON) && !JERSEY1.equals(getLibrary())) { List<Map<String, String>> imports = (List<Map<String, String>>) objs.get("imports"); for (Object _mo : models) { Map<String, Object> mo = (Map<String, Object>) _mo; CodegenModel cm = (CodegenModel) mo.get("model"); boolean addImports = false; for (CodegenProperty var : cm.vars) { if (this.openApiNullable) { boolean isOptionalNullable = Boolean.FALSE.equals(var.required) && Boolean.TRUE.equals(var.isNullable); // only add JsonNullable and related imports to optional and nullable values addImports |= isOptionalNullable; var.getVendorExtensions().put("x-is-jackson-optional-nullable", isOptionalNullable); } if (Boolean.TRUE.equals(var.getVendorExtensions().get("x-enum-as-string"))) { // treat enum string as just string var.datatypeWithEnum = var.dataType; if (StringUtils.isNotEmpty(var.defaultValue)) { // has default value String defaultValue = var.defaultValue.substring(var.defaultValue.lastIndexOf('.') + 1); for (Map<String, Object> enumVars : (List<Map<String, Object>>) var.getAllowableValues().get("enumVars")) { if (defaultValue.equals(enumVars.get("name"))) { // update default to use the string directly instead of enum string var.defaultValue = (String) enumVars.get("value"); } } } // add import for Set, HashSet cm.imports.add("Set"); Map<String, String> importsSet = new HashMap<String, String>(); importsSet.put("import", "java.util.Set"); imports.add(importsSet); Map<String, String> importsHashSet = new HashMap<String, String>(); importsHashSet.put("import", "java.util.HashSet"); imports.add(importsHashSet); } } if (addImports) { Map<String, String> imports2Classnames = new HashMap<>(); imports2Classnames.put("JsonNullable", "org.openapitools.jackson.nullable.JsonNullable"); imports2Classnames.put("NoSuchElementException", "java.util.NoSuchElementException"); imports2Classnames.put("JsonIgnore", "com.fasterxml.jackson.annotation.JsonIgnore"); for (Map.Entry<String, String> entry : imports2Classnames.entrySet()) { cm.imports.add(entry.getKey()); Map<String, String> importsItem = new HashMap<String, String>(); importsItem.put("import", entry.getValue()); imports.add(importsItem); } } } // add implements for serializable/parcelable to all models for (Object _mo : models) { Map<String, Object> mo = (Map<String, Object>) _mo; CodegenModel cm = (CodegenModel) mo.get("model"); cm.getVendorExtensions().putIfAbsent("x-implements", new ArrayList<String>()); if (JERSEY2.equals(getLibrary()) || NATIVE.equals(getLibrary())) { cm.getVendorExtensions().put("x-implements", new ArrayList<String>()); if (cm.oneOf != null && !cm.oneOf.isEmpty() && cm.oneOf.contains("ModelNull")) { // if oneOf contains "null" type cm.isNullable = true; cm.oneOf.remove("ModelNull"); } if (cm.anyOf != null && !cm.anyOf.isEmpty() && cm.anyOf.contains("ModelNull")) { // if anyOf contains "null" type cm.isNullable = true; cm.anyOf.remove("ModelNull"); } } if (this.parcelableModel) { ((ArrayList<String>) cm.getVendorExtensions().get("x-implements")).add("Parcelable"); } if (this.serializableModel) { ((ArrayList<String>) cm.getVendorExtensions().get("x-implements")).add("Serializable"); } } } return objs; } public void setUseRxJava(boolean useRxJava) { this.useRxJava = useRxJava; doNotUseRx = false; } public void setUseRxJava2(boolean useRxJava2) { this.useRxJava2 = useRxJava2; doNotUseRx = false; } public void setUseRxJava3(boolean useRxJava3) { this.useRxJava3 = useRxJava3; doNotUseRx = false; } public void setDoNotUseRx(boolean doNotUseRx) { this.doNotUseRx = doNotUseRx; } public void setUsePlayWS(boolean usePlayWS) { this.usePlayWS = usePlayWS; } public void setPlayVersion(String playVersion) { this.playVersion = playVersion; } public void setAsyncNative(boolean asyncNative) { this.asyncNative = asyncNative; } public void setMicroprofileFramework(String microprofileFramework) { this.microprofileFramework = microprofileFramework; } public void setParcelableModel(boolean parcelableModel) { this.parcelableModel = parcelableModel; } public void setUseBeanValidation(boolean useBeanValidation) { this.useBeanValidation = useBeanValidation; } public void setPerformBeanValidation(boolean performBeanValidation) { this.performBeanValidation = performBeanValidation; } public void setUseGzipFeature(boolean useGzipFeature) { this.useGzipFeature = useGzipFeature; } public void setUseRuntimeException(boolean useRuntimeException) { this.useRuntimeException = useRuntimeException; } public void setUseReflectionEqualsHashCode(boolean useReflectionEqualsHashCode) { this.useReflectionEqualsHashCode = useReflectionEqualsHashCode; } public void setCaseInsensitiveResponseHeaders(final Boolean caseInsensitiveResponseHeaders) { this.caseInsensitiveResponseHeaders = caseInsensitiveResponseHeaders; } public void setUseAbstractionForFiles(boolean useAbstractionForFiles) { this.useAbstractionForFiles = useAbstractionForFiles; } public void setDynamicOperations(final boolean dynamicOperations) { this.dynamicOperations = dynamicOperations; } /** * Serialization library. * * @return 'gson' or 'jackson' */ public String getSerializationLibrary() { return serializationLibrary; } public void setSerializationLibrary(String serializationLibrary) { if (SERIALIZATION_LIBRARY_JACKSON.equalsIgnoreCase(serializationLibrary)) { this.serializationLibrary = SERIALIZATION_LIBRARY_JACKSON; } else if (SERIALIZATION_LIBRARY_GSON.equalsIgnoreCase(serializationLibrary)) { this.serializationLibrary = SERIALIZATION_LIBRARY_GSON; } else { throw new IllegalArgumentException("Unexpected serializationLibrary value: " + serializationLibrary); } } public void forceSerializationLibrary(String serializationLibrary) { if ((this.serializationLibrary != null) && !this.serializationLibrary.equalsIgnoreCase(serializationLibrary)) { LOGGER.warn("The configured serializationLibrary '" + this.serializationLibrary + "', is not supported by the library: '" + getLibrary() + "', switching back to: " + serializationLibrary); } setSerializationLibrary(serializationLibrary); } @Override public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) { generateYAMLSpecFile(objs); return super.postProcessSupportingFileData(objs); } @Override public String toApiVarName(String name) { String apiVarName = super.toApiVarName(name); if (reservedWords.contains(apiVarName)) { apiVarName = escapeReservedWord(apiVarName); } return apiVarName; } @Override public void addImportsToOneOfInterface(List<Map<String, String>> imports) { for (String i : Arrays.asList("JsonSubTypes", "JsonTypeInfo")) { Map<String, String> oneImport = new HashMap<>(); oneImport.put("import", importMapping.get(i)); if (!imports.contains(oneImport)) { imports.add(oneImport); } } } }
package bashar.astifan.ismart.smart.mobi; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Environment; import android.util.Log; /** * * * @author Bashar Astifan <br> * <a href= * "astifan.online" * >Read More</a> <br> * @version 2.0 * */ public class iFileManager { public static String Environmentpath = Environment .getExternalStorageDirectory().toString() + "/"; /** * * * @param path * @return boolean * * <b>use simple path without Environmentpath</b> */ public static boolean DeleteFile(String path) { File file = new File(Environmentpath + path); return file.delete(); } /** * * * @param path * @return boolean * * <b>use simple path without Environmentpath</b> */ public static boolean DeleteFolder(String path) { File cachedir = new File(Environmentpath + path); if (cachedir.isDirectory()) { String[] children = cachedir.list(); for (int i = 0; i < children.length; i++) { new File(cachedir, children[i]).delete(); } } return isExsistFolder(Environmentpath + path); } /** * * * @param path * @param newName * @return boolean * * <b>use simple path without Environmentpath</b> */ public static boolean RenameFile(String path, String newName) { File file = new File(Environmentpath + path); File newfile = new File(Environmentpath + "/" + newName); return file.renameTo(newfile); } /** * * * @param path * @return boolean * * <b>use simple path without Environmentpath</b> */ public static boolean isExsistFile(String path) { File file = new File(Environmentpath + path); return file.exists(); } /** * * * @param path * @return boolean * * <b>use simple path without Environmentpath</b> */ public static boolean isExsistFolder(String path) { File dir = new File(Environmentpath + path); return dir.isDirectory(); } /** * * * @param path * @return long * * <b>use simple path without Environmentpath</b> */ public static long FileSize(String path) { File file = new File(Environmentpath + path); return file.length(); } /** * * * @param path * @return long * * <b>use simple path without Environmentpath</b> */ public static long FolderSize(String path) { File file = new File(Environmentpath + path); return dirSize(file); } /** * * * @param path * @return String * * <b>use simple path without Environmentpath</b> */ public static String FileMD5(String path) { return fileToMD5(Environmentpath + path); } /** * * * @param path * @param fname * @param Content * @return boolean * * <b>use simple path without Environmentpath</b> * */ public static boolean TextCreator(String path, String fname, String Content) { SaveText(Content, Environmentpath + path, fname); return isExsistFile(Environmentpath + path + fname); } public static void openFile(Context ctx,String types,int code){ Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType(types); ((Activity) ctx).startActivityForResult(intent,code); } private static String fileToMD5(String filePath) { InputStream inputStream = null; try { inputStream = new FileInputStream(filePath); byte[] buffer = new byte[1024]; MessageDigest digest = MessageDigest.getInstance("MD5"); int numRead = 0; while (numRead != -1) { numRead = inputStream.read(buffer); if (numRead > 0) digest.update(buffer, 0, numRead); } byte[] md5Bytes = digest.digest(); return convertHashToString(md5Bytes); } catch (Exception e) { return null; } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { } } } } private static String convertHashToString(byte[] md5Bytes) { String returnVal = ""; for (int i = 0; i < md5Bytes.length; i++) { returnVal += Integer.toString((md5Bytes[i] & 0xff) + 0x100, 16) .substring(1); } return returnVal; } private static long dirSize(File dir) { if (dir.exists()) { long result = 0; File[] fileList = dir.listFiles(); for (int i = 0; i < fileList.length; i++) { // Recursive call if it's a directory if (fileList[i].isDirectory()) { result += dirSize(fileList[i]); } else { // Sum the file size in bytes result += fileList[i].length(); } } return result; // return the file size } return 0; } public static void SaveText(String Content, String Path, String name) { try { String path = Environment.getExternalStorageDirectory().toString() + "/" + Path; File myDir = new File(path); if (myDir.isDirectory() && myDir.exists()) { Log.d("Dir exist : ", path); } else { File wallpaperDirectory = new File(path); wallpaperDirectory.mkdirs(); Log.d("Create To : ", path); } String fname = name; File gpxfile = new File(path, fname); FileWriter writer = new FileWriter(gpxfile); writer.append(Content); ; writer.flush(); writer.close(); } catch (IOException e) { } } public static String GetTextContentFromSDWithOutEnvironment(String fileName) { File sdcard = Environment.getExternalStorageDirectory(); // Get the text file File file = new File(sdcard, fileName); Log.e("File Path", file.getPath()); // Read text from file StringBuilder text = new StringBuilder(); try { @SuppressWarnings("resource") BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) { text.append(line); text.append('\n'); } } catch (IOException e) { // You'll need to add proper error handling here } return text.toString(); } /** * Check if an asset exists. This will fail if the asset has a size < 1 * byte. * * @param context * @param path * @return TRUE if the asset exists and FALSE otherwise */ public static boolean isAssets(Context context, String path) { boolean bAssetOk = false; try { InputStream stream = context.getAssets().open(path); stream.close(); bAssetOk = true; } catch (FileNotFoundException e) { Log.w("IOUtilities", "assetExists failed: " + e.toString()); } catch (IOException e) { Log.w("IOUtilities", "assetExists failed: " + e.toString()); } return bAssetOk; } }
/** * Copyright Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tour.guide; public class ChatMessageClass { private String text; private String name; private String photoUrl; public ChatMessageClass() { } public ChatMessageClass(String text, String name, String photoUrl) { this.text = text; this.name = name; this.photoUrl = photoUrl; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhotoUrl() { return photoUrl; } public void setPhotoUrl(String photoUrl) { this.photoUrl = photoUrl; } }
package com.xboxcollectorsplace; import android.app.Application; import android.content.Context; /** * Class used to recover the Application context anywhere in the code */ public class App extends Application { //------------------------------------------------------------------------- ATTRIBUTES*/ private static Context _context = null; //------------------------------------------------------------------------- ON CREATE*/ public void onCreate() { super.onCreate(); _context = this.getApplicationContext(); } //------------------------------------------------------------------------- PRIVATE METHODS*/ public static Context getContext() { return _context; } }
package com.diboot.framework.config; /** * 状态码定义 * @author Mazc@dibo.ltd * @version 2017/8/30 * */ public enum Status { OK(0, "操作成功"), // 请求处理成功 WARN_PARTIAL_SUCCESS(1001, "部分成功"), // 部分成功 WARN_PERFORMANCE_ISSUE(1002, "潜在的性能问题"), // 有性能问题 FAIL_INVALID_PARAM(4000, "请求参数不匹配"), // 传入参数不对 FAIL_INVALID_TOKEN(4001, "Token无效或已过期"), // token无效 FAIL_NO_PERMISSION(4003, "没有权限执行该操作"), // 无权查看 FAIL_NOT_FOUND(4004, "请求资源不存在"), // 404 页面不存在 FAIL_VALIDATION(4005, "提交数据校验不通过"), // 数据校验不通过 FAIL_OPERATION(4006, "操作执行失败"), // 操作执行失败 FAIL_EXCEPTION(5000, "系统异常"); // 系统异常 private int code; private String label; Status(int code, String label){ this.code = code; this.label = label; } public int code(){ return this.code; } public String label(){ return this.label; } public static int getCode(String value){ for(Status eu : Status.values()){ if(eu.name().equals(value)){ return eu.code(); } } return 0; } public static String getLabel(String value){ for(Status eu : Status.values()){ if(eu.name().equals(value)){ return eu.label(); } } return null; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.controller; import org.apache.nifi.parameter.ParameterParser; import org.apache.nifi.parameter.ParameterTokenList; import org.apache.nifi.parameter.ExpressionLanguageAwareParameterParser; import org.apache.nifi.persistence.TemplateDeserializer; import org.apache.nifi.web.api.dto.ConnectableDTO; import org.apache.nifi.web.api.dto.ConnectionDTO; import org.apache.nifi.web.api.dto.ControllerServiceDTO; import org.apache.nifi.web.api.dto.FlowSnippetDTO; import org.apache.nifi.web.api.dto.ProcessGroupDTO; import org.apache.nifi.web.api.dto.ProcessorConfigDTO; import org.apache.nifi.web.api.dto.ProcessorDTO; import org.apache.nifi.web.api.dto.PropertyDescriptorDTO; import org.apache.nifi.web.api.dto.RelationshipDTO; import org.apache.nifi.web.api.dto.RemoteProcessGroupDTO; import org.apache.nifi.web.api.dto.TemplateDTO; import org.w3c.dom.Element; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; public class TemplateUtils { public static TemplateDTO parseDto(final Element templateElement) { try { final DOMSource domSource = new DOMSource(templateElement); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final StreamResult streamResult = new StreamResult(baos); // need to stream the template element as the TemplateDeserializer.deserialize operation needs to re-parse // in order to apply explicit properties on the XMLInputFactory final TransformerFactory transformerFactory = TransformerFactory.newInstance(); final Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); return parseDto(baos.toByteArray()); } catch (final Exception e) { throw new RuntimeException("Could not parse XML as a valid template", e); } } public static TemplateDTO parseDto(final byte[] bytes) { try (final InputStream in = new ByteArrayInputStream(bytes)) { return TemplateDeserializer.deserialize(in); } catch (final IOException ioe) { throw new RuntimeException("Could not parse bytes as template", ioe); } } /** * If template was serialized in a version before Parameters were supported, ensures that any reference to a * Parameter is escaped so that the value is treated as a literal value. * @param templateDto the template */ public static void escapeParameterReferences(final TemplateDTO templateDto) { final String encodingVersion = templateDto.getEncodingVersion(); if (encodingVersion == null) { escapeParameterReferences(templateDto.getSnippet()); } else { switch (encodingVersion) { case "1.0": case "1.1": case "1.2": escapeParameterReferences(templateDto.getSnippet()); break; } } } private static void escapeParameterReferences(final FlowSnippetDTO flowSnippetDTO) { flowSnippetDTO.getProcessors().forEach(TemplateUtils::escapeParameterReferences); flowSnippetDTO.getControllerServices().forEach(TemplateUtils::escapeParameterReferences); for (final ProcessGroupDTO groupDto : flowSnippetDTO.getProcessGroups()) { escapeParameterReferences(groupDto.getContents()); } } private static void escapeParameterReferences(final ProcessorDTO processorDto) { final ProcessorConfigDTO config = processorDto.getConfig(); if (config == null) { return; } final ParameterParser parameterParser = new ExpressionLanguageAwareParameterParser(); final Map<String, String> escapedPropertyValues = new HashMap<>(); for (final Map.Entry<String, String> entry : config.getProperties().entrySet()) { final ParameterTokenList references = parameterParser.parseTokens(entry.getValue()); final String escaped = references.escape(); escapedPropertyValues.put(entry.getKey(), escaped); } config.setProperties(escapedPropertyValues); } private static void escapeParameterReferences(final ControllerServiceDTO controllerServiceDTO) { final ParameterParser parameterParser = new ExpressionLanguageAwareParameterParser(); final Map<String, String> escapedPropertyValues = new HashMap<>(); for (final Map.Entry<String, String> entry : controllerServiceDTO.getProperties().entrySet()) { final ParameterTokenList references = parameterParser.parseTokens(entry.getValue()); final String escaped = references.escape(); escapedPropertyValues.put(entry.getKey(), escaped); } controllerServiceDTO.setProperties(escapedPropertyValues); } /** * Scrubs the template prior to persisting in order to remove fields that shouldn't be included or are unnecessary. * * @param templateDto template */ public static void scrubTemplate(final TemplateDTO templateDto) { scrubSnippet(templateDto.getSnippet()); } private static void scrubSnippet(final FlowSnippetDTO snippet) { // ensure that contents have been specified if (snippet != null) { // go through each processor if specified if (snippet.getProcessors() != null) { scrubProcessors(snippet.getProcessors()); } // go through each connection if specified if (snippet.getConnections() != null) { scrubConnections(snippet.getConnections()); } // go through each remote process group if specified if (snippet.getRemoteProcessGroups() != null) { scrubRemoteProcessGroups(snippet.getRemoteProcessGroups()); } // go through each process group if specified if (snippet.getProcessGroups() != null) { scrubProcessGroups(snippet.getProcessGroups()); } // go through each controller service if specified if (snippet.getControllerServices() != null) { scrubControllerServices(snippet.getControllerServices()); } } } /** * Scrubs process groups prior to saving. * * @param processGroups groups */ private static void scrubProcessGroups(final Set<ProcessGroupDTO> processGroups) { // go through each process group for (final ProcessGroupDTO processGroupDTO : processGroups) { processGroupDTO.setActiveRemotePortCount(null); processGroupDTO.setDisabledCount(null); processGroupDTO.setInactiveRemotePortCount(null); processGroupDTO.setLocalInputPortCount(null); processGroupDTO.setPublicInputPortCount(null); processGroupDTO.setInvalidCount(null); processGroupDTO.setLocalOutputPortCount(null); processGroupDTO.setPublicOutputPortCount(null); processGroupDTO.setRunningCount(null); processGroupDTO.setStoppedCount(null); processGroupDTO.setUpToDateCount(null); processGroupDTO.setLocallyModifiedCount(null); processGroupDTO.setStaleCount(null); processGroupDTO.setLocallyModifiedAndStaleCount(null); processGroupDTO.setSyncFailureCount(null); processGroupDTO.setVersionControlInformation(null); processGroupDTO.setParameterContext(null); scrubSnippet(processGroupDTO.getContents()); } } /** * Scrubs processors prior to saving. This includes removing sensitive properties, validation errors, property descriptors, etc. * * @param processors procs */ private static void scrubProcessors(final Set<ProcessorDTO> processors) { // go through each processor for (final ProcessorDTO processorDTO : processors) { final ProcessorConfigDTO processorConfig = processorDTO.getConfig(); // ensure that some property configuration have been specified if (processorConfig != null) { // if properties have been specified, remove sensitive ones if (processorConfig.getProperties() != null) { Map<String, String> processorProperties = processorConfig.getProperties(); // look for sensitive properties and remove them if (processorConfig.getDescriptors() != null) { final Collection<PropertyDescriptorDTO> descriptors = processorConfig.getDescriptors().values(); for (PropertyDescriptorDTO descriptor : descriptors) { if (Boolean.TRUE.equals(descriptor.isSensitive())) { processorProperties.put(descriptor.getName(), null); } scrubPropertyDescriptor(descriptor); } } } processorConfig.setCustomUiUrl(null); processorConfig.setDefaultConcurrentTasks(null); processorConfig.setDefaultSchedulingPeriod(null); processorConfig.setReferencedAttributes(null); processorConfig.setAutoTerminatedRelationships(null); } if (processorDTO.getRelationships() != null) { for (final RelationshipDTO relationship : processorDTO.getRelationships()) { relationship.setDescription(null); } } processorDTO.setExtensionMissing(null); processorDTO.setMultipleVersionsAvailable(null); processorDTO.setValidationErrors(null); processorDTO.setValidationStatus(null); processorDTO.setInputRequirement(null); processorDTO.setDescription(null); processorDTO.setInputRequirement(null); processorDTO.setPersistsState(null); processorDTO.setSupportsBatching(null); processorDTO.setSupportsEventDriven(null); processorDTO.setSupportsParallelProcessing(null); } } /** * The only thing that we really need from the Property Descriptors in the templates is the * flag that indicates whether or not the property identifies a controller service. * Everything else is unneeded and makes templates very verbose and more importantly makes it * so that if one of these things changes, the template itself changes, which makes it hard to * use a CM tool for versioning. So we remove all that we don't need. * * @param descriptor the PropertyDescriptor to scrub */ private static void scrubPropertyDescriptor(final PropertyDescriptorDTO descriptor) { descriptor.setAllowableValues(null); descriptor.setDefaultValue(null); descriptor.setDescription(null); descriptor.setDisplayName(null); descriptor.setDynamic(null); descriptor.setRequired(null); descriptor.setSensitive(null); descriptor.setSupportsEl(null); descriptor.setExpressionLanguageScope(null); descriptor.setIdentifiesControllerServiceBundle(null); } private static void scrubControllerServices(final Set<ControllerServiceDTO> controllerServices) { for (final ControllerServiceDTO serviceDTO : controllerServices) { final Map<String, String> properties = serviceDTO.getProperties(); final Map<String, PropertyDescriptorDTO> descriptors = serviceDTO.getDescriptors(); if (properties != null && descriptors != null) { for (final PropertyDescriptorDTO descriptor : descriptors.values()) { if (Boolean.TRUE.equals(descriptor.isSensitive())) { properties.put(descriptor.getName(), null); } scrubPropertyDescriptor(descriptor); } } serviceDTO.setControllerServiceApis(null); serviceDTO.setExtensionMissing(null); serviceDTO.setMultipleVersionsAvailable(null); serviceDTO.setCustomUiUrl(null); serviceDTO.setValidationErrors(null); serviceDTO.setValidationStatus(null); serviceDTO.setReferencedAttributes(null); } } /** * Scrubs connections prior to saving. This includes removing available relationships. * * @param connections conns */ private static void scrubConnections(final Set<ConnectionDTO> connections) { // go through each connection for (final ConnectionDTO connectionDTO : connections) { connectionDTO.setAvailableRelationships(null); scrubConnectable(connectionDTO.getSource()); scrubConnectable(connectionDTO.getDestination()); } } /** * Remove unnecessary fields in connectables prior to saving. * * @param connectable connectable */ private static void scrubConnectable(final ConnectableDTO connectable) { if (connectable != null) { connectable.setComments(null); connectable.setExists(null); connectable.setRunning(null); connectable.setTransmitting(null); connectable.setName(null); } } /** * Remove unnecessary fields in remote groups prior to saving. * * @param remoteGroups groups */ private static void scrubRemoteProcessGroups(final Set<RemoteProcessGroupDTO> remoteGroups) { // go through each remote process group for (final RemoteProcessGroupDTO remoteProcessGroupDTO : remoteGroups) { remoteProcessGroupDTO.setFlowRefreshed(null); remoteProcessGroupDTO.setInputPortCount(null); remoteProcessGroupDTO.setOutputPortCount(null); remoteProcessGroupDTO.setTransmitting(null); remoteProcessGroupDTO.setProxyPassword(null); remoteProcessGroupDTO.setActiveRemoteInputPortCount(null); remoteProcessGroupDTO.setInactiveRemoteInputPortCount(null); remoteProcessGroupDTO.setActiveRemoteOutputPortCount(null); remoteProcessGroupDTO.setInactiveRemoteOutputPortCount(null); remoteProcessGroupDTO.setAuthorizationIssues(null); remoteProcessGroupDTO.setFlowRefreshed(null); remoteProcessGroupDTO.setName(null); remoteProcessGroupDTO.setTargetSecure(null); remoteProcessGroupDTO.setTransmitting(null); } } }
/* * JGeneradorJTable.java * * Created on 5 de agosto de 2005, 17:38 * */ package generadorClases.modulosCodigo; import generadorClases.*; import utiles.*; import ListDatos.estructuraBD.*; public class JGeneradorJTable2 implements IModuloProyecto { private JConexionGeneradorClass moConex; //Conexion a la base de datos private JUtiles moUtiles; //Clase de utilidades private boolean mbRelacionesExport; private JProyecto moProyecto; /** * Creates a new instance of JGeneradorJTable */ public JGeneradorJTable2(JProyecto poProyec) { moUtiles = new JUtiles(poProyec); moConex = poProyec.getConex(); moProyecto = poProyec; } public String getCodigo() { StringBuffer lsText = new StringBuffer(100); JTableDef loTabla = moConex.getTablaBD(moConex.getTablaActual()); JFieldDefs loCampos = moConex.getCamposBD(moConex.getTablaActual());; boolean lbEsCamposMinimos = (loCampos.size()<moProyecto.getOpciones().getCamposMinimosTodosModulos()); String lsTablaClase = moUtiles.msSustituirRaros(loTabla.getNombre()); //Compruebo el numero de relaciones de importacion para saber si tiene que llevar pestaNas mbRelacionesExport = moConex.tieneRelacionesExport(); //CABECERA********************************* JDateEdu loDate = new JDateEdu(); lsText.append("/*");lsText.append(JUtiles.msRetornoCarro); lsText.append("* "+moUtiles.getNombreTablaExtends(lsTablaClase) + ".java");lsText.append(JUtiles.msRetornoCarro); lsText.append("*");lsText.append(JUtiles.msRetornoCarro); lsText.append("* Creado el " + loDate.getDia() + "/" + loDate.getMes() + "/" + loDate.getAno());lsText.append(JUtiles.msRetornoCarro); lsText.append("*/");lsText.append(JUtiles.msRetornoCarro); lsText.append(JUtiles.msRetornoCarro); //***************************************** //IMPORTACION************************************ lsText.append("package " + moConex.getDirPadre() + "." + moUtiles.getPaqueteExtend() + ";");lsText.append(JUtiles.msRetornoCarro); lsText.append(JUtiles.msRetornoCarro); lsText.append("import java.util.HashMap;");lsText.append(JUtiles.msRetornoCarro); lsText.append("import ListDatos.*;");lsText.append(JUtiles.msRetornoCarro); lsText.append("import ListDatos.estructuraBD.*;");lsText.append(JUtiles.msRetornoCarro); lsText.append("import " + moConex.getDirPadre() + "." + "tablas.*;");lsText.append(JUtiles.msRetornoCarro); lsText.append("import " + moConex.getDirPadre() + "." + "*;");lsText.append(JUtiles.msRetornoCarro); lsText.append("import utilesGUIx.formsGenericos.*;");lsText.append(JUtiles.msRetornoCarro); lsText.append("import utilesGUIx.formsGenericos.edicion.*;");lsText.append(JUtiles.msRetornoCarro); lsText.append("import utilesGUIx.formsGenericos.busqueda.*;");lsText.append(JUtiles.msRetornoCarro); lsText.append("import utilesGUIx.aplicacion.IGestionProyecto;");lsText.append(JUtiles.msRetornoCarro); lsText.append("import utilesGUIx.panelesGenericos.JConsulta;");lsText.append(JUtiles.msRetornoCarro); lsText.append("import utilesGUIx.panelesGenericos.JPanelBusquedaParametros;");lsText.append(JUtiles.msRetornoCarro); lsText.append("import "+moConex.getDirPadre()+".consultas.*;");lsText.append(JUtiles.msRetornoCarro); lsText.append("import "+moConex.getDirPadre()+".tablasControladoras.*;");lsText.append(JUtiles.msRetornoCarro); lsText.append("import "+moConex.getDirPadre()+".forms.*;");lsText.append(JUtiles.msRetornoCarro); lsText.append(JUtiles.msRetornoCarro); //*********************************************** //CUERPO DE LA CLASE************************************** lsText.append("public class "+moUtiles.getNombreTablaExtends(lsTablaClase) + " extends JT" + lsTablaClase + (lbEsCamposMinimos?" implements IConsulta ":"") +" {");lsText.append(JUtiles.msRetornoCarro); lsText.append(" private static final long serialVersionUID = 1L;");lsText.append(JUtiles.msRetornoCarro); lsText.append(" public static final String[] masCaption = JDatosGeneralesP.getDatosGenerales().getTextosForms().getCaptions(msCTabla, masNombres);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" protected transient HashMap moListaRelaciones = new HashMap();");lsText.append(JUtiles.msRetornoCarro); // //Controladores para las pestaNas // if(mbRelacionesExport) { // for(int i=0;i<loTabla.getRelaciones().count();i++) { // JRelacionesDef loRelacion = loTabla.getRelaciones().getRelacion(i); // if(loRelacion.getTipoRelacion() == JRelacionesDef.mclRelacionExport) { //Si es una relacion de exportacion // JTableDef loTablaRelac = moConex.getTablaBD(loTabla.getRelaciones().getRelacion(i).getTablaRelacionada()); // if(loTablaRelac.getCampos().size()>=moProyecto.getOpciones().getCamposMinimosTodosModulos()){ // lsText.append(" protected JT2"+ moConex.getNomTablaSimple(i) +" moCtrl"+ moConex.getNomTablaComplejo(i,JUtiles.mcnCamposTablaRelacionada) +" = null;");lsText.append(JUtiles.msRetornoCarro); // } // } // } // lsText.append(JUtiles.msRetornoCarro); // } lsText.append(JUtiles.msRetornoCarro); lsText.append(" /**");lsText.append(JUtiles.msRetornoCarro); lsText.append(" * Crea una instancia de la clase intermedia para la tabla " + lsTablaClase + " incluyendole el servidor de datos");lsText.append(JUtiles.msRetornoCarro); lsText.append(" */");lsText.append(JUtiles.msRetornoCarro); lsText.append(" public "+moUtiles.getNombreTablaExtends(lsTablaClase) + "(IServerServidorDatos poServidorDatos) {");lsText.append(JUtiles.msRetornoCarro); lsText.append(" super(poServidorDatos);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" moList.getFields().setCaptions(masCaption);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" moList.getFields().get(0).setActualizarValorSiNulo(JFieldDef.mclActualizarUltMasUno);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); lsText.append(JUtiles.msRetornoCarro); lsText.append(" public static boolean getPasarACache(){");lsText.append(JUtiles.msRetornoCarro); lsText.append(" return false;");lsText.append(JUtiles.msRetornoCarro); lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); if(lbEsCamposMinimos){ lsText.append(" public boolean getPasarCache(){");lsText.append(JUtiles.msRetornoCarro); lsText.append(" return getPasarACache();");lsText.append(JUtiles.msRetornoCarro); lsText.append(" } ");lsText.append(JUtiles.msRetornoCarro); lsText.append(JUtiles.msRetornoCarro); lsText.append("");lsText.append(JUtiles.msRetornoCarro); lsText.append(" public void refrescar(boolean pbPasarACache, boolean pbLimpiarCache) throws Exception {");lsText.append(JUtiles.msRetornoCarro); lsText.append(" super.refrescar(pbPasarACache, pbLimpiarCache);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); lsText.append("");lsText.append(JUtiles.msRetornoCarro); lsText.append(" public void addFilaPorClave(IFilaDatos poFila) throws Exception {");lsText.append(JUtiles.msRetornoCarro); lsText.append(" switch(poFila.getTipoModif()){");lsText.append(JUtiles.msRetornoCarro); lsText.append(" case JListDatos.mclBorrar:");lsText.append(JUtiles.msRetornoCarro); lsText.append(" moList.borrar(false);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" break;");lsText.append(JUtiles.msRetornoCarro); lsText.append(" case JListDatos.mclEditar:");lsText.append(JUtiles.msRetornoCarro); lsText.append(" moList.getFields().cargar(poFila);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" moList.update(false);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" break;");lsText.append(JUtiles.msRetornoCarro); lsText.append(" case JListDatos.mclNuevo:");lsText.append(JUtiles.msRetornoCarro); lsText.append(" moList.addNew();");lsText.append(JUtiles.msRetornoCarro); lsText.append(" moList.getFields().cargar(poFila);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" moList.update(false);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" break;");lsText.append(JUtiles.msRetornoCarro); lsText.append(" default:");lsText.append(JUtiles.msRetornoCarro); lsText.append(" throw new Exception(\"Tipo modificacion incorrecto\");");lsText.append(JUtiles.msRetornoCarro); lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); } lsText.append(" public static "+moUtiles.getNombreTablaExtends(lsTablaClase) + " getTabla("); String lsCamposPrincipales=""; String lsCamposPrincipalesFila=""; int[] lalCamposP = loCampos.malCamposPrincipales(); if(lalCamposP!=null){ for(int i = 0; i < lalCamposP.length; i++ ){ String lsCampo = moUtiles.msSustituirRaros(loCampos.get(lalCamposP[i]).getNombre()); if(i == (lalCamposP.length-1)){ lsCamposPrincipales += "ps" + lsCampo; lsText.append("final String ps" + lsCampo + ""); lsCamposPrincipalesFila += "poFila.msCampo(lPosi" + lsCampo + "),"; }else{ lsCamposPrincipales += "ps" + lsCampo + ","; lsText.append("final String ps" + lsCampo + ","); lsCamposPrincipalesFila += "poFila.msCampo(lPosi" + lsCampo + "),"; } } } lsText.append(",final IServerServidorDatos poServer) throws Exception {"); lsText.append(JUtiles.msRetornoCarro); lsText.append(" "+moUtiles.getNombreTablaExtends(lsTablaClase) + " loTabla = new "+moUtiles.getNombreTablaExtends(lsTablaClase) + "(poServer);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" if(getPasarACache()){");lsText.append(JUtiles.msRetornoCarro); lsText.append(" loTabla.recuperarTodosNormalCache();");lsText.append(JUtiles.msRetornoCarro); lsText.append(" loTabla.moList.getFiltro().addCondicion(");lsText.append(JUtiles.msRetornoCarro); lsText.append(" JListDatosFiltroConj.mclAND, ");lsText.append(JUtiles.msRetornoCarro); lsText.append(" JListDatos.mclTIgual, ");lsText.append(JUtiles.msRetornoCarro); lsText.append(" malCamposPrincipales, ");lsText.append(JUtiles.msRetornoCarro); lsText.append(" new String[]{"+lsCamposPrincipales+"});");lsText.append(JUtiles.msRetornoCarro); lsText.append(" loTabla.moList.filtrar();");lsText.append(JUtiles.msRetornoCarro); lsText.append(" }else{");lsText.append(JUtiles.msRetornoCarro); lsText.append(" loTabla.recuperarFiltradosNormal(new JListDatosFiltroElem(");lsText.append(JUtiles.msRetornoCarro); lsText.append(" JListDatos.mclTIgual, malCamposPrincipales, new String[]{"+lsCamposPrincipales+"}) ,false);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); lsText.append(" return loTabla;");lsText.append(JUtiles.msRetornoCarro); lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); lsText.append(JUtiles.msRetornoCarro); lsText.append("");lsText.append(JUtiles.msRetornoCarro); lsText.append(" public static "+moUtiles.getNombreTablaExtends(lsTablaClase) + " getTabla(IFilaDatos poFila, IServerServidorDatos poServer) throws Exception {");lsText.append(JUtiles.msRetornoCarro); lsText.append(" return getTabla(");lsText.append(JUtiles.msRetornoCarro); lsText.append(" " + lsCamposPrincipalesFila);lsText.append(JUtiles.msRetornoCarro); lsText.append(" poServer);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); lsText.append(" public static utilesGUIx.panelesGenericos.JPanelBusquedaParametros getParamPanelBusq(final IServerServidorDatos poServer, final IMostrarPantalla poMostrar) throws Exception {");lsText.append(JUtiles.msRetornoCarro); lsText.append(" utilesGUIx.panelesGenericos.JPanelBusquedaParametros loParam = new utilesGUIx.panelesGenericos.JPanelBusquedaParametros();");lsText.append(JUtiles.msRetornoCarro); if(lbEsCamposMinimos){ lsText.append(" loParam.mlCamposPrincipales = malCamposPrincipales;");lsText.append(JUtiles.msRetornoCarro); }else{ lsText.append(" loParam.mlCamposPrincipales = "+"JTFORM"+lsTablaClase+".getFieldsEstaticos().malCamposPrincipales();");lsText.append(JUtiles.msRetornoCarro); } lsText.append(" loParam.masTextosDescripciones = masCaption;");lsText.append(JUtiles.msRetornoCarro); lsText.append(" loParam.mbConDatos=false;");lsText.append(JUtiles.msRetornoCarro); lsText.append(" loParam.mbMensajeSiNoExiste=true;");lsText.append(JUtiles.msRetornoCarro); lsText.append(JUtiles.msRetornoCarro); lsText.append(" loParam.malDescripciones = new int[]{");lsText.append(JUtiles.msRetornoCarro); if(loCampos.malCamposPrincipales()!=null){ for(int i = loCampos.malCamposPrincipales().length; i < loCampos.count(); i++ ){ if(lbEsCamposMinimos){ lsText.append(" lPosi" + moUtiles.msSustituirRaros(loCampos.get(i).getNombre()) + (i==(loCampos.count()-1)? "" : ",") );lsText.append(JUtiles.msRetornoCarro); }else{ lsText.append(" JTFORM"+lsTablaClase+".lPosi" + moUtiles.msSustituirRaros(loCampos.get(i).getNombre()) + (i==(loCampos.count()-1)? "" : ",") );lsText.append(JUtiles.msRetornoCarro); } } } lsText.append(" };" + JUtiles.msRetornoCarro); lsText.append(" loParam.masTextosDescripciones = new String[]{");lsText.append(JUtiles.msRetornoCarro); if(loCampos.malCamposPrincipales()!=null){ for(int i = loCampos.malCamposPrincipales().length; i < loCampos.count(); i++ ){ if(lbEsCamposMinimos){ lsText.append(" "+ "masCaption[lPosi" + moUtiles.msSustituirRaros(loCampos.get(i).getNombre()) +"]" ); if(i!=(loCampos.count()-1)){ lsText.append(","); } lsText.append(JUtiles.msRetornoCarro); }else{ lsText.append(" "+ "JTFORM"+lsTablaClase+".getFieldEstatico("+ "JTFORM"+lsTablaClase+".lPosi" + moUtiles.msSustituirRaros(loCampos.get(i).getNombre()) + (i==(loCampos.count()-1)? ").getCaption()" : ").getCaption(),") );lsText.append(JUtiles.msRetornoCarro); } } } lsText.append(" };" + JUtiles.msRetornoCarro); lsText.append(JUtiles.msRetornoCarro); if(lbEsCamposMinimos){ lsText.append(" "+moUtiles.getNombreTablaExtends(lsTablaClase)+" loObj = new "+moUtiles.getNombreTablaExtends(lsTablaClase)+"(poServer);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" "+moUtiles.getNombreTablaExtends(lsTablaClase)+" loObjC = new "+moUtiles.getNombreTablaExtends(lsTablaClase)+"(poServer);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" JT2GENERICO loControlador = new JT2GENERICO(");lsText.append(JUtiles.msRetornoCarro); lsText.append(" poMostrar,");lsText.append(JUtiles.msRetornoCarro); lsText.append(" loObj,");lsText.append(JUtiles.msRetornoCarro); lsText.append(" loObjC,");lsText.append(JUtiles.msRetornoCarro); lsText.append(" loObj.getPasarACache()");lsText.append(JUtiles.msRetornoCarro); lsText.append(" );");lsText.append(JUtiles.msRetornoCarro); lsText.append(" loParam.moControlador = loControlador;");lsText.append(JUtiles.msRetornoCarro); lsText.append("");lsText.append(JUtiles.msRetornoCarro); lsText.append(" loObj = new "+moUtiles.getNombreTablaExtends(lsTablaClase)+"(poServer);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" loParam.moTabla = loObj;");lsText.append(JUtiles.msRetornoCarro); lsText.append(" ");lsText.append(JUtiles.msRetornoCarro); }else{ lsText.append(" loParam.moControlador = new JT2"+lsTablaClase+"(poServer, poMostrar);");lsText.append(JUtiles.msRetornoCarro); lsText.append(JUtiles.msRetornoCarro); lsText.append(" JTFORM"+lsTablaClase+" loConsulta = new JTFORM"+lsTablaClase+"(poServer);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" loConsulta.crearSelectSimple();");lsText.append(JUtiles.msRetornoCarro); lsText.append(" ");lsText.append(JUtiles.msRetornoCarro); lsText.append(" loParam.moTabla = loConsulta;");lsText.append(JUtiles.msRetornoCarro); lsText.append(" ");lsText.append(JUtiles.msRetornoCarro); } lsText.append(" return loParam;");lsText.append(JUtiles.msRetornoCarro); lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); lsText.append(" public void valoresDefecto() throws Exception { ");lsText.append(JUtiles.msRetornoCarro); lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); lsText.append(" protected void comprobarClaveCargar(boolean pbEsMismaclave) throws Exception{");lsText.append(JUtiles.msRetornoCarro); lsText.append(" if(!pbEsMismaclave){");lsText.append(JUtiles.msRetornoCarro); lsText.append(" moListaRelaciones = null;");lsText.append(JUtiles.msRetornoCarro); lsText.append(" moListaRelaciones = new HashMap();");lsText.append(JUtiles.msRetornoCarro); // //Controladores para las pestanas // if(mbRelacionesExport) { // for(int i=0;i<loTabla.getRelaciones().count();i++) { // JRelacionesDef loRelacion = loTabla.getRelaciones().getRelacion(i); // if(loRelacion.getTipoRelacion() == JRelacionesDef.mclRelacionExport) { //Si es una relacion de exportacion // JTableDef loTablaRelac = moConex.getTablaBD(loTabla.getRelaciones().getRelacion(i).getTablaRelacionada()); // if(loTablaRelac.getCampos().size()>=moProyecto.getOpciones().getCamposMinimosTodosModulos()){ // lsText.append(" moCtrl"+ moConex.getNomTablaComplejo(i,JUtiles.mcnCamposTablaRelacionada) +" = null;");lsText.append(JUtiles.msRetornoCarro); // } // // } // } // lsText.append(JUtiles.msRetornoCarro); // } lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); lsText.append(" protected void cargarControlador(String psTabla, IMostrarPantalla poMostrar) throws Exception{");lsText.append(JUtiles.msRetornoCarro); lsText.append(" IPanelControlador loAux =");lsText.append(JUtiles.msRetornoCarro); lsText.append(" JDatosGeneralesP.getDatosGenerales().getControlador(");lsText.append(JUtiles.msRetornoCarro); lsText.append(" moList.moServidor,");lsText.append(JUtiles.msRetornoCarro); lsText.append(" poMostrar,");lsText.append(JUtiles.msRetornoCarro); lsText.append(" psTabla,");lsText.append(JUtiles.msRetornoCarro); lsText.append(" moList.msTabla,");lsText.append(JUtiles.msRetornoCarro); lsText.append(" moList.getFields().moFilaDatos()");lsText.append(JUtiles.msRetornoCarro); lsText.append(" );");lsText.append(JUtiles.msRetornoCarro); lsText.append(" moListaRelaciones.put(psTabla, loAux);");lsText.append(JUtiles.msRetornoCarro); // //Controladores para las pestanas // if(mbRelacionesExport) { // for(int i=0;i<loTabla.getRelaciones().count();i++) { // JRelacionesDef loRelacion = loTabla.getRelaciones().getRelacion(i); // if(loRelacion.getTipoRelacion() == JRelacionesDef.mclRelacionExport) { //Si es una relacion de exportacion // JTableDef loTablaRelac = moConex.getTablaBD(loTabla.getRelaciones().getRelacion(i).getTablaRelacionada()); // if(loTablaRelac.getCampos().size()>=moProyecto.getOpciones().getCamposMinimosTodosModulos()){ // // // String lsControlador = "moCtrl"+ moConex.getNomTablaComplejo(i,JUtiles.mcnCamposTablaRelacionada); // String lsTabla = moConex.getNomTablaSimple(i); // String lsControladorClase = "JT2"+lsTabla; // // // lsText.append(" if(psTabla.equalsIgnoreCase(JTEE" + lsTabla + ".msCTabla) && ");lsText.append(JUtiles.msRetornoCarro); // lsText.append(" ("+lsControlador+"==null) ");lsText.append(JUtiles.msRetornoCarro); // lsText.append(" ){");lsText.append(JUtiles.msRetornoCarro); // // // lsText.append(" "+lsControlador+" = new "+lsControladorClase +"(");lsText.append(JUtiles.msRetornoCarro); // lsText.append(" moList.moServidor, ");lsText.append(JUtiles.msRetornoCarro); // lsText.append(" poMostrar, ");lsText.append(JUtiles.msRetornoCarro); // lsText.append(" moList.msTabla, ");lsText.append(JUtiles.msRetornoCarro); // // // for(int j = 0; j < loCampos.count(); j++ ){ // if (loCampos.get(j).getPrincipalSN()) { // lsText.append(" get" + moUtiles.msSustituirRaros(loCampos.get(j).getNombre()) + "().getString() , ");lsText.append(JUtiles.msRetornoCarro); // } // } // //borramos la coma del final + retornmo carro ,mas espacio // lsText.delete(lsText.length()-5, lsText.length()-1); // // lsText.append(" );");lsText.append(JUtiles.msRetornoCarro); // lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); // } // } // } // lsText.append(JUtiles.msRetornoCarro); // } lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); lsText.append(" protected void cargar(String psTabla, IMostrarPantalla poMostrar) throws Exception{");lsText.append(JUtiles.msRetornoCarro); lsText.append(" comprobarClaveCargar(isMismaClave());");lsText.append(JUtiles.msRetornoCarro); lsText.append(" if(!isMismaClave()){");lsText.append(JUtiles.msRetornoCarro); lsText.append(" msCodigoRelacionado = getClave();");lsText.append(JUtiles.msRetornoCarro); lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); lsText.append(" ");lsText.append(JUtiles.msRetornoCarro); for(int i = 0; i < loTabla.getRelaciones().count();i++) { if(loTabla.getRelaciones().getRelacion(i).getTipoRelacion() == JRelacionesDef.mclRelacionImport) { String lsNomTabla = moUtiles.msSustituirRaros(loTabla.getRelaciones().getRelacion(i).getTablaRelacionada()); String lsNomCampo = moUtiles.msSustituirRaros(loTabla.getRelaciones().getRelacion(i).getCampoPropio(0)); lsText.append(" if(("+moUtiles.getNombreTablaExtends(lsNomTabla)+".msCTabla+get"+lsNomCampo+"Nombre()).equalsIgnoreCase(psTabla)){");lsText.append(JUtiles.msRetornoCarro); lsText.append(" "+moUtiles.getNombreTablaExtends(lsNomTabla)+" loTabla = ("+moUtiles.getNombreTablaExtends(lsNomTabla)+")moListaRelaciones.get(psTabla);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" if(loTabla==null){");lsText.append(JUtiles.msRetornoCarro); lsText.append(" loTabla = "+moUtiles.getNombreTablaExtends(lsNomTabla)+".getTabla("); for(int l = 0 ; l < loTabla.getRelaciones().getRelacion(i).getCamposRelacionCount(); l++ ){ lsNomCampo = moUtiles.msSustituirRaros(loTabla.getRelaciones().getRelacion(i).getCampoPropio(l)); lsText.append("get"+lsNomCampo + "().getString(), "); } lsText.append(" moList.moServidor);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" moListaRelaciones.put(psTabla, loTabla);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); lsText.append(" } else ");lsText.append(JUtiles.msRetornoCarro); lsText.append(JUtiles.msRetornoCarro); } } lsText.append(" cargarControlador(psTabla, poMostrar);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" ");lsText.append(JUtiles.msRetornoCarro); lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); lsText.append(" public IPanelControlador getControlador(String psTabla, IMostrarPantalla poMostrar) throws Exception{");lsText.append(JUtiles.msRetornoCarro); lsText.append(" cargar(psTabla, poMostrar);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" return (IPanelControlador) moListaRelaciones.get(psTabla);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); for(int i = 0; i < loTabla.getRelaciones().count();i++) { if(loTabla.getRelaciones().getRelacion(i).getTipoRelacion() == JRelacionesDef.mclRelacionImport) { String lsNomTabla = moUtiles.msSustituirRaros(loTabla.getRelaciones().getRelacion(i).getTablaRelacionada()); String lsNomCampo = moUtiles.msSustituirRaros(loTabla.getRelaciones().getRelacion(i).getCampoPropio(0)); lsText.append(" public "+moUtiles.getNombreTablaExtends(lsNomTabla)+" get"+lsNomTabla+lsNomCampo+"() throws Exception{");lsText.append(JUtiles.msRetornoCarro); lsText.append(" cargar("+moUtiles.getNombreTablaExtends(lsNomTabla)+".msCTabla+ get" + lsNomCampo + "Nombre(), null);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" return ("+moUtiles.getNombreTablaExtends(lsNomTabla)+") moListaRelaciones.get("+moUtiles.getNombreTablaExtends(lsNomTabla)+".msCTabla + get" + lsNomCampo + "Nombre());");lsText.append(JUtiles.msRetornoCarro); lsText.append(" } ");lsText.append(JUtiles.msRetornoCarro); lsText.append(JUtiles.msRetornoCarro); } } // if(mbRelacionesExport) { // for(int i=0;i<loTabla.getRelaciones().count();i++) { // JRelacionesDef loRelacion = loTabla.getRelaciones().getRelacion(i); // if(loRelacion.getTipoRelacion() == JRelacionesDef.mclRelacionExport) { //Si es una relacion de exportacion // JTableDef loTablaRelac = moConex.getTablaBD(loTabla.getRelaciones().getRelacion(i).getTablaRelacionada()); // if(loTablaRelac.getCampos().size()>=moProyecto.getOpciones().getCamposMinimosTodosModulos()){ // String lsNombreCompuesto = moConex.getNomTablaComplejo(i,JUtiles.mcnCamposTablaRelacionada); // String lsTabla = moConex.getNomTablaSimple(i); // lsText.append(" public JT2"+lsTabla+" getCtrl"+lsNombreCompuesto+"(IMostrarPantalla poMostrar) throws Exception{");lsText.append(JUtiles.msRetornoCarro); // lsText.append(" cargar(JTEE"+lsTabla+".msCTabla, poMostrar);");lsText.append(JUtiles.msRetornoCarro); // lsText.append(" return moCtrl"+lsNombreCompuesto+";");lsText.append(JUtiles.msRetornoCarro); // lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); // } // } // } // lsText.append(JUtiles.msRetornoCarro); // } // lsText.append(" public IResultado guardar() throws Exception{");lsText.append(JUtiles.msRetornoCarro); lsText.append(" //se comprueba antes de guardar la clave pq despues de ");lsText.append(JUtiles.msRetornoCarro); lsText.append(" //guardar puede cambiar (por ejem. si estaba en modo nuevo )");lsText.append(JUtiles.msRetornoCarro); lsText.append(" boolean lbIsMismaClave = isMismaClave();");lsText.append(JUtiles.msRetornoCarro); lsText.append(" //comprobamos las tablas relacionadas");lsText.append(JUtiles.msRetornoCarro); lsText.append(" comprobarClaveCargar(lbIsMismaClave);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" JResultado loResult = new JResultado(\"\", true);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" loResult.addResultado(moList.update(true));");lsText.append(JUtiles.msRetornoCarro); lsText.append(" ");lsText.append(JUtiles.msRetornoCarro); lsText.append(" if(loResult.getBien() && ");lsText.append(JUtiles.msRetornoCarro); lsText.append(" lbIsMismaClave) {");lsText.append(JUtiles.msRetornoCarro); lsText.append("// JTEESUBFAMILIAS loSub = JTEESUBFAMILIAS.getTabla(getCODIGOFAMILIA().getString(),moList.moServidor);");lsText.append(JUtiles.msRetornoCarro); lsText.append("// if(loSub.moList.moveFirst()){");lsText.append(JUtiles.msRetornoCarro); lsText.append("// do{");lsText.append(JUtiles.msRetornoCarro); lsText.append("// loSub.getUSALOTESSN().setValue(getUSALOTESSN().getBoolean()); ");lsText.append(JUtiles.msRetornoCarro); lsText.append("// loSub.moList.update(false);");lsText.append(JUtiles.msRetornoCarro); lsText.append("// }while(loSub.moList.moveNext());");lsText.append(JUtiles.msRetornoCarro); lsText.append("// JActualizarConj loAct = new JActualizarConj(\"\",\"\",\"\");");lsText.append(JUtiles.msRetornoCarro); lsText.append("// loAct.crearUpdateAPartirList(loSub.moList);");lsText.append(JUtiles.msRetornoCarro); lsText.append("// loResult.addResultado(loSub.moList.moServidor.actualizarConj(loAct));");lsText.append(JUtiles.msRetornoCarro); lsText.append("// ");lsText.append(JUtiles.msRetornoCarro); lsText.append("// }");lsText.append(JUtiles.msRetornoCarro); lsText.append(" ");lsText.append(JUtiles.msRetornoCarro); lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); lsText.append(" //si estaba en modo nuevo, si todo bien se queda en modo Nada/editar, por lo q hay");lsText.append(JUtiles.msRetornoCarro); lsText.append(" //q actualizar el codigo relacionado");lsText.append(JUtiles.msRetornoCarro); lsText.append(" if(loResult.getBien()){");lsText.append(JUtiles.msRetornoCarro); lsText.append(" if(lbIsMismaClave){");lsText.append(JUtiles.msRetornoCarro); lsText.append(" msCodigoRelacionado = getClave();");lsText.append(JUtiles.msRetornoCarro); lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); lsText.append(" } ");lsText.append(JUtiles.msRetornoCarro); lsText.append(" return loResult;");lsText.append(JUtiles.msRetornoCarro); lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); lsText.append(" public IResultado borrar() throws Exception {");lsText.append(JUtiles.msRetornoCarro); lsText.append(" IResultado loResult = moList.borrar(true);");lsText.append(JUtiles.msRetornoCarro); lsText.append(" return loResult;");lsText.append(JUtiles.msRetornoCarro); lsText.append(" }");lsText.append(JUtiles.msRetornoCarro); if(loCampos.size()<moProyecto.getOpciones().getCamposMinimosTodosModulos()){ lsText.append(JGeneradorJ2Table.getProyectoTabla(loTabla, moProyecto)); } lsText.append("}"); return lsText.toString(); } public String getRutaRelativa() { return moUtiles.getPaqueteExtend(); } public String getNombre() { return moUtiles.getNombreTablaExtends(moConex.getTablaActual()) + ".java"; } public boolean isGeneral() { return false; } public String getNombreModulo() { return "JTEETable"; } public JModuloProyectoParametros getParametros() { return new JModuloProyectoParametros(); } }
package sqlancer.cockroachdb.ast; import sqlancer.visitor.UnaryOperation; public class CockroachDBAlias implements UnaryOperation<CockroachDBExpression>, CockroachDBExpression { private CockroachDBExpression expr; private String alias; public CockroachDBAlias(CockroachDBExpression expr, String alias) { this.expr = expr; this.alias = alias; } @Override public CockroachDBExpression getExpression() { return expr; } @Override public String getOperatorRepresentation() { return " as " + alias; } @Override public OperatorKind getOperatorKind() { return OperatorKind.POSTFIX; } @Override public boolean omitBracketsWhenPrinting() { return true; } }