hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
5ea2c927c3b5abb0478d0f737fc104a08a7b5bf6
11,750
package com.rosemeire.deconti.bestmeal.RecipeSecondNavigation; /* **************************************************************************** /* Copyright (C) 2016 The Android Open Source Project /* /* Licensed under the Apache License, Version 2.0 (the "License"); /* you may not use this file except in compliance with the License. /* You may obtain a copy of the License at /* /* http://www.apache.org/licenses/LICENSE-2.0 /* /* Unless required by applicable law or agreed to in writing, software /* distributed under the License is distributed on an "AS IS" BASIS, /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /* See the License for the specific language governing permissions and /* limitations under the License. /* **************************************************************************** /* UDACITY Android Developer NanoDegree Program /* Created by Rosemeire Deconti on 02/01/2019 /* ****************************************************************************/ import android.content.Context; import android.content.Intent; import android.net.Uri; import android.speech.tts.TextToSpeech; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.rosemeire.deconti.bestmeal.ApplicationSupport.SupportCheckNetworkAvailability; import com.rosemeire.deconti.bestmeal.ApplicationSupport.SupportMessageToast; import com.rosemeire.deconti.bestmeal.DatabaseModel.RecipeInstructionsModel; import com.rosemeire.deconti.bestmeal.R; import com.rosemeire.deconti.bestmeal.RecipeTool.RecipeToolMaintenanceInstructionsActivity; import com.rosemeire.deconti.bestmeal.RecipeTool.RecipeToolTalkerActivity; import java.util.List; import java.util.Locale; import static com.rosemeire.deconti.bestmeal.ApplicationDefinitions.ApplicationDatabaseDefinitions.CRUD_TYPE_U; import static com.rosemeire.deconti.bestmeal.ApplicationDefinitions.ApplicationDatabaseDefinitions.FILE_TYPE; import static com.rosemeire.deconti.bestmeal.ApplicationDefinitions.ApplicationDatabaseDefinitions.PATH_INSTRUCTIONS_1; import static com.rosemeire.deconti.bestmeal.ApplicationDefinitions.ApplicationDatabaseDefinitions.sTypeCRUD; import static com.rosemeire.deconti.bestmeal.ApplicationDefinitions.ApplicationGeneralDefinitions.sCurrentRecipeAuthor; import static com.rosemeire.deconti.bestmeal.ApplicationDefinitions.ApplicationGeneralDefinitions.sCurrentRecipeInstructionNumber; import static com.rosemeire.deconti.bestmeal.ApplicationDefinitions.ApplicationGeneralDefinitions.sCurrentRecipeInstructionPhoto; import static com.rosemeire.deconti.bestmeal.ApplicationDefinitions.ApplicationGeneralDefinitions.sCurrentRecipeInstructionText; import static com.rosemeire.deconti.bestmeal.ApplicationDefinitions.ApplicationGeneralDefinitions.sCurrentUserFirebaseUid; import static com.rosemeire.deconti.bestmeal.ApplicationDefinitions.ApplicationGeneralDefinitions.sReturnCode; /* ************************************************************************************************/ /* *** Treat recycler view /* ************************************************************************************************/ public class RecipeSecondNavigationInstructionsRecyclerAdapter extends RecyclerView.Adapter<RecipeSecondNavigationInstructionsRecyclerAdapter.ViewHolder> { private final List<RecipeInstructionsModel> mValues; private final Context mContext; private Intent intent; private TextToSpeech textToSpeech; /* ********************************************************************************************/ /* *** Load data to update recycler view /* ********************************************************************************************/ RecipeSecondNavigationInstructionsRecyclerAdapter(List<RecipeInstructionsModel> items, RecipeSecondNavigationInstructionsFragment.OnListFragmentInteractionListener listener, Context context) { mValues = items; @SuppressWarnings("UnnecessaryLocalVariable") RecipeSecondNavigationInstructionsFragment.OnListFragmentInteractionListener mListener = listener; mContext = context; } /* ********************************************************************************************/ /* *** Recycler view OnCreate /* ********************************************************************************************/ @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recipe_second_navigation_fragment_instructions_item, parent, false); textToSpeech = new TextToSpeech(parent.getContext(), new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if (status != TextToSpeech.ERROR) { textToSpeech.setLanguage(Locale.US); } } }); return new ViewHolder(view); } /* ********************************************************************************************/ /* *** Update recycler view /* ********************************************************************************************/ @Override public void onBindViewHolder(@NonNull final ViewHolder holder, int position) { // ................................................................. Get value from position RecipeInstructionsModel model = mValues.get(position); // .................................................................... Set data from holder holder.recipeDetailInstructionsModelItem = model; holder.textView_InstructionsText.setText(model.getRecipe_instructions_text()); holder.textView_InstructionNumber.setText(model.getRecipe_instructions_number()); // ................................................................ Obtain photo from recipe obtainRecipePhoto(holder, mContext); sCurrentRecipeInstructionNumber = holder.textView_InstructionNumber.getText().toString().trim(); sCurrentRecipeInstructionPhoto = model.getRecipe_instructions_photo(); obtainRecipePhoto(holder, mContext); // ........................................................ Save data to maintenance classes sCurrentRecipeInstructionText = holder.textView_InstructionsText.getText().toString().trim(); sCurrentRecipeInstructionNumber = holder.textView_InstructionNumber.getText().toString().trim(); /* ****************************************************************************************/ /* *** Treat click on button HANDS OFF /* ****************************************************************************************/ holder.imageButton_handsOff.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View view) { sCurrentRecipeInstructionText = holder.textView_InstructionsText.getText().toString(); intent = new Intent(view.getContext(), RecipeToolTalkerActivity.class); mContext.startActivity(intent); } }); /* ****************************************************************************************/ /* *** Treat click on button EDIT /* ****************************************************************************************/ holder.imageButton_edit.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View view) { sReturnCode = SupportCheckNetworkAvailability.isNetworkAvailable(mContext); if (!sReturnCode) { new SupportMessageToast(mContext, mContext.getString(R.string.message_network_not_available)); }else { if (sCurrentRecipeAuthor.equals(sCurrentUserFirebaseUid)) { sTypeCRUD = CRUD_TYPE_U; new RecipeToolMaintenanceInstructionsActivity(); } else { new SupportMessageToast(mContext, mContext.getString(R.string.message_recipe_not_yours)); } } } }); /* ****************************************************************************************/ /* *** Treat click on ITEM /* ****************************************************************************************/ holder.mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); } /* ********************************************************************************************/ /* *** Update recipe photo /* ********************************************************************************************/ private void obtainRecipePhoto(final ViewHolder holder, final Context context) { StorageReference storageReference = FirebaseStorage.getInstance().getReference().child(PATH_INSTRUCTIONS_1).child(sCurrentRecipeInstructionPhoto + FILE_TYPE); storageReference.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() { @Override public void onComplete(@NonNull Task<Uri> task) { if (task.isSuccessful()) { Glide.with(context) .load(task.getResult()) .apply(RequestOptions.centerCropTransform()) .into(holder.imageView_photo); } } }); } /* ********************************************************************************************/ /* *** Get Recycler View Size /* ********************************************************************************************/ @Override public int getItemCount() { return mValues.size(); } /* ********************************************************************************************/ /* *** A ViewHolder describes an item view and metadata about its place within the RecyclerView /* ********************************************************************************************/ public class ViewHolder extends RecyclerView.ViewHolder { public final View mView; public final ImageView imageView_photo; public final ImageButton imageButton_edit; final ImageButton imageButton_handsOff; final TextView textView_InstructionsText; final TextView textView_InstructionNumber; RecipeInstructionsModel recipeDetailInstructionsModelItem; public ViewHolder(View view) { super(view); mView = view; imageView_photo = view.findViewById(R.id.imageView_InstructionsPhoto); imageButton_handsOff = view.findViewById(R.id.button_talker); imageButton_edit = view.findViewById(R.id.imageButton_edit); textView_InstructionsText = view.findViewById(R.id.textView_InstructionsText); textView_InstructionNumber = view.findViewById(R.id.textView_IngredientNumber); } } }
47.379032
196
0.570213
3655d43708b454c65f422c1e6468d4d261386bb9
948
package com.exmaple.session; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.*; import java.io.IOException; @WebServlet(name = "sessionDemo2", value = "/sessionDemo2") public class SessionDemo2 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); //希望客户端关闭后,session也能相同,创建Cookie Cookie cookie = new Cookie("JSSIONID", session.getId()); cookie.setMaxAge(3600); response.addCookie(cookie); Object msg = session.getAttribute("msg"); System.out.println(msg); } }
35.111111
123
0.71097
3e39fd0e695d285cfcb00dee241dc4c0104b3f3f
7,141
package xworker.net.jsch; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xmeta.ActionContext; import org.xmeta.ActionException; import org.xmeta.Thing; import org.xmeta.World; import org.xmeta.util.OgnlUtil; import org.xmeta.util.UtilMap; import org.xmeta.util.UtilString; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import freemarker.template.TemplateException; import ognl.OgnlException; import xworker.task.UserTask; import xworker.task.UserTaskManager; import xworker.util.StringUtils; public class Exec { private static Logger logger = LoggerFactory.getLogger(Exec.class); public static Session getSession(ActionContext actionContext) throws OgnlException{ Thing self = (Thing) actionContext.get("self"); String sessionVar = self.getStringBlankAsNull("sessionVar"); if(sessionVar != null){ return (Session) OgnlUtil.getValue(self, "sessionVar", actionContext); } String sessionPath= UtilString.getString(self, "sessionPath", actionContext); if(sessionPath != null){ Thing thing = World.getInstance().getThing(sessionPath); if(thing != null){ return (Session) thing.doAction("create", actionContext); } } Thing thing = self.getThing("Session@0"); if(thing != null){ return (Session) thing.doAction("create", actionContext); } thing = self.getThing("AppSession@0"); if(thing != null){ return (Session) thing.doAction("create", actionContext); } return null; } /** * 相关事物定义的session是否需要关闭,如果从变量得到的session不需要关闭,其他情况都需要关闭。 * * @param self * @return */ public static boolean isSessionNeedClose(Thing self){ String sessionVar = self.getStringBlankAsNull("sessionVar"); if(sessionVar != null && !self.getBoolean("closeSession")){ return false; }else{ return true; } } public static String getCommand(ActionContext actionContext) throws IOException, TemplateException{ Thing self = (Thing) actionContext.get("self"); return StringUtils.getString(self, "command", actionContext); } public static Object run(ActionContext actionContext) throws JSchException, OgnlException, IOException, InterruptedException{ Thing self = (Thing) actionContext.get("self"); boolean runBackground = self.getBoolean("runBackground"); Session session = (Session) self.doAction("getSession", actionContext); if(session == null){ throw new ActionException("Jsch Session can not be null, path=" + self.getMetadata().getPath()); } String command = (String) self.doAction("getCommand", actionContext); if(command == null){ throw new ActionException("Command can not be null, path=" + self.getMetadata().getPath()); } Channel channel = session.openChannel("exec"); ((ChannelExec)channel).setCommand(command.replace("\r", "").trim()); channel.setInputStream(null); self.doAction("initIo", actionContext, UtilMap.toMap(new Object[]{"session", session, "channel", channel})); InputStream in = channel.getInputStream(); channel.connect(); try{ OutputStream outputStream = null; String outputStreamStr = self.getStringBlankAsNull("outputStream"); if(outputStreamStr != null){ outputStream = (OutputStream) OgnlUtil.getValue(self, "outputStream", actionContext); } UserTask task = UserTaskManager.createTask(self, false); task.start(); task.setDetail("session=" + session + "<br/>command=" + command); if(runBackground){ ExecTask exec = new ExecTask(self, task, session, channel, outputStream, actionContext, self.getBoolean("closeSession"), in); new Thread(exec).start(); return task; }else{ try { return self.doAction("afterConnected", actionContext, UtilMap.toMap(new Object[]{"session", session, "channel", channel, "outputStream", outputStream, "in", in, "task", task})); }finally { task.finished(); } } }finally{ if(!runBackground){ channel.disconnect(); if(self.getBoolean("closeSession")){ session.disconnect(); } } } } static class ExecTask implements Runnable{ UserTask task; Thing self; OutputStream outputStream; Channel channel; Session session; ActionContext actionContext; boolean closeSession = false; InputStream in; public ExecTask(Thing self, UserTask task, Session session, Channel channel, OutputStream outputStream, ActionContext actionContext, boolean closeSession, InputStream in){ this.self = self; this.task = task; this.outputStream = outputStream; this.channel = channel; this.session = session; this.actionContext = actionContext; this.closeSession = closeSession; this.in = in; } public void run(){ try{ self.doAction("afterConnected", actionContext, UtilMap.toMap(new Object[]{ "session", session, "channel", channel, "outputStream", outputStream, "task", task, "in", in})); }catch(Exception e){ logger.error("exec error, path=" + self.getMetadata().getPath(), e); }finally{ task.finished(); channel.disconnect(); if(closeSession){ session.disconnect(); } } } } public static void initIo(ActionContext actionContext) throws OgnlException{ Thing self = (Thing) actionContext.get("self"); //Session session = (Session) actionContext.get("session"); Channel channel = (Channel) actionContext.get("channel"); String errStream = self.getStringBlankAsNull("errStream"); if(errStream != null){ ((ChannelExec)channel).setErrStream((OutputStream) OgnlUtil.getValue(self, "errStream", actionContext), true); }else{ ((ChannelExec)channel).setErrStream(System.err, true); } } public static Object afterConnected(ActionContext actionContext) throws IOException{ Thing self = (Thing) actionContext.get("self"); // Session session = (Session) actionContext.get("session"); Channel channel = (Channel) actionContext.get("channel"); InputStream in = (InputStream) actionContext.get("in"); OutputStream out = (OutputStream) actionContext.get("outputStream"); UserTask task = (UserTask) actionContext.get("task"); boolean returnString = false; if(out == null){ out = new ByteArrayOutputStream(); returnString = true; } byte[] tmp = new byte[1024]; while (true) { while(in.available()>0){ int i = in.read(tmp, 0, 1024); if (i <= 0) break; out.write(tmp, 0, i); out.flush(); } if (channel.isClosed()) { if (in.available() > 0){ continue; } //logger.info("channel closed, exitStatus=" + channel.getExitStatus() + ", thing=" + self.getMetadata().getPath()); break; } if(task != null && task.getStatus() == UserTask.CANCEL){ task.terminated(); break; } try{Thread.sleep(100);}catch(Exception ee){} } if(returnString){ return new String(((ByteArrayOutputStream) out).toByteArray()); }else{ return null; } } }
31.320175
173
0.69318
f6b76a5369de3576481aee433e6537cd3a9e26b0
3,881
package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.bian.dto.CRMerchantAcquiringFacilityFulfillmentArrangementUpdateInputModelMerchantAcquiringFacilityFulfillmentArrangementInstanceRecord; import javax.validation.Valid; /** * CRMerchantAcquiringFacilityFulfillmentArrangementUpdateOutputModel */ public class CRMerchantAcquiringFacilityFulfillmentArrangementUpdateOutputModel { private CRMerchantAcquiringFacilityFulfillmentArrangementUpdateInputModelMerchantAcquiringFacilityFulfillmentArrangementInstanceRecord merchantAcquiringFacilityFulfillmentArrangementInstanceRecord = null; private String merchantAcquiringFacilityFulfillmentArrangementUpdateActionTaskReference = null; private Object merchantAcquiringFacilityFulfillmentArrangementUpdateActionTaskRecord = null; private Object updateResponseRecord = null; /** * Get merchantAcquiringFacilityFulfillmentArrangementInstanceRecord * @return merchantAcquiringFacilityFulfillmentArrangementInstanceRecord **/ public CRMerchantAcquiringFacilityFulfillmentArrangementUpdateInputModelMerchantAcquiringFacilityFulfillmentArrangementInstanceRecord getMerchantAcquiringFacilityFulfillmentArrangementInstanceRecord() { return merchantAcquiringFacilityFulfillmentArrangementInstanceRecord; } public void setMerchantAcquiringFacilityFulfillmentArrangementInstanceRecord(CRMerchantAcquiringFacilityFulfillmentArrangementUpdateInputModelMerchantAcquiringFacilityFulfillmentArrangementInstanceRecord merchantAcquiringFacilityFulfillmentArrangementInstanceRecord) { this.merchantAcquiringFacilityFulfillmentArrangementInstanceRecord = merchantAcquiringFacilityFulfillmentArrangementInstanceRecord; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to an update service call * @return merchantAcquiringFacilityFulfillmentArrangementUpdateActionTaskReference **/ public String getMerchantAcquiringFacilityFulfillmentArrangementUpdateActionTaskReference() { return merchantAcquiringFacilityFulfillmentArrangementUpdateActionTaskReference; } public void setMerchantAcquiringFacilityFulfillmentArrangementUpdateActionTaskReference(String merchantAcquiringFacilityFulfillmentArrangementUpdateActionTaskReference) { this.merchantAcquiringFacilityFulfillmentArrangementUpdateActionTaskReference = merchantAcquiringFacilityFulfillmentArrangementUpdateActionTaskReference; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The update service call consolidated processing record * @return merchantAcquiringFacilityFulfillmentArrangementUpdateActionTaskRecord **/ public Object getMerchantAcquiringFacilityFulfillmentArrangementUpdateActionTaskRecord() { return merchantAcquiringFacilityFulfillmentArrangementUpdateActionTaskRecord; } public void setMerchantAcquiringFacilityFulfillmentArrangementUpdateActionTaskRecord(Object merchantAcquiringFacilityFulfillmentArrangementUpdateActionTaskRecord) { this.merchantAcquiringFacilityFulfillmentArrangementUpdateActionTaskRecord = merchantAcquiringFacilityFulfillmentArrangementUpdateActionTaskRecord; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: Details of the Update action service response * @return updateResponseRecord **/ public Object getUpdateResponseRecord() { return updateResponseRecord; } public void setUpdateResponseRecord(Object updateResponseRecord) { this.updateResponseRecord = updateResponseRecord; } }
47.329268
270
0.870652
7f358b5596742cad116bc760354fee0696c436fc
234
package com.ruk.sid.sheduller; public class MyJobHelper { private String someStr; public MyJobHelper(String s) { this.someStr = s; } public String getSomeStr() { return someStr; } }
15.6
35
0.589744
804c96b86892cdf2ed51826fa9efbe0e46e00c4e
1,155
import java.util.ArrayList; import java.util.List; import static java.lang.Math.abs; public class Car { private List<Ride> rides = new ArrayList<>(); private int currentRow, currentCol; private int t; public Car(){ currentRow = 0; currentCol = 0; t = 0; } public int getRangeToRide(Ride ride){ return (abs (currentRow - ride.getStartCol())) + abs(currentCol - ride.getStartRow()); } public void addRideToCar(Ride ride){ rides.add(ride); } public int getCurrentRow() { return currentRow; } public void setCurrentRow(int currentRow) { this.currentRow = currentRow; } public int getCurrentCol() { return currentCol; } public void setCurrentCol(int currentCol) { this.currentCol = currentCol; } public void setT(int t) { this.t = t; } public int getT() { return t; } public String rideToString(){ String output = "" + rides.size(); for (Ride ride : rides) output += " " + ride.getRideId(); output += "\n"; return output; } }
20.625
93
0.57316
a198c03d723b0c60f25ffb8919ad81d91c7d9dcb
1,760
/* This file was generated by SableCC (http://www.sablecc.org/). */ package drlc.node; import drlc.analysis.*; @SuppressWarnings("nls") public final class ANotUnaryOp extends PUnaryOp { private TNot _not_; public ANotUnaryOp() { // Constructor } public ANotUnaryOp( @SuppressWarnings("hiding") TNot _not_) { // Constructor setNot(_not_); } @Override public Object clone() { return new ANotUnaryOp( cloneNode(this._not_)); } @Override public void apply(Switch sw) { ((Analysis) sw).caseANotUnaryOp(this); } public TNot getNot() { return this._not_; } public void setNot(TNot node) { if(this._not_ != null) { this._not_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._not_ = node; } @Override public String toString() { return "" + toString(this._not_); } @Override void removeChild(@SuppressWarnings("unused") Node child) { // Remove child if(this._not_ == child) { this._not_ = null; return; } throw new RuntimeException("Not a child."); } @Override void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild) { // Replace child if(this._not_ == oldChild) { setNot((TNot) newChild); return; } throw new RuntimeException("Not a child."); } }
18.333333
107
0.515909
9011c4de10c4bd74883ff8b151a9cfa3fec060a4
748
package TotalGoodsSold; import java.io.IOException; import mappers.Tuple; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; public class TotalGoodsSoldReducer extends Reducer<Text, Tuple, Text, IntWritable> { @Override public void reduce(Text key, Iterable<Tuple> values, Context context) throws IOException, InterruptedException { int finalSum = 0; String[] good = null; for(Tuple value: values){ if(value.getType().equals("Goods")){ good = value.getContent().split(","); }else if(value.getType().equals("ItemsToGoods")){ finalSum += 1; } } context.write(new Text(key.toString()+","+good[0]+","+good[1]), new IntWritable(finalSum)); } }
27.703704
115
0.71123
9da8ec10e4e774301484493a0d6913cb3c0e9017
1,015
//******************************************************************** // Volunteer.java // // Represents a staff member that works as a volunteer. //******************************************************************** // Checks to see if the staffmember is a volunteer. public class Volunteer extends StaffMember { //----------------------------------------------------------------- // Constructor: Sets up this volunteer using the specified // information. //----------------------------------------------------------------- public Volunteer(String eName, String eAddress, String ePhone) { super(eName, eAddress, ePhone); } //----------------------------------------------------------------- // Returns a zero pay value for this volunteer. //----------------------------------------------------------------- public double pay() { return 0.0; } // Sets vacation days to 0. public int vacation() { return 0; } }
30.757576
71
0.363547
6c5a8f77676aaa21bcf59523341a3089b172252b
465
package demo4031.model; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableLogic; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Getter; import lombok.Setter; /** * @author noear 2022/4/5 created */ @Setter @Getter @TableName("user") public class UserModel { @TableId("id") Long id; Long userId; String nickname; String password; // @TableLogic Integer deleted; }
19.375
54
0.735484
d4c6d3303040fc9dab7b28683aff71c364d236de
372
package de.wigenso.springboot; public class TestParam { private Integer int1; private String str1; public Integer getInt1() { return int1; } public void setInt1(Integer int1) { this.int1 = int1; } public String getStr1() { return str1; } public void setStr1(String str1) { this.str1 = str1; } }
16.173913
39
0.58871
009e38e9d280d84ad2a7ded3aa97ec27639bb25a
12,801
package com.github.qishi604.mdviewer.util; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.animation.PropertyValuesHolder; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.ResultReceiver; import android.text.Html; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.Display; import android.view.View; import android.view.ViewTreeObserver; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.view.inputmethod.InputMethodManager; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import java.util.List; /** * UI工具类 * * @author Lin * @version V1.0 * @since 16/5/26 */ public final class ViewUtils { public static final DisplayMetrics DISPLAY_METRICS = Resources.getSystem().getDisplayMetrics(); private ViewUtils() { } /** * 获取屏幕宽度 * * @return 屏幕宽度 */ public static int getWidth() { return DISPLAY_METRICS.widthPixels; } /** * 获取屏幕高度 * * @return 屏幕高度 */ public static int getHeight() { return DISPLAY_METRICS.heightPixels; } /** * dp2px(四舍五入) * * @param dp * @return */ public static int dp2Px(float dp) { return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, DISPLAY_METRICS) + 0.5f); } public static int sp2Px(float sp) { return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, DISPLAY_METRICS) + 0.5f); } /** * 获取控件宽 */ public static int getWidth(View view) { measureView(view); return view.getMeasuredWidth(); } /** * 获取控件高 */ public static int getHeight(View view) { measureView(view); return view.getMeasuredHeight(); } /** * 测量View */ private static void measureView(View view) { int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); view.measure(w, h); } /* * 设图片背景 */ public static void setBackground(View view, Drawable d) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { view.setBackground(d); } else { view.setBackgroundDrawable(d); } } /** * 设置选中某一些 下拉框 * * @param spinner * @param selection * @return void * kibey 2013-10-12 下午3:47:51 */ public static void setSelection(Spinner spinner, Object selection) { setSelection(spinner, selection.toString()); } /** * 设置选中某一些 下拉框 * * @param spinner * @param selection * @return void * kibey 2013-10-12 下午3:47:34 */ public static void setSelection(Spinner spinner, String selection) { final int count = spinner.getCount(); for (int i = 0; i < count; i++) { String item = spinner.getItemAtPosition(i).toString(); if (item.equalsIgnoreCase(selection)) { spinner.setSelection(i); } } } /** * 显示软键盘,通过获取activity当前获取焦点的View来显示软键盘 * Activity没有获取焦点的View,则不能显示出软键盘 * * @param activity Activity */ public static void showSoftKeyboard(Activity activity) { if (null != activity && null != activity.getCurrentFocus()) { showSoftKeyboard(activity.getCurrentFocus()); } } /** * 显示软键盘 * * @param view * @return void * kibey 2013-10-12 下午3:46:44 */ public static void showSoftKeyboard(View view) { showSoftKeyboard(view, null); } /** * 显示软键盘 * * @param view * @param resultReceiver * @return void * kibey 2013-10-12 下午3:47:19 */ public static void showSoftKeyboard(View view, ResultReceiver resultReceiver) { Configuration config = view.getContext().getResources().getConfiguration(); if (config.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) { InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); if (resultReceiver != null) { imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT, resultReceiver); } else { imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT); } } } /** * 隐藏软键盘,通过获取activity当前获取焦点的View来隐藏软键盘 * Activity没有获取焦点的View,则不能隐藏软键盘 * * @param activity Activity */ public static void hideSoftKeyboard(Activity activity) { if (null != activity && null != activity.getCurrentFocus()) { hideSoftKeyboard(activity.getCurrentFocus()); } } /** * 关闭软键盘 * * @param view View */ public static void hideSoftKeyboard(View view) { if (null == view) { return; } Context context = view.getContext(); if (null == context || null == view.getWindowToken()) { return; } InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); if (inputMethodManager != null) { inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } /** * 截屏 * * @param activity * @return Bitmap * kibey 2013-10-26 下午2:39:01 */ public static Bitmap shot(Activity activity) { View view = activity.getWindow().getDecorView(); Display display = activity.getWindowManager().getDefaultDisplay(); view.layout(0, 0, display.getWidth(), display.getHeight()); return getBitmapFromView(view); } /** * 获得Intent中跳转前Activity的Icon,若无,则返回App图标 * * @param context * @param i * @return */ public static Drawable getIconForIntent(final Context context, Intent i) { final PackageManager pm = context.getPackageManager(); final List<ResolveInfo> infos = pm.queryIntentActivities(i, PackageManager.MATCH_DEFAULT_ONLY); if (infos.size() > 0) { return infos.get(0).loadIcon(pm); } return null; } /** * 代码实现旋转的菊花效果 * * @param imageView 需要旋转的图片 * @param drawable 旋转菊花 * @return void * kibey 2014-2-21 下午5:09:58 */ public static void startAnim(ImageView imageView, int drawable) { try { imageView.setScaleType(ImageView.ScaleType.CENTER); imageView.setImageResource(drawable); AnimationSet animationSet = new AnimationSet(false); RotateAnimation rotateAnimation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); rotateAnimation.setDuration(2000); rotateAnimation.setInterpolator(new LinearInterpolator()); rotateAnimation.setRepeatMode(Animation.RESTART); rotateAnimation.setRepeatCount(Animation.INFINITE); animationSet.addAnimation(rotateAnimation); imageView.setAnimation(animationSet); } catch (Exception e) { } } /** * 停止自定义菊花的旋转 * * @param imageView * @return void * kibey 2014-2-21 下午5:10:40 */ public static void stopAnim(ImageView imageView) { try { imageView.clearAnimation(); imageView.setImageBitmap(null); } catch (Exception e) { } } /** * 加载html/普通文字,链接可点击 * <p> * Populate the given {@link TextView} with the requested text, formatting through {@link Html#fromHtml(String)} * when applicable. Also sets {@link TextView#setMovementMethod} so inline links are handled. */ public static void setTextMaybeHtml(TextView view, String text) { if (TextUtils.isEmpty(text)) { view.setText(""); return; } if (text.contains("<") && text.contains(">")) { view.setText(Html.fromHtml(text)); view.setMovementMethod(LinkMovementMethod.getInstance()); } else { view.setText(text); } } /** * 移除所有监听 * * @param view * @param listener */ public static void removeOnGlobalLayoutListener(View view, ViewTreeObserver.OnGlobalLayoutListener listener) { if (null != view && null != listener) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { view.getViewTreeObserver().removeOnGlobalLayoutListener(listener); } else { view.getViewTreeObserver().removeGlobalOnLayoutListener(listener); } } } public static void hideNavigationBar(Activity activity) { int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar | View.SYSTEM_UI_FLAG_FULLSCREEN; // hide status bar if (Build.VERSION.SDK_INT >= 19) { uiFlags |= 0x00001000; //SYSTEM_UI_FLAG_IMMERSIVE_STICKY: hide navigation bars - compatibility: building API level is lower thatn 19, use magic number directly for higher API target level } else { uiFlags |= View.SYSTEM_UI_FLAG_LOW_PROFILE; } try { activity.getWindow().getDecorView().setSystemUiVisibility(uiFlags); } catch (Exception e) { e.printStackTrace(); } } public static void showNavigationBar(Activity activity) { int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_VISIBLE; try { activity.getWindow().getDecorView().setSystemUiVisibility(uiFlags); } catch (Exception e) { e.printStackTrace(); } } /** * Rect在屏幕上去掉状态栏高度的绝对位置 */ public static Rect getViewAbsRect(View view, int parentX, int parentY) { int[] loc = new int[2]; view.getLocationInWindow(loc); Rect rect = new Rect(); rect.set(loc[0], loc[1], loc[0] + view.getMeasuredWidth(), loc[1] + view.getMeasuredHeight()); rect.offset(-parentX, -parentY); return rect; } /** * 向上翻转 */ static PropertyValuesHolder mPullUpHolder = PropertyValuesHolder.ofFloat("rotation", 0f, 180f); /** * 向下翻转 */ static PropertyValuesHolder mPullDownHolder = PropertyValuesHolder.ofFloat("rotation", 180f, 360f); /** * 展开动画 * * @param view 需要动画的对象 * @param isExpand true向上旋转,false向下旋转 */ public static void expandAnimator(final View view, boolean isExpand) { ObjectAnimator objectAnimator; if (isExpand) { objectAnimator = ObjectAnimator.ofPropertyValuesHolder(view, mPullUpHolder); } else { objectAnimator = ObjectAnimator.ofPropertyValuesHolder(view, mPullDownHolder); } // 防止重复点击 objectAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { view.setClickable(false); } @Override public void onAnimationEnd(Animator animation) { view.setClickable(true); } }); objectAnimator.start(); } /** * 获取view的图片 * * @param view * @return */ public static Bitmap getBitmapFromView(View view) { view.setDrawingCacheEnabled(true); view.buildDrawingCache(); //启用DrawingCache并创建位图 Bitmap bitmap = view.getDrawingCache(); //创建一个DrawingCache的拷贝,因为DrawingCache得到的位图在禁用后会被回收 if (null != bitmap && !bitmap.isRecycled()) { bitmap = Bitmap.createBitmap(bitmap); } view.setDrawingCacheEnabled(false); //禁用DrawingCahce否则会影响性能 return bitmap; } }
29.700696
202
0.619639
5eeab89295b641842dc55ec0f70269e19c6d2bad
937
package com.rongyan.hpmessage.devicecenter; import com.rongyan.hpmessage.database.DataBaseOpenHelper; import com.rongyan.hpmessage.item.AppItem; import android.content.Context; import android.util.Log; public class AppSysncThread extends Thread { private String mPkgname; private DataBaseOpenHelper mDataBaseOpenHelper; public AppSysncThread(Context context, String pkgname) { mPkgname = pkgname; mDataBaseOpenHelper = DataBaseOpenHelper.getInstance(context); } @Override public void run() { synchronized (this) { AppInfoOprea appInfoUtils = AppInfoOprea.getIntance(); AppItem item = appInfoUtils.isInInstalledApp(mPkgname); if (item != null) { item.setUseRate(item.getUseRate() + 1); synchronized (this) { if (mDataBaseOpenHelper.haveAppInfo(mPkgname)) { mDataBaseOpenHelper.UpdateAppInfoString(item); } else { mDataBaseOpenHelper.SaveUserInfo(item); } } } } } }
24.657895
64
0.744931
3093033bb61174fb9aa335afc98ce3223159d90b
404
package com.zeny.springcloud.config; import feign.Logger; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @ClassName FeignConfig * @Description TODO * @Author zeny * @Date 2020/4/4 0004 18:41 */ @Configuration public class FeignConfig { @Bean public Logger.Level logger() { return Logger.Level.FULL; } }
18.363636
60
0.725248
33536c2d5b791f60e17f0fb9c91c00fa4513cf52
4,254
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.jellytools.modules.editor; import java.awt.event.KeyEvent; import javax.swing.JButton; import javax.swing.JPanel; import org.netbeans.jellytools.EditorOperator; import org.netbeans.jemmy.operators.ContainerOperator; import org.netbeans.jemmy.operators.JButtonOperator; import org.netbeans.jemmy.operators.JCheckBoxOperator; import org.netbeans.jemmy.operators.JComboBoxOperator; import org.netbeans.jemmy.operators.JTextComponentOperator; import org.netbeans.modules.editor.search.SearchBar; /** * * @author jprox */ public class SearchBarOperator extends EditorPanelOperator { private JTextComponentOperator findOp; private JButtonOperator nextButtonOp; private JButtonOperator prevButtonOp; private JButtonOperator closeButtonOp; private JCheckBoxOperator match; private JCheckBoxOperator whole; private JCheckBoxOperator regular; private JCheckBoxOperator highlight; private JCheckBoxOperator wrap; private SearchBarOperator() { super(SearchBar.class); } @Override protected void invokeAction(EditorOperator editorOperator) { editorOperator.pushKey(KeyEvent.VK_F, KeyEvent.CTRL_DOWN_MASK); } @Override protected JButton getExpandButton() { if(buttons.size()<=3) return null; if(buttons.size()==4) return buttons.get(2); return null; } public static SearchBarOperator invoke(EditorOperator editorOperator) { SearchBarOperator sbo = new SearchBarOperator(); sbo.openPanel(editorOperator); return sbo; } public static SearchBarOperator getPanel(EditorOperator editorOperator) { SearchBarOperator sbo = new SearchBarOperator(); JPanel panel = sbo.getOpenedPanel(editorOperator); if(panel==null) throw new IllegalArgumentException("Panel is not found"); return sbo; } public JTextComponentOperator findCombo() { if (findOp == null) { findOp = new JTextComponentOperator(getContainerOperator()); } return findOp; } public JButtonOperator prevButton() { if (prevButtonOp == null) { prevButtonOp = new JButtonOperator(getButton(0)); } return prevButtonOp; } public JButtonOperator nextButton() { if (nextButtonOp == null) { nextButtonOp = new JButtonOperator(getButton(1)); } return nextButtonOp; } public JButtonOperator closeButton() { if (closeButtonOp == null) { closeButtonOp = new JButtonOperator(getButton(buttons.size()-1)); } return closeButtonOp; } public JCheckBoxOperator matchCaseCheckBox() { return getCheckbox(0); } public JCheckBoxOperator highlightResultsCheckBox() { return getCheckbox(3); } public JCheckBoxOperator reqularExpressionCheckBox() { return getCheckbox(2); } public JCheckBoxOperator wholeWordsCheckBox() { return getCheckbox(1); } public JCheckBoxOperator wrapAroundCheckBox() { return getCheckbox(4); } void uncheckAll() { matchCaseCheckBox().setSelected(false); highlightResultsCheckBox().setSelected(false); reqularExpressionCheckBox().setSelected(false); // highlightResultsCheckBox().setSelected(false); // wrapAroundCheckBox().setSelected(false); } }
30.604317
81
0.698872
33942b661e3ac84e5e893abf6dc78842b3b22a41
14,376
package com.codedx.plugins.bamboo; import com.atlassian.bamboo.collections.ActionParametersMap; import com.atlassian.bamboo.task.AbstractTaskConfigurator; import com.atlassian.bamboo.task.TaskDefinition; import com.atlassian.bamboo.utils.error.ErrorCollection; import com.codedx.client.ApiClient; import com.codedx.client.ApiException; import com.codedx.client.api.Project; import com.codedx.client.api.ProjectsApi; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import javax.ws.rs.ProcessingException; import java.util.ArrayList; import java.util.List; import java.util.Map; public class CodeDxScanTaskConfigurator extends AbstractTaskConfigurator { private static final Logger _logger = Logger.getLogger(CodeDxScanTaskConfigurator.class); // Since much work was done surrounding saving invalid configs, lets keep the code and toggle it with a flag. private static final boolean ALLOW_SAVE_INVALID_CONFIG = true; private static final Severity[] severities = Severity.all; // Tracks if we are going into an edit after a failed save attempt and remembers the credentials the user put in private FailedCredentials failedSave = null; private static class FailedCredentials { private String useDefaults; private String url; private String apiKey; private String fingerprint; public boolean missingSelectedProject; public FailedCredentials(final ActionParametersMap params) { useDefaults = params.getString("useDefaults"); url = params.getString("url"); apiKey = params.getString("apiKey"); fingerprint = params.getString("fingerprint"); missingSelectedProject = StringUtils.isEmpty(params.getString("selectedProjectId")); if (url == null && Boolean.parseBoolean(useDefaults)) { url = emptyIfNull(ServerConfigManager.getUrl()); apiKey = emptyIfNull(ServerConfigManager.getApiKey()); fingerprint = emptyIfNull(ServerConfigManager.getFingerprint()); } } public void setContext(Map<String, Object> context) { context.put("useDefaults", useDefaults); context.put("url", url); context.put("apiKey", apiKey); context.put("fingerprint", fingerprint); } } @java.lang.Override public Map<String, String> generateTaskConfigMap(final ActionParametersMap params, final TaskDefinition previousTaskDefinition) { final Map<String, String> config = super.generateTaskConfigMap(params, previousTaskDefinition); _logger.info("generateTaskConfigMap(...) called"); // Save succeeded. Set this back to false. this.failedSave = null; config.put("useDefaults", params.getString("useDefaults")); config.put("url", params.getString("url")); config.put("apiKey", params.getString("apiKey")); config.put("fingerprint", params.getString("fingerprint")); config.put("analysisName", params.getString("analysisName")); config.put("selectedProjectId", params.getString("selectedProjectId")); config.put("includePaths", params.getString("includePaths")); config.put("excludePaths", params.getString("excludePaths")); config.put("toolOutputFiles", params.getString("toolOutputFiles")); config.put("waitForResults", params.getString("waitForResults")); config.put("selectedFailureSeverity", params.getString("selectedFailureSeverity")); config.put("onlyConsiderNewFindings", params.getString("onlyConsiderNewFindings")); return config; } public void validate(final ActionParametersMap params, final ErrorCollection errorCollection) { super.validate(params, errorCollection); _logger.info("validate(...) called"); if (ALLOW_SAVE_INVALID_CONFIG) { return; } // Will be set back to false in generateTaskConfigMap(...) if save succeeds this.failedSave = new FailedCredentials(params); final String analysisName = params.getString("analysisName"); if (StringUtils.isEmpty(analysisName)) { errorCollection.addError("analysisName", "Missing analysis name"); _logger.error("Missing analysis name"); } final String selectedProjectId = params.getString("selectedProjectId"); if (StringUtils.isEmpty(selectedProjectId)) { errorCollection.addError("selectedProjectId", "Missing selected project"); _logger.error("Missing selected project"); } final String includePaths = params.getString("includePaths"); if (StringUtils.isEmpty(includePaths)) { errorCollection.addError("includePaths", "Missing source and binary files"); _logger.error("Missing source and binary files"); } final String useDefaults = params.getString("useDefaults"); if (!Boolean.parseBoolean(useDefaults)) { final String url = params.getString("url"); if (url != null && !url.isEmpty()) { // Make sure the URL is valid if (!ServerConfigManager.isURLValid(url)) { errorCollection.addError("url", "Malformed URL"); _logger.error("Malformed URL"); } } else { errorCollection.addError("url", "Missing Code Dx URL"); _logger.error("Missing Code Dx URL"); } final String apiKey = params.getString("apiKey"); if (StringUtils.isEmpty(apiKey)) { errorCollection.addError("apiKey", "Missing Code Dx API key"); _logger.error("Missing Code Dx API key"); } } } private static List<Project> getProjectList(Map<String, Object> context) { _logger.info("getProjectList(...) called"); String url = null; String apiKey = null; String fingerprint = null; // We check defaultsSet in case the defaults were erased. We have what they used to be in the task configuration. if (context.get("useDefaults").equals("true") && ServerConfigManager.getDefaultsSet()) { url = ServerConfigManager.getUrl(); apiKey = ServerConfigManager.getApiKey(); fingerprint = ServerConfigManager.getFingerprint(); } else { url = context.get("url").toString(); apiKey = context.get("apiKey").toString(); fingerprint = context.get("fingerprint").toString(); } if (url == null || apiKey == null || url.isEmpty() || apiKey.isEmpty()) { _logger.info("Code Dx URL and API key are not configured"); context.put("reachabilityMessage", "Code Dx URL and API key are not configured"); return new ArrayList<Project>(); } ApiClient cdxApiClient = ServerConfigManager.getConfiguredClient(url, apiKey, fingerprint); ProjectsApi projectsApi = new ProjectsApi(); projectsApi.setApiClient(cdxApiClient); try { return projectsApi.getProjects().getProjects(); } catch (IllegalArgumentException e) { _logger.error(e); } catch (ApiException e) { _logger.error(e); } catch (ProcessingException e) { context.put("reachabilityMessage", "Connection refused. Please confirm that the URL is correct and that the Code Dx server is running."); _logger.error(e); } return new ArrayList<Project>(); } @Override public void populateContextForCreate(final Map<String, Object> context) { super.populateContextForCreate(context); _logger.info("populateContextForCreate(...) called"); boolean defaultsSet = ServerConfigManager.getDefaultsSet(); context.put("defaultsSet", String.valueOf(defaultsSet)); context.put("failedSave", String.valueOf(failedSave)); String defaultUrl = emptyIfNull(ServerConfigManager.getUrl()); String defaultApiKey = emptyIfNull(ServerConfigManager.getApiKey()); String defaultFingerprint = emptyIfNull(ServerConfigManager.getFingerprint()); context.put("useDefaults", String.valueOf(defaultsSet)); if (defaultsSet) { _logger.info("User has default Code Dx credentials saved"); context.put("url", defaultUrl); context.put("apiKey", defaultApiKey); context.put("fingerprint", defaultFingerprint); } else { _logger.info("User does not have default Code Dx credentials saved"); context.put("url", ""); context.put("apiKey", ""); context.put("fingerprint", ""); } context.put("defaultUrl", defaultUrl); context.put("defaultApiKey", defaultApiKey); context.put("defaultFingerprint", defaultFingerprint); context.put("analysisName", "Bamboo Analysis"); context.put("reachabilityMessage", ""); List<Project> projectList = getProjectList(context); context.put("projectList", projectList); if (projectList.size() > 0) { context.put("selectedProjectId", projectList.get(0).getId().toString()); } context.put("includePaths", "**"); context.put("excludePaths", ""); context.put("toolOutputFiles", ""); context.put("waitForResults", false); context.put("severities", severities); context.put("selectedFailureSeverity", severities[0]); context.put("onlyConsiderNewFindings", false); } @Override public void populateContextForEdit(Map<String, Object> context, TaskDefinition taskDefinition) { super.populateContextForEdit(context, taskDefinition); _logger.info("populateContextForEdit(...) called"); // Get saved user config Map<String, String> config = taskDefinition.getConfiguration(); // Keep track of weather or not we got here after failing to save a configuration context.put("failedSave", String.valueOf(failedSave)); // To populate the dropdown of severity thresholds context.put("severities", severities); // Boolean to denote weather or not the user set up default Code Dx server credentials on the admin page boolean defaultsSet = ServerConfigManager.getDefaultsSet(); context.put("defaultsSet", String.valueOf(defaultsSet)); // The default Code Dx server credentials - if they were set up by the user on the admin page String defaultUrl = emptyIfNull(ServerConfigManager.getUrl()); String defaultApiKey = emptyIfNull(ServerConfigManager.getApiKey()); String defaultFingerprint = emptyIfNull(ServerConfigManager.getFingerprint()); context.put("defaultUrl", defaultUrl); context.put("defaultApiKey", defaultApiKey); context.put("defaultFingerprint", defaultFingerprint); // Populate context from saved task config context.put("analysisName", config.get("analysisName")); context.put("includePaths", config.get("includePaths")); context.put("excludePaths", config.get("excludePaths")); context.put("toolOutputFiles", config.get("toolOutputFiles")); context.put("waitForResults", config.get("waitForResults")); context.put("selectedFailureSeverity", config.get("selectedFailureSeverity")); context.put("onlyConsiderNewFindings", config.get("onlyConsiderNewFindings")); if (failedSave != null) { _logger.info("Failed save exists"); failedSave.setContext(context); } else { // Weather or not the task is using the default Code Dx server credentials from the admin page. boolean useDefaults = Boolean.parseBoolean(config.get("useDefaults")); context.put("useDefaults", String.valueOf(useDefaults)); // We check defaultsSet in case the defaults were erased. In that case we have what they used to be in the task configuration. if (useDefaults && defaultsSet) { _logger.info("User has default Code Dx credentials saved"); context.put("url", defaultUrl); context.put("apiKey", defaultApiKey); context.put("fingerprint", defaultFingerprint); } else { _logger.info("User does not have default Code Dx credentials saved"); context.put("url", config.get("url")); context.put("apiKey", config.get("apiKey")); context.put("fingerprint", config.get("fingerprint")); } } List<Project> projectList = getProjectList(context); String selectedProjectId = config.get("selectedProjectId"); context.put("selectedProjectId", selectedProjectId); if (selectedProjectId != null && !selectedProjectId.isEmpty() && projectList.size() == 0 && (failedSave == null || !failedSave.missingSelectedProject)) { // Case where user already selected a project, but we can't communicate with CodeDx for the name. Just use a generic "name". _logger.info("User already selected a project, but we can't communicate with CodeDx for the name. using a generic name."); Project p = new Project(); p.setId(Integer.parseInt(selectedProjectId)); p.setName("Project Id: " + selectedProjectId); projectList.add(p); // We get here if the previously selected project is not found if (context.get("reachabilityMessage") == null) { _logger.info("Unable to access previously selected project from Code Dx"); context.put("reachabilityMessage", "Unable to access previously selected project from Code Dx"); } } context.put("projectList", projectList); if (context.get("reachabilityMessage") == null) { context.put("reachabilityMessage", ""); } // Reset this in case they cancel out of the page failedSave = null; } // Private helpers private static String emptyIfNull(String value) { if (value == null) { return ""; } return value; } }
42.532544
161
0.647885
928803b882506846603d5ae5c557a0cb47bb16b7
831
package net.romvoid95.galactic.core.permission; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraftforge.server.permission.PermissionAPI; public class GCTPermissions { public static GCTNode ADMIN_TELEPORT = GCTNode.registerAdminNode("teleport", "Allows server Admins to use admintp Command"); public static GCTNode ADMIN_OXYGEN = GCTNode.registerAdminNode("oxygen", "Allows server Admins to use oxygenreset Command"); public static void registerNodes() { PermissionAPI.registerNode(ADMIN_TELEPORT.node(), ADMIN_TELEPORT.level(), ADMIN_TELEPORT.description()); PermissionAPI.registerNode(ADMIN_OXYGEN.node(), ADMIN_OXYGEN.level(), ADMIN_OXYGEN.description()); } public static boolean hasPerm(EntityPlayerMP player, GCTNode node) { return PermissionAPI.hasPermission(player, node.node()); } }
41.55
125
0.801444
aec564e564d7b00401734dfb5e1932cdd8c37978
1,362
package com.skytala.eCommerce.domain.product.relations.product.model.storeVendorPayment; import java.util.Map; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.Map; import java.io.Serializable; import com.skytala.eCommerce.domain.product.relations.product.mapper.storeVendorPayment.ProductStoreVendorPaymentMapper; public class ProductStoreVendorPayment implements Serializable{ private static final long serialVersionUID = 1L; private String productStoreId; private String vendorPartyId; private String paymentMethodTypeId; private String creditCardEnumId; public String getProductStoreId() { return productStoreId; } public void setProductStoreId(String productStoreId) { this.productStoreId = productStoreId; } public String getVendorPartyId() { return vendorPartyId; } public void setVendorPartyId(String vendorPartyId) { this.vendorPartyId = vendorPartyId; } public String getPaymentMethodTypeId() { return paymentMethodTypeId; } public void setPaymentMethodTypeId(String paymentMethodTypeId) { this.paymentMethodTypeId = paymentMethodTypeId; } public String getCreditCardEnumId() { return creditCardEnumId; } public void setCreditCardEnumId(String creditCardEnumId) { this.creditCardEnumId = creditCardEnumId; } public Map<String, Object> mapAttributeField() { return ProductStoreVendorPaymentMapper.map(this); } }
24.763636
120
0.831865
f8078323348dab55c716f9195d08d6c8fecb14d1
986
package com.furkanyesilyurt.springboot.springboottraining.dto; import java.util.Date; public class CommentDto { private Long id; private String yorum; private Date yorumTarihi; private String urunId; private String kullaniciId; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getYorum() { return yorum; } public void setYorum(String yorum) { this.yorum = yorum; } public Date getYorumTarihi() { return yorumTarihi; } public void setYorumTarihi(Date yorumTarihi) { this.yorumTarihi = yorumTarihi; } public String getUrunId() { return urunId; } public void setUrunId(String urunId) { this.urunId = urunId; } public String getKullaniciId() { return kullaniciId; } public void setKullaniciId(String kullaniciId) { this.kullaniciId = kullaniciId; } }
18.259259
62
0.621704
0d73219d48799d0dea9cb89091b37d7867c3db7e
5,549
package Boundary; import Controller.*; import java.sql.SQLException; import java.util.Scanner; import Actors.Cicerone; import DBManagers.DBManagerStampa; public class MenuCicerone { private static MenuCicerone menuCicerone; private final Scanner scanner = new Scanner(System.in); public MenuCicerone() { } public static MenuCicerone getInstance() { if (menuCicerone == null) { menuCicerone = new MenuCicerone(); } return menuCicerone; } public void menuCicerone(String username) { Cicerone cicerone = new Cicerone(); String email = ""; String risposta; System.out.println("Bentornato: " + username); System.out.println("Cosa vuoi fare?"); System.out.println("0 - Esci."); System.out.println("1 - Crea un tour."); System.out.println("2 - Modifica un tour."); System.out.println("3 - Aggiungi disponibilita'."); System.out.println("4 - Rimuovi disponibilita'."); System.out.println("5 - Proponi tag."); System.out.println("6 - Elimina tour."); System.out.println("7 - Visualizza i tuoi tour."); System.out.println("8 - Visualizza il tuo calendario delle disponibilita'."); System.out.println("9 - Visualizza gli avvisi e aggiornamenti sui tuoi tour."); System.out.println("10 - Cambia la lingua del sistema."); System.out.println("11 - Log out."); risposta = scanner.nextLine(); if(risposta.equals("")){ risposta = scanner.nextLine(); } switch (risposta) { case "0": MenuUtenteGenerico.setEsci(); risposta = "0"; break; case "1": try { email = DBManagerStampa.prendiEmail(username); } catch (SQLException | ClassNotFoundException e) { System.out.println("Errore: non è possibile accedere al database."); } cicerone.creaTour(email); menuCicerone(username); break; case "2": MenuModificaTour.getInstance().menuModificaTour(username); break; case "3": try { email = DBManagerStampa.prendiEmail(username); } catch (SQLException | ClassNotFoundException e) { System.out.println("Errore: non è possibile accedere al database."); } cicerone.aggiungiDisponibilita(email); menuCicerone(username); break; case "4": try { email = DBManagerStampa.prendiEmail(username); } catch (SQLException | ClassNotFoundException e) { System.out.println("Errore: non è possibile accedere al database."); } cicerone.rimuoviDisponibilita(email); menuCicerone(username); break; case "5": cicerone.proponiTag(); menuCicerone(username); break; case "6": try { email = DBManagerStampa.prendiEmail(username); } catch (SQLException | ClassNotFoundException e) { System.out.println("Errore: non è possibile accedere al database."); } cicerone.eliminaTourDefinitivamente(email); menuCicerone(username); break; case "7": try { email = DBManagerStampa.prendiEmail(username); } catch (SQLException | ClassNotFoundException e) { System.out.println("Errore: non è possibile accedere al database."); } TourController.getInstance().stampaElencoTourCiceroneConDettagli(email); menuCicerone(username); break; case "8": try { email = DBManagerStampa.prendiEmail(username); } catch (SQLException | ClassNotFoundException e) { System.out.println("Errore: non è possibile accedere al database."); } DisponibilitaController.getInstance().eseguiMostraDisponibilita(email); menuCicerone(username); break; case "9": break; case "10": System.out.println("Seleziona l'id della lingua che vuoi utilizzare:"); System.out.println("1 - Italiano"); System.out.println("2 - English (coming soon)"); System.out.println("3 - 语 (即将推出)"); String lingua = scanner.nextLine(); while (!lingua.equalsIgnoreCase("1")) { System.out.println("Lingua non disponibile. Seleziona un'altra lingua."); lingua = scanner.nextLine(); } System.out.println("Lingua cambiata con successo"); menuCicerone(username); break; case "11": System.out.println("Log out effettuato con successo."); MenuUtenteGenerico.getInstance().menu(); risposta = "0"; break; default: System.out.println("ERRORE: inserisci un id presente nella lista."); menuCicerone(username); } } }
40.210145
93
0.528744
6a30fb8deef160521457738a609e759cc18532b9
114
/** * Transfer of state to new caches in a cluster. * * @api.private */ package org.infinispan.statetransfer;
16.285714
48
0.692982
f5ee9f7ac0b1ba847fabcb213c0fba45109bc4e2
1,213
package com.redhat.developers; import org.junit.Test; import static org.junit.Assert.*; public class PhoneNumberTest { @Test public void testReflexive() { PhoneNumber p1 = PhoneNumber.of(123, 1234); assertTrue(p1.equals(p1)); } @Test public void testSymmetrical() { PhoneNumber x = PhoneNumber.of(123, 1234); PhoneNumber y = PhoneNumber.of(123, 1234); assertTrue(x.equals(y)); assertTrue(y.equals(x)); } @Test public void testTransitive() { PhoneNumber x = PhoneNumber.of(123, 1234); PhoneNumber y = PhoneNumber.of(123, 1234); PhoneNumber z = PhoneNumber.of(123, 1234); assertTrue(x.equals(y)); assertTrue(y.equals(z)); assertTrue(x.equals(z)); } @Test public void testConsistent() { PhoneNumber x = PhoneNumber.of(123, 1234); PhoneNumber y = PhoneNumber.of(123, 1234); assertTrue(x.equals(y)); assertTrue(x.equals(y)); assertTrue(x.equals(y)); assertTrue(x.equals(y)); } @Test public void testNonNullity() { PhoneNumber x = PhoneNumber.of(123, 1234); assertFalse(x.equals(null)); } }
24.755102
51
0.600989
ebe361fcc0ea98ade815e03a0a9cbd8d7e7f8531
1,541
package com.project.ishoupbud.view.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.project.ishoupbud.R; import com.project.ishoupbud.api.model.Transaction; import com.project.ishoupbud.helper.InsetDividerItemDecoration; import com.project.ishoupbud.view.adapters.TransactionAdapter; import com.project.michael.base.views.BaseFragment; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by michael on 4/10/17. */ public class ProductDetailFragment extends BaseFragment { @BindView(R.id.tv_detail_product) TextView tvDetail; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { if(this._rootView == null) { _rootView = inflater.inflate(R.layout.fragment_detail_product, container, false); ButterKnife.bind(this, _rootView); } return _rootView; } public void updateDetail(String detail){ tvDetail.setText(detail); } public static ProductDetailFragment newInstance() { Bundle args = new Bundle(); ProductDetailFragment fragment = new ProductDetailFragment(); fragment.setArguments(args); return fragment; } }
28.018182
123
0.741726
87395f9f19ec1425fffba99ddc4375235500af20
2,208
/** * Copyright 2017-2020 O2 Czech Republic, a.s. * * 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 cz.o2.proxima.beam.tools.groovy; import static org.junit.Assert.assertEquals; import cz.o2.proxima.functional.Consumer; import java.util.ArrayList; import java.util.List; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.junit.Test; /** Test {@link RemoteConsumer}. */ public class RemoteConsumerTest { @Test public void testConsumeOk() { testConsumeOkWithPort(-1); } @Test(expected = RuntimeException.class) public void testConsumeException() { try (RemoteConsumer<String> remoteConsumer = RemoteConsumer.create(this, "localhost", -1, throwingConsumer(), StringUtf8Coder.of())) { remoteConsumer.accept("test"); } } @Test public void testBindOnSpecificPort() { testConsumeOkWithPort(43764); } @Test(expected = RuntimeException.class) public void testRebindOnSamePort() { int port = 43764; try (RemoteConsumer<String> consumer1 = RemoteConsumer.create(this, "localhost", port, tmp -> {}, StringUtf8Coder.of())) { RemoteConsumer.create(this, "localhost", port, tmp -> {}, StringUtf8Coder.of()); } } private void testConsumeOkWithPort(int port) { List<String> consumed = new ArrayList<>(); try (RemoteConsumer<String> remoteConsumer = RemoteConsumer.create(this, "localhost", port, consumed::add, StringUtf8Coder.of())) { remoteConsumer.accept("test"); } assertEquals(1, consumed.size()); assertEquals("test", consumed.get(0)); } private <T> Consumer<T> throwingConsumer() { return tmp -> { throw new RuntimeException("Fail"); }; } }
30.666667
97
0.701993
624ba91bf7f4152bc885e714b2d8ad48d3c6c0f8
7,064
/* * 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.parquet.cli.commands; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import org.apache.parquet.cli.BaseCommand; import org.apache.parquet.cli.csv.AvroCSVReader; import org.apache.parquet.cli.csv.CSVProperties; import org.apache.parquet.cli.csv.AvroCSV; import org.apache.parquet.cli.util.Schemas; import org.apache.avro.Schema; import org.apache.avro.generic.GenericData; import org.apache.parquet.avro.AvroParquetWriter; import org.apache.parquet.cli.util.Codecs; import org.apache.parquet.hadoop.ParquetFileWriter; import org.apache.parquet.hadoop.ParquetWriter; import org.apache.parquet.hadoop.metadata.CompressionCodecName; import org.slf4j.Logger; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.List; import java.util.Set; import static org.apache.avro.generic.GenericData.Record; import static org.apache.parquet.column.ParquetProperties.WriterVersion.PARQUET_1_0; import static org.apache.parquet.column.ParquetProperties.WriterVersion.PARQUET_2_0; @Parameters(commandDescription="Create a file from CSV data") public class ConvertCSVCommand extends BaseCommand { public ConvertCSVCommand(Logger console) { super(console); } @Parameter(description="<csv path>") List<String> targets; @Parameter( names={"-o", "--output"}, description="Output file path", required=true) String outputPath = null; @Parameter( names={"-2", "--format-version-2", "--writer-version-2"}, description="Use Parquet format version 2", hidden = true) boolean v2 = false; @Parameter(names="--delimiter", description="Delimiter character") String delimiter = ","; @Parameter(names="--escape", description="Escape character") String escape = "\\"; @Parameter(names="--quote", description="Quote character") String quote = "\""; @Parameter(names="--no-header", description="Don't use first line as CSV header") boolean noHeader = false; @Parameter(names="--skip-lines", description="Lines to skip before CSV start") int linesToSkip = 0; @Parameter(names="--charset", description="Character set name", hidden = true) String charsetName = Charset.defaultCharset().displayName(); @Parameter(names="--header", description="Line to use as a header. Must match the CSV settings.") String header; @Parameter(names="--require", description="Do not allow null values for the given field") List<String> requiredFields; @Parameter(names = {"-s", "--schema"}, description = "The file containing the Avro schema.") String avroSchemaFile; @Parameter(names = {"--compression-codec"}, description = "A compression codec name.") String compressionCodecName = "GZIP"; @Parameter(names="--row-group-size", description="Target row group size") int rowGroupSize = ParquetWriter.DEFAULT_BLOCK_SIZE; @Parameter(names="--page-size", description="Target page size") int pageSize = ParquetWriter.DEFAULT_PAGE_SIZE; @Parameter(names="--dictionary-size", description="Max dictionary page size") int dictionaryPageSize = ParquetWriter.DEFAULT_PAGE_SIZE; @Parameter( names={"--overwrite"}, description="Remove any data already in the target view or dataset") boolean overwrite = false; @Override @SuppressWarnings("unchecked") public int run() throws IOException { Preconditions.checkArgument(targets != null && targets.size() == 1, "CSV path is required."); if (header != null) { // if a header is given on the command line, don't assume one is in the file noHeader = true; } CSVProperties props = new CSVProperties.Builder() .delimiter(delimiter) .escape(escape) .quote(quote) .header(header) .hasHeader(!noHeader) .linesToSkip(linesToSkip) .charset(charsetName) .build(); String source = targets.get(0); Schema csvSchema; if (avroSchemaFile != null) { csvSchema = Schemas.fromAvsc(open(avroSchemaFile)); } else { Set<String> required = ImmutableSet.of(); if (requiredFields != null) { required = ImmutableSet.copyOf(requiredFields); } String filename = new File(source).getName(); String recordName; if (filename.contains(".")) { recordName = filename.substring(0, filename.indexOf(".")); } else { recordName = filename; } csvSchema = AvroCSV.inferNullableSchema( recordName, open(source), props, required); } long count = 0; try (AvroCSVReader<Record> reader = new AvroCSVReader<>( open(source), props, csvSchema, Record.class, true)) { CompressionCodecName codec = Codecs.parquetCodec(compressionCodecName); try (ParquetWriter<Record> writer = AvroParquetWriter .<Record>builder(qualifiedPath(outputPath)) .withWriterVersion(v2 ? PARQUET_2_0 : PARQUET_1_0) .withWriteMode(overwrite ? ParquetFileWriter.Mode.OVERWRITE : ParquetFileWriter.Mode.CREATE) .withCompressionCodec(codec) .withDictionaryEncoding(true) .withDictionaryPageSize(dictionaryPageSize) .withPageSize(pageSize) .withRowGroupSize(rowGroupSize) .withDataModel(GenericData.get()) .withConf(getConf()) .withSchema(csvSchema) .build()) { for (Record record : reader) { writer.write(record); } } catch (RuntimeException e) { throw new RuntimeException("Failed on record " + count, e); } } return 0; } @Override public List<String> getExamples() { return Lists.newArrayList( "# Create a Parquet file from a CSV file", "sample.csv sample.parquet --schema schema.avsc", "# Create a Parquet file in HDFS from local CSV", "path/to/sample.csv hdfs:/user/me/sample.parquet --schema schema.avsc", "# Create an Avro file from CSV data in S3", "s3:/data/path/sample.csv sample.avro --format avro --schema s3:/schemas/schema.avsc" ); } }
34.458537
93
0.695215
631a8e6633d77f0a0e54c85e7d747c9d4089294b
3,453
package seedu.address.logic.commands; import static java.util.Objects.requireNonNull; import static seedu.address.model.Model.PREDICATE_SHOW_ALL_PERSONS; import java.util.ArrayList; import java.util.List; import seedu.address.commons.core.Messages; import seedu.address.commons.core.index.Index; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.person.Person; import seedu.address.model.tag.Tag; /** * Adds tag to specified person in the address book. */ public class AddTagCommand extends Command { public static final String COMMAND_WORD = "addTag"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Adds tag to the client identified " + "by the index number used in the displayed person list. " + "Only one tag can be added at a time. Duplicates cannot be added. " + "Parameters: INDEX (must be a positive integer) + TAG\n" + "Example: " + COMMAND_WORD + " 1 " + "owes money :p3 "; public static final String MESSAGE_SUCCESS = "Added tag(s) to Person: %1$s"; public static final String MESSAGE_DUPLICATE_TAG = "The tag you want to add is already present."; private final Index index; private final Tag tagToAdd; /** * Creates an AddTagCommand to add the specified {@code Tag}. * * @param index of the person in the filtered person list to edit * @param tag to be added to the person identified */ public AddTagCommand(Index index, Tag tag) { requireNonNull(index); requireNonNull(tag); this.index = index; tagToAdd = tag; } @Override public CommandResult execute(Model model) throws CommandException { requireNonNull(model); List<Person> lastShownList = model.getFilteredPersonList(); if (index.getZeroBased() >= lastShownList.size()) { throw new CommandException(Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX); } Person personToEdit = lastShownList.get(index.getZeroBased()); Person tagAddedPerson = addTagToPerson(personToEdit, tagToAdd); model.setPerson(personToEdit, tagAddedPerson); model.updateFilteredPersonList(PREDICATE_SHOW_ALL_PERSONS); return new CommandResult(String.format(MESSAGE_SUCCESS, tagAddedPerson)); } /** * Adds {@code Tag} to taglist of {@code Person} specified. * @param personToEdit Person to add tag to * @param tagToAdd Tag to be added * @return Person with the tag added * @throws CommandException if there is a duplicate tag already existing */ private Person addTagToPerson(Person personToEdit, Tag tagToAdd) throws CommandException { Person newPerson = Person.copyPerson(personToEdit); ArrayList<Tag> tagList = newPerson.getTags(); if (!tagList.contains(tagToAdd)) { tagList.add(tagToAdd); } else { throw new CommandException(MESSAGE_DUPLICATE_TAG); } newPerson.setTags(tagList); return newPerson; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof AddTagCommand // instanceof handles nulls && index.equals(((AddTagCommand) other).index) && tagToAdd.equals(((AddTagCommand) other).tagToAdd)); } }
36.347368
101
0.67912
900fdc7b71e00de06c5365c55d2c431f7b33e140
2,066
package pl.allegro.tech.hermes.client.okhttp; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import pl.allegro.tech.hermes.client.HermesMessage; import pl.allegro.tech.hermes.client.HermesResponse; import pl.allegro.tech.hermes.client.HermesSender; import java.io.IOException; import java.net.URI; import java.util.concurrent.CompletableFuture; import static pl.allegro.tech.hermes.client.HermesResponseBuilder.hermesResponse; public class OkHttpHermesSender implements HermesSender { private final OkHttpClient client; public OkHttpHermesSender(OkHttpClient client) { this.client = client; } @Override public CompletableFuture<HermesResponse> send(URI uri, HermesMessage message) { CompletableFuture<HermesResponse> future = new CompletableFuture<>(); RequestBody body = RequestBody.create(MediaType.parse(message.getContentType()), message.getBody()); Request.Builder builder = new Request.Builder(); message.consumeHeaders(builder::addHeader); Request request = builder .post(body) .url(uri.toString()) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { future.completeExceptionally(e); } @Override public void onResponse(Call call, Response response) throws IOException { future.complete(fromOkHttpResponse(response)); } }); return future; } HermesResponse fromOkHttpResponse(Response response) throws IOException { return hermesResponse() .withHeaderSupplier(response::header) .withHttpStatus(response.code()) .withBody(response.body().string()) .withProtocol(response.protocol().toString()) .build(); } }
32.28125
108
0.673282
43dba2bea2bf1c65b5404b885235a8b717d4ee5d
11,930
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|// Copyright (C) 2017 The Android Open Source Project end_comment begin_comment comment|// end_comment begin_comment comment|// Licensed under the Apache License, Version 2.0 (the "License"); end_comment begin_comment comment|// you may not use this file except in compliance with the License. end_comment begin_comment comment|// You may obtain a copy of the License at end_comment begin_comment comment|// end_comment begin_comment comment|// http://www.apache.org/licenses/LICENSE-2.0 end_comment begin_comment comment|// end_comment begin_comment comment|// Unless required by applicable law or agreed to in writing, software end_comment begin_comment comment|// distributed under the License is distributed on an "AS IS" BASIS, end_comment begin_comment comment|// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. end_comment begin_comment comment|// See the License for the specific language governing permissions and end_comment begin_comment comment|// limitations under the License. end_comment begin_package DECL|package|com.google.gerrit.acceptance.rest.change package|package name|com operator|. name|google operator|. name|gerrit operator|. name|acceptance operator|. name|rest operator|. name|change package|; end_package begin_import import|import static name|com operator|. name|google operator|. name|common operator|. name|truth operator|. name|Truth operator|. name|assertThat import|; end_import begin_import import|import static name|com operator|. name|google operator|. name|gerrit operator|. name|extensions operator|. name|client operator|. name|ReviewerState operator|. name|REVIEWER import|; end_import begin_import import|import name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|ImmutableSet import|; end_import begin_import import|import name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|Iterables import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|acceptance operator|. name|AbstractDaemonTest import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|acceptance operator|. name|PushOneCommit import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|acceptance operator|. name|RestResponse import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|acceptance operator|. name|testsuite operator|. name|request operator|. name|RequestScopeOperations import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|entities operator|. name|Account import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|extensions operator|. name|api operator|. name|changes operator|. name|ReviewInput import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|extensions operator|. name|common operator|. name|AccountInfo import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|extensions operator|. name|common operator|. name|ChangeInfo import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|extensions operator|. name|common operator|. name|ChangeMessageInfo import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|testing operator|. name|FakeEmailSender import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gson operator|. name|reflect operator|. name|TypeToken import|; end_import begin_import import|import name|com operator|. name|google operator|. name|inject operator|. name|Inject import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Collection import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Map import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_class DECL|class|DeleteVoteIT specifier|public class|class name|DeleteVoteIT extends|extends name|AbstractDaemonTest block|{ DECL|field|requestScopeOperations annotation|@ name|Inject specifier|private name|RequestScopeOperations name|requestScopeOperations decl_stmt|; annotation|@ name|Test DECL|method|deleteVoteOnChange () specifier|public name|void name|deleteVoteOnChange parameter_list|() throws|throws name|Exception block|{ name|deleteVote argument_list|( literal|false argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|deleteVoteOnRevision () specifier|public name|void name|deleteVoteOnRevision parameter_list|() throws|throws name|Exception block|{ name|deleteVote argument_list|( literal|true argument_list|) expr_stmt|; block|} DECL|method|deleteVote (boolean onRevisionLevel) specifier|private name|void name|deleteVote parameter_list|( name|boolean name|onRevisionLevel parameter_list|) throws|throws name|Exception block|{ name|PushOneCommit operator|. name|Result name|r init|= name|createChange argument_list|() decl_stmt|; name|gApi operator|. name|changes argument_list|() operator|. name|id argument_list|( name|r operator|. name|getChangeId argument_list|() argument_list|) operator|. name|revision argument_list|( name|r operator|. name|getCommit argument_list|() operator|. name|name argument_list|() argument_list|) operator|. name|review argument_list|( name|ReviewInput operator|. name|approve argument_list|() argument_list|) expr_stmt|; name|PushOneCommit operator|. name|Result name|r2 init|= name|amendChange argument_list|( name|r operator|. name|getChangeId argument_list|() argument_list|) decl_stmt|; name|requestScopeOperations operator|. name|setApiUser argument_list|( name|user operator|. name|id argument_list|() argument_list|) expr_stmt|; name|recommend argument_list|( name|r operator|. name|getChangeId argument_list|() argument_list|) expr_stmt|; name|sender operator|. name|clear argument_list|() expr_stmt|; name|String name|endPoint init|= literal|"/changes/" operator|+ name|r operator|. name|getChangeId argument_list|() operator|+ operator|( name|onRevisionLevel condition|? operator|( literal|"/revisions/" operator|+ name|r2 operator|. name|getCommit argument_list|() operator|. name|getName argument_list|() operator|) else|: literal|"" operator|) operator|+ literal|"/reviewers/" operator|+ name|user operator|. name|id argument_list|() operator|. name|toString argument_list|() operator|+ literal|"/votes/Code-Review" decl_stmt|; name|RestResponse name|response init|= name|adminRestSession operator|. name|delete argument_list|( name|endPoint argument_list|) decl_stmt|; name|response operator|. name|assertNoContent argument_list|() expr_stmt|; name|List argument_list|< name|FakeEmailSender operator|. name|Message argument_list|> name|messages init|= name|sender operator|. name|getMessages argument_list|() decl_stmt|; name|assertThat argument_list|( name|messages argument_list|) operator|. name|hasSize argument_list|( literal|1 argument_list|) expr_stmt|; name|FakeEmailSender operator|. name|Message name|msg init|= name|messages operator|. name|get argument_list|( literal|0 argument_list|) decl_stmt|; name|assertThat argument_list|( name|msg operator|. name|rcpt argument_list|() argument_list|) operator|. name|containsExactly argument_list|( name|user operator|. name|getEmailAddress argument_list|() argument_list|) expr_stmt|; name|assertThat argument_list|( name|msg operator|. name|body argument_list|() argument_list|) operator|. name|contains argument_list|( name|admin operator|. name|fullName argument_list|() operator|+ literal|" has removed a vote from this change." argument_list|) expr_stmt|; name|assertThat argument_list|( name|msg operator|. name|body argument_list|() argument_list|) operator|. name|contains argument_list|( literal|"Removed Code-Review+1 by " operator|+ name|user operator|. name|fullName argument_list|() operator|+ literal|"<" operator|+ name|user operator|. name|email argument_list|() operator|+ literal|">\n" argument_list|) expr_stmt|; name|endPoint operator|= literal|"/changes/" operator|+ name|r operator|. name|getChangeId argument_list|() operator|+ operator|( name|onRevisionLevel condition|? operator|( literal|"/revisions/" operator|+ name|r2 operator|. name|getCommit argument_list|() operator|. name|getName argument_list|() operator|) else|: literal|"" operator|) operator|+ literal|"/reviewers/" operator|+ name|user operator|. name|id argument_list|() operator|. name|toString argument_list|() operator|+ literal|"/votes" expr_stmt|; name|response operator|= name|adminRestSession operator|. name|get argument_list|( name|endPoint argument_list|) expr_stmt|; name|response operator|. name|assertOK argument_list|() expr_stmt|; name|Map argument_list|< name|String argument_list|, name|Short argument_list|> name|m init|= name|newGson argument_list|() operator|. name|fromJson argument_list|( name|response operator|. name|getReader argument_list|() argument_list|, operator|new name|TypeToken argument_list|< name|Map argument_list|< name|String argument_list|, name|Short argument_list|> argument_list|> argument_list|() block|{} operator|. name|getType argument_list|() argument_list|) decl_stmt|; name|assertThat argument_list|( name|m argument_list|) operator|. name|containsExactly argument_list|( literal|"Code-Review" argument_list|, name|Short operator|. name|valueOf argument_list|( operator|( name|short operator|) literal|0 argument_list|) argument_list|) expr_stmt|; name|ChangeInfo name|c init|= name|gApi operator|. name|changes argument_list|() operator|. name|id argument_list|( name|r operator|. name|getChangeId argument_list|() argument_list|) operator|. name|get argument_list|() decl_stmt|; name|ChangeMessageInfo name|message init|= name|Iterables operator|. name|getLast argument_list|( name|c operator|. name|messages argument_list|) decl_stmt|; name|assertThat argument_list|( name|message operator|. name|author operator|. name|_accountId argument_list|) operator|. name|isEqualTo argument_list|( name|admin operator|. name|id argument_list|() operator|. name|get argument_list|() argument_list|) expr_stmt|; name|assertThat argument_list|( name|message operator|. name|message argument_list|) operator|. name|isEqualTo argument_list|( literal|"Removed Code-Review+1 by User<[email protected]>\n" argument_list|) expr_stmt|; name|assertThat argument_list|( name|getReviewers argument_list|( name|c operator|. name|reviewers operator|. name|get argument_list|( name|REVIEWER argument_list|) argument_list|) argument_list|) operator|. name|containsExactlyElementsIn argument_list|( name|ImmutableSet operator|. name|of argument_list|( name|admin operator|. name|id argument_list|() argument_list|, name|user operator|. name|id argument_list|() argument_list|) argument_list|) expr_stmt|; block|} DECL|method|getReviewers (Collection<AccountInfo> r) specifier|private name|Iterable argument_list|< name|Account operator|. name|Id argument_list|> name|getReviewers parameter_list|( name|Collection argument_list|< name|AccountInfo argument_list|> name|r parameter_list|) block|{ return|return name|Iterables operator|. name|transform argument_list|( name|r argument_list|, name|a lambda|-> name|Account operator|. name|id argument_list|( name|a operator|. name|_accountId argument_list|) argument_list|) return|; block|} block|} end_class end_unit
13.480226
83
0.802096
56a57ecfbfe1b1334d4adbba974b89474ed9ae20
9,819
package com.jim.account.model.imp; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.jim.account.bean.AccountBean; import com.jim.account.db.AccountDbHelper; import com.jim.account.db.AccountDbHelper.AccountColum; import com.jim.account.model.AccountModel; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2016/12/20. */ public class AccountModelImp implements AccountModel { private Context mCxt; private SQLiteDatabase mDatabase; public AccountModelImp(Context context) { this.mCxt = context; AccountDbHelper helper = new AccountDbHelper(context); mDatabase = helper.getWritableDatabase(); } @Override public List<AccountBean> queryAllAccounts() { Cursor cursor = mDatabase.query(AccountDbHelper.ACCOUNT_TABLE_NAME, AccountColum.COLUMS, null, null, null, null, null, null); List<AccountBean> list = cursor.getCount() >0?fillAccount(cursor):new ArrayList<AccountBean>(); cursor.close(); return list; } @Override public List<AccountBean> queryAllGroupByProject() { Cursor cursor = mDatabase.query(AccountDbHelper.ACCOUNT_TABLE_NAME, AccountColum.COLUMS, null, null, AccountColum.PROJECT, null, null, null); List<AccountBean> list = cursor.getCount() >0?fillAccount(cursor):new ArrayList<AccountBean>(); cursor.close(); return list; } @Override public List<AccountBean> queryAllGroupByNormal() { Cursor cursor = mDatabase.query(AccountDbHelper.ACCOUNT_TABLE_NAME, AccountColum.COLUMS, null, null, AccountColum.NORMAL, null, null, null); List<AccountBean> list = cursor.getCount() >0?fillAccount(cursor):new ArrayList<AccountBean>(); cursor.close(); return list; } @Override public AccountBean queryAccountById(int id) { Cursor cursor = mDatabase.query(AccountDbHelper.ACCOUNT_TABLE_NAME, AccountColum.COLUMS, AccountColum.ID + " = ?", new String[]{String.valueOf(id)}, null, null, null, null); List<AccountBean> list = cursor.getCount() >0?fillAccount(cursor):new ArrayList<AccountBean>(); cursor.close(); return list.size()>0?list.get(0):null; } @Override public List<AccountBean> queryAccountsByDate(String date) { Cursor cursor = mDatabase.query(AccountDbHelper.ACCOUNT_TABLE_NAME, AccountColum.COLUMS, AccountColum.TIME + " = ?", new String[]{date}, null, null, null, null); List<AccountBean> list = cursor.getCount() >0?fillAccount(cursor):new ArrayList<AccountBean>(); cursor.close(); return list; } @Override public List<AccountBean> queryAccountsByMonth(String date) { String where = AccountColum.TIME + " LIKE '"+date+"%'"; Cursor cursor = mDatabase.query(AccountDbHelper.ACCOUNT_TABLE_NAME, AccountColum.COLUMS,where , null, null, null, null, null); List<AccountBean> list = cursor.getCount() >0?fillAccount(cursor):new ArrayList<AccountBean>(); cursor.close(); return list; } @Override public List<AccountBean> queryAccountsByYear(String date) { String where = AccountColum.TIME + " LIKE '"+date+"%'"; Cursor cursor = mDatabase.query(AccountDbHelper.ACCOUNT_TABLE_NAME, AccountColum.COLUMS,where , null, null, null, null, null); List<AccountBean> list = cursor.getCount() >0?fillAccount(cursor):new ArrayList<AccountBean>(); cursor.close(); return list; } @Override public List<AccountBean> queryAccountsByProject(String project) { Cursor cursor = mDatabase.query(AccountDbHelper.ACCOUNT_TABLE_NAME, AccountColum.COLUMS, AccountColum.PROJECT + " = ?", new String[]{project}, null, null, null, null); List<AccountBean> list = cursor.getCount() >0?fillAccount(cursor):new ArrayList<AccountBean>(); cursor.close(); return list; } @Override public List<AccountBean> queryAccountsByNormal(String normal) { Cursor cursor = mDatabase.query(AccountDbHelper.ACCOUNT_TABLE_NAME, AccountColum.COLUMS, AccountColum.NORMAL + " = ?", new String[]{normal}, null, null, null, null); List<AccountBean> list = cursor.getCount() >0?fillAccount(cursor):new ArrayList<AccountBean>(); cursor.close(); return list; } @Override public List<AccountBean> queryAccountsBetweenDate(String startDate, String endDate) { Cursor cursor = mDatabase.query(AccountDbHelper.ACCOUNT_TABLE_NAME, AccountColum.COLUMS, AccountColum.TIME + " BETWEEN ? AND ?", new String[]{startDate,endDate}, null, null, null, null); List<AccountBean> list = cursor.getCount() >0?fillAccount(cursor):new ArrayList<AccountBean>(); cursor.close(); return list; } @Override public double getCountByDate(String date) { List<AccountBean> list = queryAccountsByDate(date); return sumAccount(list); } @Override public double getCountByMonth(String month) { List<AccountBean> list = queryAccountsByMonth(month); return sumAccount(list); } @Override public double getCountByYear(String year) { List<AccountBean> list = queryAccountsByYear(year); return sumAccount(list); } @Override public double getCountByProject(String project) { List<AccountBean> list = queryAccountsByProject(project); return sumAccount(list); } @Override public double getCountByNormal(String normal) { List<AccountBean> list = queryAccountsByNormal(normal); return sumAccount(list); } @Override public double getCountBetWeenDay(String start, String end) { List<AccountBean> list = queryAccountsBetweenDate(start,end); return sumAccount(list); } //通过查询计算 private double sumAccount(List<AccountBean> list ){ double count = 0; for(AccountBean b:list){ count += b.getPay(); } return count; } /* 没有能够计算出价格 @Override public double getCountByDate(String date) { double count = 0; String sql = String.format("SELECT SUM(pay) AS sum FROM account_table WHERE time = '%s' " ,date); Cursor cursor = mDatabase.rawQuery(sql,null); if (cursor != null) { cursor.moveToFirst(); count = cursor.getColumnIndex("sum"); } cursor.close(); return count; } @Override public double getCountBetWeenDay(String start, String end) { double count = 0; String sql = String.format("SELECT time,SUM(pay) AS sum FROM account_table WHERE time BETWEEN '%s' AND '%s' " ,start,end); Cursor cursor = mDatabase.rawQuery(sql,null); if (cursor != null) { cursor.moveToFirst(); count = cursor.getColumnIndex("sum"); } cursor.close(); return count; }*/ @Override public long insertAllAccounts(AccountBean bean) { ContentValues values = new ContentValues(); values.put(AccountColum.PROJECT,bean.getProject()); values.put(AccountColum.PAY,bean.getPay()); values.put(AccountColum.TIME,bean.getTime()); values.put(AccountColum.NORMAL,bean.getNormal()); values.put(AccountColum.IMAGE_ID,bean.getImageId()); values.put(AccountColum.REMARK,bean.getRemark()); return mDatabase.insert(AccountDbHelper.ACCOUNT_TABLE_NAME,null,values); } @Override public int updateAccount(AccountBean bean) { ContentValues values = new ContentValues(); values.put(AccountColum.ID,bean.getId()); values.put(AccountColum.PROJECT,bean.getProject()); values.put(AccountColum.PAY,bean.getPay()); values.put(AccountColum.TIME,bean.getTime()); values.put(AccountColum.NORMAL,bean.getNormal()); values.put(AccountColum.IMAGE_ID,bean.getImageId()); values.put(AccountColum.REMARK,bean.getRemark()); return mDatabase.update(AccountDbHelper.ACCOUNT_TABLE_NAME,values,AccountColum.ID + " = ?",new String[]{String.valueOf(bean.getId())}); } @Override public int deleteAccount(int id) { return mDatabase.delete(AccountDbHelper.ACCOUNT_TABLE_NAME,AccountColum.ID + " = ?",new String[]{String.valueOf(id)}); } public void insertDemo(){ ContentValues values = new ContentValues(); values.put(AccountColum.PROJECT,"晚餐"); values.put(AccountColum.PAY,"10.0"); values.put(AccountColum.TIME,"100"); values.put(AccountColum.NORMAL,"Y"); values.put(AccountColum.IMAGE_ID,"987654"); values.put(AccountColum.REMARK,"测试插入记录"); mDatabase.insert(AccountDbHelper.ACCOUNT_TABLE_NAME,null,values); } private List<AccountBean> fillAccount(Cursor cursor) { List<AccountBean> list = new ArrayList<>(); cursor.moveToFirst(); do { AccountBean bean = new AccountBean(); bean.setProject(getColumData(cursor, AccountColum.PROJECT)); bean.setPay(cursor.getDouble(cursor.getColumnIndex(AccountColum.PAY))); bean.setTime(getColumData(cursor, AccountColum.TIME)); bean.setNormal(getColumData(cursor, AccountColum.NORMAL)); bean.setImageId(cursor.getInt(cursor.getColumnIndex( AccountColum.IMAGE_ID))); bean.setRemark(getColumData(cursor, AccountColum.REMARK)); bean.setId(cursor.getInt(cursor.getColumnIndex(AccountColum.ID))); list.add(bean); } while (cursor.moveToNext()); return list; } private String getColumData(Cursor cursor, String name) { return cursor.getString(cursor.getColumnIndex(name)); } }
40.077551
195
0.672574
21ff5fd317d3e4eb5ff7c0fd5717d65b243f4f27
23,861
/* * Copyright 2011-2019 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.snomed.api.rest; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import java.net.URI; import java.security.Principal; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.context.request.async.DeferredResult; import com.b2international.commons.StringUtils; import com.b2international.commons.http.ExtendedLocale; import com.b2international.snowowl.core.domain.IComponent; import com.b2international.snowowl.core.domain.PageableCollectionResource; import com.b2international.snowowl.core.request.SearchResourceRequest; import com.b2international.snowowl.core.request.SearchResourceRequest.Sort; import com.b2international.snowowl.core.request.SearchResourceRequest.SortField; import com.b2international.snowowl.datastore.request.SearchIndexResourceRequest; import com.b2international.snowowl.snomed.api.ISnomedExpressionService; import com.b2international.snowowl.snomed.api.domain.expression.ISnomedExpression; import com.b2international.snowowl.snomed.api.rest.domain.ChangeRequest; import com.b2international.snowowl.snomed.api.rest.domain.RestApiError; import com.b2international.snowowl.snomed.api.rest.domain.SnomedConceptRestInput; import com.b2international.snowowl.snomed.api.rest.domain.SnomedConceptRestSearch; import com.b2international.snowowl.snomed.api.rest.domain.SnomedConceptRestUpdate; import com.b2international.snowowl.snomed.api.rest.util.DeferredResults; import com.b2international.snowowl.snomed.api.rest.util.Responses; import com.b2international.snowowl.snomed.common.SnomedRf2Headers; import com.b2international.snowowl.snomed.core.domain.SnomedConcept; import com.b2international.snowowl.snomed.core.domain.SnomedConcepts; import com.b2international.snowowl.snomed.datastore.request.SnomedDescriptionSearchRequestBuilder; import com.b2international.snowowl.snomed.datastore.request.SnomedRequests; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import springfox.documentation.annotations.ApiIgnore; /** * @since 1.0 */ @Api(value = "Concepts", description = "Concepts", tags = { "concepts" }) @Controller @RequestMapping(produces={ AbstractRestService.SO_MEDIA_TYPE }) public class SnomedConceptRestService extends AbstractRestService { @Autowired private ISnomedExpressionService expressionService; public SnomedConceptRestService() { super(ImmutableSet.<String>builder() .addAll(SnomedConcept.Fields.ALL) .add("term") // special term based sort for concepts .build()); } @ApiOperation( value="Retrieve Concepts from a branch", notes="Returns a list with all/filtered Concepts from a branch." + "<p>The following properties can be expanded:" + "<p>" + "&bull; pt() &ndash; the description representing the concept's preferred term in the given locale<br>" + "&bull; fsn() &ndash; the description representing the concept's fully specified name in the given locale<br>" + "&bull; descriptions() &ndash; the list of descriptions for the concept<br>") @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = PageableCollectionResource.class), @ApiResponse(code = 400, message = "Invalid search config", response = RestApiError.class), @ApiResponse(code = 404, message = "Branch not found", response = RestApiError.class) }) @GetMapping(value="/{path:**}/concepts", produces={ AbstractRestService.SO_MEDIA_TYPE, AbstractRestService.TEXT_CSV_MEDIA_TYPE }) public @ResponseBody DeferredResult<SnomedConcepts> searchByGet( @ApiParam(value="The branch path", required = true) @PathVariable(value="path") final String branch, @ApiParam(value="The Concept identifier(s) to match") @RequestParam(value="conceptIds", required=false) final Set<String> conceptIds, @ApiParam(value="The effective time to match (yyyyMMdd, exact matches only)") @RequestParam(value="effectiveTime", required=false) final String effectiveTimeFilter, @ApiParam(value="The concept status to match") @RequestParam(value="active", required=false) final Boolean activeFilter, @ApiParam(value="The concept module identifier to match") @RequestParam(value="module", required=false) final String moduleFilter, @ApiParam(value="The definition status to match") @RequestParam(value="definitionStatus", required=false) final String definitionStatusFilter, @ApiParam(value="The namespace to match") @RequestParam(value="namespace", required=false) final String namespaceFilter, @ApiParam(value="The ECL expression to match on the inferred form") @RequestParam(value="ecl", required=false) final String eclFilter, @ApiParam(value="The ECL expression to match on the stated form") @RequestParam(value="statedEcl", required=false) final String statedEclFilter, @ApiParam(value="The SNOMED CT Query expression to match (inferred form only)") @RequestParam(value="query", required=false) final String queryFilter, @ApiParam(value="Description semantic tag(s) to match") @RequestParam(value="semanticTag", required=false) final String[] semanticTags, @ApiParam(value="The description term to match") @RequestParam(value="term", required=false) final String termFilter, @ApiParam(value="Description type ECL expression to match") @RequestParam(value="descriptionType", required=false) final String descriptionTypeFilter, @ApiParam(value="The description active state to match") @RequestParam(value="termActive", required=false) final Boolean descriptionActiveFilter, @ApiParam(value = "The inferred parent(s) to match") @RequestParam(value="parent", required=false) final String[] parent, @ApiParam(value = "The inferred ancestor(s) to match") @RequestParam(value="ancestor", required=false) final String[] ancestor, @ApiParam(value = "The stated parent(s) to match") @RequestParam(value="statedParent", required=false) final String[] statedParent, @ApiParam(value = "The stated ancestor(s) to match") @RequestParam(value="statedAncestor", required=false) final String[] statedAncestor, @ApiParam(value="Expansion parameters") @RequestParam(value="expand", required=false) final String expand, @ApiParam(value="The scrollKeepAlive to start a scroll using this query") @RequestParam(value="scrollKeepAlive", required=false) final String scrollKeepAlive, @ApiParam(value="A scrollId to continue scrolling a previous query") @RequestParam(value="scrollId", required=false) final String scrollId, @ApiParam(value="The search key to use for retrieving the next page of results") @RequestParam(value="searchAfter", required=false) final String searchAfter, @ApiParam(value = "Sort keys") @RequestParam(value="sort", required=false) final List<String> sort, @ApiParam(value="The maximum number of items to return") @RequestParam(value="limit", defaultValue="50", required=false) final int limit, @ApiParam(value="Accepted language tags, in order of preference") @RequestHeader(value=HttpHeaders.ACCEPT_LANGUAGE, defaultValue="en-US;q=0.8,en-GB;q=0.6", required=false) final String languageSetting, @ApiIgnore @RequestHeader(value=HttpHeaders.ACCEPT, required=false) final String contentType ) { return doSearch(branch, conceptIds, effectiveTimeFilter, activeFilter, moduleFilter, definitionStatusFilter, namespaceFilter, eclFilter, statedEclFilter, queryFilter, semanticTags, termFilter, descriptionTypeFilter, descriptionActiveFilter, parent, ancestor, statedParent, statedAncestor, expand, scrollKeepAlive, scrollId, searchAfter, sort, limit, languageSetting, contentType); } @ApiOperation( value="Retrieve Concepts from a branch", notes="Returns a list with all/filtered Concepts from a branch." + "<p>The following properties can be expanded:" + "<p>" + "&bull; pt() &ndash; the description representing the concept's preferred term in the given locale<br>" + "&bull; fsn() &ndash; the description representing the concept's fully specified name in the given locale<br>" + "&bull; descriptions() &ndash; the list of descriptions for the concept<br>") @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = PageableCollectionResource.class), @ApiResponse(code = 400, message = "Invalid search config", response = RestApiError.class), @ApiResponse(code = 404, message = "Branch not found", response = RestApiError.class) }) @PostMapping(value="/{path:**}/concepts/search", produces={ AbstractRestService.SO_MEDIA_TYPE, AbstractRestService.TEXT_CSV_MEDIA_TYPE }) public @ResponseBody DeferredResult<SnomedConcepts> searchByPost( @ApiParam(value="The branch path", required = true) @PathVariable(value="path") final String branch, @RequestBody(required = false) final SnomedConceptRestSearch body, @ApiParam(value="Accepted language tags, in order of preference") @RequestHeader(value=HttpHeaders.ACCEPT_LANGUAGE, defaultValue="en-US;q=0.8,en-GB;q=0.6", required=false) final String languageSetting, @ApiIgnore @RequestHeader(value=HttpHeaders.ACCEPT, defaultValue=AbstractRestService.SO_MEDIA_TYPE, required=false) final String contentType) { return doSearch(branch, body.getConceptIds(), body.getEffectiveTimeFilter(), body.getActiveFilter(), body.getModuleFilter(), body.getDefinitionStatusFilter(), body.getNamespaceFilter(), body.getEclFilter(), body.getStatedEclFilter(), body.getQueryFilter(), body.getSemanticTags(), body.getTermFilter(), body.getDescriptionTypeFilter(), body.getDescriptionActiveFilter(), body.getParent(), body.getAncestor(), body.getStatedParent(), body.getStatedAncestor(), body.getExpand(), body.getScrollKeepAlive(), body.getScrollId(), body.getSearchAfter(), body.getSort(), body.getLimit(), languageSetting, contentType); } private DeferredResult<SnomedConcepts> doSearch( final String branch, final Set<String> conceptIds, final String effectiveTimeFilter, final Boolean activeFilter, final String moduleFilter, final String definitionStatusFilter, final String namespaceFilter, final String eclFilter, final String statedEclFilter, final String queryFilter, final String[] semanticTags, final String termFilter, final String descriptionTypeFilter, final Boolean descriptionActiveFilter, final String[] parent, final String[] ancestor, final String[] statedParent, final String[] statedAncestor, final String expandParams, final String scrollKeepAlive, final String scrollId, final String searchAfter, final List<String> sort, final int limit, final String languageSetting, final String contentType) { final List<ExtendedLocale> extendedLocales = getExtendedLocales(languageSetting); String expand = expandParams; if (AbstractRestService.TEXT_CSV_MEDIA_TYPE.equals(contentType)) { if (!Strings.isNullOrEmpty(expand) && expand.contains("pt") && !expand.contains("descriptions()")) { expand = String.format("%s,descriptions()", expand); } } List<Sort> sorts = extractSortFields(sort, branch, extendedLocales); if (sorts.isEmpty()) { final SortField sortField = StringUtils.isEmpty(termFilter) ? SearchIndexResourceRequest.DOC_ID : SearchIndexResourceRequest.SCORE; sorts = Collections.singletonList(sortField); } return DeferredResults.wrap( SnomedRequests .prepareSearchConcept() .setLimit(limit) .setScroll(scrollKeepAlive) .setScrollId(scrollId) .setSearchAfter(searchAfter) .filterByIds(conceptIds) .filterByEffectiveTime(effectiveTimeFilter) .filterByActive(activeFilter) .filterByModule(moduleFilter) .filterByDefinitionStatus(definitionStatusFilter) .filterByNamespace(namespaceFilter) .filterByParents(parent == null ? null : ImmutableSet.copyOf(parent)) .filterByAncestors(ancestor == null ? null : ImmutableSet.copyOf(ancestor)) .filterByStatedParents(statedParent == null ? null : ImmutableSet.copyOf(statedParent)) .filterByStatedAncestors(statedAncestor == null ? null : ImmutableSet.copyOf(statedAncestor)) .filterByEcl(eclFilter) .filterByStatedEcl(statedEclFilter) .filterByQuery(queryFilter) .filterByTerm(Strings.emptyToNull(termFilter)) .filterByDescriptionLanguageRefSet(extendedLocales) .filterByDescriptionType(descriptionTypeFilter) .filterByDescriptionSemanticTags(semanticTags == null ? null : ImmutableSet.copyOf(semanticTags)) .filterByDescriptionActive(descriptionActiveFilter) .setExpand(expand) .setLocales(extendedLocales) .sortBy(sorts) .build(repositoryId, branch) .execute(bus)); } @ApiOperation( value="Retrieve Concept properties", notes="Returns all properties of the specified Concept, including a summary of inactivation indicator and association members." + "<p>The following properties can be expanded:" + "<p>" + "&bull; pt() &ndash; the description representing the concept's preferred term in the given locale<br>" + "&bull; fsn() &ndash; the description representing the concept's fully specified name in the given locale<br>" + "&bull; descriptions() &ndash; the list of descriptions for the concept<br>" + "&bull; ancestors(limit:50,direct:true,expand(pt(),...)) &ndash; the list of concept ancestors (parameter 'direct' is required)<br>" + "&bull; descendants(limit:50,direct:true,expand(pt(),...)) &ndash; the list of concept descendants (parameter 'direct' is required)<br>") @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = Void.class), @ApiResponse(code = 404, message = "Branch or Concept not found", response = RestApiError.class) }) @RequestMapping(value="/{path:**}/concepts/{conceptId}", method=RequestMethod.GET) public @ResponseBody DeferredResult<SnomedConcept> read( @ApiParam(value="The branch path") @PathVariable(value="path") final String branchPath, @ApiParam(value="The Concept identifier") @PathVariable(value="conceptId") final String conceptId, @ApiParam(value="Expansion parameters") @RequestParam(value="expand", required=false) final String expand, @ApiParam(value="Accepted language tags, in order of preference") @RequestHeader(value=HttpHeaders.ACCEPT_LANGUAGE, defaultValue="en-US;q=0.8,en-GB;q=0.6", required=false) final String acceptLanguage) { final List<ExtendedLocale> extendedLocales = getExtendedLocales(acceptLanguage); return DeferredResults.wrap( SnomedRequests .prepareGetConcept(conceptId) .setExpand(expand) .setLocales(extendedLocales) .build(repositoryId, branchPath) .execute(bus)); } @ApiOperation( value="Retrieve authoring form of a concept", notes="Retrieve authoring form of a concept which includes proximal primitive super-types and all inferred relationships " + "which are not of type 'Is a'.") @ApiResponses({ @ApiResponse(code = 200, message = "OK", response = Void.class), @ApiResponse(code = 404, message = "Branch or Concept not found", response = RestApiError.class) }) @RequestMapping(value="/{path:**}/concepts/{conceptId}/authoring-form", method=RequestMethod.GET) public @ResponseBody ISnomedExpression readShortNormalForm( @ApiParam(value="The branch path") @PathVariable(value="path") final String branchPath, @ApiParam(value="The Concept identifier") @PathVariable(value="conceptId") final String conceptId, @ApiParam(value="Accepted language tags, in order of preference") @RequestHeader(value=HttpHeaders.ACCEPT_LANGUAGE, defaultValue="en-US;q=0.8,en-GB;q=0.6", required=false) final String acceptLanguage) { final List<ExtendedLocale> extendedLocales = getExtendedLocales(acceptLanguage); return expressionService.getConceptAuthoringForm(conceptId, branchPath, extendedLocales); } @ApiOperation( value="Create Concept", notes="Creates a new Concept directly on a branch.") @ApiResponses({ @ApiResponse(code = 201, message = "Concept created on task"), @ApiResponse(code = 404, message = "Branch not found", response = RestApiError.class) }) @RequestMapping( value="/{path:**}/concepts", method=RequestMethod.POST, consumes={ AbstractRestService.SO_MEDIA_TYPE, MediaType.APPLICATION_JSON_VALUE }) @ResponseStatus(HttpStatus.CREATED) public ResponseEntity<Void> create( @ApiParam(value="The branch path") @PathVariable(value="path") final String branchPath, @ApiParam(value="Concept parameters") @RequestBody final ChangeRequest<SnomedConceptRestInput> body, final Principal principal) { final String userId = principal.getName(); final SnomedConceptRestInput change = body.getChange(); final String commitComment = body.getCommitComment(); final String createdConceptId = change .toRequestBuilder() .build(repositoryId, branchPath, userId, commitComment) .execute(bus) .getSync(COMMIT_TIMEOUT, TimeUnit.MILLISECONDS) .getResultAs(String.class); return Responses.created(getConceptLocationURI(branchPath, createdConceptId)).build(); } @ApiOperation( value="Update Concept", notes="Updates properties of the specified Concept, also managing inactivation indicator and association reference set " + "membership in case of inactivation." + "<p>The following properties are allowed to change:" + "<p>" + "&bull; module identifier<br>" + "&bull; subclass definition status<br>" + "&bull; definition status<br>" + "&bull; associated Concepts<br>" + "" + "<p>The following properties, when changed, will trigger inactivation:" + "<p>" + "&bull; inactivation indicator<br>") @ApiResponses({ @ApiResponse(code = 204, message = "Update successful"), @ApiResponse(code = 404, message = "Branch or Concept not found", response = RestApiError.class) }) @RequestMapping( value="/{path:**}/concepts/{conceptId}/updates", method=RequestMethod.POST, consumes={ AbstractRestService.SO_MEDIA_TYPE, MediaType.APPLICATION_JSON_VALUE }) @ResponseStatus(HttpStatus.NO_CONTENT) public void update( @ApiParam(value="The branch path") @PathVariable(value="path") final String branchPath, @ApiParam(value="The Concept identifier") @PathVariable(value="conceptId") final String conceptId, @ApiParam(value="Updated Concept parameters") @RequestBody final ChangeRequest<SnomedConceptRestUpdate> body, final Principal principal) { final String userId = principal.getName(); final String commitComment = body.getCommitComment(); body.getChange().toRequestBuilder(conceptId) .build(repositoryId, branchPath, userId, commitComment) .execute(bus) .getSync(COMMIT_TIMEOUT, TimeUnit.MILLISECONDS); } @ApiOperation( value="Delete Concept", notes="Permanently removes the specified unreleased Concept and related components.<p>If any participating " + "component has already been released the Concept can not be removed and a <code>409</code> " + "status will be returned." + "<p>The force flag enables the deletion of a released Concept. " + "Deleting published components is against the RF2 history policy so" + " this should only be used to remove a new component from a release before the release is published.</p>") @ApiResponses({ @ApiResponse(code = 204, message = "Deletion successful"), @ApiResponse(code = 404, message = "Branch or Concept not found", response = RestApiError.class), @ApiResponse(code = 409, message = "Cannot be deleted if released", response = RestApiError.class) }) @RequestMapping(value="/{path:**}/concepts/{conceptId}", method=RequestMethod.DELETE) @ResponseStatus(HttpStatus.NO_CONTENT) public void delete( @ApiParam(value="The branch path") @PathVariable(value="path") final String branchPath, @ApiParam(value="The Concept identifier") @PathVariable(value="conceptId") final String conceptId, @ApiParam(value="Force deletion flag") @RequestParam(defaultValue="false", required=false) final Boolean force, final Principal principal) { SnomedRequests .prepareDeleteConcept(conceptId) .force(force) .build(repositoryId, branchPath, principal.getName(), String.format("Deleted Concept '%s' from store.", conceptId)) .execute(bus) .getSync(COMMIT_TIMEOUT, TimeUnit.MILLISECONDS); } private URI getConceptLocationURI(String branchPath, String conceptId) { return linkTo(SnomedConceptRestService.class).slash(branchPath).slash("concepts").slash(conceptId).toUri(); } @Override protected Sort toSort(String field, boolean ascending, String branch, List<ExtendedLocale> extendedLocales) { switch (field) { case SnomedRf2Headers.FIELD_TERM: return toTermSort(field, ascending, branch, extendedLocales); } return super.toSort(field, ascending, branch, extendedLocales); } private Sort toTermSort(String field, boolean ascending, String branchPath, List<ExtendedLocale> extendedLocales) { final Set<String> synonymIds = SnomedRequests.prepareGetSynonyms() .setFields(SnomedConcept.Fields.ID) .build(repositoryId, branchPath) .execute(bus) .getSync() .getItems() .stream() .map(IComponent::getId) .collect(Collectors.toSet()); final Map<String, Object> args = ImmutableMap.of("locales", SnomedDescriptionSearchRequestBuilder.getLanguageRefSetIds(extendedLocales), "synonymIds", synonymIds); return SearchResourceRequest.SortScript.of("termSort", args, ascending); } }
38.672609
165
0.74649
20e031a9f9af725206187180896061cb9bb4bd09
524
package com.ibm.ram.guards; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; /** * @author seanyu */ @SpringBootApplication @EnableDiscoveryClient @EnableZuulProxy public class EurekaClientZuul { public static void main(String[] args) { SpringApplication.run( EurekaClientZuul.class, args ); } }
26.2
72
0.801527
1c2b99cc8ff13f068fd6ca655f71d708ffa7d5b9
1,059
package io.github.greyp9.arwo.core.metric.histogram.core; import io.github.greyp9.arwo.core.date.DateU; import java.util.Date; import java.util.Map; public final class TimeHistogramSerializerMem extends TimeHistogramSerializer { private final Map<String, byte[]> store; public TimeHistogramSerializerMem(final Map<String, byte[]> store) { this.store = store; } @Override public void save(final TimeHistogram histogram, final Date date) { final Date dateStart = DateU.floor(date, histogram.getDurationPage()); final TimeHistogramPage page = histogram.getHistogramPage(dateStart); store.put(getFile(histogram, dateStart), toBytes(page)); } @Override public void load(final TimeHistogram histogram, final Date date) { final Date dateStart = DateU.floor(date, histogram.getDurationPage()); final String file = getFile(histogram, dateStart); final byte[] bytes = store.get(file); if (bytes != null) { toHistogram(histogram, bytes); } } }
33.09375
79
0.692162
652e913ab67e711afc68d30bb3fd8fa5a1abe347
7,253
/**************************************************************************************** * StreamVisitorBase.java * * Created: Jan 30, 2009 * * @author DRAND * * (C) Copyright MITRE Corporation 2009 * * The program is provided "as is" without any warranty express or implied, including * the warranty of non-infringement and the implied warranties of merchantability and * fitness for a particular purpose. The Copyright owner will not be liable for any * damages suffered by you as a result of using the Program. In no event will the * Copyright owner be liable for any special, indirect or consequential damages or * lost profits even if the Copyright owner has been advised of the possibility of * their occurrence. * ***************************************************************************************/ package org.opensextant.giscore.output; import java.io.File; import org.opensextant.giscore.IStreamVisitor; import org.opensextant.giscore.events.AtomHeader; import org.opensextant.giscore.events.Comment; import org.opensextant.giscore.events.ContainerEnd; import org.opensextant.giscore.events.ContainerStart; import org.opensextant.giscore.events.DocumentStart; import org.opensextant.giscore.events.Element; import org.opensextant.giscore.events.Feature; import org.opensextant.giscore.events.GroundOverlay; import org.opensextant.giscore.events.NetworkLink; import org.opensextant.giscore.events.NetworkLinkControl; import org.opensextant.giscore.events.PhotoOverlay; import org.opensextant.giscore.events.Row; import org.opensextant.giscore.events.Schema; import org.opensextant.giscore.events.ScreenOverlay; import org.opensextant.giscore.events.Style; import org.opensextant.giscore.events.StyleMap; import org.opensextant.giscore.geometry.Circle; import org.opensextant.giscore.geometry.Geometry; import org.opensextant.giscore.geometry.GeometryBag; import org.opensextant.giscore.geometry.Line; import org.opensextant.giscore.geometry.LinearRing; import org.opensextant.giscore.geometry.Model; import org.opensextant.giscore.geometry.MultiLine; import org.opensextant.giscore.geometry.MultiLinearRings; import org.opensextant.giscore.geometry.MultiPoint; import org.opensextant.giscore.geometry.MultiPolygons; import org.opensextant.giscore.geometry.Point; import org.opensextant.giscore.geometry.Polygon; /** * The stream visitor base extends the original visitor base and changes the * default behaviors to be compatible with the new stream elements. It hides * the elements that should no longer be used (org.mitre.itf.Feature and * org.mitre.itf.ThematicLayer). * * @author DRAND * */ public class StreamVisitorBase implements IStreamVisitor { /** * Default behavior ignores containers * @param containerStart */ @Override public void visit(ContainerStart containerStart) { // Ignored by default } /** * @param styleMap */ @Override public void visit(StyleMap styleMap) { // Ignored by default } /** * @param style */ @Override public void visit(Style style) { // Ignored by default } /** * @param schema */ @Override public void visit(Schema schema) { // Ignored by default } /** * Visting a row causes an error for non-row oriented output streams * @param row */ @Override public void visit(Row row) { throw new UnsupportedOperationException("Can't output a tabular row"); } /** * @param feature */ @Override public void visit(Feature feature) { final Geometry geometry = feature.getGeometry(); if (geometry != null) { geometry.accept(this); } } /* (non-Javadoc) * @see org.mitre.giscore.IStreamVisitor#visit(org.mitre.giscore.events.NetworkLink) */ @Override public void visit(NetworkLink link) { visit((Feature) link); } /** * Visit NetworkLinkControl. * Default behavior ignores NetworkLinkControls * @param networkLinkControl */ @Override public void visit(NetworkLinkControl networkLinkControl) { // Ignored by default } /* (non-Javadoc) * @see org.mitre.giscore.IStreamVisitor#visit(org.mitre.giscore.events.PhotoOverlay) */ @Override public void visit(PhotoOverlay overlay) { visit((Feature) overlay); } /* (non-Javadoc) * @see org.mitre.giscore.IStreamVisitor#visit(org.mitre.giscore.events.ScreenOverlay) */ @Override public void visit(ScreenOverlay overlay) { visit((Feature) overlay); } /** * @param overlay */ @Override public void visit(GroundOverlay overlay) { visit((Feature) overlay); } /** * @param documentStart */ @Override public void visit(DocumentStart documentStart) { // Ignored by default } /** * @param containerEnd */ @Override public void visit(ContainerEnd containerEnd) { // Ignored by default } /** * @param point */ @Override public void visit(Point point) { // do nothing } /** * @param multiPoint */ @Override public void visit(MultiPoint multiPoint) { for (Point point : multiPoint) { point.accept(this); } } /** * @param line */ @Override public void visit(Line line) { for (Point pt : line) { pt.accept(this); } } /** * @param geobag a geometry bag */ @Override public void visit(GeometryBag geobag) { for(Geometry geo : geobag) { geo.accept(this); } } /** * @param multiLine */ @Override public void visit(MultiLine multiLine) { for (Line line : multiLine) { line.accept(this); } } /** * @param ring */ @Override public void visit(LinearRing ring) { for (Point pt : ring) { pt.accept(this); } } /** * @param rings */ @Override public void visit(MultiLinearRings rings) { for (LinearRing ring : rings) { ring.accept(this); } } /** * @param polygon */ @Override public void visit(Polygon polygon) { polygon.getOuterRing().accept(this); for (LinearRing ring : polygon.getLinearRings()) { ring.accept(this); } } /** * @param polygons */ @Override public void visit(MultiPolygons polygons) { for (Polygon polygon : polygons) { polygon.accept(this); } } @Override public void visit(Comment comment) { // Ignored by default } @Override public void visit(Model model) { // Ignored by default } /** * Handle the output of a Circle * * @param circle the circle */ @Override public void visit(Circle circle) { // treat as Point by default visit((Point)circle); } @Override public void visit(Element element) { // Ignored by default } @Override public void visit(AtomHeader header) { // Ignored by default } /** * delete dir content * @param directory */ protected static void deleteDirContents(File directory) { if (directory != null) { File[] files = directory.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) { deleteDirContents(file); } file.delete(); } } } } }
23.098726
89
0.656832
c2ec6ba4c00ab86d1a6d757de3d843eee75389ab
1,869
package com.cbec.common.exception; import com.cbec.common.rest.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; @RestControllerAdvice public class RestAdviceHandler { private static final Logger logger = LoggerFactory.getLogger(RestAdviceHandler.class); private static final String DIVIDER = ","; @ExceptionHandler(BizException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public Result baseBusinessException(BizException e) { logger.error(e.getMessage(), e); return Result.error(e.getCode(), e.getMessage()); } @ExceptionHandler(IllegalArgumentException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public Result illegalArgumentException(IllegalArgumentException e) { logger.error(e.getMessage(), e); return Result.error(400, "非法参数: " + e.getMessage()); } @ExceptionHandler(NullPointerException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public Result nullPointerException(NullPointerException e) { logger.error(e.getMessage(), e); return Result.error(500, "服务内部错误(NullPointer)"); } @ExceptionHandler(RuntimeException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public Result runtimeException(RuntimeException e) { logger.error(e.getMessage(), e); return Result.error(500, e.getMessage()); } @ExceptionHandler(Throwable.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public Result defaultHandler(Throwable e) { logger.error(e.getMessage(), e); return Result.error(500, "服务内部错误"); } }
35.942308
90
0.744248
2f9aad315d5ee421a2706b4e3a5c98cafbe3798b
9,959
package com.agh.givealift.controller; import com.agh.givealift.exceptions.FacebookAccessException; import com.agh.givealift.model.AuthToken; import com.agh.givealift.model.entity.GalUser; import com.agh.givealift.model.entity.Route; import com.agh.givealift.model.enums.EmailTemplate; import com.agh.givealift.model.enums.ResetTokenEnum; import com.agh.givealift.model.request.LoginUser; import com.agh.givealift.model.request.SignUpUserRequest; import com.agh.givealift.model.response.AuthenticationResponse; import com.agh.givealift.model.response.GalUserResponse; import com.agh.givealift.security.JwtTokenUtil; import com.agh.givealift.security.UserDetails; import com.agh.givealift.service.FacebookService; import com.agh.givealift.service.PasswordResetService; import com.agh.givealift.service.RouteService; import com.agh.givealift.service.UserService; import com.agh.givealift.service.implementation.EmailService; import com.agh.givealift.util.ResetTokenExpirationException; import com.stefanik.cod.controller.COD; import com.stefanik.cod.controller.CODFactory; import org.hibernate.TransactionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.transaction.TransactionSystemException; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.naming.AuthenticationException; import javax.servlet.http.HttpServletRequest; import javax.validation.ConstraintViolationException; import javax.validation.ValidationException; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.UUID; @RestController @RequestMapping("/api") @CrossOrigin(origins = "*") public class UserController { private final static COD cod = CODFactory.get(); private final AuthenticationManager authenticationManager; private final JwtTokenUtil jwtTokenUtil; private final UserService userService; private final FacebookService facebookService; private final RouteService routeService; private final EmailService emailService; private final PasswordResetService passwordResetService; @Autowired public UserController(AuthenticationManager authenticationManager, JwtTokenUtil jwtTokenUtil, UserService userService, FacebookService facebookService, RouteService routeService, EmailService emailService, PasswordResetService passwordResetService) { this.authenticationManager = authenticationManager; this.jwtTokenUtil = jwtTokenUtil; this.userService = userService; this.facebookService = facebookService; this.routeService = routeService; this.emailService = emailService; this.passwordResetService = passwordResetService; } @PostMapping(value = "/authenticate") public ResponseEntity signIn(@RequestBody LoginUser loginUser) throws AuthenticationException { cod.i(loginUser); final Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken( loginUser.getUsername(), loginUser.getPassword() ) ); SecurityContextHolder.getContext().setAuthentication(authentication); final GalUser user = userService.getUserByUsername(loginUser.getUsername()).get(); final String token = jwtTokenUtil.generateToken(user); return ResponseEntity.ok(new AuthenticationResponse(user.getGalUserId(), token)); } @RequestMapping(value = "/user/signup", method = RequestMethod.POST) public ResponseEntity<Long> signUp(@RequestBody SignUpUserRequest signUpUserRequest) { cod.i(signUpUserRequest); // emailService.sendMessage(signUpUserRequest.getEmail(), EmailTemplate.USER_SIGN_UP.getSubject(), EmailTemplate.USER_SIGN_UP.getText()); return new ResponseEntity<>(userService.signUp(signUpUserRequest), HttpStatus.CREATED); } @RequestMapping(value = "/user/list", method = RequestMethod.GET) public ResponseEntity<?> list() { return new ResponseEntity<>(userService.list(), HttpStatus.OK); } @PutMapping(value = "/user/edit/{id}") public ResponseEntity<?> editUser(@PathVariable("id") long id, @RequestBody SignUpUserRequest signUpUserRequest) { return new ResponseEntity<>(userService.editUser(signUpUserRequest, id), HttpStatus.CREATED); } @PostMapping(value = "/user/photo/{id}") public ResponseEntity<?> photoUser(@PathVariable("id") long id, @RequestParam("file") MultipartFile file) { return new ResponseEntity<>(userService.saveUserPhoto(id, file), HttpStatus.OK); } @PostMapping(value = "/user/send-reset-email/{email}") public ResponseEntity<?> sendResetEmail(@PathVariable("email") String email, HttpServletRequest request) { Optional<GalUser> userOptional = userService.getUserByUsername(email); if (!userOptional.isPresent()) { return new ResponseEntity<>("Nie znaleziono użytkownika: " + email, HttpStatus.UNAUTHORIZED); } GalUser user = userOptional.get(); String token = UUID.randomUUID().toString(); passwordResetService.createEmailResetPassToken(user, token); String url = request.getHeader("origin") + "/change-password?id=" + user.getGalUserId() + "&token=" + token; emailService.sendMessage (user.getEmail(), EmailTemplate.PASSWORD_RESET.getSubject(), EmailTemplate.PASSWORD_RESET.getText() + " " + url); return new ResponseEntity<>(user.getEmail(), HttpStatus.OK); } @SuppressWarnings("deprecation") @GetMapping(value = "/user/change/password") public ResponseEntity<String> changePassword( @RequestParam("old-password") String oldPass, @RequestParam("new-password") String newPass, Authentication authentication ) throws AuthenticationException { GalUser user = ((UserDetails) authentication.getPrincipal()).getUser(); userService.changeUserPassword(user, oldPass, newPass); return new ResponseEntity<>("Hasło zmienione", HttpStatus.OK); } @PutMapping(value = "/user/reset/password") @SuppressWarnings("deprecation") public ResponseEntity<?> editPassword(@RequestParam("id") long id, @RequestParam("token") String token, @RequestBody String password) { try { passwordResetService.validateResetPasswordToken(id, token, ResetTokenEnum.EMAIL_CONFIRMED); } catch (IllegalStateException _) { return new ResponseEntity<>("Wrong user or state", HttpStatus.BAD_REQUEST); } catch (ResetTokenExpirationException _) { return new ResponseEntity<>("Token Expired", HttpStatus.FORBIDDEN); } return new ResponseEntity<>(userService.resetUserPassword(password, id), HttpStatus.CREATED); } @GetMapping(value = "/user/photo/{id}") public ResponseEntity<byte[]> getImage(@PathVariable("id") long id) throws IOException { return new ResponseEntity<>(userService.getUserPhoto(id), HttpStatus.OK); } @GetMapping(value = "/user/route/{id}") public ResponseEntity<List<Route>> getRoutes(@PathVariable("id") long id, @RequestParam("page") int page) throws IOException { return new ResponseEntity<>(routeService.userRoute(id, PageRequest.of(page, 3)), HttpStatus.OK); } @GetMapping(value = "/user/count/route/{id}") public ResponseEntity<Integer> getRoutes(@PathVariable("id") long id) { return new ResponseEntity<>(routeService.countUserRoute(id), HttpStatus.OK); } @PutMapping(value = "/user/rate/{id}") public ResponseEntity<Double> rateUsser(@PathVariable("id") long id, Integer rate) throws IOException { return new ResponseEntity<>(userService.changeRate(rate, id), HttpStatus.OK); } @GetMapping(value = "/user/public/{id}") public ResponseEntity<?> getPublicInfo(@PathVariable("id") long id) { return new ResponseEntity<>(userService.getUserPublicInfo(id), HttpStatus.OK); } @GetMapping(value = "/user/{id}") public ResponseEntity<GalUserResponse> list(@PathVariable("id") long id) { return userService.getUserById(id).map(u -> new ResponseEntity<>(new GalUserResponse(u), HttpStatus.OK)) .orElse(new ResponseEntity<>(HttpStatus.NO_CONTENT)); } @RequestMapping(value = "/facebook/url", method = RequestMethod.GET) public ResponseEntity<?> facebookUrl() { return new ResponseEntity<>(Collections.singletonMap("response", facebookService.createFacebookAuthorizationURL()), HttpStatus.OK); } @RequestMapping(value = "/facebook", method = RequestMethod.GET) public ResponseEntity<?> facebook(@RequestParam("code") String code) { GalUser user = null; try { user = facebookService.createFacebookAccessToken(code); } catch (FacebookAccessException e) { return new ResponseEntity<>("Cannot sign in with Facebook", HttpStatus.FORBIDDEN); } final Authentication authentication = new UsernamePasswordAuthenticationToken( user.getEmail(), user.getPassword()); SecurityContextHolder.getContext().setAuthentication(authentication); final String token = jwtTokenUtil.generateToken(user); return new ResponseEntity<>(new AuthToken(token), HttpStatus.OK); } }
46.537383
254
0.730997
3c3151210cbb3751bfd170f6badf10084cad8cf9
2,687
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.ontology.impl; import org.apache.jena.ontology.OntModelSpec ; import org.apache.jena.rdf.model.test.ModelTestBase ; public class TestOntModelSpec extends ModelTestBase { public TestOntModelSpec( String name ) { super( name ); } public void testEqualityAndDifference() { testEqualityAndDifference( OntModelSpec.OWL_MEM ); testEqualityAndDifference( OntModelSpec.OWL_MEM_RDFS_INF ); testEqualityAndDifference( OntModelSpec.OWL_MEM_RULE_INF ); testEqualityAndDifference( OntModelSpec.OWL_MEM_TRANS_INF ); testEqualityAndDifference( OntModelSpec.OWL_MEM_MICRO_RULE_INF ); testEqualityAndDifference( OntModelSpec.OWL_MEM_MINI_RULE_INF ); testEqualityAndDifference( OntModelSpec.OWL_DL_MEM ); testEqualityAndDifference( OntModelSpec.OWL_DL_MEM_RDFS_INF ); testEqualityAndDifference( OntModelSpec.OWL_DL_MEM_RULE_INF ); testEqualityAndDifference( OntModelSpec.OWL_DL_MEM_TRANS_INF ); testEqualityAndDifference( OntModelSpec.OWL_LITE_MEM ); testEqualityAndDifference( OntModelSpec.OWL_LITE_MEM_TRANS_INF ); testEqualityAndDifference( OntModelSpec.OWL_LITE_MEM_RDFS_INF ); testEqualityAndDifference( OntModelSpec.OWL_LITE_MEM_RULES_INF ); testEqualityAndDifference( OntModelSpec.RDFS_MEM ); testEqualityAndDifference( OntModelSpec.RDFS_MEM_TRANS_INF ); testEqualityAndDifference( OntModelSpec.RDFS_MEM_RDFS_INF ); } private void testEqualityAndDifference( OntModelSpec os ) { assertEquals( os, new OntModelSpec( os ) ); } public void testAssembleRoot() { // TODO OntModelSpec.assemble( Resource root ) } public void testAssembleModel() { // TODO OntModelSpec.assemble( Model model ) } }
41.338462
75
0.731299
9e9d7f14defb5ce5c6c98c76ec943dfa3cfca88d
11,009
package com.keqi.springbootwebsocket.constants; /** * @ClassName WebSocketCode * @Author ZNYK-HYL * @Date 2019-07-26-14:36 * @Version 1.0 * WebSocket 消息定义 **/ public enum WebSocketCode { /*** *@doc 全局消息Code */ GLOBAL_CODE("全局msgCode","1",null), GLOBAL_SECURITY("全局大安全状态/右下角告警轮播","1","1_1"), // GLOBAL_LATEST_ALARM("右下角最新告警轮播","1","1_2"), //==================告警=================== /** * 告警聚焦 6010 * */ ALARM_FOCUSING_B3("告警聚焦","601010","601010_1"), ALARM_FOCUSING_B2("告警聚焦","601011","601011_1"), ALARM_FOCUSING_B1("告警聚焦","601012","601012_1"), ALARM_FOCUSING_F1("告警聚焦","601013","601013_1"), ALARM_FOCUSING_F2("告警聚焦","601014","601014_1"), //==================智能监测=================== /** * 人员 4010 * */ INMONITORING_PERSONNEL_SECURITY_ALL("人员-楼层安全状态","4010","4010_1"), INMONITORING_PERSONNEL_CURR_ALL("人员-楼层当前数据","4010","4010_2"), INMONITORING_PERSONNEL_CURR_F1("人员-单场当前数据","401010","401010_1"), INMONITORING_PERSONNEL_VISITORS_DATA_F1("人员_当前人数","40101010","40101010_1"), INMONITORING_PERSONNEL_VISITORS_POINT_F1("客流人员点位","40101010","40101010_2"), INMONITORING_PERSONNEL_INDIVIDUAL_DATA_F1("人员_单兵","40101011","40101011_1"), INMONITORING_PERSONNEL_INDIVIDUAL_POINT_F1("单兵点位","40101011","40101011_2"), INMONITORING_PERSONNEL_DOOR_DATA_F1("人员_客流统计设备","40101012","40101012_1"), INMONITORING_PERSONNEL_DOOR_POINT_F1("统计设备点位","40101012","40101012_2"), INMONITORING_PERSONNEL_INTRUSIONALARM_POINT_F1("人员_入侵报警设备点位","40101013","40101013_1"), INMONITORING_PERSONNEL_CAMERA_DATA_F1("人员_摄像头","40101014","40101014_1"), INMONITORING_PERSONNEL_CAMERA_POINT_F1("人员_摄像头点位","40101014","40101014_2"), INMONITORING_PERSONNEL_CURR_F2("人员-当前数据","401011","401011_1"), INMONITORING_PERSONNEL_VISITORS_DATA_F2("人员_当前人数","40101110","40101110_1"), INMONITORING_PERSONNEL_VISITORS_POINT_F2("客流人员点位","40101110","40101110_2"), INMONITORING_PERSONNEL_INDIVIDUAL_DATA_F2("人员_单兵","40101111","40101111_1"), INMONITORING_PERSONNEL_INDIVIDUAL_POINT_F2("单兵点位","40101111","40101111_2"), INMONITORING_PERSONNEL_DOOR_DATA_F2("人员_客流统计设备","40101112","40101112_1"), INMONITORING_PERSONNEL_DOOR_POINT_F2("统计设备点位","40101112","40101112_2"), INMONITORING_PERSONNEL_INTRUSIONALARM_POINT_F2("人员_入侵报警设备点位","40101113","40101113_1"), INMONITORING_PERSONNEL_CAMERA_DATA_F2("人员_摄像头","40101114","40101114_1"), INMONITORING_PERSONNEL_CAMERA_POINT_F2("人员_摄像头点位","40101114","40101114_2"), /** * 车辆 4011 * */ INMONITORING_CAR_COUNT("智能检测-车辆-停车数量","4011","4011_1"), INMONITORING_CAR_SECURITY_B12("智能检测-车辆-B1/B2安全状态","4011","4011_2"), INMONITORING_CAR_BRAKE_F1("智能检测-车辆-车闸地图","40111110","40111110_1"), INMONITORING_CAR_CARPORT_F1("智能检测-车辆-车位地图","40111111","40111111_1"), INMONITORING_CAR_CAMERA_F1("智能检测-车辆-摄像头地图","40111112","40111112_1"), INMONITORING_CAR_INDIVIDUAL_F1("智能检测-车辆-单兵地图","40111113","40111113_1"), INMONITORING_CAR_BRAKE_B1("智能检测-车辆-车闸地图","40111210","40111210_1"), INMONITORING_CAR_CARPORT_B1("智能检测-车辆-车位地图","40111211","40111211_1"), INMONITORING_CAR_CAMERA_B1("智能检测-车辆-摄像头地图","40111212","40111212_1"), INMONITORING_CAR_INDIVIDUAL_B1("智能检测-车辆-单兵地图","40111213","40111213_1"), INMONITORING_CAR_BRAKE_B2("智能检测-车辆-车闸地图","40111310","40111310_1"), INMONITORING_CAR_CARPORT_B2("智能检测-车辆-车位地图","40111311","40111311_1"), INMONITORING_CAR_CAMERA_B2("智能检测-车辆-摄像头地图","40111312","40111312_1"), INMONITORING_CAR_INDIVIDUAL_B2("智能检测-车辆-单兵地图","40111313","40111313_1"), /** * 物品 4012 * */ INMONITORING_GOODS_SECURITY_ALL("智能检测-物品-安全状态","4012","4012_1"), INMONITORING_GOODS_MAP_F1("智能检测-物品-地图","401210","401210_1"), INMONITORING_GOODS_MAP_F2("智能检测-物品-地图","401211","401211_1"), INMONITORING_GOODS_CAMERA_F1("智能检测-物品-摄像头-点位","40121010","40121010_1"), INMONITORING_GOODS_INDIVIDUAL_F1("智能检测-物品-单兵点位","40121011","40121011_1"), INMONITORING_GOODS_GOODS_F1("智能检测-物品-物品点位","40121012","40121012_1"), INMONITORING_GOODS_CAMERA_F2("智能检测-物品-摄像头-点位","40121110","40121110_1"), INMONITORING_GOODS_INDIVIDUAL_F2("智能检测-物品-单兵点位","40121111","40121111_1"), INMONITORING_GOODS_GOODS_F2("智能检测-物品-物品点位","40121112","40121112_1"), INMONITORING_GOODS_GOODS_CAMERA_F1("智能检测-物品-物品和摄像头点位","40121099","40121099_1"), INMONITORING_GOODS_GOODS_CAMERA_F2("智能检测-物品-物品和摄像头点位","40121199","40121199_1"), /** * 环境 4013 * */ INMONITORING_ENVIRONMENT_CURR_ALL("智能检测-环境-当前数据","4013","4013_1"), INMONITORING_ENVIRONMENT_SECURITY_ALL("智能检测-环境-楼层安全状态","4013","4013_2"), INMONITORING_ENVIRONMENT_MAP_DATA_F1("智能检测-环境-地图区域数据","401310","401310_1"), INMONITORING_ENVIRONMENT_MAP_DATA_B1("智能检测-环境-地图区域数据","401311","401311_1"), INMONITORING_ENVIRONMENT_MAP_DATA_B2("智能检测-环境-地图区域数据","401312","401312_1"), INMONITORING_ENVIRONMENT_CAMERA_F1("智能检测-环境-摄像头","40131010","40131010_1"), INMONITORING_ENVIRONMENT_INDIVIDUAL_F1("智能检测-环境-单兵","40131011","40131011_1"), INMONITORING_ENVIRONMENT_CO2_F1("智能检测-环境-空间CO2检测","40131012","40131012_1"), INMONITORING_ENVIRONMENT_EXHAUST_FAN_F1("智能检测-环境-排风机","40131013","40131013_1"), INMONITORING_ENVIRONMENT_BLOWER_F1("智能检测-环境-送风机","40131014","40131014_1"), INMONITORING_ENVIRONMENT_EXHAUST_FAN2_F1("智能检测-环境-排风机(变频)","40131015","40131015_1"), INMONITORING_ENVIRONMENT_EMERGENCY_FAN_F1("智能检测-环境-事故补风机","40131016","40131016_1"), INMONITORING_ENVIRONMENT_TAKE_LAMPBLACK_CHANCE_F1("智能检测-环境-送油烟机","40131017","40131017_1"), INMONITORING_ENVIRONMENT_FUME_EXHAUSTER_F1("智能检测-环境-排油烟风机","40131018","40131018_1"), INMONITORING_ENVIRONMENT_EMERGENCY_EXHAUST_FAN_F1("智能检测-环境-事故排风机","40131019","40131019_1"), INMONITORING_ENVIRONMENT_FUME_PURIFIER_F1("智能检测-环境-油烟净化器","40131020","40131020_1"), INMONITORING_ENVIRONMENT_ROOF_AIR_VALUE_F1("智能检测-环境-屋顶风阀","40131021","40131021_1"), INMONITORING_ENVIRONMENT_INDOOR_TEMPERATURE_HUMIDITY_SENSOR_F1("智能检测-环境-室内温湿度传感器","40131022","40131022_1"), INMONITORING_ENVIRONMENT_INDOOR_CO_MONITOR_F1("智能检测-环境-室内一氧化碳监测","40131023","40131023_1"), INMONITORING_ENVIRONMENT_CAMERA_B1("智能检测-环境-摄像头","40131110","40131110_1"), INMONITORING_ENVIRONMENT_INDIVIDUAL_B1("智能检测-环境-单兵","40131111","40131111_1"), INMONITORING_ENVIRONMENT_CO2_B1("智能检测-环境-空间CO2检测","40131112","40131112_1"), INMONITORING_ENVIRONMENT_EXHAUST_FAN_B1("智能检测-环境-排风机","40131113","40131113_1"), INMONITORING_ENVIRONMENT_BLOWER_B1("智能检测-环境-送风机","40131114","40131114_1"), INMONITORING_ENVIRONMENT_EXHAUST_FAN2_B1("智能检测-环境-排风机(变频)","40131115","40131115_1"), INMONITORING_ENVIRONMENT_EMERGENCY_FAN_B1("智能检测-环境-事故补风机","40131116","40131116_1"), INMONITORING_ENVIRONMENT_TAKE_LAMPBLACK_CHANCE_B1("智能检测-环境-送油烟机","40131117","40131117_1"), INMONITORING_ENVIRONMENT_FUME_EXHAUSTER_B1("智能检测-环境-排油烟风机","40131118","40131118_1"), INMONITORING_ENVIRONMENT_EMERGENCY_EXHAUST_FAN_B1("智能检测-环境-事故排风机","40131119","40131119_1"), INMONITORING_ENVIRONMENT_FUME_PURIFIER_B1("智能检测-环境-油烟净化器","40131120","40131120_1"), INMONITORING_ENVIRONMENT_ROOF_AIR_VALUE_B1("智能检测-环境-屋顶风阀","40131121","40131121_1"), INMONITORING_ENVIRONMENT_INDOOR_TEMPERATURE_HUMIDITY_SENSOR_B1("智能检测-环境-室内温湿度传感器","40131122","40131122_1"), INMONITORING_ENVIRONMENT_INDOOR_CO_MONITOR_B1("智能检测-环境-室内一氧化碳监测","40131123","40131123_1"), INMONITORING_ENVIRONMENT_CAMERA_B2("智能检测-环境-摄像头","40131210","40131210_1"), INMONITORING_ENVIRONMENT_INDIVIDUAL_B2("智能检测-环境-单兵","40131211","40131211_1"), INMONITORING_ENVIRONMENT_CO2_B2("智能检测-环境-空间CO2检测","40131212","40131212_1"), INMONITORING_ENVIRONMENT_EXHAUST_FAN_B2("智能检测-环境-排风机","40131213","40131213_1"), INMONITORING_ENVIRONMENT_BLOWER_B2("智能检测-环境-送风机","40131214","40131214_1"), INMONITORING_ENVIRONMENT_EXHAUST_FAN2_B2("智能检测-环境-排风机(变频)","40131215","40131215_1"), INMONITORING_ENVIRONMENT_EMERGENCY_FAN_B2("智能检测-环境-事故补风机","40131216","40131216_1"), INMONITORING_ENVIRONMENT_TAKE_LAMPBLACK_CHANCE_B2("智能检测-环境-送油烟机","40131217","40131217_1"), INMONITORING_ENVIRONMENT_FUME_EXHAUSTER_B2("智能检测-环境-排油烟风机","40131218","40131218_1"), INMONITORING_ENVIRONMENT_EMERGENCY_EXHAUST_FAN_B2("智能检测-环境-事故排风机","40131219","40131219_1"), INMONITORING_ENVIRONMENT_FUME_PURIFIER_B2("智能检测-环境-油烟净化器","40131220","40131220_1"), INMONITORING_ENVIRONMENT_ROOF_AIR_VALUE_B2("智能检测-环境-屋顶风阀","40131221","40131221_1"), INMONITORING_ENVIRONMENT_INDOOR_TEMPERATURE_HUMIDITY_SENSOR_B2("智能检测-环境-室内温湿度传感器","40131222","40131222_1"), INMONITORING_ENVIRONMENT_INDOOR_CO_MONITOR_B2("智能检测-环境-室内一氧化碳监测","40131223","40131223_1"), /** * 告警 4013 * */ INMONITORING_ALARM_FOCUSING("智能告警-列表-聚焦","6010","6010_1"), /** * 消防资源 * */ DEPLOY_FIRE_FIGHTING_EQUIPMENT_POINT_F3("智能分析-安全资源配置-点位", "501210", "501210_1"), DEPLOY_FIRE_FIGHTING_EQUIPMENT_POINT_F2("智能分析-安全资源配置-点位", "501211", "501211_1"), DEPLOY_FIRE_FIGHTING_EQUIPMENT_POINT_F1("智能分析-安全资源配置-点位", "501212", "501212_1"), DEPLOY_FIRE_FIGHTING_EQUIPMENT_POINT_B1("智能分析-安全资源配置-点位", "501213", "501213_1"), DEPLOY_FIRE_FIGHTING_EQUIPMENT_POINT_B2("智能分析-安全资源配置-点位", "501214", "501214_1"), DEPLOY_FIRE_FIGHTING_EQUIPMENT_TOTAL_F3("智能分析-安全资源配置-统计", "501210", "501210_2"), DEPLOY_FIRE_FIGHTING_EQUIPMENT_TOTAL_F2("智能分析-安全资源配置-统计", "501211", "501211_2"), DEPLOY_FIRE_FIGHTING_EQUIPMENT_TOTAL_F1("智能分析-安全资源配置-统计", "501212", "501212_2"), DEPLOY_FIRE_FIGHTING_EQUIPMENT_TOTAL_B1("智能分析-安全资源配置-统计", "501213", "501213_2"), DEPLOY_FIRE_FIGHTING_EQUIPMENT_TOTAL_B2("智能分析-安全资源配置-统计", "501214", "501214_2"), /** * 指挥调度 msgCode * */ //=====1可视化指挥==== COMMAND_INDIVIDUAL_F3("指挥调度-可视化指挥-单兵-F3","801010","801010_1"), COMMAND_INDIVIDUAL_F2("指挥调度-可视化指挥-单兵-F2","801110","801110_1"), COMMAND_INDIVIDUAL_F1("指挥调度-可视化指挥-单兵-F2","801210","801210_1"), COMMAND_INDIVIDUAL_B1("指挥调度-可视化指挥-单兵-B1","801310","801310_1"), COMMAND_INDIVIDUAL_B2("指挥调度-可视化指挥-单兵-B2","801410","801410_1"), COMMAND_SCREEN_ALL("指挥调度-应急管理-信息屏-ALL","8610","8610_1"), COMMAND_SCREEN_F3("指挥调度-应急管理-信息屏-F3","861010","861010_1"), COMMAND_SCREEN_F2("指挥调度-应急管理-信息屏-F2","861110","861110_1"), COMMAND_SCREEN_F1("指挥调度-应急管理-信息屏-F1","861210","861210_1"), COMMAND_SCREEN_B1("指挥调度-应急管理-信息屏-B1","861310","861310_1"), COMMAND_SCREEN_B2("指挥调度-应急管理-信息屏-B2","861410","861410_1") ; private String name; private String msgCode; private String msgType; WebSocketCode(String name, String msgCode, String msgType) { this.name = name; this.msgCode = msgCode; this.msgType = msgType; } public String getName() { return name; } private void setName(String name) { this.name = name; } public String getMsgCode() { return msgCode; } private void setMsgCode(String msgCode) { this.msgCode = msgCode; } public String getMsgType() { return msgType; } private void setMsgType(String msgType) { this.msgType = msgType; } }
48.074236
111
0.733945
5cb5828fcef83a95b2768efa386b7c9f78ed808d
2,606
/** * Copyright (c) 2011, Cloudera, Inc. All Rights Reserved. * * Cloudera, Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"). You may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * This software 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.cloudera.crunch.io.text; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import com.cloudera.crunch.SourceTarget; import com.cloudera.crunch.io.MapReduceTarget; import com.cloudera.crunch.io.OutputHandler; import com.cloudera.crunch.io.PathTarget; import com.cloudera.crunch.io.SourceTargetHelper; import com.cloudera.crunch.type.Converter; import com.cloudera.crunch.type.DataBridge; import com.cloudera.crunch.type.PTableType; import com.cloudera.crunch.type.PType; import com.cloudera.crunch.type.avro.AvroTypeFamily; public class TextFileTarget implements PathTarget, MapReduceTarget { protected final Path path; public TextFileTarget(String path) { this(new Path(path)); } public TextFileTarget(Path path) { this.path = path; } @Override public Path getPath() { return path; } @Override public boolean equals(Object other) { if (other == null || !(other instanceof TextFileTarget)) { return false; } TextFileTarget o = (TextFileTarget) other; return path.equals(o.path); } @Override public int hashCode() { return new HashCodeBuilder().append(path).toHashCode(); } @Override public String toString() { return "TextTarget(" + path + ")"; } @Override public boolean accept(OutputHandler handler, PType<?> ptype) { handler.configure(this, ptype); return true; } @Override public void configureForMapReduce(Job job, PType<?> ptype, Path outputPath, String name) { Converter converter = ptype.getConverter(); SourceTargetHelper.configureTarget(job, TextOutputFormat.class, converter.getKeyClass(), converter.getValueClass(), outputPath, name); } @Override public <T> SourceTarget<T> asSourceTarget(PType<T> ptype) { if (ptype instanceof PTableType) { return null; } return new TextFileSourceTarget<T>(path, ptype); } }
28.955556
92
0.726784
92a1ca6d2d17c56baa567bc4041ec0646216d644
3,845
package org.whispercomm.shout.ui.widget; import java.util.HashSet; import java.util.Set; import android.database.DataSetObservable; import android.database.DataSetObserver; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; /** * A class for adding {@link Marker}s to a {@link GoogleMap} from an * {@link ItemAdapter}. * <p> * After construction, call {@link #setAdapter(ItemAdapter)} to specify the * source of the {@link MarkerOptions}. */ public class MarkerMapLayer { private final DataSetObservable mDataSetObservable = new DataSetObservable(); private final Set<Marker> mMarkers = new HashSet<Marker>(); private final GoogleMap mMap; private ItemAdapter<MarkerOptions> mAdapter; private DataSetObserver mDataSetObserver; private int mItemCount; private LatLngBounds mLatLngBounds; public MarkerMapLayer(GoogleMap map) { mMap = map; } /** * Set the adapter providing the {@link MarkerOptions} to render on the map. * * @param adapter the adapter providing the {@link MarkerOptions} to render * on the map. */ public void setAdapter(ItemAdapter<MarkerOptions> adapter) { if (mAdapter != null && mDataSetObserver != null) { mAdapter.unregisterDataSetObserver(mDataSetObserver); } mAdapter = adapter; if (mAdapter != null) { mItemCount = mAdapter.getCount(); mDataSetObserver = new AdapterDataSetObserver(); mAdapter.registerDataSetObserver(mDataSetObserver); } fillMarkers(); } /** * @return the adapter providing the {@link MarkerOptions} to render on the * map */ public ItemAdapter<MarkerOptions> getAdapter() { return mAdapter; } /** * @return the number of markers in this layer */ public int getMarkerCount() { return mMarkers.size(); } /** * @return the bounds of the markers in this map or {@code null} if no * markers */ public LatLngBounds getLatLngBounds() { return mLatLngBounds; } /** * Register an observer that is called when the set of displayed markers * changes. * * @param observer the object that gets notified when the markers change */ public void registerDataSetObserver(DataSetObserver observer) { mDataSetObservable.registerObserver(observer); } /** * Unregister an observer that has previously been registered with this * adapter via {@link #registerDataSetObserver(DataSetObserver)}. * * @param observer the object to unregister */ public void unregisterDataSetObserver(DataSetObserver observer) { mDataSetObservable.unregisterObserver(observer); } private void clearMarkers() { for (Marker marker : mMarkers) { marker.remove(); } mMarkers.clear(); mLatLngBounds = null; } private void fillMarkers() { /* * This method clears all markers and recreates everything from the * underlying adapter. One could optimize by not removing existing * items. */ clearMarkers(); LatLngBounds.Builder builder = new LatLngBounds.Builder(); for (int i = 0; i < mItemCount; i++) { MarkerOptions markerOptions = mAdapter.get(i); if (markerOptions != null) { Marker marker = mMap.addMarker(markerOptions); mMarkers.add(marker); builder.include(marker.getPosition()); } } try { mLatLngBounds = builder.build(); } catch (IllegalStateException e) { // Ignore. Thrown if no points in builder. } mDataSetObservable.notifyChanged(); } class AdapterDataSetObserver extends DataSetObserver { @Override public void onChanged() { mItemCount = getAdapter().getCount(); fillMarkers(); } @Override public void onInvalidated() { // Data is invalid so we should reset our state mItemCount = 0; fillMarkers(); } } }
23.881988
78
0.714174
cab375934059813b936e9b42c0cbb285478ca595
1,906
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.1 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package Vixen; public class TriMesh extends Mesh { private long swigCPtr; public TriMesh(long cPtr, boolean cMemoryOwn) { super(VixenLibJNI.TriMesh_SWIGUpcast(cPtr), cMemoryOwn); swigCPtr = cPtr; } public static long getCPtr(TriMesh obj) { return (obj == null) ? 0 : obj.swigCPtr; } protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; VixenLibJNI.delete_TriMesh(swigCPtr); } swigCPtr = 0; } super.delete(); } public TriMesh(int style, long nvtx) { this(VixenLibJNI.new_TriMesh__SWIG_0(style, nvtx), true); } public TriMesh(int style) { this(VixenLibJNI.new_TriMesh__SWIG_1(style), true); } public TriMesh() { this(VixenLibJNI.new_TriMesh__SWIG_2(), true); } public TriMesh(String layout_desc, long nvtx) { this(VixenLibJNI.new_TriMesh__SWIG_3(layout_desc, nvtx), true); } public TriMesh(String layout_desc) { this(VixenLibJNI.new_TriMesh__SWIG_4(layout_desc), true); } public TriMesh(TriMesh arg0) { this(VixenLibJNI.new_TriMesh__SWIG_5(TriMesh.getCPtr(arg0), arg0), true); } public long GetNumFaces() { return VixenLibJNI.TriMesh_GetNumFaces(swigCPtr, this); } public boolean MakeNormals(boolean noclear) { return VixenLibJNI.TriMesh_MakeNormals__SWIG_0(swigCPtr, this, noclear); } public boolean MakeNormals() { return VixenLibJNI.TriMesh_MakeNormals__SWIG_1(swigCPtr, this); } }
25.413333
83
0.634313
58b272ff6192f2474fa3b3714c41f38ace93f754
159
package com.mo9.risk.modules.dunning.entity; /** * Created by sun on 2016/7/20. */ public class DunningPeriod { public int begin; public int end; }
15.9
44
0.679245
7d5c6e900da7881322f114101f35f79c7c53028e
322
package test; class ExtendsB extends B { void test() { byte x = foo(); Byte y = foo(); Object z = foo(); } } class ExtendsC extends C { void test() { byte x = foo(); Byte y = foo(); Object z = foo(); } @Override public Byte foo() { return 42; } }
15.333333
36
0.465839
36d9ee5af0a68dbf5453cd7dec50005d108c166f
1,031
package controllers; import models.Oauth; import play.mvc.Controller; public class BaseRestfulController extends Controller { /** * Constant for authentication */ private static final int OathTokenActive = 1; /** * Checks if the token provided is saved. * Collects the heading token, Compares it against the DB records. * WARNING : this is not a production method. * TODO : Compare vs user, Pass token securely to avoid SQL injection * * @author Channing Froom * @return */ protected Boolean Authenticated() { String OauthToken = request().getHeader("token"); if (OauthToken == null || OauthToken.isEmpty()) { return false; } Oauth token = Oauth .find .where() .eq("token", OauthToken) .eq("active", OathTokenActive) .findUnique(); if (token != null) { return true; } return false; } }
22.413043
73
0.561591
cddea04f8b39dcc4d75992a6db4dfa449e341830
2,330
package com.blakebr0.mysticalagriculture; import com.blakebr0.mysticalagriculture.proxy.CommonProxy; import com.blakebr0.mysticalagriculture.registry.LateModRegistry; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; @EventBusSubscriber @Mod(modid = MysticalAgriculture.MOD_ID, name = MysticalAgriculture.NAME, version = MysticalAgriculture.VERSION, dependencies = MysticalAgriculture.DEPENDENCIES, guiFactory = MysticalAgriculture.GUI_FACTORY) public class MysticalAgriculture { public static final String MOD_ID = "mysticalagriculture"; public static final String NAME = "Mystical Agriculture"; public static final String VERSION = "${version}"; public static final String DEPENDENCIES = "required-after:cucumber@[1.1.2,)"; public static final String GUI_FACTORY = "com.blakebr0.mysticalagriculture.config.GuiFactory"; public static final CreativeTabs CREATIVE_TAB = new MACreativeTab(); public static final LateModRegistry REGISTRY = LateModRegistry.create(MOD_ID); @Mod.Instance(MysticalAgriculture.MOD_ID) public static MysticalAgriculture INSTANCE; @SidedProxy(clientSide = "com.blakebr0.mysticalagriculture.proxy.ClientProxy", serverSide = "com.blakebr0.mysticalagriculture.proxy.ServerProxy") public static CommonProxy proxy; @EventHandler public void preInit(FMLPreInitializationEvent event) { proxy.preInit(event); } @EventHandler public void init(FMLInitializationEvent event) { proxy.init(event); } @EventHandler public void postInit(FMLPostInitializationEvent event) { proxy.postInit(event); } @SubscribeEvent(priority=EventPriority.LOW) public static void registerItems(RegistryEvent.Register<Item> event) { proxy.registerItems(event); } }
39.491525
207
0.822747
b3790eccccc24f1d6241020e9418fe182e929f41
23,263
package edu.stanford.nlp.ie; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.*; import java.util.stream.Collectors; import edu.stanford.nlp.ie.regexp.ChineseNumberSequenceClassifier; import edu.stanford.nlp.ie.regexp.NumberSequenceClassifier; import edu.stanford.nlp.io.IOUtils; import edu.stanford.nlp.io.RuntimeIOException; import edu.stanford.nlp.ling.CoreLabel; import edu.stanford.nlp.ling.CoreAnnotations; import edu.stanford.nlp.pipeline.Annotation; import edu.stanford.nlp.pipeline.DefaultPaths; import edu.stanford.nlp.sequences.DocumentReaderAndWriter; import edu.stanford.nlp.sequences.SeqClassifierFlags; import edu.stanford.nlp.util.*; import edu.stanford.nlp.util.logging.Redwood; /** * Subclass of ClassifierCombiner that behaves like a NER, by copying * the AnswerAnnotation labels to NERAnnotation. Also, it can run additional * classifiers (NumberSequenceClassifier, QuantifiableEntityNormalizer, SUTime) * to recognize numeric and date/time entities, depending on flag settings. * * @author Mihai Surdeanu */ public class NERClassifierCombiner extends ClassifierCombiner<CoreLabel> { /** A logger for this class */ private static final Redwood.RedwoodChannels log = Redwood.channels(NERClassifierCombiner.class); private final boolean applyNumericClassifiers; public static final boolean APPLY_NUMERIC_CLASSIFIERS_DEFAULT = true; public static final String APPLY_NUMERIC_CLASSIFIERS_PROPERTY = "ner.applyNumericClassifiers"; private static final String APPLY_NUMERIC_CLASSIFIERS_PROPERTY_BASE = "applyNumericClassifiers"; public static final String APPLY_GAZETTE_PROPERTY = "ner.regex"; public static final boolean APPLY_GAZETTE_DEFAULT = false; private final Language nerLanguage; public static final Language NER_LANGUAGE_DEFAULT = Language.ENGLISH; public static final String NER_LANGUAGE_PROPERTY = "ner.language"; public static final String NER_LANGUAGE_PROPERTY_BASE = "language"; private final boolean useSUTime; public enum Language { ENGLISH("English"), CHINESE("Chinese"); public String languageName; Language(String name) { this.languageName = name; } public static Language fromString(String name, Language defaultValue) { if(name != null) { for(Language l : Language.values()) { if(name.equalsIgnoreCase(l.languageName)) { return l; } } } return defaultValue; } } // todo [cdm 2015]: Could avoid constructing this if applyNumericClassifiers is false private final AbstractSequenceClassifier<CoreLabel> nsc; /** * A mapping from single words to the NER tag that they should be. */ private final Map<String, String> gazetteMapping; public NERClassifierCombiner(Properties props) throws IOException { super(props); applyNumericClassifiers = PropertiesUtils.getBool(props, APPLY_NUMERIC_CLASSIFIERS_PROPERTY, APPLY_NUMERIC_CLASSIFIERS_DEFAULT); nerLanguage = Language.fromString(PropertiesUtils.getString(props, NER_LANGUAGE_PROPERTY, null), NER_LANGUAGE_DEFAULT); useSUTime = PropertiesUtils.getBool(props, NumberSequenceClassifier.USE_SUTIME_PROPERTY, NumberSequenceClassifier.USE_SUTIME_DEFAULT); nsc = new NumberSequenceClassifier(new Properties(), useSUTime, props); if (PropertiesUtils.getBool(props, NERClassifierCombiner.APPLY_GAZETTE_PROPERTY, NERClassifierCombiner.APPLY_GAZETTE_DEFAULT) ) { this.gazetteMapping = readRegexnerGazette(DefaultPaths.DEFAULT_NER_GAZETTE_MAPPING); } else { this.gazetteMapping = Collections.emptyMap(); } } public NERClassifierCombiner(String... loadPaths) throws IOException { this(APPLY_NUMERIC_CLASSIFIERS_DEFAULT, NERClassifierCombiner.APPLY_GAZETTE_DEFAULT, NumberSequenceClassifier.USE_SUTIME_DEFAULT, loadPaths); } public NERClassifierCombiner(boolean applyNumericClassifiers, boolean augmentRegexNER, boolean useSUTime, String... loadPaths) throws IOException { super(loadPaths); this.applyNumericClassifiers = applyNumericClassifiers; this.nerLanguage = NER_LANGUAGE_DEFAULT; this.useSUTime = useSUTime; this.nsc = new NumberSequenceClassifier(useSUTime); if (augmentRegexNER) { this.gazetteMapping = readRegexnerGazette(DefaultPaths.DEFAULT_NER_GAZETTE_MAPPING); } else { this.gazetteMapping = Collections.emptyMap(); } } public NERClassifierCombiner(boolean applyNumericClassifiers, Language nerLanguage, boolean useSUTime, boolean augmentRegexNER, Properties nscProps, String... loadPaths) throws IOException { // NOTE: nscProps may contains sutime props which will not be recognized by the SeqClassifierFlags super(nscProps, ClassifierCombiner.extractCombinationModeSafe(nscProps), loadPaths); this.applyNumericClassifiers = applyNumericClassifiers; this.nerLanguage = nerLanguage; this.useSUTime = useSUTime; // check for which language to use for number sequence classifier if (nerLanguage == Language.CHINESE) { this.nsc = new ChineseNumberSequenceClassifier(new Properties(), useSUTime, nscProps); } else { this.nsc = new NumberSequenceClassifier(new Properties(), useSUTime, nscProps); } if (augmentRegexNER) { this.gazetteMapping = readRegexnerGazette(DefaultPaths.DEFAULT_NER_GAZETTE_MAPPING); } else { this.gazetteMapping = Collections.emptyMap(); } } @SafeVarargs public NERClassifierCombiner(AbstractSequenceClassifier<CoreLabel>... classifiers) throws IOException { this(APPLY_NUMERIC_CLASSIFIERS_DEFAULT, NumberSequenceClassifier.USE_SUTIME_DEFAULT, NERClassifierCombiner.APPLY_GAZETTE_DEFAULT, classifiers); } @SafeVarargs public NERClassifierCombiner(boolean applyNumericClassifiers, boolean useSUTime, boolean augmentRegexNER, AbstractSequenceClassifier<CoreLabel>... classifiers) throws IOException { super(classifiers); this.applyNumericClassifiers = applyNumericClassifiers; this.nerLanguage = NER_LANGUAGE_DEFAULT; this.useSUTime = useSUTime; this.nsc = new NumberSequenceClassifier(useSUTime); if (augmentRegexNER) { this.gazetteMapping = readRegexnerGazette(DefaultPaths.DEFAULT_NER_GAZETTE_MAPPING); } else { this.gazetteMapping = Collections.emptyMap(); } } // constructor which builds an NERClassifierCombiner from an ObjectInputStream public NERClassifierCombiner(ObjectInputStream ois, Properties props) throws IOException, ClassCastException, ClassNotFoundException { super(ois,props); // read the useSUTime from disk Boolean diskUseSUTime = ois.readBoolean(); if (props.getProperty("ner.useSUTime") != null) { this.useSUTime = Boolean.parseBoolean(props.getProperty("ner.useSUTime")); } else { this.useSUTime = diskUseSUTime; } // read the applyNumericClassifiers from disk Boolean diskApplyNumericClassifiers = ois.readBoolean(); if (props.getProperty("ner.applyNumericClassifiers") != null) { this.applyNumericClassifiers = Boolean.parseBoolean(props.getProperty("ner.applyNumericClassifiers")); } else { this.applyNumericClassifiers = diskApplyNumericClassifiers; } this.nerLanguage = NER_LANGUAGE_DEFAULT; // build the nsc, note that initProps should be set by ClassifierCombiner this.nsc = new NumberSequenceClassifier(new Properties(), useSUTime, props); if (PropertiesUtils.getBool(props, NERClassifierCombiner.APPLY_GAZETTE_PROPERTY, NERClassifierCombiner.APPLY_GAZETTE_DEFAULT) ) { this.gazetteMapping = readRegexnerGazette(DefaultPaths.DEFAULT_NER_GAZETTE_MAPPING); } else { this.gazetteMapping = Collections.emptyMap(); log.fatal("Property ner.language not recognized: " + nerLanguage); } } public static final Set<String> DEFAULT_PASS_DOWN_PROPERTIES = CollectionUtils.asSet("encoding", "inputEncoding", "outputEncoding", "maxAdditionalKnownLCWords","map", "ner.combinationMode"); /** This factory method is used to create the NERClassifierCombiner used in NERCombinerAnnotator * (and, thence, in StanfordCoreNLP). * * @param name A "x.y" format property name prefix (the "x" part). This is commonly null, * and then "ner" is used. If it is the empty string, then no property prefix is used. * @param properties Various properties, including a list in "ner.model". * The used ones start with name + "." or are in passDownProperties * @return An NERClassifierCombiner with the given properties */ public static NERClassifierCombiner createNERClassifierCombiner(String name, Properties properties) { return createNERClassifierCombiner(name, DEFAULT_PASS_DOWN_PROPERTIES, properties); } /** This factory method is used to create the NERClassifierCombiner used in NERCombinerAnnotator * (and, thence, in StanfordCoreNLP). * * @param name A "x.y" format property name prefix (the "x" part). This is commonly null, * and then "ner" is used. If it is the empty string, then no property prefix is used. * @param passDownProperties Property names for which the property should be passed down * to the NERClassifierCombiner. The default is not to pass down, but pass down is * useful for things like charset encoding. * @param properties Various properties, including a list in "ner.model". * The used ones start with name + "." or are in passDownProperties * @return An NERClassifierCombiner with the given properties */ public static NERClassifierCombiner createNERClassifierCombiner(String name, Set<String> passDownProperties, Properties properties) { String prefix = (name == null) ? "ner." : name.isEmpty() ? "" : name + '.'; String modelNames = properties.getProperty(prefix + "model"); if (modelNames == null) { modelNames = DefaultPaths.DEFAULT_NER_THREECLASS_MODEL + ',' + DefaultPaths.DEFAULT_NER_MUC_MODEL + ',' + DefaultPaths.DEFAULT_NER_CONLL_MODEL; } // but modelNames can still be empty string is set explicitly to be empty! String[] models; if ( ! modelNames.isEmpty()) { models = modelNames.split(","); } else { // Allow for no real NER model - can just use numeric classifiers or SUTime log.info("WARNING: no NER models specified"); models = StringUtils.EMPTY_STRING_ARRAY; } NERClassifierCombiner nerCombiner; try { boolean applyNumericClassifiers = PropertiesUtils.getBool(properties, prefix + APPLY_NUMERIC_CLASSIFIERS_PROPERTY_BASE, APPLY_NUMERIC_CLASSIFIERS_DEFAULT); boolean useSUTime = PropertiesUtils.getBool(properties, prefix + NumberSequenceClassifier.USE_SUTIME_PROPERTY_BASE, NumberSequenceClassifier.USE_SUTIME_DEFAULT); boolean applyRegexner = PropertiesUtils.getBool(properties, NERClassifierCombiner.APPLY_GAZETTE_PROPERTY, NERClassifierCombiner.APPLY_GAZETTE_DEFAULT); Properties combinerProperties; if (passDownProperties != null) { combinerProperties = PropertiesUtils.extractSelectedProperties(properties, passDownProperties); if (useSUTime) { // Make sure SUTime parameters are included Properties sutimeProps = PropertiesUtils.extractPrefixedProperties(properties, NumberSequenceClassifier.SUTIME_PROPERTY + ".", true); PropertiesUtils.overWriteProperties(combinerProperties, sutimeProps); } } else { // if passDownProperties is null, just pass everything through combinerProperties = properties; } //Properties combinerProperties = PropertiesUtils.extractSelectedProperties(properties, passDownProperties); Language nerLanguage = Language.fromString(properties.getProperty(prefix+"language"),Language.ENGLISH); nerCombiner = new NERClassifierCombiner(applyNumericClassifiers, nerLanguage, useSUTime, applyRegexner, combinerProperties, models); } catch (IOException e) { throw new RuntimeIOException(e); } return nerCombiner; } public boolean appliesNumericClassifiers() { return applyNumericClassifiers; } public boolean usesSUTime() { // if applyNumericClassifiers is false, SUTime isn't run regardless of setting of useSUTime return useSUTime && applyNumericClassifiers; } private static <INN extends CoreMap> void copyAnswerFieldsToNERField(List<INN> l) { for (INN m: l) { m.set(CoreAnnotations.NamedEntityTagAnnotation.class, m.get(CoreAnnotations.AnswerAnnotation.class)); } } @Override public List<CoreLabel> classify(List<CoreLabel> tokens) { return classifyWithGlobalInformation(tokens, null, null); } @Override public List<CoreLabel> classifyWithGlobalInformation(List<CoreLabel> tokens, final CoreMap document, final CoreMap sentence) { List<CoreLabel> output = super.classify(tokens); if (applyNumericClassifiers) { try { // recognizes additional MONEY, TIME, DATE, and NUMBER using a set of deterministic rules // note: some DATE and TIME entities are recognized by our statistical NER based on MUC // note: this includes SUTime // note: requires TextAnnotation, PartOfSpeechTagAnnotation, and AnswerAnnotation // note: this sets AnswerAnnotation! recognizeNumberSequences(output, document, sentence); } catch (RuntimeInterruptedException e) { throw e; } catch (Exception e) { log.info("Ignored an exception in NumberSequenceClassifier: (result is that some numbers were not classified)"); log.info("Tokens: " + StringUtils.joinWords(tokens, " ")); e.printStackTrace(System.err); } // AnswerAnnotation -> NERAnnotation copyAnswerFieldsToNERField(output); try { // normalizes numeric entities such as MONEY, TIME, DATE, or PERCENT // note: this uses and sets NamedEntityTagAnnotation! if(nerLanguage == Language.CHINESE) { // For chinese there is no support for SUTime by default // We need to hand in document and sentence for Chinese to handle DocDate; however, since English normalization // is handled by SUTime, and the information is passed in recognizeNumberSequences(), English only need output. ChineseQuantifiableEntityNormalizer.addNormalizedQuantitiesToEntities(output, document, sentence); } else { QuantifiableEntityNormalizer.addNormalizedQuantitiesToEntities(output, false, useSUTime); } } catch (Exception e) { log.info("Ignored an exception in QuantifiableEntityNormalizer: (result is that entities were not normalized)"); log.info("Tokens: " + StringUtils.joinWords(tokens, " ")); e.printStackTrace(System.err); } catch(AssertionError e) { log.info("Ignored an assertion in QuantifiableEntityNormalizer: (result is that entities were not normalized)"); log.info("Tokens: " + StringUtils.joinWords(tokens, " ")); e.printStackTrace(System.err); } } else { // AnswerAnnotation -> NERAnnotation copyAnswerFieldsToNERField(output); } // Apply RegexNER annotations // cdm 2016: Used to say and do "// skip first token" but I couldn't understand why, so I removed that. for (CoreLabel token : tokens) { // System.out.println(token.toShorterString()); if ((token.tag() == null || token.tag().charAt(0) == 'N') && "O".equals(token.ner()) || "MISC".equals(token.ner())) { String target = gazetteMapping.get(token.originalText()); if (target != null) { token.setNER(target); } } } // Return return output; } private void recognizeNumberSequences(List<CoreLabel> words, final CoreMap document, final CoreMap sentence) { // we need to copy here because NumberSequenceClassifier overwrites the AnswerAnnotation List<CoreLabel> newWords = NumberSequenceClassifier.copyTokens(words, sentence); nsc.classifyWithGlobalInformation(newWords, document, sentence); // copy AnswerAnnotation back. Do not overwrite! // also, copy all the additional annotations generated by SUTime and NumberNormalizer for (int i = 0, sz = words.size(); i < sz; i++){ CoreLabel origWord = words.get(i); CoreLabel newWord = newWords.get(i); // log.info(newWord.word() + " => " + newWord.get(CoreAnnotations.AnswerAnnotation.class) + " " + origWord.ner()); String before = origWord.get(CoreAnnotations.AnswerAnnotation.class); String newGuess = newWord.get(CoreAnnotations.AnswerAnnotation.class); if ((before == null || before.equals(nsc.flags.backgroundSymbol) || before.equals("MISC")) && !newGuess.equals(nsc.flags.backgroundSymbol)) { origWord.set(CoreAnnotations.AnswerAnnotation.class, newGuess); } // transfer other annotations generated by SUTime or NumberNormalizer NumberSequenceClassifier.transferAnnotations(newWord, origWord); } } public void finalizeAnnotation(Annotation annotation) { nsc.finalizeClassification(annotation); } // write an NERClassifierCombiner to an ObjectOutputStream public void serializeClassifier(ObjectOutputStream oos) { try { // first write the ClassifierCombiner part to disk super.serializeClassifier(oos); // write whether to use SUTime oos.writeBoolean(useSUTime); // write whether to use NumericClassifiers oos.writeBoolean(applyNumericClassifiers); } catch (IOException e) { throw new RuntimeIOException(e); } } /** Static method for getting an NERClassifierCombiner from a string path. */ public static NERClassifierCombiner getClassifier(String loadPath, Properties props) throws IOException, ClassNotFoundException, ClassCastException { ObjectInputStream ois = IOUtils.readStreamFromString(loadPath); NERClassifierCombiner returnNCC = getClassifier(ois, props); IOUtils.closeIgnoringExceptions(ois); return returnNCC; } // static method for getting an NERClassifierCombiner from an ObjectInputStream public static NERClassifierCombiner getClassifier(ObjectInputStream ois, Properties props) throws IOException, ClassNotFoundException, ClassCastException { return new NERClassifierCombiner(ois, props); } /** Method for displaying info about an NERClassifierCombiner. */ public static void showNCCInfo(NERClassifierCombiner ncc) { log.info(""); log.info("info for this NERClassifierCombiner: "); ClassifierCombiner.showCCInfo(ncc); log.info("useSUTime: "+ncc.useSUTime); log.info("applyNumericClassifier: "+ncc.applyNumericClassifiers); log.info(""); } /** * Read a gazette mapping in TokensRegex format from the given path * The format is: 'case_sensitive_word \t target_ner_class' (additional info is ignored). * * @param mappingFile The mapping file to read from, as a path either on the filesystem or in your classpath. * * @return The mapping from word to NER tag. */ private static Map<String, String> readRegexnerGazette(String mappingFile) { Map<String, String> mapping = new HashMap<>(); try { for (String line : IOUtils.slurpReader(IOUtils.readerFromString(mappingFile.trim())).split("\n")) { String[] fields = line.split("\t"); String key = fields[0]; String target = fields[1]; mapping.put(key, target); } } catch (IOException e) { log.warn("Could not read Regex mapping: " + mappingFile); } return Collections.unmodifiableMap(mapping); } /** The main method. */ public static void main(String[] args) throws Exception { StringUtils.logInvocationString(log, args); Properties props = StringUtils.argsToProperties(args); SeqClassifierFlags flags = new SeqClassifierFlags(props, false); // false for print probs as printed in next code block String loadPath = props.getProperty("loadClassifier"); NERClassifierCombiner ncc; if (loadPath != null) { // note that when loading a serialized classifier, the philosophy is override // any settings in props with those given in the commandline // so if you dumped it with useSUTime = false, and you say -useSUTime at // the commandline, the commandline takes precedence ncc = getClassifier(loadPath,props); } else { // pass null for passDownProperties to let all props go through ncc = createNERClassifierCombiner("ner", null, props); } // write the NERClassifierCombiner to the given path on disk String serializeTo = props.getProperty("serializeTo"); if (serializeTo != null) { ncc.serializeClassifier(serializeTo); } String textFile = props.getProperty("textFile"); if (textFile != null) { ncc.classifyAndWriteAnswers(textFile); } // run on multiple textFiles , based off CRFClassifier code String textFiles = props.getProperty("textFiles"); if (textFiles != null) { List<File> files = new ArrayList<>(); for (String filename : textFiles.split(",")) { files.add(new File(filename)); } ncc.classifyFilesAndWriteAnswers(files); } // options for run the NERClassifierCombiner on a testFile or testFiles String testFile = props.getProperty("testFile"); String testFiles = props.getProperty("testFiles"); String crfToExamine = props.getProperty("crfToExamine"); DocumentReaderAndWriter<CoreLabel> readerAndWriter = ncc.defaultReaderAndWriter(); if (testFile != null || testFiles != null) { // check if there is not a crf specific request if (crfToExamine == null) { // in this case there is no crfToExamine if (testFile != null) { ncc.classifyAndWriteAnswers(testFile, readerAndWriter, true); } else { List<File> files = Arrays.asList(testFiles.split(",")).stream().map(File::new).collect(Collectors.toList()); ncc.classifyFilesAndWriteAnswers(files, ncc.defaultReaderAndWriter(), true); } } else { ClassifierCombiner.examineCRF(ncc, crfToExamine, flags, testFile, testFiles, readerAndWriter); } } // option for showing info about the NERClassifierCombiner String showNCCInfo = props.getProperty("showNCCInfo"); if (showNCCInfo != null) { showNCCInfo(ncc); } // option for reading in from stdin if (flags.readStdin) { ncc.classifyStdin(); } } }
43.482243
147
0.704638
e4f1d5c44955e2d01ddea29804a4d8be0bf347e6
1,066
import java.io.*; import java.lang.*; import java.io.FileReader; import java.io.FileWriter; public class replace { String operation(String str,String word) { String[] word_list=str.split("\\s+"); String result=""; String hash=""; for(int i=0;i<word.length();i++) { hash+="#"; } int index=0; for(String i:word_list) { if(i.compareTo(word)==0) word_list[index]=hash; index++; } for(String i:word_list) { result+=i; } return result; } public static void main(String[] args) { try { System.out.println("Enter the file path"); File path=new File(System.in); reader=new BufferedReader(new FileReader(path)); System.out.println("Enter the word"); word=new char(System.in); FileReader fr=new FileReader(reader); String str=""; int i; while((i=fr.read())!=-1) { str+=(char)i; } replace obj=new replace(); String resul=obj.operation(str,word); fr.write(resul); System.out.println(resul); fr.close(); } catch(IOException e){ System.out.println("IOException"); } } }
18.701754
50
0.630394
7f7d2a5e108cdfac83c5ff42fa109ca4772ed3a5
83
public interface FactoryCar { Minivan createMinivan(); Pickup createPickup(); }
13.833333
29
0.759036
bafc98779686216f2d430f7bc86b81748989ae8e
3,340
package jetbrains.mps.baseLanguage.closures.constraints; /*Generated by MPS */ import jetbrains.mps.smodel.runtime.base.BaseConstraintsDescriptor; import jetbrains.mps.smodel.runtime.ConstraintFunction; import jetbrains.mps.smodel.runtime.ConstraintContext_CanBeChild; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import jetbrains.mps.smodel.runtime.CheckingNodeContext; import org.jetbrains.mps.openapi.model.SNode; import org.jetbrains.mps.openapi.language.SAbstractConcept; import org.jetbrains.mps.openapi.language.SContainmentLink; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations; import jetbrains.mps.typechecking.TypecheckingFacade; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations; import jetbrains.mps.smodel.SNodePointer; import org.jetbrains.mps.openapi.language.SConcept; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; public class InvokeFunctionOperation_Constraints extends BaseConstraintsDescriptor { public InvokeFunctionOperation_Constraints() { super(CONCEPTS.InvokeFunctionOperation$cv); } @Override protected ConstraintFunction<ConstraintContext_CanBeChild, Boolean> calculateCanBeChildConstraint() { return new ConstraintFunction<ConstraintContext_CanBeChild, Boolean>() { @NotNull public Boolean invoke(@NotNull ConstraintContext_CanBeChild context, @Nullable CheckingNodeContext checkingNodeContext) { boolean result = staticCanBeAChild(context.getNode(), context.getParentNode(), context.getConcept(), context.getLink()); if (!(result) && checkingNodeContext != null) { checkingNodeContext.setBreakingNode(canBeChildBreakingPoint); } return result; } }; } private static boolean staticCanBeAChild(SNode node, SNode parentNode, SAbstractConcept childConcept, SContainmentLink link) { return SNodeOperations.isInstanceOf(parentNode, CONCEPTS.DotExpression$yW) && (TypecheckingFacade.getFromContext().strongCoerceType(TypecheckingFacade.getFromContext().getTypeOf(SLinkOperations.getTarget(SNodeOperations.cast(parentNode, CONCEPTS.DotExpression$yW), LINKS.operand$w6IR)), CONCEPTS.FunctionType$9U) != null); } private static final SNodePointer canBeChildBreakingPoint = new SNodePointer("r:00000000-0000-4000-0000-011c89590334(jetbrains.mps.baseLanguage.closures.constraints)", "1227128029536560058"); private static final class CONCEPTS { /*package*/ static final SConcept InvokeFunctionOperation$cv = MetaAdapterFactory.getConcept(0xfd3920347849419dL, 0x907112563d152375L, 0x11d67349093L, "jetbrains.mps.baseLanguage.closures.structure.InvokeFunctionOperation"); /*package*/ static final SConcept DotExpression$yW = MetaAdapterFactory.getConcept(0xf3061a5392264cc5L, 0xa443f952ceaf5816L, 0x116b46a08c4L, "jetbrains.mps.baseLanguage.structure.DotExpression"); /*package*/ static final SConcept FunctionType$9U = MetaAdapterFactory.getConcept(0xfd3920347849419dL, 0x907112563d152375L, 0x1174a4d19ffL, "jetbrains.mps.baseLanguage.closures.structure.FunctionType"); } private static final class LINKS { /*package*/ static final SContainmentLink operand$w6IR = MetaAdapterFactory.getContainmentLink(0xf3061a5392264cc5L, 0xa443f952ceaf5816L, 0x116b46a08c4L, 0x116b46a4416L, "operand"); } }
59.642857
326
0.818263
141b215de11188fed0001e07845200bd61274d46
5,823
package org.influxdb.impl; import org.influxdb.InfluxDB; import org.influxdb.InfluxDBException; import org.influxdb.dto.BatchPoints; import org.influxdb.dto.Point; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.function.BiConsumer; /** * Batch writer that tries to retry a write if it failed previously and * the reason of the failure is not permanent. */ class RetryCapableBatchWriter implements BatchWriter { private InfluxDB influxDB; private BiConsumer<Iterable<Point>, Throwable> exceptionHandler; private LinkedList<BatchPoints> batchQueue; private int requestActionsLimit; private int retryBufferCapacity; private int usedRetryBufferCapacity; RetryCapableBatchWriter(final InfluxDB influxDB, final BiConsumer<Iterable<Point>, Throwable> exceptionHandler, final int retryBufferCapacity, final int requestActionsLimit) { this.influxDB = influxDB; this.exceptionHandler = exceptionHandler; batchQueue = new LinkedList<>(); this.retryBufferCapacity = retryBufferCapacity; this.requestActionsLimit = requestActionsLimit; } private enum WriteResultOutcome { WRITTEN, FAILED_RETRY_POSSIBLE, FAILED_RETRY_IMPOSSIBLE } private static final class WriteResult { static final WriteResult WRITTEN = new WriteResult(WriteResultOutcome.WRITTEN); WriteResultOutcome outcome; Throwable throwable; private WriteResult(final WriteResultOutcome outcome) { this.outcome = outcome; } private WriteResult(final WriteResultOutcome outcome, final Throwable throwable) { this.outcome = outcome; this.throwable = throwable; } private WriteResult(final InfluxDBException e) { this.throwable = e; if (e.isRetryWorth()) { this.outcome = WriteResultOutcome.FAILED_RETRY_POSSIBLE; } else { this.outcome = WriteResultOutcome.FAILED_RETRY_IMPOSSIBLE; } } } /* This method is synchronized to avoid parallel execution when the user invokes flush/close * of the client in the middle of scheduled write execution (buffer flush / action limit overrun) */ @Override public synchronized void write(final Collection<BatchPoints> collection) { // empty the cached data first ListIterator<BatchPoints> batchQueueIterator = batchQueue.listIterator(); while (batchQueueIterator.hasNext()) { BatchPoints entry = batchQueueIterator.next(); WriteResult result = tryToWrite(entry); if (result.outcome == WriteResultOutcome.WRITTEN || result.outcome == WriteResultOutcome.FAILED_RETRY_IMPOSSIBLE) { batchQueueIterator.remove(); usedRetryBufferCapacity -= entry.getPoints().size(); // we are throwing out data, notify the client if (result.outcome == WriteResultOutcome.FAILED_RETRY_IMPOSSIBLE) { exceptionHandler.accept(entry.getPoints(), result.throwable); } } else { // we cannot send more data otherwise we would write them in different // order than in which were submitted for (BatchPoints batchPoints : collection) { addToBatchQueue(batchPoints); } return; } } // write the last given batch last so that duplicate data points get overwritten correctly Iterator<BatchPoints> collectionIterator = collection.iterator(); while (collectionIterator.hasNext()) { BatchPoints batchPoints = collectionIterator.next(); WriteResult result = tryToWrite(batchPoints); switch (result.outcome) { case FAILED_RETRY_POSSIBLE: addToBatchQueue(batchPoints); while (collectionIterator.hasNext()) { addToBatchQueue(collectionIterator.next()); } break; case FAILED_RETRY_IMPOSSIBLE: exceptionHandler.accept(batchPoints.getPoints(), result.throwable); break; default: } } } /* This method is synchronized to avoid parallel execution when the BatchProcessor scheduler * has been shutdown but there are jobs still being executed (using RetryCapableBatchWriter.write).*/ @Override public synchronized void close() { // try to write everything queued / buffered for (BatchPoints points : batchQueue) { WriteResult result = tryToWrite(points); if (result.outcome != WriteResultOutcome.WRITTEN) { exceptionHandler.accept(points.getPoints(), result.throwable); } } } private WriteResult tryToWrite(final BatchPoints batchPoints) { try { influxDB.write(batchPoints); return WriteResult.WRITTEN; } catch (InfluxDBException e) { return new WriteResult(e); } catch (Exception e) { return new WriteResult(WriteResultOutcome.FAILED_RETRY_POSSIBLE, e); } } private void evictTooOldFailedWrites() { while (usedRetryBufferCapacity > retryBufferCapacity && batchQueue.size() > 0) { List<Point> points = batchQueue.removeFirst().getPoints(); usedRetryBufferCapacity -= points.size(); exceptionHandler.accept(points, new InfluxDBException.RetryBufferOverrunException( "Retry buffer overrun, current capacity: " + retryBufferCapacity)); } } private void addToBatchQueue(final BatchPoints batchPoints) { if (batchQueue.size() > 0) { BatchPoints last = batchQueue.getLast(); if (last.getPoints().size() + batchPoints.getPoints().size() <= requestActionsLimit) { boolean hasBeenMergedIn = last.mergeIn(batchPoints); if (hasBeenMergedIn) { return; } } } batchQueue.add(batchPoints); usedRetryBufferCapacity += batchPoints.getPoints().size(); evictTooOldFailedWrites(); } }
36.167702
113
0.704276
2555cf2e43059312b4ef73cacef1b8bcfc5fd132
4,216
package org.vcell.client.logicalwindow; import java.awt.Window; import java.util.Collections; import java.util.Iterator; import javax.swing.JDialog; import javax.swing.JMenuItem; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.vcell.client.logicalwindow.LWTraits.InitialPosition; import edu.uchc.connjur.wb.ExecutionTrace; /** * base class for logical dialog windows * * defaults to {@link LWTraits.InitialPosition#CENTERED_ON_PARENT} * * implements all {@link LWHandle} methods */ @SuppressWarnings("serial") public abstract class LWDialog extends JDialog implements LWFrameOrDialog, LWHandle { private static final Logger LG = LogManager.getLogger(LWDialog.class); private final LWContainerHandle lwParent; protected LWTraits traits; /** * see {@link JDialog#JDialog(String title)} * @param parent logical owner, ideally not null but accepted * @param title to set null's okay */ public LWDialog(LWContainerHandle parent, String title) { //support null for use in WindowBuilder, and during transition super(parent != null ? parent.getWindow() : null, title, ModalityType.DOCUMENT_MODAL); lwParent = parent; if (parent != null) { parent.manage(this); } traits = new LWTraits(InitialPosition.CENTERED_ON_PARENT); setDefaultCloseOperation(DISPOSE_ON_CLOSE); } @Override public LWTraits getTraits() { return traits; } public void setTraits(LWTraits traits) { this.traits = traits; } /** * see {@link JDialog#JDialog()} * @param parent logical owner, not null */ public LWDialog(LWContainerHandle parent) { this(parent,null); } @Override public LWContainerHandle getlwParent() { return lwParent; } @Override public Window getWindow() { return this; } @Override public LWModality getLWModality() { return LWModality.PARENT_ONLY; } @Override public Iterator<LWHandle> iterator() { return Collections.emptyIterator(); } @Override public void closeRecursively() { } @Override public void unIconify() { } @Override public JMenuItem menuItem(int level) { return LWMenuItemFactory.menuFor(level, this); } @Override public Window self() { return this; } @Override public void setModal(boolean modal) { super.setModal(modal); LWDialog.normalizeModality(this); } @Override public void setModalityType(ModalityType type) { super.setModalityType(type); LWDialog.normalizeModality(this); } /** * remove application / toolkit modality */ public static void normalizeModality(JDialog jdialog ) { switch (jdialog.getModalityType()) { case MODELESS: if (LG.isWarnEnabled()) { //we want our modeless windows to be LWChildWindows, not Dialogs LG.warn(ExecutionTrace.justClassName(jdialog) + ' ' + jdialog.getTitle() + " invalid modeless dialog"); } break; case DOCUMENT_MODAL: //this is what we want break; case APPLICATION_MODAL: case TOOLKIT_MODAL: //fix jdialog.setModalityType(ModalityType.DOCUMENT_MODAL); break; } } // private static class AncestorModal implements ComponentListener { // private List<Window> disabled; // private final LWHandle handle; // // AncestorModal(LWHandle handle) { // super(); // this.handle = handle; // disabled = null; // } // // @Override // public void componentResized(ComponentEvent e) { } // // @Override // public void componentMoved(ComponentEvent e) { } // // @Override // public void componentShown(ComponentEvent e) { // // disabled = new ArrayList<Window>( ); // LWContainerHandle p = handle.getlwParent(); // while (p != null) { // Window w = p.getWindow(); // if (w.isEnabled()) { // w.setEnabled(false); // disabled.add(w); // } // } // } // // @Override // public void componentHidden(ComponentEvent e) { // if (disabled != null) { // for (Window w: disabled) { // w.setEnabled(true); // } // disabled = null; // } // else { // System.err.println("????"); // } // } // // } }
23.038251
108
0.662476
7bb5968ddf62d978539708718de96dcb3ba73e15
12,669
package tests.restapi.copy_import.purchases_with_strings; import org.apache.wink.json4j.JSONObject; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import tests.com.ibm.qautils.FileUtils; import tests.restapi.AirlockUtils; import tests.restapi.FeaturesRestApi; import tests.restapi.InAppPurchasesRestApi; import tests.restapi.ProductsRestApi; import tests.restapi.SeasonsRestApi; import tests.restapi.StringsRestApi; import tests.restapi.TranslationsRestApi; import tests.restapi.UtilitiesRestApi; public class CopyHierarchyOfPurchaseItemsWithNewStrings { private String seasonID; private String seasonID2; private String seasonID3; private String entitlementID1; private String filePath; private StringsRestApi stringsApi; private ProductsRestApi p; private AirlockUtils baseUtils; private TranslationsRestApi translationsApi; private String productID; private String m_url; private String sessionToken = ""; private String m_translationsUrl; private FeaturesRestApi f; private UtilitiesRestApi u; private SeasonsRestApi s; private InAppPurchasesRestApi purchasesApi; private String purchaseOptionsID1; @BeforeClass @Parameters({"url", "analyticsUrl", "translationsUrl", "configPath", "sessionToken", "userName", "userPassword", "appName", "productsToDeleteFile"}) public void init(String url, String analyticsUrl, String translationsUrl, String configPath, String sToken, String userName, String userPassword, String appName, String productsToDeleteFile) throws Exception{ m_url = url; m_translationsUrl = translationsUrl; filePath = configPath; stringsApi = new StringsRestApi(); stringsApi.setURL(m_translationsUrl); translationsApi = new TranslationsRestApi(); translationsApi.setURL(translationsUrl); purchasesApi = new InAppPurchasesRestApi(); purchasesApi.setURL(m_url); p = new ProductsRestApi(); p.setURL(m_url); s = new SeasonsRestApi(); s.setURL(m_url); f = new FeaturesRestApi(); f.setURL(m_url); u = new UtilitiesRestApi(); u.setURL(m_url); baseUtils = new AirlockUtils(url, analyticsUrl, translationsUrl, configPath, sToken, userName, userPassword, appName, productsToDeleteFile); sessionToken = baseUtils.sessionToken; productID = baseUtils.createProduct(); baseUtils.printProductToFile(productID); seasonID = baseUtils.createSeason(productID); seasonID2 = s.addSeason(productID, "{\"minVersion\": \"5.0\"}", sessionToken); seasonID3 = s.addSeason(productID, "{\"minVersion\": \"6.0\"}", sessionToken); } /* E1 -> E_MIX ->E2 -> MIXCR ->CR1, CR2 ->E3 -> CR3 -> CR4 PO_MIX ->PO1 -> MIXCR ->CR5, CR6 ->PO2 -> CR7 -> CR8 */ @Test (description = "Add string and entitlement with configuration rule using this string") public void addComponents() throws Exception{ //add string String str = FileUtils.fileToString(filePath + "strings/string1.txt", "UTF-8", false); String stringID = stringsApi.addString(seasonID, str, sessionToken); Assert.assertFalse(stringID.contains("Error"), "String was not added:" + stringID); JSONObject strJson = new JSONObject(str); strJson.put("key", "app.hello2"); String stringID2 = stringsApi.addString(seasonID, strJson.toString(), sessionToken); Assert.assertFalse(stringID2.contains("Error"), "String was not added:" + stringID2); strJson.put("key", "app.hello3"); String stringID3 = stringsApi.addString(seasonID, strJson.toString(), sessionToken); Assert.assertFalse(stringID3.contains("Error"), "String was not added:" + stringID3); strJson.put("key", "app.hello4"); String stringID4 = stringsApi.addString(seasonID, strJson.toString(), sessionToken); Assert.assertFalse(stringID4.contains("Error"), "String was not added:" + stringID4); strJson.put("key", "app.hello5"); String stringID5 = stringsApi.addString(seasonID, strJson.toString(), sessionToken); Assert.assertFalse(stringID5.contains("Error"), "String was not added:" + stringID4); strJson.put("key", "app.hello6"); String stringID6 = stringsApi.addString(seasonID, strJson.toString(), sessionToken); Assert.assertFalse(stringID6.contains("Error"), "String was not added:" + stringID4); strJson.put("key", "app.hello7"); String stringID7 = stringsApi.addString(seasonID, strJson.toString(), sessionToken); Assert.assertFalse(stringID7.contains("Error"), "String was not added:" + stringID4); strJson.put("key", "app.hello8"); String stringID8 = stringsApi.addString(seasonID, strJson.toString(), sessionToken); Assert.assertFalse(stringID8.contains("Error"), "String was not added:" + stringID4); //create entitlement and purchaseOptions tree in season1 String entitlement1 = FileUtils.fileToString(filePath + "purchases/inAppPurchase1.txt", "UTF-8", false); entitlementID1 = purchasesApi.addPurchaseItem(seasonID, entitlement1, "ROOT", sessionToken); Assert.assertFalse(entitlementID1.contains("error"), "Entitlement was not added to the season"); String entitlementMix = FileUtils.fileToString(filePath + "purchases/inAppPurchaseMutual.txt", "UTF-8", false); String mixID1 = purchasesApi.addPurchaseItem(seasonID, entitlementMix, entitlementID1, sessionToken); Assert.assertFalse(mixID1.contains("error"), "Entitlement mix was not added to the season: " + mixID1); String entitlement2 = FileUtils.fileToString(filePath + "purchases/inAppPurchase2.txt", "UTF-8", false); String entitlementID2 = purchasesApi.addPurchaseItem(seasonID, entitlement2, mixID1, sessionToken); Assert.assertFalse(entitlementID2.contains("error"), "Entitlement was not added to the season"); String entitlement3 = FileUtils.fileToString(filePath + "purchases/inAppPurchase3.txt", "UTF-8", false); String entitlementID3 = purchasesApi.addPurchaseItem(seasonID, entitlement3, mixID1, sessionToken); Assert.assertFalse(entitlementID3.contains("error"), "Entitlement was not added to the season"); String configurationMix = FileUtils.fileToString(filePath + "configuration_feature-mutual.txt", "UTF-8", false); String mixConfigID = purchasesApi.addPurchaseItem(seasonID, configurationMix, entitlementID2, sessionToken); Assert.assertFalse(mixConfigID.contains("error"), "Configuration mix was not added to the season"); String configuration1 = FileUtils.fileToString(filePath + "configuration_rule1.txt", "UTF-8", false); JSONObject jsonCR = new JSONObject(configuration1); jsonCR.put("name", "CR1"); jsonCR.put("configuration", "{ \"text\" : translate(\"app.hello\", \"testing string\") }"); String configID1 = purchasesApi.addPurchaseItem(seasonID, jsonCR.toString(), mixConfigID, sessionToken); Assert.assertFalse(configID1.contains("error"), "cr was not added to the season"); jsonCR.put("name", "CR2"); jsonCR.put("configuration", "{ \"text\" : translate(\"app.hello2\", \"testing string\") }"); String configID2 = purchasesApi.addPurchaseItem(seasonID, jsonCR.toString(), mixConfigID, sessionToken); Assert.assertFalse(configID2.contains("error"), "cr was not added to the season"); jsonCR.put("name", "CR3"); jsonCR.put("configuration", "{ \"text\" : translate(\"app.hello3\", \"testing string\") }"); String configID3 = purchasesApi.addPurchaseItem(seasonID, jsonCR.toString(),entitlementID3, sessionToken); Assert.assertFalse(configID3.contains("error"), "cr was not added to the season"); jsonCR.put("name", "CR4"); jsonCR.put("configuration", "{ \"text\" : translate(\"app.hello4\", \"testing string\") }"); String configID4 = purchasesApi.addPurchaseItem(seasonID, jsonCR.toString(),configID3, sessionToken); Assert.assertFalse(configID4.contains("error"), "cr was not added to the season"); ///// String purchaseOptionsMix = FileUtils.fileToString(filePath + "purchases/purchaseOptionsMutual.txt", "UTF-8", false); String purchaseOptionsmixID = purchasesApi.addPurchaseItem(seasonID, purchaseOptionsMix, entitlementID1, sessionToken); Assert.assertFalse(purchaseOptionsmixID.contains("error"), "Entitlement mix was not added to the season: " + purchaseOptionsmixID); String purchaseOptions1 = FileUtils.fileToString(filePath + "purchases/purchaseOptions1.txt", "UTF-8", false); purchaseOptionsID1 = purchasesApi.addPurchaseItem(seasonID, purchaseOptions1, purchaseOptionsmixID, sessionToken); Assert.assertFalse(purchaseOptionsID1.contains("error"), "purchaseOptions was not added to the season"); String purchaseOptions2 = FileUtils.fileToString(filePath + "purchases/purchaseOptions2.txt", "UTF-8", false); String purchaseOptionsID2 = purchasesApi.addPurchaseItem(seasonID, purchaseOptions2, purchaseOptionsmixID, sessionToken); Assert.assertFalse(purchaseOptionsID2.contains("error"), "Entitlement was not added to the season"); String configurationMix2 = FileUtils.fileToString(filePath + "configuration_feature-mutual.txt", "UTF-8", false); String mixConfigID2 = purchasesApi.addPurchaseItem(seasonID, configurationMix2, purchaseOptionsID1, sessionToken); Assert.assertFalse(mixConfigID2.contains("error"), "Configuration mix was not added to the season"); jsonCR = new JSONObject(configuration1); jsonCR.put("name", "CR5"); jsonCR.put("configuration", "{ \"text\" : translate(\"app.hello5\", \"testing string\") }"); String configID5 = purchasesApi.addPurchaseItem(seasonID, jsonCR.toString(), mixConfigID2, sessionToken); Assert.assertFalse(configID5.contains("error"), "cr was not added to the season"); jsonCR.put("name", "CR6"); jsonCR.put("configuration", "{ \"text\" : translate(\"app.hello6\", \"testing string\") }"); String configID6 = purchasesApi.addPurchaseItem(seasonID, jsonCR.toString(), mixConfigID2, sessionToken); Assert.assertFalse(configID6.contains("error"), "cr was not added to the season"); jsonCR.put("name", "CR7"); jsonCR.put("configuration", "{ \"text\" : translate(\"app.hello7\", \"testing string\") }"); String configID7 = purchasesApi.addPurchaseItem(seasonID, jsonCR.toString(), purchaseOptionsID2, sessionToken); Assert.assertFalse(configID7.contains("error"), "cr was not added to the season"); jsonCR.put("name", "CR8"); jsonCR.put("configuration", "{ \"text\" : translate(\"app.hello8\", \"testing string\") }"); String configID8 = purchasesApi.addPurchaseItem(seasonID, jsonCR.toString(),configID7, sessionToken); Assert.assertFalse(configID8.contains("error"), "cr was not added to the season"); } @Test (dependsOnMethods="addComponents", description = "Copy entitlement to season2 - no string conflict") public void copyEntitlementDifferentSeason() throws Exception{ String rootId2 = purchasesApi.getBranchRootId(seasonID2, "MASTER", sessionToken); String response = f.copyFeature(entitlementID1, rootId2, "ACT", null, null, sessionToken); Assert.assertTrue(response.contains("newSubTreeId"), "Entitlement was not copied: " + response); //validate that strings were copied to season2 String stringsInSeason = stringsApi.getAllStrings(seasonID2, sessionToken); JSONObject stringsInSeasonJson = new JSONObject(stringsInSeason); Assert.assertTrue(stringsInSeasonJson.getJSONArray("strings").size()==8, "Not all strings were copied to season2"); } @Test (dependsOnMethods="copyEntitlementDifferentSeason", description = "Copy purchaseOptions to season3 - no string conflict") public void copyPurchaseOptionsDifferentSeason() throws Exception{ String entitlement = FileUtils.fileToString(filePath + "purchases/inAppPurchase1.txt", "UTF-8", false); String entitlementID = purchasesApi.addPurchaseItem(seasonID3, entitlement, "ROOT", sessionToken); Assert.assertFalse(entitlementID.contains("error"), "Entitlement was not added to the season3"); String response = f.copyFeature(purchaseOptionsID1, entitlementID, "ACT", null, null, sessionToken); Assert.assertTrue(response.contains("newSubTreeId"), "Entitlement was not copied: " + response); //validate that strings were copied to season3 String stringsInSeason = stringsApi.getAllStrings(seasonID3, sessionToken); JSONObject stringsInSeasonJson = new JSONObject(stringsInSeason); Assert.assertTrue(stringsInSeasonJson.getJSONArray("strings").size()==2, "Not all strings were copied to season3"); } @AfterTest private void reset(){ baseUtils.reset(productID, sessionToken); } }
54.373391
210
0.743784
e68756f64c741c3c812bac0a802616352cfea2a8
1,400
package com.skywomantech.app.symptommanagement.data.graphics; public class MedicationPlotPoint extends TimePoint { String medId; String name; public MedicationPlotPoint() { } public MedicationPlotPoint(long timeValue, String medId, String name) { super(timeValue); this.medId = medId; this.name = name; } public String getMedId() { return medId; } public void setMedId(String medId) { this.medId = medId; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof MedicationPlotPoint)) return false; if (!super.equals(o)) return false; MedicationPlotPoint that = (MedicationPlotPoint) o; if (medId != null ? !medId.equals(that.medId) : that.medId != null) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (medId != null ? medId.hashCode() : 0); return result; } @Override public String toString() { return "MedicationPlotPoint{" + "medId='" + medId + '\'' + ", name='" + name + '\'' + "} " + super.toString(); } }
23.728814
89
0.567143
861f880ba7299680b512eb355e8b633dcc1e3dc9
1,593
package dagger.activity; import android.app.Activity; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import dagger.application.DaggerApplication; import dagger.bot.R; import dagger.fragment.StabbedFragment; import javax.inject.Inject; public class StabbedActivity extends Activity { @Inject LocationManager locationManager; private TextView locationView; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.stabbed_activity); DaggerApplication.inject(this); locationView = (TextView) findViewById(R.id.locationView); button = (Button) findViewById(R.id.button); Location location = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); String text = String.format("Last known location: (%f, %f)", location.getLatitude(), location.getLongitude()); locationView.setText(text); button.setOnClickListener(new FragmentStabber()); } private class FragmentStabber implements View.OnClickListener { @Override public void onClick(View view) { StabbedFragment stabbedFragment = new StabbedFragment(); DaggerApplication.inject(stabbedFragment); getFragmentManager().beginTransaction() .setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out) .replace(R.id.container, stabbedFragment).addToBackStack(null).commit(); } } }
32.510204
95
0.7715
3021171f3ecba1edb9b606727ad2ff5339d2f74a
151
package com.icewind.silestahivesync.dto; import lombok.Data; @Data public class BaseApiDto { public long dayStart; public boolean status; }
13.727273
40
0.748344
48320471fa41a8720d68bd0f235e6e81b038864c
226
package com.kiselev.enemy.network.telegram.api.bot.command; import com.pengrad.telegrambot.model.Update; public interface TelegramCommand { boolean is(Update update); void execute(Update update, String... args); }
20.545455
59
0.761062
5b25249e30820d79a257bf36f35d8bfe4643457b
2,921
package com.pi.web; import android.os.AsyncTask; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by Marcelo Júnior on 13/12/2017. */ public abstract class Web { public final String GET = "GET"; public final String POST = "POST"; public final String PUT = "PUT"; public final String DELETE = "DELETE"; private final int SEGUNDOS = 1000; private final String CONTENT_TYPE = "Content-Type"; private final String APPLICATION_JSON = "application/json"; private HttpURLConnection conexao; private WebTask webTask; protected boolean conectar(String urlWebService) { return conectar(urlWebService, GET, false); } protected boolean conectar(String urlWebService, String metodo) { return conectar(urlWebService, metodo, false); } protected boolean conectar(String urlWebService, String metodo, boolean fazOutput) { try { URL url = new URL(urlWebService); this.conexao = (HttpURLConnection) url.openConnection(); this.conexao.setReadTimeout(15 * SEGUNDOS); this.conexao.setConnectTimeout(10 * SEGUNDOS); this.conexao.setRequestMethod(metodo); this.conexao.setDoInput(true); this.conexao.setDoOutput(fazOutput); if (fazOutput) { this.conexao.addRequestProperty(CONTENT_TYPE, APPLICATION_JSON); } this.conexao.connect(); return true; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } public void onPreExecute() { } public void onPostExecute(Object o) { } public abstract Object doInBackground(int requestCode); public String getDados() { try { return streamParaString(this.conexao.getInputStream()); } catch (IOException e) { e.printStackTrace(); } return null; } private String streamParaString(InputStream is) { byte[] bytes = new byte[1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int lidos = 0; try { while ((lidos = is.read(bytes)) > 0) { baos.write(bytes, 0, lidos); } return new String(baos.toByteArray()); } catch (IOException e) { e.printStackTrace(); } return null; } public void executar(String urlWebService, int requestCode) { if (webTask == null || webTask.getStatus() != AsyncTask.Status.RUNNING) { this.webTask = new WebTask(urlWebService, this); this.webTask.execute(new Integer[]{requestCode}); } } }
28.637255
88
0.619993
e598705a48408b019140cf22054476800de8d897
1,089
package org.squirrelframework.cloud.resource.security.rsa; import com.google.common.base.Preconditions; import org.apache.commons.codec.binary.Base64; import org.squirrelframework.cloud.resource.security.AbstractSignatureChecker; import org.squirrelframework.cloud.utils.CloudConfigCommon; import java.security.Key; import java.security.PublicKey; import java.security.Signature; /** * Created by kailianghe on 16/1/6. */ public class RSASignatureChecker extends AbstractSignatureChecker { private final PublicKey publicKey; public RSASignatureChecker(Key publicKey) { Preconditions.checkArgument(publicKey instanceof PublicKey, "must use public key to verify signature"); this.publicKey = (PublicKey) publicKey; } public boolean verify(String data, String charset, String sign) throws Exception { Signature signature = Signature.getInstance(CloudConfigCommon.SIGNATURE_ALGORITHM); signature.initVerify(publicKey); signature.update(data.getBytes(charset)); return signature.verify(Base64.decodeBase64(sign)); } }
35.129032
111
0.775023
395b6a2e929aa23f7b29a218a5c73606255b2c60
4,496
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings.deviceinfo; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.net.TrafficStats; import android.os.AsyncTask; import android.os.IBinder; import android.os.RemoteException; import android.os.UserHandle; import android.os.storage.StorageManager; import android.os.storage.VolumeInfo; import android.telecom.Log; import android.text.format.DateUtils; import android.text.format.Formatter; import com.android.internal.app.IMediaContainerService; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static com.android.settings.deviceinfo.StorageSettings.TAG; public abstract class MigrateEstimateTask extends AsyncTask<Void, Void, Long> implements ServiceConnection { private static final String EXTRA_SIZE_BYTES = "size_bytes"; private static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( "com.android.defcontainer", "com.android.defcontainer.DefaultContainerService"); /** * Assume roughly a Class 10 card. */ private static final long SPEED_ESTIMATE_BPS = 10 * TrafficStats.MB_IN_BYTES; private final Context mContext; private final StorageManager mStorage; private final CountDownLatch mConnected = new CountDownLatch(1); private IMediaContainerService mService; private long mSizeBytes = -1; public MigrateEstimateTask(Context context) { mContext = context; mStorage = context.getSystemService(StorageManager.class); } public void copyFrom(Intent intent) { mSizeBytes = intent.getLongExtra(EXTRA_SIZE_BYTES, -1); } public void copyTo(Intent intent) { intent.putExtra(EXTRA_SIZE_BYTES, mSizeBytes); } @Override protected Long doInBackground(Void... params) { if (mSizeBytes != -1) { return mSizeBytes; } final VolumeInfo privateVol = mContext.getPackageManager().getPrimaryStorageCurrentVolume(); final VolumeInfo emulatedVol = mStorage.findEmulatedForPrivate(privateVol); if (emulatedVol == null) { Log.w(TAG, "Failed to find current primary storage"); return -1L; } final String path = emulatedVol.getPath().getAbsolutePath(); Log.d(TAG, "Estimating for current path " + path); final Intent intent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM); try { if (mConnected.await(15, TimeUnit.SECONDS)) { return mService.calculateDirectorySize(path); } } catch (InterruptedException | RemoteException e) { Log.w(TAG, "Failed to measure " + path); } finally { mContext.unbindService(this); } return -1L; } @Override protected void onPostExecute(Long result) { mSizeBytes = result; long timeMillis = (mSizeBytes * DateUtils.SECOND_IN_MILLIS) / SPEED_ESTIMATE_BPS; timeMillis = Math.max(timeMillis, DateUtils.SECOND_IN_MILLIS); final String size = Formatter.formatFileSize(mContext, mSizeBytes); final String time = DateUtils.formatDuration(timeMillis).toString(); onPostExecute(size, time); } public abstract void onPostExecute(String size, String time); @Override public void onServiceConnected(ComponentName name, IBinder service) { mService = IMediaContainerService.Stub.asInterface(service); mConnected.countDown(); } @Override public void onServiceDisconnected(ComponentName name) { // Ignored; we leave service in place for the background thread to // run into DeadObjectException } }
34.060606
100
0.711077
323df828aedea2daacc64d687a6e9a12d726f154
3,064
package commons.box.app.bean; import commons.box.app.AppError; import commons.box.util.Strs; /** * Bean操作,封装了针对metaBean,map和object的统一访问机制 * <p>创建作者:xingxiuyi </p> * <p>版权所属:xingxiuyi </p> */ public interface BeanAccess { public static final Class<?> DEFAULT_TYPE = Object.class; /** * @param type * @param <T> * @return * @throws AppError */ public <T> T inst(Class<T> type) throws AppError; /** * 获取属性 * * @param bean * @param property * @param <T> * @param <O> * @return * @throws AppError */ public <T, O> O prop(T bean, String property) throws AppError; /** * 设置属性 * * @param bean * @param property * @param value * @param <T> * @param <O> * @throws AppError */ public <T, O> void prop(T bean, String property, O value) throws AppError; /** * 获取字段值 * * @param bean * @param name * @param <T> * @param <O> * @return * @throws AppError */ public <T, O> O field(T bean, String name) throws AppError; /** * 设置字段值 * * @param bean * @param name * @param value * @param <T> * @param <O> * @throws AppError */ public <T, O> void field(T bean, String name, O value) throws AppError; /** * 调用方法 * * @param bean * @param method * @param args * @param <T> * @param <R> * @return * @throws AppError */ public <T, R> R invoke(T bean, String method, Object... args) throws Throwable; /** * 是否包含属性 * * @param bean * @param name * @param <T> * @return */ public <T> boolean has(T bean, String name); /** * 是否包含字段 * * @param bean * @param name * @param <T> * @return */ public <T> boolean hasField(T bean, String name); /** * 是否包含方法 * * @param bean * @param method * @param args * @param <T> * @return */ public <T> boolean canInvoke(T bean, String method, Object... args); /** * 属性名 * <p> * 对于Object返回Bean Property名, 包含通过getter或setter访问的属性和field * <p> * 对于map返回keys * * @param bean * @param <T> * @return */ public <T> String[] props(T bean); /** * 字段名 * <p> * 对于Object来说此方法只返回可公共访问的Field,不包括通常意义的property(包含getter或setter) * <p> * 对于map返回keys,与property一致 * * @param bean * @param <T> * @return */ public <T> String[] fields(T bean); /** * 获取属性对应的类型 如果属性为空 返回bean当前类型 属性不存在返回Object 注意此方法返回永远不为空 * * @param bean * @param prop * @param <T> * @return */ public <T> Class<?> type(T bean, String prop); /** * 是否表示本对象的属性 用于type判断过程 * 以下值表示本对象: * 空 空字符串 $ . * * @param prop * @return */ default boolean isThis(String prop) { return (Strs.isBlank(prop) || Strs.equals(prop, "$") || Strs.equals(prop, ".")); } }
18.797546
88
0.506201
d353ad3cd6f6cddf8d453905e7a03701ed720d2d
2,776
package com.itfvck.wechatframework.api.jsapi; import org.apache.commons.lang3.StringUtils; import com.alibaba.fastjson.JSON; import com.itfvck.wechatframework.core.util.EncryptUtil; import com.itfvck.wechatframework.core.util.RandomStringGenerator; import com.itfvck.wechatframework.core.util.http.HttpUtils; /** * JS-SDK操作API * * @Author vcdemon * @CreationDate 2016年5月12日 上午10:31:55 * */ public class WxJsSDKAPI { private static final String GET_JS_SDK_CONF = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi"; /** * @Description 获取ticket(jsapi_ticket) * @param access_token * 传入access_token * @return * @CreationDate 2016年5月25日 下午3:59:07 * @Author vcdemon */ public static String getJs_tiket(String access_token) { JSSDKParams jssdkConf = new JSSDKParams(); jssdkConf.setAccess_token(access_token); jssdkConf = getJSSDKConf(jssdkConf); if (StringUtils.isNotEmpty(jssdkConf.getTicket())) { return jssdkConf.getTicket(); } return null; } /** * @Description 获取ticket(jsapi_ticket) * @param jssdkConf * 传入access_token * @return * @CreationDate 2016年5月25日 下午3:59:07 * @Author vcdemon */ private static JSSDKParams getJSSDKConf(JSSDKParams jssdkConf) { try { String responseBody = HttpUtils.get(String.format(GET_JS_SDK_CONF, jssdkConf.getAccess_token())); if (StringUtils.isNotEmpty(responseBody)) { jssdkConf.setTicket(JSON.parseObject(responseBody, JSSDKParams.class).getTicket()); } } catch (Exception e) { e.printStackTrace(); } return jssdkConf; } /** * @Description JS-SDK使用权限签名算法 * @param ticket * (jsapi_ticket) * @param url * 当前网页url * @return * @CreationDate 2016年5月25日 下午4:00:42 */ public static JSSDKParams signatureJS_SDK(String ticket, String url, String appid) { JSSDKParams jssdkConf = new JSSDKParams(); jssdkConf.setNonceStr(RandomStringGenerator.generate()); jssdkConf.setTimestamp(System.currentTimeMillis() / 1000); jssdkConf.setSignature(signatureJSSDKConf(ticket, url, jssdkConf.getNonceStr(), jssdkConf.getTimestamp())); jssdkConf.setAppId(appid); return jssdkConf; } /** * @Description JS-SDK使用权限签名算法 * @param jssdkConf * 传入ticket(jsapi_ticket),url * @return * @CreationDate 2016年5月25日 下午4:00:42 * @Author vcdemon */ private static String signatureJSSDKConf(String ticket, String url, String nonceStr, Long timestamp) { return EncryptUtil.SHA1Encrypt(new StringBuilder().append("jsapi_ticket=").append(ticket).append("&noncestr=").append(nonceStr).append("&timestamp=").append(timestamp) .append("&url=").append(url).toString()); } }
30.505495
170
0.700648
94b9a67169b498a11327a6628f31035df7ec7d3f
371
package io.datakitchen.ide.model; import java.util.EventObject; public class ConnectionListEvent extends EventObject { private Connection connection; public ConnectionListEvent(Object source, Connection connection) { super(source); this.connection = connection; } public Connection getConnection(){ return connection; } }
20.611111
70
0.714286
71c753b39145a4c4613052a35e92051666317a37
352
package l09.contas; public class ContaEspecial extends ContaCorrente { private double taxa = 0.5; public ContaEspecial(double saldoInicial, String numConta, String t) { super(saldoInicial, numConta, t); } public void sacar(double valorSaque) { double novosaldo = (this.getSaldo() - (valorSaque + taxa)); this.setSaldo(novosaldo); } }
20.705882
71
0.727273
8849ec9d5374f70d5810c8fad085f4d2b2cb24b1
26,596
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.android_webview.test; import android.os.Build; import android.test.suitebuilder.annotation.SmallTest; import static org.chromium.base.test.util.ScalableTimeout.scaleTimeout; import static org.chromium.content.browser.test.util.TestCallbackHelperContainer.OnPageFinishedHelper; import org.chromium.android_webview.AwContents; import org.chromium.android_webview.AwMessagePortService; import org.chromium.android_webview.MessagePort; import org.chromium.android_webview.test.util.CommonResources; import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.MinAndroidSdkLevel; import org.chromium.content.browser.test.util.Criteria; import org.chromium.content.browser.test.util.CriteriaHelper; import org.chromium.net.test.util.TestWebServer; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; /** * The tests for content postMessage API. */ @MinAndroidSdkLevel(Build.VERSION_CODES.KITKAT) public class PostMessageTest extends AwTestBase { private static final String SOURCE_ORIGIN = ""; // Timeout to failure, in milliseconds private static final long TIMEOUT = scaleTimeout(5000); // Inject to the page to verify received messages. private static class MessageObject { private boolean mReady; private String mData; private String mOrigin; private int[] mPorts; private Object mLock = new Object(); public void setMessageParams(String data, String origin, int[] ports) { synchronized (mLock) { mData = data; mOrigin = origin; mPorts = ports; mReady = true; mLock.notify(); } } public void waitForMessage() throws InterruptedException { synchronized (mLock) { if (!mReady) mLock.wait(TIMEOUT); } } public String getData() { return mData; } public String getOrigin() { return mOrigin; } public int[] getPorts() { return mPorts; } } private MessageObject mMessageObject; private TestAwContentsClient mContentsClient; private AwTestContainerView mTestContainerView; private AwContents mAwContents; private TestWebServer mWebServer; @Override protected void setUp() throws Exception { super.setUp(); mMessageObject = new MessageObject(); mContentsClient = new TestAwContentsClient(); mTestContainerView = createAwTestContainerViewOnMainSync(mContentsClient); mAwContents = mTestContainerView.getAwContents(); enableJavaScriptOnUiThread(mAwContents); try { runTestOnUiThread(new Runnable() { @Override public void run() { mAwContents.addPossiblyUnsafeJavascriptInterface(mMessageObject, "messageObject", null); } }); } catch (Throwable t) { throw new RuntimeException(t); } mWebServer = TestWebServer.start(); } @Override protected void tearDown() throws Exception { mWebServer.shutdown(); super.tearDown(); } private static final String WEBVIEW_MESSAGE = "from_webview"; private static final String JS_MESSAGE = "from_js"; private static final String TEST_PAGE = "<!DOCTYPE html><html><body>" + " <script type=\"text/javascript\">" + " onmessage = function (e) {" + " messageObject.setMessageParams(e.data, e.origin, e.ports);" + " if (e.ports != null && e.ports.length > 0) {" + " e.ports[0].postMessage(\"" + JS_MESSAGE + "\");" + " }" + " }" + " </script>" + "</body></html>"; private void loadPage(String page) throws Throwable { final String url = mWebServer.setResponse("/test.html", page, CommonResources.getTextHtmlHeaders(true)); OnPageFinishedHelper onPageFinishedHelper = mContentsClient.getOnPageFinishedHelper(); int currentCallCount = onPageFinishedHelper.getCallCount(); loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), url); onPageFinishedHelper.waitForCallback(currentCallCount); } @SmallTest @Feature({"AndroidWebView", "Android-PostMessage"}) public void testPostMessageToMainFrame() throws Throwable { loadPage(TEST_PAGE); runTestOnUiThread(new Runnable() { @Override public void run() { mAwContents.postMessageToFrame(null, WEBVIEW_MESSAGE, mWebServer.getBaseUrl(), null); } }); mMessageObject.waitForMessage(); assertEquals(WEBVIEW_MESSAGE, mMessageObject.getData()); assertEquals(SOURCE_ORIGIN, mMessageObject.getOrigin()); } @SmallTest @Feature({"AndroidWebView", "Android-PostMessage"}) public void testTransferringSamePortTwiceViaPostMessageToFrameNotAllowed() throws Throwable { loadPage(TEST_PAGE); final CountDownLatch latch = new CountDownLatch(1); runTestOnUiThread(new Runnable() { @Override public void run() { MessagePort[] channel = mAwContents.createMessageChannel(); mAwContents.postMessageToFrame(null, "1", mWebServer.getBaseUrl(), new MessagePort[]{channel[1]}); // Retransfer the port. This should fail with an exception. try { mAwContents.postMessageToFrame(null, "2", mWebServer.getBaseUrl(), new MessagePort[]{channel[1]}); } catch (IllegalStateException ex) { latch.countDown(); return; } fail(); } }); boolean ignore = latch.await(TIMEOUT, java.util.concurrent.TimeUnit.MILLISECONDS); } // channel[0] and channel[1] are entangled ports, establishing a channel. Verify // it is not allowed to transfer channel[0] on channel[0].postMessage. // TODO(sgurun) Note that the related case of posting channel[1] via // channel[0].postMessage does not throw a JS exception at present. We do not throw // an exception in this case either since the information of entangled port is not // available at the source port. We need a new mechanism to implement to prevent // this case. @SmallTest @Feature({"AndroidWebView", "Android-PostMessage"}) public void testTransferSourcePortViaMessageChannelNotAllowed() throws Throwable { loadPage(TEST_PAGE); final CountDownLatch latch = new CountDownLatch(1); runTestOnUiThread(new Runnable() { @Override public void run() { MessagePort[] channel = mAwContents.createMessageChannel(); try { channel[0].postMessage("1", new MessagePort[]{channel[0]}); } catch (IllegalStateException ex) { latch.countDown(); return; } fail(); } }); boolean ignore = latch.await(TIMEOUT, java.util.concurrent.TimeUnit.MILLISECONDS); } // Verify a closed port cannot be transferred to a frame. @SmallTest @Feature({"AndroidWebView", "Android-PostMessage"}) public void testSendClosedPortToFrameNotAllowed() throws Throwable { loadPage(TEST_PAGE); final CountDownLatch latch = new CountDownLatch(1); runTestOnUiThread(new Runnable() { @Override public void run() { MessagePort[] channel = mAwContents.createMessageChannel(); channel[1].close(); try { mAwContents.postMessageToFrame(null, "1", mWebServer.getBaseUrl(), new MessagePort[]{channel[1]}); } catch (IllegalStateException ex) { latch.countDown(); return; } fail(); } }); boolean ignore = latch.await(TIMEOUT, java.util.concurrent.TimeUnit.MILLISECONDS); } // Verify a closed port cannot be transferred to a port. @SmallTest @Feature({"AndroidWebView", "Android-PostMessage"}) public void testSendClosedPortToPortNotAllowed() throws Throwable { loadPage(TEST_PAGE); final CountDownLatch latch = new CountDownLatch(1); runTestOnUiThread(new Runnable() { @Override public void run() { MessagePort[] channel1 = mAwContents.createMessageChannel(); MessagePort[] channel2 = mAwContents.createMessageChannel(); channel2[1].close(); try { channel1[0].postMessage("1", new MessagePort[]{channel2[1]}); } catch (IllegalStateException ex) { latch.countDown(); return; } fail(); } }); boolean ignore = latch.await(TIMEOUT, java.util.concurrent.TimeUnit.MILLISECONDS); } // Verify messages cannot be posted to closed ports. @SmallTest @Feature({"AndroidWebView", "Android-PostMessage"}) public void testPostMessageToClosedPortNotAllowed() throws Throwable { loadPage(TEST_PAGE); final CountDownLatch latch = new CountDownLatch(1); runTestOnUiThread(new Runnable() { @Override public void run() { MessagePort[] channel = mAwContents.createMessageChannel(); channel[0].close(); try { channel[0].postMessage("1", null); } catch (IllegalStateException ex) { latch.countDown(); return; } fail(); } }); boolean ignore = latch.await(TIMEOUT, java.util.concurrent.TimeUnit.MILLISECONDS); } private static class ChannelContainer { private boolean mReady; private MessagePort[] mChannel; private Object mLock = new Object(); private String mMessage; public void set(MessagePort[] channel) { mChannel = channel; } public MessagePort[] get() { return mChannel; } public void setMessage(String message) { synchronized (mLock) { mMessage = message; mReady = true; mLock.notify(); } } public String getMessage() { return mMessage; } public void waitForMessage() throws InterruptedException { synchronized (mLock) { if (!mReady) mLock.wait(TIMEOUT); } } } // Verify that messages from JS can be waited on a UI thread. // TODO(sgurun) this test turned out to be flaky. When it fails, it always fails in IPC. // When a postmessage is received, an IPC message is sent from browser to renderer // to convert the postmessage from WebSerializedScriptValue to a string. The IPC is sent // and seems to be received by IPC in renderer, but then nothing else seems to happen. // The issue seems like blocking the UI thread causes a racing SYNC ipc from renderer // to browser to block waiting for UI thread, and this would in turn block renderer // doing the conversion. @DisabledTest @Feature({"AndroidWebView", "Android-PostMessage"}) public void testReceiveMessageInBackgroundThread() throws Throwable { loadPage(TEST_PAGE); final ChannelContainer channelContainer = new ChannelContainer(); runTestOnUiThread(new Runnable() { @Override public void run() { MessagePort[] channel = mAwContents.createMessageChannel(); // verify communication from JS to Java. channelContainer.set(channel); channel[0].setWebEventHandler(new MessagePort.WebEventHandler() { @Override public void onMessage(String message) { channelContainer.setMessage(message); } }); mAwContents.postMessageToFrame(null, WEBVIEW_MESSAGE, mWebServer.getBaseUrl(), new MessagePort[]{channel[1]}); } }); mMessageObject.waitForMessage(); assertEquals(WEBVIEW_MESSAGE, mMessageObject.getData()); assertEquals(SOURCE_ORIGIN, mMessageObject.getOrigin()); // verify that one message port is received at the js side assertEquals(1, mMessageObject.getPorts().length); // wait until we receive a message from JS runTestOnUiThread(new Runnable() { @Override public void run() { try { channelContainer.waitForMessage(); } catch (InterruptedException e) { // ignore. } } }); assertEquals(JS_MESSAGE, channelContainer.getMessage()); } private static final String ECHO_PAGE = "<!DOCTYPE html><html><body>" + " <script type=\"text/javascript\">" + " onmessage = function (e) {" + " var myPort = e.ports[0];" + " myPort.onmessage = function(e) {" + " myPort.postMessage(e.data + \"" + JS_MESSAGE + "\"); }" + " }" + " </script>" + "</body></html>"; // Call on non-UI thread. private void waitUntilPortReady(final MessagePort port) throws Throwable { CriteriaHelper.pollForCriteria(new Criteria() { @Override public boolean isSatisfied() { return ThreadUtils.runOnUiThreadBlockingNoException( new Callable<Boolean>() { @Override public Boolean call() throws Exception { return port.isReady(); } }); } }); } private static final String HELLO = "HELLO"; // Message channels are created on UI thread in a pending state. They are // initialized at a later stage. Verify that a message port that is initialized // can be transferred to JS and full communication can happen on it. // Do this by sending a message to JS and let it echo'ing the message with // some text prepended to it. @SmallTest @Feature({"AndroidWebView", "Android-PostMessage"}) public void testMessageChannelUsingInitializedPort() throws Throwable { final ChannelContainer channelContainer = new ChannelContainer(); loadPage(ECHO_PAGE); final MessagePort[] channel = ThreadUtils.runOnUiThreadBlocking( new Callable<MessagePort[]>() { @Override public MessagePort[] call() { return mAwContents.createMessageChannel(); } }); waitUntilPortReady(channel[0]); waitUntilPortReady(channel[1]); runTestOnUiThread(new Runnable() { @Override public void run() { channel[0].setWebEventHandler(new MessagePort.WebEventHandler() { @Override public void onMessage(String message) { channelContainer.setMessage(message); } }); mAwContents.postMessageToFrame(null, WEBVIEW_MESSAGE, mWebServer.getBaseUrl(), new MessagePort[]{channel[1]}); channel[0].postMessage(HELLO, null); } }); // wait for the asynchronous response from JS channelContainer.waitForMessage(); assertEquals(HELLO + JS_MESSAGE, channelContainer.getMessage()); } // Verify that a message port can be used immediately (even if it is in // pending state) after creation. In particular make sure the message port can be // transferred to JS and full communication can happen on it. // Do this by sending a message to JS and let it echo'ing the message with // some text prepended to it. @SmallTest @Feature({"AndroidWebView", "Android-PostMessage"}) public void testMessageChannelUsingPendingPort() throws Throwable { final ChannelContainer channelContainer = new ChannelContainer(); loadPage(ECHO_PAGE); runTestOnUiThread(new Runnable() { @Override public void run() { MessagePort[] channel = mAwContents.createMessageChannel(); channel[0].setWebEventHandler(new MessagePort.WebEventHandler() { @Override public void onMessage(String message) { channelContainer.setMessage(message); } }); mAwContents.postMessageToFrame(null, WEBVIEW_MESSAGE, mWebServer.getBaseUrl(), new MessagePort[]{channel[1]}); channel[0].postMessage(HELLO, null); } }); // Wait for the asynchronous response from JS. channelContainer.waitForMessage(); assertEquals(HELLO + JS_MESSAGE, channelContainer.getMessage()); } // Verify that a message port can be used for message transfer when both // ports are owned by same Webview. @SmallTest @Feature({"AndroidWebView", "Android-PostMessage"}) public void testMessageChannelCommunicationWithinWebView() throws Throwable { final ChannelContainer channelContainer = new ChannelContainer(); loadPage(ECHO_PAGE); runTestOnUiThread(new Runnable() { @Override public void run() { MessagePort[] channel = mAwContents.createMessageChannel(); channel[1].setWebEventHandler(new MessagePort.WebEventHandler() { @Override public void onMessage(String message) { channelContainer.setMessage(message); } }); channel[0].postMessage(HELLO, null); } }); // Wait for the asynchronous response from JS. channelContainer.waitForMessage(); assertEquals(HELLO, channelContainer.getMessage()); } // concats all the data fields of the received messages and makes it // available as page title. private static final String TITLE_PAGE = "<!DOCTYPE html><html><body>" + " <script>" + " var received = \"\";" + " onmessage = function (e) {" + " received = received + e.data;" + " document.title = received;" + " }" + " </script>" + "</body></html>"; // Call on non-UI thread. private void expectTitle(final String title) throws Throwable { assertTrue("Received title " + mAwContents.getTitle() + " while expecting " + title, CriteriaHelper.pollForCriteria(new Criteria() { @Override public boolean isSatisfied() { return ThreadUtils.runOnUiThreadBlockingNoException( new Callable<Boolean>() { @Override public Boolean call() throws Exception { return mAwContents.getTitle().equals(title); } }); } })); } // Post a message with a pending port to a frame and then post a bunch of messages // after that. Make sure that they are not ordered at the receiver side. @SmallTest @Feature({"AndroidWebView", "Android-PostMessage"}) public void testPostMessageToFrameNotReordersMessages() throws Throwable { loadPage(TITLE_PAGE); runTestOnUiThread(new Runnable() { @Override public void run() { MessagePort[] channel = mAwContents.createMessageChannel(); mAwContents.postMessageToFrame(null, "1", mWebServer.getBaseUrl(), new MessagePort[]{channel[1]}); mAwContents.postMessageToFrame(null, "2", mWebServer.getBaseUrl(), null); mAwContents.postMessageToFrame(null, "3", mWebServer.getBaseUrl(), null); } }); expectTitle("123"); } private static class TestMessagePort extends MessagePort { private boolean mReady; private MessagePort mPort; private Object mLock = new Object(); public TestMessagePort(AwMessagePortService service) { super(service); } public void setMessagePort(MessagePort port) { mPort = port; } public void setReady(boolean ready) { synchronized (mLock) { mReady = ready; } } @Override public boolean isReady() { synchronized (mLock) { return mReady; } } @Override public int portId() { return mPort.portId(); } @Override public void setPortId(int id) { mPort.setPortId(id); } @Override public void close() { mPort.close(); } @Override public boolean isClosed() { return mPort.isClosed(); } @Override public void setWebEventHandler(WebEventHandler handler) { mPort.setWebEventHandler(handler); } @Override public void onMessage(String message) { mPort.onMessage(message); } @Override public void postMessage(String message, MessagePort[] msgPorts) throws IllegalStateException { mPort.postMessage(message, msgPorts); } } // Post a message with a pending port to a frame and then post a message that // is pending after that. Make sure that when first message becomes ready, // the subsequent not-ready message is not sent. @SmallTest @Feature({"AndroidWebView", "Android-PostMessage"}) public void testPostMessageToFrameNotSendsPendingMessages() throws Throwable { loadPage(TITLE_PAGE); final TestMessagePort testPort = new TestMessagePort(getAwBrowserContext().getMessagePortService()); runTestOnUiThread(new Runnable() { @Override public void run() { MessagePort[] channel = mAwContents.createMessageChannel(); mAwContents.postMessageToFrame(null, "1", mWebServer.getBaseUrl(), new MessagePort[]{channel[1]}); mAwContents.postMessageToFrame(null, "2", mWebServer.getBaseUrl(), null); MessagePort[] channel2 = mAwContents.createMessageChannel(); // Test port is in a pending state so it should not be transferred. testPort.setMessagePort(channel2[0]); mAwContents.postMessageToFrame(null, "3", mWebServer.getBaseUrl(), new MessagePort[]{testPort}); } }); expectTitle("12"); } private static final String WORKER_MESSAGE = "from_worker"; // Listen for messages. Pass port 1 to worker and use port 2 to receive messages from // from worker. private static final String TEST_PAGE_FOR_PORT_TRANSFER = "<!DOCTYPE html><html><body>" + " <script type=\"text/javascript\">" + " var worker = new Worker(\"worker.js\");" + " onmessage = function (e) {" + " if (e.data == \"" + WEBVIEW_MESSAGE + "\") {" + " worker.postMessage(\"worker_port\", [e.ports[0]]);" + " var messageChannelPort = e.ports[1];" + " messageChannelPort.onmessage = receiveWorkerMessage;" + " }" + " };" + " function receiveWorkerMessage(e) {" + " if (e.data == \"" + WORKER_MESSAGE + "\") {" + " messageObject.setMessageParams(e.data, e.origin, e.ports);" + " }" + " };" + " </script>" + "</body></html>"; private static final String WORKER_SCRIPT = "onmessage = function(e) {" + " if (e.data == \"worker_port\") {" + " var toWindow = e.ports[0];" + " toWindow.postMessage(\"" + WORKER_MESSAGE + "\");" + " toWindow.start();" + " }" + "}"; // Test if message ports created at the native side can be transferred // to JS side, to establish a communication channel between a worker and a frame. @SmallTest @Feature({"AndroidWebView", "Android-PostMessage"}) public void testTransferPortsToWorker() throws Throwable { mWebServer.setResponse("/worker.js", WORKER_SCRIPT, CommonResources.getTextJavascriptHeaders(true)); loadPage(TEST_PAGE_FOR_PORT_TRANSFER); runTestOnUiThread(new Runnable() { @Override public void run() { MessagePort[] channel = mAwContents.createMessageChannel(); mAwContents.postMessageToFrame(null, WEBVIEW_MESSAGE, mWebServer.getBaseUrl(), new MessagePort[]{channel[0], channel[1]}); } }); mMessageObject.waitForMessage(); assertEquals(WORKER_MESSAGE, mMessageObject.getData()); } }
40.236006
102
0.572906
2bbe3768aa1031b2036db2d22924af9ddc1f1e25
4,153
package com.jinke.calligraphy.ftp; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPClientConfig; import org.apache.commons.net.ftp.FTPReply; import android.os.Environment; public class FtpUnit { private FTPClient ftpClient = null; private String SDPATH; public FtpUnit(){ SDPATH =Environment.getExternalStorageDirectory()+"/"; } /** * 连接Ftp服务器 */ public void connectServer(){ if(ftpClient == null){ int reply; try{ ftpClient = new FTPClient(); ftpClient.setDefaultPort(21); ftpClient.configure(getFtpConfig()); ftpClient.connect("172.16.18.175"); ftpClient.login("anonymous",""); ftpClient.setDefaultPort(21); reply = ftpClient.getReplyCode(); System.out.println(reply+"----"); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.err.println("FTP server refused connection."); } ftpClient.enterLocalPassiveMode(); ftpClient.setControlEncoding("gbk"); }catch(Exception e){ e.printStackTrace(); } } } /** * 上传文件 * @param localFilePath--本地文件路径 * @param newFileName--新的文件名 */ public void uploadFile(String localFilePath,String newFileName){ connectServer(); //上传文件 BufferedInputStream buffIn=null; try{ buffIn=new BufferedInputStream(new FileInputStream(SDPATH+"/"+localFilePath)); System.out.println(SDPATH+"/"+localFilePath); System.out.println("start="+System.currentTimeMillis()); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.storeFile("a1.mp3", buffIn); System.out.println("end="+System.currentTimeMillis()); }catch(Exception e){ e.printStackTrace(); }finally{ try{ if(buffIn!=null) buffIn.close(); }catch(Exception e){ e.printStackTrace(); } } } /** * 下载文件 * @param remoteFileName --服务器上的文件名 * @param localFileName--本地文件名 */ public void loadFile(String remoteFileName,String localFileName){ connectServer(); System.out.println("==============="+localFileName); //下载文件 BufferedOutputStream buffOut=null; try{ buffOut=new BufferedOutputStream(new FileOutputStream(SDPATH+localFileName)); long start = System.currentTimeMillis(); ftpClient.retrieveFile(remoteFileName, buffOut); long end = System.currentTimeMillis(); System.out.println(end-start); }catch(Exception e){ e.printStackTrace(); }finally{ try{ if(buffOut!=null) buffOut.close(); }catch(Exception e){ e.printStackTrace(); } } } /** * 设置FTP客服端的配置--一般可以不设置 * @return */ private static FTPClientConfig getFtpConfig(){ FTPClientConfig ftpConfig=new FTPClientConfig(FTPClientConfig.SYST_UNIX); ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING); return ftpConfig; } /** * 关闭连接 */ public void closeConnect(){ try{ if(ftpClient!=null){ ftpClient.logout(); ftpClient.disconnect(); } }catch(Exception e){ e.printStackTrace(); } } }
32.193798
93
0.525403
0a8bb60d0e405d5b896b54ea0128bd7f01ba262b
1,700
package jp.brbranch.lib; import org.cocos2dx.lib.Cocos2dxActivity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.view.Gravity; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.LinearLayout; import android.widget.RelativeLayout; abstract public class MyActivity extends Cocos2dxActivity { static Cocos2dxMyActivity my; private static native void onMessageBoxResult(final int num); protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); my = this; } public static void showAlertDialog(final String title , final String message , final String okButton , final String cancelButton){ my.runOnUiThread(new Runnable(){ @Override public void run(){ new AlertDialog.Builder(Cocos2dxActivity.getContext()) .setTitle(title) .setMessage(message) .setPositiveButton(okButton, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Cocos2dxMyActivity.onMessageBoxResult(1); } }) .setNegativeButton(cancelButton, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Cocos2dxMyActivity.onMessageBoxResult(2); } }) .show(); } }); } }
30.909091
134
0.66
d66e1a7a282149141482be11a8f5e8267af75323
258
package de.mcella.openapi.v3.objectconverter.example; import java.util.List; public class ListOfListOfStringsField { public final List<List<String>> fields; public ListOfListOfStringsField(List<List<String>> fields) { this.fields = fields; } }
19.846154
62
0.75969
36e466ef20c6d724607e7ac1e2424cf90e4a0a57
928
package microlit.json.rpc.api.body.request; import microlit.json.rpc.api.body.AbstractJsonRpcBody; import javax.json.bind.annotation.JsonbProperty; public abstract class AbstractJsonRpcRequest extends AbstractJsonRpcBody { @JsonbProperty("method") protected String methodName; @JsonbProperty("params") protected Object[] parameters; public AbstractJsonRpcRequest() { super(); } public AbstractJsonRpcRequest(String methodName, Object[] parameters) { super(); this.methodName = methodName; this.parameters = parameters; } public String getMethodName() { return methodName; } public Object[] getParameters() { return parameters; } public void setMethodName(String methodName) { this.methodName = methodName; } public void setParameters(Object[] parameters) { this.parameters = parameters; } }
23.794872
75
0.68319
bfc1c07fa2df81b2caa0c9d989e645ddf0ccb4a7
4,180
package net.instant.tools.console_client.cli; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.management.MBeanServerConnection; import javax.management.remote.JMXConnector; import net.instant.tools.console_client.jmx.Util; public class CLI implements Runnable { public static class Abort extends Exception { public Abort(String message) { super(message); } public Abort(String message, Throwable cause) { super(message, cause); } } public static final String PROMPT = "> "; private final SynchronousClient client; private final Terminal term; public CLI(SynchronousClient client, Terminal term) { this.client = client; this.term = term; } public SynchronousClient getClient() { return client; } public Terminal getTerminal() { return term; } public void run() { try { for (;;) { for (;;) { String block = client.readOutputBlock(); if (block == null) break; term.write(block); } if (client.isAtEOF()) break; String command = term.readLine(PROMPT); if (command == null) { term.write("\n"); break; } client.submitCommand(command); } } catch (InterruptedException exc) { /* NOP */ } finally { client.close(); } } public static Terminal createDefaultTerminal(boolean isBatch) { Terminal ret = ConsoleTerminal.getDefault(); if (ret == null) ret = StreamPairTerminal.getDefault(! isBatch); return ret; } public static void runDefault(Map<String, String> arguments, boolean isBatch, Terminal term) throws Abort, IOException { String address = arguments.get("address"); if (address == null) { if (isBatch) { throw new Abort("Missing connection address"); } else { address = term.readLine("Address : "); } } String username = arguments.get("login"); String password = null; Map<String, Object> env = new HashMap<String, Object>(); /* The code below tries to concisely implement these behaviors: * - In batch mode, there is exactly one connection attempt which * authenticates the user if-and-only-if a username is specified on * the command line. * - In interactive mode, if the first connection attempt fails, * another is made with credentials supplied. * - Failing a connection attempt with credentials provided is * fatal. */ boolean addCredentials = (isBatch && username != null); JMXConnector connector; for (;;) { if (addCredentials) { if (username == null) username = term.readLine("Username: "); if (password == null) password = term.readPassword("Password: "); Util.insertCredentials(env, username, password); } try { connector = Util.connectJMX(address, env); break; } catch (SecurityException exc) { if (isBatch || addCredentials) throw new Abort("Security error: " + exc.getMessage(), exc); } addCredentials = true; } MBeanServerConnection conn = connector.getMBeanServerConnection(); try { SynchronousClient client = SynchronousClient.getNewDefault(conn); new CLI(client, term).run(); } finally { connector.close(); } } public static void runDefault(Map<String, String> arguments, boolean isBatch) throws Abort, IOException { runDefault(arguments, isBatch, createDefaultTerminal(isBatch)); } }
33.174603
78
0.545215
d14b1aa561bf5187866469ef91f14f064a8bf565
1,017
/** * * @author Josué Rodríguez */ public class TeddyBear { public String size; public String color; public String smell; public boolean pants; public boolean shirt; public boolean hat; public String name; public TeddyBear(){ } public TeddyBear(String size, String color, String smell, boolean pants, boolean shirt, boolean hat, String name) { this.size = size; this.color = color; this.smell = smell; this.pants = pants; this.shirt = shirt; this.hat = hat; this.name = name; } @Override public String toString(){ return "This is " + this.name + ". It is a " + this.size + " sized " + this.color + " bear with " + this.smell + " smell.\nIt is " + this.pants + " that it wears pants, as it is " + this.shirt + " that it wears a shirt and it is " + this.hat + " that it has a hat.\n" + this.name + " really loves you!"; } }
26.763158
152
0.553589
27b845bb60341be0d40d7ea92fa7a30e745382ad
1,076
package com.dt.betting.db.domain; import java.util.ArrayList; import java.util.List; public class User extends DomainObject<User> { private List<Long> betIds = new ArrayList<>(); private boolean admin; private long scores; public List<Long> getBetIds() { return betIds; } public void setAdmin(boolean admin) { this.admin = admin; } public boolean isAdmin() { return admin; } public long getScores() { return scores; } public void setScores(long scores) { this.scores = scores; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
18.877193
68
0.618959
3df49f5ce594c78c581ce6d6e7e7b216bd8a1fa1
563
package datadog.trace.util.gc; import java.lang.ref.WeakReference; public abstract class GCUtils { public static void awaitGC() throws InterruptedException { Object obj = new Object(); final WeakReference<Object> ref = new WeakReference<>(obj); obj = null; awaitGC(ref); } public static void awaitGC(final WeakReference<?> ref) throws InterruptedException { while (ref.get() != null) { if (Thread.interrupted()) { throw new InterruptedException(); } System.gc(); System.runFinalization(); } } }
23.458333
86
0.660746
10c069ce7501918ce3045944f88e6df3e8514f99
13,952
package day2; import java.io.File; import java.io.PrintWriter; import java.util.Scanner; import javax.swing.JOptionPane; public class MyNotepad extends javax.swing.JFrame { public MyNotepad() { initComponents(); setLocationRelativeTo(null); jTextArea1.setLineWrap(true); } private boolean savedPreviously = false; private String filename; private void writeToFile(File file) throws Exception { PrintWriter pw = new PrintWriter(file); String text = jTextArea1.getText(); pw.print(text); pw.close(); JOptionPane.showMessageDialog(null, "Saved!"); } private void writeToFileWithSave(File file, String name) throws Exception { writeToFile(file); savedPreviously = true; filename = name; } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jLabel1 = new javax.swing.JLabel(); jLabelChars = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabelWords = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabelCharsNoSpaces = new javax.swing.JLabel(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItemNew = new javax.swing.JMenuItem(); jMenuItemOpen = new javax.swing.JMenuItem(); jMenuItemSave = new javax.swing.JMenuItem(); jMenuItemSaveAs = new javax.swing.JMenuItem(); jMenuItemExit = new javax.swing.JMenuItem(); jMenu2 = new javax.swing.JMenu(); jMenuItemFind = new javax.swing.JMenuItem(); jMenuItemReplace = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("My Notepad"); setResizable(false); jTextArea1.setColumns(20); jTextArea1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jTextArea1.setRows(5); jTextArea1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { jTextArea1KeyReleased(evt); } }); jScrollPane1.setViewportView(jTextArea1); jLabel1.setText("Chars:"); jLabelChars.setText("0"); jLabel3.setText("Words:"); jLabelWords.setText("0"); jLabel5.setText("Characters Without Spaces:"); jLabelCharsNoSpaces.setText("0"); jMenu1.setText("File"); jMenuItemNew.setText("New"); jMenuItemNew.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemNewActionPerformed(evt); } }); jMenu1.add(jMenuItemNew); jMenuItemOpen.setText("Open"); jMenuItemOpen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemOpenActionPerformed(evt); } }); jMenu1.add(jMenuItemOpen); jMenuItemSave.setText("Save"); jMenuItemSave.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemSaveActionPerformed(evt); } }); jMenu1.add(jMenuItemSave); jMenuItemSaveAs.setText("Save-As"); jMenuItemSaveAs.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemSaveAsActionPerformed(evt); } }); jMenu1.add(jMenuItemSaveAs); jMenuItemExit.setText("Exit"); jMenuItemExit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemExitActionPerformed(evt); } }); jMenu1.add(jMenuItemExit); jMenuBar1.add(jMenu1); jMenu2.setText("Edit"); jMenuItemFind.setText("Find"); jMenuItemFind.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemFindActionPerformed(evt); } }); jMenu2.add(jMenuItemFind); jMenuItemReplace.setText("Replace"); jMenuItemReplace.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemReplaceActionPerformed(evt); } }); jMenu2.add(jMenuItemReplace); jMenuBar1.add(jMenu2); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 620, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelChars) .addGap(18, 18, 18) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelWords) .addGap(18, 18, 18) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelCharsNoSpaces) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 429, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabelChars) .addComponent(jLabel3) .addComponent(jLabelWords) .addComponent(jLabel5) .addComponent(jLabelCharsNoSpaces)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jTextArea1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextArea1KeyReleased String text = jTextArea1.getText(); int chars = text.length(); int words = text.split("\\s+").length; text = text.replace(" ", ""); int charnospaces = text.length(); jLabelChars.setText("" + chars); jLabelWords.setText("" + words); jLabelCharsNoSpaces.setText("" + charnospaces); }//GEN-LAST:event_jTextArea1KeyReleased private void jMenuItemExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemExitActionPerformed int res = JOptionPane.showConfirmDialog(null, "Are you sure?"); if (res == JOptionPane.YES_OPTION) { System.exit(0); } }//GEN-LAST:event_jMenuItemExitActionPerformed private void jMenuItemNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemNewActionPerformed jTextArea1.setText(""); jLabelChars.setText("0"); jLabelCharsNoSpaces.setText("0"); jLabelWords.setText("0"); savedPreviously = false; }//GEN-LAST:event_jMenuItemNewActionPerformed private void jMenuItemOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemOpenActionPerformed String name = JOptionPane.showInputDialog("Filename:"); File file = new File(name); try { Scanner sc = new Scanner(file); while (sc.hasNext()) { String str = sc.next(); jTextArea1.append(str + " "); jTextArea1KeyReleased(null); // re-use (not copied) } savedPreviously = true; filename = name; } catch (Exception e) { JOptionPane.showMessageDialog(null, "File Not Found"); } }//GEN-LAST:event_jMenuItemOpenActionPerformed private void jMenuItemSaveAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemSaveAsActionPerformed try { String name = JOptionPane.showInputDialog("Filename:"); File file = new File(name); if (file.exists()) { int res = JOptionPane.showConfirmDialog(null, "Replace?"); if (res == JOptionPane.YES_OPTION) { writeToFileWithSave(file, name); } } else { file.createNewFile(); writeToFileWithSave(file, name); } } catch (Exception e) { } }//GEN-LAST:event_jMenuItemSaveAsActionPerformed private void jMenuItemSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemSaveActionPerformed if (savedPreviously) { try { File file = new File(filename); writeToFile(file); } catch (Exception e) { } } else { jMenuItemSaveAsActionPerformed(null); } }//GEN-LAST:event_jMenuItemSaveActionPerformed private void jMenuItemFindActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemFindActionPerformed String find = JOptionPane.showInputDialog("Text to Find:"); String text = jTextArea1.getText(); int index = text.indexOf(find); if (index != -1) { jTextArea1.select(index, index + find.length()); } }//GEN-LAST:event_jMenuItemFindActionPerformed private void jMenuItemReplaceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemReplaceActionPerformed String txt1 = JOptionPane.showInputDialog("Replace What?"); String txt2 = JOptionPane.showInputDialog("Replace With?"); String text = jTextArea1.getText(); text = text.replace(txt1, txt2); jTextArea1.setText(text); }//GEN-LAST:event_jMenuItemReplaceActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MyNotepad.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MyNotepad.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MyNotepad.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MyNotepad.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MyNotepad().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabelChars; private javax.swing.JLabel jLabelCharsNoSpaces; private javax.swing.JLabel jLabelWords; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItemExit; private javax.swing.JMenuItem jMenuItemFind; private javax.swing.JMenuItem jMenuItemNew; private javax.swing.JMenuItem jMenuItemOpen; private javax.swing.JMenuItem jMenuItemReplace; private javax.swing.JMenuItem jMenuItemSave; private javax.swing.JMenuItem jMenuItemSaveAs; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; // End of variables declaration//GEN-END:variables }
40.914956
151
0.630877
4d3ebcbfa9d28a5ec30d5526c9cffd54cb08e18c
943
package util.kafka; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; import java.util.Properties; import java.util.concurrent.ExecutionException; /** * Kafka event helper. */ public class KafkaEventHelper { private Properties configs; private Producer<String, String> producer = null; public KafkaEventHelper(Properties configs) { this.configs = configs; producer = new KafkaProducer<String, String>(configs); } public RecordMetadata sendEvent(String topic, String event) throws ExecutionException, InterruptedException { ProducerRecord<String, String> data = new ProducerRecord<String, String>(topic, event); return producer.send(data).get(); } public void close() { producer.close(); } }
28.575758
113
0.735949
ac479c0e4fc13887067be886ee7b92b10083bf1c
2,135
package egovframework.com.uss.umt.service.impl; import java.util.List; import egovframework.com.uss.umt.service.DeptManageVO; import egovframework.com.uss.umt.service.EgovDeptManageService; import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl; import javax.annotation.Resource; import org.springframework.stereotype.Service; @Service("egovDeptManageService") public class EgovDeptManageServiceImpl extends EgovAbstractServiceImpl implements EgovDeptManageService { @Resource(name="deptManageDAO") private DeptManageDAO deptManageDAO; /** * 부서를 관리하기 위해 등록된 부서목록을 조회한다. * @param deptManageVO - 부서 Vo * @return List - 부서 목록 * * @param deptManageVO */ public List<DeptManageVO> selectDeptManageList(DeptManageVO deptManageVO) throws Exception { return deptManageDAO.selectDeptManageList(deptManageVO); } /** * 부서목록 총 갯수를 조회한다. * @param deptManageVO - 부서 Vo * @return int - 부서 카운트 수 * * @param deptManageVO */ public int selectDeptManageListTotCnt(DeptManageVO deptManageVO) throws Exception { return deptManageDAO.selectDeptManageListTotCnt(deptManageVO); } /** * 등록된 부서의 상세정보를 조회한다. * @param deptManageVO - 부서 Vo * @return deptManageVO - 부서 Vo * * @param deptManageVO */ public DeptManageVO selectDeptManage(DeptManageVO deptManageVO) throws Exception { return deptManageDAO.selectDeptManage(deptManageVO); } /** * 부서정보를 신규로 등록한다. * @param deptManageVO - 부서 model * * @param deptManageVO */ public void insertDeptManage(DeptManageVO deptManageVO) throws Exception { deptManageDAO.insertDeptManage(deptManageVO); } /** * 기 등록된 부서정보를 수정한다. * @param deptManageVO - 부서 model * * @param deptManageVO */ public void updateDeptManage(DeptManageVO deptManageVO) throws Exception { deptManageDAO.updateDeptManage(deptManageVO); } /** * 기 등록된 부서정보를 삭제한다. * @param deptManageVO - 부서 model * * @param deptManageVO */ public void deleteDeptManage(DeptManageVO deptManageVO) throws Exception { deptManageDAO.deleteDeptManage(deptManageVO); } }
25.722892
106
0.72178
18e6e766d3309d2c4dd75ba535ea5d7540cb60c7
3,461
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.api.records; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceAudience.Public; import org.apache.hadoop.classification.InterfaceStability.Stable; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse; import org.apache.hadoop.yarn.util.Records; /** * <p>The NMToken is used for authenticating communication with * <code>NodeManager</code></p> * <p>It is issued by <code>ResourceMananger</code> when <code>ApplicationMaster</code> * negotiates resource with <code>ResourceManager</code> and * validated on <code>NodeManager</code> side.</p> * <p> Token: 令牌 </p> * <p> RM向AM分配资源的凭据, AM通过此凭据向NM获取资源. </p> * @see AllocateResponse#getNMTokens() */ @Public @Stable public abstract class NMToken { @Private @Unstable public static NMToken newInstance(NodeId nodeId, Token token) { NMToken nmToken = Records.newRecord(NMToken.class); nmToken.setNodeId(nodeId); nmToken.setToken(token); return nmToken; } /** * Get the {@link NodeId} of the <code>NodeManager</code> for which the NMToken * is used to authenticate. * @return the {@link NodeId} of the <code>NodeManager</code> for which the * NMToken is used to authenticate. */ @Public @Stable public abstract NodeId getNodeId(); @Public @Stable public abstract void setNodeId(NodeId nodeId); /** * Get the {@link Token} used for authenticating with <code>NodeManager</code> * @return the {@link Token} used for authenticating with <code>NodeManager</code> */ @Public @Stable public abstract Token getToken(); @Public @Stable public abstract void setToken(Token token); @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getNodeId() == null) ? 0 : getNodeId().hashCode()); result = prime * result + ((getToken() == null) ? 0 : getToken().hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NMToken other = (NMToken) obj; if (getNodeId() == null) { if (other.getNodeId() != null) return false; } else if (!getNodeId().equals(other.getNodeId())) return false; if (getToken() == null) { if (other.getToken() != null) return false; } else if (!getToken().equals(other.getToken())) return false; return true; } }
31.18018
87
0.692863
80d394f74bb31a36d0bbd017995868b0ae04d9b4
294
package com.ssafy.blog.payload; import lombok.Getter; import lombok.Setter; @Getter @Setter public class AuthResponse { private String accessToken; private String tokenType = "Bearer"; public AuthResponse(String accessToken) { this.accessToken = accessToken; } }
18.375
45
0.714286
bc152f6a0bc206e97df05501d1dd4592ec75da18
329
package com.haidong.SeirMeng.service.edu.mapper; import com.haidong.SeirMeng.service.edu.entity.CourseCollect; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * <p> * 课程收藏 Mapper 接口 * </p> * * @author atguigu * @since 2021-11-14 */ public interface CourseCollectMapper extends BaseMapper<CourseCollect> { }
19.352941
72
0.74772
b4a16a91b20e7db425095326690cec3e3946fa88
1,935
package tech.elc1798.projectpepe.activities.extras.drawing.special; import android.content.Context; import org.opencv.core.Mat; import tech.elc1798.projectpepe.imgprocessing.OpenCVLibLoader; /** * Abstract class for a DrawingSession operation that performs an automatic built-in operation that is too complicated * or impossible to do using standard free-draw and text boxes */ public abstract class SpecialTool { /** * Constructs a SpecialTool object. This constructor will load OpenCV for the Context provided, and will also call * the implementation of the {@code onOpenCVLoad} method if OpenCV is successfully loaded. * * @param context The context to load OpenCV for * @param tag The Android Log Tag to use for debugging purposes */ public SpecialTool(final Context context, String tag) { OpenCVLibLoader.loadOpenCV(context, new OpenCVLibLoader.Callback(context, tag) { @Override public void onOpenCVLoadSuccess() { onOpenCVLoad(context); } }); } /** * Gets the name of the tool * * @return a String */ public abstract String getName(); /** * Performs the action done by the tool. This operation is done IN PLACE on the inputMat. This is to adhere to the * convention laid by OpenCV, since Java OpenCV is just a C / C++ wrapper using JNI * * @param inputImage The image to perform the action on */ public abstract void doAction(Mat inputImage); /** * This method is called as part of the OpenCV load process as a callback when OpenCV is successfully loaded. An * implementation of this method should be used to initialize any OpenCV objects, such as {@code Mat}s, XML * files for classifiers, etc. * * @param context The app context to load OpenCV for */ public abstract void onOpenCVLoad(Context context); }
34.553571
118
0.687855
87d783c97c28b4893e9ad06c0a16bd6873ec9460
352
package core.comparision.comparator; import core.comparision.Player; import java.util.Comparator; /** * PlayerAgeComparator.java * * @author: zhaoxiaoping * @date: 2019/10/28 **/ public class PlayerAgeComparator implements Comparator<Player> { @Override public int compare(Player o1, Player o2) { return o1.getAge() - o1.getAge(); } }
19.555556
64
0.721591
1935c6a4a9fff60c37d4619e3c61f868172ace49
1,676
/** * Copyright 2012 Rainer Bieniek ([email protected]) * * 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.bgp4j.weld; import java.lang.annotation.Annotation; import org.jboss.weld.environment.se.StartMain; import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; /** * @author Rainer Bieniek ([email protected]) * */ public class SeApplicationBootstrap { public static void bootstrapApplication(String[] args, Annotation selection) { StartMain.PARAMETERS = args; Weld weld = new Weld(); WeldContainer weldContainer = weld.initialize(); Runtime.getRuntime().addShutdownHook(new ShutdownHook(weld)); weldContainer.event().select(ApplicationBootstrapEvent.class).fire(new ApplicationBootstrapEvent(weldContainer)); weldContainer.event().select(SeApplicationStartEvent.class, selection).fire(new SeApplicationStartEvent()); } static class ShutdownHook extends Thread { private final Weld weld; ShutdownHook(Weld weld) { this.weld = weld; } public void run() { weld.shutdown(); } } }
31.037037
115
0.715394
949846b8e4e10850c5d5894929746bf7f7f229bd
9,193
package com.sequenceiq.cloudbreak.cloud.aws; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import com.amazonaws.services.cloudformation.model.ListStackResourcesRequest; import com.amazonaws.services.cloudformation.model.ListStackResourcesResult; import com.amazonaws.services.cloudformation.model.StackResourceSummary; import com.amazonaws.services.elasticloadbalancingv2.model.LoadBalancer; import com.sequenceiq.cloudbreak.cloud.aws.client.AmazonCloudFormationClient; import com.sequenceiq.cloudbreak.cloud.aws.common.client.AmazonEc2Client; import com.sequenceiq.cloudbreak.cloud.aws.common.loadbalancer.AwsListener; import com.sequenceiq.cloudbreak.cloud.aws.common.loadbalancer.AwsLoadBalancer; import com.sequenceiq.cloudbreak.cloud.aws.common.loadbalancer.AwsLoadBalancerScheme; import com.sequenceiq.cloudbreak.cloud.aws.common.loadbalancer.AwsTargetGroup; import com.sequenceiq.cloudbreak.cloud.aws.common.view.AwsLoadBalancerMetadataView; import com.sequenceiq.cloudbreak.cloud.context.AuthenticatedContext; import com.sequenceiq.cloudbreak.cloud.context.CloudContext; import com.sequenceiq.cloudbreak.cloud.model.AvailabilityZone; import com.sequenceiq.cloudbreak.cloud.model.CloudCredential; import com.sequenceiq.cloudbreak.cloud.model.Location; import com.sequenceiq.cloudbreak.cloud.model.Region; @ExtendWith(MockitoExtension.class) public class AwsLoadBalancerMetadataCollectorTest { private static final Long WORKSPACE_ID = 1L; private static final String TARGET_GROUP_ARN = "arn:targetgroup"; private static final String LOAD_BALANCER_ARN = "arn:loadbalancer"; private static final String LISTENER_ARN = "arn:listener"; @Mock private AmazonEc2Client amazonEC2Client; @Mock private AwsCloudFormationClient awsClient; @Mock private CloudFormationStackUtil cloudFormationStackUtil; @Mock private AwsStackRequestHelper awsStackRequestHelper; @Mock private AmazonCloudFormationClient cfRetryClient; @InjectMocks private AwsLoadBalancerMetadataCollector underTest; @Test public void testCollectInternalLoadBalancer() { int numPorts = 1; AuthenticatedContext ac = authenticatedContext(); LoadBalancer loadBalancer = createLoadBalancer(); List<StackResourceSummary> summaries = createSummaries(numPorts, true); ListStackResourcesResult result = new ListStackResourcesResult(); result.setStackResourceSummaries(summaries); Map<String, Object> expectedParameters = Map.of( AwsLoadBalancerMetadataView.LOADBALANCER_ARN, LOAD_BALANCER_ARN, AwsLoadBalancerMetadataView.LISTENER_ARN_PREFIX + 0, LISTENER_ARN + "0Internal", AwsLoadBalancerMetadataView.TARGET_GROUP_ARN_PREFIX + 0, TARGET_GROUP_ARN + "0Internal" ); when(awsClient.createCloudFormationClient(any(), any())).thenReturn(cfRetryClient); when(cloudFormationStackUtil.getCfStackName(ac)).thenReturn("stackName"); when(awsStackRequestHelper.createListStackResourcesRequest(eq("stackName"))).thenReturn(new ListStackResourcesRequest()); when(cfRetryClient.listStackResources(any())).thenReturn(result); Map<String, Object> parameters = underTest.getParameters(ac, loadBalancer, AwsLoadBalancerScheme.INTERNAL); assertEquals(expectedParameters, parameters); } @Test public void testCollectLoadBalancerMultiplePorts() { int numPorts = 3; AuthenticatedContext ac = authenticatedContext(); LoadBalancer loadBalancer = createLoadBalancer(); List<StackResourceSummary> summaries = createSummaries(numPorts, true); ListStackResourcesResult result = new ListStackResourcesResult(); result.setStackResourceSummaries(summaries); Map<String, Object> expectedParameters = Map.of( AwsLoadBalancerMetadataView.LOADBALANCER_ARN, LOAD_BALANCER_ARN, AwsLoadBalancerMetadataView.LISTENER_ARN_PREFIX + 0, LISTENER_ARN + "0Internal", AwsLoadBalancerMetadataView.TARGET_GROUP_ARN_PREFIX + 0, TARGET_GROUP_ARN + "0Internal", AwsLoadBalancerMetadataView.LISTENER_ARN_PREFIX + 1, LISTENER_ARN + "1Internal", AwsLoadBalancerMetadataView.TARGET_GROUP_ARN_PREFIX + 1, TARGET_GROUP_ARN + "1Internal", AwsLoadBalancerMetadataView.LISTENER_ARN_PREFIX + 2, LISTENER_ARN + "2Internal", AwsLoadBalancerMetadataView.TARGET_GROUP_ARN_PREFIX + 2, TARGET_GROUP_ARN + "2Internal" ); when(awsClient.createCloudFormationClient(any(), any())).thenReturn(cfRetryClient); when(cloudFormationStackUtil.getCfStackName(ac)).thenReturn("stackName"); when(awsStackRequestHelper.createListStackResourcesRequest(eq("stackName"))).thenReturn(new ListStackResourcesRequest()); when(cfRetryClient.listStackResources(any())).thenReturn(result); Map<String, Object> parameters = underTest.getParameters(ac, loadBalancer, AwsLoadBalancerScheme.INTERNAL); assertEquals(expectedParameters, parameters); } @Test public void testCollectLoadBalancerMissingTargetGroup() { int numPorts = 1; AuthenticatedContext ac = authenticatedContext(); LoadBalancer loadBalancer = createLoadBalancer(); List<StackResourceSummary> summaries = createSummaries(numPorts, false); ListStackResourcesResult result = new ListStackResourcesResult(); result.setStackResourceSummaries(summaries); Map<String, Object> expectedParameters = new HashMap<>(); expectedParameters.put(AwsLoadBalancerMetadataView.LOADBALANCER_ARN, LOAD_BALANCER_ARN); expectedParameters.put(AwsLoadBalancerMetadataView.LISTENER_ARN_PREFIX + 0, LISTENER_ARN + "0Internal"); expectedParameters.put(AwsLoadBalancerMetadataView.TARGET_GROUP_ARN_PREFIX + 0, null); when(awsClient.createCloudFormationClient(any(), any())).thenReturn(cfRetryClient); when(cloudFormationStackUtil.getCfStackName(ac)).thenReturn("stackName"); when(awsStackRequestHelper.createListStackResourcesRequest(eq("stackName"))).thenReturn(new ListStackResourcesRequest()); when(cfRetryClient.listStackResources(any())).thenReturn(result); Map<String, Object> parameters = underTest.getParameters(ac, loadBalancer, AwsLoadBalancerScheme.INTERNAL); assertEquals(expectedParameters, parameters); } private AuthenticatedContext authenticatedContext() { Location location = Location.location(Region.region("region"), AvailabilityZone.availabilityZone("az")); CloudContext context = CloudContext.Builder.builder() .withId(5L) .withName("name") .withCrn("crn") .withPlatform("platform") .withVariant("variant") .withLocation(location) .withWorkspaceId(WORKSPACE_ID) .build(); CloudCredential credential = new CloudCredential("crn", null, null, false); AuthenticatedContext authenticatedContext = new AuthenticatedContext(context, credential); authenticatedContext.putParameter(AmazonEc2Client.class, amazonEC2Client); return authenticatedContext; } private LoadBalancer createLoadBalancer() { LoadBalancer loadBalancer = new LoadBalancer(); loadBalancer.setLoadBalancerArn(LOAD_BALANCER_ARN); return loadBalancer; } private List<StackResourceSummary> createSummaries(int numPorts, boolean includeTargetGroup) { List<StackResourceSummary> summaries = new ArrayList<>(); for (AwsLoadBalancerScheme scheme : AwsLoadBalancerScheme.class.getEnumConstants()) { StackResourceSummary lbSummary = new StackResourceSummary(); lbSummary.setLogicalResourceId(AwsLoadBalancer.getLoadBalancerName(scheme)); lbSummary.setPhysicalResourceId(LOAD_BALANCER_ARN + scheme.resourceName()); summaries.add(lbSummary); for (int i = 0; i < numPorts; i++) { if (includeTargetGroup) { StackResourceSummary tgSummary = new StackResourceSummary(); tgSummary.setLogicalResourceId(AwsTargetGroup.getTargetGroupName(i, scheme)); tgSummary.setPhysicalResourceId(TARGET_GROUP_ARN + i + scheme.resourceName()); summaries.add(tgSummary); } StackResourceSummary lSummary = new StackResourceSummary(); lSummary.setLogicalResourceId(AwsListener.getListenerName(i, scheme)); lSummary.setPhysicalResourceId(LISTENER_ARN + i + scheme.resourceName()); summaries.add(lSummary); } } return summaries; } }
48.384211
129
0.744588
592f0ae993b087071dbfdceece7301be45e1e74b
127,136
package main; import java.io.BufferedReader; import java.io.StringReader; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; public class GuKKiCalComponent { Logger logger = Logger.getLogger("GuKKiCal"); Level logLevel = Level.FINEST; /* * Standardvariablen für alle Komponenten */ GuKKiCalcKennung kennung = GuKKiCalcKennung.UNDEFINIERT; GuKKiCalcStatus status = GuKKiCalcStatus.UNDEFINIERT; String schluessel = ""; boolean bearbeiteSubKomponente = false; boolean vEventBearbeiten = false; GuKKiCalvEvent vEventNeu; boolean vTodoBearbeiten = false; GuKKiCalvTodo vTodoNeu; boolean vJournalBearbeiten = false; GuKKiCalvJournal vJournalNeu; boolean vAlarmBearbeiten = false; GuKKiCalvAlarm vAlarmNeu; boolean vTimezoneBearbeiten = false; GuKKiCalvTimezone vTimezoneNeu; boolean cDaylightBearbeiten = false; GuKKiCalcDaylight cDaylightNeu; boolean cStandardBearbeiten = false; GuKKiCalcStandard cStandardNeu; boolean vFreeBusyBearbeiten = false; GuKKiCalvFreeBusy vFreeBusyNeu; /* * Standard-Variablen (Konstanten) */ String nz = "\n"; /** * Konstruktor */ public GuKKiCalComponent() { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen\n"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet\n"); } // TODO Automatisch generierter Konstruktorstub } /** * * Generelle Bearbeitungsfunktionen * */ protected void einlesenAusDatenstrom(String vComponentDaten) throws Exception { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen\n"); } String zeile = ""; String folgezeile = ""; boolean datenVorhanden = true; try { // System.out.println(vComponentDaten); BufferedReader vComponentDatenstrom = new BufferedReader(new StringReader(vComponentDaten)); zeile = vComponentDatenstrom.readLine(); // System.out.println("-->" + zeile + "<--"); if (zeile == null) { datenVorhanden = false; } while (datenVorhanden) { folgezeile = vComponentDatenstrom.readLine(); // System.out.println("-->" + folgezeile + "<--"); if (folgezeile == null) { verarbeitenZeile(zeile); datenVorhanden = false; } else { if (folgezeile.length() > 0) { if (folgezeile.substring(0, 1).equals(" ")) { zeile = zeile.substring(0, zeile.length()) + folgezeile.substring(1); } else { verarbeitenZeile(zeile); zeile = folgezeile; } } } } /* end while-Schleife */ } finally { } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet\n"); } } protected void verarbeitenZeile(String zeile) throws Exception { System.out.println("GuKKiCalComponent verarbeitenZeile-->" + zeile + "<--"); } protected String ausgebenInDatenstrom(String vComponentDaten) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen\n"); } String ausgabeString = ""; int laenge = 75; int anf = 0; if (vComponentDaten.length() < laenge) { ausgabeString = vComponentDaten + "\n"; } else { ausgabeString = vComponentDaten.substring(0, laenge - 1) + "\n "; anf = laenge - 1; for (; anf < vComponentDaten.length() - laenge; anf += laenge - 1) { ausgabeString += vComponentDaten.substring(anf, anf + laenge - 1) + "\n "; } ausgabeString += vComponentDaten.substring(anf) + "\n"; } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet\n"); } return ausgabeString; } /** * Bearbeitungsroutinen für die Eigenschaft Action * * @formatter:off * * RFC 5545 (september 2009) item 3.8.6.1.; p. 132 * * Property Name: ACTION * * Purpose: This property defines the action to be invoked when an * alarm is triggered. * * Value Type: TEXT * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: This property MUST be specified once in a "VALARM" * calendar component. * * Description: Each "VALARM" calendar component has a particular type * of action with which it is associated. This property specifies * the type of action. Applications MUST ignore alarms with x-name * and iana-token values they don’t recognize. * * Format Definition: This property is defined by the following notation: * * action = "ACTION" actionparam ":" actionvalue CRLF * * actionparam = *(";" other-param) * * actionvalue = "AUDIO" / "DISPLAY" / "EMAIL" * / iana-token / x-name * * @formatter:on * */ boolean untersuchenACTION(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Attach * * @formatter:off * * RFC 5545 (september 2009) item 3.8.1.1; p. 80 * * Property Name: ATTACH * * Purpose: This property provides the capability to associate a * document object with a calendar component. * * Value Type: The default value type for this property is URI. The * value type can also be set to BINARY to indicate inline binary * encoded content information. * * Property Parameters: IANA, non-standard, inline encoding, and value * data type property parameters can be specified on this property. * The format type parameter can be specified on this property and is * RECOMMENDED for inline binary encoded content information. * * Conformance: This property can be specified multiple times in a * "VEVENT", "VTODO", "VJOURNAL", or "VALARM" calendar component with * the exception of AUDIO alarm that only allows this property to * occur once. * * Description: This property is used in "VEVENT", "VTODO", and * "VJOURNAL" calendar components to associate a resource (e.g., * document) with the calendar component. This property is used in * "VALARM" calendar components to specify an audio sound resource or * an email message attachment. This property can be specified as a * URI pointing to a resource or as inline binary encoded content. * When this property is specified as inline binary encoded content, * calendar applications MAY attempt to guess the media type of the * resource via inspection of its content if and only if the media * type of the resource is not given by the "FMTTYPE" parameter. If * the media type remains unknown, calendar applications SHOULD treat * it as type "application/octet-stream". * * Format Definition: This property is defined by the following notation: * * attach = "ATTACH" attachparam ( ":" uri ) / * ( * ";" "ENCODING" "=" "BASE64" * ";" "VALUE" "=" "BINARY" * ":" binary * ) CRLF * * attachparam = *( * * The following is OPTIONAL for a URI value, RECOMMENDED for a BINARY value, * and MUST NOT occur more than once. * * (";" fmttypeparam) / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * * ) * * @formatter:on * */ boolean untersuchenATTACH(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Attendee * * @formatter:off * * RFC 5545 (september 2009) item 3.8.4.1.; p. 107 * * Property Name: ATTENDEE * * Purpose: This property defines an "Attendee" within a calendar component. * * Value Type: CAL-ADDRESS * * Property Parameters: IANA, non-standard, language, calendar user * type, group or list membership, participation role, participation * status, RSVP expectation, delegatee, delegator, sent by, common * name, or directory entry reference property parameters can be * specified on this property. * * Conformance: This property MUST be specified in an iCalendar object * that specifies a group-scheduled calendar entity. This property * MUST NOT be specified in an iCalendar object when publishing the * calendar information (e.g., NOT in an iCalendar object that * specifies the publication of a calendar user’s busy time, event, * to-do, or journal). This property is not specified in an * iCalendar object that specifies only a time zone definition or * that defines calendar components that are not group-scheduled * components, but are components only on a single user’s calendar. * * Description: This property MUST only be specified within calendar * components to specify participants, non-participants, and the * chair of a group-scheduled calendar entity. The property is * specified within an "EMAIL" category of the "VALARM" calendar * component to specify an email address that is to receive the email * type of iCalendar alarm. * The property parameter "CN" is for the common or displayable name * associated with the calendar address; "ROLE", for the intended * role that the attendee will have in the calendar component; * "PARTSTAT", for the status of the attendee’s participation; * "RSVP", for indicating whether the favor of a reply is requested; * "CUTYPE", to indicate the type of calendar user; * "MEMBER", to indicate the groups that the attendee belongs to; * "DELEGATED-TO",to indicate the calendar users that the original request was * delegated to; and * "DELEGATED-FROM", to indicate whom the request was delegated from; * "SENT-BY", to indicate whom is acting on behalf of the "ATTENDEE"; and * "DIR", to indicate the URI that points to the directory information * corresponding to the attendee. * These property parameters can be specified on an "ATTENDEE" * property in either a "VEVENT", "VTODO", or "VJOURNAL" calendar * component. They MUST NOT be specified in an "ATTENDEE" property * in a "VFREEBUSY" or "VALARM" calendar component. * If the "LANGUAGE" property parameter is specified, the identified * language applies to the "CN" parameter. * * A recipient delegated a request MUST inherit the "RSVP" and "ROLE" * values from the attendee that delegated the request to them. * * Multiple attendees can be specified by including multiple * "ATTENDEE" properties within the calendar component. * * Format Definition: This property is defined by the following notation: * * attendee = "ATTENDEE" attparam ":" cal-address CRLF * * attparam = *( * * The following are OPTIONAL, but MUST NOT occur more than once. * (";" cutypeparam) / * (";" memberparam) / * (";" roleparam) / * (";" partstatparam) / * (";" rsvpparam) / * (";" deltoparam) / * (";" delfromparam) / * (";" sentbyparam) / * (";" cnparam) / * (";" dirparam) / * (";" languageparam) / * * The following is OPTIONAL, and MAY occur more than once. * * *(";" other-param) * * ) * * @formatter:on * */ boolean untersuchenATTENDEE(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Calendar Scale * * RFC 5545 (september 2009) item 3.7.1.; p. 76 * * @formatter:off * * Property Name: CALSCALE * * Purpose: This property defines the calendar scale used for the * calendar information specified in the iCalendar object. * * Value Type: TEXT * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: This property can be specified once in an iCalendar * object. The default value is "GREGORIAN". * * Description: This memo is based on the Gregorian calendar scale. * The Gregorian calendar scale is assumed if this property is not * specified in the iCalendar object. It is expected that other * calendar scales will be defined in other specifications or by * future versions of this memo. * * Format Definition: This property is defined by the following notation: * * calscale = "CALSCALE" calparam ":" calvalue CRLF * * calparam = *(";" other-param) * * calvalue = "GREGORIAN" * * @formatter:on * */ boolean untersuchenCALSCALE(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Categories * * @formatter:off * * RFC 5545 (september 2009) item 3.8.1.2; p. 81 * * Property Name: CATEGORIES * * Purpose: This property defines the categories for a calendar component. * * Value Type: TEXT * * Property Parameters: IANA, non-standard, and language property * parameters can be specified on this property. * * Conformance: The property can be specified within "VEVENT", "VTODO", * or "VJOURNAL" calendar components. * * Description: This property is used to specify categories or subtypes * of the calendar component. The categories are useful in searching * for a calendar component of a particular type and category. * Within the "VEVENT", "VTODO", or "VJOURNAL" calendar components, * more than one category can be specified as a COMMA-separated list * of categories. * * Format Definition: This property is defined by the following notation: * * categories = "CATEGORIES" catparam ":" text *("," text) CRLF * * catparam = *( * * The following is OPTIONAL, but MUST NOT occur more than once. * * (";" languageparam ) / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * * ) * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * * RFC 7986 (October 2016) item 5.6.; p. 8 * * CATEGORIES * * This specification modifies the definition of the "CATEGORIES" * property to allow it to be defined in an iCalendar object. The * following additions are made to the definition of this property, * originally specified in Section 3.8.1.2 of [RFC5545]. * * Purpose: This property defines the categories for an entire calendar. * * Conformance: This property can be specified multiple times in an iCalendar object. * * Description: When multiple properties are present, the set of * categories that apply to the iCalendar object are the union of all * the categories listed in each property value. * * @formatter:on * */ boolean untersuchenCATEGORIES(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Classification * * @formatter:off * * RFC 5545 (september 2009) item 3.8.1.3; p. 82 * * Property Name: CLASS * * Purpose: This property defines the access classification for a calendar component. * * Value Type: TEXT * * Property Parameters: IANA and non-standard property parameters can be * specified on this property. * * Conformance: The property can be specified once in a "VEVENT", "VTODO", * or "VJOURNAL" calendar components. * * Description: An access classification is only one component of the * general security system within a calendar application. It * provides a method of capturing the scope of the access the * calendar owner intends for information within an individual * calendar entry. The access classification of an individual * iCalendar component is useful when measured along with the other * security components of a calendar system (e.g., calendar user * authentication, authorization, access rights, access role, etc.). * Hence, the semantics of the individual access classifications * cannot be completely defined by this memo alone. Additionally, * due to the "blind" nature of most exchange processes using this * memo, these access classifications cannot serve as an enforcement * statement for a system receiving an iCalendar object. Rather, * they provide a method for capturing the intention of the calendar * owner for the access to the calendar component. If not specified * in a component that allows this property, the default value is * PUBLIC. Applications MUST treat x-name and iana-token values they * don’t recognize the same way as they would the PRIVATE value. * * Format Definition: This property is defined by the following notation: * * class = "CLASS" classparam ":" classvalue CRLF * * classparam = *(";" other-param) * * classvalue = "PUBLIC" / "PRIVATE" / "CONFIDENTIAL" / iana-token * / x-name * * Default is PUBLIC * * @formatter:on * */ boolean untersuchenCLASS(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft COLOR * * RFC 7986 (October 2016) item 5.9.; p. 10 * * @formatter:off * * Property Name: COLOR * * Purpose: This property specifies a color used for displaying the * calendar, event, todo, or journal data. * * Value Type: TEXT * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: This property can be specified once in an iCalendar * object or in "VEVENT", "VTODO", or "VJOURNAL" calendar components. * * Description: This property specifies a color that clients MAY use * when presenting the relevant data to a user. Typically, this * would appear as the "background" color of events or tasks. The * value is a case-insensitive color name taken from the CSS3 set of * names, defined in Section 4.3 of [W3C.REC-css3-color-20110607]. * * Format Definition: This property is defined by the following notation: * * color = "COLOR" colorparam ":" text CRLF * * colorparam = *(";" other-param) * * text = Value is CSS3 color name * * @formatter:on * */ boolean untersuchenCOLOR(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Comment * * @formatter:off * * RFC 5545 (september 2009) item 3.8.1.4.; p. 83 * * Property Name: COMMENT * * Purpose: This property specifies non-processing information intended * to provide a comment to the calendar user. * * Value Type: TEXT * * Property Parameters: IANA, non-standard, alternate text * representation, and language property parameters can be specified * on this property. * * Conformance: This property can be specified multiple times in * "VEVENT", "VTODO", "VJOURNAL", and "VFREEBUSY" calendar components * as well as in the "STANDARD" and "DAYLIGHT" sub-components. * * Description: This property is used to specify a comment to the calendar user. * * Format Definition: This property is defined by the following notation: * * comment = "COMMENT" commparam ":" text CRLF * * commparam = *( * * The following are OPTIONAL, but MUST NOT occur more than once. * * (";" altrepparam) / (";" languageparam) / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * ) * * @formatter:on * */ boolean untersuchenCOMMENT(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Datetime-Completed * * @formatter:off * * RFC 5545 (september 2009) item 3.8.2.1; p. 94 * * Property Name: COMPLETED * * Purpose: This property defines the date and time that a to-do was * actually completed. * * Value Type: DATE-TIME * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: The property can be specified in a "VTODO" calendar * component. The value MUST be specified as a date with UTC time. * * Description: This property defines the date and time that a to-do * was actually completed. * * Format Definition: This property is defined by the following notation: * * completed = "COMPLETED" compparam ":" date-time CRLF * * compparam = *(";" other-param) * * @formatter:on * */ boolean untersuchenCOMPLETED(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft CONFERENCE * * @formatter:off * * RFC 7986 (October 2016) item 5.11.; p. 13 * * Property Name: CONFERENCE * * Purpose: This property specifies information for accessing a * conferencing system. * * Value Type: URI -- no default. * * Property Parameters: IANA, non-standard, feature, and label property * parameters can be specified on this property. * * Conformance: This property can be specified multiple times in a * "VEVENT" or "VTODO" calendar component. * * Description: This property specifies information for accessing a * conferencing system for attendees of a meeting or task. This * might be for a telephone-based conference number dial-in with * access codes included (such as a tel: URI [RFC3966] or a sip: or * sips: URI [RFC3261]), for a web-based video chat (such as an http: * or https: URI [RFC7230]), or for an instant messaging group chat * room (such as an xmpp: URI [RFC5122]). If a specific URI for a * conferencing system is not available, a data: URI [RFC2397] * containing a text description can be used. * * A conference system can be a bidirectional communication channel * or a uni-directional "broadcast feed". * * The "FEATURE" property parameter is used to describe the key * capabilities of the conference system to allow a client to choose * the ones that give the required level of interaction from a set of * multiple properties. * * The "LABEL" property parameter is used to convey additional * details on the use of the URI. For example, the URIs or access * codes for the moderator and attendee of a teleconference system * could be different, and the "LABEL" property parameter could be * used to "tag" each "CONFERENCE" property to indicate which is * which. * * The "LANGUAGE" property parameter can be used to specify the * language used for text values used with this property (as per * Section 3.2.10 of [RFC5545]). * * Format Definition: This property is defined by the following notation: * * conference = "CONFERENCE" confparam ":" uri CRLF * * confparam = *( * * The following is REQUIRED, but MUST NOT occur more than once. * * (";" "VALUE" "=" "URI") / * * The following are OPTIONAL, and MUST NOT occur more than once. * * (";" featureparam) / (";" labelparam) / * (";" languageparam ) / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * ) * * @formatter:on * */ boolean untersuchenCONFERENCE(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Contact * * @formatter:off * * RFC 5545 (september 2009) item 3.8.4.2.; p. 109 * * Property Name: CONTACT * * Purpose: This property is used to represent contact information or * alternately a reference to contact information associated with the * calendar component. * * Value Type: TEXT * * Property Parameters: IANA, non-standard, alternate text * representation, and language property parameters can be specified * on this property. * * Conformance: This property can be specified in a "VEVENT", "VTODO", * "VJOURNAL", or "VFREEBUSY" calendar component. * * Description: The property value consists of textual contact * information. An alternative representation for the property value * can also be specified that refers to a URI pointing to an * alternate form, such as a vCard [RFC2426], for the contact * information. * * Format Definition: This property is defined by the following notation: * * contact = "CONTACT" contparam ":" text CRLF * * contparam = *( * * The following are OPTIONAL, but MUST NOT occur more than once. * * (";" altrepparam) / (";" languageparam) / * * The following is OPTIONAL, and MAY occur more than once. * (";" other-param) * ) * * @formatter:on * */ boolean untersuchenCONTACT(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft CREATED * * @formatter:off * * RFC 5545 (september 2009) item 3.8.7.3; p. 138 * * Property Name: CREATED * * Purpose: This property specifies the date and time that the calendar * information was created by the calendar user agent in the calendar * store. * * Note: This is analogous to the creation date and time for a * file in the file system. * * Value Type: DATE-TIME * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: The property can be specified once in "VEVENT", * "VTODO", or "VJOURNAL" calendar components. The value MUST be * specified as a date with UTC time. * * Description: This property specifies the date and time that the * calendar information was created by the calendar user agent in the * calendar store. * * Format Definition: This property is defined by the following notation: * * created = "CREATED" creaparam ":" date-time CRLF * * creaparam = *(";" other-param) * * @formatter:on * */ boolean untersuchenCREATED(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft DESCRIPTION * * @formatter:off * * RFC 5545 (september 2009) item 3.8.1.5; p. 84 * * Property Name: DESCRIPTION * * Purpose: This property provides a more complete description of the * calendar component than that provided by the "SUMMARY" property. * * Value Type: TEXT * * Property Parameters: IANA, non-standard, alternate text * representation, and language property parameters can be specified * on this property. * * Conformance: The property can be specified in the "VEVENT", "VTODO", * "VJOURNAL", or "VALARM" calendar components. The property can be * specified multiple times only within a "VJOURNAL" calendar * component. * * Description: This property is used in the "VEVENT" and "VTODO" to * capture lengthy textual descriptions associated with the activity. * This property is used in the "VJOURNAL" calendar component to * capture one or more textual journal entries. * This property is used in the "VALARM" calendar component to * capture the display text for a DISPLAY category of alarm, and to * capture the body text for an EMAIL category of alarm. * * Format Definition: This property is defined by the following notation: * * description = "DESCRIPTION" descparam ":" text CRLF * * descparam = *( * * The following are OPTIONAL, but MUST NOT occur more than once. * * (";" altrepparam) / (";" languageparam) / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * * ) * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * * RFC 7986 (October 2016) item 5.2.; p. 6 * * DESCRIPTION * * This specification modifies the definition of the "DESCRIPTION" * property to allow it to be defined in an iCalendar object. The * following additions are made to the definition of this property, * originally specified in Section 3.8.1.5 of [RFC5545]. * * Purpose: This property specifies the description of the calendar. * * Conformance: This property can be specified multiple times in an * iCalendar object. However, each property MUST represent the * description of the calendar in a different language. * * Description: This property is used to specify a lengthy textual * description of the iCalendar object that can be used by calendar * user agents when describing the nature of the calendar data to a * user. Whilst a calendar only has a single description, multiple * language variants can be specified by including this property * multiple times with different "LANGUAGE" parameter values on each. * * @formatter:on * */ boolean untersuchenDESCRIPTION(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft DTEND * * @formatter:off * * RFC 5545 (september 2009) item 3.8.2.2; p. 95 * * Property Name: DTEND * * Purpose: This property specifies the date and time that a calendar * component ends. * * Value Type: The default value type is DATE-TIME. * The value type can be set to a DATE value type. * * Property Parameters: IANA, non-standard, value data type, and time * zone identifier property parameters can be specified on this * property. * * Conformance: This property can be specified in "VEVENT" or * "VFREEBUSY" calendar components. * * Description: Within the "VEVENT" calendar component, this property * defines the date and time by which the event ends. The value type * of this property MUST be the same as the "DTSTART" property, and * its value MUST be later in time than the value of the "DTSTART" * property. Furthermore, this property MUST be specified as a date * with local time if and only if the "DTSTART" property is also * specified as a date with local time. * Within the "VFREEBUSY" calendar component, this property defines * the end date and time for the free or busy time information. The * time MUST be specified in the UTC time format. The value MUST be * later in time than the value of the "DTSTART" property. * * Format Definition: This property is defined by the following notation: * * dtend = "DTEND" dtendparam ":" dtendval CRLF * * dtendparam = *( * * The following are OPTIONAL, but MUST NOT occur more than once. * * (";" "VALUE" "=" ("DATE-TIME" / "DATE")) / * (";" tzidparam) / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * ) * * dtendval = date-time / date * * Value MUST match value type * * @formatter:on * */ boolean untersuchenDTEND(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft DTSTAMP * * @formatter:off * * RFC 5545 (september 2009) item 3.8.7.2; p. 137 * * Property Name: DTSTAMP * * Purpose: In the case of an iCalendar object that specifies a * "METHOD" property, this property specifies the date and time that * the instance of the iCalendar object was created. In the case of * an iCalendar object that doesn’t specify a "METHOD" property, this * property specifies the date and time that the information * associated with the calendar component was last revised in the * calendar store. * * Value Type: DATE-TIME * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: This property MUST be included in the "VEVENT", * "VTODO", "VJOURNAL", or "VFREEBUSY" calendar components. * * Description: The value MUST be specified in the UTC time format. * This property is also useful to protocols such as [2447bis] that * have inherent latency issues with the delivery of content. This * property will assist in the proper sequencing of messages * containing iCalendar objects. * In the case of an iCalendar object that specifies a "METHOD" * property, this property differs from the "CREATED" and "LAST- * MODIFIED" properties. These two properties are used to specify * when the particular calendar data in the calendar store was * created and last modified. This is different than when the * iCalendar object representation of the calendar service * information was created or last modified. * In the case of an iCalendar object that doesn’t specify a "METHOD" * property, this property is equivalent to the "LAST-MODIFIED" property. * * Format Definition: This property is defined by the following notation: * * dtstamp = "DTSTAMP" stmparam ":" date-time CRLF * * stmparam = *(";" other-param) * * @formatter:on * */ boolean untersuchenDTSTAMP(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft DTSTART * * @formatter:off * * RFC 5545 (september 2009) item 3.8.2.4; p. 97 * * Property Name: DTSTART * * Purpose: This property specifies when the calendar component begins. * * Value Type: The default value type is DATE-TIME. The time value * MUST be one of the forms defined for the DATE-TIME value type. * The value type can be set to a DATE value type. * * Property Parameters: IANA, non-standard, value data type, and time * zone identifier property parameters can be specified on this property. * * Conformance: This property can be specified once in the "VEVENT", * "VTODO", or "VFREEBUSY" calendar components as well as in the * "STANDARD" and "DAYLIGHT" sub-components. This property is * REQUIRED in all types of recurring calendar components that * specify the "RRULE" property. This property is also REQUIRED in * "VEVENT" calendar components contained in iCalendar objects that * don’t specify the "METHOD" property. * * Description: Within the "VEVENT" calendar component, this property * defines the start date and time for the event. * Within the "VFREEBUSY" calendar component, this property defines * the start date and time for the free or busy time information. * The time MUST be specified in UTC time. * Within the "STANDARD" and "DAYLIGHT" sub-components, this property * defines the effective start date and time for a time zone * specification. This property is REQUIRED within each "STANDARD" * and "DAYLIGHT" sub-components included in "VTIMEZONE" calendar * components and MUST be specified as a date with local time without * the "TZID" property parameter. * * Format Definition: This property is defined by the following notation: * * dtstart = "DTSTART" dtstparam ":" dtstval CRLF * * dtstparam = *( * * The following are OPTIONAL, but MUST NOT occur more than once. * * (";" "VALUE" "=" ("DATE-TIME" / "DATE")) / * (";" tzidparam) / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * ) * * dtstval = date-time / date * * Value MUST match value type * * @formatter:on * */ boolean untersuchenDTSTART(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft DUE * * @formatter:off * * RFC 5545 (september 2009) item 3.8.2.3; p. 96 * * Property Name: DUE * * Purpose: This property defines the date and time that a to-do is * expected to be completed. * * Value Type: The default value type is DATE-TIME. * The value type can be set to a DATE value type. * * Property Parameters: IANA, non-standard, value data type, and time * zone identifier property parameters can be specified on this property. * * Conformance: The property can be specified once in a "VTODO" calendar component. * * Description: This property defines the date and time before which a * to-do is expected to be completed. For cases where this property * is specified in a "VTODO" calendar component that also specifies a * "DTSTART" property, the value type of this property MUST be the * same as the "DTSTART" property, and the value of this property * MUST be later in time than the value of the "DTSTART" property. * Furthermore, this property MUST be specified as a date with local * time if and only if the "DTSTART" property is also specified as a * date with local time. * * Format Definition: This property is defined by the following notation: * * due = "DUE" dueparam ":" dueval CRLF * * dueparam = *( * * The following are OPTIONAL, but MUST NOT occur more than once. * (";" "VALUE" "=" ("DATE-TIME" / "DATE")) / * (";" tzidparam) / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * * ) * * dueval = date-time / date * * Value MUST match value type * * * @formatter:on * */ boolean untersuchenDUE(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft DURATION * * @formatter:off * * RFC 5545 (september 2009) item 3.8.2.5; p. 99 * * * Property Name: DURATION * * Purpose: This property specifies a positive duration of time. * * Value Type: DURATION * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: This property can be specified in "VEVENT", "VTODO", or * "VALARM" calendar components. * * Description: In a "VEVENT" calendar component the property may be * used to specify a duration of the event, instead of an explicit * end DATE-TIME. In a "VTODO" calendar component the property may * be used to specify a duration for the to-do, instead of an * explicit due DATE-TIME. In a "VALARM" calendar component the * property may be used to specify the delay period prior to * repeating an alarm. When the "DURATION" property relates to a * "DTSTART" property that is specified as a DATE value, then the * "DURATION" property MUST be specified as a "dur-day" or "dur-week" * value. * * Format Definition: This property is defined by the following notation: * * duration = "DURATION" durparam ":" dur-value CRLF * * consisting of a positive duration of time. * * durparam = *(";" other-param) * * @formatter:on * */ boolean untersuchenDURATION(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Exception Date-Times * * @formatter:off * * RFC 5545 (september 2009) item 3.8.5.1.; p. 118 * * Property Name: EXDATE * * Purpose: This property defines the list of DATE-TIME exceptions for * recurring events, to-dos, journal entries, or time zone * definitions. * * Value Type: The default value type for this property is DATE-TIME. * The value type can be set to DATE. * * Property Parameters: IANA, non-standard, value data type, and time * zone identifier property parameters can be specified on this property. * * Conformance: This property can be specified in recurring "VEVENT", * "VTODO", and "VJOURNAL" calendar components as well as in the * "STANDARD" and "DAYLIGHT" sub-components of the "VTIMEZONE" * calendar component. * * Description: The exception dates, if specified, are used in * computing the recurrence set. The recurrence set is the complete * set of recurrence instances for a calendar component. The * recurrence set is generated by considering the initial "DTSTART" * property along with the "RRULE", "RDATE", and "EXDATE" properties * contained within the recurring component. The "DTSTART" property * defines the first instance in the recurrence set. The "DTSTART" * property value SHOULD match the pattern of the recurrence rule, if * specified. The recurrence set generated with a "DTSTART" property * value that doesn’t match the pattern of the rule is undefined. * The final recurrence set is generated by gathering all of the * start DATE-TIME values generated by any of the specified "RRULE" * and "RDATE" properties, and then excluding any start DATE-TIME * values specified by "EXDATE" properties. This implies that start * DATE-TIME values specified by "EXDATE" properties take precedence * over those specified by inclusion properties (i.e., "RDATE" and * "RRULE"). When duplicate instances are generated by the "RRULE" * and "RDATE" properties, only one recurrence is considered. * Duplicate instances are ignored. * * The "EXDATE" property can be used to exclude the value specified * in "DTSTART". However, in such cases, the original "DTSTART" date * MUST still be maintained by the calendaring and scheduling system * because the original "DTSTART" value has inherent usage * dependencies by other properties such as the "RECURRENCE-ID". * * Format Definition: This property is defined by the following notation: * * exdate = "EXDATE" exdtparam ":" exdtval *("," exdtval) CRLF * * exdtparam = *( * * The following are OPTIONAL, but MUST NOT occur more than once. * * (";" "VALUE" "=" ("DATE-TIME" / "DATE")) / * (";" tzidparam) / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * ) * * exdtval = date-time / date * * Value MUST match value type * * @formatter:on * */ boolean untersuchenEXDATE(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Exception Rule * * D E P R E C A T E D * * @formatter:off * * RFC 2445 (November 1998) item 4.8.5.2; p. 114 * * Property Name: EXRULE * * Purpose: This property defines a rule or repeating pattern for an * exception to a recurrence set. * * Value Type: RECUR * * Property Parameters: Non-standard property parameters can be * specified on this property. * * Conformance: This property can be specified in "VEVENT", "VTODO" or * "VJOURNAL" calendar components. * * Description: The exception rule, if specified, is used in computing * the recurrence set. The recurrence set is the complete set of * recurrence instances for a calendar component. The recurrence set is * generated by considering the initial "DTSTART" property along with * the "RRULE", "RDATE", "EXDATE" and "EXRULE" properties contained * within the iCalendar object. The "DTSTART" defines the first instance * in the recurrence set. Multiple instances of the "RRULE" and "EXRULE" * properties can also be specified to define more sophisticated * recurrence sets. The final recurrence set is generated by gathering * all of the start date-times generated by any of the specified "RRULE" * and "RDATE" properties, and excluding any start date and times which * fall within the union of start date and times generated by any * specified "EXRULE" and "EXDATE" properties. This implies that start * date and times within exclusion related properties (i.e., "EXDATE" * and "EXRULE") take precedence over those specified by inclusion * properties (i.e., "RDATE" and "RRULE"). Where duplicate instances are * generated by the "RRULE" and "RDATE" properties, only one recurrence * is considered. Duplicate instances are ignored. * The "EXRULE" property can be used to exclude the value specified in * "DTSTART". However, in such cases the original "DTSTART" date MUST * still be maintained by the calendaring and scheduling system because * the original "DTSTART" value has inherent usage dependencies by other * properties such as the "RECURRENCE-ID". * * Format Definition: The property is defined by the following notation: * * exrule = "EXRULE" exrparam ":" recur CRLF * * exrparam = *(";" xparam) * * * @formatter:on * */ // boolean untersuchenEXRULE(GuKKiCalProperty property) { // if (logger.isLoggable(logLevel)) { // logger.log(logLevel, "begonnen"); // } // if (logger.isLoggable(logLevel)) { // logger.log(logLevel, "beendet"); // } // return true; // } /** * Bearbeitungsroutinen für die Eigenschaft Free/Busy Time * * @formatter:off * * RFC 5545 (september 2009) item 3.8.2.6.; p. 100 * * Property Name: FREEBUSY * * Purpose: This property defines one or more free or busy time * intervals. * * Value Type: PERIOD * * Property Parameters: IANA, non-standard, and free/busy time type * property parameters can be specified on this property. * * Conformance: The property can be specified in a "VFREEBUSY" calendar * component. * * Description: These time periods can be specified as either a start * and end DATE-TIME or a start DATE-TIME and DURATION. The date and * time MUST be a UTC time format. * * "FREEBUSY" properties within the "VFREEBUSY" calendar component * SHOULD be sorted in ascending order, based on start time and then * end time, with the earliest periods first. * * The "FREEBUSY" property can specify more than one value, separated * by the COMMA character. In such cases, the "FREEBUSY" property * values MUST all be of the same "FBTYPE" property parameter type * (e.g., all values of a particular "FBTYPE" listed together in a * single property). * * Format Definition: This property is defined by the following notation: * * freebusy = "FREEBUSY" fbparam ":" fbvalue CRLF * * fbparam = *( * * The following is OPTIONAL, but MUST NOT occur more than once. * * (";" fbtypeparam) / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * ) * * fbvalue = period *("," period) * * Time value MUST be in the UTC time format. * * @formatter:on * */ boolean untersuchenFREEBUSY(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Geographic Position * * @formatter:off * * RFC 5545 (september 2009) item 3.8.1.6; p. 85 * * Property Name: GEO * * Purpose: This property specifies information related to the global * position for the activity specified by a calendar component. * * Value Type: FLOAT. The value MUST be two SEMICOLON-separated FLOAT values. * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: This property can be specified in "VEVENT" or "VTODO" * calendar components. * * Description: This property value specifies latitude and longitude, * in that order (i.e., "LAT LON" ordering). The longitude * represents the location east or west of the prime meridian as a * positive or negative real number, respectively. The longitude and * latitude values MAY be specified up to six decimal places, which * will allow for accuracy to within one meter of geographical * position. Receiving applications MUST accept values of this * precision and MAY truncate values of greater precision. * Values for latitude and longitude shall be expressed as decimal * fractions of degrees. Whole degrees of latitude shall be * represented by a two-digit decimal number ranging from 0 through * 90. Whole degrees of longitude shall be represented by a decimal * number ranging from 0 through 180. When a decimal fraction of a * degree is specified, it shall be separated from the whole number * of degrees by a decimal point. * Latitudes north of the equator shall be specified by a plus sign * (+), or by the absence of a minus sign (-), preceding the digits * designating degrees. Latitudes south of the Equator shall be * designated by a minus sign (-) preceding the digits designating * degrees. A point on the Equator shall be assigned to the Northern * Hemisphere. * Longitudes east of the prime meridian shall be specified by a plus * sign (+), or by the absence of a minus sign (-), preceding the * digits designating degrees. Longitudes west of the meridian shall * be designated by minus sign (-) preceding the digits designating * degrees. A point on the prime meridian shall be assigned to the * Eastern Hemisphere. A point on the 180th meridian shall be * assigned to the Western Hemisphere. One exception to this last * convention is permitted. For the special condition of describing * a band of latitude around the earth, the East Bounding Coordinate * data element shall be assigned the value +180 (180) degrees. * Any spatial address with a latitude of +90 (90) or -90 degrees * will specify the position at the North or South Pole, * respectively. The component for longitude may have any legal * value. * With the exception of the special condition described above, this * form is specified in [ANSI INCITS 61-1986]. * The simple formula for converting degrees-minutes-seconds into * decimal degrees is: * * decimal = degrees + minutes/60 + seconds/3600. * * Format Definition: This property is defined by the following notation: * * geo = "GEO" geoparam ":" geovalue CRLF * * geoparam = *(";" other-param) * * geovalue = float ";" float * * Latitude and Longitude components * * @formatter:on * */ boolean untersuchenGEO(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft IMAGE * * @formatter:off * * RFC 7986 (October 2016) item 5.10.; p. 11 * * Property Name: IMAGE * * Purpose: This property specifies an image associated with the * calendar or a calendar component. * * Value Type: URI or BINARY -- no default. * The value MUST be data with a media type of "image" or refer to such data. * * Property Parameters: IANA, non-standard, display, inline encoding, * and value data type property parameters can be specified on this * property. The format type parameter can be specified on this * property and is RECOMMENDED for inline binary-encoded content * information. * * Conformance: This property can be specified multiple times in an * iCalendar object or in "VEVENT", "VTODO", or "VJOURNAL" calendar components. * * Description: This property specifies an image for an iCalendar * object or a calendar component via a URI or directly with inline * data that can be used by calendar user agents when presenting the * calendar data to a user. Multiple properties MAY be used to * specify alternative sets of images with, for example, varying * media subtypes, resolutions, or sizes. When multiple properties * are present, calendar user agents SHOULD display only one of them, * picking one that provides the most appropriate image quality, or * display none. The "DISPLAY" parameter is used to indicate the * intended display mode for the image. The "ALTREP" parameter, * defined in [RFC5545], can be used to provide a "clickable" image * where the URI in the parameter value can be "launched" by a click * on the image in the calendar user agent. * * Format Definition: This property is defined by the following notation: * * image = "IMAGE" imageparam ( * * (";" "VALUE" "=" "URI" ":" uri) / * (";" "ENCODING" "=" "BASE64" ";" "VALUE" "=" "BINARY" ":" binary) * * ) CRLF * * imageparam = *( * * The following is OPTIONAL for a URI value, RECOMMENDED for a BINARY value, * and MUST NOT occur more than once. * * (";" fmttypeparam) / * * The following are OPTIONAL, and MUST NOT occur more than once.; * * (";" altrepparam) / (";" displayparam) / * * The following is OPTIONAL,and MAY occur more than once. * * (";" other-param) * * ) * * @formatter:on * */ boolean untersuchenIMAGE(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Last Modified * * @formatter:off * * RFC 5545 (september 2009) item 3.8.7.3p. 138 * * Property Name: LAST-MODIFIED * * Purpose: This property specifies the date and time that the * information associated with the calendar component was last * revised in the calendar store. * * Note: This is analogous to the modification date and time for a * file in the file system. * * Value Type: DATE-TIME * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: This property can be specified in the "VEVENT", * "VTODO", "VJOURNAL", or "VTIMEZONE" calendar components. * * Description: The property value MUST be specified in the UTC time * format. * * Format Definition: This property is defined by the following notation: * * last-mod = "LAST-MODIFIED" lstparam ":" date-time CRLF * * lstparam = *(";" other-param) * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * * RFC 7986 (October 2016) item 5.4.; p. 8 * * LAST-MODIFIED Property * * This specification modifies the definition of the "LAST-MODIFIED" * property to allow it to be defined in an iCalendar object. The * following additions are made to the definition of this property, * originally specified in Section 3.8.7.3 of [RFC5545]. * * Purpose: This property specifies the date and time that the * information associated with the calendar was last revised. * * Conformance: This property can be specified once in an iCalendar object. * * @formatter:on * */ boolean untersuchenLAST_MOD(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Location * * @formatter:off * * RFC 5545 (september 2009) item 3.8.1.7; p. 87 * * Property Name: LOCATION * * Purpose: This property defines the intended venue for the activity * defined by a calendar component. * * Value Type: TEXT * * Property Parameters: IANA, non-standard, alternate text * representation, and language property parameters can be specified * on this property. * * Conformance: This property can be specified in "VEVENT" or "VTODO" * calendar component. * * Description: Specific venues such as conference or meeting rooms may * be explicitly specified using this property. An alternate * representation may be specified that is a URI that points to * directory information with more structured specification of the * location. For example, the alternate representation may specify * either an LDAP URL [RFC4516] pointing to an LDAP server entry or a * CID URL [RFC2392] pointing to a MIME body part containing a * Virtual-Information Card (vCard) [RFC2426] for the location. * * Format Definition: This property is defined by the following notation: * * location = "LOCATION" locparam ":" text CRLF * * locparam= *( * * The following are OPTIONAL, but MUST NOT occur more than once. * * (";" altrepparam) / (";" languageparam) / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * * ) * * @formatter:on * */ boolean untersuchenLOCATION(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Method * * RFC 5545 (september 2009) item 3.7.2.; p. 77 * * @formatter:off * * Property Name: METHOD * * Purpose: This property defines the iCalendar object method * associated with the calendar object. * * Value Type: TEXT * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: This property can be specified once in an iCalendar object. * * Description: When used in a MIME message entity, the value of this * property MUST be the same as the Content-Type "method" parameter * value. If either the "METHOD" property or the Content-Type * "method" parameter is specified, then the other MUST also be * specified. * No methods are defined by this specification. This is the subject * of other specifications, such as the iCalendar Transport- * independent Interoperability Protocol (iTIP) defined by [2446bis]. * If this property is not present in the iCalendar object, then a * scheduling transaction MUST NOT be assumed. In such cases, the * iCalendar object is merely being used to transport a snapshot of * some calendar information; without the intention of conveying a * scheduling semantic. * * Format Definition: This property is defined by the following notation: * * method = "METHOD" metparam ":" metvalue CRLF * * metparam = *(";" other-param) * * metvalue = iana-token * * @formatter:on * */ boolean untersuchenMETHOD(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft NAME * * @formatter:off * * RFC 7986 (October 2016) item 5.1.; p. 5 * * Property Name: NAME * * Purpose: This property specifies the name of the calendar. * * Value Type: TEXT * * Property Parameters: IANA, non-standard, alternate text * representation, and language property parameters can be specified * on this property. * * Conformance: This property can be specified multiple times in an * iCalendar object. However, each property MUST represent the name * of the calendar in a different language. * * Description: This property is used to specify a name of the * iCalendar object that can be used by calendar user agents when * presenting the calendar data to a user. Whilst a calendar only * has a single name, multiple language variants can be specified by * including this property multiple times with different "LANGUAGE" * parameter values on each. * * Format Definition: This property is defined by the following notation: * * name = "NAME" nameparam ":" text CRLF * * nameparam = *( * * The following are OPTIONAL, but MUST NOT occur more than once. * * (";" altrepparam) / (";" languageparam) / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * * ) * * @formatter:on * */ boolean untersuchenNAME(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Organizer * * @formatter:off * * RFC 5545 (september 2009) item 3.8.4.3; p. 111 * * Property Name: ORGANIZER * * Purpose: This property defines the organizer for a calendar * component. * * Value Type: CAL-ADDRESS * * Property Parameters: IANA, non-standard, language, common name, * directory entry reference, and sent-by property parameters can be * specified on this property. * * Conformance: This property MUST be specified in an iCalendar object * that specifies a group-scheduled calendar entity. This property * MUST be specified in an iCalendar object that specifies the * publication of a calendar user’s busy time. This property MUST * NOT be specified in an iCalendar object that specifies only a time * zone definition or that defines calendar components that are not * group-scheduled components, but are components only on a single * user’s calendar. * * Description: This property is specified within the "VEVENT", * "VTODO", and "VJOURNAL" calendar components to specify the * organizer of a group-scheduled calendar entity. The property is * specified within the "VFREEBUSY" calendar component to specify the * calendar user requesting the free or busy time. When publishing a * "VFREEBUSY" calendar component, the property is used to specify * the calendar that the published busy time came from. * The property has the property parameters "CN", for specifying the * common or display name associated with the "Organizer", "DIR", for * specifying a pointer to the directory information associated with * the "Organizer", "SENT-BY", for specifying another calendar user * that is acting on behalf of the "Organizer". The non-standard * parameters may also be specified on this property. If the * "LANGUAGE" property parameter is specified, the identified * language applies to the "CN" parameter value. * * Format Definition: This property is defined by the following notation: * * organizer = "ORGANIZER" orgparam ":" cal-address CRLF * * orgparam= *( * * The following are OPTIONAL, but MUST NOT occur more than once. * * (";" cnparam) / (";" dirparam) / (";" sentbyparam) / * (";" languageparam) / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * * ) * * @formatter:on * */ boolean untersuchenORGANIZER(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Percent Complete * * @formatter:off * * RFC 5545 (september 2009) item 3.8.1.8; p. 88. * * Property Name: PERCENT-COMPLETE * * Purpose: This property is used by an assignee or delegatee of a * to-do to convey the percent completion of a to-do to the * "Organizer". * * Value Type: INTEGER * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: This property can be specified once in a "VTODO" * calendar component. * * Description: The property value is a positive integer between 0 and * 100. A value of "0" indicates the to-do has not yet been started. * A value of "100" indicates that the to-do has been completed. * Integer values in between indicate the percent partially complete. * When a to-do is assigned to multiple individuals, the property * value indicates the percent complete for that portion of the to-do * assigned to the assignee or delegatee. For example, if a to-do is * assigned to both individuals "A" and "B". A reply from "A" with a * percent complete of "70" indicates that "A" has completed 70% of * the to-do assigned to them. A reply from "B" with a percent * complete of "50" indicates "B" has completed 50% of the to-do * assigned to them. * * Format Definition: This property is defined by the following notation: * * percent = "PERCENT-COMPLETE" pctparam ":" integer CRLF * * pctparam = *(";" other-param) * * @formatter:on * */ boolean untersuchenPERCENT(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Priority * * @formatter:off * * RFC 5545 (september 2009) item 3.8.1.9; p. 89 * * Property Name: PRIORITY * * Purpose: This property defines the relative priority for a calendar * component. * * Value Type: INTEGER * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: This property can be specified in "VEVENT" and "VTODO" * calendar components. * * Description: This priority is specified as an integer in the range 0 * to 9. A value of 0 specifies an undefined priority. A value of 1 * is the highest priority. A value of 2 is the second highest * priority. Subsequent numbers specify a decreasing ordinal * priority. A value of 9 is the lowest priority. * A CUA with a three-level priority scheme of "HIGH", "MEDIUM", and * "LOW" is mapped into this property such that a property value in * the range of 1 to 4 specifies "HIGH" priority. A value of 5 is * the normal or "MEDIUM" priority. A value in the range of 6 to 9 * is "LOW" priority. * A CUA with a priority schema of "A1", "A2", "A3", "B1", "B2", ..., * "C3" is mapped into this property such that a property value of 1 * specifies "A1", a property value of 2 specifies "A2", a property * value of 3 specifies "A3", and so forth up to a property value of * 9 specifies "C3". * Other integer values are reserved for future use. * Within a "VEVENT" calendar component, this property specifies a * priority for the event. This property may be useful when more * than one event is scheduled for a given time period. * Within a "VTODO" calendar component, this property specified a * priority for the to-do. This property is useful in prioritizing * multiple action items for a given time period. * * Format Definition: This property is defined by the following notation: * * priority = "PRIORITY" prioparam ":" priovalue CRLF * * Default is zero (i.e., undefined). * * prioparam = *(";" other-param) * * priovalue = integer * * Must be in the range [0..9] * All other values are reserved for future use. * * @formatter:on * */ boolean untersuchenPRIORITY(String zeichenkette, int aktion) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Product Identifier * * RFC 5545 (september 2009) item 3.7.3.; p. 78 * * @formatter:off * * Property Name: PRODID * * Purpose: This property specifies the identifier for the product that * created the iCalendar object. * * Value Type: TEXT * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: The property MUST be specified once in an iCalendar object. * * Description: The vendor of the implementation SHOULD assure that * this is a globally unique identifier; using some technique such as * an FPI value, as defined in [ISO.9070.1991]. * This property SHOULD NOT be used to alter the interpretation of an * iCalendar object beyond the semantics specified in this memo. For * example, it is not to be used to further the understanding of non- * standard properties. * * Format Definition: This property is defined by the following notation: * * prodid = "PRODID" pidparam ":" pidvalue CRLF * * pidparam = *(";" other-param) * * pidvalue = text * * Any text that describes the product and version * * @formatter:on * */ boolean untersuchenPRODID(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Recurrence Date-Times * * @formatter:off * * RFC 5545 (september 2009) item 3.8.5.2.; p. 120 * * Property Name: RDATE * * Purpose: This property defines the list of DATE-TIME values for * recurring events, to-dos, journal entries, or time zone * definitions. * * Value Type: The default value type for this property is DATE-TIME. * The value type can be set to DATE or PERIOD. * * Property Parameters: IANA, non-standard, value data type, and time * zone identifier property parameters can be specified on this * property. * * Conformance: This property can be specified in recurring "VEVENT", * "VTODO", and "VJOURNAL" calendar components as well as in the * "STANDARD" and "DAYLIGHT" sub-components of the "VTIMEZONE" * calendar component. * * Description: This property can appear along with the "RRULE" * property to define an aggregate set of repeating occurrences. * When they both appear in a recurring component, the recurrence * instances are defined by the union of occurrences defined by both * the "RDATE" and "RRULE". * * The recurrence dates, if specified, are used in computing the * recurrence set. The recurrence set is the complete set of * recurrence instances for a calendar component. The recurrence set * is generated by considering the initial "DTSTART" property along * with the "RRULE", "RDATE", and "EXDATE" properties contained * within the recurring component. The "DTSTART" property defines * the first instance in the recurrence set. The "DTSTART" property * value SHOULD match the pattern of the recurrence rule, if * specified. The recurrence set generated with a "DTSTART" property * value that doesn’t match the pattern of the rule is undefined. * The final recurrence set is generated by gathering all of the * start DATE-TIME values generated by any of the specified "RRULE" * and "RDATE" properties, and then excluding any start DATE-TIME * values specified by "EXDATE" properties. This implies that start * DATE-TIME values specified by "EXDATE" properties take precedence * over those specified by inclusion properties (i.e., "RDATE" and * "RRULE"). Where duplicate instances are generated by the "RRULE" * and "RDATE" properties, only one recurrence is considered. * Duplicate instances are ignored. * * Format Definition: This property is defined by the following notation: * * rdate = "RDATE" rdtparam ":" rdtval *("," rdtval) CRLF * * rdtparam = *( * * The following are OPTIONAL, but MUST NOT occur more than once. * * (";" "VALUE" "=" ("DATE-TIME" / "DATE" / "PERIOD")) / * (";" tzidparam) / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * ) * * rdtval = date-time / date / period * * Value MUST match value type * * @formatter:on * */ boolean untersuchenRDATE(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Recurrence ID * * @formatter:off * * RFC 5545 (september 2009) item 3.8.4.4; p. 112 * * Property Name: RECURRENCE-ID * * Purpose: This property is used in conjunction with the "UID" and * "SEQUENCE" properties to identify a specific instance of a * recurring "VEVENT", "VTODO", or "VJOURNAL" calendar component. * The property value is the original value of the "DTSTART" property * of the recurrence instance. * * Value Type: The default value type is DATE-TIME. The value type can * be set to a DATE value type. This property MUST have the same * value type as the "DTSTART" property contained within the * recurring component. Furthermore, this property MUST be specified * as a date with local time if and only if the "DTSTART" property * contained within the recurring component is specified as a date * with local time. * * Property Parameters: IANA, non-standard, value data type, time zone * identifier, and recurrence identifier range parameters can be * specified on this property. * * Conformance: This property can be specified in an iCalendar object * containing a recurring calendar component. * * Description: The full range of calendar components specified by a * recurrence set is referenced by referring to just the "UID" * property value corresponding to the calendar component. The * "RECURRENCE-ID" property allows the reference to an individual * instance within the recurrence set. * If the value of the "DTSTART" property is a DATE type value, then * the value MUST be the calendar date for the recurrence instance. * The DATE-TIME value is set to the time when the original * recurrence instance would occur; meaning that if the intent is to * change a Friday meeting to Thursday, the DATE-TIME is still set to * the original Friday meeting. * The "RECURRENCE-ID" property is used in conjunction with the "UID" * and "SEQUENCE" properties to identify a particular instance of a * recurring event, to-do, or journal. For a given pair of "UID" and * "SEQUENCE" property values, the "RECURRENCE-ID" value for a * recurrence instance is fixed. * The "RANGE" parameter is used to specify the effective range of * recurrence instances from the instance specified by the * "RECURRENCE-ID" property value. The value for the range parameter * can only be "THISANDFUTURE" to indicate a range defined by the * given recurrence instance and all subsequent instances. * Subsequent instances are determined by their "RECURRENCE-ID" value * and not their current scheduled start time. Subsequent instances * defined in separate components are not impacted by the given * recurrence instance. When the given recurrence instance is * rescheduled, all subsequent instances are also rescheduled by the * same time difference. For instance, if the given recurrence * instance is rescheduled to start 2 hours later, then all * subsequent instances are also rescheduled 2 hours later. * Similarly, if the duration of the given recurrence instance is * modified, then all subsequence instances are also modified to have * this same duration. * * Note: The "RANGE" parameter may not be appropriate to * reschedule specific subsequent instances of complex recurring * calendar component. Assuming an unbounded recurring calendar * component scheduled to occur on Mondays and Wednesdays, the * "RANGE" parameter could not be used to reschedule only the * future Monday instances to occur on Tuesday instead. In such * cases, the calendar application could simply truncate the * unbounded recurring calendar component (i.e., with the "COUNT" * or "UNTIL" rule parts), and create two new unbounded recurring * calendar components for the future instances. * * Format Definition: This property is defined by the following notation: * * recurid = "RECURRENCE-ID" ridparam ":" ridval CRLF * * ridparam = *( * * The following are OPTIONAL, but MUST NOT occur more than once. * * (";" "VALUE" "=" ("DATE-TIME" / "DATE")) / * (";" tzidparam) / (";" rangeparam) / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * * ) * * ridval = date-time / date * * Value MUST match value type * * @formatter:on * */ boolean untersuchenRECURID(String zeichenkette, int aktion) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft REFRESH-INTERVAL * * @formatter:off * * RFC 7986 (October 2016) item 5.7.; p. 9 * * Property Name: REFRESH-INTERVAL * * Purpose: This property specifies a suggested minimum interval for * polling for changes of the calendar data from the original source * of that data. * * Value Type: DURATION -- no default * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: This property can be specified once in an iCalendar object. * * Description: This property specifies a positive duration that gives * a suggested minimum polling interval for checking for updates to * the calendar data. The value of this property SHOULD be used by * calendar user agents to limit the polling interval for calendar * data updates to the minimum interval specified. * * Format Definition: This property is defined by the following notation: * * refresh = "REFRESH-INTERVAL" refreshparam":" dur-value CRLF * * consisting of a positive duration of time. * * refreshparam = *( * * The following is REQUIRED, but MUST NOT occur more than once. * * (";" "VALUE" "=" "DURATION") / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * ) * * @formatter:on * */ boolean untersuchenREFRESH(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Related To * * RFC 5545 (September 2009) item 3.8.4.5.; p. 115 * * @formatter:off * * Property Name: RELATED-TO * * Purpose: This property is used to represent a relationship or * reference between one calendar component and another. * * Value Type: TEXT * * Property Parameters: IANA, non-standard, and relationship type * property parameters can be specified on this property. * * Conformance: This property can be specified in the "VEVENT", * "VTODO", and "VJOURNAL" calendar components. * * Description: The property value consists of the persistent, globally * unique identifier of another calendar component. This value would * be represented in a calendar component by the "UID" property. * * By default, the property value points to another calendar * component that has a PARENT relationship to the referencing * object. The "RELTYPE" property parameter is used to either * explicitly state the default PARENT relationship type to the * referenced calendar component or to override the default PARENT * relationship type and specify either a CHILD or SIBLING * relationship. The PARENT relationship indicates that the calendar * component is a subordinate of the referenced calendar component. * The CHILD relationship indicates that the calendar component is a * superior of the referenced calendar component. The SIBLING * relationship indicates that the calendar component is a peer of * the referenced calendar component. * * Changes to a calendar component referenced by this property can * have an implicit impact on the related calendar component. For * example, if a group event changes its start or end date or time, * then the related, dependent events will need to have their start * and end dates changed in a corresponding way. Similarly, if a * PARENT calendar component is cancelled or deleted, then there is * an implied impact to the related CHILD calendar components. This * property is intended only to provide information on the * relationship of calendar components. It is up to the target * calendar system to maintain any property implications of this * relationship. * * Format Definition: This property is defined by the following notation: * * related = "RELATED-TO" relparam ":" text CRLF * * relparam = *( * * The following is OPTIONAL, but MUST NOT occur more than once. * * (";" reltypeparam) / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * ) * * @formatter:on * */ boolean untersuchenRELATED(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Repeat Count * * @formatter:off * * RFC 5545 (september 2009) item 3.8.6.2.; p. 133 * * Property Name: REPEAT * * Purpose: This property defines the number of times the alarm should * be repeated, after the initial trigger. * * Value Type: INTEGER * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: This property can be specified in a "VALARM" calendar * component. * * Description: This property defines the number of times an alarm * should be repeated after its initial trigger. If the alarm * triggers more than once, then this property MUST be specified * along with the "DURATION" property. * * Format Definition: This property is defined by the following notation: * * repeat = "REPEAT" repparam ":" integer CRLF * * Default is "0", zero. * * repparam = *(";" other-param) * * @formatter:on * */ boolean untersuchenREPEAT(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Request Status * * @formatter:off * * RFC 5545 (september 2009) item 3.8.8.3.; p. 141 * * Property Name: REQUEST-STATUS * * Purpose: This property defines the status code returned for a * scheduling request. * * Value Type: TEXT * * Property Parameters: IANA, non-standard, and language property * parameters can be specified on this property. * * Conformance: The property can be specified in the "VEVENT", "VTODO", * "VJOURNAL", or "VFREEBUSY" calendar component. * * Description: This property is used to return status code information * related to the processing of an associated iCalendar object. The * value type for this property is TEXT. * * The value consists of a short return status component, a longer * return status description component, and optionally a status- * specific data component. The components of the value are * separated by the SEMICOLON character. * * The short return status is a PERIOD character separated pair or * 3-tuple of integers. For example, "3.1" or "3.1.1". The * successive levels of integers provide for a successive level of * status code granularity. * * The following are initial classes for the return status code. * Individual iCalendar object methods will define specific return * status codes for these classes. In addition, other classes for * the return status code may be defined using the registration * process defined later in this memo. * * +--------+----------------------------------------------------------+ * | Short | Longer Return Status Description | * | Return | | * | Status | | * | Code | | * +--------+----------------------------------------------------------+ * | 1.xx | Preliminary success. This class of status code | * | | indicates that the request has been initially processed | * | | but that completion is pending. | * | | | * | 2.xx | Successful. This class of status code indicates that | * | | the request was completed successfully. However, the | * | | exact status code can indicate that a fallback has been | * | | taken. | * | | | * | 3.xx | Client Error. This class of status code indicates that | * | | the request was not successful. The error is the result | * | | of either a syntax or a semantic error in the client- | * | | formatted request. Request should not be retried until | * | | the condition in the request is corrected. | * | | | * | 4.xx | Scheduling Error. This class of status code indicates | * | | that the request was not successful. Some sort of error | * | | occurred within the calendaring and scheduling service, | * | | not directly related to the request itself. | * +--------+----------------------------------------------------------+ * * Format Definition: This property is defined by the following notation: * * rstatus = "REQUEST-STATUS" rstatparam ":" * * statcode ";" statdesc [";" extdata] * * rstatparam = *( * * The following is OPTIONAL, but MUST NOT occur more than once. * * (";" languageparam) / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * ) * * statcode = 1*DIGIT 1*2("." 1*DIGIT) * * Hierarchical, numeric return status code * * statdesc = text * * Textual status description * * extdata = text * * Textual exception data. For example, the offending property * name and value or complete property line. * * @formatter:on * */ boolean untersuchenRSTATUS(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Resources * * @formatter:off * * RFC 5545 (september 2009) item 3.8.1.10.; p. 91 * * Property Name: RESOURCES * * Purpose: This property defines the equipment or resources * anticipated for an activity specified by a calendar component. * * Value Type: TEXT * * Property Parameters: IANA, non-standard, alternate text * representation, and language property parameters can be specified * on this property. * * Conformance: This property can be specified once in "VEVENT" or * "VTODO" calendar component. * * Description: The property value is an arbitrary text. More than one * resource can be specified as a COMMA-separated list of resources. * * Format Definition: This property is defined by the following notation: * * resources = "RESOURCES" resrcparam ":" text *("," text) CRLF * * resrcparam = *( * * The following are OPTIONAL, but MUST NOT occur more than once. * * (";" altrepparam) / (";" languageparam) / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * ) * * @formatter:on * */ boolean untersuchenRESOURCES(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Recurrence Rule * * @formatter:off * * RFC 5545 (september 2009) item 3.8.5.3; p. 122 * * Property Name: RRULE * * Purpose: This property defines a rule or repeating pattern for * recurring events, to-dos, journal entries, or time zone definitions. * * Value Type: RECUR * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: This property can be specified in recurring "VEVENT", * "VTODO", and "VJOURNAL" calendar components as well as in the * "STANDARD" and "DAYLIGHT" sub-components of the "VTIMEZONE" * calendar component, but it SHOULD NOT be specified more than once. * The recurrence set generated with multiple "RRULE" properties is * undefined. * * Description: The recurrence rule, if specified, is used in computing * the recurrence set. The recurrence set is the complete set of * recurrence instances for a calendar component. The recurrence set * is generated by considering the initial "DTSTART" property along * with the "RRULE", "RDATE", and "EXDATE" properties contained * within the recurring component. The "DTSTART" property defines * the first instance in the recurrence set. The "DTSTART" property * value SHOULD be synchronized with the recurrence rule, if * specified. The recurrence set generated with a "DTSTART" property * value not synchronized with the recurrence rule is undefined. The * final recurrence set is generated by gathering all of the start * DATE-TIME values generated by any of the specified "RRULE" and * "RDATE" properties, and then excluding any start DATE-TIME values * specified by "EXDATE" properties. This implies that start DATE-TIME * values specified by "EXDATE" properties take precedence over * those specified by inclusion properties (i.e., "RDATE" and * "RRULE"). Where duplicate instances are generated by the "RRULE" * and "RDATE" properties, only one recurrence is considered. * Duplicate instances are ignored. * The "DTSTART" property specified within the iCalendar object * defines the first instance of the recurrence. In most cases, a * "DTSTART" property of DATE-TIME value type used with a recurrence * rule, should be specified as a date with local time and time zone * reference to make sure all the recurrence instances start at the * same local time regardless of time zone changes. * If the duration of the recurring component is specified with the * "DTEND" or "DUE" property, then the same exact duration will apply * to all the members of the generated recurrence set. Else, if the * duration of the recurring component is specified with the * "DURATION" property, then the same nominal duration will apply to * all the members of the generated recurrence set and the exact * duration of each recurrence instance will depend on its specific * start time. For example, recurrence instances of a nominal * duration of one day will have an exact duration of more or less * than 24 hours on a day where a time zone shift occurs. The * duration of a specific recurrence may be modified in an exception * component or simply by using an "RDATE" property of PERIOD value * type. * * Format Definition: This property is defined by the following notation: * * rrule = "RRULE" rrulparam ":" recur CRLF * * rrulparam = *(";" other-param) * * @formatter:on * */ boolean untersuchenRRULE(String zeichenkette, int aktion) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Sequence Number * * @formatter:off * * RFC 5545 (september 2009) item 3.8.7.4; p. 138 * * Property Name: SEQUENCE * * Purpose: This property defines the revision sequence number of the * calendar component within a sequence of revisions. * * Value Type: INTEGER * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: The property can be specified in "VEVENT", "VTODO", or * "VJOURNAL" calendar component. * * Description: When a calendar component is created, its sequence * number is 0. It is monotonically incremented by the "Organizer’s" * CUA each time the "Organizer" makes a significant revision to the * calendar component. * The "Organizer" includes this property in an iCalendar object that * it sends to an "Attendee" to specify the current version of the * calendar component. * The "Attendee" includes this property in an iCalendar object that * it sends to the "Organizer" to specify the version of the calendar * component to which the "Attendee" is referring. * A change to the sequence number is not the mechanism that an * "Organizer" uses to request a response from the "Attendees". The * "RSVP" parameter on the "ATTENDEE" property is used by the * "Organizer" to indicate that a response from the "Attendees" is * requested. * Recurrence instances of a recurring component MAY have different * sequence numbers. * * Format Definition: This property is defined by the following notation: * * seq = "SEQUENCE" seqparam ":" integer CRLF * * Default is "0" * * seqparam = *(";" other-param) * * @formatter:on * */ boolean untersuchenSEQ(String zeichenkette, int aktion) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft SOURCE * * RFC 7986 (October 2016) item 5.8.; p. 9 * * @formatter:off * * Property Name: SOURCE * * Purpose: This property identifies a URI where calendar data can be * refreshed from. * * Value Type: URI -- no default * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: This property can be specified once in an iCalendar object. * * Description: This property identifies a location where a client can * retrieve updated data for the calendar. Clients SHOULD honor any * specified "REFRESH-INTERVAL" value when periodically retrieving * data. Note that this property differs from the "URL" property in * that "URL" is meant to provide an alternative representation of * the calendar data rather than the original location of the data. * * Format Definition: This property is defined by the following notation: * * source = "SOURCE" sourceparam ":" uri CRLF * * sourceparam = *( * * The following is REQUIRED, but MUST NOT occur more than once. * * (";" "VALUE" "=" "URI") / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * ) * * @formatter:on * */ boolean untersuchenSOURCE(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Status * * @formatter:off * * RFC 5545 (september 2009) item 3.8.1.11; p. 92 * * Property Name: STATUS * * Purpose: This property defines the overall status or confirmation * for the calendar component. * * Value Type: TEXT * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: This property can be specified once in "VEVENT", * "VTODO", or "VJOURNAL" calendar components. * * Description: In a group-scheduled calendar component, the property * is used by the "Organizer" to provide a confirmation of the event * to the "Attendees". For example in a "VEVENT" calendar component, * the "Organizer" can indicate that a meeting is tentative, * confirmed, or cancelled. In a "VTODO" calendar component, the * "Organizer" can indicate that an action item needs action, is * completed, is in process or being worked on, or has been * cancelled. In a "VJOURNAL" calendar component, the "Organizer" * can indicate that a journal entry is draft, final, or has been * cancelled or removed. * Format Definition: This property is defined by the following notation: * * status = "STATUS" statparam ":" statvalue CRLF * * statparam = *(";" other-param) * * statvalue = (statvalue-event / statvalue-todo / statvalue-jour) * * Status values for a "VEVENT" * statvalue-event = "TENTATIVE" ;Indicates event is tentative. * / "CONFIRMED" ;Indicates event is definite. * / "CANCELLED" ;Indicates event was cancelled. * * Status values for "VTODO" * statvalue-todo = "NEEDS-ACTION" ;Indicates to-do needs action. * / "COMPLETED" ;Indicates to-do is completed. * / "IN-PROCESS" ;Indicates to-do in process of. * / "CANCELLED" ;Indicates to-do was cancelled. * * Status values for "VJOURNAL" * statvalue-jour = "DRAFT" ;Indicates journal is draft. * / "FINAL" ;Indicates journal is final. * / "CANCELLED" ;Indicates journal is removed. * * @formatter:on * */ boolean untersuchenSTATUS(String zeichenkette, int aktion) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Summary * * @formatter:off * * RFC 5545 (september 2009) item 3.8.1.12; p. 93 * * Property Name: SUMMARY * * Purpose: This property defines a short summary or subject for the * calendar component. * * Value Type: TEXT * * Property Parameters: IANA, non-standard, alternate text * representation, and language property parameters can be specified * on this property. * * Conformance: The property can be specified in "VEVENT", "VTODO", * "VJOURNAL", or "VALARM" calendar components. * * Description: This property is used in the "VEVENT", "VTODO", and * "VJOURNAL" calendar components to capture a short, one-line * summary about the activity or journal entry. * This property is used in the "VALARM" calendar component to * capture the subject of an EMAIL category of alarm. * * Format Definition: This property is defined by the following notation: * * summary = "SUMMARY" summparam ":" text CRLF * * summparam = *( * * The following are OPTIONAL, but MUST NOT occur more than once. * * (";" altrepparam) / (";" languageparam) / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * * ) * * @formatter:on * * @param zeichenkette - String * @param aktion - int * * @return * * aktion 0 * Teil der übergebenen Zeichenkette nach dem Schlüsselwort * */ boolean untersuchenSUMMARY(String zeichenkette, int aktion) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Time Transparency * * @formatter:off * * RFC 5545 (september 2009) item 3.8.2.7; p. 101 * * Property Name: TRANSP * * Purpose: This property defines whether or not an event is * transparent to busy time searches. * * Value Type: TEXT * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: This property can be specified once in a "VEVENT" * calendar component. * * Description: Time Transparency is the characteristic of an event * that determines whether it appears to consume time on a calendar. * Events that consume actual time for the individual or resource * associated with the calendar SHOULD be recorded as OPAQUE, * allowing them to be detected by free/busy time searches. Other * events, which do not take up the individual’s (or resource’s) time * SHOULD be recorded as TRANSPARENT, making them invisible to free/ * busy time searches. * * Format Definition: This property is defined by the following notation: * * transp = "TRANSP" transparam ":" transvalue CRLF * * transparam = *(";" other-param) * * transvalue = "OPAQUE" * * Blocks or opaque on busy time searches. * * / "TRANSPARENT" * * Transparent on busy time searches. * * Default value is OPAQUE * * @formatter:on * */ boolean untersuchenTRANSP(String zeichenkette, int aktion) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Trigger * * @formatter:off * * RFC 5545 (september 2009) item 3.8.6.3.; p. 133 * * Property Name: TRIGGER * * Purpose: This property specifies when an alarm will trigger. * * Value Type: The default value type is DURATION. The value type can * be set to a DATE-TIME value type, in which case the value MUST * specify a UTC-formatted DATE-TIME value. * * Property Parameters: IANA, non-standard, value data type, time zone * identifier, or trigger relationship property parameters can be * specified on this property. The trigger relationship property * parameter MUST only be specified when the value type is * "DURATION". * * Conformance: This property MUST be specified in the "VALARM" * calendar component. * * Description: This property defines when an alarm will trigger. The * default value type is DURATION, specifying a relative time for the * trigger of the alarm. The default duration is relative to the * start of an event or to-do with which the alarm is associated. * The duration can be explicitly set to trigger from either the end * or the start of the associated event or to-do with the "RELATED" * parameter. A value of START will set the alarm to trigger off the * start of the associated event or to-do. A value of END will set * the alarm to trigger off the end of the associated event or to-do. * * Either a positive or negative duration may be specified for the * "TRIGGER" property. An alarm with a positive duration is * triggered after the associated start or end of the event or to-do. * An alarm with a negative duration is triggered before the * associated start or end of the event or to-do. * * The "RELATED" property parameter is not valid if the value type of * the property is set to DATE-TIME (i.e., for an absolute date and * time alarm trigger). If a value type of DATE-TIME is specified, * then the property value MUST be specified in the UTC time format. * If an absolute trigger is specified on an alarm for a recurring * event or to-do, then the alarm will only trigger for the specified * absolute DATE-TIME, along with any specified repeating instances. * * If the trigger is set relative to START, then the "DTSTART" * property MUST be present in the associated "VEVENT" or "VTODO" * calendar component. If an alarm is specified for an event with * the trigger set relative to the END, then the "DTEND" property or * the "DTSTART" and "DURATION " properties MUST be present in the * associated "VEVENT" calendar component. If the alarm is specified * for a to-do with a trigger set relative to the END, then either * the "DUE" property or the "DTSTART" and "DURATION " properties * MUST be present in the associated "VTODO" calendar component. * * Alarms specified in an event or to-do that is defined in terms of * a DATE value type will be triggered relative to 00:00:00 of the * user’s configured time zone on the specified date, or relative to * 00:00:00 UTC on the specified date if no configured time zone can * be found for the user. For example, if "DTSTART" is a DATE value * set to 19980205 then the duration trigger will be relative to * 19980205T000000 America/New_York for a user configured with the * America/New_York time zone. * * Format Definition: This property is defined by the following notation: * * trigger = "TRIGGER" (trigrel / trigabs) CRLF * * trigrel = *( * * The following are OPTIONAL, but MUST NOT occur more than once. * * (";" "VALUE" "=" "DURATION") / * (";" trigrelparam) / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * ) ":" dur-value * * trigabs = *( * * The following is REQUIRED, but MUST NOT occur more than once. * * (";" "VALUE" "=" "DATE-TIME") / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * ) ":" date-time * * @formatter:on * */ boolean untersuchenTRIGGER(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Time Zone Identifier * * @formatter:off * * RFC 5545 (september 2009) item 3.8.3.1.; p. 102 * * Property Name: TZID * * Purpose: This property specifies the text value that uniquely * identifies the "VTIMEZONE" calendar component in the scope of an * iCalendar object. * * Value Type: TEXT * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: This property MUST be specified in a "VTIMEZONE" * calendar component. * * Description: This is the label by which a time zone calendar * component is referenced by any iCalendar properties whose value * type is either DATE-TIME or TIME and not intended to specify a UTC * or a "floating" time. The presence of the SOLIDUS character as a * prefix, indicates that this "TZID" represents an unique ID in a * globally defined time zone registry (when such registry is * defined). * * Note: This document does not define a naming convention for * time zone identifiers. Implementers may want to use the naming * conventions defined in existing time zone specifications such * as the public-domain TZ database [TZDB]. The specification of * globally unique time zone identifiers is not addressed by this * document and is left for future study. * * Format Definition: This property is defined by the following notation: * * tzid = "TZID" tzidpropparam ":" [tzidprefix] text CRLF * * tzidpropparam = *(";" other-param) * * tzidprefix = "/" * Defined previously. Just listed here for reader convenience. * * @formatter:on * */ boolean untersuchenTZID(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Time Zone Name * * @formatter:off * * RFC 5545 (september 2009) item 3.8.3.2.; p. 103 * * Property Name: TZNAME * * Purpose: This property specifies the customary designation for a * time zone description. * * Value Type: TEXT * * Property Parameters: IANA, non-standard, and language property * parameters can be specified on this property. * * Conformance: This property can be specified in "STANDARD" and * "DAYLIGHT" sub-components. * * Description: This property specifies a customary name that can be * used when displaying dates that occur during the observance * defined by the time zone sub-component. * * Format Definition: This property is defined by the following notation: * * tzname = "TZNAME" tznparam ":" text CRLF * * tznparam = *( * * The following is OPTIONAL, but MUST NOT occur more than once. * * (";" languageparam) / * * The following is OPTIONAL, and MAY occur more than once. * * (";" other-param) * ) * * @formatter:on * */ boolean untersuchenTZNAME(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Time Zone Offset From * * @formatter:off * * RFC 5545 (september 2009) item 3.8.3.3.; p. 104 * * Property Name: TZOFFSETFROM * * Purpose: This property specifies the offset that is in use prior to * this time zone observance. * * Value Type: UTC-OFFSET * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: This property MUST be specified in "STANDARD" and * "DAYLIGHT" sub-components. * * Description: This property specifies the offset that is in use prior * to this time observance. It is used to calculate the absolute * time at which the transition to a given observance takes place. * This property MUST only be specified in a "VTIMEZONE" calendar * component. A "VTIMEZONE" calendar component MUST include this * property. The property value is a signed numeric indicating the * number of hours and possibly minutes from UTC. Positive numbers * represent time zones east of the prime meridian, or ahead of UTC. * Negative numbers represent time zones west of the prime meridian, * or behind UTC. * * Format Definition: This property is defined by the following notation: * * tzoffsetfrom = "TZOFFSETFROM" frmparam ":" utc-offset CRLF * * frmparam = *(";" other-param) * * @formatter:on * */ boolean untersuchenTZOFFSETFROM(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Time Zone Offset To * * @formatter:off * * RFC 5545 (september 2009) item 3.8.3.4.; p. 105 * * Property Name: TZOFFSETTO * * Purpose: This property specifies the offset that is in use in this * time zone observance. * * Value Type: UTC-OFFSET * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: This property MUST be specified in "STANDARD" and * "DAYLIGHT" sub-components. * * Description: This property specifies the offset that is in use in * this time zone observance. It is used to calculate the absolute * time for the new observance. The property value is a signed * numeric indicating the number of hours and possibly minutes from * UTC. Positive numbers represent time zones east of the prime * meridian, or ahead of UTC. Negative numbers represent time zones * west of the prime meridian, or behind UTC. * * Format Definition: This property is defined by the following notation: * * tzoffsetto = "TZOFFSETTO" toparam ":" utc-offset CRLF * * toparam = *(";" other-param) * * @formatter:on * */ boolean untersuchenTZOFFSETTO(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Time Zone URL * * @formatter:off * * RFC 5545 (september 2009) item 3.8.3.5.; p. 80 * * Property Name: TZURL * * Purpose: This property provides a means for a "VTIMEZONE" component * to point to a network location that can be used to retrieve an up- * to-date version of itself. * * Value Type: URI * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: This property can be specified in a "VTIMEZONE" * calendar component. * * Description: This property provides a means for a "VTIMEZONE" * component to point to a network location that can be used to * retrieve an up-to-date version of itself. This provides a hook to * handle changes government bodies impose upon time zone * definitions. Retrieval of this resource results in an iCalendar * object containing a single "VTIMEZONE" component and a "METHOD" * property set to PUBLISH. * * Format Definition: This property is defined by the following notation: * * tzurl = "TZURL" tzurlparam ":" uri CRLF * * tzurlparam = *(";" other-param) * * @formatter:on * */ boolean untersuchenTZURL(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Unique Identifier * * @formatter:off * * RFC 5545 (september 2009) item 3.8.4.7; p. 117 * * Property Name: UID * * Purpose: This property defines the persistent, globally unique * identifier for the calendar component. * * Value Type: TEXT * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: The property MUST be specified in the "VEVENT", * "VTODO", "VJOURNAL", or "VFREEBUSY" calendar components. * Description: The "UID" itself MUST be a globally unique identifier. * The generator of the identifier MUST guarantee that the identifier * is unique. There are several algorithms that can be used to * accomplish this. A good method to assure uniqueness is to put the * domain name or a domain literal IP address of the host on which * the identifier was created on the right-hand side of an "@", and * on the left-hand side, put a combination of the current calendar * date and time of day (i.e., formatted in as a DATE-TIME value) * along with some other currently unique (perhaps sequential) * identifier available on the system (for example, a process id * number). Using a DATE-TIME value on the left-hand side and a * domain name or domain literal on the right-hand side makes it * possible to guarantee uniqueness since no two hosts should be * using the same domain name or IP address at the same time. Though * other algorithms will work, it is RECOMMENDED that the right-hand * side contain some domain identifier (either of the host itself or * otherwise) such that the generator of the message identifier can * guarantee the uniqueness of the left-hand side within the scope of * that domain. * * This is the method for correlating scheduling messages with the * referenced "VEVENT", "VTODO", or "VJOURNAL" calendar component. * The full range of calendar components specified by a recurrence * set is referenced by referring to just the "UID" property value * corresponding to the calendar component. The "RECURRENCE-ID" * property allows the reference to an individual instance within the * recurrence set. * * This property is an important method for group-scheduling * applications to match requests with later replies, modifications, * or deletion requests. Calendaring and scheduling applications * MUST generate this property in "VEVENT", "VTODO", and "VJOURNAL" * calendar components to assure interoperability with other group- * scheduling applications. This identifier is created by the * calendar system that generates an iCalendar object. * Implementations MUST be able to receive and persist values of at * least 255 octets for this property, but they MUST NOT truncate * values in the middle of a UTF-8 multi-octet sequence. * * Format Definition: This property is defined by the following notation: * * uid = "UID" uidparam ":" text CRLF * * uidparam = *(";" other-param) * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * * RFC 7986 (october 2016) item 5.3.; p. 7 * * UID Property * * This specification modifies the definition of the "UID" property to * allow it to be defined in an iCalendar object. The following * additions are made to the definition of this property, originally * specified in Section 3.8.4.7 of [RFC5545]. * * Purpose: This property specifies the persistent, globally unique * identifier for the iCalendar object. This can be used, for * example, to identify duplicate calendar streams that a client may * have been given access to. It can be used in conjunction with the * "LAST-MODIFIED" property also specified on the "VCALENDAR" object * to identify the most recent version of a calendar. * * Conformance: This property can be specified once in an iCalendar object. * * Description: The description of the "UID" property in [RFC5545] contains some * recommendations on how the value can be constructed. In particular, * it suggests use of host names, IP addresses, and domain names to * construct the value. However, this is no longer considered good * practice, particularly from a security and privacy standpoint, since * use of such values can leak key information about a calendar user or * their client and network environment. This specification updates * [RFC5545] by stating that "UID" values MUST NOT include any data that * might identify a user, host, domain, or any other security- or * privacy-sensitive information. It is RECOMMENDED that calendar user * agents now generate "UID" values that are hex-encoded random * Universally Unique Identifier (UUID) values as defined in * Sections 4.4 and 4.5 of [RFC4122]. * * The following is an example of such a property value: * UID:5FC53010-1267-4F8E-BC28-1D7AE55A7C99 * * Additionally, if calendar user agents choose to use other forms of * opaque identifiers for the "UID" value, they MUST have a length less * than 255 octets and MUST conform to the "iana-token" ABNF syntax * defined in Section 3.1 of [RFC5545]. * * @formatter:on * */ boolean untersuchenUID(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } private String holenNeueUID() { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } String uniqueID = UUID.randomUUID().toString(); if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return uniqueID; } /** * Bearbeitungsroutinen für die Eigenschaft Uniform Resource Locator * * @formatter:off * * RFC 5545 (september 2009) item 3.8.4.6; p. 116 * * Property Name: URL * * Purpose: This property defines a Uniform Resource Locator (URL) * associated with the iCalendar object. * * Value Type: URI * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: This property can be specified once in the "VEVENT", * "VTODO", "VJOURNAL", or "VFREEBUSY" calendar components. * * Description: This property may be used in a calendar component to * convey a location where a more dynamic rendition of the calendar * information associated with the calendar component can be found. * This memo does not attempt to standardize the form of the URI, nor * the format of the resource pointed to by the property value. If * the URL property and Content-Location MIME header are both * specified, they MUST point to the same resource. * * Format Definition: This property is defined by the following notation: * * url = "URL" urlparam ":" uri CRLF * * urlparam = *(";" other-param) * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * * RFC 7986 (October 2016) item 5.5.; p. 8 * * URL Property * * This specification modifies the definition of the "URL" property to * allow it to be defined in an iCalendar object. The following * additions are made to the definition of this property, originally * specified in Section 3.8.4.6 of [RFC5545]. * * Purpose: This property may be used to convey a location where a more * dynamic rendition of the calendar information can be found. * * Conformance: This property can be specified once in an iCalendar object. * * @formatter:on * */ boolean untersuchenURL(String zeichenkette, int aktion) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Version * * RFC 5545 (september 2009) item 3.7.4.; p. 79 * * @formatter:off * * Property Name: VERSION * * Purpose: This property specifies the identifier corresponding to the * highest version number or the minimum and maximum range of the * iCalendar specification that is required in order to interpret the * iCalendar object. * * Value Type: TEXT * * Property Parameters: IANA and non-standard property parameters can * be specified on this property. * * Conformance: This property MUST be specified once in an iCalendar object. * * Description: A value of "2.0" corresponds to this memo. * * Format Definition: This property is defined by the following notation: * * version = "VERSION" verparam ":" vervalue CRLF * * verparam = *(";" other-param) * * vervalue = "2.0" ;This memo * / maxver * / (minver ";" maxver) * * minver = <A IANA-registered iCalendar version identifier> * ;Minimum iCalendar version needed to parse the iCalendar object. * * maxver = <A IANA-registered iCalendar version identifier> * ;Maximum iCalendar version needed to parse the iCalendar object. * * @formatter:on * */ boolean untersuchenVERSION(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } /** * Bearbeitungsroutinen für die Eigenschaft Non-Standard Properties * * RFC 5545 (september 2009) item 3.8.8.2.; p. 140 * * @formatter:off * * Property Name: Any property name with a "X-" prefix * * Purpose: This class of property provides a framework for defining * non-standard properties. * * Value Type: The default value type is TEXT. * The value type can be set to any value type. * * Property Parameters: IANA, non-standard, and language property * parameters can be specified on this property. * * Conformance: This property can be specified in any calendar * component. * * Description: The MIME Calendaring and Scheduling Content Type * provides a "standard mechanism for doing non-standard things". * This extension support is provided for implementers to "push the * envelope" on the existing version of the memo. Extension * properties are specified by property and/or property parameter * names that have the prefix text of "X-" (the two-character * sequence: LATIN CAPITAL LETTER X character followed by the HYPHEN- * MINUS character). It is recommended that vendors concatenate onto * this sentinel another short prefix text to identify the vendor. * This will facilitate readability of the extensions and minimize * possible collision of names between different vendors. User * agents that support this content type are expected to be able to * parse the extension properties and property parameters but can * ignore them. * * At present, there is no registration authority for names of * extension properties and property parameters. The value type for * this property is TEXT. Optionally, the value type can be any of * the other valid value types. * * Format Definition: This property is defined by the following notation: * * x-prop = x-name *(";" icalparameter) ":" value CRLF * * @formatter:on * */ boolean untersuchenX_PROP(GuKKiCalProperty property) { if (logger.isLoggable(logLevel)) { logger.log(logLevel, "begonnen"); } if (logger.isLoggable(logLevel)) { logger.log(logLevel, "beendet"); } return true; } }
34.231556
95
0.677511
13b1f6e72cdf67a1bdca53e36459ca311d6965d6
292
class TestFeatureG { public static void main(String[] a){ System.out.println(new Test().f()); } } class Test { public int f(){ int result, count; result = 0; count = 1; while (count < 11) { result = result + count; count = count + 1; } return result; } }
13.272727
40
0.568493
054cdf16dfcf6cf69e696889da98894bc9bc18ad
18,497
package Model.AccountRelated; import Controller.IDGenerator; import Model.GameRelated.GameLog; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Comparator; import java.util.LinkedList; import java.util.stream.Collectors; public abstract class Event { private static LinkedList<Event> events = new LinkedList<>(); private final String eventID; private String pictureUrl; private String title, details; private double eventScore; private LocalDate start, end; private LinkedList<EventParticipant> participants = new LinkedList<>(); private boolean awardsGiven = false; // true if an event has ended and its awards have been given, false otherwise protected Event (String pictureUrl, String title, String details, double eventScore, LocalDate start, LocalDate end) { this.pictureUrl = pictureUrl; this.title = title; this.details = details; this.eventScore = eventScore; this.start = start; this.end = end; this.eventID = IDGenerator.generateNext(); } /** * @param eventType if 1 -> MVPEvent * if 2 -> LoginEvent * if 3 -> NumOfPlayedEvent * if 4 -> NumOfWinsEvent * if 5 -> NConsecutiveWinsEvent */ public static void addEvent (int eventType, int numberOfRequired, String pictureUrl, String title, String gameName, String details, double eventScore, LocalDate start, LocalDate end) { switch (eventType) { case 1 -> new MVPEvent(pictureUrl, title, details, eventScore, start, end, gameName); case 2 -> new LoginEvent(pictureUrl, title, details, eventScore, start, end, numberOfRequired); case 3 -> new NumberOfPlayedEvent(pictureUrl, title, details, eventScore, start, end, numberOfRequired, gameName); case 4 -> new NumberOfWinsEvent(pictureUrl, title, details, eventScore, start, end, numberOfRequired, gameName); case 5 -> new WinGameNTimesConsecutiveLyEvent(pictureUrl, title, details, eventScore, start, end, numberOfRequired, gameName); default -> throw new IllegalStateException("Unexpected value: " + eventType); } } // بین ایونتها میگرده دنبال یه ایونتی که آیدیش این باشه public static void removeEvent (String eventID) { events.remove(getEvent(eventID)); } // یین همه ایونتا میگرده و اونایی که این کاربر جزو شرکت کننده هاشون بوده رو برمیگردونه public static LinkedList<Event> getInSessionEventsParticipatingIn (Gamer gamer) { return getAllInSessionEvents().stream() .filter(event -> event.participantExists(gamer.getUsername())) .collect(Collectors.toCollection(LinkedList::new)); } // وقتی هر روز برای ایونتایی که تایمشون تموم شده میگرده، این متد جایزه اونایی که تموم شدن رو میده @SuppressWarnings("ForLoopReplaceableByForEach") public static void dealWOverdueEvents () { for (int i = 0; i < events.size(); i++) { Event event = events.get(i); if (event.isDue() && !event.awardsGiven) event.giveAwardsOfOverdueEvent(); } } public static LinkedList<Event> getAllEvents () { return events; } // برای deserialize کردن public static void setEvents (LinkedList<Event> events) { if (events == null) events = new LinkedList<>(); Event.events = events; } // ایونتایی که شروع شدند .لی تموم نشدند رو مرتب میکنه و برمیگردونه // ترتیب مرتب کردن تو کامنتای داخل متده public static LinkedList<Event> getAllInSessionEvents () { return getAllEvents().stream() .filter(Event::isInSession) .collect(Collectors.toCollection(LinkedList::new)); } // چک میکنه اگه ایونت شروع نشده ای با این آیدی وجود داره یا نه @SuppressWarnings("unused") public static boolean upcomingEventExists (String eventID) { return events.stream() .filter(event -> !event.hasStarted()) .anyMatch(event -> event.getEventID().equals(eventID)); } public static LinkedList<Event> getAllUpcomingEvents () { return events.stream() .filter(event -> !event.hasStarted()) .collect(Collectors.toCollection(LinkedList::new)); } public static LinkedList<Event> getSortedEvents (LinkedList<Event> list) { return list.stream() .sorted(Comparator.comparing(Event::getStart) // from earliest starting .thenComparing(Event::getEnd) // from earliest ending .thenComparingDouble(Event::getEventScore).reversed() // from highest prizes .thenComparing(Event::getEventID)) .collect(Collectors.toCollection(LinkedList::new)); } // بین ایونتا دنبال این آیدی میگرده و اون ایونت رو پس میده @SuppressWarnings("OptionalGetWithoutIsPresent") public static Event getEvent (String eventID) { return events.stream() .filter(event -> event.getEventID().equals(eventID)) .findAny().get(); } // بین ایونتا میگرده که آیا این آیدی وجود داره یا نه public static boolean eventExists (String eventID) { return events.stream() .anyMatch(event -> event.getEventID().equals(eventID)); } // چک میکنه که آیا ایونت درحال اجرایی با این آیدی وجود داره یا نه public static boolean eventInSessionExists (String eventID) { for (int i = 0; i < getAllInSessionEvents().size(); i++) if (getAllInSessionEvents().get(i).getEventID().equals(eventID)) return true; return false; } public static LinkedList<Event> getAllEventsParticipatingIn (Gamer gamer) { return events.stream() .filter(event -> event.participantExists(gamer.getUsername())) .collect(Collectors.toCollection(LinkedList::new)); } public static LinkedList<Event> getAllUpcomingEventsParticipatingIn (Gamer gamer) { return getAllUpcomingEvents().stream() .filter(event -> event.participantExists(gamer.getUsername())) .collect(Collectors.toCollection(LinkedList::new)); } // ویژگی گفته شده رو تغییر میده public void editField (String field, String newVal) { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("d-MMM-yyyy"); switch (field.toLowerCase()) { case "title" -> title = newVal; case "prize" -> eventScore = Double.parseDouble(newVal); case "start date" -> start = LocalDate.parse(newVal, dateTimeFormatter); case "end date" -> end = LocalDate.parse(newVal, dateTimeFormatter); case "details" -> details = newVal; case "pic-url" -> pictureUrl = newVal; default -> throw new IllegalStateException("Unexpected value: " + field.toLowerCase()); } } // چک میکنه که آیا زمان شروع ایونت قبل یا خود امروز هست یا نه public boolean hasStarted () { return !LocalDate.now().isBefore(start); } // چک میکنه که ایا زمان پایان ایونت قبل امروز هست یا نه private boolean isDue () { return LocalDate.now().isAfter(end); } // چک میکنه کا آیا ایونت شروع شده و تموم نشده هست یا نه public boolean isInSession () { return hasStarted() && !isDue(); } // وقتی هر روز برای ایونتایی که تایمشون تموم شده میگرده، این متد جایزه اونایی که تموم شدن رو میده public void giveAwardsOfOverdueEvent () { awardsGiven = true; } // بازیکن را به لیست شرکت کنندگان ایونت اضافه میکند public abstract void addParticipant (Gamer gamer); // بازیکن را از لیست شرکت کنندگان ایونت حذف میکند public void removeParticipant (Gamer gamer) { participants.removeIf(participant -> participant.getUsername().equals(gamer.getUsername())); } // چک میکنه که آیا بازیکن تو ایونت شرکت میکنه یا نه @SuppressWarnings("ForLoopReplaceableByForEach") public boolean participantExists (String username) { for (int i = 0; i < participants.size(); i++) { if (participants.get(i).getUsername().equals(username)) return true; } return false; } // دنبال شرکت کننده با این نام کاربری میگرده و برمیگردونه @SuppressWarnings({"ForLoopReplaceableByForEach", "unused"}) public Gamer getParticipant (String username) { for (int i = 0; i < participants.size(); i++) if (participants.get(i).getUsername().equals(username)) return (Gamer) Account.getAccount(participants.get(i).getUsername()); return null; } // لیست کل شرکنندگان رو میده public LinkedList<EventParticipant> getParticipants () { if (participants == null) participants = new LinkedList<>(); return participants; } public String getEventID () { return eventID; } public double getEventScore () { return eventScore; } public LocalDate getStart () { return start; } public LocalDate getEnd () { return end; } public String getTitle () { return title; } public String getPictureUrl () { return pictureUrl; } public String getDetails () { return details; } public abstract String getGameName (); public abstract String getHowTo (); } class MVPEvent extends Event { private String gameName; public MVPEvent (String pictureUrl, String title, String details, double eventScore, LocalDate start, LocalDate end, String gameName) { super(pictureUrl, title, details, eventScore, start, end); this.gameName = gameName; } public MVPEvent (String pictureUrl, String title, String details, double eventScore, LocalDate start, LocalDate end) { super(pictureUrl, title, details, eventScore, start, end); } @Override public void editField (String field, String newVal) { super.editField(field, newVal); switch (field.toLowerCase()) { case "title", "pic-url", "details", "end date", "start date", "prize" -> {} case "game name" -> gameName = newVal; default -> throw new IllegalStateException("Unexpected value: " + field.toLowerCase()); } } @Override public void giveAwardsOfOverdueEvent () { super.giveAwardsOfOverdueEvent(); Gamer mvpGamer = getMvp(); if (GameLog.getPlayedCount(mvpGamer, gameName) == 0) return; mvpGamer.setMoney(mvpGamer.getMoney() + getEventScore()); } @Override public void addParticipant (Gamer gamer) { getParticipants().add(new MVPEventParticipant(gamer.getUsername())); } @Override public String getGameName () { return gameName; } @Override public String getHowTo () { return "get to the #1 spot on the scoreboard for " + gameName + " until " + getEnd().format(DateTimeFormatter.ofPattern("dth of MMMM")) + " to get the prize"; } public Gamer getMvp () { return GameLog.getAllGamersWhoPlayedGame(gameName).stream() .sorted((gamer1, gamer2) -> { int cmp; cmp = -GameLog.getPoints(gamer1, gameName).compareTo(GameLog.getPoints(gamer2, gameName)); if (cmp != 0) return cmp; cmp = -GameLog.getWinCount(gamer1, gameName).compareTo(GameLog.getWinCount(gamer2, gameName)); if (cmp != 0) return cmp; cmp = GameLog.getLossCount(gamer1, gameName).compareTo(GameLog.getLossCount(gamer2, gameName)); if (cmp != 0) return cmp; cmp = GameLog.getPlayedCount(gamer1, gameName).compareTo(GameLog.getPlayedCount(gamer2, gameName)); if (cmp != 0) return cmp; return -GameLog.getDrawCount(gamer1, gameName).compareTo(GameLog.getDrawCount(gamer2, gameName)); }) .collect(Collectors.toCollection(LinkedList::new)) .get(0); } } class LoginEvent extends Event { private int numberOfRequired; public LoginEvent (String pictureUrl, String title, String details, double eventScore, LocalDate start, LocalDate end, int numberOfRequired) { super(pictureUrl, title, details, eventScore, start, end); this.numberOfRequired = numberOfRequired; } public LoginEvent (String pictureUrl, String title, String details, double eventScore, LocalDate start, LocalDate end) { super(pictureUrl, title, details, eventScore, start, end); } @Override public void giveAwardsOfOverdueEvent () { super.giveAwardsOfOverdueEvent(); getWinners() .forEach(participant -> { Gamer gamer = (Gamer) Account.getAccount(participant.getUsername()); gamer.setMoney(gamer.getMoney() + getEventScore()); }); } @Override public void addParticipant (Gamer gamer) { getParticipants().add(new LoginEventParticipant(gamer.getUsername())); } @Override public String getGameName () { return null; } @Override public String getHowTo () { return "login " + numberOfRequired + " time" + (numberOfRequired == 1 ? "" : "s") + " until " + getEnd().format(DateTimeFormatter.ofPattern("dth of MMMM")) + " to get the prize"; } public LinkedList<LoginEventParticipant> getWinners () { return getParticipants().stream() .map(participant -> ((LoginEventParticipant) participant)) .filter(participant -> participant.getNumberOfLogins() >= numberOfRequired) .collect(Collectors.toCollection(LinkedList::new)); } } class NumberOfPlayedEvent extends Event { private int numberOfRequired; private String gameName; public NumberOfPlayedEvent (String pictureUrl, String title, String details, double eventScore, LocalDate start, LocalDate end, int numberOfRequired, String gameName) { super(pictureUrl, title, details, eventScore, start, end); this.numberOfRequired = numberOfRequired; this.gameName = gameName; } public NumberOfPlayedEvent (String pictureUrl, String title, String details, double eventScore, LocalDate start, LocalDate end) { super(pictureUrl, title, details, eventScore, start, end); } @Override public void editField (String field, String newVal) { super.editField(field, newVal); switch (field.toLowerCase()) { case "title", "pic-url", "details", "end date", "start date", "prize" -> {} case "game name" -> gameName = newVal; default -> throw new IllegalStateException("Unexpected value: " + field.toLowerCase()); } } @Override public void giveAwardsOfOverdueEvent () { super.giveAwardsOfOverdueEvent(); getWinners() .forEach(participant -> { Gamer gamer = (Gamer) Account.getAccount(participant.getUsername()); gamer.setMoney(gamer.getMoney() + getEventScore()); }); } @Override public void addParticipant (Gamer gamer) { getParticipants().add(new NumberOfPlayedEventParticipant(gamer.getUsername())); } @Override public String getGameName () { return gameName; } @Override public String getHowTo () { return "play " + gameName + " " + numberOfRequired + " time" + (numberOfRequired == 1 ? "" : "s") + " until " + getEnd().format(DateTimeFormatter.ofPattern("dth of MMMM")) + " to get the prize"; } public LinkedList<NumberOfPlayedEventParticipant> getWinners () { return getParticipants().stream() .map(participant -> ((NumberOfPlayedEventParticipant) participant)) .filter(participant -> participant.getNumberOfPlayed() >= numberOfRequired) .collect(Collectors.toCollection(LinkedList::new)); } } class NumberOfWinsEvent extends Event { private int numberOfRequired; private String gameName; public NumberOfWinsEvent (String pictureUrl, String title, String details, double eventScore, LocalDate start, LocalDate end, int numberOfRequired, String gameName) { super(pictureUrl, title, details, eventScore, start, end); this.numberOfRequired = numberOfRequired; this.gameName = gameName; } public NumberOfWinsEvent (String pictureUrl, String title, String details, double eventScore, LocalDate start, LocalDate end) { super(pictureUrl, title, details, eventScore, start, end); } @Override public void editField (String field, String newVal) { super.editField(field, newVal); switch (field.toLowerCase()) { case "title", "pic-url", "details", "end date", "start date", "prize" -> {} case "game name" -> gameName = newVal; default -> throw new IllegalStateException("Unexpected value: " + field.toLowerCase()); } } @Override public void giveAwardsOfOverdueEvent () { super.giveAwardsOfOverdueEvent(); getWinners() .forEach(participant -> { Gamer gamer = (Gamer) Account.getAccount(participant.getUsername()); gamer.setMoney(gamer.getMoney() + getEventScore()); }); } @Override public void addParticipant (Gamer gamer) { getParticipants().add(new NumberOfWinsEventParticipant(gamer.getUsername())); } @Override public String getGameName () { return gameName; } @Override public String getHowTo () { return "win " + gameName + " " + numberOfRequired + " time" + (numberOfRequired == 1 ? "" : "s") + " until " + getEnd().format(DateTimeFormatter.ofPattern("dth of MMMM")) + " to get the prize"; } public LinkedList<NumberOfWinsEventParticipant> getWinners () { return getParticipants().stream() .map(participant -> ((NumberOfWinsEventParticipant) participant)) .filter(participant -> participant.getNumberOfWins() >= numberOfRequired) .collect(Collectors.toCollection(LinkedList::new)); } } /** * player wins in event if they win a game n times one after another. basically no loss or draw or forfeit for n times */ class WinGameNTimesConsecutiveLyEvent extends Event { private int numberOfRequired; private String gameName; public WinGameNTimesConsecutiveLyEvent (String pictureUrl, String title, String details, double eventScore, LocalDate start, LocalDate end, int numberOfRequired, String gameName) { super(pictureUrl, title, details, eventScore, start, end); this.numberOfRequired = numberOfRequired; this.gameName = gameName; } public WinGameNTimesConsecutiveLyEvent (String pictureUrl, String title, String details, double eventScore, LocalDate start, LocalDate end) { super(pictureUrl, title, details, eventScore, start, end); } @Override public void editField (String field, String newVal) { super.editField(field, newVal); switch (field.toLowerCase()) { case "title", "pic-url", "details", "end date", "start date", "prize" -> {} case "game name" -> gameName = newVal; default -> throw new IllegalStateException("Unexpected value: " + field.toLowerCase()); } } @Override public void giveAwardsOfOverdueEvent () { super.giveAwardsOfOverdueEvent(); getWinners() .forEach(participant -> { Gamer gamer = (Gamer) Account.getAccount(participant.getUsername()); gamer.setMoney(gamer.getMoney() + getEventScore()); }); } @Override public void addParticipant (Gamer gamer) { getParticipants().add(new WinGameNTimesConsecutiveLyEventParticipant(gamer.getUsername())); } @Override public String getGameName () { return gameName; } @Override public String getHowTo () { return "win " + gameName + " " + numberOfRequired + " time" + (numberOfRequired == 1 ? "" : "s") + " consecutively until " + getEnd().format(DateTimeFormatter.ofPattern("dth of MMMM")) + " to get the prize"; } public LinkedList<WinGameNTimesConsecutiveLyEventParticipant> getWinners () { return getParticipants().stream() .map(participant -> ((WinGameNTimesConsecutiveLyEventParticipant) participant)) .filter(participant -> participant.getNumberOfWins() >= numberOfRequired) .collect(Collectors.toCollection(LinkedList::new)); } }
33.448463
209
0.719522
aac83f4752a7d8dc5336013eebda6dd529d21526
2,179
package inpro.io.rsb; import java.util.ArrayList; import java.util.Arrays; import org.apache.log4j.Logger; import venice.lib.AbstractSlot; import venice.lib.AbstractSlotListener; import venice.lib.networkRSB.RSBNamespaceBuilder; import edu.cmu.sphinx.util.props.PropertyException; import edu.cmu.sphinx.util.props.PropertySheet; import edu.cmu.sphinx.util.props.S4String; import inpro.io.ListenerModule; /** * @author casey * */ public class RsbListenerModule extends ListenerModule implements AbstractSlotListener { static Logger log = Logger.getLogger(RsbListenerModule.class.getName()); @S4String(defaultValue = "") public final static String ID_PROP = "id"; @S4String(defaultValue = "") public final static String SCOPE_PROP = "scope"; private String fullScope; @Override public void newProperties(PropertySheet ps) throws PropertyException { super.newProperties(ps); String scope = ps.getString(SCOPE_PROP); String id = ps.getString(ID_PROP); fullScope = makeScope(scope); logger.info("Listening on scope: " + fullScope); // listener from the venice wrapper for RSB ArrayList<AbstractSlot> slots = new ArrayList<AbstractSlot>(); slots.add(new AbstractSlot(fullScope, String.class)); RSBNamespaceBuilder.initializeProtobuf(); RSBNamespaceBuilder.initializeInSlots(slots); RSBNamespaceBuilder.setMasterInSlotListener(this); this.setID(id); } private String makeScope(String scope) { return scope; } /** * Take data from the scope and split it up into an ArrayList * * @param line * @return list of data from the scope */ public ArrayList<String> parseScopedString(String line) { //sometimes it has slashes at the beginning and end if (line.startsWith("/") && line.endsWith("/")) line = line.trim().substring(1,line.length()-1); ArrayList<String> splitString = new ArrayList<String>(Arrays.asList(line.split("/"))); return splitString; } /* (non-Javadoc) * This method is called from RSB/venice when new data is received on a specified scope. * */ @Override public void newData(Object arg0, Class<?> arg1, String arg2) { process(arg0.toString(), arg2); } }
26.573171
89
0.7352
cf25fe1bc0c49820f8985f5d722e4970dad4de87
2,288
package org.thoughtcrime.securesms.util; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.Signature; import android.os.Build; import androidx.annotation.NonNull; import org.thoughtcrime.securesms.logging.Log; import org.whispersystems.libsignal.util.guava.Optional; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; public final class AppSignatureUtil { private static final String TAG = Log.tag(AppSignatureUtil.class); private static final String HASH_TYPE = "SHA-256"; private static final int HASH_LENGTH_BYTES = 9; private static final int HASH_LENGTH_CHARS = 11; private AppSignatureUtil() {} /** * Only intended to be used for logging. */ @SuppressLint("PackageManagerGetSignatures") public static Optional<String> getAppSignature(@NonNull Context context) { try { String packageName = context.getPackageName(); PackageManager packageManager = context.getPackageManager(); PackageInfo packageInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES); Signature[] signatures = packageInfo.signatures; if (signatures.length > 0) { String hash = hash(packageName, signatures[0].toCharsString()); return Optional.fromNullable(hash); } } catch (PackageManager.NameNotFoundException e) { Log.w(TAG, e); } return Optional.absent(); } private static String hash(String packageName, String signature) { String appInfo = packageName + " " + signature; try { MessageDigest messageDigest = MessageDigest.getInstance(HASH_TYPE); messageDigest.update(appInfo.getBytes(StandardCharsets.UTF_8)); byte[] hashSignature = messageDigest.digest(); hashSignature = Arrays.copyOfRange(hashSignature, 0, HASH_LENGTH_BYTES); String base64Hash = Base64.encodeBytes(hashSignature); base64Hash = base64Hash.substring(0, HASH_LENGTH_CHARS); return base64Hash; } catch (NoSuchAlgorithmException e) { Log.w(TAG, e); } return null; } }
31.777778
112
0.730769
bd1bd2aa260b11c7aad710428c58ac23c2e64229
993
package com.cainiao.wireless.crashdefend.plugin.config; public class DefendConfigElements { public static final String TAG_DEFEND_ON_DEBUG = "defendOnDebug"; public static final String TAG_DEFEND_OFF = "defendOff"; public static final String TAG_DEFEND_INTERFACE_IMPL = "defendInterfaceImpl"; public static final String TAG_DEFEND_METHOD = "defendMethod"; public static final String TAG_DEFEND_AUTO = "defendAuto"; public static final String TAG_DEFEND_CLASS = "defendClass"; public static final String TAG_DEFEND_SUB_CLASS = "defendSubClass"; public static final String ATTR_INTERFACE = "interface"; public static final String ATTR_SCOPE = "scope"; public static final String ATTR_NAME = "name"; public static final String ATTR_RETURN_VALUE = "returnValue"; public static final String ATTR_REPORT_EXCEPTION = "reportException"; public static final String ATTR_PARENT = "parent"; public static final String ATTR_CLASS = "class"; }
41.375
81
0.767372
3e8dd85abf9391c44ed4013f8eb6618d6244af31
414
package com.xkcoding.mpwechatdemo.autoconfiguration; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; /** * <p> * 属性注入 * </p> * * @author yangkai.shen * @date Created in 2019/10/22 13:54 */ @Data @ConfigurationProperties(prefix = "wechat") public class MpWeChatProperties { private String appId; private String appSecret; private String token; }
19.714286
75
0.736715
d7728f35b829109e5e2b19b68a6eec78bd244f18
9,972
/** */ package IFML.Mobile.impl; import IFML.Core.ActionEvent; import IFML.Core.ActivationExpression; import IFML.Core.CatchingEvent; import IFML.Core.CorePackage; import IFML.Core.Event; import IFML.Core.InteractionFlowExpression; import IFML.Mobile.MicrophoneActionEvent; import IFML.Mobile.MobileActionEvent; import IFML.Mobile.MobilePackage; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Microphone Action Event</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link IFML.Mobile.impl.MicrophoneActionEventImpl#getActivationExpression <em>Activation Expression</em>}</li> * <li>{@link IFML.Mobile.impl.MicrophoneActionEventImpl#getInteractionFlowExpression <em>Interaction Flow Expression</em>}</li> * </ul> * </p> * * @generated */ public class MicrophoneActionEventImpl extends MicrophoneActionImpl implements MicrophoneActionEvent { /** * The cached value of the '{@link #getActivationExpression() <em>Activation Expression</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getActivationExpression() * @generated * @ordered */ protected ActivationExpression activationExpression; /** * The cached value of the '{@link #getInteractionFlowExpression() <em>Interaction Flow Expression</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getInteractionFlowExpression() * @generated * @ordered */ protected InteractionFlowExpression interactionFlowExpression; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected MicrophoneActionEventImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return MobilePackage.Literals.MICROPHONE_ACTION_EVENT; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ActivationExpression getActivationExpression() { if (activationExpression != null && activationExpression.eIsProxy()) { InternalEObject oldActivationExpression = (InternalEObject)activationExpression; activationExpression = (ActivationExpression)eResolveProxy(oldActivationExpression); if (activationExpression != oldActivationExpression) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, MobilePackage.MICROPHONE_ACTION_EVENT__ACTIVATION_EXPRESSION, oldActivationExpression, activationExpression)); } } return activationExpression; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ActivationExpression basicGetActivationExpression() { return activationExpression; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setActivationExpression(ActivationExpression newActivationExpression) { ActivationExpression oldActivationExpression = activationExpression; activationExpression = newActivationExpression; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MobilePackage.MICROPHONE_ACTION_EVENT__ACTIVATION_EXPRESSION, oldActivationExpression, activationExpression)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public InteractionFlowExpression getInteractionFlowExpression() { return interactionFlowExpression; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetInteractionFlowExpression(InteractionFlowExpression newInteractionFlowExpression, NotificationChain msgs) { InteractionFlowExpression oldInteractionFlowExpression = interactionFlowExpression; interactionFlowExpression = newInteractionFlowExpression; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MobilePackage.MICROPHONE_ACTION_EVENT__INTERACTION_FLOW_EXPRESSION, oldInteractionFlowExpression, newInteractionFlowExpression); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setInteractionFlowExpression(InteractionFlowExpression newInteractionFlowExpression) { if (newInteractionFlowExpression != interactionFlowExpression) { NotificationChain msgs = null; if (interactionFlowExpression != null) msgs = ((InternalEObject)interactionFlowExpression).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - MobilePackage.MICROPHONE_ACTION_EVENT__INTERACTION_FLOW_EXPRESSION, null, msgs); if (newInteractionFlowExpression != null) msgs = ((InternalEObject)newInteractionFlowExpression).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - MobilePackage.MICROPHONE_ACTION_EVENT__INTERACTION_FLOW_EXPRESSION, null, msgs); msgs = basicSetInteractionFlowExpression(newInteractionFlowExpression, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MobilePackage.MICROPHONE_ACTION_EVENT__INTERACTION_FLOW_EXPRESSION, newInteractionFlowExpression, newInteractionFlowExpression)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case MobilePackage.MICROPHONE_ACTION_EVENT__INTERACTION_FLOW_EXPRESSION: return basicSetInteractionFlowExpression(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case MobilePackage.MICROPHONE_ACTION_EVENT__ACTIVATION_EXPRESSION: if (resolve) return getActivationExpression(); return basicGetActivationExpression(); case MobilePackage.MICROPHONE_ACTION_EVENT__INTERACTION_FLOW_EXPRESSION: return getInteractionFlowExpression(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case MobilePackage.MICROPHONE_ACTION_EVENT__ACTIVATION_EXPRESSION: setActivationExpression((ActivationExpression)newValue); return; case MobilePackage.MICROPHONE_ACTION_EVENT__INTERACTION_FLOW_EXPRESSION: setInteractionFlowExpression((InteractionFlowExpression)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case MobilePackage.MICROPHONE_ACTION_EVENT__ACTIVATION_EXPRESSION: setActivationExpression((ActivationExpression)null); return; case MobilePackage.MICROPHONE_ACTION_EVENT__INTERACTION_FLOW_EXPRESSION: setInteractionFlowExpression((InteractionFlowExpression)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case MobilePackage.MICROPHONE_ACTION_EVENT__ACTIVATION_EXPRESSION: return activationExpression != null; case MobilePackage.MICROPHONE_ACTION_EVENT__INTERACTION_FLOW_EXPRESSION: return interactionFlowExpression != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public int eBaseStructuralFeatureID(int derivedFeatureID, Class<?> baseClass) { if (baseClass == Event.class) { switch (derivedFeatureID) { case MobilePackage.MICROPHONE_ACTION_EVENT__ACTIVATION_EXPRESSION: return CorePackage.EVENT__ACTIVATION_EXPRESSION; case MobilePackage.MICROPHONE_ACTION_EVENT__INTERACTION_FLOW_EXPRESSION: return CorePackage.EVENT__INTERACTION_FLOW_EXPRESSION; default: return -1; } } if (baseClass == CatchingEvent.class) { switch (derivedFeatureID) { default: return -1; } } if (baseClass == ActionEvent.class) { switch (derivedFeatureID) { default: return -1; } } if (baseClass == MobileActionEvent.class) { switch (derivedFeatureID) { default: return -1; } } return super.eBaseStructuralFeatureID(derivedFeatureID, baseClass); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public int eDerivedStructuralFeatureID(int baseFeatureID, Class<?> baseClass) { if (baseClass == Event.class) { switch (baseFeatureID) { case CorePackage.EVENT__ACTIVATION_EXPRESSION: return MobilePackage.MICROPHONE_ACTION_EVENT__ACTIVATION_EXPRESSION; case CorePackage.EVENT__INTERACTION_FLOW_EXPRESSION: return MobilePackage.MICROPHONE_ACTION_EVENT__INTERACTION_FLOW_EXPRESSION; default: return -1; } } if (baseClass == CatchingEvent.class) { switch (baseFeatureID) { default: return -1; } } if (baseClass == ActionEvent.class) { switch (baseFeatureID) { default: return -1; } } if (baseClass == MobileActionEvent.class) { switch (baseFeatureID) { default: return -1; } } return super.eDerivedStructuralFeatureID(baseFeatureID, baseClass); } } //MicrophoneActionEventImpl
32.482085
211
0.715403
7e236f6fb5aabe36a072d3101ba08eeb3987b889
440
/** * Automatically generated file. DO NOT MODIFY */ package com.theflopguyproductions.ticktrack; public final class BuildConfig { public static final boolean DEBUG = Boolean.parseBoolean("true"); public static final String APPLICATION_ID = "com.theflopguyproductions.ticktrack"; public static final String BUILD_TYPE = "debug"; public static final int VERSION_CODE = 14; public static final String VERSION_NAME = "2.1.2.2"; }
33.846154
84
0.765909
c3a9bc23a731f0ee91c83d3b297134ed637a3887
10,539
package com.mana.innovative.dao.consumer; import com.mana.innovative.constants.TestConstants; import com.mana.innovative.dao.response.DAOResponse; import com.mana.innovative.domain.consumer.Card; import com.mana.innovative.dto.request.RequestParams; import junit.framework.Assert; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.AfterTransaction; import org.springframework.test.context.transaction.BeforeTransaction; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import javax.annotation.Resource; import java.util.List; /** * Created by Bloom/Rono on 5/2/2015 6:14 PM. This class WhenGetCardThenTestCardDAOGetMethods is a test class * * @author Rono, AB, Vadim Servetnik * @email arkoghosh @hotmail.com, [email protected], [email protected] * @Copyright */ @RunWith( value = SpringJUnit4ClassRunner.class ) @ContextConfiguration( locations = { "/dbConfig-test.xml" } ) // "" <- <add location file> @Transactional // If required public class WhenGetCardThenTestCardDAOGetMethods { /** * The constant logger. */ private static final Logger logger = LoggerFactory.getLogger( WhenGetCardThenTestCardDAOGetMethods.class ); /** * The Card dAO. */ @Resource private CardDAO cardDAO; /** * The Request params. */ private RequestParams requestParams; /** * Sets up. * * @throws Exception the exception */ @Before @BeforeTransaction public void setUp( ) throws Exception { logger.debug( TestConstants.setUpMethodLoggerMsg ); requestParams = new RequestParams( ); } /** * Tear down. * * @throws Exception the exception */ @After @AfterTransaction public void tearDown( ) throws Exception { logger.debug( TestConstants.tearDownMethodLoggerMsg ); } /** * Test get cards with error disabled. * * @throws Exception the exception */ @Test @Transactional( propagation = Propagation.REQUIRES_NEW, isolation = Isolation.DEFAULT ) public void testGetCardsWithErrorDisabled( ) throws Exception { logger.debug( "Starting test for GetCardsWithErrorDisabled" ); requestParams.setIsError( TestConstants.IS_ERROR ); DAOResponse< Card > cardDAOResponse = cardDAO.getCards( requestParams ); Assert.assertNotNull( TestConstants.nullMessage, cardDAOResponse ); // test error container Assert.assertNull( TestConstants.notNullMessage, cardDAOResponse.getErrorContainer( ) ); // test result object Assert.assertNotNull( TestConstants.nullMessage, cardDAOResponse.getResults( ) ); Assert.assertFalse( TestConstants.trueMessage, cardDAOResponse.getResults( ).isEmpty( ) ); // card list and its size with DAOResponse<T> class count List< Card > cards = cardDAOResponse.getResults( ); Assert.assertNotNull( TestConstants.nullMessage, cards ); Assert.assertFalse( TestConstants.trueMessage, cards.isEmpty( ) ); Assert.assertEquals( TestConstants.notEqualsMessage, cardDAOResponse.getCount( ), cards.size( ) ); for ( Card card : cards ) { Assert.assertNotNull( TestConstants.nullMessage, card ); } logger.debug( "Finishing test for GetCardsWithErrorDisabled" ); } /** * Test get card with error disabled. * * @throws Exception the exception */ @Test @Transactional( propagation = Propagation.REQUIRES_NEW, isolation = Isolation.DEFAULT ) public void testGetCardWithErrorDisabled( ) throws Exception { logger.debug( "Starting test for GetCardWithErrorDisabled" ); requestParams.setIsError( TestConstants.IS_ERROR ); DAOResponse< Card > cardDAOResponse = cardDAO.getCardByCardId( TestConstants.TEST_ID, requestParams ); Assert.assertNotNull( TestConstants.nullMessage, cardDAOResponse ); // test error container Assert.assertNull( TestConstants.notNullMessage, cardDAOResponse.getErrorContainer( ) ); // test result object Assert.assertNotNull( TestConstants.nullMessage, cardDAOResponse.getResults( ) ); Assert.assertFalse( TestConstants.trueMessage, cardDAOResponse.getResults( ).isEmpty( ) ); // card list and its size with DAOResponse<T> class count List< Card > cards = cardDAOResponse.getResults( ); Assert.assertNotNull( TestConstants.nullMessage, cards ); Assert.assertFalse( TestConstants.trueMessage, cards.isEmpty( ) ); Assert.assertEquals( TestConstants.notEqualsMessage, cardDAOResponse.getCount( ), cards.size( ) ); Assert.assertEquals( TestConstants.ONE, cards.size( ) ); // test card Card card = cards.get( TestConstants.ZERO ); Assert.assertNotNull( TestConstants.nullMessage, card ); Assert.assertNotNull( TestConstants.nullMessage, card.getCardId( ) ); Assert.assertNotNull( TestConstants.nullMessage, card.getCardNumber( ) ); Assert.assertNotNull( TestConstants.nullMessage, card.getIssueDate( ) ); Assert.assertFalse( TestConstants.trueMessage, card.isCardHasCustomerPic( ) ); System.out.println( card.getPictureLocation( ) ); Assert.assertTrue( TestConstants.falseMessage, StringUtils.isEmpty( card.getPictureLocation( ).trim( ) ) ); Assert.assertNotNull( TestConstants.nullMessage, card.getFirstName( ) ); Assert.assertNotNull( TestConstants.nullMessage, card.getLastName( ) ); Assert.assertNotNull( TestConstants.nullMessage, card.getCreatedDate( ) ); Assert.assertNotNull( TestConstants.nullMessage, card.getUpdatedDate( ) ); logger.debug( "Finishing test for GetCardWithErrorDisabled" ); } /** * Test get cards with error enabled. * * @throws Exception the exception */ @Test @Transactional( propagation = Propagation.REQUIRES_NEW, isolation = Isolation.DEFAULT ) public void testGetCardsWithErrorEnabled( ) throws Exception { logger.debug( "Starting test for GetCardsWithErrorEnabled" ); requestParams.setIsError( TestConstants.IS_ERROR_TRUE ); DAOResponse< Card > cardDAOResponse = cardDAO.getCards( requestParams ); Assert.assertNotNull( TestConstants.nullMessage, cardDAOResponse ); // test error container Assert.assertNotNull( TestConstants.nullMessage, cardDAOResponse.getErrorContainer( ) ); Assert.assertNotNull( TestConstants.nullMessage, cardDAOResponse.getErrorContainer( ).getErrors( ) ); Assert.assertTrue( TestConstants.falseMessage, cardDAOResponse.getErrorContainer( ).getErrors( ).isEmpty( ) ); // test result object Assert.assertNotNull( TestConstants.nullMessage, cardDAOResponse.getResults( ) ); Assert.assertFalse( TestConstants.trueMessage, cardDAOResponse.getResults( ).isEmpty( ) ); // card list and its size with DAOResponse<T> class count List< Card > cards = cardDAOResponse.getResults( ); Assert.assertNotNull( TestConstants.nullMessage, cards ); Assert.assertFalse( TestConstants.trueMessage, cards.isEmpty( ) ); Assert.assertEquals( TestConstants.notEqualsMessage, cardDAOResponse.getCount( ), cards.size( ) ); for ( Card card : cards ) { Assert.assertNotNull( TestConstants.nullMessage, card ); } logger.debug( "Finishing test for GetCardsWithErrorEnabled" ); } /** * Test get card with error enabled. * * @throws Exception the exception */ @Test @Transactional( propagation = Propagation.REQUIRES_NEW, isolation = Isolation.DEFAULT ) public void testGetCardWithErrorEnabled( ) throws Exception { logger.debug( "Starting test for GetCardWithErrorEnabled" ); requestParams.setIsError( TestConstants.IS_ERROR_TRUE ); DAOResponse< Card > cardDAOResponse = cardDAO.getCardByCardId( TestConstants.TEST_ID, requestParams ); Assert.assertNotNull( TestConstants.nullMessage, cardDAOResponse ); // test error container Assert.assertNotNull( TestConstants.nullMessage, cardDAOResponse.getErrorContainer( ) ); Assert.assertNotNull( TestConstants.nullMessage, cardDAOResponse.getErrorContainer( ).getErrors( ) ); Assert.assertTrue( TestConstants.falseMessage, cardDAOResponse.getErrorContainer( ).getErrors( ).isEmpty( ) ); // test result object Assert.assertNotNull( TestConstants.nullMessage, cardDAOResponse.getResults( ) ); Assert.assertFalse( TestConstants.trueMessage, cardDAOResponse.getResults( ).isEmpty( ) ); // card list and its size with DAOResponse<T> class count List< Card > cards = cardDAOResponse.getResults( ); Assert.assertNotNull( TestConstants.nullMessage, cards ); Assert.assertFalse( TestConstants.trueMessage, cards.isEmpty( ) ); Assert.assertEquals( TestConstants.notEqualsMessage, cardDAOResponse.getCount( ), cards.size( ) ); Assert.assertEquals( TestConstants.ONE, cards.size( ) ); // test card Card card = cards.get( TestConstants.ZERO ); Assert.assertNotNull( TestConstants.nullMessage, card ); Assert.assertNotNull( TestConstants.nullMessage, card.getCardId( ) ); Assert.assertNotNull( TestConstants.nullMessage, card.getCardNumber( ) ); Assert.assertNotNull( TestConstants.nullMessage, card.getIssueDate( ) ); Assert.assertFalse( TestConstants.trueMessage, card.isCardHasCustomerPic( ) ); Assert.assertTrue( TestConstants.falseMessage, StringUtils.isEmpty( card.getPictureLocation( ).trim( ) ) ); Assert.assertNotNull( TestConstants.nullMessage, card.getFirstName( ) ); Assert.assertNotNull( TestConstants.nullMessage, card.getLastName( ) ); Assert.assertNotNull( TestConstants.nullMessage, card.getCreatedDate( ) ); Assert.assertNotNull( TestConstants.nullMessage, card.getUpdatedDate( ) ); logger.debug( "Finishing test for GetCardWithErrorEnabled" ); } }
42.841463
118
0.711073
9bb83d104131ff1dbd662e237e0f289e48f0532c
2,446
package zmaster587.advancedRocketry.tile.multiblock.machine; import java.util.List; import java.util.Set; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import zmaster587.advancedRocketry.api.AdvancedRocketryBlocks; import zmaster587.advancedRocketry.inventory.TextureResources; import zmaster587.libVulpes.LibVulpes; import zmaster587.libVulpes.api.LibVulpesBlocks; import zmaster587.libVulpes.api.material.MaterialRegistry; import zmaster587.libVulpes.block.BlockMeta; import zmaster587.libVulpes.interfaces.IRecipe; import zmaster587.libVulpes.inventory.modules.ModuleBase; import zmaster587.libVulpes.inventory.modules.ModuleProgress; import zmaster587.libVulpes.recipe.RecipesMachine; import zmaster587.libVulpes.tile.energy.TilePlugInputRF; import zmaster587.libVulpes.tile.multiblock.TileMultiBlock; import zmaster587.libVulpes.tile.multiblock.TileMultiblockMachine; public class TileElectrolyser extends TileMultiblockMachine { public static final Object[][][] structure = { {{null,null,null}, {'P', new BlockMeta(LibVulpesBlocks.blockStructureBlock),'P'}}, {{'l', 'c', 'l'}, {new BlockMeta(LibVulpesBlocks.blockStructureBlock), 'L', new BlockMeta(LibVulpesBlocks.blockStructureBlock)}}, }; @Override public Object[][][] getStructure() { return structure; } @Override public ResourceLocation getSound() { return TextureResources.sndElectrolyser; } @Override public boolean shouldHideBlock(World world, int x, int y, int z, Block tile) { TileEntity tileEntity = world.getTileEntity(x, y, z); return !TileMultiBlock.getMapping('P').contains(new BlockMeta(tile, BlockMeta.WILDCARD)) && tileEntity != null && !(tileEntity instanceof TileElectrolyser); } @Override public AxisAlignedBB getRenderBoundingBox() { return AxisAlignedBB.getBoundingBox(xCoord -2,yCoord -2, zCoord -2, xCoord + 2, yCoord + 2, zCoord + 2); } @Override public List<ModuleBase> getModules(int ID, EntityPlayer player) { List<ModuleBase> modules = super.getModules(ID, player); modules.add(new ModuleProgress(100, 4, 0, TextureResources.crystallizerProgressBar, this)); return modules; } @Override public String getMachineName() { return "tile.electrolyser.name"; } }
33.972222
158
0.790679
0dea7f3bfff388f24d73c0b15753c763fed5879c
594
package org.multibit.hd.core.dto; /** * <p>Enum to provide the following to Core API:</p> * <ul> * <li>Information about the Bitcoin network status</li> * </ul> * * @since 0.0.1 *   */ public enum BitcoinNetworkStatus { /** * No connection to the network */ NOT_CONNECTED, /** * In the process of making a connection (no peers) */ CONNECTING, /** * In the process of downloading the blockchain (not ready for a send) */ DOWNLOADING_BLOCKCHAIN, /** * Connected and synchronized (ready to send) */ SYNCHRONIZED, // End of enum ; }
16.054054
72
0.614478
2def60cbddbd20188d7a9c5ac9009f8e7b689384
2,552
package ru.otus.db.dao; import org.hibernate.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.otus.db.model.User; import ru.otus.db.sessionmanager.SessionManager; import ru.otus.db.sessionmanager.DatabaseSessionHibernate; import ru.otus.db.sessionmanager.SessionManagerHibernate; import java.util.*; public class UserDaoImpl implements UserDao { private static final Logger logger = LoggerFactory.getLogger(UserDaoImpl.class); private final SessionManagerHibernate sessionManager; public UserDaoImpl(SessionManagerHibernate sessionManager) { this.sessionManager = sessionManager; } @Override public List<User> findAll() { DatabaseSessionHibernate currentSession = sessionManager.getCurrentSession(); try { return currentSession .getHibernateSession() .createQuery("SELECT u FROM User u", User.class).getResultList(); } catch (Exception e) { logger.error(e.getMessage(), e); } return new ArrayList<>(); } @Override public Optional<User> findById(long id) { DatabaseSessionHibernate currentSession = sessionManager.getCurrentSession(); try { return Optional.ofNullable(currentSession.getHibernateSession().find(User.class, id)); } catch (Exception e) { logger.error(e.getMessage(), e); } return Optional.empty(); } @Override public long insert(User user) { DatabaseSessionHibernate currentSession = sessionManager.getCurrentSession(); try { Session hibernateSession = currentSession.getHibernateSession(); hibernateSession.persist(user); hibernateSession.flush(); return user.getId(); } catch (Exception e) { throw new DaoException(e); } } @Override public Optional<User> findByLogin(String login) { DatabaseSessionHibernate currentSession = sessionManager.getCurrentSession(); try { return Optional.ofNullable( (User) currentSession.getHibernateSession() .createQuery("FROM User u WHERE u.name=:userName") .setParameter("userName", login).uniqueResult()); } catch (Exception e) { logger.error(e.getMessage(), e); } return Optional.empty(); } @Override public SessionManager getSessionManager() { return sessionManager; } }
32.303797
98
0.641458
35d0e90d60c1891a0046eaa9b7507c7775434a8b
750
package com.baeldung.hexagonalarchitecture.infrastructutre.driveradapter; import com.baeldung.hexagonalarchitecture.application.boundary.driverports.ICommandOperator; import com.baeldung.hexagonalarchitecture.domain.command.RequestGreeting; /** * The driver adapter. It's on the left side of the hexagon. It sends * requests as commands to a driver port on the hexagon boundary. */ public class GreetingsMachine { private ICommandOperator driverPort; public GreetingsMachine(ICommandOperator driverPort) { this.driverPort = driverPort; } public void run() { driverPort.reactTo(new RequestGreeting("fr")); driverPort.reactTo(new RequestGreeting("en")); } }
35.714286
92
0.717333
1b4a5ac07e72ebd4ef6d70f5595733c380893c91
1,890
package io.oneko.configuration; import java.io.IOException; import java.util.concurrent.Executor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler; import org.springframework.web.reactive.config.ResourceHandlerRegistry; import org.springframework.web.reactive.config.WebFluxConfigurer; import org.springframework.web.reactive.resource.GzipResourceResolver; import org.springframework.web.reactive.resource.PathResourceResolver; import reactor.core.publisher.Mono; @Configuration public class AngularWebappConfiguration implements WebFluxConfigurer { @Bean public TaskScheduler taskScheduler() { return new ConcurrentTaskScheduler(); } @Bean public Executor taskExecutor() { return new SimpleAsyncTaskExecutor(); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**") .addResourceLocations("classpath:/public/") .resourceChain(true) .addResolver(new GzipResourceResolver()) .addResolver(new PathResourceResolver() { @Override protected Mono<Resource> getResource(String resourcePath, Resource location) { Resource requestedResource; try { requestedResource = location.createRelative(resourcePath); } catch (IOException e) { return Mono.just(new ClassPathResource("/public/index.html")); } return requestedResource.exists() && requestedResource.isReadable() ? Mono.just(requestedResource) : Mono.just(new ClassPathResource("/public/index.html")); } }); } }
34.363636
104
0.781481
905b043b852604fc8b44be6ade9e518787ac532b
717
package com.example.kkalanhw2.entity; import javax.persistence.*; import java.io.Serializable; import java.util.Date; @Entity @Table(name = "PRODUCT_COMMENT") public class ProductComment implements Serializable { @SequenceGenerator(name = "generator", sequenceName = "COMMENT_ID_SEQ") @Id @GeneratedValue(generator = "generator") @Column(name = "ID", nullable = false) private Long id; @Column(name = "COMMENT", length = 500) private String comment; @Column(name = "COMMANT_DATE") @Temporal(TemporalType.TIMESTAMP) private Date commantDate; @Column(name = "PRODUCT_ID") private Long productId; @Column(name = "CUSTOMER_ID") private Long customerId; }
21.727273
75
0.700139
a2faaaf4457c299dfe9d1992bc9eca991097cbef
323
package ro.ne8.blogsample.services; import ro.ne8.blogsample.entities.CommentEntity; import java.util.List; public interface CommentService { void save(CommentEntity commentEntity); void delete(CommentEntity commentEntity); void update(CommentEntity commentEntity); List<CommentEntity> findAll(); }
17.944444
48
0.770898
ca20bfa52afeeb81b3bc59f5dc0b14815f1e7179
1,259
package com.threeq.dubbo.tracing; import com.alibaba.dubbo.rpc.RpcContext; import org.springframework.cloud.sleuth.Span; import org.springframework.cloud.sleuth.SpanInjector; import java.util.Map; /** * @Date 2017/2/8 * @User three */ public class DubboSpanInjector implements SpanInjector<RpcContext> { @Override public void inject(Span span, RpcContext carrier) { Map<String, String> attachments = carrier.getAttachments(); if (span.getTraceId() != 0) { attachments.put(Span.TRACE_ID_NAME, Span.idToHex(span.getTraceId())); } if (span.getSpanId() != 0) { attachments.put(Span.SPAN_ID_NAME, Span.idToHex(span.getSpanId())); } attachments.put(Span.SAMPLED_NAME, span.isExportable() ? Span.SPAN_SAMPLED : Span.SPAN_NOT_SAMPLED); attachments.put(Span.SPAN_NAME_NAME, span.getName()); Long parentId = getParentId(span); if (parentId != null && parentId != 0) { attachments.put(Span.PARENT_ID_NAME, Span.idToHex(parentId)); } attachments.put(Span.PROCESS_ID_NAME, span.getProcessId()); } private Long getParentId(Span span) { return !span.getParents().isEmpty() ? span.getParents().get(0) : null; } }
32.282051
108
0.664813
23f49e1ad605596b04d37a03a75bf7505deda13c
585
/* {{IS_NOTE Purpose: Description: History: 2013/12/01 , Created by dennis }}IS_NOTE Copyright (C) 2013 Potix Corporation. All Rights Reserved. {{IS_RIGHT }}IS_RIGHT */ package org.zkoss.zss.model.sys.input; /** * Determine a cell's type and value by parsing editing text with predefined patterns. * The parsing process considers the locale for decimal separator, thousands separator, and date format. * @author dennis * @since 3.5.0 */ public interface InputEngine { public InputResult parseInput(String editText,String format, InputParseContext context); }
19.5
106
0.740171