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
5b059df8997ff0e2872a8b16b1d955f35703a422
796
package org.opentripplanner.middleware.controllers.api; import org.opentripplanner.middleware.models.Model; import org.opentripplanner.middleware.persistence.TypedPersistence; import spark.Request; /** * Provides a basic implementation of the {@link ApiController} abstract class. */ public class ApiControllerImpl<T extends Model> extends ApiController<T> { public ApiControllerImpl(String apiPrefix, TypedPersistence typedPersistence){ super(apiPrefix, typedPersistence); } @Override T preCreateHook(T entity, Request req) { return entity; } @Override T preUpdateHook(T entityToUpdate, T preExistingEntity, Request req) { return null; } @Override boolean preDeleteHook(T entity, Request req) { return true; } }
26.533333
82
0.727387
ef4681d57d47606f1977dec8af3f33270f762f58
5,711
/************************************************************************************************ * ____________ _ _ _____ _ _____ _ _ _______ __ _ _ _ * |___ / ____| \ | |/ ____| | | / ____| | | |_ _\ \ / / | | | | | * / /| |__ | \| | | __ _ ___| |__ | | __| | | | | | \ \ /\ / /_ _| | | ___| |_ * / / | __| | . ` | | / _` / __| '_ \| | |_ | | | | | | \ \/ \/ / _` | | |/ _ \ __| * / /__| |____| |\ | |___| (_| \__ \ | | | |__| | |__| |_| |_ \ /\ / (_| | | | __/ |_ * /_____|______|_| \_|\_____\__,_|___/_| |_|\_____|\____/|_____| \/ \/ \__,_|_|_|\___|\__| * * Copyright (c) 2016-2021 Zen Blockchain Foundation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. **********************************************************************************/ package com.vaklinov.zcashui.msg; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import com.vaklinov.zcashui.Log; import com.vaklinov.zcashui.StatusUpdateErrorReporter; /** * Dialog used to edit one's own identity */ public class OwnIdentityEditDialog extends IdentityInfoDialog { private MessagingStorage storage; private StatusUpdateErrorReporter errorReporter; public OwnIdentityEditDialog(JFrame parent, MessagingIdentity identity, MessagingStorage storage, StatusUpdateErrorReporter errorReporter, boolean identityIsBeingCreated) { super(parent, identity); this.storage = storage; this.errorReporter = errorReporter; this.setTitle("Own messaging identity - edit..."); this.infoLabel.setText( "<html><span style=\"font-size:0.97em;\">" + "The fields below make up your messaging identity. This information is meant to be " + "shared with other users.<br/> The only mandatory field is the \"Nick name\"." + "</span>"); nicknameTextField.setEditable(true); firstnameTextField.setEditable(true); middlenameTextField.setEditable(true); surnameTextField.setEditable(true); emailTextField.setEditable(true); streetaddressTextField.setEditable(true); facebookTextField.setEditable(true); twitterTextField.setEditable(true); // Build the save and Cancel buttons if (identityIsBeingCreated) { // If the identity is being created only save is allowed this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); this.buttonPanel.removeAll(); } JButton saveButon = new JButton("Save & close"); buttonPanel.add(saveButon); saveButon.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { // Check for validity and save the data - T/Z addresses are not changed! String nick = OwnIdentityEditDialog.this.nicknameTextField.getText(); if ((nick == null) || nick.trim().length() <= 0) { JOptionPane.showMessageDialog( OwnIdentityEditDialog.this.parentFrame, "The nick name field is empty. It is mandatory - please fill it.", "Mandatory data missing", JOptionPane.ERROR_MESSAGE); return; } // TODO: check validity of fields to avoid entering rubbish (e.g. invalid e-mail) // Save all identity fields from the text fields MessagingIdentity id = OwnIdentityEditDialog.this.identity; id.setNickname(OwnIdentityEditDialog.this.nicknameTextField.getText()); id.setFirstname(OwnIdentityEditDialog.this.firstnameTextField.getText()); id.setMiddlename(OwnIdentityEditDialog.this.middlenameTextField.getText()); id.setSurname(OwnIdentityEditDialog.this.surnameTextField.getText()); id.setEmail(OwnIdentityEditDialog.this.emailTextField.getText()); id.setStreetaddress(OwnIdentityEditDialog.this.streetaddressTextField.getText()); id.setFacebook(OwnIdentityEditDialog.this.facebookTextField.getText()); id.setTwitter(OwnIdentityEditDialog.this.twitterTextField.getText()); // Save the identity OwnIdentityEditDialog.this.storage.updateOwnIdentity(id); OwnIdentityEditDialog.this.setVisible(false); OwnIdentityEditDialog.this.dispose(); } catch (Exception ex) { Log.error("Unexpected error in editing own messaging identity!", ex); OwnIdentityEditDialog.this.errorReporter.reportError(ex, false); } } }); this.pack(); this.setLocation(100, 100); this.setLocationRelativeTo(parent); } } // End public class OwnIdentityEditDialog
41.686131
122
0.655052
45f494d92a3ed868848b53a4351e947c890866b2
997
package com.mmall.vo; import java.math.BigDecimal; import java.util.List; public class CartVo { private List<CartProductVo> cartProductVoList; private BigDecimal cartTotalPrice; private boolean allChecked; private String imgHost; public List<CartProductVo> getCartProductVoList() { return cartProductVoList; } public void setCartProductVoList(List<CartProductVo> cartProductVoList) { this.cartProductVoList = cartProductVoList; } public BigDecimal getCartTotalPrice() { return cartTotalPrice; } public void setCartTotalPrice(BigDecimal cartTotalPrice) { this.cartTotalPrice = cartTotalPrice; } public boolean isAllChecked() { return allChecked; } public void setAllChecked(boolean allChecked) { this.allChecked = allChecked; } public String getImgHost() { return imgHost; } public void setImgHost(String imgHost) { this.imgHost = imgHost; } }
22.659091
77
0.689067
1a0cbd1b5ff76aae25c34e11bc389ee04d53baec
16,386
package uk.co.nevarneyok.ux.fragments; import android.os.Bundle; import android.os.SystemClock; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import java.util.List; import uk.co.nevarneyok.CONST; import uk.co.nevarneyok.MyApplication; import uk.co.nevarneyok.R; import uk.co.nevarneyok.SettingsMy; import uk.co.nevarneyok.api.EndPoints; import uk.co.nevarneyok.api.GsonRequest; import uk.co.nevarneyok.entities.drawerMenu.DrawerItemCategory; import uk.co.nevarneyok.entities.drawerMenu.DrawerItemPage; import uk.co.nevarneyok.entities.drawerMenu.DrawerResponse; import uk.co.nevarneyok.interfaces.DrawerRecyclerInterface; import uk.co.nevarneyok.interfaces.DrawerSubmenuRecyclerInterface; import uk.co.nevarneyok.utils.MsgUtils; import uk.co.nevarneyok.ux.adapters.DrawerRecyclerAdapter; import uk.co.nevarneyok.ux.adapters.DrawerSubmenuRecyclerAdapter; import timber.log.Timber; /** * Fragment handles the drawer menu. */ public class DrawerFragment extends Fragment { private static final int BANNERS_ID = -123; public static final String NULL_DRAWER_LISTENER_WTF = "Null drawer listener. WTF."; private ProgressBar drawerProgress; /** * Button to reload drawer menu content (used when content failed to load). */ private Button drawerRetryBtn; /** * Indicates that menu is currently loading. */ private boolean drawerLoading = false; /** * Listener indicating events that occurred on the menu. */ private FragmentDrawerListener drawerListener; private ActionBarDrawerToggle mDrawerToggle; // Drawer top menu fields. private DrawerLayout mDrawerLayout; private RecyclerView drawerRecycler; private DrawerRecyclerAdapter drawerRecyclerAdapter; // Drawer sub menu fields private LinearLayout drawerSubmenuLayout; private TextView drawerSubmenuTitle; private DrawerSubmenuRecyclerAdapter drawerSubmenuRecyclerAdapter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Timber.d("%s - onCreateView", this.getClass().getSimpleName()); // Inflating view layout View layout = inflater.inflate(R.layout.fragment_drawer, container, false); drawerSubmenuLayout = (LinearLayout) layout.findViewById(R.id.drawer_submenu_layout); drawerSubmenuTitle = (TextView) layout.findViewById(R.id.drawer_submenu_title); drawerProgress = (ProgressBar) layout.findViewById(R.id.drawer_progress); drawerRetryBtn = (Button) layout.findViewById(R.id.drawer_retry_btn); drawerRetryBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!drawerLoading) getDrawerItems(); } }); prepareDrawerRecycler(layout); Button backBtn = (Button) layout.findViewById(R.id.drawer_submenu_back_btn); backBtn.setOnClickListener(new View.OnClickListener() { private long mLastClickTime = 0; @Override public void onClick(View v) { if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) return; mLastClickTime = SystemClock.elapsedRealtime(); animateSubListHide(); } }); getDrawerItems(); return layout; } /** * Prepare drawer menu content views, adapters and listeners. * * @param view fragment base view. */ private void prepareDrawerRecycler(View view) { drawerRecycler = (RecyclerView) view.findViewById(R.id.drawer_recycler); drawerRecyclerAdapter = new DrawerRecyclerAdapter(getContext(), new DrawerRecyclerInterface() { @Override public void onCategorySelected(View v, DrawerItemCategory drawerItemCategory) { if (drawerItemCategory.getChildren() == null || drawerItemCategory.getChildren().isEmpty()) { if (drawerListener != null) { if (drawerItemCategory.getId() == BANNERS_ID) drawerListener.onDrawerBannersSelected(); else drawerListener.onDrawerItemCategorySelected(drawerItemCategory); closeDrawerMenu(); } else { Timber.e(new RuntimeException(), NULL_DRAWER_LISTENER_WTF); } } else animateSubListShow(drawerItemCategory); } @Override public void onPageSelected(View v, DrawerItemPage drawerItemPage) { if (drawerListener != null) { drawerListener.onDrawerItemPageSelected(drawerItemPage); closeDrawerMenu(); } else { Timber.e(new RuntimeException(), NULL_DRAWER_LISTENER_WTF); } } @Override public void onHeaderSelected() { if (drawerListener != null) { drawerListener.onAccountSelected(); closeDrawerMenu(); } else { Timber.e(new RuntimeException(), NULL_DRAWER_LISTENER_WTF); } } }); drawerRecycler.setLayoutManager(new LinearLayoutManager(getContext())); drawerRecycler.setHasFixedSize(true); drawerRecycler.setAdapter(drawerRecyclerAdapter); RecyclerView drawerSubmenuRecycler = (RecyclerView) view.findViewById(R.id.drawer_submenu_recycler); drawerSubmenuRecyclerAdapter = new DrawerSubmenuRecyclerAdapter(new DrawerSubmenuRecyclerInterface() { @Override public void onSubCategorySelected(View v, DrawerItemCategory drawerItemCategory) { if (drawerListener != null) { drawerListener.onDrawerItemCategorySelected(drawerItemCategory); closeDrawerMenu(); } } }); drawerSubmenuRecycler.setLayoutManager(new LinearLayoutManager(getContext())); drawerSubmenuRecycler.setItemAnimator(new DefaultItemAnimator()); drawerSubmenuRecycler.setHasFixedSize(true); drawerSubmenuRecycler.setAdapter(drawerSubmenuRecyclerAdapter); } /** * Base method for layout preparation. Also set a listener that will respond to events that occurred on the menu. * * @param drawerLayout drawer layout, which will be managed. * @param toolbar toolbar bundled with a side menu. * @param eventsListener corresponding listener class. */ public void setUp(DrawerLayout drawerLayout, final Toolbar toolbar, FragmentDrawerListener eventsListener) { mDrawerLayout = drawerLayout; this.drawerListener = eventsListener; mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.content_description_open_navigation_drawer, R.string.content_description_close_navigation_drawer) { @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); getActivity().invalidateOptionsMenu(); } @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); getActivity().invalidateOptionsMenu(); } @Override public void onDrawerSlide(View drawerView, float slideOffset) { super.onDrawerSlide(drawerView, slideOffset); // toolbar.setAlpha(1 - slideOffset / 2); } }; toolbar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { toggleDrawerMenu(); } }); mDrawerLayout.addDrawerListener(mDrawerToggle); mDrawerLayout.post(new Runnable() { @Override public void run() { mDrawerToggle.syncState(); } }); } /** * When the drawer menu is open, close it. Otherwise open it. */ public void toggleDrawerMenu() { if (mDrawerLayout != null) { if (mDrawerLayout.isDrawerVisible(GravityCompat.START)) { mDrawerLayout.closeDrawer(GravityCompat.START); } else { mDrawerLayout.openDrawer(GravityCompat.START); } } } /** * When the drawer menu is open, close it. */ public void closeDrawerMenu() { if (mDrawerLayout != null) { mDrawerLayout.closeDrawer(GravityCompat.START); } } /** * Check if drawer is open. If so close it. * * @return false if drawer was already closed */ public boolean onBackHide() { if (mDrawerLayout != null && mDrawerLayout.isDrawerVisible(GravityCompat.START)) { if (drawerSubmenuLayout.getVisibility() == View.VISIBLE) animateSubListHide(); else mDrawerLayout.closeDrawer(GravityCompat.START); return true; } return false; } /** * Method invalidates a drawer menu header. It is used primarily on a login state change. */ public void invalidateHeader() { if (drawerRecyclerAdapter != null) { Timber.d("Invalidate drawer menu header."); drawerRecyclerAdapter.notifyItemChanged(0); } } private void getDrawerItems() { drawerLoading = true; drawerProgress.setVisibility(View.VISIBLE); drawerRetryBtn.setVisibility(View.GONE); String url = String.format(EndPoints.NAVIGATION_DRAWER, SettingsMy.getActualNonNullShop(getActivity()).getId()); GsonRequest<DrawerResponse> getDrawerMenu = new GsonRequest<>(Request.Method.GET, url, null, DrawerResponse.class, new Response.Listener<DrawerResponse>() { @Override public void onResponse(@NonNull DrawerResponse drawerResponse) { drawerRecyclerAdapter.addDrawerItem(new DrawerItemCategory(BANNERS_ID, BANNERS_ID, getString(R.string.Just_arrived))); drawerRecyclerAdapter.addDrawerItemList(drawerResponse.getNavigation()); drawerRecyclerAdapter.addPageItemList(drawerResponse.getPages()); drawerRecyclerAdapter.notifyDataSetChanged(); if (drawerListener != null) drawerListener.prepareSearchSuggestions(drawerResponse.getNavigation()); drawerLoading = false; if (drawerRecycler != null) drawerRecycler.setVisibility(View.VISIBLE); if (drawerProgress != null) drawerProgress.setVisibility(View.GONE); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { MsgUtils.logAndShowErrorMessage(getActivity(), error); drawerLoading = false; if (drawerProgress != null) drawerProgress.setVisibility(View.GONE); if (drawerRetryBtn != null) drawerRetryBtn.setVisibility(View.VISIBLE); } }); getDrawerMenu.setRetryPolicy(MyApplication.getDefaultRetryPolice()); getDrawerMenu.setShouldCache(false); MyApplication.getInstance().addToRequestQueue(getDrawerMenu, CONST.DRAWER_REQUESTS_TAG); } private void animateSubListHide() { Animation slideAwayDisappear = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_away_disappear); final Animation slideAwayAppear = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_away_appear); slideAwayDisappear.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { drawerRecycler.setVisibility(View.VISIBLE); drawerRecycler.startAnimation(slideAwayAppear); } @Override public void onAnimationEnd(Animation animation) { drawerSubmenuLayout.setVisibility(View.GONE); } @Override public void onAnimationRepeat(Animation animation) { } }); drawerSubmenuLayout.startAnimation(slideAwayDisappear); } private void animateSubListShow(DrawerItemCategory drawerItemCategory) { if (drawerItemCategory != null) { drawerSubmenuTitle.setText(drawerItemCategory.getName()); drawerSubmenuRecyclerAdapter.changeDrawerItems(drawerItemCategory.getChildren()); Animation slideInDisappear = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_in_disappear); final Animation slideInAppear = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_in_appear); slideInDisappear.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { drawerSubmenuLayout.setVisibility(View.VISIBLE); drawerSubmenuLayout.startAnimation(slideInAppear); } @Override public void onAnimationEnd(Animation animation) { drawerRecycler.setVisibility(View.GONE); } @Override public void onAnimationRepeat(Animation animation) { } }); drawerRecycler.startAnimation(slideInDisappear); } else { Timber.e("Populate submenu with null category drawer item."); } } @Override public void onPause() { // Cancellation during onPause is needed because of app restarting during changing shop. MyApplication.getInstance().cancelPendingRequests(CONST.DRAWER_REQUESTS_TAG); if (drawerLoading) { if (drawerProgress != null) drawerProgress.setVisibility(View.GONE); if (drawerRetryBtn != null) drawerRetryBtn.setVisibility(View.VISIBLE); drawerLoading = false; } super.onPause(); } @Override public void onDestroy() { mDrawerLayout.removeDrawerListener(mDrawerToggle); super.onDestroy(); } /** * Interface defining events initiated by {@link DrawerFragment}. */ public interface FragmentDrawerListener { /** * Launch {@link BannersFragment}. If fragment is already launched nothing happen. */ void onDrawerBannersSelected(); /** * Launch {@link CategoryFragment}. * * @param drawerItemCategory object specifying selected item in the drawer. */ void onDrawerItemCategorySelected(DrawerItemCategory drawerItemCategory); /** * Launch {@link PageFragment}, with downloadable content. * * @param drawerItemPage id of page for download and display. (Define in OpenShop server administration) */ void onDrawerItemPageSelected(DrawerItemPage drawerItemPage); /** * Launch {@link AccountFragment}. */ void onAccountSelected(); /** * Prepare all search strings for search whisperer. * * @param navigation items for suggestions generating. */ void prepareSearchSuggestions(List<DrawerItemCategory> navigation); } }
38.921615
196
0.648419
d952905b676a25eca9e34b4e27963818621e7e0d
3,965
package gov.va.escreening.templateprocessor; import java.util.EnumSet; import gov.va.escreening.constants.TemplateConstants.TemplateType; import gov.va.escreening.constants.TemplateConstants.ViewType; import gov.va.escreening.entity.Battery; import gov.va.escreening.entity.VeteranAssessment; import gov.va.escreening.exception.EntityNotFoundException; import gov.va.escreening.exception.IllegalSystemStateException; import gov.va.escreening.exception.TemplateProcessorException; public interface TemplateProcessorService { /** * Generates the CPRS Note for the given assessment * @param veteranAssessmentId * @param viewType from {@link TemplateTagProcessor} indicates how the the note should be rendered * @param optionalTemplates a set of optional {@link TemplateType} which will be included. Header and footer will always be included. * Supported template types are: {@link TemplateType.VISTA_QA} and {@link TemplateType.ASSESS_SCORE_TABLE} * @return the rendered CPRS Note * @throws IllegalSystemStateException if the system is missing a required template or template property. These * errors can be fixed by updating the database. * @throws TemplateProcessorException if a bug was found in code (including template code), or a needed resource cannot be found. */ public String generateCPRSNote(int veteranAssessmentId, ViewType viewType, EnumSet<TemplateType> optionalTemplates) throws IllegalSystemStateException, TemplateProcessorException; /** * Convenience method for when no optional templates should be used. * @param veteranAssessmentId * @param viewType from {@link TemplateTagProcessor} indicates how the the note should be rendered * @return the rendered CPRS Note * @throws IllegalSystemStateException if the system is missing a required template or template property. These * errors can be fixed by updating the database. * @throws TemplateProcessorException if a bug was found in code (including template code), or a needed resource cannot be found. */ public String generateCPRSNote(int veteranAssessmentId, ViewType viewType) throws IllegalSystemStateException, TemplateProcessorException; /** * Renders the given assessment's veteran summary printout (this is always in HTML) * @param veteranAssessmentId * @return HTML of the veteran summary printout */ public String generateVeteranPrintout(int veteranAssessmentId) throws IllegalSystemStateException, TemplateProcessorException; /** * Renders a template of the given type using responses in the given assessment * @param surveyId the id of the survey to render a template for * @param type TemplateType to render * @param veteranAssessment the assessment we are rendering a battery for * @return rendered text * @throws IllegalSystemStateException * @throw IllegalStateException * @throw EntityNotFoundException if a template of the given type does not exist for the given survey */ public String renderSurveyTemplate(int surveyId, TemplateType type, VeteranAssessment veteranAssessment, ViewType viewType) throws IllegalSystemStateException, EntityNotFoundException; /** * Renders a template of the given type using responses in the given assessment * @param batteryId the id of the battery to render a template for * @param type TemplateType to render * @param veteranAssessment the assessment we are rendering a battery for * @param viewType - the view type to render * @return rendered text * @throws IllegalSystemStateException * @throw IllegalStateException * @throw EntityNotFoundException if a template of the given type does not exist for the given battery */ public String renderBatteryTemplate(Battery battery, TemplateType type, VeteranAssessment veteranAssessment, ViewType viewType) throws IllegalSystemStateException, EntityNotFoundException; }
53.581081
181
0.778562
240a4e2d1a09d11ae4f44ba0ac40901a6b8b68ed
2,415
package de.polocloud.api.bridge; import de.polocloud.api.common.PoloType; import java.util.UUID; public interface PoloPluginBridge { /** * Checks if a player with a given {@link UUID} has a permission * * @param uniqueId the uuid of the player * @param permission the permission * @return if it has permission */ boolean hasPermission(UUID uniqueId, String permission); /** * Gets the ping of a player with a given {@link UUID} * * @param uniqueId the uuid * @return ping as long */ long getPing(UUID uniqueId); /** * Checks if a player with a given {@link UUID} is online * * @param uniqueId the uuid of the player * @return if online */ boolean isPlayerOnline(UUID uniqueId); /** * Sends a message to a player with a given {@link UUID} * * @param uniqueId the uuid * @param message the message */ void sendMessage(UUID uniqueId, String message); /** * Sets the tablist for a player with a given {@link UUID} * * @param uniqueId the uuid * @param header the header * @param footer the footer */ void sendTabList(UUID uniqueId, String header, String footer); /** * Broadcasts a message * * @param message the message */ void broadcast(String message); /** * Kicks a player from this bridge instance * For a given reason as {@link String} * * @param uniqueId the uuid of the player * @param reason the reason to display */ void kickPlayer(UUID uniqueId, String reason); /** * Sends a title to a player with a given {@link UUID} * * @param uniqueId the uuid * @param title the title * @param subTitle the subtitle */ void sendTitle(UUID uniqueId, String title, String subTitle); /** * Executes a console command * * @param command the command-line to execute */ void executeCommand(String command); /** * The environment of this bridge instance */ PoloType getEnvironment(); /** * Displays a message above the hotbar of a player * with a given {@link UUID} * * @param uniqueId the uuid * @param message the message */ void sendActionbar(UUID uniqueId, String message); /** * Shuts down this bridge */ void shutdown(); }
23.446602
68
0.608696
594a4c90cf44adee9536b37ebcc6f849de981ab8
2,531
// Copyright © Matt Jones and Contributors. Licensed under the MIT License (MIT). See LICENCE.md in the repository root for more information. package com.github.novelrt.fumocement; /** * Represents a struct from the native land. * <p> * This base class is mainly used in code generation for mapping C structs * to their Java equivalent. * <p> * In order to make interop between Java and C easier, * the {@link NativeObject#getHandle()} method becomes public. This allows for directly * passing pointers to native methods. * <p> * <b>WARNING:</b> This class (and any of its inheritors) must <b>NOT</b> be used as * a public API surface. It must be only used internally as a helper for accessing * C structs. */ public abstract class NativeStruct extends NativeObject { /** * Constructs a new {@link NativeStruct} with the given handle, the native resource owning state, and * a {@link HandleDeleter} deleting the native handle. It can be {@code null} if the * {@code owned} parameter is {@code false}. This object's native resources will be garbage collected. * * @param handle the native handle * @param owned whether or not this object owns native resources * @param handleDeleter the {@link HandleDeleter} to use in order to delete native resources, * which can be {@code null} when {@code owned} is false */ public NativeStruct(@Pointer long handle, boolean owned, HandleDeleter handleDeleter) { super(handle, owned, handleDeleter); } /** * Constructs a new {@link NativeStruct} with the given handle, the native resource owning state, * the {@link DisposalMethod} and a {@link HandleDeleter} deleting the native handle. * It can be {@code null} if the {@code owned} parameter is {@code false}. * * @param handle the native handle * @param owned whether or not this object owns native resources * @param disposalMethod the disposal method to use * @param handleDeleter the {@link HandleDeleter} to use in order to delete native resources, * which can be {@code null} when {@code owned} is false */ public NativeStruct(@Pointer long handle, boolean owned, DisposalMethod disposalMethod, HandleDeleter handleDeleter) { super(handle, owned, disposalMethod, handleDeleter); } /** * {@inheritDoc} */ @Override public @Pointer long getHandle() { return super.getHandle(); } }
44.403509
141
0.676412
5e7df45c58a3ea36d45388c8db59987a32cd7f7e
1,781
// PaintDemo.java - Simple painting program. // Illustrates use of mouse and BufferedImage. // Fred Swartz 2002-12-02 // Possible Enhancements: // * Clear drawing area // * Other shapes (line, outline shapes, text, ...) // * Color selection. // * An eraser. // * Create a real toobar. // * Save/Load import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import java.awt.image.BufferedImage; //////////////////////////////////////////////////////////// PaintWindow class PaintWindow extends JFrame { PaintPanel canvas = new PaintPanel(); //====================================================== constructor public PaintWindow() { //--- create the buttons JButton circleButton = new JButton("Circle"); circleButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { canvas.setShape(PaintPanel.CIRCLE); }}); JButton rectangleButton = new JButton("Rectangle"); rectangleButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { canvas.setShape(PaintPanel.RECTANGLE); }}); //--- layout the buttons JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(2, 1)); buttonPanel.add(circleButton); buttonPanel.add(rectangleButton); //--- layout the window Container content = this.getContentPane(); content.setLayout(new BorderLayout()); content.add(buttonPanel, BorderLayout.WEST); content.add(canvas , BorderLayout.CENTER); this.setTitle("Paint Demo"); this.pack(); }//end constructor }//endclass PaintWindow
34.921569
72
0.600225
c70e7080c93e2d93c911ef9b36c8c6f95fe9c7a0
4,177
package net.minecraft.world.level.block; import com.google.common.collect.Maps; import java.util.Iterator; import java.util.Map; import java.util.function.Supplier; import net.minecraft.core.BlockPosition; import net.minecraft.server.level.WorldServer; import net.minecraft.world.entity.EntityTypes; import net.minecraft.world.entity.monster.EntitySilverfish; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.enchantment.EnchantmentManager; import net.minecraft.world.item.enchantment.Enchantments; import net.minecraft.world.level.Explosion; import net.minecraft.world.level.GameRules; import net.minecraft.world.level.World; import net.minecraft.world.level.block.state.BlockBase; import net.minecraft.world.level.block.state.IBlockData; import net.minecraft.world.level.block.state.properties.IBlockState; public class BlockMonsterEggs extends Block { private final Block hostBlock; private static final Map<Block, Block> BLOCK_BY_HOST_BLOCK = Maps.newIdentityHashMap(); private static final Map<IBlockData, IBlockData> HOST_TO_INFESTED_STATES = Maps.newIdentityHashMap(); private static final Map<IBlockData, IBlockData> INFESTED_TO_HOST_STATES = Maps.newIdentityHashMap(); public BlockMonsterEggs(Block block, BlockBase.Info blockbase_info) { super(blockbase_info.destroyTime(block.defaultDestroyTime() / 2.0F).explosionResistance(0.75F)); this.hostBlock = block; BlockMonsterEggs.BLOCK_BY_HOST_BLOCK.put(block, this); } public Block getHostBlock() { return this.hostBlock; } public static boolean isCompatibleHostBlock(IBlockData iblockdata) { return BlockMonsterEggs.BLOCK_BY_HOST_BLOCK.containsKey(iblockdata.getBlock()); } private void spawnInfestation(WorldServer worldserver, BlockPosition blockposition) { EntitySilverfish entitysilverfish = (EntitySilverfish) EntityTypes.SILVERFISH.create(worldserver); entitysilverfish.moveTo((double) blockposition.getX() + 0.5D, (double) blockposition.getY(), (double) blockposition.getZ() + 0.5D, 0.0F, 0.0F); worldserver.addFreshEntity(entitysilverfish); entitysilverfish.spawnAnim(); } @Override public void spawnAfterBreak(IBlockData iblockdata, WorldServer worldserver, BlockPosition blockposition, ItemStack itemstack) { super.spawnAfterBreak(iblockdata, worldserver, blockposition, itemstack); if (worldserver.getGameRules().getBoolean(GameRules.RULE_DOBLOCKDROPS) && EnchantmentManager.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, itemstack) == 0) { this.spawnInfestation(worldserver, blockposition); } } @Override public void wasExploded(World world, BlockPosition blockposition, Explosion explosion) { if (world instanceof WorldServer) { this.spawnInfestation((WorldServer) world, blockposition); } } public static IBlockData infestedStateByHost(IBlockData iblockdata) { return getNewStateWithProperties(BlockMonsterEggs.HOST_TO_INFESTED_STATES, iblockdata, () -> { return ((Block) BlockMonsterEggs.BLOCK_BY_HOST_BLOCK.get(iblockdata.getBlock())).defaultBlockState(); }); } public IBlockData hostStateByInfested(IBlockData iblockdata) { return getNewStateWithProperties(BlockMonsterEggs.INFESTED_TO_HOST_STATES, iblockdata, () -> { return this.getHostBlock().defaultBlockState(); }); } private static IBlockData getNewStateWithProperties(Map<IBlockData, IBlockData> map, IBlockData iblockdata, Supplier<IBlockData> supplier) { return (IBlockData) map.computeIfAbsent(iblockdata, (iblockdata1) -> { IBlockData iblockdata2 = (IBlockData) supplier.get(); IBlockState iblockstate; for (Iterator iterator = iblockdata1.getProperties().iterator(); iterator.hasNext(); iblockdata2 = iblockdata2.hasProperty(iblockstate) ? (IBlockData) iblockdata2.setValue(iblockstate, iblockdata1.getValue(iblockstate)) : iblockdata2) { iblockstate = (IBlockState) iterator.next(); } return iblockdata2; }); } }
44.913978
248
0.746708
140131f0cf3c65380ab9b3e1cb0c8f1d85c70e4c
5,900
/* * Copyright (c) 2005 Brian Wellington (bwelling@xbill.org) * * Copied from the DnsJava project * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.milton.dns.record; import io.milton.dns.Name; import io.milton.dns.utils.base64; import java.io.*; import java.util.*; import io.milton.dns.utils.*; /** * Transaction Key - used to compute and/or securely transport a shared * secret to be used with TSIG. * @see TSIG * * @author Brian Wellington */ public class TKEYRecord extends Record { private static final long serialVersionUID = 8828458121926391756L; private Name alg; private Date timeInception; private Date timeExpire; private int mode, error; private byte [] key; private byte [] other; /** The key is assigned by the server (unimplemented) */ public static final int SERVERASSIGNED = 1; /** The key is computed using a Diffie-Hellman key exchange */ public static final int DIFFIEHELLMAN = 2; /** The key is computed using GSS_API (unimplemented) */ public static final int GSSAPI = 3; /** The key is assigned by the resolver (unimplemented) */ public static final int RESOLVERASSIGNED = 4; /** The key should be deleted */ public static final int DELETE = 5; TKEYRecord() {} Record getObject() { return new TKEYRecord(); } /** * Creates a TKEY Record from the given data. * @param alg The shared key's algorithm * @param timeInception The beginning of the validity period of the shared * secret or keying material * @param timeExpire The end of the validity period of the shared * secret or keying material * @param mode The mode of key agreement * @param error The extended error field. Should be 0 in queries * @param key The shared secret * @param other The other data field. Currently unused * responses. */ public TKEYRecord(Name name, int dclass, long ttl, Name alg, Date timeInception, Date timeExpire, int mode, int error, byte [] key, byte other[]) { super(name, Type.TKEY, dclass, ttl); this.alg = checkName("alg", alg); this.timeInception = timeInception; this.timeExpire = timeExpire; this.mode = checkU16("mode", mode); this.error = checkU16("error", error); this.key = key; this.other = other; } void rrFromWire(DNSInput in) throws IOException { alg = new Name(in); timeInception = new Date(1000 * in.readU32()); timeExpire = new Date(1000 * in.readU32()); mode = in.readU16(); error = in.readU16(); int keylen = in.readU16(); if (keylen > 0) key = in.readByteArray(keylen); else key = null; int otherlen = in.readU16(); if (otherlen > 0) other = in.readByteArray(otherlen); else other = null; } void rdataFromString(Tokenizer st, Name origin) throws IOException { throw st.exception("no text format defined for TKEY"); } protected String modeString() { switch (mode) { case SERVERASSIGNED: return "SERVERASSIGNED"; case DIFFIEHELLMAN: return "DIFFIEHELLMAN"; case GSSAPI: return "GSSAPI"; case RESOLVERASSIGNED: return "RESOLVERASSIGNED"; case DELETE: return "DELETE"; default: return Integer.toString(mode); } } /** Converts rdata to a String */ String rrToString() { StringBuffer sb = new StringBuffer(); sb.append(alg); sb.append(" "); if (Options.check("multiline")) sb.append("(\n\t"); sb.append(FormattedTime.format(timeInception)); sb.append(" "); sb.append(FormattedTime.format(timeExpire)); sb.append(" "); sb.append(modeString()); sb.append(" "); sb.append(Rcode.TSIGstring(error)); if (Options.check("multiline")) { sb.append("\n"); if (key != null) { sb.append(base64.formatString(key, 64, "\t", false)); sb.append("\n"); } if (other != null) sb.append(base64.formatString(other, 64, "\t", false)); sb.append(" )"); } else { sb.append(" "); if (key != null) { sb.append(base64.toString(key)); sb.append(" "); } if (other != null) sb.append(base64.toString(other)); } return sb.toString(); } /** Returns the shared key's algorithm */ public Name getAlgorithm() { return alg; } /** * Returns the beginning of the validity period of the shared secret or * keying material */ public Date getTimeInception() { return timeInception; } /** * Returns the end of the validity period of the shared secret or * keying material */ public Date getTimeExpire() { return timeExpire; } /** Returns the key agreement mode */ public int getMode() { return mode; } /** Returns the extended error */ public int getError() { return error; } /** Returns the shared secret or keying material */ public byte [] getKey() { return key; } /** Returns the other data */ public byte [] getOther() { return other; } void rrToWire(DNSOutput out, Compression c, boolean canonical) { alg.toWire(out, null, canonical); out.writeU32(timeInception.getTime() / 1000); out.writeU32(timeExpire.getTime() / 1000); out.writeU16(mode); out.writeU16(error); if (key != null) { out.writeU16(key.length); out.writeByteArray(key); } else out.writeU16(0); if (other != null) { out.writeU16(other.length); out.writeByteArray(other); } else out.writeU16(0); } }
25.764192
756
0.672881
32af106076b73267a16fe9744cfcdb4f8456574c
2,436
package eutro.jsonflattener; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.util.Map; /** * A class that provides methods for expanding Gson Json Objects. */ public class JsonExpander { /** * Expand a Json Object, the opposite of flattening it. * * @param object The object to expand. * @return A new, expanded object. * @see JsonFlattener#flatten(JsonObject) */ public static JsonObject expand(JsonObject object) { JsonObject expanded = new JsonObject(); for (Map.Entry<String, JsonElement> entry : object.entrySet()) { JsonObject mapObj = expanded; String key = entry.getKey(); if (key.indexOf('.') != -1) { String[] path = entry.getKey().split("\\."); for (int i = 0; i < path.length - 1; i++) { mapObj = getObj(mapObj, path[i]); } key = path[path.length - 1]; } JsonElement value = entry.getValue(); JsonElement oldVal = mapObj.get(key); if (oldVal != null) { JsonArray array = new JsonArray(); array.add(oldVal); array.add(value); value = array; } mapObj.add(key, value); } return expanded; } private static JsonObject getObj(JsonObject object, String key) { JsonObject mapObj; JsonElement mappedVal = object.get(key); if (mappedVal == null) { JsonElement value = mapObj = new JsonObject(); object.add(key, value); } else if (mappedVal.isJsonObject()) { mapObj = mappedVal.getAsJsonObject(); } else if (mappedVal.isJsonArray()) { JsonArray mappedArr = mappedVal.getAsJsonArray(); JsonElement last; if (mappedArr.size() > 0 && (last = mappedArr.get(mappedArr.size() - 1)) .isJsonObject()) { mapObj = last.getAsJsonObject(); } else { mappedArr.add(mapObj = new JsonObject()); } } else { JsonArray newVal = new JsonArray(); object.add(key, newVal); newVal.add(mappedVal); newVal.add(mapObj = new JsonObject()); } return mapObj; } }
33.833333
72
0.531609
d7f8c9ff19025ed0306140761a702b1c022b188d
2,675
/* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.gradle.api.internal.tasks.testing.results; import org.gradle.api.tasks.testing.TestResult; import java.io.Serializable; import java.util.List; public class DefaultTestResult implements TestResult, Serializable { private final List<Throwable> failures; private final ResultType resultType; private final long startTime; private final long endTime; private final long testCount; private final long successfulCount; private final long failedCount; public DefaultTestResult(TestState state) { this(state.resultType, state.getStartTime(), state.getEndTime(), state.testCount, state.successfulCount, state.failedCount, state.failures); } public DefaultTestResult(ResultType resultType, long startTime, long endTime, long testCount, long successfulCount, long failedCount, List<Throwable> failures) { this.resultType = resultType; this.startTime = startTime; this.endTime = endTime; this.testCount = testCount; this.successfulCount = successfulCount; this.failedCount = failedCount; this.failures = failures; } @Override public ResultType getResultType() { return resultType; } @Override public Throwable getException() { return failures.isEmpty() ? null : failures.get(0); } @Override public List<Throwable> getExceptions() { return failures; } @Override public long getStartTime() { return startTime; } @Override public long getEndTime() { return endTime; } @Override public long getTestCount() { return testCount; } @Override public long getSuccessfulTestCount() { return successfulCount; } @Override public long getSkippedTestCount() { return testCount - successfulCount - failedCount; } @Override public long getFailedTestCount() { return failedCount; } @Override public String toString() { return resultType.toString(); } }
27.57732
165
0.68972
b449f9e32edfe192d43281f3f353c51b0f80f53e
2,290
package im.cave.ms.provider.info; import im.cave.ms.enums.InventoryType; import im.cave.ms.enums.ScrollStat; import im.cave.ms.enums.SpecStat; import lombok.Data; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * @author fair * @version V1.0 * @Package im.cave.ms.client.items * @date 11/22 1:35 */ @Data public class ItemInfo { private int itemId; private InventoryType invType; private boolean cash; private int price; private int slotMax = 200; private boolean tradeBlock; private boolean notSale; private String path = ""; private boolean noCursed; private Map<ScrollStat, Integer> scrollStats = new HashMap<>(); private Map<SpecStat, Integer> specStats = new HashMap<>(); private int bagType; private int charmEXP; private boolean quest; private int reqQuestOnProgress; private int senseEXP; private final Set<Integer> questIDs = new HashSet<>(); private int mobID; private int npcID; private int linkedID; private boolean monsterBook; private boolean notConsume; private String script = ""; private int scriptNPC; private int life; private int masterLv; private int reqSkillLv; private Set<Integer> skills = new HashSet<>(); private int moveTo; private final Set<ItemRewardInfo> itemRewardInfos = new HashSet<>(); private int skillId; private int grade; private int android; private int familiarID; private double unitPrice; private int reqLevel; private int incTameness; private int incRepleteness; private int incCharmExp; private boolean choice; private int gender; private List<Integer> limitedPets = new ArrayList<>(); public void putScrollStat(ScrollStat scrollStat, int val) { getScrollStats().put(scrollStat, val); } public void addQuest(int questId) { questIDs.add(questId); } public void putSpecStat(SpecStat ss, int i) { getSpecStats().put(ss, i); } public void addLimitedPet(int itemId) { limitedPets.add(itemId); } public void addItemReward(ItemRewardInfo rewardInfo) { itemRewardInfos.add(rewardInfo); } }
26.627907
72
0.693013
91f05c8f1e6b00a0096da029412750b006a1c8e5
2,160
package me.alpha432.oyvey.features.modules.misc; import com.mojang.realmsclient.gui.ChatFormatting; import java.util.HashMap; import java.util.UUID; import me.alpha432.oyvey.OyVey; import me.alpha432.oyvey.features.command.Command; import me.alpha432.oyvey.features.modules.Module; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; public class PearlNotify extends Module { private final HashMap<EntityPlayer, UUID> list; private Entity enderPearl; private boolean flag; public PearlNotify() { super("PearlResolver", "Notify pearl throws.", Module.Category.MISC, true, true, false); this.list = new HashMap<>(); } public void onEnable() { this.flag = true; } public void onUpdate() { if (mc.world == null || mc.player == null) return; this.enderPearl = null; for (Entity e : mc.world.loadedEntityList) { if (e instanceof net.minecraft.entity.item.EntityEnderPearl) { this.enderPearl = e; break; } } if (this.enderPearl == null) { this.flag = true; return; } EntityPlayer closestPlayer = null; for (EntityPlayer entity : mc.world.playerEntities) { if (closestPlayer == null) { closestPlayer = entity; continue; } if (closestPlayer.getDistance(this.enderPearl) <= entity.getDistance(this.enderPearl)) continue; closestPlayer = entity; } if (closestPlayer == mc.player) this.flag = false; if (closestPlayer != null && this.flag) { String faceing = this.enderPearl.getHorizontalFacing().toString(); if (faceing.equals("west")) { faceing = "east"; } else if (faceing.equals("east")) { faceing = "west"; } Command.sendSilentMessage(OyVey.friendManager.isFriend(closestPlayer.getName()) ? (ChatFormatting.AQUA + closestPlayer.getName() + ChatFormatting.DARK_GRAY + " has just thrown a pearl heading " + faceing + "!") : (ChatFormatting.RED + closestPlayer.getName() + ChatFormatting.DARK_GRAY + " has just thrown a pearl heading " + faceing + "!")); this.flag = false; } } }
32.727273
348
0.661111
da07d0e1cc0b2b88626cc87103880e195945d666
6,137
package yalantis.com.sidemenu.sample.fragment; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import yalantis.com.sidemenu.interfaces.ScreenShotable; import yalantis.com.sidemenu.sample.Edit; import yalantis.com.sidemenu.sample.R; /** * Created by Konstantin on 22.12.2014. */ public class FatherMothers extends Fragment implements ScreenShotable { public static final String CLOSE = "Close"; public static final String FATHERMOTHERS = "Fathermothers"; private View containerView; protected int res; private Bitmap bitmap; private ImageView fm2,fm3,fm4,fm5,fm7,fm8,father1,fm10,fm11,fm13; public static FatherMothers newInstance() { FatherMothers contentFragment = new FatherMothers(); return contentFragment; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); this.containerView = view.findViewById(R.id.container); fm2=(ImageView)view.findViewById(R.id.fm2); fm3=(ImageView)view.findViewById(R.id.fm3); fm4=(ImageView)view.findViewById(R.id.fm4); fm5=(ImageView)view.findViewById(R.id.fm5); fm7=(ImageView)view.findViewById(R.id.fm7); fm8=(ImageView)view.findViewById(R.id.fm8); fm10=(ImageView)view.findViewById(R.id.fm10); father1=(ImageView)view.findViewById(R.id.father1); fm11=(ImageView)view.findViewById(R.id.fm11); fm13=(ImageView)view.findViewById(R.id.fm13); fm2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), Edit.class); intent.putExtra("imageid","fm2"); startActivity(intent); } }); fm3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), Edit.class); intent.putExtra("imageid","fm3"); startActivity(intent); } }); fm4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), Edit.class); intent.putExtra("imageid","fm4"); startActivity(intent); } }); fm5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), Edit.class); intent.putExtra("imageid","fm5"); startActivity(intent); } }); fm7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), Edit.class); intent.putExtra("imageid","fm7"); startActivity(intent); } }); fm8.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), Edit.class); intent.putExtra("imageid","fm8"); startActivity(intent); } }); fm10.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), Edit.class); intent.putExtra("imageid","fm10"); startActivity(intent); } }); father1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), Edit.class); intent.putExtra("imageid","father1"); startActivity(intent); } }); fm11.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), Edit.class); intent.putExtra("imageid","fm11"); startActivity(intent); } }); fm13.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), Edit.class); intent.putExtra("imageid","fm13"); startActivity(intent); } }); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fathermothers, container, false); // mImageView = (ImageView) rootView.findViewById(R.id.image_content); // mImageView.setClickable(true); // mImageView.setFocusable(true); // mImageView.setImageResource(res); return rootView; } @Override public void takeScreenShot() { Thread thread = new Thread() { @Override public void run() { Bitmap bitmap = Bitmap.createBitmap(containerView.getWidth(), containerView.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); containerView.draw(canvas); FatherMothers.this.bitmap = bitmap; } }; thread.start(); } @Override public Bitmap getBitmap() { return bitmap; } }
32.3
83
0.591331
4b12309f81200061b11d4030825a46ce5bf22287
2,004
package com.github.onsdigital.babbage.search; import com.github.onsdigital.babbage.api.util.SearchRendering; import com.github.onsdigital.babbage.api.util.SearchUtils; import com.github.onsdigital.babbage.error.ValidationError; import com.github.onsdigital.babbage.response.base.BabbageResponse; import com.github.onsdigital.babbage.search.helpers.SearchRequestHelper; import com.github.onsdigital.babbage.search.helpers.base.SearchQueries; import com.github.onsdigital.babbage.search.helpers.dates.PublishDates; import com.github.onsdigital.babbage.search.helpers.dates.PublishDatesException; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.List; import java.util.Optional; /** * Encapsulates some of the static search methods making it easier to test. */ public class SearchService { private static final SearchService service = new SearchService(); public static SearchService get() { return service; } public PublishDates extractPublishDates(HttpServletRequest request) throws PublishDatesException { return SearchRequestHelper.extractPublishDates(request); } public BabbageResponse listPageWithValidationErrors(String listType, SearchQueries queries, List<ValidationError> errors) throws IOException { if (errors == null || errors.isEmpty()) { return listPage(listType, queries); } return SearchRendering.buildPageResponseWithValidationErrors(listType, SearchUtils.searchAll(queries), Optional.ofNullable(errors)); } public BabbageResponse listPage(String listType, SearchQueries queries) throws IOException { return SearchRendering.buildPageResponse(listType, SearchUtils.searchAll(queries)); } public BabbageResponse listJson(String listType, SearchQueries queries) throws IOException { return SearchRendering.buildDataResponse(listType, SearchUtils.searchAll(queries)); } }
41.75
140
0.766966
e43178e357856ef4dd18ae9d3d033ad57251a28f
2,355
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.ipmi.protocol.packet.ipmi.command.messaging; import com.google.common.primitives.UnsignedBytes; import java.nio.ByteBuffer; import org.anarres.ipmi.protocol.client.visitor.IpmiClientIpmiCommandHandler; import org.anarres.ipmi.protocol.client.visitor.IpmiHandlerContext; import org.anarres.ipmi.protocol.packet.common.Code; import org.anarres.ipmi.protocol.packet.ipmi.IpmiChannelNumber; import org.anarres.ipmi.protocol.packet.ipmi.IpmiCommandName; import org.anarres.ipmi.protocol.packet.ipmi.command.AbstractIpmiRequest; /** * [IPMI2] Section 22.23, table 22-27, page 304. * * @author shevek */ public class GetChannelAccessRequest extends AbstractIpmiRequest { public enum RequestedSetting implements Code.Wrapper { NonVolatile(0b01), Volatile(0b10); private final byte code; /* pp */ RequestedSetting(int code) { this.code = UnsignedBytes.checkedCast(code); } @Override public byte getCode() { return code; } } public IpmiChannelNumber channelNumber = IpmiChannelNumber.CURRENT; public RequestedSetting requestedSetting; @Override public IpmiCommandName getCommandName() { return IpmiCommandName.GetChannelAccess; } @Override public void apply(IpmiClientIpmiCommandHandler handler, IpmiHandlerContext context) { handler.handleGetChannelAccessRequest(context, this); } @Override protected int getDataWireLength() { return 2; } @Override protected void toWireData(ByteBuffer buffer) { buffer.put(channelNumber.getCode()); buffer.put((byte) (requestedSetting.getCode() << 6)); } @Override protected void fromWireData(ByteBuffer buffer) { channelNumber = Code.fromBuffer(IpmiChannelNumber.class, buffer); int tmp = UnsignedBytes.toInt(buffer.get()); requestedSetting = Code.fromInt(RequestedSetting.class, (tmp >> 6) & 0x3); } @Override public void toStringBuilder(StringBuilder buf, int depth) { super.toStringBuilder(buf, depth); appendValue(buf, depth, "ChannelNumber", channelNumber); appendValue(buf, depth, "RequestedSetting", requestedSetting); } }
31.4
89
0.707856
bda24fcd03463e29b52f3f525d97a897ac1e60f5
1,078
package com.qcosmos.vpb.todolist; import android.app.Activity; import android.content.Context; import android.view.View; import android.view.inputmethod.InputMethodManager; /** * Created by vpb on 8/22/17. */ public final class Utils { public static void showKeyboard(View view, Activity activity) { InputMethodManager imm =(InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(view,InputMethodManager.SHOW_IMPLICIT); } public static void dismissKeyboard(View view, Activity activity) { InputMethodManager imm =(InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } public static String capitalizeString(String str) { if(str != null && !str.trim().isEmpty()) { if(str.length() > 1) { str = Character.toUpperCase(str.charAt(0)) + str.substring(1); } else { str = str.toUpperCase(); } } return str; } }
31.705882
109
0.670686
1c5e9b2c69bc2cb180f873c0d8876c5831c3e386
521
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.reactnativecommunity.netinfo; public class NetInfoUtils { public static void reverseByteArray(byte[] array) { for (int i = 0; i < array.length / 2; i++) { byte temp = array[i]; array[i] = array[array.length - i - 1]; array[array.length - i - 1] = temp; } } }
28.944444
66
0.608445
8bc68f1df237e24bf628f880af86dfbf3ce7a8b0
4,912
package org.markysoft.vani.core.wait; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import org.markysoft.vani.core.VaniContext; import org.markysoft.vani.core.javascript.VaniUtils; import org.markysoft.vani.core.locating.locator.ByJQuery; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.SearchContext; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.FluentWait; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; /** * This class provides convenience methods for declaring wait conditions. * * @author Thomas * */ public class WaitBuilder implements WaitOperatorBuilder, WaitConditionTargetBuilder { protected List<WaitCommand> commands = new ArrayList<>(1); protected ConjunctionType conjunctionType; protected VaniContext vaniContext; public WaitBuilder(WaitCommand command, VaniContext vaniContext) { commands.add(command); this.vaniContext = vaniContext; } public WaitBuilder(VaniContext vaniContext) { this.vaniContext = vaniContext; } protected WaitCommand cmd() { return commands.isEmpty() ? null : commands.get(commands.size() - 1); } @Override public WaitOperatorBuilder is(Predicate<?> predicate) { cmd().setConditionPredicate(predicate); return this; } @Override public WaitOperatorBuilder is(Supplier<Boolean> supplier) { cmd().setConditionSupplier(supplier); return this; } @Override public WaitOperatorBuilder is(Function<?, Boolean> function) { cmd().setConditionFunction(function); return this; } @Override public WaitOperatorBuilder not() { cmd().setNotFlag(true); return this; } @Override public WaitConditionTargetBuilder and() { this.conjunctionType = ConjunctionType.AND; return this; } @Override public WaitConditionTargetBuilder or() { this.conjunctionType = ConjunctionType.OR; return this; } @Override public boolean until(long timeout, long period, WebDriver webDriver) { FluentWait<WebDriver> wait = new FluentWait<WebDriver>(webDriver).withTimeout(timeout, TimeUnit.MILLISECONDS) .pollingEvery(period, TimeUnit.MILLISECONDS); wait.ignoring(NoSuchElementException.class); return wait.until(evalFunction); } @Override public boolean until(long timeout, long period) { return until(timeout, period, null); } @Override public WaitOperatorBuilder element(WebElement element) { commands.add(new WebElementWaitCommand(element)); return this; } @Override public WaitOperatorBuilder element(String selector) { commands.add(new ByWaitCommand(new ByJQuery(selector, vaniContext), null)); return this; } @Override public WaitOperatorBuilder element(String selector, SearchContext rootElement) { commands.add(new ByWaitCommand(new ByJQuery(selector, vaniContext), rootElement)); return this; } @Override public WaitOperatorBuilder webDriver(WebDriver webDriver) { commands.add(new WebDriverWaitCommand(webDriver)); return this; } public WaitOperatorBuilder ajax(String url, long startInMillis, WebDriver webDriver) { commands.add(new AjaxWaitCommand(vaniContext, url, startInMillis, webDriver)); return this; } protected com.google.common.base.Function<WebDriver, Boolean> evalFunction = new com.google.common.base.Function<WebDriver, Boolean>() { @Override public Boolean apply(WebDriver webDriver) { boolean result = true; for (WaitCommand cmd : commands) { result &= cmd.eval(); } return result; } }; @SuppressWarnings("unchecked") @Override public <T, R> WaitOperatorBuilder has(Function<T, R> function, R expected) { cmd().setConditionPredicate(new Predicate<T>() { @Override public boolean test(T target) { R actual = function.apply(target); boolean result = expected.equals(actual); return result; } }); return this; } @SuppressWarnings("unchecked") @Override public WaitOperatorBuilder spel(String condition) { cmd().setConditionPredicate(new Predicate<WebElement>() { ExpressionParser parser = new SpelExpressionParser(); Expression exp = parser.parseExpression(condition); @Override public boolean test(WebElement element) { boolean result = exp.getValue(element, Boolean.class); return result; } }); return this; } public WaitOperatorBuilder variable(String variableName) { commands.add(new VariableWaitCommand(variableName, vaniContext.getAppContext().getBean(VaniUtils.class))); return this; } }
28.393064
138
0.738803
2cc171df5aa273330efd8d2b66b9237100237361
8,414
package com.aura.util; import java.util.Collection; import java.util.Set; import com.alibaba.fastjson.JSON; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; //@Component public class JedisUtil { private static JedisPool jedisPool = null; //volatile修饰的变量对于其他线程是可见的,但是变量的操作不是原子操作。只有基本类型操作(赋值,读取)才是原子性操作。其他类型变量或基本类型的运算操作都是非原子操作 private static Jedis jedis = null;//volatile /** * 初始化非切片池 */ //private void initialPool() static { // 池基本配置 JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(20); config.setMaxIdle(5); config.setMaxWaitMillis(10000); config.setTestOnBorrow(false); jedisPool = new JedisPool(config,"172.16.22.244",6379); } public JedisUtil(){} public static Jedis getJedis(){ if (jedis ==null){ synchronized (Jedis.class){ if (jedis ==null){ jedis = jedisPool.getResource(); } } } return jedis; } /*public static JedisPool jedisPool{ if (jedisPool ==null){ synchronized (JedisPool.class){ if (jedisPool==null){ jedisPool = applicationContext.getBean(JedisPool.class); } } } return jedisPool; }*/ /* @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if(JedisUtil.applicationContext == null){ JedisUtil.applicationContext = applicationContext; //初始化 spring applicationContext } }*/ /** * 根据key查看是否存在 * @param key * @return */ public static boolean hasKey(String key){ try { jedis = jedisPool.getResource(); jedis.exists(key); return true; } catch (Exception e) { if (jedis != null) { jedisPool.returnBrokenResource(jedis); jedis = null; } e.printStackTrace(); return false; }finally{ jedisPool.returnResource(jedis); } } /** * 向缓存中设置字符串内容 * @param key key * @param value value * @return * @throws Exception */ public static boolean set(String key,String value) { Jedis jedis = null; try { jedis = jedisPool.getResource(); jedis.set(key, value); return true; } catch (Exception e) { if (jedis != null) { jedisPool.returnBrokenResource(jedis); jedis = null; } e.printStackTrace(); return false; }finally{ jedisPool.returnResource(jedis); } } /** * 向缓存中设置对象 * @param key * @param value * @return */ public static boolean set(String key,Object value){ Jedis jedis = null; try { String objectJson = JSON.toJSONString(value); jedis = jedisPool.getResource(); jedis.set(key, objectJson); return true; } catch (Exception e) { if (jedis != null) { jedisPool.returnBrokenResource(jedis); jedis = null; } e.printStackTrace(); return false; }finally{ jedisPool.returnResource(jedis); } } /** * 设置key -value 形式数据 * @param key * @param value * @return */ // public static String set(String key,String value){ // String result = getJedis().set(key,value); // return result; // } /** * 设置 一个过期时间 * @param key * @param value * @param timeOut 单位秒 * @return */ public static String set(String key,String value,int timeOut){ try { jedis = jedisPool.getResource(); return jedis.setex(key,timeOut,value); } catch (Exception e) { if (jedis != null) { jedisPool.returnBrokenResource(jedis); jedis = null; } e.printStackTrace(); return ""; }finally{ jedisPool.returnResource(jedis); } } /** * 根据key获取value * @param key * @return */ // public static String getByKey(String key){ // return getJedis().get(key); // } /** * 根据key 获取内容 * @param key * @return */ public static String getByKey(String key){ Jedis jedis = null; try { jedis = jedisPool.getResource(); String value = jedis.get(key); return value; } catch (Exception e) { if (jedis != null) { jedisPool.returnBrokenResource(jedis); jedis = null; } return ""; }finally{ jedisPool.returnResource(jedis); } } /** * 根据key 获取对象 * @param key * @return */ public static <T> T get(String key,Class<T> clazz){ Jedis jedis = null; try { jedis = jedisPool.getResource(); String value = jedis.get(key); return JSON.parseObject(value, clazz); } catch (Exception e) { if (jedis != null) { jedisPool.returnBrokenResource(jedis); jedis = null; } e.printStackTrace(); return null; }finally{ jedisPool.returnResource(jedis); } } /** * 根据通配符获取所有匹配的key * @param pattern * @return */ public static Set<String> getKesByPattern(String pattern){ Jedis jedis = null; try { jedis = jedisPool.getResource(); return jedis.keys(pattern); } catch (Exception e) { if (jedis != null) { jedisPool.returnBrokenResource(jedis); jedis = null; } }finally{ jedisPool.returnResource(jedis); } return null; } /** * 删除缓存中得对象,根据key * @param key * @return */ public static boolean del(String key){ Jedis jedis = null; try { jedis = jedisPool.getResource(); jedis.del(key); return true; } catch (Exception e) { if (jedis != null) { jedisPool.returnBrokenResource(jedis); jedis = null; } e.printStackTrace(); return false; }finally{ jedisPool.returnResource(jedis); } } /** * 模糊匹配KEY,获取key集合后批量删除缓存中得对象 * @param * @return */ public static boolean deleteKeys(String keys){ Jedis jedis = null; try { jedis = jedisPool.getResource(); Set<String> stringSet = jedis.keys(keys); if(stringSet.size()==0){ del(keys); } for(String key:stringSet){ jedis.del(key); } return true; } catch (Exception e) { if (jedis != null) { jedisPool.returnBrokenResource(jedis); jedis = null; } e.printStackTrace(); return false; }finally{ jedisPool.returnResource(jedis); } } /** * 根据key获取过期时间 * @param key * @return */ public static long getTimeOutByKey(String key){ Jedis jedis = null; try { jedis = jedisPool.getResource(); return jedis.ttl(key); } catch (Exception e) { if (jedis != null) { jedisPool.returnBrokenResource(jedis); jedis = null; } e.printStackTrace(); }finally{ jedisPool.returnResource(jedis); } return 0L; } /** * 清空数据 【慎用啊!】 */ public static void flushDB(){ getJedis().flushDB(); } /** * 返回所有的keys集合 * @return */ public static Set<String> getkeys(){ Set set=getJedis().keys("*"); return set; } /** * 刷新过期时间 * @param key * @param timeOut * @return */ public static long refreshLiveTime(String key,int timeOut){ return getJedis().expire(key,timeOut); } }
24.459302
100
0.504754
890c4848a58c94096356356e516baa3dbc5301af
756
package com.example; import javax.annotation.Generated; @Generated("org.realityforge.webtack") public final class Dictionary_requiredDoubleValueTestCompile { static Dictionary_requiredDoubleValue $typeReference$; public static Dictionary_requiredDoubleValue requiredDoubleValue( final double requiredDoubleValue) { return Dictionary_requiredDoubleValue.requiredDoubleValue( requiredDoubleValue ); } public static double requiredDoubleValue(final Dictionary_requiredDoubleValue $instance) { return $instance.requiredDoubleValue(); } public static void setRequiredDoubleValue(final Dictionary_requiredDoubleValue $instance, double requiredDoubleValue) { $instance.setRequiredDoubleValue( requiredDoubleValue ); } }
32.869565
92
0.816138
a8c8026ca318a57f11187cd52bcd88c4ddb4a6f3
1,858
package de.superklug.mygames.supertavarialobby.utils.runnables; import de.superklug.mygames.supertavarialobby.Lobby; import org.bukkit.Bukkit; import org.bukkit.scheduler.BukkitRunnable; public class UpdateScoreboardRunnable extends BukkitRunnable { private final Lobby module; public UpdateScoreboardRunnable(final Lobby module) { this.module = module; } @Override public void run() { try { Bukkit.getOnlinePlayers().forEach((players) -> { if(players.getScoreboard() != null) { if(module.getUserData(players) != null) { int seconds = module.getUserData(players).getPlaytime(); int hours = 0; int minutes = 0; while(seconds >= 60) { minutes++; seconds = seconds - 60; } while(minutes >= 60) { hours++; minutes = minutes - 60; } module.getSuperAPI().scoreboard(players).update("§8➥ §b" + hours + "§7h", " §b" + minutes + "§7m §b" + seconds + "§7s", 9); module.getSuperAPI().scoreboard(players).update("§8➥ ", "§b" + module.getUserData(players).getTokens(), 6); module.getSuperAPI().scoreboard(players).update("§8➥ ", "§b" + module.getUserData(players).getCoins(), 3); module.getSuperAPI().scoreboard(players).update("§8➥ ", "§cLädt...", 0); module.getUserData(players).setPlaytime(module.getUserData(players).getPlaytime() + 1); } } }); } catch(Exception exception) {} } }
35.730769
147
0.493541
3bd1babe1621cdbc0224fd9eb29d3422c6fc86de
1,566
/* * Copyright (C) 2020 Dremio * * 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.dremio.nessie.versioned.impl.experimental; import java.io.IOException; import org.eclipse.jgit.errors.MissingObjectException; import org.eclipse.jgit.internal.storage.dfs.DfsObjDatabase; import org.eclipse.jgit.internal.storage.dfs.DfsReader; import org.eclipse.jgit.lib.AnyObjectId; import org.eclipse.jgit.lib.ObjectLoader; public class NessieObjReader extends DfsReader { private final NessieObjDatabase db; /** * Initialize a new DfsReader. * * @param db parent DfsObjDatabase. */ protected NessieObjReader(DfsObjDatabase db) { super(db); this.db = (NessieObjDatabase) db; } @Override public boolean has(AnyObjectId objectId) { try { return db.get(objectId, -1) != null; } catch (MissingObjectException | IllegalArgumentException e) { return false; } } @Override public ObjectLoader open(AnyObjectId objectId, int typeHint) throws IOException { return db.get(objectId, typeHint); } }
28.472727
83
0.736909
9c4ba5643229cd86f8a8f897065d9b8c5f13ea88
291
package com.zkh.cloud.utils; public interface Constants { static final String REGISTERUSER_QUEUE ="registeruser_queue";//注册用户队列 static final String EMAIL_FROM ="592470261@qq.com";//邮件发送者 static final String EMAIL_SUBJECT ="用户注册验证码";//标题 static final String EMAIL_TEXT ="您的验证码是:";//内容 }
32.333333
70
0.776632
cafe2e55bd21c6483b6cdfb649544203c670fec4
7,577
package pl.allegro.tech.hermes.consumers.supervisor.workload.mirror; import com.google.common.collect.Sets; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.allegro.tech.hermes.api.Subscription; import pl.allegro.tech.hermes.api.SubscriptionName; import pl.allegro.tech.hermes.api.Topic; import pl.allegro.tech.hermes.common.admin.zookeeper.ZookeeperAdminCache; import pl.allegro.tech.hermes.common.config.ConfigFactory; import pl.allegro.tech.hermes.common.config.Configs; import pl.allegro.tech.hermes.consumers.subscription.cache.SubscriptionsCache; import pl.allegro.tech.hermes.consumers.supervisor.ConsumersSupervisor; import pl.allegro.tech.hermes.consumers.supervisor.workload.ConsumerAssignmentCache; import pl.allegro.tech.hermes.consumers.supervisor.workload.ConsumerAssignmentRegistry; import pl.allegro.tech.hermes.consumers.supervisor.workload.SubscriptionAssignment; import pl.allegro.tech.hermes.consumers.supervisor.workload.SubscriptionAssignmentView; import pl.allegro.tech.hermes.consumers.supervisor.workload.SupervisorController; import pl.allegro.tech.hermes.domain.notifications.InternalNotificationsBus; import java.util.Collections; import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.Collectors; import static pl.allegro.tech.hermes.common.config.Configs.CONSUMER_WORKLOAD_ALGORITHM; import static pl.allegro.tech.hermes.common.config.Configs.CONSUMER_WORKLOAD_NODE_ID; public class MirroringSupervisorController implements SupervisorController { private static final Logger logger = LoggerFactory.getLogger(MirroringSupervisorController.class); private final String consumerNodeId; private final ConsumersSupervisor supervisor; private final InternalNotificationsBus notificationsBus; private final ConsumerAssignmentCache assignmentCache; private final ConsumerAssignmentRegistry consumerAssignmentRegistry; private final SubscriptionsCache subscriptionsCache; private final ZookeeperAdminCache adminCache; private final ConfigFactory configFactory; private final ExecutorService executorService; public MirroringSupervisorController(ConsumersSupervisor supervisor, InternalNotificationsBus notificationsBus, ConsumerAssignmentCache assignmentCache, ConsumerAssignmentRegistry consumerAssignmentRegistry, SubscriptionsCache subscriptionsCache, ZookeeperAdminCache adminCache, ConfigFactory configFactory) { this.consumerNodeId = configFactory.getStringProperty(CONSUMER_WORKLOAD_NODE_ID); this.supervisor = supervisor; this.notificationsBus = notificationsBus; this.assignmentCache = assignmentCache; this.consumerAssignmentRegistry = consumerAssignmentRegistry; this.subscriptionsCache = subscriptionsCache; this.adminCache = adminCache; this.configFactory = configFactory; this.executorService = Executors.newFixedThreadPool( configFactory.getIntProperty(Configs.ZOOKEEPER_TASK_PROCESSING_THREAD_POOL_SIZE), new ThreadFactoryBuilder().setNameFormat("mirroring-supervisor-%d").build() ); } @Override public void onSubscriptionCreated(Subscription subscription) { Set<SubscriptionAssignment> currentAssignments = getConsumerAssignments(); SubscriptionAssignmentView currentState = SubscriptionAssignmentView.of(currentAssignments); SubscriptionAssignment addedAssignment = new SubscriptionAssignment(consumerNodeId, subscription.getQualifiedName()); SubscriptionAssignmentView targetState = SubscriptionAssignmentView.of( Sets.union(currentAssignments, Collections.singleton(addedAssignment)) ); executorService.submit(() -> consumerAssignmentRegistry.updateAssignments(currentState, targetState)); } @Override public void onSubscriptionRemoved(Subscription subscription) { Set<SubscriptionAssignment> currentAssignments = getConsumerAssignments(); SubscriptionAssignmentView currentState = SubscriptionAssignmentView.of(currentAssignments); SubscriptionAssignment deletedAssignment = new SubscriptionAssignment(consumerNodeId, subscription.getQualifiedName()); SubscriptionAssignmentView targetState = SubscriptionAssignmentView.of( Sets.difference(currentAssignments, Collections.singleton(deletedAssignment)) ); executorService.submit(() -> consumerAssignmentRegistry.updateAssignments(currentState, targetState)); } private Set<SubscriptionAssignment> getConsumerAssignments() { return assignmentCache.getConsumerSubscriptions().stream() .map(s -> new SubscriptionAssignment(consumerNodeId, s)) .collect(Collectors.toSet()); } @Override public void onSubscriptionChanged(Subscription subscription) { executorService.submit(() -> { switch (subscription.getState()) { case PENDING: case ACTIVE: onSubscriptionCreated(subscription); break; case SUSPENDED: onSubscriptionRemoved(subscription); break; default: break; } supervisor.updateSubscription(subscription); }); } @Override public void onTopicChanged(Topic topic) { for (Subscription subscription : subscriptionsCache.subscriptionsOfTopic(topic.getName())) { executorService.submit(() -> supervisor.updateTopic(subscription, topic)); } } @Override public void onSubscriptionAssigned(SubscriptionName subscriptionName) { logger.info("Assigning consumer for {}", subscriptionName.getQualifiedName()); Subscription subscription = subscriptionsCache.getSubscription(subscriptionName); supervisor.assignConsumerForSubscription(subscription); } @Override public void onAssignmentRemoved(SubscriptionName subscription) { logger.info("Removing assignment from consumer for {}", subscription); supervisor.deleteConsumerForSubscriptionName(subscription); } @Override public void start() throws Exception { adminCache.start(); adminCache.addCallback(this); notificationsBus.registerSubscriptionCallback(this); notificationsBus.registerTopicCallback(this); assignmentCache.registerAssignmentCallback(this); supervisor.start(); logger.info("Consumer boot complete. Workload config: [{}]", configFactory.print(CONSUMER_WORKLOAD_NODE_ID, CONSUMER_WORKLOAD_ALGORITHM)); } @Override public Set<SubscriptionName> assignedSubscriptions() { return assignmentCache.getConsumerSubscriptions(); } @Override public void shutdown() throws InterruptedException { supervisor.shutdown(); } @Override public void onRetransmissionStarts(SubscriptionName subscription) throws Exception { supervisor.retransmit(subscription); } @Override public Optional<String> watchedConsumerId() { return Optional.of(consumerNodeId); } }
43.797688
146
0.7305
7ca9e3ecc7302dcaca13a2b21d2a7195fc79a96f
2,127
package edu.westga.cs3212.meal_planning.test.model.recipe_manager; import static org.junit.jupiter.api.Assertions.*; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; import edu.westga.cs3212.meal_planning.model.Recipe; import edu.westga.cs3212.meal_planning.model.RecipeManager; class TestConstructor { @Test void testRecipesIsNull() { assertThrows( IllegalArgumentException.class, ()->{ new RecipeManager(null); } ); } @Test void testCreateManagerWithNoRecipes() { ArrayList<Recipe> recipes = new ArrayList<Recipe>(); RecipeManager result = new RecipeManager(recipes); List<Recipe> recipesList = result.getRecipes(); assertEquals(0, recipesList.size()); } @Test void testCreateManagerWithOneRecipe() { ArrayList<Recipe> recipes = new ArrayList<Recipe>(); Recipe recipe1 = new Recipe("lasagna", List.of("pasta", "italian"), 1.0, 2.0, List.of("meat", "noodles", "sauce", "cheese"), List.of("Combine ingredients", "Cook ingredients"), 2); recipes.add(recipe1); RecipeManager result = new RecipeManager(recipes); List<Recipe> recipesList = result.getRecipes(); assertEquals(1, recipesList.size()); assertSame(recipe1, recipesList.get(0)); } @Test void testCreateManagerWithSeveralRecipes() { ArrayList<Recipe> recipes = new ArrayList<Recipe>(); Recipe recipe1 = new Recipe("lasagna", List.of("pasta", "italian"), 1.0, 2.0, List.of("meat", "noodles", "sauce", "cheese"), List.of("Combine ingredients", "Cook ingredients"), 2); recipes.add(recipe1); Recipe recipe2 = new Recipe("eggplant parmesan", List.of("pasta", "italian", "vegetarian"), 3.0, 4.0, List.of("eggplant", "noodles", "sauce", "cheese"), List.of("Combine ingredients", "Cook ingredients"), 4); recipes.add(recipe2); RecipeManager result = new RecipeManager(recipes); List<Recipe> recipesList = result.getRecipes(); assertEquals(2, recipesList.size()); assertSame(recipe1, recipesList.get(0)); assertSame(recipe2, recipesList.get(1)); } }
31.279412
211
0.685002
5f5d2770246fb5c9db0dfbd84ac2e0f5cd3392ea
2,111
/* * Copyright 2019 MovingBlocks * * 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.terasology.launcher.config; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import org.terasology.launcher.packages.Package; import java.io.IOException; import java.util.Collections; /** * Adds GSON support for {@link Package} instances. */ class PackageAdapter extends TypeAdapter<Package> { private static final String KEY_ID = "id"; private static final String KEY_VERSION = "version"; @Override public void write(JsonWriter out, Package pkg) throws IOException { if (pkg != null) { out.beginObject() .name(KEY_ID) .value(pkg.getId()) .name(KEY_VERSION) .value(pkg.getVersion()) .endObject(); } else { out.nullValue(); } } @Override public Package read(JsonReader in) throws IOException { String id = null; String version = null; in.beginObject(); while (in.hasNext()) { switch (in.nextName()) { case KEY_ID: id = in.nextString(); break; case KEY_VERSION: version = in.nextString(); break; default: in.skipValue(); } } in.endObject(); return new Package(id, null, version, null, Collections.emptyList()); } }
29.732394
77
0.598768
85133fcf30c9cf97e0b8eb446cba80095c9d9ce3
4,238
package com.github.stephanenicolas.injectview; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.os.Bundle; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.annotation.Config; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; /** * These tests are really complex to setup. * Take your time for maintenance. * @author SNI */ @RunWith(InjectViewTestRunner.class) @Config(manifest= Config.NONE) public class InjectViewProcessorForFragmentsWithOtherTest { public static final String VIEW_TAG = "TAG"; public static final String VIEW_TAG2 = "TAG2"; public static final int VIEW_ID = 101; public static final int VIEW_ID2 = 102; private InjectViewProcessor processor = new InjectViewProcessor(); @Test public void shouldInjectFragment_withId() { TestActivityWithId activity = Robolectric.buildActivity(TestActivityWithId.class) .create() .get(); assertNotNull(activity.pojoWithActivityConstructor.fragment); assertThat(activity.pojoWithActivityConstructor.fragment.getId(), is(VIEW_ID2)); assertThat(activity.pojoWithActivityConstructor.fragment2.getTag(), is(VIEW_TAG2)); assertNotNull(activity.pojoWithFragmentConstructor.fragment); assertThat(activity.pojoWithFragmentConstructor.fragment.getId(), is(VIEW_ID2)); assertThat(activity.pojoWithActivityConstructor.fragment2.getTag(), is(VIEW_TAG2)); } public static class TestActivityWithId extends Activity { private PojoWithActivityConstructor pojoWithActivityConstructor; private PojoWithFragmentConstructor pojoWithFragmentConstructor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout layout = new LinearLayout(this); final TextView text1 = new TextView(this); text1.setId(VIEW_ID); layout.addView(text1); LinearLayout layout2 = new LinearLayout(this); layout2.setId(VIEW_ID2); layout.addView(layout2); pojoWithActivityConstructor = new PojoWithActivityConstructor(this); setContentView(layout); pojoWithFragmentConstructor = new PojoWithFragmentConstructor(getFragmentManager().findFragmentByTag( VIEW_TAG2)); } @Override public FragmentManager getFragmentManager() { FragmentManager fragmentManager = super.getFragmentManager(); if (fragmentManager.findFragmentById(VIEW_ID2) == null ) { fragmentManager.beginTransaction().add(VIEW_ID2, new DummyFragment(), VIEW_TAG).commit(); } if (fragmentManager.findFragmentByTag(VIEW_TAG2) == null ) { fragmentManager.beginTransaction().add(new DummyFragmentWithView(), VIEW_TAG2).commit(); } fragmentManager.executePendingTransactions(); return fragmentManager; } @Override public View findViewById(int id) { if (id == VIEW_ID) { final TextView text1 = new TextView(this); text1.setId(id); return text1; } else { return super.findViewById(id); } } } public static class PojoWithActivityConstructor { @InjectFragment(VIEW_ID2) protected Fragment fragment; @InjectFragment(tag = VIEW_TAG2) protected Fragment fragment2; public PojoWithActivityConstructor(Activity activity) { } } public static class PojoWithFragmentConstructor { @InjectFragment(VIEW_ID2) protected Fragment fragment; @InjectFragment(tag = VIEW_TAG2) protected Fragment fragment2; public PojoWithFragmentConstructor(Fragment fragment) { } } public static class DummyFragment extends Fragment { public DummyFragment() { } } public static class DummyFragmentWithView extends Fragment { @Override public View getView() { LinearLayout layout = new LinearLayout(getActivity()); final TextView text1 = new TextView(getActivity()); text1.setId(VIEW_ID); layout.addView(text1); return layout; } } }
32.6
107
0.739028
b60d6de845b94cf72c2908c05580f93624bf2bc1
864
package com.malalaoshi.android.core.utils; /** * 年级 * Created by tianwei on 6/5/16. */ public class GradeUtils { public static String getGradeName(int gradeId) { switch (gradeId) { case 1: return "小学一年级"; case 2: return "小学二年级"; case 3: return "小学三年级"; case 4: return "小学四年级"; case 5: return "小学五年级"; case 6: return "小学六年级"; case 7: return "初中一年级"; case 8: return "初中二年级"; case 9: return "初中三年级"; case 10: return "高中一年级"; case 11: return "高中二年级"; case 12: return "高中三年级"; } return null; } }
22.153846
52
0.392361
f0cf9210a0d4e95493d93f5dd7ca8f9df3566e30
2,020
package ru.otus.spring.hw.config; import java.util.Optional; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.integration.annotation.Gateway; import org.springframework.integration.annotation.MessagingGateway; import org.springframework.integration.dsl.IntegrationFlow; import org.springframework.integration.dsl.Pollers; import ru.otus.spring.hw.model.Address; import ru.otus.spring.hw.model.Coordinate; import ru.otus.spring.hw.model.Description; @Configuration public class FlowConfig { @MessagingGateway public interface MessageGateway { @Gateway(requestChannel = "coordinateToDescriptionFlow.input", replyChannel = "descriptionChannel") Description process(Coordinate coordinate); } @Bean public IntegrationFlow coordinateToDescriptionFlow() { return f->f.channel(c->c.queue(10)) .bridge(e -> e.poller(Pollers.fixedDelay(100).maxMessagesPerPoll(1))) .handle("addressService", "getAddress", e->e.id("addressActivator")) .<Optional<Address>, Boolean>route(Optional::isEmpty, mapping->mapping .subFlowMapping(false, sf->sf .<Optional<Address>, Address>transform(Optional::get) .handle( "descriptionService", "getDescription" , e->e.id("descriptionActivator")) .channel("descriptionChannel") ) .subFlowMapping(true, sf->sf .<Object, Description>transform(orderItem ->{ return new Description(); }) .channel("descriptionChannel") ) ); } }
40.4
107
0.569802
224a490ca32ce6fc8b28baa3a984aea51844aae0
1,327
/* * (C) Copyright IBM Corp. 2021 * * SPDX-License-Identifier: Apache-2.0 */ package com.ibm.cohort.cql.translation; import java.io.File; import java.io.Reader; import java.util.HashMap; import java.util.Map; import javax.xml.bind.JAXB; import org.cqframework.cql.cql2elm.ModelInfoProvider; import org.hl7.elm.r1.VersionedIdentifier; import org.hl7.elm_modelinfo.r1.ModelInfo; public class CustomModelInfoProvider implements ModelInfoProvider { private Map<VersionedIdentifier,ModelInfo> models = new HashMap<>(); public void addModel(Reader modelInfoXML) { ModelInfo modelInfo = JAXB.unmarshal(modelInfoXML, ModelInfo.class); addModel(modelInfo); } public void addModel(File modelInfoXML) { ModelInfo modelInfo = JAXB.unmarshal(modelInfoXML, ModelInfo.class); addModel(modelInfo); } protected void addModel(ModelInfo modelInfo) { VersionedIdentifier modelId = new VersionedIdentifier().withId(modelInfo.getName()) .withVersion(modelInfo.getVersion()); models.put(modelId, modelInfo); } @Override public ModelInfo load(VersionedIdentifier modelIdentifier) { return models.get(modelIdentifier); } public Map<VersionedIdentifier, ModelInfo> getModels() { return models; } }
27.081633
91
0.709872
ed9d83fae87c95168390813441faffc2d17d4d50
5,001
/* * Copyright 2015-2017 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.real_logic.artio.engine.logger; import io.aeron.logbuffer.ControlledFragmentHandler.Action; import org.agrona.DirectBuffer; import org.agrona.collections.CollectionUtil; import org.agrona.concurrent.Agent; import uk.co.real_logic.artio.DebugLogger; import uk.co.real_logic.artio.LogTag; import uk.co.real_logic.artio.dictionary.generation.Exceptions; import uk.co.real_logic.artio.engine.CompletionPosition; import uk.co.real_logic.artio.replication.ClusterFragmentHandler; import uk.co.real_logic.artio.replication.ClusterHeader; import uk.co.real_logic.artio.replication.ClusterableSubscription; import java.util.List; import static io.aeron.logbuffer.ControlledFragmentHandler.Action.CONTINUE; import static io.aeron.protocol.DataHeaderFlyweight.HEADER_LENGTH; import static uk.co.real_logic.artio.engine.logger.ArchiveDescriptor.alignTerm; /** * Incrementally builds indexes by polling a subscription. */ public class Indexer implements Agent, ClusterFragmentHandler { private static final int LIMIT = 20; private final List<Index> indices; private final ArchiveReader archiveReader; private final ClusterableSubscription subscription; private final String agentNamePrefix; private final CompletionPosition completionPosition; public Indexer( final List<Index> indices, final ArchiveReader archiveReader, final ClusterableSubscription subscription, final String agentNamePrefix, final CompletionPosition completionPosition) { this.indices = indices; this.archiveReader = archiveReader; this.subscription = subscription; this.agentNamePrefix = agentNamePrefix; this.completionPosition = completionPosition; catchIndexUp(); } public int doWork() throws Exception { return subscription.poll(this, LIMIT) + CollectionUtil.sum(indices, Index::doWork); } private void catchIndexUp() { for (final Index index : indices) { index.readLastPosition((aeronSessionId, endOfLastMessageposition) -> { final ArchiveReader.SessionReader sessionReader = archiveReader.session(aeronSessionId); if (sessionReader != null) { do { final long nextMessagePosition = alignTerm(endOfLastMessageposition) + HEADER_LENGTH; endOfLastMessageposition = sessionReader.read(nextMessagePosition, index); } while (endOfLastMessageposition > 0); } }); } } public Action onFragment(final DirectBuffer buffer, final int offset, final int length, final ClusterHeader header) { final int streamId = header.streamId(); final int aeronSessionId = header.sessionId(); final long position = header.position(); DebugLogger.log( LogTag.INDEX, "Indexing @ %d from [%d, %d]%n", position, streamId, aeronSessionId); for (final Index index : indices) { index.indexRecord(buffer, offset, length, streamId, aeronSessionId, position); } return CONTINUE; } public void onClose() { quiesce(); Exceptions.closeAll(() -> Exceptions.closeAll(indices), archiveReader, subscription); } private void quiesce() { while (!completionPosition.hasCompleted()) { Thread.yield(); } if (completionPosition.wasStartupComplete()) { return; } // We know that any remaining data to quiesce at this point must be in the subscription. subscription.poll(this::quiesceFragment, Integer.MAX_VALUE); } private Action quiesceFragment( final DirectBuffer buffer, final int offset, final int length, final ClusterHeader header) { if (completedPosition(header.sessionId()) <= header.position()) { return onFragment(buffer, offset, length, header); } return CONTINUE; } private long completedPosition(final int aeronSessionId) { return completionPosition.positions().get(aeronSessionId); } public String roleName() { return agentNamePrefix + "Indexer"; } }
32.686275
119
0.670866
b41eeb1895a2382570ebdacfaeb36e440720802c
6,264
/* * GROOVE: GRaphs for Object Oriented VErification Copyright 2003--2007 * University of Twente * * 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. * * $Id: JAttr.java 5787 2016-08-04 10:36:41Z rensink $ */ package groove.gui.jgraph; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.MultipleGradientPaint.CycleMethod; import java.awt.Paint; import java.awt.RadialGradientPaint; import java.awt.Rectangle; import java.awt.Stroke; import java.util.HashMap; import java.util.Map; import groove.gui.Options; /** * Class of constant definitions. * @author Arend Rensink * @version $Revision: 5787 $ */ public class JAttr { static { Options.initLookAndFeel(); } /** * The line width used for edges and node borders. */ public static final int DEFAULT_LINE_WIDTH = 1; /** Default background for editor panels. */ public static final Color EDITOR_BACKGROUND = new Color(255, 255, 230); /** Default background for state panels. */ public static final Color STATE_BACKGROUND = new Color(242, 250, 254); /** Error background for state panels. */ public static final Color ERROR_BACKGROUND = new Color(255, 245, 245); /** Background for internal state panels. */ public static final Color TRANSIENT_BACKGROUND = new Color(255, 235, 245); /** Default background for LTS with filtering. */ public static final Color FILTER_BACKGROUND = new Color(230, 230, 255); /** The size of the rounded corners for rounded-rectangle vertices. */ public static final int NORMAL_ARC_SIZE = 5; /** The size of the rounded corners for strongly rounded-rectangle vertices. */ public static final int STRONG_ARC_SIZE = 20; /** * The standard bounds used for nodes. */ public static final Rectangle DEFAULT_NODE_BOUNDS = new Rectangle(10, 10, 19, 19); /** * The standard size used for nodes. */ public static final Dimension DEFAULT_NODE_SIZE = new Dimension(DEFAULT_NODE_BOUNDS.width, DEFAULT_NODE_BOUNDS.height); /** Space left outside the borders of nodes to enable larger * error or emphasis overlays to be painted correctly. * This also influences the initial positioning of the nodes * (at creation time). */ public static final int EXTRA_BORDER_SPACE = 6; /** Node radius for nodified edges. */ static final public Dimension NODE_EDGE_DIMENSION = new Dimension(6, 6); /** The height of the adornment text box. */ public static final int ADORNMENT_HEIGHT = 12; /** The font used for adornment text. */ public static final Font ADORNMENT_FONT = Options.getLabelFont(); /** Foreground (= border) colour of the rubber band selector. */ static public final Color RUBBER_FOREGROUND = new Color(150, 150, 150); /** Foreground (= border) colour of the rubber band selector. */ static public final Color RUBBER_BACKGROUND = new Color(100, 212, 224, 40); /** Line width used for emphasised cells. */ public static final int EMPH_WIDTH = 3; /** Difference in line width between emphasised and non-emphasised. */ public static final float EMPH_INCREMENT = EMPH_WIDTH - DEFAULT_LINE_WIDTH; /** * Static flag determining if gradient background paint should be used. * Gradient paint looks better, but there is a performance hit. */ static final private boolean GRADIENT_PAINT = false; /** Key value for vertex shapes in the attribute map. */ static public String SHAPE_KEY = "vertexShape"; /** Creates a stroke with a given line width and dash pattern. */ public static Stroke createStroke(float width, float[] dash) { Stroke result; if (dash == null) { result = new BasicStroke(width, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER); } else { result = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash, 1.0f); } return result; } /** * Creates paint for a vertex with given bounds and (inner) colour. */ static public Paint createPaint(Rectangle b, Color c) { // only bother with special paint if the vertex is not too small to notice if (!GRADIENT_PAINT || b.width < 10 && b.height < 10) { return c; } else { int cx = b.x + b.width / 2; int cy = b.y + b.height / 2; int fx = b.x + b.width / 3; int fy = b.y + 2 * b.height / 3; int rx = b.width - fx; int ry = b.height - fy; float r = (float) Math.sqrt(rx * rx + ry * ry); Paint newPaint = new RadialGradientPaint(cx, cy, r, fx, fy, new float[] {0f, 1f}, getGradient(c), CycleMethod.NO_CYCLE); return newPaint; } } /** Lazily creates and returns the colour gradient derived from a given colour. */ static private Color[] getGradient(Color c) { Color[] result = gradientMap.get(c); if (result == null) { float factor = .9f; Color inC = new Color((int) Math.min(c.getRed() / factor, 255), (int) Math.min(c.getGreen() / factor, 255), (int) Math.min(c.getBlue() / factor, 255), c.getAlpha()); Color outC = new Color((int) (c.getRed() * factor), (int) (c.getGreen() * factor), (int) (c.getBlue() * factor), c.getAlpha()); gradientMap.put(c, result = new Color[] {inC, outC}); } return result; } /** Mapping from colours to colour gradients for {@link #createPaint(Rectangle, Color)}. */ static private Map<Color,Color[]> gradientMap = new HashMap<>(); }
38.429448
96
0.652299
7c23d454acf6f5b8acc9862589f8876352c7f908
1,626
/* * Copyright 2017 Crown Copyright * * 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 stroom.dashboard.expression.v1; import java.text.ParseException; import java.util.Map; class CurrentUser extends AbstractFunction { static final String KEY = "currentUser()"; static final String NAME = "currentUser"; private static final Generator NULL_GEN = new StaticValueFunction(ValNull.INSTANCE).createGenerator(); private Generator gen = NULL_GEN; public CurrentUser(final String name) { super(name, 0, 0); } @Override public void setParams(final Param[] params) throws ParseException { super.setParams(params); } @Override public void setStaticMappedValues(final Map<String, String> staticMappedValues) { final String v = staticMappedValues.get(KEY); if (v != null) { gen = new StaticValueFunction(ValString.create(v)).createGenerator(); } } @Override public Generator createGenerator() { return gen; } @Override public boolean hasAggregate() { return false; } }
28.526316
106
0.695572
fe272a635f61a998d17b84ff037aa08a90388852
1,451
/* * Copyright (C) 2019 The mx-mod-web-starter Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.github.x19990416.macrossx.guice.modules.starter; import com.github.x19990416.macrossx.guice.modules.common.BaseModuleFactory; import com.google.inject.AbstractModule; public class ApplicationModuleFactory extends BaseModuleFactory { public static final String WEB_JERSEY_APPLICATION = "WebJerseyApplication"; @Override public AbstractModule export(String key) { if(!super.getModules().containsKey(key)) { switch(key){ case WEB_JERSEY_APPLICATION:{ super.getModules().put(WEB_JERSEY_APPLICATION, new JerseyWebApplicationModule()); break; } } } return super.getModules().get(key); } @Override public String getName() { // TODO Auto-generated method stub return "ApplicationModuleFactory"; } }
33.744186
101
0.707788
cd5faa0a4cd6e6150fd667d9399c6a03fe2441e2
7,612
package com.themovie.db.app.model; import static com.themovie.db.app.constants.Constants.IMAGE_URL; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.databinding.BindingAdapter; import com.bumptech.glide.Glide; import com.google.gson.annotations.SerializedName; import java.io.Serializable; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; public class MoviesDTO implements Serializable { @SerializedName("id") private int id; @SerializedName("adult") private boolean adult; @SerializedName("category") private String category; @SerializedName("backdrop_path") private String backdrop_path; @SerializedName("original_language") private String original_language; @SerializedName("original_title") private String original_title; @SerializedName("overview") private String overview; @SerializedName("popularity") private double popularity; @SerializedName("poster_path") private String poster_path; @SerializedName("release_date") private String release_date; @SerializedName("title") private String title; @SerializedName("video") private boolean video; @SerializedName("vote_average") private float vote_average; @SerializedName("vote_count") private int vote_count; @SerializedName("genre_ids") private ArrayList<Integer> genre_ids; @SerializedName("genres") private ArrayList<GenresDTO> genres; @SerializedName("budget") private long budget; @SerializedName("status") private String status; @SerializedName("revenue") private long revenue; @SerializedName("m_genres") private String m_genres; public String getM_genres() { return m_genres; } public void setM_genres(String m_genres) { this.m_genres = m_genres; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public int getId() { return id; } public void setId(int id) { this.id = id; } public boolean isAdult() { return adult; } public void setAdult(boolean adult) { this.adult = adult; } public String getBackdrop_path() { return backdrop_path; } public void setBackdrop_path(String backdrop_path) { this.backdrop_path = backdrop_path; } public String getOriginal_language() { return original_language; } public void setOriginal_language(String original_language) { this.original_language = original_language; } public String getOriginal_title() { return original_title; } public void setOriginal_title(String original_title) { this.original_title = original_title; } public String getOverview() { return overview; } public void setOverview(String overview) { this.overview = overview; } public double getPopularity() { return popularity; } public void setPopularity(double popularity) { this.popularity = popularity; } public String getPoster_path() { return poster_path; } public void setPoster_path(String poster_path) { this.poster_path = poster_path; } public String getRelease_date() { return release_date; } public void setRelease_date(String release_date) { this.release_date = release_date; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public boolean isVideo() { return video; } public void setVideo(boolean video) { this.video = video; } public float getVote_average() { return vote_average; } public void setVote_average(float vote_average) { this.vote_average = vote_average; } public int getVote_count() { return vote_count; } public void setVote_count(int vote_count) { this.vote_count = vote_count; } public ArrayList<Integer> getGenre_ids() { return genre_ids; } public void setGenre_ids(ArrayList<Integer> genre_ids) { this.genre_ids = genre_ids; } public ArrayList<GenresDTO> getGenres() { return genres; } public void setGenres(ArrayList<GenresDTO> genres) { this.genres = genres; } public long getBudget() { return budget; } public void setBudget(long budget) { this.budget = budget; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public long getRevenue() { return revenue; } public void setRevenue(long revenue) { this.revenue = revenue; } @NonNull @Override public String toString() { return "MoviesDTO{" + "id=" + id + ", adult=" + adult + ", backdrop_path='" + backdrop_path + '\'' + ", original_language='" + original_language + '\'' + ", original_title='" + original_title + '\'' + ", overview='" + overview + '\'' + ", popularity=" + popularity + ", poster_path='" + poster_path + '\'' + ", release_date='" + release_date + '\'' + ", title='" + title + '\'' + ", video=" + video + ", vote_average=" + vote_average + ", vote_count=" + vote_count + ", category=" + category + ", genre_ids=" + genre_ids + ", genres=" + genres + ", budget=" + budget + ", status=" + status + ", revenue=" + revenue + ", m_genres=" + m_genres + '}'; } public String convertServerDateToUi(String requestedDate) { String SERVER_FORMAT = "yyyy-MM-dd"; String UI_FORMAT = "MMM dd, yyyy"; if (requestedDate == null) { return "-"; } SimpleDateFormat sourceFormat = new SimpleDateFormat(SERVER_FORMAT, Locale.getDefault()); SimpleDateFormat destFormat = new SimpleDateFormat(UI_FORMAT, Locale.getDefault()); Date date = null; try { date = sourceFormat.parse(requestedDate); } catch (ParseException e) { e.printStackTrace(); } if (date != null) { return destFormat.format(date); } return requestedDate; } public int getVotes(float vote) { return (int) (vote * 10); } @BindingAdapter({"imageUrl"}) public static void loadImage(ImageView view, String imageUrl) { String url = IMAGE_URL + imageUrl; Glide.with(view.getContext()).load(url).into(view); } public String getMovieGenres(String gnr) { StringBuilder sb = new StringBuilder(); if (getGenres() == null) { return gnr; } for (GenresDTO genresDTO : getGenres()) { sb.append(genresDTO.getName()); sb.append(", "); } return "● "+ sb.substring(0, sb.length() - 2); } public String getValues(long value) { DecimalFormat formatter = new DecimalFormat("#,###,###.00"); return formatter.format(value); } }
24.012618
97
0.60155
954dee23e8ad3a595af76572fd525c1e4a7dfbed
1,102
package com.github.thedoghusky.dogmanager; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class Dog { @NotNull @Size(min = 2, max = 28) String name; @NotNull @Size(min = 2, max = 28) String breed; Integer age; Boolean owned; public Dog(String name, String breed, Integer age, Boolean isOwned) { this.name = name; this.breed = breed; this.age = age; this.owned = isOwned; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBreed() { return breed; } public void setBreed(String breed) { this.breed = breed; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Boolean isOwned() { return owned; } public Boolean getOwned() { return owned; } public void setOwned(Boolean isOwned) { this.owned = isOwned; } @Override public String toString() { return "\n--\nINFOS CHIEN - " + name + " \nRace: " + breed + " \n�ge: " + age + " \nA-t-il un Maitre: " + owned; } }
15.305556
114
0.649728
578982b4040c5583bf32d05d8165792d75a223c2
2,044
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class movie { static int n, l; public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new FileReader("movie.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("movie.out"))); StringTokenizer st = new StringTokenizer(f.readLine()); n = Integer.parseInt(st.nextToken()); l = Integer.parseInt(st.nextToken()); Showing[] movies = new Showing[n]; for (int i = 0; i < n; i++) { st = new StringTokenizer(f.readLine()); int d = Integer.parseInt(st.nextToken()); int c = Integer.parseInt(st.nextToken()); movies[i] = new Showing(d, c); for (int j = 0; j < c; j++) { int showtime = Integer.parseInt(st.nextToken()); movies[i].showtimes[j] = showtime; } } int size = (int) Math.pow(2, n); int[] dp = new int[size]; //dp[movies] = latest ending time for (int i = 0; i < size; i++) { //build up int num = i; for (int j = 0; j < n; j++) { if ((num & 1) == 0) { int digit = (int) Math.pow(2, j); int idx = Arrays.binarySearch(movies[j].showtimes, dp[i]); if (idx < 0) { idx += 2; idx *= -1; } if (idx < movies[j].showtimes.length && idx >= 0) { dp[i + digit] = Math.max(dp[i + digit], movies[j].showtimes[idx] + movies[j].dur); } } num = num >> 1; } } int ans = Integer.MAX_VALUE; for (int i = 0; i < size; i++) { if (dp[i] >= l) { ans = Math.min(ans, numOnes(i)); } } if (ans == Integer.MAX_VALUE) ans = -1; out.println(ans); out.close(); } private static int numOnes(int num) { if (num == 0) return 0; return (num & 1) + numOnes(num >> 1); } } class Showing { int dur, numShows; int[] showtimes; public Showing (int dur, int numShows) { this.dur = dur; this.numShows = numShows; showtimes = new int[numShows]; } }
25.234568
89
0.553327
e6a496a1c297e07d5ae69ebdef61095cf225d496
2,105
package ashwin.joshi.xmlxslt.service.impl; import ashwin.joshi.xmlxslt.dao.PdfDocumentDAO; import ashwin.joshi.xmlxslt.exception.BadRequestException; import ashwin.joshi.xmlxslt.exception.DocumentObjectException; import ashwin.joshi.xmlxslt.model.PdfDocument; import ashwin.joshi.xmlxslt.service.PdfDocumentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Optional; @Service public class PdfDocumentServiceImpl implements PdfDocumentService { @Autowired private PdfDocumentDAO dao; @Override @Transactional(readOnly = true) public List<PdfDocument> findAll() { return dao.findAll(); } @Override @Transactional(readOnly = true) public PdfDocument findById(String id) { Optional<PdfDocument> pdf = dao.findById(id); if(!pdf.isPresent()){ throw new DocumentObjectException("Document object with id='"+id+"\' not found."); } return pdf.get(); } @Override @Transactional public PdfDocument create(PdfDocument pdfDocument) { Optional<PdfDocument> pdf = dao.findById(pdfDocument.getId()); if(pdf.isPresent()){ throw new BadRequestException("Document object with id='"+pdfDocument.getId()+"\' already exists."); } return dao.save(pdfDocument); } @Override @Transactional public PdfDocument update(String id, PdfDocument pdfDocument) { Optional<PdfDocument> pdf = dao.findById(id); if(!pdf.isPresent()){ throw new DocumentObjectException("Document object with id='"+id+"\' not found."); } return dao.save(pdfDocument); } @Override @Transactional public void delete(String id) { Optional<PdfDocument> pdf = dao.findById(id); if(!pdf.isPresent()){ throw new DocumentObjectException("Document object with id='"+id+"\' not found."); } dao.delete(pdf.get()); } }
31.41791
112
0.684561
48fc060362e639c4ee4d16a026d4ea7e199f2bd2
883
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ public class LongestUnivaluePath { public int longestUnivaluePath(TreeNode root) { if (root == null) { return 0; } dfs(root, root.val); return res - 1; } int res = 0; int dfs(TreeNode root, int prev) { if (root == null) { return 0; } int left = dfs(root.left, root.val); int right = dfs(root.right, root.val); res = Math.max(res, 1 + left + right); if (prev != root.val) { return 0; } return 1 + Math.max(left, right); } }
22.641026
53
0.524349
e3263b052bd249e33eae0792a4258742e6680c2e
7,736
package com.annaru.upms.entity; import com.annaru.common.util.JacksonUtils; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.extension.activerecord.Model; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.Date; /** * 预约 * * @author xck * @date 2019-05-13 00:50:41 */ @ApiModel(value = "预约") @TableName("order_appointment") public class OrderAppointment extends Model<OrderAppointment> implements Serializable { private static final long serialVersionUID = 1L; /** * 系统编号 */ @ApiModelProperty(value = "系统编号") @TableId(type = IdType.AUTO) private Integer sysId; /** * 定单号 */ @ApiModelProperty(value = "定单号") @TableField("order_no") private String orderNo; /** * 企业编号(分布式体检B端必填) */ @ApiModelProperty(value = "企业编号(分布式体检B端必填)") @TableField("entity_id") private String entityId; /** * 用户编号 */ @ApiModelProperty(value = "用户编号") @TableField("user_id") @NotNull private String userId; private String parentNo; @TableField("extensionItem_id") private Integer extensionItemId; /** * 类别: 1:一般体检预约(C端) 2:进阶体检预约(C端) 3:分布式体检预约(B端) 4:进阶体检预约(B端) 5:家庭医生 6.门诊绿通预约 */ @ApiModelProperty(value = "类别:1:一般体检预约(C端) 2:进阶体检预约(C端) 3:分布式体检预约(B端) 4:进阶体检预约(B端) 5:家庭医生 6.门诊绿通预约") @TableField("appointment_cates") private Integer appointmentCates; /** * 关联编号 */ @ApiModelProperty(value = "关联编号") @TableField("related_no") private String relatedNo; /** * 预约日期 */ @ApiModelProperty(value = "预约日期") @TableField("appoint_date") private Date appointDate; /** * 预约时间 */ @ApiModelProperty(value = "预约时间") @TableField("time_from") private String timeFrom; /** * 预约结束时间 */ @ApiModelProperty(value = "预约结束时间") @TableField("time_to") private String timeTo; /** * 预约地址 */ @ApiModelProperty(value = "预约地址") private String address; /** * 当前状态(0:待确认/1:已确认/2:进行中/3:已完成) */ @ApiModelProperty(value = "当前状态(0:待确认/1:已确认/2:进行中/3:已完成)") private Integer status = 0; /** * 机构编号 */ @ApiModelProperty(value = "机构编号") @TableField("institution_id") private String institutionId; @ApiModelProperty(value = "科室编号") @TableField("department_id") private Integer departmentId; /** * 服务选项(1:护士上门/2:指定地点) */ @ApiModelProperty(value = "服务选项(1:护士上门/2:指定地点)") @TableField("service_option") private Integer serviceOption; /** * 评分 */ @ApiModelProperty(value = "评分") private Double appraisal; /** * 预约取消(0:未取消/1:已取消) */ @ApiModelProperty(value = "预约取消(0:未取消/1:已取消)") @TableField("is_cancelled") private Integer isCancelled = 0; /** * 创建时间 */ @ApiModelProperty(value = "创建时间") @TableField("creation_time") private Date creationTime = new Date(); /** * 创建人 */ @ApiModelProperty(value = "创建人") @TableField("create_by") private String createBy; /** * 编辑时间 */ @ApiModelProperty(value = "编辑时间") @TableField("edit_time") private Date editTime; /** * 编辑人 */ @ApiModelProperty(value = "编辑人") @TableField("edit_by") private String editBy; public Integer getExtensionItemId() { return extensionItemId; } public void setExtensionItemId(Integer extensionItemId) { this.extensionItemId = extensionItemId; } public String getParentNo() { return parentNo; } public void setParentNo(String parentNo) { this.parentNo = parentNo; } public Integer getDepartmentId() { return departmentId; } public void setDepartmentId(Integer departmentId) { this.departmentId = departmentId; } /** * 获取:系统编号 */ public Integer getSysId() { return sysId; } /** * 设置:系统编号 */ public void setSysId(Integer sysId) { this.sysId = sysId; } public Integer getServiceOption() { return serviceOption; } public void setServiceOption(Integer serviceOption) { this.serviceOption = serviceOption; } /** * 获取:定单号 */ public String getOrderNo() { return orderNo; } /** * 设置:定单号 */ public void setOrderNo(String orderNo) { this.orderNo = orderNo; } /** * 获取:企业编号(分布式体检B端必填) */ public String getEntityId() { return entityId; } /** * 设置:企业编号(分布式体检B端必填) */ public void setEntityId(String entityId) { this.entityId = entityId; } /** * 获取:用户编号 */ public String getUserId() { return userId; } /** * 设置:用户编号 */ public void setUserId(String userId) { this.userId = userId; } /** * 获取:类别: 1:一般体检预约(C端) 2:进阶体检预约(C端) 3:分布式体检预约(B端) 4:进阶体检预约(B端) 5:家庭医生 6.门诊绿通预约 */ public Integer getAppointmentCates() { return appointmentCates; } /** * 设置:类别: 1:一般体检预约(C端) 2:进阶体检预约(C端) 3:分布式体检预约(B端) 4:进阶体检预约(B端) 5:家庭医生 6.门诊绿通预约 */ public void setAppointmentCates(Integer appointmentCates) { this.appointmentCates = appointmentCates; } /** * 获取:关联编号 */ public String getRelatedNo() { return relatedNo; } /** * 设置:关联编号 */ public void setRelatedNo(String relatedNo) { this.relatedNo = relatedNo; } /** * 获取:预约日期 */ public Date getAppointDate() { return appointDate; } /** * 设置:预约日期 */ public void setAppointDate(Date appointDate) { this.appointDate = appointDate; } public String getTimeFrom() { return timeFrom; } public void setTimeFrom(String timeFrom) { this.timeFrom = timeFrom; } public String getTimeTo() { return timeTo; } public void setTimeTo(String timeTo) { this.timeTo = timeTo; } /** * 获取:预约地址 */ public String getAddress() { return address; } /** * 设置:预约地址 */ public void setAddress(String address) { this.address = address; } /** * 获取:当前状态(0:待确认/1:已确认/2:进行中/3:已完成) */ public Integer getStatus() { return status; } /** * 设置:当前状态(0:待确认/1:已确认/2:进行中/3:已完成) */ public void setStatus(Integer status) { this.status = status; } /** * 获取:机构编号 */ public String getInstitutionId() { return institutionId; } /** * 设置:机构编号 */ public void setInstitutionId(String institutionId) { this.institutionId = institutionId; } /** * 获取:评分 */ public Double getAppraisal() { return appraisal; } /** * 设置:评分 */ public void setAppraisal(Double appraisal) { this.appraisal = appraisal; } /** * 获取:预约取消(0:未取消/1:已取消) */ public Integer getIsCancelled() { return isCancelled; } /** * 设置:预约取消(0:未取消/1:已取消) */ public void setIsCancelled(Integer isCancelled) { this.isCancelled = isCancelled; } /** * 获取:创建时间 */ public Date getCreationTime() { return creationTime; } /** * 设置:创建时间 */ public void setCreationTime(Date creationTime) { this.creationTime = creationTime; } /** * 获取:创建人 */ public String getCreateBy() { return createBy; } /** * 设置:创建人 */ public void setCreateBy(String createBy) { this.createBy = createBy; } /** * 获取:编辑时间 */ public Date getEditTime() { return editTime; } /** * 设置:编辑时间 */ public void setEditTime(Date editTime) { this.editTime = editTime; } /** * 获取:编辑人 */ public String getEditBy() { return editBy; } /** * 设置:编辑人 */ public void setEditBy(String editBy) { this.editBy = editBy; } @Override protected Serializable pkVal() { return this.sysId; } @Override public String toString() { return JacksonUtils.toJson(this); } }
18.331754
104
0.635988
e92775ce9cc1d66a515b82c2b0f640490e433131
548
package com.hashmap.haf.metadata.config.actors.message.scheduler; import akka.actor.ActorRef; import com.hashmap.haf.metadata.config.model.query.MetadataQuery; import lombok.Getter; public final class CreateJob { @Getter MetadataQuery metadataQuery; @Getter private final ActorRef actor; @Getter private final Object messge; public CreateJob(MetadataQuery metadataQuery, ActorRef actor, Object messge) { this.metadataQuery = metadataQuery; this.actor = actor; this.messge = messge; } }
22.833333
82
0.724453
566825105c66f3dd2b1574308554f99b4be3bb55
2,847
package outbackcdx.auth; import com.nimbusds.jose.JOSEException; import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.jwk.source.JWKSource; import com.nimbusds.jose.jwk.source.RemoteJWKSet; import com.nimbusds.jose.proc.BadJOSEException; import com.nimbusds.jose.proc.JWSVerificationKeySelector; import com.nimbusds.jose.proc.SecurityContext; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.proc.ConfigurableJWTProcessor; import com.nimbusds.jwt.proc.DefaultJWTProcessor; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.util.*; public class JwtAuthorizer implements Authorizer { private final String permsPath; private final ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>(); public JwtAuthorizer(URL jwksUrl, String permsPath) throws MalformedURLException { this(new RemoteJWKSet<>(jwksUrl), permsPath); } JwtAuthorizer(JWKSource<SecurityContext> jwkSource, String permsPath) { this.permsPath = permsPath; jwtProcessor.setJWSKeySelector(new JWSVerificationKeySelector<>(JWSAlgorithm.RS256, jwkSource)); } @SuppressWarnings("unchecked") static List<String> lookup(Map<String,Object> nestedMap, String path) throws AuthException { Object value = nestedMap; for (String segment: path.split("/")) { value = ((Map<String, Object>) value).get(segment); if (value == null) { return Collections.emptyList(); } } return (List<String>) value; } @Override public Permit verify(String authzHeader) throws AuthException { try { if (!authzHeader.regionMatches(true, 0, "bearer ", 0, "bearer ".length())) { return new Permit("anonymous", Collections.emptySet()); } String token = authzHeader.substring("bearer ".length()); JWTClaimsSet claimsSet = jwtProcessor.process(token, null); List<String> roles = lookup(claimsSet.getClaims(), permsPath); EnumSet<Permission> permissions = EnumSet.noneOf(Permission.class); for (String role : roles) { Permission permission; try { permission = Permission.valueOf(role.toUpperCase()); } catch (IllegalArgumentException e) { continue; // ignore unknown permissions I guess } permissions.add(permission); } return new Permit(claimsSet.getStringClaim("preferred_username"), permissions); } catch (ParseException | BadJOSEException | JOSEException e) { e.printStackTrace(); throw new AuthException("Invalid acccess token: " + e.getMessage(), e); } } }
39.541667
104
0.665964
37639132963f288db8e858e5587ab597a52e9fcd
567
/** Ben F Rayfield offers this software opensource MIT license */ package mutable.util.ui; import static mutable.util.Lg.*; import javax.swing.JOptionPane; public class Ask{ public static void ok(String message){ JOptionPane.showMessageDialog(null, message); } public static boolean yesNo(String yesNoQuestion){ int input = JOptionPane.showConfirmDialog(null, yesNoQuestion); // 0=yes, 1=no, 2=cancel return input==0; //TODO remove the Cancel button. Should only be Yes and No. } public static void main(String[] args){ ok("test"); } }
24.652174
65
0.72134
7e59c36546e20f43e09490d5916f2ad776ee2ef2
799
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package class03.exercise.classroom; import javax.swing.JOptionPane; /** * * @author alessandro.jean */ public class Troca { public static void main(String[] args) { double a = Double.parseDouble(JOptionPane.showInputDialog(null, "A:").replace(",", ".")), b = Double.parseDouble(JOptionPane.showInputDialog(null, "B:").replace(",", ".")); a = a * b; b = a / b; a = a / b; /*double c = a; a = b; b = c;*/ JOptionPane.showMessageDialog(null, String.format("A: %.18f\nB: %.18f", a, b)); } }
26.633333
99
0.569462
4f6843c9404c5f0b5db6a07ea8ab0259c8ad9eef
339
package com.aiitec.base.model.comm; import com.aiitec.base.annotation.NoConfound; /** * Where条件 * @param <WHERE> */ @NoConfound public class Table<WHERE>{ public int pa =1; public int li=20; public int ob= 0; public int ot=0; public WHERE where; public Table(WHERE where){ this.where = where; } }
16.142857
45
0.637168
3d198bfd9cbe4885022cd8241422b0d9b0518272
39,944
package org.docksidestage.compatible10x.dbflute.howto; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import org.dbflute.bhv.readable.EntityRowHandler; import org.dbflute.bhv.referrer.ConditionBeanSetupper; import org.dbflute.bhv.referrer.EntityListSetupper; import org.dbflute.bhv.referrer.LoadReferrerOption; import org.dbflute.cbean.paging.numberlink.group.PageGroupBean; import org.dbflute.cbean.paging.numberlink.range.PageRangeBean; import org.dbflute.cbean.result.ListResultBean; import org.dbflute.cbean.result.PagingResultBean; import org.dbflute.cbean.result.grouping.GroupingListDeterminer; import org.dbflute.cbean.result.grouping.GroupingListRowResource; import org.dbflute.cbean.scoping.SpecifyQuery; import org.dbflute.exception.OutsideSqlNotFoundException; import org.dbflute.jdbc.StatementConfig; import org.dbflute.twowaysql.exception.BindVariableCommentNotFoundPropertyException; import org.dbflute.twowaysql.exception.EndCommentNotFoundException; import org.dbflute.twowaysql.exception.IfCommentNotBooleanResultException; import org.dbflute.twowaysql.exception.IfCommentNotFoundPropertyException; import org.dbflute.util.DfCollectionUtil; import org.dbflute.util.DfTypeUtil; import org.docksidestage.compatible10x.dbflute.allcommon.CDef; import org.docksidestage.compatible10x.dbflute.cbean.MemberCB; import org.docksidestage.compatible10x.dbflute.cbean.MemberLoginCB; import org.docksidestage.compatible10x.dbflute.cbean.MemberStatusCB; import org.docksidestage.compatible10x.dbflute.cbean.PurchaseCB; import org.docksidestage.compatible10x.dbflute.exbhv.MemberBhv; import org.docksidestage.compatible10x.dbflute.exbhv.MemberStatusBhv; import org.docksidestage.compatible10x.dbflute.exbhv.PurchaseBhv; import org.docksidestage.compatible10x.dbflute.exbhv.cursor.PurchaseSummaryMemberCursor; import org.docksidestage.compatible10x.dbflute.exbhv.cursor.PurchaseSummaryMemberCursorHandler; import org.docksidestage.compatible10x.dbflute.exbhv.pmbean.PurchaseMaxPriceMemberPmb; import org.docksidestage.compatible10x.dbflute.exbhv.pmbean.PurchaseSummaryMemberPmb; import org.docksidestage.compatible10x.dbflute.exbhv.pmbean.ResolvedPackageNamePmb; import org.docksidestage.compatible10x.dbflute.exbhv.pmbean.SimpleMemberPmb; import org.docksidestage.compatible10x.dbflute.exbhv.pmbean.UnpaidSummaryMemberPmb; import org.docksidestage.compatible10x.dbflute.exentity.Member; import org.docksidestage.compatible10x.dbflute.exentity.MemberLogin; import org.docksidestage.compatible10x.dbflute.exentity.MemberStatus; import org.docksidestage.compatible10x.dbflute.exentity.Product; import org.docksidestage.compatible10x.dbflute.exentity.Purchase; import org.docksidestage.compatible10x.dbflute.exentity.customize.PurchaseMaxPriceMember; import org.docksidestage.compatible10x.dbflute.exentity.customize.SimpleMember; import org.docksidestage.compatible10x.dbflute.exentity.customize.UnpaidSummaryMember; import org.docksidestage.compatible10x.unit.UnitContainerTestCase; /** * @author jflute * @since 0.7.3 (2008/05/31 Saturday) */ public class BehaviorPlatinumTest extends UnitContainerTestCase { // =================================================================================== // Attribute // ========= /** The behavior of Member. (Injection Object) */ private MemberBhv memberBhv; /** The behavior of MemberStatus. (Injection Object) */ private MemberStatusBhv memberStatusBhv; /** The behavior of Purchase. (Injection Object) */ private PurchaseBhv purchaseBhv; // =================================================================================== // Page Select // =========== @SuppressWarnings("deprecation") public void test_selectPage_PageRangeOption_PageGroupOption() { // ## Arrange ## MemberCB cb = new MemberCB(); cb.query().addOrderBy_MemberName_Asc(); // ## Act ## cb.paging(4, 2); PagingResultBean<Member> page2 = memberBhv.selectPage(cb); cb.paging(4, 3); PagingResultBean<Member> page3 = memberBhv.selectPage(cb); // ## Assert ## assertNotSame(0, page3.size()); log("{PageRange}"); { { PageRangeBean pageRange = page2.pageRange(op -> op.rangeSize(2)); boolean existsPre = pageRange.isExistPrePageRange(); boolean existsNext = pageRange.isExistNextPageRange(); log(" page2: " + existsPre + " " + pageRange.createPageNumberList() + " " + existsNext); } { PageRangeBean pageRange = page3.pageRange(op -> op.rangeSize(2)); boolean existsPre = pageRange.isExistPrePageRange(); boolean existsNext = pageRange.isExistNextPageRange(); log(" page3: " + existsPre + " " + pageRange.createPageNumberList() + " " + existsNext); } log("PagingResultBean.toString():" + ln() + " " + page2 + ln() + " " + page3); log(""); } log("{PageRange-fillLimit}"); { { PageRangeBean pageRange = page2.pageRange(op -> op.rangeSize(2).fillLimit()); boolean existsPre = pageRange.isExistPrePageRange(); boolean existsNext = pageRange.isExistNextPageRange(); log(" page2: " + existsPre + " " + pageRange.createPageNumberList() + " " + existsNext); } { PageRangeBean pageRange = page3.pageRange(op -> op.rangeSize(2).fillLimit()); boolean existsPre = pageRange.isExistPrePageRange(); boolean existsNext = pageRange.isExistNextPageRange(); log(" page3: " + existsPre + " " + pageRange.createPageNumberList() + " " + existsNext); } log("PagingResultBean.toString():" + ln() + " " + page2 + ln() + " " + page3); log(""); } log("{PageGroup}"); { { PageGroupBean pageGroup = page2.pageGroup(op -> op.groupSize(2)); boolean existsPre = pageGroup.isExistPrePageGroup(); boolean existsNext = pageGroup.isExistNextPageGroup(); log(" page2: " + existsPre + " " + pageGroup.createPageNumberList() + " " + existsNext); } { PageGroupBean pageGroup = page3.pageGroup(op -> op.groupSize(2)); boolean existsPre = pageGroup.isExistPrePageGroup(); boolean existsNext = pageGroup.isExistNextPageGroup(); log(" page3: " + existsPre + " " + pageGroup.createPageNumberList() + " " + existsNext); } log("PagingResultBean.toString():" + ln() + " " + page2 + ln() + " " + page3); log(""); } } // =================================================================================== // Cursor Select // ============= public void test_selectCursor_EntityRowHandler() { // ## Arrange ## int allCount = memberBhv.selectCount(new MemberCB()); MemberCB cb = new MemberCB(); cb.setupSelect_MemberStatus(); final Set<Integer> memberIdSet = new HashSet<Integer>(); // ## Act ## memberBhv.selectCursor(cb, new EntityRowHandler<Member>() { public void handle(Member entity) { memberIdSet.add(entity.getMemberId()); log(entity.getMemberName() + ", " + entity.getMemberStatus().getMemberStatusName()); } }); // ## Assert ## assertEquals(allCount, memberIdSet.size()); } // =================================================================================== // Load Referrer // ============= public void test_LoadReferrer_setupSelect_Foreign() { // ## Arrange ## final MemberCB cb = new MemberCB(); final ListResultBean<Member> memberList = memberBhv.selectList(cb); // ## Act ## memberBhv.loadPurchaseList(memberList, new ConditionBeanSetupper<PurchaseCB>() { public void setup(PurchaseCB cb) { cb.setupSelect_Product();// *Point! cb.query().addOrderBy_PurchaseCount_Desc(); } }); // ## Assert ## assertFalse(memberList.isEmpty()); for (Member member : memberList) { List<Purchase> purchaseList = member.getPurchaseList(); log("[MEMBER]: " + member.getMemberName()); for (Purchase purchase : purchaseList) { Long purchaseId = purchase.getPurchaseId(); Product product = purchase.getProduct();// *Point! log(" [PURCHASE]: purchaseId=" + purchaseId + ", product=" + product); assertNotNull(product); } } } public void test_LoadReferrer_loadReferrerReferrer() { // ## Arrange ## // A base table is MemberStatus at this test case. MemberStatusCB cb = new MemberStatusCB(); ListResultBean<MemberStatus> memberStatusList = memberStatusBhv.selectList(cb); LoadReferrerOption<MemberCB, Member> loadReferrerOption = new LoadReferrerOption<MemberCB, Member>(); // Member loadReferrerOption.setConditionBeanSetupper(new ConditionBeanSetupper<MemberCB>() { public void setup(MemberCB cb) { cb.query().addOrderBy_FormalizedDatetime_Desc(); } }); // Purchase loadReferrerOption.setEntityListSetupper(new EntityListSetupper<Member>() { public void setup(List<Member> entityList) { memberBhv.loadPurchaseList(entityList, new ConditionBeanSetupper<PurchaseCB>() { public void setup(PurchaseCB cb) { cb.query().addOrderBy_PurchaseCount_Desc(); cb.query().addOrderBy_ProductId_Desc(); } }); } }); // ## Act ## memberStatusBhv.loadMemberList(memberStatusList, loadReferrerOption); // ## Assert ## boolean existsPurchase = false; assertNotSame(0, memberStatusList.size()); for (MemberStatus memberStatus : memberStatusList) { List<Member> memberList = memberStatus.getMemberList(); log("[MEMBER_STATUS]: " + memberStatus.getMemberStatusName()); for (Member member : memberList) { List<Purchase> purchaseList = member.getPurchaseList(); log(" [MEMBER]: " + member.getMemberName() + ", " + member.getFormalizedDatetime()); for (Purchase purchase : purchaseList) { log(" [PURCHASE]: " + purchase.getPurchaseId() + ", " + purchase.getPurchaseCount()); existsPurchase = true; } } log(""); } assertTrue(existsPurchase); } public void test_LoadReferrer_pulloutMember_loadMemberLoginList() { // ## Arrange ## PurchaseCB cb = new PurchaseCB(); cb.setupSelect_Member();// *Point! ListResultBean<Purchase> purchaseList = purchaseBhv.selectList(cb); // ## Act ## List<Member> memberList = purchaseBhv.pulloutMember(purchaseList);// *Point! memberBhv.loadMemberLoginList(memberList, new ConditionBeanSetupper<MemberLoginCB>() { public void setup(MemberLoginCB cb) { cb.query().setMobileLoginFlg_Equal_True(); cb.query().addOrderBy_LoginDatetime_Desc(); } }); // ## Assert ## assertFalse(memberList.isEmpty()); boolean existsMemberLogin = false; log(""); for (Purchase purchase : purchaseList) { Member member = purchase.getMember(); log("[PURCHASE & MEMBER]: " + purchase.getPurchaseId() + ", " + member.getMemberName()); List<MemberLogin> memberLoginList = member.getMemberLoginList(); for (MemberLogin memberLogin : memberLoginList) { log(" [MEMBER_LOGIN]: " + memberLogin); existsMemberLogin = true; } } assertTrue(existsMemberLogin); log(""); boolean existsPurchase = false; for (Member member : memberList) { List<Purchase> backToPurchaseList = member.getPurchaseList(); if (!backToPurchaseList.isEmpty()) { existsPurchase = true; } log("[MEMBER]: " + member.getMemberName()); for (Purchase backToPurchase : backToPurchaseList) { log(" " + backToPurchase); } } assertTrue(existsPurchase); } public void test_LoadReferrer_ousdieSql_paging() { // ## Arrange ## String path = MemberBhv.PATH_selectUnpaidSummaryMember; UnpaidSummaryMemberPmb pmb = new UnpaidSummaryMemberPmb(); pmb.paging(8, 2); Class<UnpaidSummaryMember> entityType = UnpaidSummaryMember.class; PagingResultBean<UnpaidSummaryMember> memberPage = memberBhv.outsideSql().autoPaging().selectPage(path, pmb, entityType); List<Member> domainList = new ArrayList<Member>(); for (UnpaidSummaryMember member : memberPage) { domainList.add(member.prepareDomain()); } // ## Act ## memberBhv.loadPurchaseList(domainList, new ConditionBeanSetupper<PurchaseCB>() { public void setup(PurchaseCB cb) { cb.setupSelect_Product(); cb.query().setPaymentCompleteFlg_Equal_True(); } }); // ## Assert ## boolean exists = false; for (UnpaidSummaryMember member : memberPage) { List<Purchase> purchaseList = member.getPurchaseList(); if (!purchaseList.isEmpty()) { exists = true; } log(member.getUnpaidManName() + ", " + member.getStatusName()); for (Purchase purchase : purchaseList) { log(" " + purchase); } assertTrue(member.getMemberLoginList().isEmpty()); } assertTrue(exists); } // =================================================================================== // Batch Update // ============ public void test_Batch_batchInsert() { // ## Arrange ## List<Member> memberList = new ArrayList<Member>(); { Member member = new Member(); member.setMemberName("testName1"); member.setMemberAccount("testAccount1"); member.setMemberStatusCode_Formalized(); memberList.add(member); } { Member member = new Member(); member.setMemberName("testName2"); member.setMemberAccount("testAccount2"); member.setMemberStatusCode_Provisional(); memberList.add(member); } { Member member = new Member(); member.setMemberName("testName3"); member.setMemberAccount("testAccount3"); member.setMemberStatusCode_Withdrawal(); memberList.add(member); } // ## Act ## int[] result = memberBhv.batchInsert(memberList); // ## Assert ## assertEquals(3, result.length); for (Member member : memberList) { log(member.getMemberId() + member.getMemberName()); } } public void test_Batch_batchUpdate() { // ## Arrange ## List<Integer> memberIdList = new ArrayList<Integer>(); memberIdList.add(1); memberIdList.add(3); memberIdList.add(7); MemberCB cb = new MemberCB(); cb.query().setMemberId_InScope(memberIdList); ListResultBean<Member> memberList = memberBhv.selectList(cb); int count = 0; List<Long> expectedVersionNoList = new ArrayList<Long>(); for (Member member : memberList) { member.setMemberName("testName" + count); member.setMemberAccount("testAccount" + count); member.setMemberStatusCode_Provisional(); member.setFormalizedDatetime(currentTimestamp()); member.setBirthdate(currentTimestamp()); expectedVersionNoList.add(member.getVersionNo()); ++count; } // ## Act ## int[] result = memberBhv.batchUpdate(memberList, new SpecifyQuery<MemberCB>() { public void specify(MemberCB cb) { cb.specify().everyColumn(); } }); // ## Assert ## assertEquals(3, result.length); } public void test_Batch_batchUpdateNonstrict() { // ## Arrange ## List<Integer> memberIdList = new ArrayList<Integer>(); memberIdList.add(1); memberIdList.add(3); memberIdList.add(7); MemberCB cb = new MemberCB(); cb.query().setMemberId_InScope(memberIdList); ListResultBean<Member> memberList = memberBhv.selectList(cb); int count = 0; for (Member member : memberList) { member.setMemberName("testName" + count); member.setMemberAccount("testAccount" + count); member.setMemberStatusCode_Provisional(); member.setFormalizedDatetime(currentTimestamp()); member.setBirthdate(currentTimestamp()); member.setVersionNo(null);// *Point! ++count; } // ## Act ## int[] result = memberBhv.batchUpdateNonstrict(memberList, new SpecifyQuery<MemberCB>() { public void specify(MemberCB cb) { cb.specify().everyColumn(); } }); // ## Assert ## assertEquals(3, result.length); for (Member member : memberList) { assertNull(member.getVersionNo()); } } /** * 排他制御ありバッチ削除: batchDelete(). */ public void test_Batch_batchDelete() { // ## Arrange ## deleteMemberReferrer(); List<Integer> memberIdList = new ArrayList<Integer>(); memberIdList.add(1); memberIdList.add(3); memberIdList.add(7); MemberCB cb = new MemberCB(); cb.query().setMemberId_InScope(memberIdList); ListResultBean<Member> memberList = memberBhv.selectList(cb); // ## Act ## int[] result = memberBhv.batchDelete(memberList); // ## Assert ## assertEquals(3, result.length); // [Description] // A. PreparedStatement.executeBatch()を利用 // --> 大量件数に向いている // // B. Oracleは排他制御できない可能性がある // --> OracleのJDBCドライバが結果件数を正常に戻さないため // // C. すれ違いが発生した場合は例外発生。{EntityAlreadyUpdatedException} // D. 存在しないPK値を指定された場合はすれ違いが発生した場合と同じ。 // --> 排他制御と区別が付かないため } /** * 排他制御なしバッチ削除: batchDeleteNonstrict(). */ public void test_Batch_batchDeleteNonstrict() { // ## Arrange ## deleteMemberReferrer(); List<Member> memberList = new ArrayList<Member>(); { Member member = new Member(); member.setMemberId(1); memberList.add(member); } { Member member = new Member(); member.setMemberId(3); memberList.add(member); } { Member member = new Member(); member.setMemberId(7); memberList.add(member); } // ## Act ## int[] result = memberBhv.batchDeleteNonstrict(memberList); // ## Assert ## assertEquals(3, result.length); // [Description] // A. PreparedStatement.executeBatch()を利用 // --> 大量件数に向いている // // B. 存在しないPK値を指定された場合は例外発生。{EntityAlreadyDeletedException} } // =================================================================================== // OutsideSql // ========== // ----------------------------------------------------- // List // ---- // /- - - - - - - - - - - - - - - - - - - - - - - - - - - // 基本的なselectList()に関しては、BehaviorBasicTestにて // - - - - - - - - - -/ // /- - - - - - - - - - - - - - - - - - - - - - - - - - - // 中級的なselectList()に関しては、BehaviorMiddleTestにて // - - - - - - - - - -/ /** * 外だしSQLでBehaviorQueryPathのSubDirectory機能を利用: PATH_xxx_selectXxx. * exbhv配下の任意のSubDirectory(SubPackage)にSQLファイルを配置して利用することが可能。 * SQLファイルの数があまりに膨大になる場合は、テーブルのカテゴリ毎にDirectoryを作成して、 * 適度にSQLファイルをカテゴリ分けすると良い。 */ public void test_outsideSql_selectList_selectSubDirectory() { // ## Arrange ## // SQLのパス String path = MemberBhv.PATH_subdirectory_selectSubDirectoryCheck; // 検索条件 SimpleMemberPmb pmb = new SimpleMemberPmb(); pmb.setMemberName_PrefixSearch("S"); // 戻り値Entityの型 Class<SimpleMember> entityType = SimpleMember.class; // ## Act ## // SQL実行! List<SimpleMember> resultList = memberBhv.outsideSql().selectList(path, pmb, entityType); // ## Assert ## assertNotSame(0, resultList.size()); log("{SimpleMember}"); for (SimpleMember entity : resultList) { Integer memberId = entity.getMemberId(); String memberName = entity.getMemberName(); String memberStatusName = entity.getMemberStatusName(); log(" " + memberId + ", " + memberName + ", " + memberStatusName); assertNotNull(memberId); assertNotNull(memberName); assertNotNull(memberStatusName); assertTrue(memberName.startsWith("S")); } } // ----------------------------------------------------- // Cursor // ------ /** * 外だしSQLでカーソルの使った検索(大量件数対策): outsideSql().cursorHandling().selectCursor(). * 実処理は、MemberBhv#makeCsvPurchaseSummaryMember()にて実装しているのでそちらを参照。 * <pre> * Entity定義にて以下のようにオプション「+cursor+」を付けることにより、タイプセーフカーソルが利用可能。 * -- #PurchaseSummaryMember# * -- +cursor+ * </pre> */ public void test_outsideSql_selectCursor_makeCsvSummaryMember_selectPurchaseSummaryMember() { // ## Arrange ## PurchaseSummaryMemberPmb pmb = new PurchaseSummaryMemberPmb(); pmb.setMemberStatusCode_Formalized(); pmb.setFormalizedDatetime(DfTypeUtil.toTimestamp("2003-08-12 12:34:56.147")); // ## Act & Assert ## memberBhv.makeCsvPurchaseSummaryMember(pmb); } // ----------------------------------------------------- // FOR Comment // ----------- /** * 外だしSQLでFORコメントを使った検索(where句の先頭、and連結): FOR pmb.xxxList, NEXT */ public void test_outsideSql_forComment_nextAnd() { // ## Arrange ## String path = MemberBhv.PATH_selectPurchaseSummaryMember; PurchaseSummaryMemberPmb pmb = new PurchaseSummaryMemberPmb(); pmb.setMemberNameList_ContainSearch(DfCollectionUtil.newArrayList("S", "v")); // ## Act & Assert ## final Set<String> existsSet = DfCollectionUtil.newHashSet(); memberBhv.outsideSql().cursorHandling().selectCursor(path, pmb, new PurchaseSummaryMemberCursorHandler() { public Object fetchCursor(PurchaseSummaryMemberCursor cursor) throws SQLException { while (cursor.next()) { existsSet.add("exists"); final Integer memberId = cursor.getMemberId(); final String memberName = cursor.getMemberName(); final Date birthdate = cursor.getBirthdate(); final String c = ", "; log(memberId + c + memberName + c + birthdate); if (!memberName.contains("S") || !memberName.contains("v")) { fail("memberName should have S and v: " + memberName); } } return null; } }); assertTrue(existsSet.contains("exists")); } /** * 外だしSQLでFORコメントを使った検索(二番目以降、or連結): FOR pmb.xxxList. FIRST, NEXT, LAST */ public void test_outsideSql_forComment_nextOr() { // ## Arrange ## String path = MemberBhv.PATH_selectPurchaseMaxPriceMember; PurchaseMaxPriceMemberPmb pmb = new PurchaseMaxPriceMemberPmb(); //pmb.setMemberId(3); pmb.setMemberNameList_PrefixSearch(DfCollectionUtil.newArrayList("S", "M")); Class<PurchaseMaxPriceMember> entityType = PurchaseMaxPriceMember.class; // ## Act ## int pageSize = 3; pmb.paging(pageSize, 1); // 1st page PagingResultBean<PurchaseMaxPriceMember> page1 = memberBhv.outsideSql().manualPaging().selectPage(path, pmb, entityType); // ## Assert ## assertNotSame(0, page1.size()); for (PurchaseMaxPriceMember member : page1) { log(member); String memberName = member.getMemberName(); if (!memberName.contains("S") && !memberName.contains("M")) { fail("memberName should have S or M: " + memberName); } } } // ----------------------------------------------------- // Statement Config // ---------------- /** * 外だしSQLでStatementのコンフィグを設定: outsideSql().configure(statementConfig). */ public void test_outsideSql_configure() { // ## Arrange ## // SQLのパス String path = MemberBhv.PATH_selectSimpleMember; // 検索条件 SimpleMemberPmb pmb = new SimpleMemberPmb(); pmb.setMemberName_PrefixSearch("S"); // 戻り値Entityの型 Class<SimpleMember> entityType = SimpleMember.class; // コンフィグ StatementConfig statementConfig = new StatementConfig().typeForwardOnly().queryTimeout(7).maxRows(2); // ## Act ## // SQL実行! List<SimpleMember> memberList = memberBhv.outsideSql().configure(statementConfig).selectList(path, pmb, entityType); // ## Assert ## assertFalse(memberList.isEmpty()); assertEquals(2, memberList.size()); log("{SimpleMember}"); for (SimpleMember entity : memberList) { Integer memberId = entity.getMemberId(); String memberName = entity.getMemberName(); String memberStatusName = entity.getMemberStatusName(); log(" " + memberId + ", " + memberName + ", " + memberStatusName); assertNotNull(memberId); assertNotNull(memberName); assertNotNull(memberStatusName); assertTrue(memberName.startsWith("S")); } } // ----------------------------------------------------- // ParameterBean ResolvePackage // ---------------------------- public void test_outsideSql_selectResolvedPackageName() { // ## Arrange ## // SQLのパス String path = MemberBhv.PATH_whitebox_pmbean_selectResolvedPackageName; // 検索条件 ResolvedPackageNamePmb pmb = new ResolvedPackageNamePmb(); pmb.setDate1(new java.util.Date()); // java.util.Dateで検索できることを確認 List<String> statusList = new ArrayList<String>(); statusList.add(CDef.MemberStatus.Formalized.code()); statusList.add(CDef.MemberStatus.Withdrawal.code()); pmb.setList1(statusList); // java.util.Listで検索できることを確認 // 戻り値Entityの型 Class<Member> entityType = Member.class; // ## Act ##ß // SQL実行! List<Member> memberList = memberBhv.outsideSql().selectList(path, pmb, entityType); // ## Assert ## assertFalse(memberList.isEmpty()); // [Description] // A. ListやDateなど良く利用されるクラスのPackageを自動で解決する。 // そのためParameterBeanの宣言でパッケージ名を記述する必要はない。 // -- !BigDecimal bigDecimal1! *java.math.BigDecimal // -- !Date bigDecimal1! *java.util.Date // -- !Time bigDecimal1! *java.sql.Time // -- !Timestamp bigDecimal1! *java.sql.Timestamp // -- !List<String> list1! * java.util.List<> // -- !Map<String, String> map1! * java.util.Map<> } // ----------------------------------------------------- // NotFound // -------- /** * 外だしSQLでSQLファイルが見つからないときの挙動とメッセージ: OutsideSqlNotFoundException. * 専用メッセージは開発者がデバッグしやすいように。 */ public void test_outsideSql_NotFound() { try { memberBhv.outsideSql().selectList("sql/noexist/selectByNoExistSql.sql", null, Member.class); fail(); } catch (OutsideSqlNotFoundException e) { log(e.getMessage()); } } // ----------------------------------------------------- // Wrong Comment // ------------- /** * 外だしSQLで間違ったバインド変数コメントの場合の挙動と専用メッセージ: BindVariableCommentNotFoundPropertyException. * 専用メッセージは開発者がデバッグしやすいように。 */ public void test_outsideSql_BindVariableNotFoundProperty() { try { String path = MemberBhv.PATH_whitebox_wrongexample_selectBindVariableNotFoundProperty; UnpaidSummaryMemberPmb pmb = new UnpaidSummaryMemberPmb(); pmb.setMemberName_PrefixSearch("S"); memberBhv.outsideSql().selectList(path, pmb, Member.class); fail(); } catch (BindVariableCommentNotFoundPropertyException e) { log(e.getMessage()); assertTrue(e.getMessage().contains("wrongMemberId")); } } /** * 外だしSQLでENDコメントがない場合の挙動と専用メッセージ: EndCommentNotFoundException. * 専用メッセージは極力開発者がデバッグしやすいように。 */ public void test_outsideSql_EndCommentNotFound() { try { String path = MemberBhv.PATH_whitebox_wrongexample_selectEndCommentNotFound; UnpaidSummaryMemberPmb pmb = new UnpaidSummaryMemberPmb(); pmb.setMemberName_PrefixSearch("S"); memberBhv.outsideSql().selectList(path, pmb, Member.class); fail(); } catch (EndCommentNotFoundException e) { log(e.getMessage()); } } /** * 外だしSQLでBooleanでないIFコメントの場合の挙動と専用メッセージ: IfCommentNotBooleanResultException. * 専用メッセージは極力開発者がデバッグしやすいように。 */ public void test_outsideSql_IfCommentNotBooleanResult() { try { String path = MemberBhv.PATH_whitebox_wrongexample_selectIfCommentNotBooleanResult; UnpaidSummaryMemberPmb pmb = new UnpaidSummaryMemberPmb(); pmb.setMemberName_PrefixSearch("S"); memberBhv.outsideSql().selectList(path, pmb, Member.class); fail(); } catch (IfCommentNotBooleanResultException e) { log(e.getMessage()); } } /** * 外だしSQLで間違ったIFコメントの場合の挙動と専用メッセージ: IfCommentWrongExpressionException. * 専用メッセージは極力開発者がデバッグしやすいように。 */ public void test_outsideSql_IfCommentWrongExpression() { try { String path = MemberBhv.PATH_whitebox_wrongexample_selectIfCommentWrongExpression; UnpaidSummaryMemberPmb pmb = new UnpaidSummaryMemberPmb(); pmb.setMemberName_PrefixSearch("S"); memberBhv.outsideSql().selectList(path, pmb, Member.class); fail(); } catch (IfCommentNotFoundPropertyException e) { log(e.getMessage()); if (!e.getMessage().contains("wrongMemberId")) { fail(); } } } // =================================================================================== // Common Column // ============= /** * 共通カラムの自動設定を無視して明示的に登録(or 更新): disableCommonColumnAutoSetup(). */ public void test_insert_disableCommonColumnAutoSetup() { // ## Arrange ## Timestamp expectedTimestamp = new Timestamp(currentTimestamp().getTime() - 10000000000l); Member member = new Member(); member.setMemberName("Billy Joel"); member.setMemberAccount("martinjoel"); member.setBirthdate(currentUtilDate()); member.setFormalizedDatetime(currentTimestamp()); member.setMemberStatusCode_Formalized(); member.setRegisterDatetime(expectedTimestamp); member.setRegisterUser("suppressRegisterUser"); member.setUpdateDatetime(expectedTimestamp); member.setUpdateUser("suppressUpdateUser"); // ## Act ## memberBhv.varyingInsert(member, op -> op.disableCommonColumnAutoSetup()); // ## Assert ## final MemberCB cb = new MemberCB(); cb.acceptPrimaryKeyMap(member.asDBMeta().extractPrimaryKeyMap(member)); final Member actualMember = memberBhv.selectEntityWithDeletedCheck(cb); final Timestamp registerDatetime = actualMember.getRegisterDatetime(); final String registerUser = actualMember.getRegisterUser(); final Timestamp updateDatetime = actualMember.getUpdateDatetime(); final String updateUser = actualMember.getUpdateUser(); log("registerDatetime = " + registerDatetime); assertNotNull(registerDatetime); assertEquals(expectedTimestamp, registerDatetime); log("registerUser = " + registerUser); assertNotNull(registerUser); assertEquals("suppressRegisterUser", registerUser); log("updateDatetime = " + updateDatetime); assertNotNull(updateDatetime); assertEquals(expectedTimestamp, updateDatetime); log("updateUser = " + updateUser); assertNotNull(updateUser); assertEquals("suppressUpdateUser", updateUser); } // =================================================================================== // Paging Re-Select // ================ /** * ページングの超過ページ番号での検索時の再検索を無効化(ConditionBean): disablePagingReSelect(). */ public void test_conditionBean_paging_disablePagingReSelect() { // ## Arrange ## MemberCB cb = new MemberCB(); cb.query().addOrderBy_MemberName_Asc(); cb.paging(4, 99999); cb.disablePagingReSelect(); // ## Act ## PagingResultBean<Member> page99999 = memberBhv.selectPage(cb); // ## Assert ## assertTrue(page99999.isEmpty()); } /** * ページングの超過ページ番号での検索時の再検索を無効化(OutsideSql): disablePagingReSelect(). */ public void test_outsideSql_paging_disablePagingReSelect() { // ## Arrange ## // SQLのパス String path = MemberBhv.PATH_selectUnpaidSummaryMember; // 検索条件 UnpaidSummaryMemberPmb pmb = new UnpaidSummaryMemberPmb(); pmb.setMemberStatusCode_Formalized();// 正式会員 pmb.disablePagingReSelect(); // 戻り値Entityの型 Class<UnpaidSummaryMember> entityType = UnpaidSummaryMember.class; // ## Act ## // SQL実行! int pageSize = 3; pmb.paging(pageSize, 99999); PagingResultBean<UnpaidSummaryMember> page99999 = memberBhv.outsideSql().autoPaging().selectPage(path, pmb, entityType); // ## Assert ## assertTrue(page99999.isEmpty()); } // =================================================================================== // ListResultBean // ============== /** * Entityリストの件数ごとのグルーピング: ListResultBean.groupingList(). * 会員リストを3件ずつのグループリストにする。 */ public void test_selectList_ListResultBean_groupingList_count() { // ## Arrange ## MemberCB cb = new MemberCB(); cb.query().addOrderBy_MemberName_Asc(); ListResultBean<Member> memberList = memberBhv.selectList(cb); log("ListResultBean.toString():" + ln() + " " + memberList); // ## Act ## List<ListResultBean<Member>> groupingList = memberList.groupingList(new GroupingListDeterminer<Member>() { public boolean isBreakRow(GroupingListRowResource<Member> rowResource, Member nextEntity) { return rowResource.getNextIndex() >= 3; } }); // ## Assert ## assertFalse(groupingList.isEmpty()); int rowIndex = 0; for (List<Member> elementList : groupingList) { assertTrue(elementList.size() <= 3); log("[" + rowIndex + "]"); for (Member member : elementList) { log(" " + member); } ++rowIndex; } } /** * Entityリストのグルーピング(コントロールブレイク): ListResultBean.groupingList(), determine(). * 会員リストを会員名称の先頭文字ごとのグループリストにする。 * @since 0.8.2 */ public void test_selectList_ListResultBean_groupingList_determine() { // ## Arrange ## MemberCB cb = new MemberCB(); cb.query().addOrderBy_MemberName_Asc(); ListResultBean<Member> memberList = memberBhv.selectList(cb); log("ListResultBean.toString():" + ln() + " " + memberList); // ## Act ## List<ListResultBean<Member>> groupingList = memberList.groupingList(new GroupingListDeterminer<Member>() { public boolean isBreakRow(GroupingListRowResource<Member> rowResource, Member nextEntity) { Member currentEntity = rowResource.getCurrentEntity(); String currentInitChar = currentEntity.getMemberName().substring(0, 1); String nextInitChar = nextEntity.getMemberName().substring(0, 1); return !currentInitChar.equalsIgnoreCase(nextInitChar); } }); // ## Assert ## assertFalse(groupingList.isEmpty()); int entityCount = 0; for (List<Member> elementList : groupingList) { String currentInitChar = null; for (Member member : elementList) { if (currentInitChar == null) { currentInitChar = member.getMemberName().substring(0, 1); log("[" + currentInitChar + "]"); } log(" " + member.getMemberName() + ", " + member); assertEquals(currentInitChar, member.getMemberName().substring(0, 1)); ++entityCount; } } assertEquals(memberList.size(), entityCount); } }
41.307135
129
0.562062
8ec04f007f72848cf8f820e1d104e56ed4e09489
310
package com.ttkey.service.mixers.model; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString(callSuper = true) public class HttpRequest extends HttpOperation { private String baseUri; public Object getRequestBody() { return super.getBody(); } }
17.222222
48
0.735484
5bde8c55da104b6975853bfe0691fe200f9a7c5b
863
package com.msp.invoice.gateway; import cc.blynk.clickhouse.BalancedClickhouseDataSource; import cc.blynk.clickhouse.settings.ClickHouseProperties; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ClickhouseConfig { @Bean @ConfigurationProperties(prefix = "db.clickhouse") public ClickHouseProperties clickHouseProperties() { return new ClickHouseProperties(); } @Bean public BalancedClickhouseDataSource chDataSource( @Value("${db.clickhouse.url}") String url, ClickHouseProperties properties ) { return new BalancedClickhouseDataSource(url, properties); } }
31.962963
75
0.771727
12559008485663b206a815ff8c0ff27560c49c2a
3,685
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See License.txt in the repository root. package com.microsoft.tfs.util.listeners; import junit.framework.TestCase; public class StandardListenerListTest extends TestCase { private StandardListenerList list; @Override public void setName(final String name) { super.setName(name); list = new StandardListenerList(); } public void testAdd() { final Listener l1 = new Listener(); final Listener l2 = new Listener(); assertEquals(0, list.size()); assertTrue(list.addListener(l1)); assertEquals(1, list.size()); assertFalse(list.addListener(l1)); assertEquals(1, list.size()); assertTrue(list.addListener(l2)); assertEquals(2, list.size()); final Object[] listeners = list.getListeners(); assertNotNull(listeners); assertEquals(2, listeners.length); } public void testRemove() { final Listener l1 = new Listener(); final Listener l2 = new Listener(); list.addListener(l1); assertFalse(list.removeListener(l2)); assertEquals(1, list.size()); assertTrue(list.removeListener(l1)); assertEquals(0, list.size()); list.addListener(l1); list.addListener(l2); assertTrue(list.removeListener(l2)); assertTrue(list.removeListener(l1)); assertEquals(0, list.size()); } public void testContains() { final Listener l1 = new Listener(); final Listener l2 = new Listener(); assertFalse(list.containsListener(l1)); list.addListener(l1); assertTrue(list.containsListener(l1)); assertFalse(list.containsListener(l2)); list.addListener(l2); assertTrue(list.containsListener(l1)); assertTrue(list.containsListener(l2)); list.removeListener(l1); list.removeListener(l2); assertFalse(list.containsListener(l1)); assertFalse(list.containsListener(l2)); } public void testClear() { assertFalse(list.clear()); final Listener l1 = new Listener(); final Listener l2 = new Listener(); list.addListener(l1); list.addListener(l2); assertTrue(list.clear()); assertEquals(0, list.size()); } public void testGetListeners() { final Listener l1 = new Listener(); final Listener l2 = new Listener(); list.addListener(l1); list.addListener(l2); final Object[] o1 = list.getListeners(); final Object[] o2 = list.getListeners(new Listener[list.size()]); assertEquals(2, o1.length); assertEquals(2, o2.length); assertTrue(o2 instanceof Listener[]); assertTrue(o1[0] == l1 || o1[1] == l1); assertTrue(o1[0] == l2 || o1[1] == l2); assertTrue(o2[0] == l1 || o2[1] == l1); assertTrue(o2[0] == l2 || o2[1] == l2); } public void testForeach() { final Listener l1 = new Listener(); final Listener l2 = new Listener(); list.addListener(l1); list.addListener(l2); list.foreachListener(new ListenerRunnable() { @Override public boolean run(final Object listener) throws Exception { ((Listener) listener).onEvent(); return true; } }); assertEquals(1, l1.notifyCount); assertEquals(1, l2.notifyCount); } private static class Listener { public int notifyCount = 0; public void onEvent() { ++notifyCount; } } }
26.510791
74
0.595387
c859d96cf5a5964d9d8ac3ad34f3648ae9f4b73e
5,317
/** * Copyright (C) 2014 Xillio (support@xillio.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.xillio.xill.plugins.jdbc.constructs; import com.google.inject.Inject; import com.google.inject.name.Named; import nl.xillio.xill.api.components.MetaExpression; import nl.xillio.xill.api.construct.Argument; import nl.xillio.xill.api.construct.Construct; import nl.xillio.xill.api.construct.ConstructContext; import nl.xillio.xill.api.construct.ConstructProcessor; import nl.xillio.xill.api.errors.RobotRuntimeException; import nl.xillio.xill.plugins.jdbc.data.ConnectionWrapper; import nl.xillio.xill.plugins.jdbc.services.ConnectionFactory; import java.net.URL; import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLInvalidAuthorizationSpecException; import java.util.Map; /** * This construct represents the generic implementation for a construct that connects to a database system. * To connect to a system this construct requires a connection factory that builds connections for the specific * database system. * <p> * Generally the only parameter of this construct is a connectionString (jdbc url). However you can easily override * the buildArguments() method to add more. All the arguments are forwarded to the connection factory. * <p> * The main responsibility for this construct is the handle exceptions that occur while building the connection. * <p> * You can optionally provide a docRoot. If you do then the documentation for this construct will be fetched from * <code>docRoot + getClass().getSimpleName() + ".xml"</code> instead of the default documentation location. * * @author Thomas Biesaart * @since 1.0.0 */ public class ConnectConstruct extends Construct { private final ConnectionFactory connectionFactory; private final String docRoot; @Inject public ConnectConstruct(ConnectionFactory connectionFactory, @Named("docRoot") String docRoot) { this.connectionFactory = connectionFactory; this.docRoot = docRoot; } @Override public ConstructProcessor prepareProcess(ConstructContext context) { return new ConstructProcessor( args -> process(context, args), buildArguments() ); } /** * This method will provide an array of arguments for this construct. You can overload it to add more parameters to * your construct. * * @return an array containing the arguments for this construct */ @SuppressWarnings("squid:S2095") // Suppress "Resources should be closed": Arguments do not need to be closed here, because ConstructProcessor closes them protected Argument[] buildArguments() { return new Argument[]{ new Argument("connectionString", ATOMIC) }; } /** * Extract a connection string from the inputs. * * @param arguments the inputs * @return the connection string */ protected String getConnectionString(MetaExpression... arguments) { return arguments[0].getStringValue(); } /** * Extract options from the inputs if they are available. * * @param arguments the inputs * @return an options map or null */ protected Map<String, MetaExpression> getOptions(MetaExpression... arguments) { if (arguments.length > 1 && arguments[1].getType() == OBJECT) { return arguments[1].getValue(); } return null; } private MetaExpression process(ConstructContext context, MetaExpression... arguments) { String connectionString = getConnectionString(arguments); Map<String, MetaExpression> options = getOptions(arguments); Connection connection = buildConnection(context, connectionString, options); MetaExpression result = fromValue("[SQL Connection]"); result.storeMeta(new ConnectionWrapper(connection)); return result; } private Connection buildConnection(ConstructContext context, String connectionString, Map<String, MetaExpression> options) { try { return connectionFactory.createAndStore(context, connectionString, options); } catch (SQLInvalidAuthorizationSpecException e) { throw new RobotRuntimeException(e.getMessage(), e); } catch (SQLException e) { throw new RobotRuntimeException("Could not connect to db: " + e.getMessage(), e); } } @Override public URL getDocumentationResource() { if (docRoot != null) { String stringUrl = docRoot + getClass().getSimpleName() + ".xml"; URL url = getClass().getResource(stringUrl); if (url != null) { return url; } } return super.getDocumentationResource(); } }
38.251799
128
0.700771
52cf98c6645e682373bb06a464306ed0ad619971
3,101
/* * Copyright (c) 2020 Siemens AG * * 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. * * SPDX-License-Identifier: Apache-2.0 */ package com.siemens.pki.lightweightcmpra.cryptoservices; import java.io.IOException; import org.bouncycastle.asn1.cms.EnvelopedData; import org.bouncycastle.asn1.cms.SignedData; import org.bouncycastle.cms.CMSAlgorithm; import org.bouncycastle.cms.CMSEnvelopedData; import org.bouncycastle.cms.CMSEnvelopedDataGenerator; import org.bouncycastle.cms.CMSException; import org.bouncycastle.cms.CMSProcessableByteArray; import org.bouncycastle.cms.RecipientInfoGenerator; import org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder; /** * * base class for CMS data encryption * */ public class CmsEncryptorBase { private final CMSEnvelopedDataGenerator envGen = new CMSEnvelopedDataGenerator(); protected CmsEncryptorBase() { } protected void addRecipientInfoGenerator( final RecipientInfoGenerator recipientGenerator) { envGen.addRecipientInfoGenerator(recipientGenerator); } /** * encrypt the data * * @param msg * data to encrypt * @return encrypted data * * @throws CMSException * in case of an CMS processing error */ public EnvelopedData encrypt(final byte[] msg) throws CMSException { final CMSEnvelopedData cmsEnvData = envGen.generate( new CMSProcessableByteArray(msg), new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES256_CBC) .setProvider(CertUtility.BOUNCY_CASTLE_PROVIDER) .build()); return EnvelopedData .getInstance(cmsEnvData.toASN1Structure().getContent()); } /** * encrypt the data * * @param data * signed data to encrypt * @return encrypted data * @throws CMSException * in case of an CMS processing error * @throws IOException * in case of ASN.1 encoding error */ public EnvelopedData encrypt(final SignedData data) throws CMSException, IOException { final CMSEnvelopedData cmsEnvData = envGen.generate( new CMSProcessableByteArray(data.getEncoded()), new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES256_CBC) .setProvider(CertUtility.BOUNCY_CASTLE_PROVIDER) .build()); return EnvelopedData .getInstance(cmsEnvData.toASN1Structure().getContent()); } }
33.344086
77
0.674299
96590ba7af55ab2f9c098db2745d1192f3c9c319
872
package io.fabric8.servicecatalog.demo; import io.fabric8.servicecatalog.api.model.ServiceBroker; import io.fabric8.servicecatalog.api.model.ServiceBrokerBuilder; import io.fabric8.servicecatalog.client.DefaultServiceCatalogClient; import io.fabric8.servicecatalog.client.ServiceCatalogClient; public class BrokerCreateOrReplace { public static void main(String[] args) { try (ServiceCatalogClient client = new DefaultServiceCatalogClient()) { ServiceBroker serviceBroker = new ServiceBrokerBuilder() .withNewMetadata().withName("broker1").endMetadata() .withNewSpec() .withUrl("http://bestdatabase.example.com") .endSpec() .build(); client.serviceBrokers().inNamespace("myproject").createOrReplace(serviceBroker); } } }
39.636364
92
0.680046
c1d74ff8da4933c94056bea086823a85e7fee53f
1,461
/* * Copyright (c) 2014, Inversoft Inc., All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package org.savantbuild.domain; import org.savantbuild.BaseUnitTest; import org.savantbuild.dep.domain.License; import org.savantbuild.dep.domain.ReifiedArtifact; import org.savantbuild.dep.domain.Version; import org.savantbuild.util.MapBuilder; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; /** * Tests the project domain. * * @author Brian Pontarelli */ public class ProjectTest extends BaseUnitTest { @Test public void toArtifact() { Project project = new Project(projectDir, output); project.group = "group"; project.name = "name"; project.version = new Version("1.1.1"); project.licenses.put(License.BSD_2_Clause, null); assertEquals(project.toArtifact(), new ReifiedArtifact("group:name:name:1.1.1:jar", MapBuilder.simpleMap(License.BSD_2_Clause, null))); } }
33.976744
139
0.747433
4bd647338034f962e2f3d204b109d3ebd422301a
9,392
/* * InfluxDB OSS API Service * The InfluxDB v2 API provides a programmatic interface for all interactions with InfluxDB. Access the InfluxDB API using the `/api/v2/` endpoint. * * OpenAPI spec version: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.influxdb.client.domain; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.influxdb.client.domain.Label; import com.influxdb.client.domain.NotificationEndpointBaseLinks; import com.influxdb.client.domain.NotificationEndpointType; import java.io.IOException; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.List; /** * NotificationEndpointBase */ public class NotificationEndpointBase { public static final String SERIALIZED_NAME_ID = "id"; @SerializedName(SERIALIZED_NAME_ID) private String id; public static final String SERIALIZED_NAME_ORG_I_D = "orgID"; @SerializedName(SERIALIZED_NAME_ORG_I_D) private String orgID; public static final String SERIALIZED_NAME_USER_I_D = "userID"; @SerializedName(SERIALIZED_NAME_USER_I_D) private String userID; public static final String SERIALIZED_NAME_CREATED_AT = "createdAt"; @SerializedName(SERIALIZED_NAME_CREATED_AT) private OffsetDateTime createdAt; public static final String SERIALIZED_NAME_UPDATED_AT = "updatedAt"; @SerializedName(SERIALIZED_NAME_UPDATED_AT) private OffsetDateTime updatedAt; public static final String SERIALIZED_NAME_DESCRIPTION = "description"; @SerializedName(SERIALIZED_NAME_DESCRIPTION) private String description; public static final String SERIALIZED_NAME_NAME = "name"; @SerializedName(SERIALIZED_NAME_NAME) private String name; /** * The status of the endpoint. */ @JsonAdapter(StatusEnum.Adapter.class) public enum StatusEnum { ACTIVE("active"), INACTIVE("inactive"); private String value; StatusEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static StatusEnum fromValue(String text) { for (StatusEnum b : StatusEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } public static class Adapter extends TypeAdapter<StatusEnum> { @Override public void write(final JsonWriter jsonWriter, final StatusEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public StatusEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return StatusEnum.fromValue(String.valueOf(value)); } } } public static final String SERIALIZED_NAME_STATUS = "status"; @SerializedName(SERIALIZED_NAME_STATUS) private StatusEnum status = StatusEnum.ACTIVE; public static final String SERIALIZED_NAME_LABELS = "labels"; @SerializedName(SERIALIZED_NAME_LABELS) private List<Label> labels = new ArrayList<>(); public static final String SERIALIZED_NAME_LINKS = "links"; @SerializedName(SERIALIZED_NAME_LINKS) private NotificationEndpointBaseLinks links = null; public static final String SERIALIZED_NAME_TYPE = "type"; @SerializedName(SERIALIZED_NAME_TYPE) private NotificationEndpointType type = null; public NotificationEndpointBase id(String id) { this.id = id; return this; } /** * Get id * @return id **/ public String getId() { return id; } public void setId(String id) { this.id = id; } public NotificationEndpointBase orgID(String orgID) { this.orgID = orgID; return this; } /** * Get orgID * @return orgID **/ public String getOrgID() { return orgID; } public void setOrgID(String orgID) { this.orgID = orgID; } public NotificationEndpointBase userID(String userID) { this.userID = userID; return this; } /** * Get userID * @return userID **/ public String getUserID() { return userID; } public void setUserID(String userID) { this.userID = userID; } /** * Get createdAt * @return createdAt **/ public OffsetDateTime getCreatedAt() { return createdAt; } /** * Get updatedAt * @return updatedAt **/ public OffsetDateTime getUpdatedAt() { return updatedAt; } public NotificationEndpointBase description(String description) { this.description = description; return this; } /** * An optional description of the notification endpoint. * @return description **/ public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public NotificationEndpointBase name(String name) { this.name = name; return this; } /** * Get name * @return name **/ public String getName() { return name; } public void setName(String name) { this.name = name; } public NotificationEndpointBase status(StatusEnum status) { this.status = status; return this; } /** * The status of the endpoint. * @return status **/ public StatusEnum getStatus() { return status; } public void setStatus(StatusEnum status) { this.status = status; } public NotificationEndpointBase labels(List<Label> labels) { this.labels = labels; return this; } public NotificationEndpointBase addLabelsItem(Label labelsItem) { if (this.labels == null) { this.labels = new ArrayList<>(); } this.labels.add(labelsItem); return this; } /** * Get labels * @return labels **/ public List<Label> getLabels() { return labels; } public void setLabels(List<Label> labels) { this.labels = labels; } public NotificationEndpointBase links(NotificationEndpointBaseLinks links) { this.links = links; return this; } /** * Get links * @return links **/ public NotificationEndpointBaseLinks getLinks() { return links; } public void setLinks(NotificationEndpointBaseLinks links) { this.links = links; } public NotificationEndpointBase type(NotificationEndpointType type) { this.type = type; return this; } /** * Get type * @return type **/ public NotificationEndpointType getType() { return type; } public void setType(NotificationEndpointType type) { this.type = type; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NotificationEndpointBase notificationEndpointBase = (NotificationEndpointBase) o; return Objects.equals(this.id, notificationEndpointBase.id) && Objects.equals(this.orgID, notificationEndpointBase.orgID) && Objects.equals(this.userID, notificationEndpointBase.userID) && Objects.equals(this.createdAt, notificationEndpointBase.createdAt) && Objects.equals(this.updatedAt, notificationEndpointBase.updatedAt) && Objects.equals(this.description, notificationEndpointBase.description) && Objects.equals(this.name, notificationEndpointBase.name) && Objects.equals(this.status, notificationEndpointBase.status) && Objects.equals(this.labels, notificationEndpointBase.labels) && Objects.equals(this.links, notificationEndpointBase.links) && Objects.equals(this.type, notificationEndpointBase.type); } @Override public int hashCode() { return Objects.hash(id, orgID, userID, createdAt, updatedAt, description, name, status, labels, links, type); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class NotificationEndpointBase {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" orgID: ").append(toIndentedString(orgID)).append("\n"); sb.append(" userID: ").append(toIndentedString(userID)).append("\n"); sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); sb.append(" updatedAt: ").append(toIndentedString(updatedAt)).append("\n"); sb.append(" description: ").append(toIndentedString(description)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append(" labels: ").append(toIndentedString(labels)).append("\n"); sb.append(" links: ").append(toIndentedString(links)).append("\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
25.731507
148
0.688245
cea49f7e58610eb0c37c73dc2c7cef445837085f
1,018
package com.lcp.learn.spring.spb.check.other.services.impls; import com.lcp.learn.spring.spb.check.other.services.LockService; import javax.annotation.Resource; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; /** * desc: <br/> * @since 2020/10/15-16:16 * @author lichunpeng */ @Service public class LockServiceImpl implements LockService { private final Logger logger = LoggerFactory.getLogger(getClass()); private final String keyPrefix = "lock-"; @Resource private RedissonClient redissonClient; @Override public int updateData(int sourceData, int target) { RLock rLock = redissonClient.getLock(keyPrefix + sourceData); rLock.lock(); String threadName = Thread.currentThread().getName(); logger.info("thread:{},update {} to {}", threadName, sourceData, target); rLock.unlock(); return target; } }
26.102564
81
0.712181
0d6bb3b197a91c3a447d5ecad4ff4a11f2e005f3
9,559
/** * The MIT License * * Copyright for portions of unirest-java are held by Kong Inc (c) 2013. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package kong.unirest.apache; import kong.unirest.*; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.concurrent.FutureCallback; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.nio.client.HttpAsyncClient; import org.apache.http.nio.conn.NoopIOSessionStrategy; import org.apache.http.nio.conn.SchemeIOSessionStrategy; import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy; import org.apache.http.ssl.SSLContextBuilder; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.stream.Stream; public class ApacheAsyncClient extends BaseApacheClient implements AsyncClient { private final HttpAsyncClient client; private AsyncIdleConnectionMonitorThread syncMonitor; private PoolingNHttpClientConnectionManager manager; private Config config; private boolean hookset; public ApacheAsyncClient(Config config) { this.config = config; try { manager = createConnectionManager(); manager.setMaxTotal(config.getMaxConnections()); manager.setDefaultMaxPerRoute(config.getMaxPerRoutes()); HttpAsyncClientBuilder ab = HttpAsyncClientBuilder.create() .setDefaultRequestConfig(RequestOptions.toRequestConfig(config)) .setConnectionManager(manager) .setDefaultCredentialsProvider(toApacheCreds(config.getProxy())) .useSystemProperties(); setOptions(ab); CloseableHttpAsyncClient build = ab.build(); build.start(); syncMonitor = new AsyncIdleConnectionMonitorThread(manager); syncMonitor.tryStart(); client = build; if (config.shouldAddShutdownHook()) { registerShutdownHook(); } } catch (Exception e) { throw new UnirestConfigException(e); } } public ApacheAsyncClient(HttpAsyncClient client, Config config) { this.config = config; this.client = client; } @Deprecated public ApacheAsyncClient(HttpAsyncClient client, Config config, PoolingNHttpClientConnectionManager manager, AsyncIdleConnectionMonitorThread monitor) { Objects.requireNonNull(client, "Client may not be null"); this.config = config; this.client = client; this.syncMonitor = monitor; this.manager = manager; } @Override public void registerShutdownHook() { if (!hookset) { hookset = true; Runtime.getRuntime().addShutdownHook(new Thread(this::close, "Unirest Apache Async Client Shutdown Hook")); } } private void setOptions(HttpAsyncClientBuilder ab) { if (!config.isVerifySsl()) { disableSsl(ab); } if (config.useSystemProperties()) { ab.useSystemProperties(); } if (!config.getFollowRedirects()) { ab.setRedirectStrategy(new ApacheNoRedirectStrategy()); } if (!config.getEnabledCookieManagement()) { ab.disableCookieManagement(); } config.getInterceptors().forEach(ab::addInterceptorFirst); } private PoolingNHttpClientConnectionManager createConnectionManager() throws Exception { return new PoolingNHttpClientConnectionManager(new DefaultConnectingIOReactor(), null, getRegistry(), null, null, config.getTTL(), TimeUnit.MILLISECONDS); } private Registry<SchemeIOSessionStrategy> getRegistry() throws Exception { if (config.isVerifySsl()) { return RegistryBuilder.<SchemeIOSessionStrategy>create() .register("http", NoopIOSessionStrategy.INSTANCE) .register("https", SSLIOSessionStrategy.getDefaultStrategy()) .build(); } else { return RegistryBuilder.<SchemeIOSessionStrategy>create() .register("http", NoopIOSessionStrategy.INSTANCE) .register("https", new SSLIOSessionStrategy(new SSLContextBuilder() .loadTrustMaterial(null, (x509Certificates, s) -> true) .build(), NoopHostnameVerifier.INSTANCE)) .build(); } } private void disableSsl(HttpAsyncClientBuilder ab) { try { ab.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE); ab.setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, (TrustStrategy) (arg0, arg1) -> true).build()); } catch (Exception e) { throw new UnirestConfigException(e); } } @Override public <T> CompletableFuture<HttpResponse<T>> request( HttpRequest request, Function<RawResponse, HttpResponse<T>> transformer, CompletableFuture<HttpResponse<T>> callback) { Objects.requireNonNull(callback); HttpUriRequest requestObj = new RequestPrep(request, config, true).prepare(configFactory); MetricContext metric = config.getMetric().begin(request.toSummary()); client.execute(requestObj, new FutureCallback<org.apache.http.HttpResponse>() { @Override public void completed(org.apache.http.HttpResponse httpResponse) { ApacheResponse t = new ApacheResponse(httpResponse, config); metric.complete(t.toSummary(), null); HttpResponse<T> response = transformBody(transformer, t); handleError(config, response); callback.complete(response); } @Override public void failed(Exception e) { metric.complete(null, e); callback.completeExceptionally(e); } @Override public void cancelled() { UnirestException canceled = new UnirestException("canceled"); metric.complete(null, canceled); callback.completeExceptionally(canceled); } }); return callback; } @Override public boolean isRunning() { return Util.tryCast(client, CloseableHttpAsyncClient.class) .map(CloseableHttpAsyncClient::isRunning) .orElse(true); } @Override public HttpAsyncClient getClient() { return client; } @Override public Stream<Exception> close() { return Util.collectExceptions(Util.tryCast(client, CloseableHttpAsyncClient.class) .filter(c -> c.isRunning()) .map(c -> Util.tryDo(c, d -> d.close())) .filter(c -> c.isPresent()) .map(c -> c.get()), Util.tryDo(manager, m -> m.shutdown()), Util.tryDo(syncMonitor, m -> m.interrupt())); } public static Builder builder(HttpAsyncClient client) { return new Builder(client); } public static class Builder implements Function<Config, AsyncClient> { private HttpAsyncClient asyncClient; private RequestConfigFactory cf; public Builder(HttpAsyncClient client) { this.asyncClient = client; } @Override public AsyncClient apply(Config config) { ApacheAsyncClient client = new ApacheAsyncClient(this.asyncClient, config); if (cf != null) { client.setConfigFactory(cf); } return client; } public Builder withRequestConfig(RequestConfigFactory factory) { Objects.requireNonNull(factory); this.cf = factory; return this; } } }
37.93254
124
0.64013
f3f3e2760032aab723ca2c03c5718508af284268
1,685
/** * 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.cxf.systest.sts.batch; import org.w3c.dom.Element; public class BatchRequest { private String tokenType; private String keyType; private String appliesTo; private Element validateTarget; public String getTokenType() { return tokenType; } public void setTokenType(String tokenType) { this.tokenType = tokenType; } public String getKeyType() { return keyType; } public void setKeyType(String keyType) { this.keyType = keyType; } public String getAppliesTo() { return appliesTo; } public void setAppliesTo(String appliesTo) { this.appliesTo = appliesTo; } public Element getValidateTarget() { return validateTarget; } public void setValidateTarget(Element validateTarget) { this.validateTarget = validateTarget; } }
29.561404
62
0.706231
15d40bc9bbc26dd5a469eb7e3c5c5f4dead0e477
469
package com.s8.io.xml.tests.example02; import com.qx.io.xml.annotations.XML_SetElement; import com.qx.io.xml.annotations.XML_Type; @XML_Type(name = "Type01Stage") public class Type01Stage extends MyStage { public MyStageDesign design; @XML_SetElement(tag = "design") public void setDesign(Type01StageDesign design) { this.design = design; } @XML_Type(name = "Type01StageDesign") public static class Type01StageDesign extends MyStageDesign { } }
20.391304
62
0.75693
11534f4b9596d26b82126c639f6701bea9dd4f8d
13,358
/** * Copyright 2005-2015 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.kew.rule; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.builder.HashCodeBuilder; import org.kuali.rice.core.api.reflect.ObjectDefinition; import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader; import org.kuali.rice.kew.actionrequest.ActionRequestValue; import org.kuali.rice.kew.actionrequest.KimGroupRecipient; import org.kuali.rice.kew.actionrequest.KimPrincipalRecipient; import org.kuali.rice.kew.actionrequest.Recipient; import org.kuali.rice.kew.api.KewApiConstants; import org.kuali.rice.kew.api.rule.RuleResponsibilityContract; import org.kuali.rice.kew.service.KEWServiceLocator; import org.kuali.rice.kew.user.RoleRecipient; import org.kuali.rice.kim.api.group.Group; import org.kuali.rice.kim.api.identity.principal.Principal; import org.kuali.rice.kim.api.services.KimApiServiceLocator; import org.kuali.rice.krad.bo.PersistableBusinessObjectBase; import org.kuali.rice.krad.data.jpa.PortableSequenceGenerator; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import java.util.List; /** * A model bean representing the responsibility of a user, workgroup, or role * to perform some action on a document. Used by the rule system to * identify the appropriate responsibile parties to generate * {@link ActionRequestValue}s to. * * @author Kuali Rice Team (rice.collab@kuali.org) */ @Entity @Table(name="KREW_RULE_RSP_T") //@Sequence(name="KREW_RSP_S", property="id") public class RuleResponsibilityBo extends PersistableBusinessObjectBase implements RuleResponsibilityContract { private static final long serialVersionUID = -1565688857123316797L; @Id @PortableSequenceGenerator(name="KREW_RSP_S") @GeneratedValue(generator="KREW_RSP_S") @Column(name="RULE_RSP_ID") private String id; @Column(name="RSP_ID") private String responsibilityId; @Column(name="RULE_ID", insertable=false, updatable=false) private String ruleBaseValuesId; @Column(name="ACTN_RQST_CD") private String actionRequestedCd; @Column(name="NM") private String ruleResponsibilityName; @Column(name="TYP") private String ruleResponsibilityType; @Column(name="PRIO") private Integer priority; @Column(name="APPR_PLCY") private String approvePolicy; @ManyToOne(fetch=FetchType.EAGER) @JoinColumn(name="RULE_ID") private RuleBaseValues ruleBaseValues; //@OneToMany(fetch=FetchType.EAGER,cascade={CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.MERGE}, // mappedBy="ruleResponsibility") //private List<RuleDelegation> delegationRules = new ArrayList<RuleDelegation>(); public Principal getPrincipal() { if (isUsingPrincipal()) { return KEWServiceLocator.getIdentityHelperService().getPrincipal(ruleResponsibilityName); } return null; } public Group getGroup() { if (isUsingGroup()) { return KimApiServiceLocator.getGroupService().getGroup(ruleResponsibilityName); } return null; } public String getRole() { if (isUsingRole()) { return ruleResponsibilityName; } return null; } public String getResolvedRoleName() { if (isUsingRole()) { return getRole().substring(getRole().indexOf("!") + 1, getRole().length()); } return null; } public String getRoleAttributeName() { return getRole().substring(0, getRole().indexOf("!")); } public RoleAttribute resolveRoleAttribute() { if (isUsingRole()) { String attributeName = getRoleAttributeName(); return (RoleAttribute) GlobalResourceLoader.getResourceLoader().getObject(new ObjectDefinition(attributeName)); } return null; } @Override public boolean isUsingRole() { return (ruleResponsibilityName != null && ruleResponsibilityType != null && ruleResponsibilityType.equals(KewApiConstants.RULE_RESPONSIBILITY_ROLE_ID)); } @Override public boolean isUsingPrincipal() { return (ruleResponsibilityName != null && !ruleResponsibilityName.trim().equals("") && ruleResponsibilityType != null && ruleResponsibilityType.equals(KewApiConstants.RULE_RESPONSIBILITY_WORKFLOW_ID)); } @Override public boolean isUsingGroup() { return (ruleResponsibilityName != null && !ruleResponsibilityName.trim().equals("") && ruleResponsibilityType != null && ruleResponsibilityType.equals(KewApiConstants.RULE_RESPONSIBILITY_GROUP_ID)); } public String getRuleBaseValuesId() { return ruleBaseValuesId; } public void setRuleBaseValuesId(String ruleBaseValuesId) { this.ruleBaseValuesId = ruleBaseValuesId; } public RuleBaseValues getRuleBaseValues() { return ruleBaseValues; } public void setRuleBaseValues(RuleBaseValues ruleBaseValues) { this.ruleBaseValues = ruleBaseValues; } public String getActionRequestedCd() { return actionRequestedCd; } public void setActionRequestedCd(String actionRequestedCd) { this.actionRequestedCd = actionRequestedCd; } public String getId() { return id; } public void setId(String ruleResponsibilityId) { this.id = ruleResponsibilityId; } public Integer getPriority() { return priority; } public void setPriority(Integer priority) { this.priority = priority; } public String getApprovePolicy() { return approvePolicy; } public void setApprovePolicy(String approvePolicy) { this.approvePolicy = approvePolicy; } public Object copy(boolean preserveKeys) { RuleResponsibilityBo ruleResponsibilityClone = new RuleResponsibilityBo(); ruleResponsibilityClone.setApprovePolicy(getApprovePolicy()); if (actionRequestedCd != null) { ruleResponsibilityClone.setActionRequestedCd(actionRequestedCd); } if (id != null && preserveKeys) { ruleResponsibilityClone.setId(id); } if (responsibilityId != null) { ruleResponsibilityClone.setResponsibilityId(responsibilityId); } if (ruleResponsibilityName != null) { ruleResponsibilityClone.setRuleResponsibilityName(ruleResponsibilityName); } if (ruleResponsibilityType != null) { ruleResponsibilityClone.setRuleResponsibilityType(ruleResponsibilityType); } if (priority != null) { ruleResponsibilityClone.setPriority(priority); } // if (delegationRules != null) { // for (Iterator iter = delegationRules.iterator(); iter.hasNext();) { // RuleDelegation delegation = (RuleDelegation) iter.next(); // RuleDelegation delegationClone = (RuleDelegation)delegation.copy(preserveKeys); // delegationClone.setRuleResponsibility(ruleResponsibilityClone); // ruleResponsibilityClone.getDelegationRules().add(delegationClone); // // } // } return ruleResponsibilityClone; } public String getRuleResponsibilityName() { return ruleResponsibilityName; } public void setRuleResponsibilityName(String ruleResponsibilityName) { this.ruleResponsibilityName = ruleResponsibilityName; } public String getRuleResponsibilityType() { return ruleResponsibilityType; } public void setRuleResponsibilityType(String ruleResponsibilityType) { this.ruleResponsibilityType = ruleResponsibilityType; } public String getResponsibilityId() { return responsibilityId; } public void setResponsibilityId(String responsibilityId) { this.responsibilityId = responsibilityId; } public List<RuleDelegationBo> getDelegationRules() { return KEWServiceLocator.getRuleDelegationService().findByResponsibilityId(getResponsibilityId()); } public RuleDelegationBo getDelegationRule(int index) { return getDelegationRules().get(index); } // public boolean isDelegating() { // return !getDelegationRules().isEmpty(); // } // // public List getDelegationRules() { // return delegationRules; // } // public void setDelegationRules(List delegationRules) { // this.delegationRules = delegationRules; // } // // public RuleDelegation getDelegationRule(int index) { // while (getDelegationRules().size() <= index) { // RuleDelegation ruleDelegation = new RuleDelegation(); // ruleDelegation.setRuleResponsibility(this); // ruleDelegation.setDelegationRuleBaseValues(new RuleBaseValues()); // getDelegationRules().add(ruleDelegation); // } // return (RuleDelegation) getDelegationRules().get(index); // } // convenience methods for the web-tier public String getActionRequestedDisplayValue() { return KewApiConstants.ACTION_REQUEST_CODES.get(getActionRequestedCd()); } public String getRuleResponsibilityTypeDisplayValue() { return KewApiConstants.RULE_RESPONSIBILITY_TYPES.get(getRuleResponsibilityType()); } public boolean equals(Object o) { if (o == null) return false; if (!(o instanceof RuleResponsibilityBo)) return false; RuleResponsibilityBo pred = (RuleResponsibilityBo) o; return ObjectUtils.equals(ruleResponsibilityName, pred.getRuleResponsibilityName()) && ObjectUtils.equals(actionRequestedCd, pred.getActionRequestedCd()) && ObjectUtils.equals(priority, pred.getPriority()) && ObjectUtils.equals(approvePolicy, pred.getApprovePolicy()); } /** * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return new HashCodeBuilder() .append(this.actionRequestedCd) .append(this.approvePolicy) .append(this.priority) .append(this.ruleResponsibilityName).toHashCode(); } @Override public String getGroupId() { if (!isUsingGroup()) { return null; } return getGroup().getId(); } @Override public String getPrincipalId() { if (getPrincipal() == null) { return null; } return getPrincipal().getPrincipalId(); } @Override public String getRoleName() { return getRole(); } /** * Convenience method to return the Recipient for this RuleResponsibility * @return the Recipient for this RuleResponsibility */ public Recipient getRecipient() { if (isUsingPrincipal()) { return new KimPrincipalRecipient(getPrincipal()); } else if (isUsingGroup()) { return new KimGroupRecipient(getGroup()); } else if (isUsingRole()) { return new RoleRecipient(getRole()); } else { return null; } } public static org.kuali.rice.kew.api.rule.RuleResponsibility to(RuleResponsibilityBo bo) { if (bo == null) { return null; } return org.kuali.rice.kew.api.rule.RuleResponsibility.Builder.create(bo).build(); /*org.kuali.rice.kew.api.rule.RuleResponsibility.Builder builder = org.kuali.rice.kew.api.rule.RuleResponsibility.Builder.create(); builder.setPriority(bo.getPriority()); builder.setResponsibilityId(bo.getResponsibilityId()); builder.setActionRequestedCd(bo.getActionRequestedCd()); builder.setApprovePolicy(bo.getApprovePolicy()); builder.setPrincipalId(bo.getPrincipal() == null ? null : bo.getPrincipal().getPrincipalId()); builder.setGroupId(bo.getGroup() == null ? null : bo.getGroup().getId()); builder.setRoleName(bo.getResolvedRoleName()); if (CollectionUtils.isNotEmpty(bo.getDelegationRules())) { List<org.kuali.rice.kew.api.rule.RuleDelegation.Builder> delegationRuleBuilders = new ArrayList<org.kuali.rice.kew.api.rule.RuleDelegation.Builder>(); for (RuleDelegation delegationRule : bo.getDelegationRules()) { delegationRuleBuilders.add( org.kuali.rice.kew.api.rule.RuleDelegation.Builder.create(RuleDelegation.to(delegationRule))); } builder.setDelegationRules(delegationRuleBuilders); } else { builder.setDelegationRules(Collections.<org.kuali.rice.kew.api.rule.RuleDelegation.Builder>emptyList()); } return builder.build();*/ } }
35.716578
206
0.692169
459cdb2a6147a66a92d222fa41b490b60c36fbd1
21,610
package postgres; import com.google.common.collect.ImmutableMap; import driver.TestDriver; import org.postgresql.ds.PGConnectionPoolDataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Random; public class PostgresDriver extends TestDriver<Connection, Map<String, Object>, ResultSet> { protected PGConnectionPoolDataSource ds; public PostgresDriver() { } public void initDataSource(String host, int port, String username, String password, String dbName) { ds = new PGConnectionPoolDataSource(); ds.setDefaultAutoCommit(false); ds.setDatabaseName(dbName); ds.setServerName(host); ds.setPortNumber(port); ds.setUser(username); ds.setPassword(password); } public String getPGVersion() throws SQLException { Connection conn = ds.getConnection(); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("select version()"); rs.next(); return rs.getString(1); } @Override public Connection startTransaction() throws SQLException { Connection conn = ds.getConnection(); conn.setAutoCommit(false); //conn.createStatement().executeUpdate(PostgresQueries.isolation_serializable); //conn.createStatement().executeUpdate(PostgresQueries.isolation_repetable_read); conn.createStatement().executeUpdate(PostgresQueries.isolation_read_committed); return conn; } @Override public void commitTransaction(Connection tt) throws SQLException { tt.commit(); } @Override public void abortTransaction(Connection tt) throws SQLException { tt.rollback(); // rollback VS. abort? } @Override public ResultSet runQuery(Connection tt, String querySpecification, Map<String, Object> stringStringMap) throws Exception { ResultSet rs = null; querySpecification = substituteParameters(querySpecification, stringStringMap); // don't close this statement before returning (e.g. in a try-with-resources block) so we can retrive elements of the resultset Statement st = tt.createStatement(); rs = st.executeQuery(querySpecification); return rs; } protected List<Object> toObjectList(Object o) { Object[] ol = (Object[])o; List<Object> lo = new ArrayList<Object>(); for(Object i: ol) { lo.add(i); } return lo; } public String substituteParameters(String querySpecification, Map<String, Object> stringStringMap) { // substitute parameters if (stringStringMap != null) { for (Map.Entry<String, Object> param : stringStringMap.entrySet()) { querySpecification = querySpecification.replace("$" + param.getKey(), param.getValue().toString()); } } //System.err.println(querySpecification); return querySpecification; } protected void executeUpdates(String[] commands) { executeUpdates(commands, true); } protected void executeUpdates(String[] commands, boolean doCommit) { try (Connection conn = startTransaction(); Statement st = conn.createStatement()) { for (String sql : commands) { // we never need info on the resultset, if any // so we use execute (which allows INSERT/UPDATE/DELETE/SELECT) instead of executeUpdate (which allows only INSERT/UPDATE/DELETE) st.execute(sql); } if (doCommit) { commitTransaction(conn); } } catch (SQLException e) { throw new RuntimeException(e); } } protected void executeUpdates(String[] commands, Map<String, Object> parameters, boolean doCommit) { for(int i=0; i<commands.length; i++) { commands[i]=substituteParameters(commands[i], parameters); } executeUpdates(commands, doCommit); } protected void executeUpdates(Connection conn, String[] commands) { executeUpdates(conn, commands, true); } protected void executeUpdates(Connection conn, String[] commands, boolean doCommit) { try (Statement st = conn.createStatement()) { for (String sql : commands) { // we never need info on the resultset, if any // so we use execute (which allows INSERT/UPDATE/DELETE/SELECT) instead of executeUpdate (which allows only INSERT/UPDATE/DELETE) st.execute(sql); } if (doCommit) { commitTransaction(conn); } } catch (SQLException e) { throw new RuntimeException(e); } } protected void executeUpdates(Connection conn, String[] commands, Map<String, Object> parameters, boolean doCommit) { for(int i=0; i<commands.length; i++) { commands[i]=substituteParameters(commands[i], parameters); } executeUpdates(conn, commands, doCommit); } protected void createSchema() { executeUpdates(PostgresQueries.tablesCreate); } @Override public void nukeDatabase() { // drop all the tables executeUpdates(PostgresQueries.tablesClear); } @Override public void atomicityInit() { createSchema(); executeUpdates(PostgresQueries.atomicityInit); } @Override public void atomicityC(Map<String, Object> parameters) { executeUpdates(PostgresQueries.atomicityCTx, parameters, true); } @Override public void atomicityRB(Map<String, Object> parameters) { try (Connection conn = startTransaction()) { executeUpdates(conn, PostgresQueries.atomicityRBxP1update, parameters, false); ResultSet rs = runQuery(conn, PostgresQueries.atomicityRBxP2check, parameters); if (rs.next()) { abortTransaction(conn); } else { executeUpdates(conn, PostgresQueries.atomicityRBxP2create, parameters, false); commitTransaction(conn); } } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Map<String, Object> atomicityCheck() { try (Connection conn = startTransaction()) { ResultSet rs = runQuery(conn, PostgresQueries.atomicityCheck, null); rs.next(); final long numPersons = rs.getLong(1); final long numNames = rs.getLong(2); final long numEmails = rs.getLong(3); return ImmutableMap.of("numPersons", numPersons, "numNames", numNames, "numEmails", numEmails); } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void g0Init() { createSchema(); executeUpdates(PostgresQueries.g0Init); } @Override public Map<String, Object> g0(Map<String, Object> parameters) { executeUpdates(PostgresQueries.g0, parameters, true); return ImmutableMap.of(); } @Override public Map<String, Object> g0check(Map<String, Object> parameters) { try (Connection conn = startTransaction()) { ResultSet rs = runQuery(conn, PostgresQueries.g0check, parameters); rs.next(); List<Object> p1VersionHistory = toObjectList((Object[])rs.getArray(1).getArray()); List<Object> kVersionHistory = toObjectList((Object[])rs.getArray(2).getArray()); List<Object> p2VersionHistory = toObjectList((Object[])rs.getArray(3).getArray()); return ImmutableMap.of("p1VersionHistory", p1VersionHistory, "kVersionHistory", kVersionHistory, "p2VersionHistory", p2VersionHistory); } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void g1aInit() { createSchema(); executeUpdates(PostgresQueries.g1aInit); } @Override public Map<String, Object> g1aW(Map<String, Object> parameters) { try (Connection conn = startTransaction()) { executeUpdates(conn, PostgresQueries.g1a1, parameters, false); abortTransaction(conn); } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } return ImmutableMap.of(); } @Override public Map<String, Object> g1aR(Map<String, Object> parameters) { try (Connection conn = startTransaction()) { final ResultSet result = runQuery(conn, PostgresQueries.g1a2, parameters); if (!result.next()) throw new IllegalStateException("G1a T2 result empty"); final long pVersion = result.getLong(1); return ImmutableMap.of("pVersion", pVersion); } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void g1bInit() { createSchema(); executeUpdates(PostgresQueries.g1bInit); } @Override public Map<String, Object> g1bW(Map<String, Object> parameters) { try (Connection conn = startTransaction()) { executeUpdates(conn, PostgresQueries.g1b1, parameters, true); return ImmutableMap.of(); } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Map<String, Object> g1bR(Map<String, Object> parameters) { try (Connection conn = startTransaction()) { final ResultSet result = runQuery(conn, PostgresQueries.g1b2, parameters); if (!result.next()) throw new IllegalStateException("G1b T2 result empty"); final long pVersion = result.getLong(1); return ImmutableMap.of("pVersion", pVersion); } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void g1cInit() { createSchema(); executeUpdates(PostgresQueries.g1cInit); } @Override public Map<String, Object> g1c(Map<String, Object> parameters) { try (Connection conn = startTransaction()) { executeUpdates(conn, PostgresQueries.g1c1, parameters, false); final ResultSet result = runQuery(conn, PostgresQueries.g1c2, parameters); if (!result.next()) throw new IllegalStateException("G1c T2 result empty"); final long person2Version = result.getLong(1); commitTransaction(conn); return ImmutableMap.of("person2Version", person2Version); } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void impInit() { createSchema(); executeUpdates(PostgresQueries.impInit); } @Override public Map<String, Object> impW(Map<String, Object> parameters) { try (Connection conn = startTransaction()) { executeUpdates(conn, PostgresQueries.impW, parameters, true); return ImmutableMap.of(); } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Map<String, Object> impR(Map<String, Object> parameters) { try (Connection conn = startTransaction()) { final ResultSet result1 = runQuery(conn, PostgresQueries.impR, parameters); if (!result1.next()) throw new IllegalStateException("IMP result1 empty"); final long firstRead = result1.getLong(1); sleep((Long) parameters.get("sleepTime")); final ResultSet result2 = runQuery(conn, PostgresQueries.impR, parameters); if (!result2.next()) throw new IllegalStateException("IMP result2 empty"); final long secondRead = result2.getLong(1); commitTransaction(conn); return ImmutableMap.of("firstRead", firstRead, "secondRead", secondRead); } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void pmpInit() { createSchema(); executeUpdates(PostgresQueries.pmpInit); } @Override public Map<String, Object> pmpW(Map<String, Object> parameters) { try (Connection conn = startTransaction()) { executeUpdates(conn, PostgresQueries.pmpW, parameters, true); return ImmutableMap.of(); } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Map<String, Object> pmpR(Map<String, Object> parameters) { try (Connection conn = startTransaction()) { final ResultSet result1 = runQuery(conn, PostgresQueries.pmpR, parameters); if (!result1.next()) throw new IllegalStateException("PMP result1 empty"); final long firstRead = result1.getLong(1); sleep((Long) parameters.get("sleepTime")); final ResultSet result2 = runQuery(conn, PostgresQueries.pmpR, parameters); if (!result2.next()) throw new IllegalStateException("PMP result2 empty"); final long secondRead = result2.getLong(1); commitTransaction(conn); return ImmutableMap.of("firstRead", firstRead, "secondRead", secondRead); } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void otvInit() { createSchema(); executeUpdates(PostgresQueries.otvInit); } @Override public Map<String, Object> otvW(Map<String, Object> parameters) { try (Connection conn = startTransaction()) { Random random = new Random(); for (int i = 0; i < 100; i++) { long personId = random.nextInt((int) parameters.get("cycleSize")+1); ResultSet rs = runQuery(conn, PostgresQueries.otvWquery, ImmutableMap.of("personId", personId)); while (rs.next()) { executeUpdates(PostgresQueries.otvWupdate, ImmutableMap.of("p1id", rs.getLong(1), "p2id", rs.getLong(2), "p3id", rs.getLong(3), "p4id", rs.getLong(4)), true); } commitTransaction(conn); } return ImmutableMap.of(); } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Map<String, Object> otvR(Map<String, Object> parameters) { try (Connection conn = startTransaction()) { final ResultSet result1 = runQuery(conn, PostgresQueries.otvR, parameters); if (!result1.next()) throw new IllegalStateException("OTV2 result1 empty"); final List<Object> firstRead = new ArrayList(); { firstRead.add(result1.getLong(1)); firstRead.add(result1.getLong(2)); firstRead.add(result1.getLong(3)); firstRead.add(result1.getLong(4)); } sleep((Long) parameters.get("sleepTime")); final ResultSet result2 = runQuery(conn, PostgresQueries.otvR, parameters); if (!result2.next()) throw new IllegalStateException("OTV2 result2 empty"); final List<Object> secondRead = new ArrayList(); { secondRead.add(result2.getLong(1)); secondRead.add(result2.getLong(2)); secondRead.add(result2.getLong(3)); secondRead.add(result2.getLong(4)); } return ImmutableMap.of("firstRead", firstRead, "secondRead", secondRead); } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void frInit() { createSchema(); executeUpdates(PostgresQueries.frInit); } @Override public Map<String, Object> frW(Map<String, Object> parameters) { try (Connection conn = startTransaction()) { executeUpdates(conn, PostgresQueries.frW, parameters, true); return ImmutableMap.of(); } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Map<String, Object> frR(Map<String, Object> parameters) { try (Connection conn = startTransaction()) { final ResultSet result1 = runQuery(conn, PostgresQueries.frR, parameters); if (!result1.next()) throw new IllegalStateException("FR2 result1 empty"); final List<Object> firstRead = toObjectList((Object[])result1.getArray(3).getArray()); sleep((Long) parameters.get("sleepTime")); final ResultSet result2 = runQuery(conn, PostgresQueries.frR, parameters); if (!result1.next()) throw new IllegalStateException("FR2 result2 empty"); final List<Object> secondRead = toObjectList((Object[])result2.getArray(3).getArray()); return ImmutableMap.of("firstRead", firstRead, "secondRead", secondRead); } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void luInit() { createSchema(); executeUpdates(PostgresQueries.luInit); } @Override public Map<String, Object> luW(Map<String, Object> parameters) { try (Connection conn = startTransaction()) { executeUpdates(conn, PostgresQueries.luW, parameters, true); return ImmutableMap.of(); } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Map<String, Object> luR(Map<String, Object> parameters) { try (Connection conn = startTransaction()) { final ResultSet result = runQuery(conn, PostgresQueries.luR, parameters); if (!result.next()) throw new IllegalStateException("LU2 result empty"); long numKnowsEdges = result.getLong(1); long numFriends = result.getLong(2); return ImmutableMap.of("numKnowsEdges", numKnowsEdges, "numFriendsProp", numFriends); } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void wsInit() { createSchema(); // create 10 pairs of persons with indices (1,2), ..., (19,20) for (int i = 1; i <= 10; i++) { // we utilise separate transactions for each iteration, but it should not matter in the initialization. executeUpdates(PostgresQueries.wsInit, ImmutableMap.of("person1Id", 2*i-1, "person2Id", 2*i), true); } } @Override public Map<String, Object> wsW(Map<String, Object> parameters) { try (Connection conn = startTransaction()) { final ResultSet rs = runQuery(conn, PostgresQueries.wsWquery, parameters); if (!rs.next()) { sleep((Long) parameters.get("sleepTime")); long personId = new Random().nextBoolean() ? (long) parameters.get("person1Id") : (long) parameters.get("person2Id"); executeUpdates(conn, PostgresQueries.wsWupdate, ImmutableMap.of("personId", personId), true); } return ImmutableMap.of(); } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Map<String, Object> wsR(Map<String, Object> parameters) { try (Connection conn = startTransaction()) { final ResultSet rs = runQuery(conn, PostgresQueries.wsR, ImmutableMap.of()); if (rs.next()) { return ImmutableMap.of( "p1id", rs.getLong(1), "p1value", rs.getLong(2), "p2id", rs.getLong(3), "p2value", rs.getLong(4)); } else { return ImmutableMap.of(); } } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void close() throws Exception { } }
35.601318
178
0.605137
ea3c541933b4efe8794ece7b1e0bf47562d974bf
1,350
/* * Copyright 2020 OPPO ESA Stack 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 esa.commons.loadbalance; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; class WeightRandomLoadBalancerTest { @Test void testAll() { final WeightRandomLoadBalancer<Integer> lb = new WeightRandomLoadBalancer<Integer>() { @Override protected int getWeight(Integer e) { return e % 2 == 0 ? 100 : 0; } }; assertNull(lb.select(Collections.emptyList())); assertEquals(1, lb.select(Collections.singletonList(1))); assertEquals(0, lb.select(Arrays.asList(0, 1, 3))); } }
31.395349
94
0.697037
98973ffc714887831ab26f56a49ce7cd3ab9b192
986
/** * Copyright information and license terms for this software can be * found in the file LICENSE.TXT included with the distribution. */ package org.epics.util.array.performance; import org.epics.util.array.ListDouble; /** * * @author carcassi */ public class ListBenchmark { public static void profileListDouble(ListDouble list, int nIterations) { long startTime = System.nanoTime(); for (int i = 0; i < nIterations; i++) { double sum = 0; for (int n = 0; n < list.size(); n++) { sum += list.getDouble(n); } if (sum == 0) { System.out.println("Unexpected value " + sum); } } long stopTime = System.nanoTime(); System.out.println("Iteration on ListDouble: " + (stopTime - startTime) / nIterations +" ns/iter - " + (stopTime - startTime) / nIterations / list.size() + " ns/sample"); } }
29.878788
111
0.554767
14d9fe31eb02aa1b70da67c86b8c0fa70a7fee74
1,774
package gloridifice.watersource.common.block; import gloridifice.watersource.common.tile.RainCollectorTile; import gloridifice.watersource.registry.TileEntityTypesRegistry; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ActionResultType; import net.minecraft.util.Hand; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockRayTraceResult; import net.minecraft.world.IBlockReader; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidUtil; public class RainCollectorBlock extends Block { public RainCollectorBlock(String name, Properties properties) { super(properties); this.setRegistryName(name); } @Override public boolean hasTileEntity(BlockState state) { return true; } @Override public TileEntity createTileEntity(BlockState state, IBlockReader world) { return TileEntityTypesRegistry.RAIN_COLLECTOR.create(); } boolean flag = false; @Override public ActionResultType onBlockActivated(BlockState blockState, World world, BlockPos blockPos, PlayerEntity player, Hand hand, BlockRayTraceResult blockRayTraceResult) { RainCollectorTile tile = (RainCollectorTile) world.getTileEntity(blockPos); tile.getTank().ifPresent(fluidTankUp -> { ItemStack heldItem = player.getHeldItem(hand); if (!heldItem.isEmpty()) { //液体交互 flag = FluidUtil.interactWithFluidHandler(player, hand, fluidTankUp); } }); return flag ? ActionResultType.SUCCESS : ActionResultType.PASS; } }
36.204082
174
0.744081
ef098db2b55f40c7e62ef8313ecb32d7cb7af9d6
1,141
package request; import log.LogHelper; import java.io.IOException; import java.io.InputStream; public class Request { private InputStream inputStream = null; private String uri; public Request(InputStream inputStream) { this.inputStream = inputStream; } public void parse() { byte[] buffer = new byte[2048]; int i; String request = null; try { i = inputStream.read(buffer); request = new String(buffer, 0, i); } catch (IOException e) { e.printStackTrace(); } LogHelper.log("request : " + request); parseUri(request); } public String parseUri(String request) { if (request == null) { return null; } int index1, index2; index1 = request.indexOf(" "); if (index1 == -1) { return null; } index2 = request.indexOf(" ", index1 + 1); if (index2 <= index1) { return null; } return request.substring(index1 + 1, index2); } public String getUri() { return this.uri; } }
21.942308
53
0.537248
41ddb663cb87b6bb652640d3ca38c6afc88806bd
12,591
/* Copyright 2021 Adobe. All rights reserved. This file is licensed 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.adobe.s3fs.metastore.internal.dynamodb.operations; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; import com.adobe.s3fs.metastore.api.ObjectHandle; import com.adobe.s3fs.metastore.api.ObjectMetadata; import com.adobe.s3fs.metastore.internal.dynamodb.versioning.VersionedObject; import com.google.common.collect.Lists; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.function.Function; import org.apache.hadoop.fs.Path; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class SynchronousDFSTreeTraversalTest { private SynchronousDFSTreeTraversal treeTraversal = new SynchronousDFSTreeTraversal(); @Mock private Function<VersionedObject, Iterable<VersionedObject>> mockChildExpansion; @Mock private ObjectVisitor mockObjectVisitor; @Before public void setup() { MockitoAnnotations.initMocks(this); when(mockObjectVisitor.childVisitor(any(), any())).thenReturn(mockObjectVisitor); } @Test public void testVisitorIsCalledInCorrectOrderWhenNoErrors() { VersionedObject root = newDirectory(); VersionedObject d1 = newDirectory(); VersionedObject f1 = newFile(); VersionedObject f2 = newFile(); VersionedObject f3 = newFile(); when(mockChildExpansion.apply(root)).thenReturn(Arrays.asList(d1, f1)); when(mockChildExpansion.apply(d1)).thenReturn(Arrays.asList(f2, f3)); List<ObjectWithVisit> capturedVisits = new ArrayList<>(); new MockVisitorStubber().stub(capturedVisits); assertTrue(treeTraversal.traverse(root, mockChildExpansion, mockObjectVisitor)); List<ObjectWithVisit> expected = Lists.newArrayList( new ObjectWithVisit(root, Visit.PreVisitDir), new ObjectWithVisit(d1, Visit.PreVisitDir), new ObjectWithVisit(f2, Visit.VisitFile), new ObjectWithVisit(f3, Visit.VisitFile), new ObjectWithVisit(d1, Visit.PostVisitDir), new ObjectWithVisit(f1, Visit.VisitFile), new ObjectWithVisit(root, Visit.PostVisitDir)); assertEquals(expected, capturedVisits); } @Test public void testVisitorIsCalledInCorrectOrderWhenPreVisitDirectoryReturnsFalse() { VersionedObject root = newDirectory(); VersionedObject d1 = newDirectory(); VersionedObject f1 = newFile(); VersionedObject f2 = newFile(); VersionedObject f3 = newFile(); when(mockChildExpansion.apply(root)).thenReturn(Arrays.asList(d1, f1)); when(mockChildExpansion.apply(d1)).thenReturn(Arrays.asList(f2, f3)); List<ObjectWithVisit> capturedVisits = new ArrayList<>(); new MockVisitorStubber().withVisitToReturnFalse(d1, Visit.PreVisitDir).stub(capturedVisits); assertFalse(treeTraversal.traverse(root, mockChildExpansion, mockObjectVisitor)); List<ObjectWithVisit> expected = Lists.newArrayList(new ObjectWithVisit(root, Visit.PreVisitDir)); assertEquals(expected, capturedVisits); } @Test public void testVisitorIsCalledInCorrectOrderWhenPreVisitDirectoryThrowsError() { VersionedObject root = newDirectory(); VersionedObject d1 = newDirectory(); VersionedObject f1 = newFile(); VersionedObject f2 = newFile(); VersionedObject f3 = newFile(); when(mockChildExpansion.apply(root)).thenReturn(Arrays.asList(d1, f1)); when(mockChildExpansion.apply(d1)).thenReturn(Arrays.asList(f2, f3)); List<ObjectWithVisit> capturedVisits = new ArrayList<>(); new MockVisitorStubber().withVisitToThrowError(d1, Visit.PreVisitDir).stub(capturedVisits); assertFalse(treeTraversal.traverse(root, mockChildExpansion, mockObjectVisitor)); List<ObjectWithVisit> expected = Lists.newArrayList(new ObjectWithVisit(root, Visit.PreVisitDir)); assertEquals(expected, capturedVisits); } @Test public void testVisitorIsCalledInCorrectOrderWhenVisitFileReturnsFalse() { VersionedObject root = newDirectory(); VersionedObject d1 = newDirectory(); VersionedObject f1 = newFile(); VersionedObject f2 = newFile(); VersionedObject f3 = newFile(); when(mockChildExpansion.apply(root)).thenReturn(Arrays.asList(f1, d1)); when(mockChildExpansion.apply(d1)).thenReturn(Arrays.asList(f2, f3)); List<ObjectWithVisit> capturedVisits = new ArrayList<>(); new MockVisitorStubber().withVisitToReturnFalse(f1, Visit.VisitFile).stub(capturedVisits); assertFalse(treeTraversal.traverse(root, mockChildExpansion, mockObjectVisitor)); List<ObjectWithVisit> expected = Lists.newArrayList(new ObjectWithVisit(root, Visit.PreVisitDir)); assertEquals(expected, capturedVisits); } @Test public void testVisitorIsCalledInCorrectOrderWhenVisitFileThrowsError() { VersionedObject root = newDirectory(); VersionedObject d1 = newDirectory(); VersionedObject f1 = newFile(); VersionedObject f2 = newFile(); VersionedObject f3 = newFile(); when(mockChildExpansion.apply(root)).thenReturn(Arrays.asList(f1, d1)); when(mockChildExpansion.apply(d1)).thenReturn(Arrays.asList(f2, f3)); List<ObjectWithVisit> capturedVisits = new ArrayList<>(); new MockVisitorStubber().withVisitToThrowError(f1, Visit.VisitFile).stub(capturedVisits); assertFalse(treeTraversal.traverse(root, mockChildExpansion, mockObjectVisitor)); List<ObjectWithVisit> expected = Lists.newArrayList(new ObjectWithVisit(root, Visit.PreVisitDir)); assertEquals(expected, capturedVisits); } @Test public void testVisitorIsCalledInCorrectOrderWhenPostVisitDirectoryReturnsFalse() { VersionedObject root = newDirectory(); VersionedObject d1 = newDirectory(); VersionedObject f1 = newFile(); VersionedObject f2 = newFile(); VersionedObject f3 = newFile(); when(mockChildExpansion.apply(root)).thenReturn(Arrays.asList(d1, f1)); when(mockChildExpansion.apply(d1)).thenReturn(Arrays.asList(f2, f3)); List<ObjectWithVisit> capturedVisits = new ArrayList<>(); new MockVisitorStubber().withVisitToReturnFalse(d1, Visit.PostVisitDir).stub(capturedVisits); assertFalse(treeTraversal.traverse(root, mockChildExpansion, mockObjectVisitor)); List<ObjectWithVisit> expected = Lists.newArrayList( new ObjectWithVisit(root, Visit.PreVisitDir), new ObjectWithVisit(d1, Visit.PreVisitDir), new ObjectWithVisit(f2, Visit.VisitFile), new ObjectWithVisit(f3, Visit.VisitFile)); assertEquals(expected, capturedVisits); } @Test public void testVisitorIsCalledInCorrectOrderWhenPostVisitDirectoryThrowsError() { VersionedObject root = newDirectory(); VersionedObject d1 = newDirectory(); VersionedObject f1 = newFile(); VersionedObject f2 = newFile(); VersionedObject f3 = newFile(); when(mockChildExpansion.apply(root)).thenReturn(Arrays.asList(d1, f1)); when(mockChildExpansion.apply(d1)).thenReturn(Arrays.asList(f2, f3)); List<ObjectWithVisit> capturedVisits = new ArrayList<>(); new MockVisitorStubber().withVisitToThrowError(d1, Visit.PostVisitDir).stub(capturedVisits); assertFalse(treeTraversal.traverse(root, mockChildExpansion, mockObjectVisitor)); List<ObjectWithVisit> expected = Lists.newArrayList( new ObjectWithVisit(root, Visit.PreVisitDir), new ObjectWithVisit(d1, Visit.PreVisitDir), new ObjectWithVisit(f2, Visit.VisitFile), new ObjectWithVisit(f3, Visit.VisitFile)); assertEquals(expected, capturedVisits); } private VersionedObject newDirectory() { ObjectMetadata metadata = ObjectMetadata.builder() .key(new Path("ks://bucket/" + UUID.randomUUID().toString())) .isDirectory(true) .size(0) .creationTime(Instant.now().getEpochSecond()) .physicalPath(Optional.empty()) .build(); return VersionedObject.builder() .metadata(metadata) .id(UUID.randomUUID()) .version(1) .build(); } private VersionedObject newFile() { ObjectMetadata metadata = ObjectMetadata.builder() .key(new Path("ks://bucket/" + UUID.randomUUID().toString())) .isDirectory(false) .size(100) .creationTime(Instant.now().getEpochSecond()) .physicalPath(UUID.randomUUID().toString()) .physicalDataCommitted(true) .build(); return VersionedObject.builder() .metadata(metadata) .version(1) .id(UUID.randomUUID()) .build(); } private class MockVisitorStubber { private Visit visitToReturnFalse; private Visit visitToThrowError; private VersionedObject failedObject; MockVisitorStubber withVisitToReturnFalse(VersionedObject object, Visit visit) { this.visitToReturnFalse = visit; this.failedObject = object; return this; } MockVisitorStubber withVisitToThrowError(VersionedObject object, Visit visit) { this.visitToThrowError = visit; this.failedObject = object; return this; } void stub(List<ObjectWithVisit> captureList) { when(mockObjectVisitor.preVisitDirectoryObject(any())) .thenAnswer( it -> { VersionedObject object = (VersionedObject) it.getArguments()[0]; if (Visit.PreVisitDir == visitToReturnFalse && object.equals(failedObject)) { return false; } if (Visit.PreVisitDir == visitToThrowError && object.equals(failedObject)) { throw new RuntimeException(); } captureList.add(new ObjectWithVisit(object, Visit.PreVisitDir)); return true; }); when(mockObjectVisitor.postVisitDirectoryObject(any())) .thenAnswer( it -> { VersionedObject object = (VersionedObject) it.getArguments()[0]; if (Visit.PostVisitDir == visitToReturnFalse && object.equals(failedObject)) { return false; } if (Visit.PostVisitDir == visitToThrowError && object.equals(failedObject)) { throw new RuntimeException(); } captureList.add(new ObjectWithVisit(object, Visit.PostVisitDir)); return true; }); when(mockObjectVisitor.visitFileObject(any())) .thenAnswer( it -> { VersionedObject object = (VersionedObject) it.getArguments()[0]; if (Visit.VisitFile == visitToReturnFalse && object.equals(failedObject)) { return false; } if (Visit.VisitFile == visitToThrowError && object.equals(failedObject)) { throw new RuntimeException(); } captureList.add(new ObjectWithVisit(object, Visit.VisitFile)); return true; }); } } private enum Visit { PreVisitDir, VisitFile, PostVisitDir } private static class ObjectWithVisit { final VersionedObject object; final Visit visit; public ObjectWithVisit(VersionedObject object, Visit visit) { this.object = object; this.visit = visit; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ObjectWithVisit that = (ObjectWithVisit) o; if (!object.equals(that.object)) { return false; } return visit == that.visit; } @Override public int hashCode() { int result = object.hashCode(); result = 31 * result + visit.hashCode(); return result; } } }
37.697605
97
0.694147
b3904dbf1ef3b4fffca8f75a4ec77a2db6809b86
7,622
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.photos.library.sample.views; import com.google.photos.library.sample.components.ConnectToPhotosButton; import com.google.photos.library.sample.helpers.UIHelper; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.Consumer; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; /** * An {@link AbstractCustomView} that lets user login to Google Photos via API. */ public final class ConnectToPhotosView extends AbstractCustomView { private static final String CREDENTIAL_CHOOSER_TITLE = "Select credential file"; private static final Dimension WINDOW_DIMENSION = new Dimension(775 /* width */, 428 /* height */); private static final Border WINDOW_PADDING = new EmptyBorder(54 /* top */, 44 /* left */, 54 /* bottom */, 44 /* right */); private static final int SAMPLE_IMAGE_WIDTH = 164; private static final int SAMPLE_IMAGE_HEIGHT = 164; private static final Border SAMPLE_IMAGE_PADDING = new EmptyBorder(0 /* top */, 56 /* left */, 0 /* bottom */, 56 /* right */); private final String title; private final String introduction; private final String sampleImageResource; private final Optional<String> credentialsFile; private final BiConsumer<ConnectToPhotosView, String> onCredentialsSelected; private final Consumer<ConnectToPhotosView> onClosed; public ConnectToPhotosView( String title, String introduction, String sampleImageResource, Optional<String> credentialsFile, BiConsumer<ConnectToPhotosView, String> onCredentialsSelected, Consumer<ConnectToPhotosView> onClosed) { this.title = title; this.introduction = introduction; this.sampleImageResource = sampleImageResource; this.credentialsFile = credentialsFile; this.onCredentialsSelected = onCredentialsSelected; this.onClosed = onClosed; UIHelper.setFixedSize(this, WINDOW_DIMENSION); initializeView(); } @Override protected void initialize() { initializeDialog(title, onClosed); JPanel contentPanel = initializeContentPanel(); contentPanel.add(getIntroLabel(introduction), BorderLayout.CENTER); contentPanel.add(getSampleIconLabel(sampleImageResource), BorderLayout.LINE_END); contentPanel.add( getConnectPanel(onCredentialsSelected, credentialsFile), BorderLayout.PAGE_END); } @Override protected void update() { } /** * Sets up title, size and layout of the view. */ private void initializeDialog(String title, Consumer<ConnectToPhotosView> onClosed) { setTitle(title); setLayout(new GridLayout(1 /* rows */, 1 /* cols */)); final ConnectToPhotosView self = this; addWindowListener( new WindowAdapter() { @Override public void windowClosing(WindowEvent windowEvent) { onClosed.accept(self); } }); } /** * Creates a border-layout panel with padding. */ private JPanel initializeContentPanel() { JPanel contentPanel = new JPanel(); contentPanel.setLayout(new BorderLayout()); contentPanel.setBorder(WINDOW_PADDING); add(contentPanel); return contentPanel; } private JLabel getIntroLabel(String introduction) { JLabel introLabel = new JLabel(introduction); introLabel.setVerticalAlignment(SwingConstants.TOP); introLabel.setHorizontalAlignment(SwingConstants.LEFT); return introLabel; } private JLabel getSampleIconLabel(String sampleImageResource) { ImageIcon originalImage = new ImageIcon(ConnectToPhotosView.class.getResource(sampleImageResource)); JLabel iconLabel = new JLabel( new ImageIcon( originalImage .getImage() .getScaledInstance( SAMPLE_IMAGE_WIDTH, SAMPLE_IMAGE_HEIGHT, Image.SCALE_SMOOTH))); iconLabel.setVerticalAlignment(SwingConstants.CENTER); iconLabel.setBorder(SAMPLE_IMAGE_PADDING); return iconLabel; } private JPanel getConnectPanel( BiConsumer<ConnectToPhotosView, String> onCredentialsSelected, Optional<String> credentialsFile) { JPanel connectPanel = new JPanel(); connectPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); if (credentialsFile.isPresent()) { // Add a connect button that loads the supplied credentials file. connectPanel.add(getConnectButton(onCredentialsSelected, credentialsFile.get())); } else { // Add a connect button that prompts the user for the credentials file. connectPanel.add(getConnectButton(onCredentialsSelected)); } return connectPanel; } /** * Creates a button that uses the given credential file. */ private ConnectToPhotosButton getConnectButton( BiConsumer<ConnectToPhotosView, String> onCredentialsSelected, String credentialsPath) { ConnectToPhotosButton connectButton = new ConnectToPhotosButton(); connectButton.addActionListener( actionEvent -> onCredentialsSelected.accept(this, credentialsPath)); return connectButton; } /** * Creates a button that lets user choose a credential file. */ private ConnectToPhotosButton getConnectButton( BiConsumer<ConnectToPhotosView, String> onCredentialsSelected) { ConnectToPhotosButton connectButton = new ConnectToPhotosButton(); connectButton.addActionListener( actionEvent -> { Optional<String> chosenFilePath = chooseCredentialsPath(); if (chosenFilePath.isPresent()) { onCredentialsSelected.accept(this, chosenFilePath.get()); } }); return connectButton; } private Optional<String> chooseCredentialsPath() { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle(CREDENTIAL_CHOOSER_TITLE); int returnVal = fileChooser.showDialog(this, null); if (returnVal == JFileChooser.APPROVE_OPTION) { return Optional.of(fileChooser.getSelectedFile().getPath()); } return Optional.empty(); } }
37.920398
111
0.666754
8ff0d1409c8502c8c08affa438681af08b69f30d
13,324
package com.github.CCwexiao.dsl.manual; import com.github.CCweixiao.constant.HMHBaseConstant; import com.github.CCweixiao.exception.HBaseOperationsException; import com.github.CCwexiao.dsl.auto.HBaseSQLParser.*; import com.github.CCwexiao.dsl.client.QueryExtInfo; import com.github.CCwexiao.dsl.client.RowKey; import com.github.CCwexiao.dsl.client.rowkeytextfunc.RowKeyTextFunc; import com.github.CCwexiao.dsl.config.HBaseColumnSchema; import com.github.CCwexiao.dsl.config.HBaseSQLRuntimeSetting; import com.github.CCwexiao.dsl.config.HBaseTableConfig; import com.github.CCwexiao.dsl.manual.visitor.*; import com.github.CCwexiao.dsl.util.Util; import org.antlr.v4.runtime.tree.TerminalNode; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; /** * @author leojie 2020/11/27 10:31 下午 */ public class HBaseSQLContextUtil { /** * 从CidContext中解析HBaseTableSchema * * @param hbaseTableConfig HBase表信息 * @param cidContext CidContext * @return HBaseColumnSchema */ public static HBaseColumnSchema parseHBaseColumnSchema(HBaseTableConfig hbaseTableConfig, CidContext cidContext) { Util.checkNull(hbaseTableConfig); Util.checkNull(cidContext); String cid = cidContext.TEXT().getText(); String[] parts = cid.split(HMHBaseConstant.FAMILY_QUALIFIER_SEPARATOR); if (parts.length == 1) { return hbaseTableConfig.gethBaseTableSchema().findColumnSchema(parts[0]); } if (parts.length == 2) { return hbaseTableConfig.gethBaseTableSchema().findColumnSchema(parts[0], parts[1]); } throw new HBaseOperationsException("parseHBaseColumnSchema error. cid=" + cid); } /** * 从CidListContext解析HBaseColumnSchema列表 * * @param hBaseTableConfig HBase表信息 * @param cidListContext CidListContext * @return HBaseColumnSchema列表 */ public static List<HBaseColumnSchema> parseHBaseColumnSchemaList(HBaseTableConfig hBaseTableConfig, CidListContext cidListContext) { Util.checkNull(hBaseTableConfig); Util.checkNull(cidListContext); List<HBaseColumnSchema> result = new ArrayList<>(); for (CidContext cidContext : cidListContext.cid()) { result.add(parseHBaseColumnSchema(hBaseTableConfig, cidContext)); } return result; } /** * 从SelectCidListContext解析HBaseColumnSchema列表 * * @param hBaseTableConfig HBase表信息 * @param selectCidListContext SelectCidListContext * @return HBaseColumnSchema列表 */ public static List<HBaseColumnSchema> parseHBaseColumnSchemaList(HBaseTableConfig hBaseTableConfig, SelectCidListContext selectCidListContext) { Util.checkNull(hBaseTableConfig); Util.checkNull(selectCidListContext); SelectCidListVisitor visitor = new SelectCidListVisitor(hBaseTableConfig); return selectCidListContext.accept(visitor); } /** * 解析参数 * * @param varContext 参数上下文 # name # * @param para 所有传参 * @return 解析出的数据 */ public static Object parsePara(VarContext varContext, Map<String, Object> para) { Util.checkNull(varContext); Util.checkNull(para); String var = varContext.TEXT().getText(); Util.checkEmptyString(var); Object obj = para.get(var); Util.checkNull(obj); return obj; } /** * 解析 select 语法上下文 * * @param progContext 全局语句上下文 * @return select 语法上下文 */ public static SelecthqlcContext parseSelecthqlcContext(ProgContext progContext) { Util.checkNull(progContext); SelectHqlClContext selectHqlClContext = (SelectHqlClContext) progContext; SelecthqlcContext result = selectHqlClContext.selecthqlc(); Util.checkNull(result); return result; } /** * 解析 insert 语法上下文 * * @param progContext 全局语句上下文 * @return insert 语法上下文 */ public static InserthqlcContext parseInserthqlcContext(ProgContext progContext) { Util.checkNull(progContext); InsertHqlClContext insertHqlClContext = (InsertHqlClContext) progContext; InserthqlcContext result = insertHqlClContext.inserthqlc(); Util.checkNull(result); return result; } /** * 解析 delete 语法上下文 * * @param progContext 全局语句上下文 * @return delete 语法上下文 */ public static DeletehqlcContext parseDeletehqlcContext(ProgContext progContext) { Util.checkNull(progContext); DeleteHqlClContext deleteHqlClContext = (DeleteHqlClContext) progContext; DeletehqlcContext result = deleteHqlClContext.deletehqlc(); Util.checkNull(progContext); return result; } /** * 时间戳转换 * * @param tsexpContext 时间戳表达式 * @return long型时间戳 */ public static long parseTimeStamp(TsexpContext tsexpContext) { Util.checkNull(tsexpContext); String constant = tsexpContext.constant().TEXT().getText(); Util.checkEmptyTimestamp(constant); return Long.parseLong(constant); } public static Date parseTimeStampDate(TsexpContext tsexpContext, HBaseSQLRuntimeSetting runtimeSetting) { Util.checkNull(tsexpContext); Util.checkNull(runtimeSetting); try { long timestamp = parseTimeStamp(tsexpContext); Date date = new Date(timestamp); Util.checkNull(date); return date; } catch (Exception e) { throw new HBaseOperationsException("please enter a 13-bit Unix timestamp."); } } /** * 解析时间戳 * * @param tsrangeContext 解析时间戳范围 * @return 时间戳范围 */ public static TimeStampRange parseTimeStampRange(TsrangeContext tsrangeContext) { Util.checkNull(tsrangeContext); TimeStampRangeVisitor visitor = new TimeStampRangeVisitor(); TimeStampRange timeStampRange = tsrangeContext.accept(visitor); Util.checkNull(timeStampRange); return timeStampRange; } /** * 解析row Key * * @param rowKeyExpContext row key表达式上下文 * @param hBaseSQLRuntimeSetting HBase SQL 运行时配置 * @return rowKey */ public static RowKey parseRowKey(RowKeyExpContext rowKeyExpContext, HBaseSQLRuntimeSetting hBaseSQLRuntimeSetting) { Util.checkNull(rowKeyExpContext); Util.checkNull(hBaseSQLRuntimeSetting); RowKeyConstantVisitor visitor = new RowKeyConstantVisitor(hBaseSQLRuntimeSetting); RowKey rowKey = rowKeyExpContext.accept(visitor); Util.checkNull(rowKey); return rowKey; } /** * 解析IN语法中的rowKey列表 * @param rowKeyExpContext row key exp * @param hBaseSQLRuntimeSetting HBase SQL运行时配置 * @return rowKey列表 */ public static List<RowKey> parseRowKeyList(RowKeyExpContext rowKeyExpContext, HBaseSQLRuntimeSetting hBaseSQLRuntimeSetting) { Util.checkNull(rowKeyExpContext); Util.checkNull(hBaseSQLRuntimeSetting); //RowKeyInSomeKeysVisitor visitor = new RowKeyInSomeKeysVisitor(hBaseSQLRuntimeSetting); RowKeyListConstantVisitor visitor = new RowKeyListConstantVisitor(hBaseSQLRuntimeSetting); final List<RowKey> rowKeyList = rowKeyExpContext.accept(visitor); if(rowKeyList == null|| rowKeyList.isEmpty()){ throw new HBaseOperationsException("please enter one or more row key."); } return rowKeyList; } /** * 从SQL中解析row key的自定义函数 * @param rowKeyExpContext row key表达式上下文 * @param hBaseSQLRuntimeSetting HBase SQL 运行时配置 * @return RowKeyTextFunc */ public static RowKeyTextFunc parseRowKeyFunction(RowKeyExpContext rowKeyExpContext, HBaseSQLRuntimeSetting hBaseSQLRuntimeSetting){ Util.checkNull(rowKeyExpContext); Util.checkNull(hBaseSQLRuntimeSetting); RowKeyFunctionVisitor visitor = new RowKeyFunctionVisitor(hBaseSQLRuntimeSetting); final RowKeyTextFunc rowKeyTextFunc = rowKeyExpContext.accept(visitor); Util.checkNull(rowKeyTextFunc); return rowKeyTextFunc; } /** * 解析 rowKey range * * @param rowKeyRangeContext rowKeyRange 表达式 * @param hBaseSQLRuntimeSetting HBase SQL 运行时配置 * @return rowKeyRange */ public static RowKeyRange parseRowKeyRange(RowKeyRangeContext rowKeyRangeContext, HBaseSQLRuntimeSetting hBaseSQLRuntimeSetting) { Util.checkNull(rowKeyRangeContext); Util.checkNull(hBaseSQLRuntimeSetting); RowKeyRangeVisitor visitor = new RowKeyRangeVisitor(hBaseSQLRuntimeSetting); RowKeyRange rowKeyRange = rowKeyRangeContext.accept(visitor); Util.checkNull(rowKeyRange); return rowKeyRange; } public static RowKeyRange parseRowKeyRange2(RowKeyRangeContext rowKeyRangeContext, HBaseSQLRuntimeSetting hBaseSQLRuntimeSetting){ Util.checkNull(rowKeyRangeContext); Util.checkNull(hBaseSQLRuntimeSetting); RowKeyRangeVisitor visitor = new RowKeyRangeVisitor(hBaseSQLRuntimeSetting); RowKeyRange rowKeyRange = rowKeyRangeContext.accept(visitor); Util.checkNull(rowKeyRange); return rowKeyRange; } public static Object parseInsertConstantValue(HBaseColumnSchema hbaseColumnSchema, InsertValueContext insertValueContext, HBaseSQLRuntimeSetting runtimeSetting) { Util.checkNull(hbaseColumnSchema); Util.checkNull(insertValueContext); Util.checkNull(runtimeSetting); InsertValueVisitor visitor = new InsertValueVisitor(hbaseColumnSchema, runtimeSetting); return insertValueContext.accept(visitor); } /** * 解析字段赋值变量 * * @param hBaseColumnSchema HBase字段定义数据模型 * @param constantContext 字段上下文 * @param runtimeSetting 运行时设置 * @return 解析字段值 */ public static Object parseConstant(HBaseColumnSchema hBaseColumnSchema, ConstantContext constantContext, HBaseSQLRuntimeSetting runtimeSetting) { Util.checkNull(hBaseColumnSchema); Util.checkNull(constantContext); Util.checkNull(runtimeSetting); String constant = constantContext.TEXT().getText(); Util.checkEmptyString(constant); Object obj = runtimeSetting.interpret(hBaseColumnSchema.getType(), constant); Util.checkNull(obj); return obj; } /** * 解析参数列表 * * @param varContextList 参数列表 * @param para 参数key * @return 获取参数值 */ public static List<Object> parseParaList(List<VarContext> varContextList, Map<String, Object> para) { Util.checkNull(varContextList); Util.checkNull(para); List<Object> result = new ArrayList<>(); for (VarContext varContext : varContextList) { result.add(parsePara(varContext, para)); } return result; } public static List<Object> parseConstantList(HBaseColumnSchema hBaseColumnSchema, List<ConstantContext> constantContextList, HBaseSQLRuntimeSetting runtimeSetting) { Util.checkNull(hBaseColumnSchema); Util.checkNull(constantContextList); Util.checkNull(runtimeSetting); List<Object> result = new ArrayList<>(); for (ConstantContext constantContext : constantContextList) { result.add(parseConstant(hBaseColumnSchema, constantContext, runtimeSetting)); } return result; } public static QueryExtInfo parseQueryExtInfo(SelecthqlcContext selecthqlcContext) { Util.checkNull(selecthqlcContext); QueryExtInfo queryExtInfo = new QueryExtInfo(); // 解析最大版本号 MaxVersionExpContext maxVersionExpContext = selecthqlcContext.maxVersionExp(); if (maxVersionExpContext != null) { queryExtInfo.setMaxVersions(Integer.parseInt(maxVersionExpContext.maxversion().TEXT().getText())); } // 解析起止时间戳范围 TsrangeContext tsrangeContext = selecthqlcContext.tsrange(); if (tsrangeContext != null) { TimeStampRange timeStampRange = parseTimeStampRange(tsrangeContext); queryExtInfo.setTimeRange(timeStampRange.getStart(), timeStampRange.getEnd()); } // 解析limit LimitExpContext limitExpContext = selecthqlcContext.limitExp(); if (limitExpContext != null) { final List<TerminalNode> terminalNodeList = limitExpContext.TEXT(); Util.checkLimitIsValid(terminalNodeList.size() == 1 || terminalNodeList.size() == 2); if (terminalNodeList.size() == 1) { queryExtInfo.setLimit(0L, Long.parseLong(terminalNodeList.get(0).getText())); } if (terminalNodeList.size() == 2) { queryExtInfo.setLimit(Long.parseLong(terminalNodeList.get(0).getText()), Long.parseLong(terminalNodeList.get(1).getText())); } } return queryExtInfo; } private HBaseSQLContextUtil() { } }
33.817259
148
0.672321
19a1ad2982f606ebc27cbb545d77a50dfe31adfd
2,668
/* * Project:Easy Web Framework * Description: * EasyFK stands for Easy Web Framework.It's an open source product for E-Business / E-Commerce.It * was launched by a chinese Hezhiping(QQ:110476592) in 2015.The goal of EasyFK is to provide a * foundation and starting point for reliable, secure , simple-to-use ,cost-effective ,scalable * and suitable-for-Chinese E-Business / E-Commerce solutions. With EasyFK, you can get started * right away without the huge deployment and maintenance costs of E-Business / E-Commerce systems. * Of course, you can customize it or use it as a framework to implement your most challenging business needs. * EasyFk is licensed under the Apache License Version 2.0. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Author:hezhiping Email:110476592@qq.com */ package cn.gorun8.easyfk.security.shiro; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import cn.gorun8.easyfk.base.util.Debug; import cn.gorun8.easyfk.base.util.UtilIOC; import cn.gorun8.easyfk.base.util.collections.ResourceBundleMessageSource; import org.apache.shiro.web.servlet.OncePerRequestFilter; public class RequestInitFilter extends OncePerRequestFilter { private final static String module = RequestInitFilter.class.getName(); private final static String FILTERED_FLG = "FILTERED_FLG"; private ResourceBundleMessageSource uiLabelMap; public ResourceBundleMessageSource getUiLabelMap() { return uiLabelMap; } public void setUiLabelMap(ResourceBundleMessageSource uiLabelMap) { this.uiLabelMap = uiLabelMap; } @Override protected void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { HttpServletRequest req = (HttpServletRequest)request; if(request.getAttribute(FILTERED_FLG) != null) { chain.doFilter(request, response); return ; } request.setAttribute(FILTERED_FLG, true); try { if(uiLabelMap != null) { String labelMapName = uiLabelMap.getLabelMapName(); request.setAttribute(labelMapName, uiLabelMap); } }catch (Exception e){ e.printStackTrace(); Debug.logWarning("i18n resource not found",module); } String ctx = req.getContextPath(); request.setAttribute("ctx", ctx); chain.doFilter(request, response); } }
38.114286
143
0.727136
18b4d019ffd43c1fc0b93b62fd433cb648584365
1,265
package utilities; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsIterableContainingInOrder.contains; import static org.hamcrest.core.Is.is; import static utilities.Collections.newCollection; import static utilities.Streams.fromOptionals; import static utilities.Streams.reverseRange; import static utilities.Streams.reverseRangeClosed; public class StreamsTest { @Test public void testReverseRange() { assertThat(collect(reverseRange(0, 5)), is(newCollection(4, 3, 2, 1, 0))); } @Test public void testReverseRangeClosed() { assertThat(collect(reverseRangeClosed(0, 5)), is(newCollection(5, 4, 3, 2, 1, 0))); } @Test public void testFromOptionals() { assertThat(fromOptionals(newCollection(Optional.of("foo"), Optional.empty(), Optional.of("bar"))).collect(Collectors.toList()), contains("foo", "bar")); } private Collection<Integer> collect(final IntStream intStream) { return intStream.collect(ArrayList::new, Collection::add, Collections::flatten); } }
30.853659
160
0.741502
f810aca7204a0e30b045a2e1e1c4c28c34688914
2,912
/* * MIT License * * Copyright (c) 2021 Hydrologic Engineering Center * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package mil.army.usace.hec.cwms.radar.client.controllers; import static mil.army.usace.hec.cwms.http.client.EndpointInput.ACCEPT_QUERY_HEADER; import static mil.army.usace.hec.cwms.radar.client.controllers.TimeSeriesGroupEndpointInput.CATEGORY_ID_QUERY_PARAMETER; import static mil.army.usace.hec.cwms.radar.client.controllers.TimeSeriesGroupEndpointInput.OFFICE_QUERY_PARAMETER; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import org.junit.jupiter.api.Test; class TestTimeSeriesGroupEndpointInput { @Test void testTimeSeriesGroupEndpointInputGetAll() { TimeSeriesGroupEndpointInput timeSeriesCategoryEndpointInput = new TimeSeriesGroupEndpointInput(); assertFalse(timeSeriesCategoryEndpointInput.getGroupId().isPresent()); } @Test void testTimeSeriesGroupEndpointInputCategoryId() { TimeSeriesGroupEndpointInput timeSeriesCategoryEndpointInput = new TimeSeriesGroupEndpointInput("category-id", "group-id"); assertEquals("group-id", timeSeriesCategoryEndpointInput.getGroupId().get()); } @Test void testQueryRequest() { MockHttpRequestBuilder mockHttpRequestBuilder = new MockHttpRequestBuilder(); TimeSeriesGroupEndpointInput input = new TimeSeriesGroupEndpointInput("category-id", "group-id") .officeId("SWT"); input.addInputParameters(mockHttpRequestBuilder); assertEquals("category-id", mockHttpRequestBuilder.getQueryParameter(CATEGORY_ID_QUERY_PARAMETER)); assertEquals("SWT", mockHttpRequestBuilder.getQueryParameter(OFFICE_QUERY_PARAMETER)); assertEquals("application/json", mockHttpRequestBuilder.getQueryHeader(ACCEPT_QUERY_HEADER)); } }
48.533333
131
0.779533
0aae890a272999e3b7f1aa56eec2dfca299de7f0
1,287
/* * Copyright 2021 EPAM Systems, Inc * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. 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.epam.deltix.test.qsrv.hf.tickdb; import org.junit.BeforeClass; import java.io.IOException; import org.junit.experimental.categories.Category; import com.epam.deltix.util.JUnitCategories.TickDBFast; /** * @author BazylevD * Tests interpreted codecs. See Test_Decoder4Truncated for details.</p> */ @Category(TickDBFast.class) public class Test_Decoder4TruncatedIntp extends Test_Decoder4Truncated { @BeforeClass public static void setUpClass() throws IOException, InterruptedException { System.setProperty("use.codecs", "interpreted"); } }
33.868421
80
0.762238
61562c2f83be6d81f2c9815b8144e75489f5a41b
1,141
package es.cic.curso.curso06.ejercicio016.repository; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import es.cic.curso.curso06.ejercicio016.domain.*; @Repository @Transactional public class RepositorySesionImpl implements RepositorySesion { @PersistenceContext private EntityManager manager; @Override public Sesion create(Sesion element) { manager.persist(element); return element; } @Override public Sesion read(Long id) { Sesion resultado = manager.find(Sesion.class, id); return resultado; } @Override public Sesion update(Sesion element) { element = manager.merge(element); return element; } @Override public Sesion delete(Long id) { Sesion sesion = new Sesion(); sesion.setId(id); Sesion resultado = manager.merge(sesion); manager.remove(resultado); return resultado; } @Override public List<Sesion> list() { return manager.createNativeQuery("SELECT * FROM SESION", Sesion.class).getResultList(); } }
20.745455
89
0.767748
b59077a600c9057d4fd5d7d4a700afa28c7e65e0
298
package husacct.bootstrap; import java.awt.Frame; public class Minimize extends AbstractBootstrap { @Override public void execute() { this.getControlService().getMainController().getMainGui().setState ( Frame.ICONIFIED ); } @Override public void execute(String[] args) { execute(); } }
19.866667
89
0.741611
1975798bae90c30b9a17e5e0ce2dfe02ac4b3699
3,192
package DataStructures; public class BinarySearchTree { private BSTNode root; public Boolean containNode(int value) { return containRecursiveNode(root, value); } public void add(int value) { setRoot(addRecursive(getRoot(), value)); } public void delete(int value) { root = deleteRecursive(root, value); } public int findLargestValue() { return findLargestValue(root); } public int findSmallestValue() { return findSmallestValue(root); } public void queryInOrder() { traverseInOrder(root); } public void queryPostOrder() { traversePostOrder(root); } public void queryPreOrder() { traversePreOrder(root); } // In Order: left, current, right private void traverseInOrder (BSTNode current) { if (current != null) { traverseInOrder(current.getLeft()); System.out.print(" " + current.getVal()); traverseInOrder(current.getRight()); } } // Pre Order: current, left, right private void traversePreOrder (BSTNode current) { if (current != null) { System.out.print(" " + current.getVal()); traversePreOrder(current.getLeft()); traversePreOrder(current.getRight()); } } // Post Order: left, right, current private void traversePostOrder (BSTNode current) { if (current != null) { traversePostOrder(current.getLeft()); traversePostOrder(current.getRight()); System.out.print(" " + current.getVal()); } } // Recursive find largest value private int findLargestValue(BSTNode current) { return current.getRight() == null ? current.getVal() : findSmallestValue(current.getRight()); } // Recursive find smallest value private int findSmallestValue(BSTNode current) { return current.getLeft() == null ? current.getVal() : findSmallestValue(current.getLeft()); } // Recursive delete private BSTNode deleteRecursive(BSTNode current, int value) { if (current == null) return null; if (value == current.getVal()) { if (current.getLeft() == null && current.getRight() == null) return null; if (current.getLeft() == null) return current.getRight(); if (current.getRight() == null) return current.getLeft(); } if (value < current.getVal()) { current.setLeft(deleteRecursive(current.getLeft(), value)); return current; } // value > current.getVal() current.setRight(deleteRecursive(current.getRight(), value)); return current; } // Recursively check if containing a Node private Boolean containRecursiveNode(BSTNode current, int value) { if (current == null) return false; if (current.getVal() == value) return true; return current.getVal() < value ? containRecursiveNode(current.getLeft(), value) : containRecursiveNode(current.getRight(), value); } // Recursively add Node in the tree private BSTNode addRecursive(BSTNode current, int value) { if (current == null) return new BSTNode(value); if (value < current.getVal()) current.setLeft(addRecursive(current.getLeft(), value)); else if (value > current.getVal()) current.setRight(addRecursive(current.getRight(), value)); else return current; return current; } public BSTNode getRoot() { return root; } public void setRoot(BSTNode root) { this.root = root; } }
26.380165
95
0.698935
1578cb0d4efe69e57aaf795f10fc73f85618ea73
4,420
/* * Copyright 2009 University Corporation for Advanced Internet Development, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openxrd.discovery.impl; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.util.EntityUtils; import org.htmlparser.Parser; import org.htmlparser.Tag; import org.htmlparser.tags.BodyTag; import org.htmlparser.tags.HeadTag; import org.htmlparser.util.ParserException; import org.htmlparser.visitors.NodeVisitor; import org.opensaml.xml.util.LazyList; import org.openxrd.common.XRDConstants; import org.openxrd.discovery.DiscoveryException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Discovery Method which retrieves the location of the XRD Document from Http Headers. */ public class HtmlLinkDiscoveryMethod extends AbstractHttpDiscoveryMethod { /** Logger. */ private static final Logger LOG = LoggerFactory.getLogger(HtmlLinkDiscoveryMethod.class); /** {@inheritDoc} */ public URI getXRDLocation(URI uri) throws DiscoveryException { try { HttpResponse response = fetch(uri); HttpEntity entity = response.getEntity(); if (entity == null) { entity.consumeContent(); return null; } String content = EntityUtils.toString(entity); Parser htmlParser = Parser.createParser(content, null); LinkVisitor linkVisitor = new LinkVisitor(); htmlParser.visitAllNodesWith(linkVisitor); for (Tag tag : linkVisitor.getLinks()) { if (!XRDConstants.XRD_MIME_TYPE.equals(tag.getAttribute("type"))) { continue; } if (!XRDConstants.XRD_REL_DESCRIBEDBY.equalsIgnoreCase(tag.getAttribute("rel"))) { continue; } try { URL xrdLocation = new URL(uri.toURL(), tag.getAttribute("href")); LOG.debug("Found XRD location: {}", xrdLocation.toString()); return xrdLocation.toURI(); } catch (URISyntaxException e) { continue; } } return null; } catch (IOException e) { throw new DiscoveryException(e); } catch (ParserException e) { throw new DiscoveryException(e); } } /** * Node Visitor implementation that stores all HTML Link elements that appear inside of the HTML Head element. */ private class LinkVisitor extends NodeVisitor { /** Whether the parser is currently inside the HTML Head element. */ private boolean inHead; /** List of HTML link elements. */ private List<Tag> links; /** Constructor. */ public LinkVisitor() { inHead = false; links = new LazyList<Tag>(); } /** {@inheritDoc} */ public void visitTag(Tag tag) { if (tag instanceof HeadTag) { inHead = true; } else if (tag instanceof BodyTag) { inHead = false; } else if (tag.getTagName().equalsIgnoreCase("link")) { if (inHead) { links.add(tag); } } } /** {@inheritDoc} */ public void visitEndTag(Tag tag) { if (tag.getTagName().equalsIgnoreCase("head")) { inHead = false; } } /** * Get the list of HTML Link elements. * * @return the list of HTML Link elements */ public List<Tag> getLinks() { return links; } } }
31.798561
114
0.598643
4d053fefaef52610001c5e2ec79f95e264df9af1
1,563
package ru.soknight.packetinventoryapi.nms.proxy.v1_16_R3.packet.server; import com.comphenix.protocol.events.PacketContainer; import org.bukkit.inventory.MerchantRecipe; import ru.soknight.packetinventoryapi.packet.server.PacketServerTradeList; import ru.soknight.packetinventoryapi.packet.server.WrappedServerPacket; import java.util.List; public class SimplePacketServerTradeList extends WrappedServerPacket implements PacketServerTradeList { public SimplePacketServerTradeList() { super(PacketServerTradeList.PACKET_TYPE); } public SimplePacketServerTradeList(PacketContainer container) { super(container); } @Override public PacketServerTradeList windowID(int value) { handle.getIntegers().write(0, value); return this; } @Override public PacketServerTradeList trades(List<MerchantRecipe> trades) { handle.getMerchantRecipeLists().write(0, trades); return this; } @Override public PacketServerTradeList villagerLevel(int value) { handle.getIntegers().write(1, value); return this; } @Override public PacketServerTradeList experience(int value) { handle.getIntegers().write(2, value); return this; } @Override public PacketServerTradeList regularVillager(boolean value) { handle.getBooleans().write(0, value); return this; } @Override public PacketServerTradeList canRestock(boolean value) { handle.getBooleans().write(1, value); return this; } }
27.421053
103
0.715291
4dc4f9ee80a022a13b76316b01fb2e18c6657359
549
package io.lambdacube.bnd.component.annotation.properties; public final class AnnotationPropMethod { public final String propName; public final String typeName; public final boolean isArray; public final String annotationMethodName; public AnnotationPropMethod(String propName, String typeName, boolean isArray, String annotationMethodName) { super(); this.propName = propName; this.typeName = typeName; this.isArray = isArray; this.annotationMethodName = annotationMethodName; } }
30.5
113
0.728597
660bdc0f376f5522c33324f273ebeab1a45568cb
2,643
package hr.fer.zemris.jcms.web.actions2; import java.io.IOException; import hr.fer.zemris.jcms.service2.ActivityService; import hr.fer.zemris.jcms.web.actions.Ext2ActionSupport; import hr.fer.zemris.jcms.web.actions.annotations.DataResultMapping; import hr.fer.zemris.jcms.web.actions.annotations.Struts2ResultMapping; import hr.fer.zemris.jcms.web.actions.annotations.WebClass; import hr.fer.zemris.jcms.web.actions.annotations.WebMethodInfo; import hr.fer.zemris.jcms.web.actions.data.ActivityGoData; import hr.fer.zemris.jcms.web.navig.builders.BuilderDefault; /** * Ova akcija predstavlja "dispatcher" za aktivnosti. Kada se studentu prikaže popis aktivnosti, * generira se link koji kao argument ima identifikator aktivnosti. Ova se akcija poziva kada student * klikne na taj link, i trebala bi studenta odvesti na stranicu koja odgovara aktivnosti. * * @author marcupic * */ @WebClass(dataClass=ActivityGoData.class, defaultNavigBuilder=BuilderDefault.class) public class ActivityGo extends Ext2ActionSupport<ActivityGoData> { private static final long serialVersionUID = 1L; @WebMethodInfo( dataResultMappings={ @DataResultMapping(dataResult="RES_MP_VIEW",struts2Result="RES_MP_VIEW",registerDelayedMessages=false), @DataResultMapping(dataResult="RES_ITEM_VIEW",struts2Result="RES_ITEM_VIEW",registerDelayedMessages=false), @DataResultMapping(dataResult="RES_COURSEINSTANCE",struts2Result="RES_COURSEINSTANCE",registerDelayedMessages=false), @DataResultMapping(dataResult="RES_A_SUMMARYVIEW",struts2Result="RES_A_SUMMARYVIEW",registerDelayedMessages=false), @DataResultMapping(dataResult="RES_STUDENT_APPLICATION_VIEW",struts2Result="RES_STUDENT_APPLICATION_VIEW",registerDelayedMessages=false), @DataResultMapping(dataResult="RES_ISSUE_VIEW",struts2Result="RES_ISSUE_VIEW",registerDelayedMessages=false) }, struts2ResultMappings={ @Struts2ResultMapping(struts2Result="RES_MP_VIEW", navigBuilder=BuilderDefault.class), @Struts2ResultMapping(struts2Result="RES_ITEM_VIEW", navigBuilder=BuilderDefault.class), @Struts2ResultMapping(struts2Result="RES_COURSEINSTANCE", navigBuilder=BuilderDefault.class), @Struts2ResultMapping(struts2Result="RES_A_SUMMARYVIEW", navigBuilder=BuilderDefault.class), @Struts2ResultMapping(struts2Result="RES_STUDENT_APPLICATION_VIEW", navigBuilder=BuilderDefault.class), @Struts2ResultMapping(struts2Result="RES_ISSUE_VIEW", navigBuilder=BuilderDefault.class) } ) public String execute() throws IOException { ActivityService.dispatch(getEntityManager(), getData()); return null; } public void setAid(Long aid) { data.setAid(aid); } }
48.054545
140
0.820658
1cbdde27ddbce6d021c5eeac4f2b520960055547
1,513
/* * Copyright 2009-2017 Aconex * * Licensed under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.pcp.parfait; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; public class CompositeCounterTest { @Test public void incrementActionsIncrementAllSubcounters() { SimpleCounter first = new SimpleCounter(); SimpleCounter second = new SimpleCounter(); CompositeCounter counter = new CompositeCounter(Arrays.asList(first, second)); counter.inc(); Assert.assertEquals(1, first.value); Assert.assertEquals(1, second.value); counter.inc(10); Assert.assertEquals(11, first.value); Assert.assertEquals(11, second.value); } private static final class SimpleCounter implements Counter { private int value; @Override public void inc() { inc(1); } @Override public void inc(long increment) { value += increment; } } }
27.509091
86
0.672174
874b7885b63e6921ba04a6bd06e51867cda6e263
462
package fr.ign.validator.cnig.model; import org.apache.commons.lang.StringUtils; public class SupCategory { public static final String REGEXP = "[a-zA-Z0-9]+"; /** * Indicates if given parameter is a valid SUP category * * @param siren * @return */ public static boolean isValid(String value) { if (StringUtils.isEmpty(value)) { return false; } return value.matches(REGEXP); } }
20.086957
59
0.608225
a3489c9bf1facac2dbcb5b888953846ac0a2c9ad
5,833
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.storage.file.datalake; import com.azure.storage.common.StorageSharedKeyCredential; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Locale; /** * This example shows how to start using the Azure Storage Data Lake SDK for Java. */ public class BasicExample { /** * Entry point into the basic examples for Storage datalake. * * @param args Unused. Arguments to the program. * @throws IOException If an I/O error occurs * @throws RuntimeException If the downloaded data doesn't match the uploaded data */ public static void main(String[] args) throws IOException { /* * From the Azure portal, get your Storage account's name and account key. */ String accountName = SampleHelper.getAccountName(); String accountKey = SampleHelper.getAccountKey(); /* * Use your Storage account's name and key to create a credential object; this is used to access your account. */ StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey); /* * From the Azure portal, get your Storage account dfs service URL endpoint. * The URL typically looks like this: */ String endpoint = String.format(Locale.ROOT, "https://%s.dfs.core.windows.net", accountName); /* * Create a DataLakeServiceClient object that wraps the service endpoint, credential and a request pipeline. */ DataLakeServiceClient storageClient = new DataLakeServiceClientBuilder().endpoint(endpoint).credential(credential).buildClient(); /* * This example shows several common operations just to get you started. */ /* * Create a client that references a to-be-created file system in your Azure Storage account. This returns a * FileSystem object that wraps the file system's endpoint, credential and a request pipeline (inherited from storageClient). * Note that file system names require lowercase. */ DataLakeFileSystemClient dataLakeFileSystemClient = storageClient.getFileSystemClient("myjavafilesystembasic" + System.currentTimeMillis()); /* * Create a file system in Storage datalake account. */ dataLakeFileSystemClient.create(); /* * Create a directory in the filesystem */ DataLakeDirectoryClient directoryClient = dataLakeFileSystemClient.createDirectory("myDirectory"); /* * Create a file and sub directory in the directory */ DataLakeFileClient fileUnderDirectory = directoryClient.createFile("myFileName"); DataLakeDirectoryClient subDirectory = directoryClient.createSubdirectory("mySubDirectory"); System.out.println("File under myDirectory is " + fileUnderDirectory.getFileName()); System.out.println("Directory under myDirectory is " + subDirectory.getDirectoryName()); /* * Create a client that references a to-be-created file in your Azure Storage account's file system. * This returns a DataLakeFileClient object that wraps the file's endpoint, credential and a request pipeline * (inherited from dataLakeFileSystemClient). Note that file names can be mixed case. */ DataLakeFileClient fileClient = dataLakeFileSystemClient.getFileClient("HelloWorld.txt"); String data = "Hello world!"; InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); /* * Create the file with string (plain text) content. */ fileClient.create(); fileClient.append(dataStream, 0, data.length()); fileClient.flush(data.length()); dataStream.close(); /* * Download the file's content to output stream. */ int dataSize = (int) fileClient.getProperties().getFileSize(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(dataSize); fileClient.read(outputStream); outputStream.close(); /* * Verify that the file data round-tripped correctly. */ if (!data.equals(new String(outputStream.toByteArray(), StandardCharsets.UTF_8))) { throw new RuntimeException("The downloaded data does not match the uploaded data."); } /* * Create more files (maybe even a few directories) before listing. */ for (int i = 0; i < 3; i++) { String sampleData = "Samples"; InputStream dataInFiles = new ByteArrayInputStream(sampleData.getBytes(Charset.defaultCharset())); DataLakeFileClient fClient = dataLakeFileSystemClient.getFileClient("myfilesforlisting" + System.currentTimeMillis()); fClient.create(); fClient.append(dataInFiles, 0, sampleData.length()); fClient.flush(sampleData.length()); dataInFiles.close(); dataLakeFileSystemClient.getDirectoryClient("mydirsforlisting" + System.currentTimeMillis()).create(); } /* * List the path(s) in our file system. */ dataLakeFileSystemClient.listPaths() .forEach(pathItem -> System.out.println("Path name: " + pathItem.getName())); /* * Delete the file we created earlier. */ fileClient.delete(); /* * Delete the file system we created earlier. */ dataLakeFileSystemClient.delete(); } }
39.412162
148
0.663295
05957c49b3f7e5182fa123d86818b31876482e5a
15,401
package DoubleLinkedList; import Socket.Client; import Socket.Server; import SwingInterfaces.BoardInterfaceClient; import SwingInterfaces.BoardInterfaceServer; import javax.swing.*; import java.io.Serializable; import java.util.*; /** * Instituto Tecnológico de Costa Rica * Area de Ingeniería en Computadores * * Lenguaje: Java * Clase: DoubleLinkedList * @version 3.0 * @author Byron Mata, Gustavo Alvarado y Sebastián Chaves * * Descripción: Esta clase contiene algunos de los métodos que se utilizan en la lista doblemente enlazada, principalmente * en los movimientos y los casos de las casillas */ public class DoubleLinkedList implements Serializable { public static String values; private static DoubleNode head; private DoubleNode tail; private int trampa = 0, tunel = 0, reto = 0; /** * Constructor de un nuevo objeto "Double Linked List" con head y tail como nulos */ public DoubleLinkedList() { head = null; tail = null; Casillas(); } /** * Método que retorna verdadero si la lista esta vacía y falso de ser caso contrario * * @return Retorno de true si la lista es vacía o flase de ser caso contario */ public boolean isEmpty(){ return head == null; } /** * Método que crea las casillas de manera aleatoria */ public void Casillas(){ int i = 1; while(i <=14){ int probability = (int)(Math.random()*3)+1; //Probabilidad random de crear las casillas if(probability == 1 && this.trampa <4){ //Casilla de trampa addCasilla('A', String.valueOf(i)); this.trampa++; i++; }else if(probability == 2 && this.reto <7){ //Casilla de reto addCasilla('R', String.valueOf(i)); this.reto++; i++; }else if (probability == 3 && this.tunel <3){ //Casilla de tunel addCasilla('T', String.valueOf(i)); this.tunel++; i++; } } } /** * Método que crea las casillas de la lista y las va añadiendo * * @param Id Parámetro que permite reconocer el tipo de casilla * @param ID Parámetro para reconcer el número de la casilla */ public void addCasilla(char Id, String ID){ DoubleNode casilla = new DoubleNode(null, Id, ID, head); if(isEmpty()){ head = tail = casilla; }else{ head.setPrev(casilla); head = casilla; } } /** * Método que permite realizar un print de la lista creada * * @return Retorno de la lista creada */ public String showList(){ DoubleNode cn = head; String str = ""; while(cn != null){ str += cn.getC() + ","; cn = cn.getNext(); } String list = str; return list; } /** * Método que busca un nodo dado por medio del parámetro * * @param Id Parámetro para permite acceder a un determinado nodo * @return Retorno null */ public static String findNode(String Id) { DoubleNode objective = head; while (objective != null){ if (objective.getID().equals(Id)) { //Se cumple si se encuentra el nodo en la lista return objective.getC(); }else{ objective = objective.getNext(); } } return null; //No se encontró el nodo en la lista } /** * Método que realiza la creación de una operación matemática aleatorea * * @return Retorno de la variable "format" que contiene el formato de la operación aleatorea */ public static String Mathchallenge() { Random r = new Random(); int A = (int) (Math.random()*50+1); //Primer operando para el reto int B = (int) (Math.random()*50+1); //Segundo operando del reto char operator = 'a'; int value = 0; switch (r.nextInt(3)){ case 0: operator = '+'; value = A+B; break; case 1: operator = '-'; value = A-B; break; case 2: operator = '*'; value = A*B; break; case 3: operator = '/'; value = A/B; break; } values = (String.valueOf(value)); String format = (String.valueOf(A)+" "+String.valueOf(operator)+" "+String.valueOf(B)); //Expresión total del reto con valores random return format; } /** * Método que contiene la funcionalidad de la casilla de tunel, asignado su movimiento de manera aleatoria * * @param Player Parámetro que pasa el Label del jugador para su actualización * @param player Parámetro que define que jugador llamó al método */ public static void Tunel(JLabel Player, String player){ int move = (int)(Math.random()*3)+1; //Cantidad de casillas a moverse, de 1 a 3 System.out.println("Tunel move: " + move); //Aumento en el contador de casillas de Clinte o Servidor if(player.equals("Server")){ BoardInterfaceServer.casillas += move; }else{ BoardInterfaceClient.casillas +=move; } if (Player.getY() == 107) { //Primera fila del tablero int pos = 0; while(pos < move){ if(Player.getX() == 516 && pos != move){ if(player.equals("Server")){ Player.setLocation(Player.getX(), Player.getY()+150); //Movimiento hacia la segunda fila del tablero pos++; for(int i = pos; i < move; i++) { //Movimiento hacia la izquierda en segunda fila Player.setLocation(Player.getX()-150, Player.getY()); pos++; } pos++; break; }else{ Player.setLocation(Player.getX()+50, Player.getY()+150); //Movimiento hacia la segunda fila del tablero pos++; for(int i = pos; i < move; i++) { //Movimiento hacia la izquierda en segunda fila Player.setLocation(Player.getX()-150, Player.getY()); pos++; } pos++; break; } } Player.setLocation(Player.getX()+150, Player.getY()); pos++; } } else if(Player.getY() == 257) { //Segunda fila del tablero int pos = 0; while(pos < move){ if((Player.getX() == 66 && pos != move)||(Player.getX() == 116 && pos != move)){ Player.setLocation(Player.getX(), Player.getY()+150); //Movimiento a la tercera fila pos++; for(int i = pos; i < move; i++) { Player.setLocation(Player.getX()+150, Player.getY()); //Movimiento a la derecha en la tercera fila del tablero pos++; } pos++; break; } Player.setLocation(Player.getX()-150, Player.getY()); //Movimiento a la izquierda en la segunda fila del tablero pos++; } } else if (Player.getY() == 407){ //Tercera fila del tablero int pos = 0; while(pos < move){ if((Player.getX() == 516 && pos != move)||(Player.getX() == 566 && pos != move)){ Player.setLocation(Player.getX(), Player.getY()+150); //Movimiento a la cuarta fila del tablero pos++; for(int i = pos; i < move; i++) { Player.setLocation(Player.getX()-150, Player.getY()); //Movimiento a la izquierda en la cuarta fila del tablero pos++; } pos++; break; } Player.setLocation(Player.getX()+150, Player.getY()); //Movimiento a la derecha en la tercera fila del tablero pos++; } } else if (Player.getY() == 557) { //Cuarta fila del tablero int pos = 0; while(pos < move){ if((Player.getX() == 66 && Player.getY() == 557)||(Player.getX() == 116 && Player.getY() == 557)){ //Jugador llegó a la última casilla del tablero BoardInterfaceServer.gameOver(); break; } Player.setLocation(Player.getX()-150, Player.getY()); //Movimeinto a la izquierda en la cuarta fila del tablero pos++; } }if((Player.getX() == 66 && Player.getY() == 557)||(Player.getX() == 116 && Player.getY() == 557)){ //Jugador llegó a la última casilla del tablero BoardInterfaceServer.gameOver(); } if(player.equals("Server")){ //Aviso al Cliente para acutalizar movimiento, cambio de turno y chequeo de la casilla en la que se encuentra el jugador Server.sendMsg("Move"); Server.updateMove(Player.getX(), Player.getY()); Server.sendMsg("Turn"); Server.sendMsg("go"); BoardInterfaceServer.checkPos(BoardInterfaceServer.casillas); }else{ //Aviso al Servidor para actualizar movimiento, cambio de turno y chequeo de la casilla en la que se encuentra el jugador Client.sendMsg("Move"); Client.updateMove(Player.getX(), Player.getY()); Client.sendMsg("Turn"); Client.sendMsg("go"); BoardInterfaceClient.checkPos(BoardInterfaceClient.casillas); } } /** * Método que contiene la funcionalidad y el movimiento de la casilla de trampa * * @param Player Parámetro que pasa el Label del jugador para su actualización * @param player Parámetro que define que jugador llamó al método */ public static void Trap(JLabel Player, String player){ int move = (int)(Math.random()*3)+1; //Cantidad de casillas a moverse, de 1 a 3 System.out.println("Trap rest: " + move); //Devolver al jugador a la primera casilla del tablero y reduce el contador de casillas if(player.equals("Server")){ if(BoardInterfaceServer.casillas - move < 0){ Player.setLocation(66, Player.getY()); }else{ BoardInterfaceServer.casillas -= move; } }else{ if(BoardInterfaceClient.casillas - move < 0){ Player.setLocation(66, Player.getY()); }else{ BoardInterfaceClient.casillas -= move; } } if (Player.getY() == 107) { //Jugador en la primera fila del tablero int pos = 0; while(pos < move){ if(Player.getX() == 66){ break; } Player.setLocation(Player.getX()-150, Player.getY()); //Movimeinto a la izquierda en la primera fila pos++; } if(Player.getX() < 66){ Player.setLocation(66,Player.getY()); //Devuelve el jugador a la casilla de inicio si este se pasa } } else if(Player.getY() == 257) { //Jugador en la segunda fila del tablero int pos = 0; while(pos < move){ if((Player.getX() == 516 && pos != move) || (Player.getX() == 566 && pos != move)){ if(player.equals("Server")){ Player.setLocation(Player.getX(), Player.getY()-150); //Devuelve el jugador a la primera fila pos++; for(int i = pos; i < move; i++) { Player.setLocation(Player.getX()-150, Player.getY()); //Movimiento a la izquierda en la primera fila pos++; } pos++; break; }else{ Player.setLocation(Player.getX()-50, Player.getY()-150); //Devuelve al jugador a la primera fila pos++; for(int i = pos; i < move; i++) { Player.setLocation(Player.getX()-150, Player.getY()); //Movimiento a la izquierda en la primera fila pos++; } pos++; break; } } Player.setLocation(Player.getX()+150, Player.getY()); //Movimiento a la derecha del jugador pos++; } } else if (Player.getY() == 407){ //Jugador en la tercera fila del tablero int pos = 0; while(pos < move){ if((Player.getX() == 66 && pos != move) || (Player.getX() == 116 && pos != move)){ Player.setLocation(Player.getX(), Player.getY()-150); //Devuelve al jugador a la segunda fila del tablero pos++; for(int i = pos; i < move; i++) { Player.setLocation(Player.getX()+150, Player.getY()); //Movimiento a la derecha en la segunda fila del tablero pos++; } pos++; break; } Player.setLocation(Player.getX()-150, Player.getY()); //Movimiento a la izquierda en la tercera fila del tablero pos++; } } else if (Player.getY() == 557) { //Jugador en la cuarta fila del tablero int pos = 0; while(pos < move){ if((Player.getX() == 516 && pos != move) || (Player.getX() == 556 && pos != move)){ Player.setLocation(Player.getX(), Player.getY()-150); //Devuelve al jugador a la tercera fila del tablero pos++; for(int i = pos; i < move; i++) { Player.setLocation(Player.getX()-150, Player.getY()); //Movimiento del jugador a la izquierda en la tercera fila pos++; } pos++; break; } Player.setLocation(Player.getX()+150, Player.getY()); //Moviento del jugador a la derecha en la cuarta fila pos++; } } if(player.equals("Server")){ //Actualiza el movimiento del jugador Server.sendMsg("Move"); Server.updateMove(Player.getX(), Player.getY()); //Cambio de turno Server.sendMsg("Turn"); Server.sendMsg("go"); BoardInterfaceServer.checkPos(BoardInterfaceServer.casillas); }else{ //Actualiza el movimiento del jugador Client.sendMsg("Move"); Client.updateMove(Player.getX(), Player.getY()); //Cambio de turno Client.sendMsg("Turn"); Client.sendMsg("go"); BoardInterfaceClient.checkPos(BoardInterfaceClient.casillas); } } }
38.598997
162
0.507175
31dbfc2111241a7fbd2b5c2be92f4f6279576680
292
package com.sparkit.staf.application.models.response.docs; import lombok.Data; import java.util.List; @Data public class LibraryDocumentation { private String libraryName; private String importName; private boolean isBuiltin; private List<KeywordDocumentation> keywords; }
20.857143
58
0.780822
3c4d6e672f67e4d7ee40dabdfd0d6c93921e7204
2,934
/* * Copyright 2015 Priyesh Patel * * 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.chromium.fontinstaller.util; import android.app.AlertDialog; import android.content.Context; import android.content.res.AssetManager; import android.graphics.Typeface; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.TextView; import com.chromium.fontinstaller.R; import com.chromium.fontinstaller.core.CommandRunner; import java.util.Collections; import butterknife.ButterKnife; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import static com.chromium.fontinstaller.util.ViewUtils.toast; public final class RebootDialog extends AlertDialog { /* Immediately after a font has been installed, the system won't be able * to provide fonts properly until after a reboot. As a workaround, these * assets are loaded and explicitly set to the necessary View's. */ private static final String REGULAR_FONT = "Roboto-Regular.ttf"; private static final String BOLD_FONT = "Roboto-Bold.ttf"; public RebootDialog(Context context) { super(context); } @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); final View view = View.inflate(getContext(), R.layout.reboot_dialog, null); ButterKnife.bind(this, view); setView(view); final AssetManager assets = view.getContext().getAssets(); final Typeface regular = Typeface.createFromAsset(assets, REGULAR_FONT); final Typeface bold = Typeface.createFromAsset(assets, BOLD_FONT); final TextView rebootMessage = (TextView) view.findViewById(R.id.reboot_message); rebootMessage.setTypeface(regular); final String buttonText = view.getContext().getString(R.string.reboot_dialog_button_text); setButton(BUTTON_POSITIVE, buttonText, (dialog, which) -> { dialog.dismiss(); Observable.just("reboot") .map(Collections::singletonList) .map(CommandRunner::run) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(s -> { }, error -> toast(R.string.reboot_failed, getContext())); }); super.onCreate(savedInstanceState); final Button button = getButton(AlertDialog.BUTTON_POSITIVE); button.setTypeface(bold); } }
34.116279
94
0.748125
970ee3325cdca7b9c7c4fa84896b488d88ec11bc
10,752
package BQN.types.callable.builtins; import BQN.errors.*; import BQN.tools.FmtInfo; import BQN.types.*; import BQN.types.arrs.*; import BQN.types.mut.SimpleMap; import java.math.BigInteger; import java.util.*; public class BaseNS extends SimpleMap { public String ln(FmtInfo f) { return "•b"; } public static final Value INSTANCE = new BaseNS(); public static Value pack(Value w, Value x, Callable blame) { if (x.r() == 0) throw new DomainError("packing scalar is pointless", blame); if (w instanceof BigValue || w.first() instanceof BigValue || x.first() instanceof BigValue) { if (w.r() == 0) { BigInteger al = BigValue.bigint(w); BigInteger res = BigInteger.ZERO; for (int i = 0; i < x.ia; i++) res = res.multiply(al).add(BigValue.bigint(x.get(i))); return new BigValue(res); } else { if (x.r() != 1) throw new NYIError(blame+": 1 < =𝕩", blame); if (w.r() != 1) throw new DomainError(blame+": 1 < =𝕨", blame); if (w.ia != x.shape[0]) throw new DomainError(blame+": (≠𝕨) ≠ ≠𝕩", blame); BigInteger res = BigInteger.ZERO; for (int i = 0; i < w.ia; i++) { res = res.multiply(BigValue.bigint(w.get(i))); res = res.add(BigValue.bigint(x.get(i))); } return new BigValue(res); } } if (w instanceof Num) { double base = w.asDouble(); if (x.r() == 1) { double res = 0; for (int i = 0; i < x.ia; i++) res = res*base + x.get(i).asDouble(); return new Num(res); } else { double[] d = x.asDoubleArr(); int[] sh = new int[x.r()-1]; System.arraycopy(x.shape, 1, sh, 0, x.r() - 1); int layers = x.shape[0]; double[] r = new double[x.ia / layers]; System.arraycopy(d, 0, r, 0, r.length); for (int i = 1; i < layers; i++) { for (int j = 0; j < r.length; j++) { r[j] = r[j]*base + d[j+r.length*i]; } } return new DoubleArr(r, sh); } } else { if (w.ia != x.shape[0]) throw new DomainError(blame+": (≠𝕨) ≠ ⊑≢𝕩", blame); double[] d = x.asDoubleArr(); double[] bases = w.asDoubleArr(); int[] sh = new int[x.r()-1]; System.arraycopy(x.shape, 1, sh, 0, x.r() - 1); int layers = x.shape[0]; double[] r = new double[x.ia/layers]; System.arraycopy(d, 0, r, 0, r.length); for (int i = 1; i < layers; i++) { double base = bases[i]; for (int j = 0; j < r.length; j++) { r[j] = r[j]*base + d[j+r.length*i]; } } if (sh.length == 0) return new Num(r[0]); return new DoubleArr(r, sh); } } public static Value unpack(Value a, Value w, Callable blame) { if (!(a instanceof Primitive)) { if (w instanceof BigValue) { ArrayList<Value> res = new ArrayList<>(); BigInteger c = ((BigValue) w).i; for (int i = 0; i < a.ia; i++) { Value v = a.get(a.ia-i-1); BigInteger[] dr = c.divideAndRemainder(BigValue.bigint(v)); res.add(v instanceof Num? new Num(dr[1].intValue()) : new BigValue(dr[1])); c = dr[0]; } Collections.reverse(res); return Arr.create(res); } int[] sh = new int[w.r()+a.r()]; if (a.r() != 1) throw new NYIError(blame+": 2≤=𝕨", blame); System.arraycopy(a.shape, 0, sh, 0, a.r()); // ≡ for (int i = 0; i < a.r(); i++) sh[i] = a.shape[i]; System.arraycopy(w.shape, 0, sh, a.r(), w.r()); // ≡ for (int i = 0; i < w.r(); i++) sh[i+a.r()] = w.shape[i]; if (a.ia == 0) return new EmptyArr(sh, Num.ZERO); double[] c = w.asDoubleArrClone(); double[] b = a.asDoubleArr(); double[] res = new double[w.ia * a.ia]; for (int i = 1; i < b.length; i++) if (b[i] == 0) throw new DomainError(blame+": 𝕨 contained a 0 as not the 1st element", blame); int last = b[0] == 0? 1 : 0; for (int i = b.length-1; i >= last; i--) { int off = w.ia*i; double cb = b[i]; for (int j = 0; j < w.ia; j++) { res[off + j] = c[j] % cb; c[j] = Math.floor(c[j] / cb); } } if (b[0] == 0) { System.arraycopy(c, 0, res, 0, w.ia); // ≡ for (int j = 0; j < w.ia; j++) res[j] = c[j]; } return new DoubleArr(res, sh); } if (!(w instanceof Num)) { if (w instanceof BigValue) { BigInteger base = BigValue.bigint(a); boolean bigBase = a instanceof BigValue; BigInteger wlr = ((BigValue) w).i; int sign = wlr.signum(); BigInteger wl = wlr.abs(); int ibase = BigValue.safeInt(base); if (ibase <= 1) { if (ibase==1 && sign!=0) throw new DomainError(blame+": 𝕨=1 and 𝕩≠0 isn't possible", blame); if (ibase < 0) throw new DomainError(blame+": 𝕨 < 0", blame); } if (sign==0) return EmptyArr.SHAPE0N; if (ibase == 2) { int len = wl.bitLength(); if (bigBase) { Value[] res = new Value[len]; if (sign==1) for (int i = 0; i < len; i++) res[len-i-1] = wl.testBit(i)? BigValue. ONE : BigValue.ZERO; else for (int i = 0; i < len; i++) res[len-i-1] = wl.testBit(i)? BigValue.MINUS_ONE : BigValue.ZERO; return new HArr(res); } else if (sign == 1) { BitArr.BA bc = new BitArr.BA(Arr.vecsh(len), true); for (int i = 0; i < len; i++) bc.add(wl.testBit(len-i-1)); return bc.finish(); } else { double[] res = new double[len]; for (int i = 0; i < len; i++) res[i] = wl.testBit(len-i-1)? -1 : 0; return new DoubleArr(res); } } if (ibase <= Character.MAX_RADIX) { // utilize the actually optimized base conversion of BigInteger.toString String str = wl.toString(ibase); Value[] res = new Value[str.length()]; for (int i = 0; i < res.length; i++) { char c = str.charAt(i); int n = c<='9'? c-'0' : 10+c-'a'; if (sign==-1) n=-n; res[i] = bigBase? new BigValue(BigInteger.valueOf(n)) : Num.of(n); } return new HArr(res); } ArrayList<Value> ns = new ArrayList<>(); // if we can't, just be lazy. ¯\_(ツ)_/¯ while (wl.signum() != 0) { BigInteger[] c = wl.divideAndRemainder(base); wl = c[0]; ns.add(bigBase? new BigValue(sign==1? c[1] : c[1].negate()) : new Num(c[1].intValue()*sign)); } Value[] res = new Value[ns.size()]; for (int i = 0; i < res.length; i++) { res[res.length-i-1] = ns.get(i); } return new HArr(res); } throw new NYIError(blame+": scalar 𝕨 and non-scalar 𝕩 not implemented", blame); } double base = a.asDouble(); double num = w.asDouble(); if (base <= 1) { if (base == 0) return Num.of(num); if (base < 0) throw new DomainError(blame+": 𝕨 < 0", blame); throw new DomainError(blame+": 𝕨 < 1", blame); } ArrayList<Double> res = new ArrayList<>(); if (num < 0) { num = -num; while (num > 0) { res.add(-num%base); num = Math.floor(num/base); } } else { while (num > 0) { res.add(num%base); num = Math.floor(num/base); } } double[] f = new double[res.size()]; for (int i = res.size()-1, j = 0; i >= 0; i--, j++) { f[j] = res.get(i); } return new DoubleArr(f); } public static Value format(Value w, Value x) { int base; int len; if (w.ia == 2) { base = w.get(0).asInt(); len = w.get(1).asInt(); } else { base = w.asInt(); len = 0; } long val = (long)x.asDouble(); String s = Long.toString(val, base).toUpperCase(); while (s.length()<len) s = "0"+s; return new ChrArr(s); } public static Value read(Value w, Value x) { int base = w.asInt(); String s = x.asString(); return new Num(Long.parseLong(s, base)); } public static Value toDigits(Value x) { String s = x.asString(); int[] r = new int[x.ia]; for (int i = 0; i < r.length; i++) { char c = s.charAt(i); r[i] = c>='0'&c<='9'? c-'0' : c>='A'&c<='Z'? c-'A'+10 : c>='a'&c<='z'? c-'a'+10 : -1; if (r[i]==-1) throw new DomainError("Bad base character '"+c+"'"); } return new IntArr(r, x.shape); } public static Value toChars(Value x) { int[] xi = x.asIntArr(); char[] r = new char[x.ia]; for (int i = 0; i < r.length; i++) { if (xi[i]<0 | xi[i]>=36) throw new DomainError("Can't •b.format number "+xi[i]); r[i] = (char) (xi[i]<10? '0' + xi[i] : 'A' + xi[i]-10); } return new ChrArr(r, x.shape); } public static final BB p = new BB("Pack") { public Value call(Value x ) { return pack(Num.NUMS[2], x, this); } public Value call(Value w, Value x) { return pack(w , x, this); } public Value callInv ( Value x) { return unpack(Num.NUMS[2], x, this); } public Value callInvX(Value w, Value x) { return unpack(w , x, this); } }; public static final BB u = new BB("Unpack") { public Value call(Value x ) { return unpack(Num.NUMS[2], x, this); } public Value call(Value w, Value x) { return unpack(w , x, this); } public Value callInv ( Value x) { return pack(Num.NUMS[2], x, this); } public Value callInvX(Value w, Value x) { return pack(w , x, this); } }; public static final BB f = new BB("Format") { public Value call (Value x) { return toChars(x); } public Value callInv(Value x) { return toDigits(x); } public Value call (Value w, Value x) { return format(w, x); } public Value callInvX(Value w, Value x) { return read (w, x); } }; public static final BB r = new BB("Read") { public Value call (Value x) { return toDigits(x); } public Value callInv(Value x) { return toChars(x); } public Value call (Value w, Value x) { return read (w, x); } public Value callInvX(Value w, Value x) { return format(w, x); } }; public Value getv(String s) { switch (s) { case "p": case "pack": return p; case "u": case "unpack": return u; case "f": case "format": return f; case "r": case "read": case "parse": return r; } throw new ValueError("No key "+s+" in •b"); } public void setv(String s, Value v) { throw new DomainError("Assigning into •b"); } private static class BB extends FnBuiltin { public final String name; public BB(String name) { this.name = "•b."+name; } public String ln(FmtInfo f) { return name; } } }
37.333333
135
0.515997
4d28ba2a69b18c9aaa93c1801833522d9d98c1b4
1,129
package ca.ubc.ece.salt.pangor.analysis.flow; import java.util.LinkedList; import java.util.List; import org.mozilla.javascript.ast.AstNode; import org.mozilla.javascript.ast.FunctionNode; import org.mozilla.javascript.ast.NodeVisitor; import org.mozilla.javascript.ast.ScriptNode; /** * Finds all the child functions in an AstNode. * * Note that only first-level children are returned. Functions inside of * functions are not visited. * * @author qhanam */ public class FunctionTreeVisitor implements NodeVisitor { private ScriptNode root; private List<FunctionNode> functions; private FunctionTreeVisitor(ScriptNode root) { this.root = root; this.functions = new LinkedList<FunctionNode>(); } public static List<FunctionNode> getFunctions(ScriptNode node) { FunctionTreeVisitor visitor = new FunctionTreeVisitor(node); node.visit(visitor); return visitor.functions; } @Override public boolean visit(AstNode node) { if(node == this.root) { return true; } else if(node instanceof FunctionNode) { this.functions.add((FunctionNode) node); return false; } return true; } }
23.520833
72
0.750221
470224f951aca0598bf1c5e0150063142845683a
2,281
package gov.cms.dpc.attribution.models; import org.hibernate.validator.constraints.NotEmpty; import javax.persistence.*; import java.util.Objects; @Entity(name = "attributions") @NamedQueries({ @NamedQuery(name = "findByProvider", query = "from attributions a where a.providerID = :id"), @NamedQuery(name = "findRelationship", query = "from attributions a where a.providerID = :provID and a.attributedPatient = :patID"), @NamedQuery(name = "getProvider", query = "select 1 from attributions a where a.providerID = :provID") }) public class AttributionRelationship { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", updatable = false, nullable = false) private Long attributionID; @NotEmpty @Column(name = "provider_id") private String providerID; @NotEmpty @Column(name = "patient_id") private String attributedPatient; public AttributionRelationship() { // Not used } public AttributionRelationship(String providerID, String attributedPatients) { this.providerID = providerID; this.attributedPatient = attributedPatients; } public Long getAttributionID() { return attributionID; } public void setAttributionID(Long attributionID) { this.attributionID = attributionID; } public String getProviderID() { return providerID; } public void setProviderID(String providerID) { this.providerID = providerID; } public String getAttributedPatient() { return attributedPatient; } public void setAttributedPatient(String attributedPatient) { this.attributedPatient = attributedPatient; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AttributionRelationship that = (AttributionRelationship) o; return Objects.equals(attributionID, that.attributionID) && Objects.equals(providerID, that.providerID) && Objects.equals(attributedPatient, that.attributedPatient); } @Override public int hashCode() { return Objects.hash(attributionID, providerID, attributedPatient); } }
29.623377
140
0.677335
b7cc21a5b36bd2be54564b4897cd52f937093e6d
1,265
package org.nem.nis.validators.transaction; import org.nem.core.model.*; import org.nem.nis.validators.*; /** * Adapter that adapts a strongly typed transaction validator to a single transaction validator. * * @param <TTransaction> The supported transaction type. */ public class TSingleTransactionValidatorAdapter<TTransaction extends Transaction> implements SingleTransactionValidator { private final int transactionType; private final TSingleTransactionValidator<TTransaction> innerValidator; /** * Creates a new validator. * * @param transactionType The supported transaction type. * @param innerValidator The inner validator. */ public TSingleTransactionValidatorAdapter(final int transactionType, final TSingleTransactionValidator<TTransaction> innerValidator) { this.transactionType = transactionType; this.innerValidator = innerValidator; } @Override public String getName() { return this.innerValidator.getName(); } @Override @SuppressWarnings("unchecked") public ValidationResult validate(final Transaction transaction, final ValidationContext context) { return this.transactionType != transaction.getType() ? ValidationResult.SUCCESS : this.innerValidator.validate((TTransaction) transaction, context); } }
32.435897
135
0.792095
9d14db72e4e115bcb3beeafc6a858651aab2e4f8
606
package at.salzburgresearch.nodekeeper.eca.function; import at.salzburgresearch.nodekeeper.NodeKeeper; import at.salzburgresearch.nodekeeper.model.Node; /** * ... * <p/> * Author: Thomas Kurz (tkurz@apache.org) */ public class CurrentNodeData extends Function { @Override public Object execute(NodeKeeper nodeKeeper, Node current) { return current.getData(); } @Override public String getName() { return "currentNodeData"; } @Override public String getDescription() { return "the data of the node that triggered the rule execution"; } }
21.642857
72
0.686469
b43bba45c1f9ee10dec676751d43036927dc3b80
1,902
/* * Copyright 2018 jd.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yihaodian.architecture.kira.manager.util; import com.yihaodian.architecture.kira.common.util.LoadProertesContainer; import java.util.Hashtable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class KiraManagerConfigCenter { private static Logger logger = LoggerFactory.getLogger(KiraManagerConfigCenter.class); private static KiraManagerConfigCenter kiraManagerConfigCenter; private Hashtable<String, String> kiraManagerProperties = new Hashtable<String, String>(); private KiraManagerConfigCenter() { // TODO Auto-generated constructor stub } public static String getProperty(String key, String defaultValue) { KiraManagerConfigCenter.getKiraManagerConfigCenter(); String value = LoadProertesContainer.provider().getProperty(key, defaultValue); return null == value ? defaultValue : value; } private static synchronized KiraManagerConfigCenter getKiraManagerConfigCenter() { if (null == kiraManagerConfigCenter) { kiraManagerConfigCenter = new KiraManagerConfigCenter(); } return kiraManagerConfigCenter; } /** * @param args */ public static void main(String[] args) { } private Hashtable<String, String> getKiraManagerProperties() { return kiraManagerProperties; } private void init() { } }
31.180328
92
0.754469
7751e9dd09e4873d59e162c0c60e45b6f41c2b93
2,240
package com.github.eyce9000.iem.api.relevance; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair; import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector; public class RowSerializer { TypeReference<HashMap<String,Object>> defObj = new TypeReference<HashMap<String,Object>>(){}; TypeReference<HashMap<String,String>> defStr = new TypeReference<HashMap<String,String>>(){}; ObjectMapper mapper; public RowSerializer(){ mapper = new ObjectMapper(); mapper.setAnnotationIntrospector(new AnnotationIntrospectorPair( new JacksonAnnotationIntrospector(), new JaxbAnnotationIntrospector(mapper.getTypeFactory()) )); } public RowSerializer(ObjectMapper mapper){ this.mapper = mapper; } public ObjectMapper getMapper(){ return mapper; } public <T> T deserializeString(Class<? extends T> clazz, Map<String,String> row){ return (T)mapper.convertValue(row,clazz); } public <T> T deserialize(Class<? extends T> clazz, Map<String,Object> row){ return (T)mapper.convertValue(row, clazz); } public Map<String,String> serializeString(Object value){ return mapper.convertValue(value, defStr); } public Map<String,Object> serialize(Object value){ return mapper.convertValue(value, defObj); } public static RowSerializer getJAXBandJacksonSerializer(){ RowSerializer serializer = new RowSerializer(); serializer.mapper.setAnnotationIntrospector(new AnnotationIntrospectorPair( new JacksonAnnotationIntrospector(), new JaxbAnnotationIntrospector(serializer.mapper.getTypeFactory()) )); return serializer; } public static RowSerializer getJacksonSerializer(){ RowSerializer serializer= new RowSerializer(); serializer.mapper = new ObjectMapper(); return serializer; } public static RowSerializer getJAXBSerializer(){ RowSerializer serializer = new RowSerializer(); serializer.mapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(serializer.mapper.getTypeFactory())); return serializer; } }
33.939394
114
0.788839
bd8c8906905f697f7de376c233945829ec087c74
2,478
package no.cantara.docsite.domain.scm; import no.cantara.docsite.cache.CacheKey; import no.cantara.docsite.json.JsonbFactory; import java.io.Serializable; import java.util.Objects; public class ScmRepositoryContents implements Serializable { private static final long serialVersionUID = -9144603141360888994L; public final CacheKey cacheKey; public final String sha; public final String filename; public final String type; public final String encoding; public final String path; public final int size; public final String content; public final String contentUrl; public final String scmUrl; public final String htmlUrl; public final String downloadUrl; public ScmRepositoryContents(CacheKey cacheKey, String sha, String filename, String type, String encoding, String path, int size, String content, String contentUrl, String scmUrl, String htmlUrl, String downloadUrl) { this.cacheKey = cacheKey; this.sha = sha; this.filename = filename; this.type = type; this.encoding = encoding; this.path = path; this.size = size; this.content = content; this.contentUrl = contentUrl; this.scmUrl = scmUrl; this.htmlUrl = htmlUrl; this.downloadUrl = downloadUrl; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ScmRepositoryContents)) return false; ScmRepositoryContents that = (ScmRepositoryContents) o; return size == that.size && Objects.equals(cacheKey, that.cacheKey) && Objects.equals(sha, that.sha) && Objects.equals(filename, that.filename) && Objects.equals(type, that.type) && Objects.equals(encoding, that.encoding) && Objects.equals(path, that.path) && Objects.equals(content, that.content) && Objects.equals(contentUrl, that.contentUrl) && Objects.equals(scmUrl, that.scmUrl) && Objects.equals(htmlUrl, that.htmlUrl) && Objects.equals(downloadUrl, that.downloadUrl); } @Override public int hashCode() { return Objects.hash(cacheKey, sha, filename, type, encoding, path, size, content, contentUrl, scmUrl, htmlUrl, downloadUrl); } @Override public String toString() { return JsonbFactory.asString(this); } }
35.4
221
0.650121
cbee3243c90554db223ac005e4e82b5400870012
1,792
package mage.cards.f; import mage.abilities.Ability; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.effects.common.AttachEffect; import mage.abilities.effects.common.continuous.BecomesCreatureAttachedEffect; import mage.abilities.keyword.EnchantAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.*; import mage.game.permanent.token.custom.CreatureToken; import mage.target.TargetPermanent; import mage.target.common.TargetCreaturePermanent; import java.util.UUID; /** * @author spjspj */ public final class FowlPlay extends CardImpl { public FowlPlay(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{2}{U}"); this.subtype.add(SubType.AURA); // Enchant creature TargetPermanent auraTarget = new TargetCreaturePermanent(); this.getSpellAbility().addTarget(auraTarget); this.getSpellAbility().addEffect(new AttachEffect(Outcome.AddAbility)); Ability ability = new EnchantAbility(auraTarget.getTargetName()); this.addAbility(ability); // Enchanted creature is a Bird with base power and toughness 1/1 and loses all abilities. this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new BecomesCreatureAttachedEffect(new CreatureToken(1, 1, "1/1 Bird creature", SubType.BIRD), "Enchanted creature is a Bird with base power and toughness 1/1 and loses all abilities", Duration.WhileOnBattlefield, BecomesCreatureAttachedEffect.LoseType.ABILITIES_SUBTYPE))); } public FowlPlay(final FowlPlay card) { super(card); } @Override public FowlPlay copy() { return new FowlPlay(this); } }
35.84
113
0.722656
c23ade35a7d77fb57c3ead3d51ced5a774124b43
686
package com.hzn.sales.model; public class EasyShopCar { private String id; private String goodsId; private String num; private String price; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getGoodsId() { return goodsId; } public void setGoodsId(String goodsId) { this.goodsId = goodsId; } public String getNum() { return num; } public void setNum(String num) { this.num = num; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } }
16.731707
44
0.571429
393b8d28057897264fb31561a14e3e892449c27b
1,829
package com.ruoyi.demo.domain; import java.math.BigDecimal; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.core.domain.BaseEntity; /** * 账户对象 demo_account * * @author zhangxiulin * @date 2021-01-20 */ public class DemoAccount extends BaseEntity { private static final long serialVersionUID = 1L; /** 主键ID */ private Long id; /** 客户号 */ @Excel(name = "客户号") private String userCode; /** 余额 */ @Excel(name = "余额") private BigDecimal money; /** 状态 */ @Excel(name = "状态") private String status; public void setId(Long id) { this.id = id; } public Long getId() { return id; } public void setUserCode(String userCode) { this.userCode = userCode; } public String getUserCode() { return userCode; } public void setMoney(BigDecimal money) { this.money = money; } public BigDecimal getMoney() { return money; } public void setStatus(String status) { this.status = status; } public String getStatus() { return status; } @Override public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("id", getId()) .append("userCode", getUserCode()) .append("money", getMoney()) .append("status", getStatus()) .append("remark", getRemark()) .append("createBy", getCreateBy()) .append("createTime", getCreateTime()) .append("updateBy", getUpdateBy()) .append("updateTime", getUpdateTime()) .toString(); } }
21.267442
71
0.585019
85fae4280a6c397c0e15ede8c223a328367bb635
8,493
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.connector.base.source.hybrid; import org.apache.flink.annotation.PublicEvolving; import org.apache.flink.api.common.ExecutionConfig; import org.apache.flink.api.connector.source.Boundedness; import org.apache.flink.api.connector.source.Source; import org.apache.flink.api.connector.source.SourceReader; import org.apache.flink.api.connector.source.SourceReaderContext; import org.apache.flink.api.connector.source.SplitEnumerator; import org.apache.flink.api.connector.source.SplitEnumeratorContext; import org.apache.flink.api.java.ClosureCleaner; import org.apache.flink.core.io.SimpleVersionedSerializer; import org.apache.flink.util.Preconditions; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Hybrid source that switches underlying sources based on configured source chain. * * <pre>{@code * FileSource<String> fileSource = null; * HybridSource<String> hybridSource = * new HybridSourceBuilder<String, ContinuousFileSplitEnumerator>() * .addSource(fileSource) // fixed start position * .addSource( * (enumerator) -> { * // instantiate Kafka source based on enumerator * KafkaSource<String> kafkaSource = createKafkaSource(enumerator); * return kafkaSource; * }, Boundedness.CONTINUOUS_UNBOUNDED) * .build(); * }</pre> */ @PublicEvolving public class HybridSource<T> implements Source<T, HybridSourceSplit, HybridSourceEnumeratorState> { private final List<SourceListEntry> sources; // sources are populated per subtask at switch time private final Map<Integer, Source> switchedSources; /** Protected for subclass, use {@link #builder(Source)} to construct source. */ protected HybridSource(List<SourceListEntry> sources) { Preconditions.checkArgument(!sources.isEmpty()); for (int i = 0; i < sources.size() - 1; i++) { Preconditions.checkArgument( Boundedness.BOUNDED.equals(sources.get(i).boundedness), "All sources except the final source need to be bounded."); } this.sources = sources; this.switchedSources = new HashMap<>(sources.size()); } /** Builder for {@link HybridSource}. */ public static <T, EnumT extends SplitEnumerator> HybridSourceBuilder<T, EnumT> builder( Source<T, ?, ?> firstSource) { HybridSourceBuilder<T, EnumT> builder = new HybridSourceBuilder<>(); return builder.addSource(firstSource); } @Override public Boundedness getBoundedness() { return sources.get(sources.size() - 1).boundedness; } @Override public SourceReader<T, HybridSourceSplit> createReader(SourceReaderContext readerContext) throws Exception { return new HybridSourceReader(readerContext, switchedSources); } @Override public SplitEnumerator<HybridSourceSplit, HybridSourceEnumeratorState> createEnumerator( SplitEnumeratorContext<HybridSourceSplit> enumContext) { return new HybridSourceSplitEnumerator(enumContext, sources, 0, switchedSources); } @Override public SplitEnumerator<HybridSourceSplit, HybridSourceEnumeratorState> restoreEnumerator( SplitEnumeratorContext<HybridSourceSplit> enumContext, HybridSourceEnumeratorState checkpoint) throws Exception { // TODO: restore underlying enumerator return new HybridSourceSplitEnumerator( enumContext, sources, checkpoint.getCurrentSourceIndex(), switchedSources); } @Override public SimpleVersionedSerializer<HybridSourceSplit> getSplitSerializer() { return new HybridSourceSplitSerializer(switchedSources); } @Override public SimpleVersionedSerializer<HybridSourceEnumeratorState> getEnumeratorCheckpointSerializer() { return new HybridSourceEnumeratorStateSerializer(switchedSources); } /** * Factory for underlying sources of {@link HybridSource}. * * <p>This factory permits building of a source at graph construction time or deferred at switch * time. Provides the ability to set a start position in any way a specific source allows. * Future convenience could be built on top of it, for example a default implementation that * recognizes optional interfaces to transfer position in a universal format. * * <p>Called when the current enumerator has finished and before the next enumerator is created. * The enumerator end state can thus be used to set the next source's start start position. Only * required for dynamic position transfer at time of switching. * * <p>If start position is known at job submission time, the source can be constructed in the * entry point and simply wrapped into the factory, providing the benefit of validation during * submission. */ public interface SourceFactory<T, SourceT extends Source, FromEnumT extends SplitEnumerator> extends Serializable { SourceT create(FromEnumT enumerator); } private static class PassthroughSourceFactory< T, SourceT extends Source<T, ?, ?>, FromEnumT extends SplitEnumerator> implements SourceFactory<T, SourceT, FromEnumT> { private final SourceT source; private PassthroughSourceFactory(SourceT source) { this.source = source; } @Override public SourceT create(FromEnumT enumerator) { return source; } } /** Entry for list of underlying sources. */ protected static class SourceListEntry implements Serializable { protected final SourceFactory configurer; protected final Boundedness boundedness; private SourceListEntry(SourceFactory configurer, Boundedness boundedness) { this.configurer = Preconditions.checkNotNull(configurer); this.boundedness = Preconditions.checkNotNull(boundedness); } public static SourceListEntry of(SourceFactory configurer, Boundedness boundedness) { return new SourceListEntry(configurer, boundedness); } } /** Builder for HybridSource. */ public static class HybridSourceBuilder<T, EnumT extends SplitEnumerator> implements Serializable { private final List<SourceListEntry> sources; public HybridSourceBuilder() { sources = new ArrayList<>(); } /** Add pre-configured source (without switch time modification). */ public <ToEnumT extends SplitEnumerator, NextSourceT extends Source<T, ?, ?>> HybridSourceBuilder<T, ToEnumT> addSource(NextSourceT source) { return addSource(new PassthroughSourceFactory<>(source), source.getBoundedness()); } /** Add source with deferred instantiation based on previous enumerator. */ public <ToEnumT extends SplitEnumerator, NextSourceT extends Source<T, ?, ?>> HybridSourceBuilder<T, ToEnumT> addSource( SourceFactory<T, NextSourceT, EnumT> sourceFactory, Boundedness boundedness) { ClosureCleaner.clean( sourceFactory, ExecutionConfig.ClosureCleanerLevel.RECURSIVE, true); sources.add(SourceListEntry.of(sourceFactory, boundedness)); return (HybridSourceBuilder) this; } /** Build the source. */ public HybridSource<T> build() { return new HybridSource(sources); } } }
41.632353
100
0.696809
5b4292be2eaf4d079756554b74029fcba51aab4a
3,262
package kb.validation.required; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.stream.Collectors; import org.eclipse.rdf4j.common.iteration.Iterations; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.query.impl.SimpleBinding; import kb.repository.KB; import kb.repository.KBConsts; import kb.utils.QueryUtil; import kb.validation.exceptions.models.RequiredPropertyAttributeModel; public class RequiredPropertyValidation { private static final Logger LOG = LoggerFactory.getLogger(RequiredPropertyValidation.class.getName()); IRI templateType; String templateName; Set<String> exchangeProperties; KB kb; Model aadm; String kindOfTemplate; List<RequiredPropertyAttributeModel> models = new ArrayList<RequiredPropertyAttributeModel>(); public RequiredPropertyValidation(String kindOfTemplate, String templateName, IRI templateType, Set<String> exchangeProperties, KB kb) { this.kindOfTemplate = kindOfTemplate; this.templateType = templateType; this.templateName = templateName; this.exchangeProperties = exchangeProperties; this.kb = kb; } public List<RequiredPropertyAttributeModel> validate() { // for each node template, find the node type and get the required properties String query = KB.PREFIXES + optionalPropertiesQuery; List<String> schemaProperties = Iterations .asSet(QueryUtil.evaluateSelectQuery(kb.getConnection(), query, new SimpleBinding("resource", templateType))) .stream() .map(x -> ((IRI) x.getBinding("property").getValue()).getLocalName()).collect(Collectors.toList()); LOG.info("validation: [{}] {}", new Object[] {templateType, schemaProperties}); LOG.info("exchange properties: {}", exchangeProperties); boolean found = false; for (String sch : schemaProperties) { for (String ex : exchangeProperties) { if (sch.equals(ex)) { found = true; break; } } if (!found) { models.add(new RequiredPropertyAttributeModel(kindOfTemplate, templateName, templateType.stringValue(), sch, null)); } found = false; } return models; } private String optionalPropertiesQuery = "select distinct ?property\r\n" + "where {\r\n" + " ?resource soda:hasInferredContext ?context .\r\n" + " ?context tosca:properties ?concept .\r\n" + " ?concept DUL:classifies ?property .\r\n" + " {\r\n" + " ?concept DUL:hasParameter [DUL:classifies tosca:required; tosca:hasDataValue true].\r\n" + " }\r\n" + " UNION\r\n" + " {\r\n" + " FILTER NOT EXISTS {?concept DUL:hasParameter [DUL:classifies tosca:required; tosca:hasDataValue []]}.\r\n" + " }\r\n" + " FILTER NOT EXISTS {\r\n" + " ?resource soda:hasInferredContext ?context2 .\r\n" + " FILTER(?context != ?context2).\r\n" + " ?context2 tosca:properties ?classifier2.\r\n" + " ?classifier2 DUL:classifies ?property .\r\n" + " \r\n" + " ?resource2 soda:hasContext ?context2 .\r\n" + " #FILTER(?resource != ?resource2). \r\n" + " FILTER(?resource2 != owl:Nothing).\r\n" + " ?resource2 rdfs:subClassOf ?resource. \r\n" + " }\r\n" + "}\r\n" + ""; }
33.285714
128
0.699264
94075fe28a5fda255b0b99416ee59d5ea5d7ef7e
16,385
package testesDeUnidadeBusiness; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import com.br.uepb.business.CaronaBusiness; import com.br.uepb.business.SessaoBusiness; import com.br.uepb.business.UsuarioBusiness; import com.br.uepb.constants.ECaronaException; import com.br.uepb.constants.MensagensDeErro; public class UsuarioBusinessExceptionsTest { private UsuarioBusiness gerenciadorDeUsuario; private SessaoBusiness gerenciadorDeSessao; private CaronaBusiness gerenciadorDeCarona; @Before public void setUp() { this.gerenciadorDeUsuario = new UsuarioBusiness(); this.gerenciadorDeSessao = new SessaoBusiness(); this.gerenciadorDeCarona = new CaronaBusiness(); } // ERROS DO US01 @Test public void loginInvalidoTest() throws ECaronaException { gerenciadorDeUsuario.criarUsuario("mark", "m@rk", "Mark Zuckerberg", "Palo Alto, California", "mark@facebook.com"); try { gerenciadorDeUsuario.criarUsuario(null, "xptz", "xpto", "xpto", "xpto"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.LOGIN_INVALIDO, eCa.getMessage()); } try { gerenciadorDeUsuario.criarUsuario("", "xptz", "xpto", "xpto", "xpto"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.LOGIN_INVALIDO, eCa.getMessage()); } try { gerenciadorDeSessao.abrirSessao(null, "teste"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.LOGIN_INVALIDO, eCa.getMessage()); } try { gerenciadorDeSessao.abrirSessao("", "segundoTeste"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.LOGIN_INVALIDO, eCa.getMessage()); } try { gerenciadorDeSessao.abrirSessao("mark", "segundoTeste"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.LOGIN_INVALIDO, eCa.getMessage()); } try { gerenciadorDeSessao.abrirSessao(null, null); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.LOGIN_INVALIDO, eCa.getMessage()); } try { gerenciadorDeSessao.abrirSessao("", ""); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.LOGIN_INVALIDO, eCa.getMessage()); } } @Test public void nomeInvalidoTest() throws ECaronaException { try { gerenciadorDeUsuario.criarUsuario("xpto", "xptz", null, "xpto", "xpto"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.NOME_INVALIDO, eCa.getMessage()); } try { gerenciadorDeUsuario.criarUsuario("xpto", "xptz", "", "xpto", "xpto"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.NOME_INVALIDO, eCa.getMessage()); } try { gerenciadorDeUsuario.criarUsuario("xpto", "xptz", " ", "xpto", "xpto"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.NOME_INVALIDO, eCa.getMessage()); } } @Test public void emailInvalidoTest() throws ECaronaException { try { gerenciadorDeUsuario.criarUsuario("xpto", "xptz", "xpto", "xpto", null); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.EMAIL_INVALIDO, eCa.getMessage()); } try { gerenciadorDeUsuario.criarUsuario("xpto", "xptz", "xpto", "xpto", ""); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.EMAIL_INVALIDO, eCa.getMessage()); } try { gerenciadorDeUsuario.criarUsuario("xpto", "xptz", "xpto", "xpto", "chico"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.EMAIL_INVALIDO, eCa.getMessage()); } try { gerenciadorDeUsuario.criarUsuario("xpto", "xptz", "xpto", "xpto", "chico@casa"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.EMAIL_INVALIDO, eCa.getMessage()); } } @Test public void existeUsuarioComEsseEmailTest() throws ECaronaException { gerenciadorDeUsuario.criarUsuario("mark", "m@rk", "Mark Zuckerberg", "Palo Alto, California", "mark@facebook.com"); try { gerenciadorDeUsuario.criarUsuario("xpto", "tttppp", "markito", "xpto", "mark@facebook.com"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.EXISTE_USUARIO_C_EMAIL, eCa.getMessage()); } } @Test public void existeUsuarioComEsseLoginTest() throws ECaronaException { gerenciadorDeUsuario.criarUsuario("mark", "m@rk", "Mark Zuckerberg", "Palo Alto, California", "mark@facebook.com"); try { gerenciadorDeUsuario.criarUsuario("mark", "tttppp", "markito", "xpto", "markinho@facebook.com"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.EXISTE_USUARIO_C_LOGIN, eCa.getMessage()); } } @Test public void usuarioInexistenteTest() throws ECaronaException { gerenciadorDeUsuario.criarUsuario("mark", "m@rk", "Mark Zuckerberg", "Palo Alto, California", "mark@facebook.com"); gerenciadorDeUsuario.criarUsuario("steve", "5t3v3", "Steven Paul Jobs", "Palo Alto, California", "jobs@apple.com"); gerenciadorDeUsuario.criarUsuario("bill", "severino", "William Henry Gates III", "Medina, Washington", "billzin@msn.com"); try { gerenciadorDeSessao.abrirSessao("hufflees", "123"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.USUARIO_INEXISTENTE, eCa.getMessage()); } try { gerenciadorDeUsuario.getAtributoUsuario("warrior", "nome"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.USUARIO_INEXISTENTE, eCa.getMessage()); } } @Test public void atributoInvalidoTest() throws ECaronaException { gerenciadorDeUsuario.criarUsuario("mark", "m@rk", "Mark Zuckerberg", "Palo Alto, California", "mark@facebook.com"); try { gerenciadorDeUsuario.getAtributoUsuario("mark", ""); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.ATRIBUTO_INVALIDO, eCa.getMessage()); } try { gerenciadorDeUsuario.getAtributoUsuario("mark", null); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.ATRIBUTO_INVALIDO, eCa.getMessage()); } } @Test public void atributoInexistenteTest() throws ECaronaException { gerenciadorDeUsuario.criarUsuario("mark", "m@rk", "Mark Zuckerberg", "Palo Alto, California", "mark@facebook.com"); try { gerenciadorDeUsuario.getAtributoUsuario("mark", "casa"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.ATRIBUTO_INEXISTENTE, eCa.getMessage()); } try { gerenciadorDeUsuario.getAtributoUsuario("mark", "lixo"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.ATRIBUTO_INEXISTENTE, eCa.getMessage()); } try { gerenciadorDeUsuario.getAtributoUsuario("mark", "????????????????"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.ATRIBUTO_INEXISTENTE, eCa.getMessage()); } try { gerenciadorDeUsuario.getAtributoUsuario("mark", "testandoOutoAtributo"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.ATRIBUTO_INEXISTENTE, eCa.getMessage()); } } // ERROS DO US02 @Test public void sessaoInvalidaTest() throws ECaronaException { try { gerenciadorDeCarona.cadastrarCarona(null, "Campina Grande", "João Pessoa", "23/06/2013", "16:00", "3"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.SESSAO_INVALIDA, eCa.getMessage()); } try { gerenciadorDeCarona.cadastrarCarona("", "Campina Grande", "João Pessoa", "23/06/2013", "16:00", "3"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.SESSAO_INVALIDA, eCa.getMessage()); } } @Test public void sessaoInexistenteTest() throws ECaronaException { try { gerenciadorDeCarona.cadastrarCarona("teste", "Campina Grande", "João Pessoa", "23/06/2013", "16:00", "3"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.SESSAO_INEXISTENTE, eCa.getMessage()); } } @Test public void origemInvalidaTest() throws ECaronaException { gerenciadorDeUsuario.criarUsuario("mark", "m@rk", "Mark Zuckerberg", "Palo Alto, California", "mark@facebook.com"); String idSessao = gerenciadorDeSessao.abrirSessao("mark", "m@rk"); try { gerenciadorDeCarona.cadastrarCarona(idSessao, "", "João Pessoa", "23/06/2013", "16:00", "3"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.ORIGEM_INVALIDA, eCa.getMessage()); } try { gerenciadorDeCarona.cadastrarCarona(idSessao, null, "João Pessoa", "23/06/2013", "16:00", "3"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.ORIGEM_INVALIDA, eCa.getMessage()); } } @Test public void destinoInvalidoTest() throws ECaronaException { gerenciadorDeUsuario.criarUsuario("mark", "m@rk", "Mark Zuckerberg", "Palo Alto, California", "mark@facebook.com"); String idSessao = gerenciadorDeSessao.abrirSessao("mark", "m@rk"); try { gerenciadorDeCarona.cadastrarCarona(idSessao, "Campina Grande", "", "23/06/2013", "16:00", "3"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.DESTINO_INVALIDO, eCa.getMessage()); } try { gerenciadorDeCarona.cadastrarCarona(idSessao, "Campina Grande", null, "23/06/2013", "16:00", "3"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.DESTINO_INVALIDO, eCa.getMessage()); } } @Test public void dataInvalidaTest() throws ECaronaException { gerenciadorDeUsuario.criarUsuario("mark", "m@rk", "Mark Zuckerberg", "Palo Alto, California", "mark@facebook.com"); String idSessao = gerenciadorDeSessao.abrirSessao("mark", "m@rk"); try { gerenciadorDeCarona.cadastrarCarona(idSessao, "Campina Grande", "João Pessoa", "", "16:00", "3"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.DATA_INVALIDA, eCa.getMessage()); } try { gerenciadorDeCarona.cadastrarCarona(idSessao, "Campina Grande", "João Pessoa", null, "16:00", "3"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.DATA_INVALIDA, eCa.getMessage()); } try { gerenciadorDeCarona.cadastrarCarona(idSessao, "Campina Grande", "João Pessoa", "30/02/2012", "16:00", "3"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.DATA_INVALIDA, eCa.getMessage()); } try { gerenciadorDeCarona.cadastrarCarona(idSessao, "Campina Grande", "João Pessoa", "31/04/2012", "16:00", "3"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.DATA_INVALIDA, eCa.getMessage()); } try { gerenciadorDeCarona.cadastrarCarona(idSessao, "Campina Grande", "João Pessoa", "32/12/2012", "16:00", "3"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.DATA_INVALIDA, eCa.getMessage()); } try { gerenciadorDeCarona.cadastrarCarona(idSessao, "Campina Grande", "João Pessoa", "30/02/2011", "16:00", "3"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.DATA_INVALIDA, eCa.getMessage()); } } @Test public void horaInvalidaTest() throws ECaronaException { gerenciadorDeUsuario.criarUsuario("mark", "m@rk", "Mark Zuckerberg", "Palo Alto, California", "mark@facebook.com"); String idSessao = gerenciadorDeSessao.abrirSessao("mark", "m@rk"); try { gerenciadorDeCarona.cadastrarCarona(idSessao, "Campina Grande", "João Pessoa", "23/06/2013", "", "3"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.HORA_INVALIDA, eCa.getMessage()); } try { gerenciadorDeCarona.cadastrarCarona(idSessao, "Campina Grande", "João Pessoa", "23/06/2013", null, "3"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.HORA_INVALIDA, eCa.getMessage()); } try { gerenciadorDeCarona.cadastrarCarona(idSessao, "Campina Grande", "João Pessoa", "23/06/2013", "sete", "3"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.HORA_INVALIDA, eCa.getMessage()); } } @Test public void vagaInvalidaTest() throws ECaronaException { gerenciadorDeUsuario.criarUsuario("mark", "m@rk", "Mark Zuckerberg", "Palo Alto, California", "mark@facebook.com"); String idSessao = gerenciadorDeSessao.abrirSessao("mark", "m@rk"); try { gerenciadorDeCarona.cadastrarCarona(idSessao, "Campina Grande", "João Pessoa", "23/06/2013", "16:00", ""); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.VAGA_INVALIDA, eCa.getMessage()); } try { gerenciadorDeCarona.cadastrarCarona(idSessao, "Campina Grande", "João Pessoa", "23/06/2013", "16:00", "null"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.VAGA_INVALIDA, eCa.getMessage()); } try { gerenciadorDeCarona.cadastrarCarona(idSessao, "Campina Grande", "João Pessoa", "23/06/2013", "16:00", "tres"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.VAGA_INVALIDA, eCa.getMessage()); } } @Test public void identificadorCaronaInvalidoTest() throws ECaronaException { gerenciadorDeUsuario.criarUsuario("mark", "m@rk", "Mark Zuckerberg", "Palo Alto, California", "mark@facebook.com"); try { gerenciadorDeCarona.getAtributoCarona("", "origem"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.IDENTIFICADOR_CARONA_INVALIDO, eCa.getMessage()); } try { gerenciadorDeCarona.getAtributoCarona(null, "origem"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.IDENTIFICADOR_CARONA_INVALIDO, eCa.getMessage()); } } @Test public void itemInexistenteTest() throws ECaronaException { gerenciadorDeUsuario.criarUsuario("mark", "m@rk", "Mark Zuckerberg", "Palo Alto, California", "mark@facebook.com"); try { gerenciadorDeCarona.getAtributoCarona("xpto", "origem"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.ITEM_INEXISTENTE, eCa.getMessage()); } } @Test public void atributoInvalido_2Test() throws ECaronaException { gerenciadorDeUsuario.criarUsuario("mark", "m@rk", "Mark Zuckerberg", "Palo Alto, California", "mark@facebook.com"); String idSessao = gerenciadorDeSessao.abrirSessao("mark", "m@rk"); String idCarona = gerenciadorDeCarona.cadastrarCarona(idSessao, "Rio de Janeiro", "São Paulo", "31/05/2013", "08:00", "2"); try { gerenciadorDeCarona.getAtributoCarona(idCarona, ""); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.ATRIBUTO_INVALIDO, eCa.getMessage()); } try { gerenciadorDeCarona.getAtributoCarona(idCarona, null); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.ATRIBUTO_INVALIDO, eCa.getMessage()); } try { gerenciadorDeCarona.getAtributoCarona(idCarona, "xpto"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.ATRIBUTO_INEXISTENTE, eCa.getMessage()); } } @Test public void origemInvalida_2Test() throws ECaronaException { gerenciadorDeUsuario.criarUsuario("mark", "m@rk", "Mark Zuckerberg", "Palo Alto, California", "mark@facebook.com"); String idSessao = gerenciadorDeSessao.abrirSessao("mark", "m@rk"); try { gerenciadorDeCarona.localizarCarona(idSessao, "-", "João Pessoa"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.ORIGEM_INVALIDA, eCa.getMessage()); } try { gerenciadorDeCarona.localizarCarona(idSessao, "()", "João Pessoa"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.ORIGEM_INVALIDA, eCa.getMessage()); } try { gerenciadorDeCarona.localizarCarona(idSessao, "!", "João Pessoa"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.ORIGEM_INVALIDA, eCa.getMessage()); } try { gerenciadorDeCarona.localizarCarona(idSessao, "!?", "João Pessoa"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.ORIGEM_INVALIDA, eCa.getMessage()); } } @Test public void destinoInvalido_2Test() throws ECaronaException { gerenciadorDeUsuario.criarUsuario("mark", "m@rk", "Mark Zuckerberg", "Palo Alto, California", "mark@facebook.com"); String idSessao = gerenciadorDeSessao.abrirSessao("mark", "m@rk"); try { gerenciadorDeCarona.localizarCarona(idSessao, "Campina Grande", "."); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.DESTINO_INVALIDO, eCa.getMessage()); } try { gerenciadorDeCarona.localizarCarona(idSessao, "Campina Grande", "()"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.DESTINO_INVALIDO, eCa.getMessage()); } try { gerenciadorDeCarona.localizarCarona(idSessao, "Campina Grande", "!?"); } catch (ECaronaException eCa) { assertEquals(MensagensDeErro.DESTINO_INVALIDO, eCa.getMessage()); } } }
30.06422
73
0.712176