text
stringlengths
10
2.72M
package com.ylz.dao; import java.util.Map; /** * Created by liuburu on 2017/3/6. */ public interface ProcedureMapper { void excuteSeckillPro(Map<String,Object> map); }
package com.hrrm.budget.application.account.service; import static graphql.schema.GraphQLObjectType.newObject; import static graphql.schema.GraphQLSchema.newSchema; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.servlet.Servlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicyOption; import org.osgi.service.component.annotations.ServiceScope; import org.osgi.service.http.whiteboard.HttpWhiteboardConstants; import org.osgi.service.log.Logger; import org.osgi.service.log.LoggerFactory; import graphql.execution.instrumentation.Instrumentation; import graphql.execution.preparsed.NoOpPreparsedDocumentProvider; import graphql.execution.preparsed.PreparsedDocumentProvider; import graphql.schema.GraphQLObjectType; import graphql.schema.GraphQLType; import graphql.servlet.DefaultExecutionStrategyProvider; import graphql.servlet.DefaultGraphQLContextBuilder; import graphql.servlet.DefaultGraphQLErrorHandler; import graphql.servlet.DefaultGraphQLRootObjectBuilder; import graphql.servlet.DefaultGraphQLSchemaProvider; import graphql.servlet.ExecutionStrategyProvider; import graphql.servlet.GraphQLContext; import graphql.servlet.GraphQLContextBuilder; import graphql.servlet.GraphQLErrorHandler; import graphql.servlet.GraphQLProvider; import graphql.servlet.GraphQLQueryProvider; import graphql.servlet.GraphQLRootObjectBuilder; import graphql.servlet.GraphQLSchemaProvider; import graphql.servlet.GraphQLServlet; import graphql.servlet.GraphQLTypesProvider; import graphql.servlet.InstrumentationProvider; import graphql.servlet.NoOpInstrumentationProvider; @Component(scope = ServiceScope.PROTOTYPE, service = Servlet.class, property = { HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN + "=/accounts/*", HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT + "=(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=com.hrrm.budget.webapp)" }) public class AccountGraphQlServlet extends GraphQLServlet { @Reference(cardinality = ReferenceCardinality.MULTIPLE, policyOption = ReferencePolicyOption.GREEDY, target = "(com.hrrm.graphql.provider=accounts)") private List<GraphQLProvider> providers; @Reference private LoggerFactory loggerFactory; private GraphQLContextBuilder contextBuilder = new DefaultGraphQLContextBuilder(); private ExecutionStrategyProvider executionStrategyProvider = new DefaultExecutionStrategyProvider(); private InstrumentationProvider instrumentationProvider = new NoOpInstrumentationProvider(); private PreparsedDocumentProvider preparsedDocumentProvider = NoOpPreparsedDocumentProvider.INSTANCE; private GraphQLErrorHandler errorHandler = new DefaultGraphQLErrorHandler(); private GraphQLRootObjectBuilder rootObjectBuilder = new DefaultGraphQLRootObjectBuilder(); private GraphQLSchemaProvider schemaProvider; private Logger logger; @Activate public void activate() { logger = loggerFactory.getLogger(this.getClass()); logger.info("Activated"); GraphQLObjectType.Builder accountsQueryTypeBuilder = newObject().name("AccountsQuery"); providers.stream().filter(GraphQLQueryProvider.class::isInstance).map(GraphQLQueryProvider.class::cast) .map(GraphQLQueryProvider::getQueries).flatMap(Collection::stream) .forEach(accountsQueryTypeBuilder::field); Set<GraphQLType> types = providers.stream().filter(GraphQLTypesProvider.class::isInstance) .map(GraphQLTypesProvider.class::cast).map(GraphQLTypesProvider::getTypes).flatMap(Collection::stream) .collect(Collectors.toSet()); schemaProvider = new DefaultGraphQLSchemaProvider( newSchema().query(accountsQueryTypeBuilder.build()).build(types)); } @Override protected GraphQLSchemaProvider getSchemaProvider() { return schemaProvider; } @Override protected GraphQLContext createContext(Optional<HttpServletRequest> request, Optional<HttpServletResponse> response) { return contextBuilder.build(request, response); } @Override protected Object createRootObject(Optional<HttpServletRequest> request, Optional<HttpServletResponse> response) { return rootObjectBuilder.build(request, response); } @Override protected ExecutionStrategyProvider getExecutionStrategyProvider() { return executionStrategyProvider; } @Override protected Instrumentation getInstrumentation() { return instrumentationProvider.getInstrumentation(); } @Override protected GraphQLErrorHandler getGraphQLErrorHandler() { return errorHandler; } @Override protected PreparsedDocumentProvider getPreparsedDocumentProvider() { return preparsedDocumentProvider; } }
package com.example.animaciones; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.example.animaciones.automaticas.Automaticas; import com.example.animaciones.crossfade.CrossfadeActivity; import com.example.animaciones.drawables.DrawablesActivity; import com.example.animaciones.lottie.LottieActivity; public class MainActivity extends AppCompatActivity { Button animacionAut,animationDrawables,animationCrossfade,animacionLottie; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); animacionAut = findViewById(R.id.button1); animationDrawables = findViewById(R.id.button2); animationCrossfade = findViewById(R.id.button2); animationCrossfade = findViewById(R.id.button3); animacionLottie = findViewById(R.id.button4); animacionAut.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(getApplicationContext(), Automaticas.class); startActivity(intent); } }); animationDrawables.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(getApplicationContext(), DrawablesActivity.class); startActivity(intent); } }); animationCrossfade.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(getApplicationContext(), CrossfadeActivity.class); startActivity(intent); } }); animacionLottie.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(getApplicationContext(), LottieActivity.class); startActivity(intent); } }); } }
package nbi.implementCores; import java.io.File; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.regex.Pattern; /** * @author robert.lee * @version $Revision: 1.0 $ */ public class RemoveTooOldDatas { private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); private final static long interval =100000000L; private static String filePatternString=""; private static String compressedFilePatternString=".*/*\\d{8}\\.zip";; private static Pattern filePattern=null; private static Pattern compressedFfilePattern=Pattern.compile(compressedFilePatternString);; /** * Method removeTooOldDatas. * @param path String */ public static void removeTooOldDatas(final String path){ filePattern = Pattern.compile(filePatternString); // compressedFfilePattern=Pattern.compile(compressedFilePatternString); File dir = new File(path); if(dir.isDirectory()){ subRemoveTooOldDatas(dir); } } /** * Method condition. * @param dir File * @return boolean */ private static boolean condition(final File dir){ String dirName = dir.getName(); boolean condition=false; if(filePattern.matcher(dirName).matches()){ try { Date itDate = sdf.parse(dirName); if((System.currentTimeMillis() -itDate.getTime()) >interval){ condition=true; } } catch (ParseException e) { e.printStackTrace(); } } if(!condition){ return true; }else{ dir.delete(); return false; } } /** * Method subRemoveTooOldDatas. * @param dir File */ private static void subRemoveTooOldDatas(final File dir){ File[] subFiles = dir.listFiles(); for(File subFile :subFiles){ String subFileName =subFile.getAbsoluteFile().getName(); if(subFile.isDirectory() && condition(subFile)){ subRemoveTooOldDatas(subFile); }else if(subFile.isFile() && compressedFfilePattern.matcher(subFileName).matches()){ subFile.delete(); } } } }
package net.roosmaa.sample.localfood.ui.fragment; import android.app.LocalActivityManager; import android.os.Bundle; import android.support.v4.app.Fragment; @SuppressWarnings("deprecation") public class ActivityManagerFragment extends Fragment { private static final String STATE_BUNDLE_KEY = "localActivityManagerState"; private LocalActivityManager mManager; protected LocalActivityManager getLocalActivityManager() { return mManager; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle state = null; if (savedInstanceState != null) state = savedInstanceState.getBundle(STATE_BUNDLE_KEY); mManager = new LocalActivityManager(getActivity(), true); mManager.dispatchCreate(state); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBundle(STATE_BUNDLE_KEY, mManager.saveInstanceState()); } @Override public void onResume() { super.onResume(); mManager.dispatchResume(); } @Override public void onPause() { super.onPause(); mManager.dispatchPause(getActivity().isFinishing()); } @Override public void onStop() { super.onStop(); mManager.dispatchStop(); } @Override public void onDestroy() { super.onDestroy(); mManager.dispatchDestroy(getActivity().isFinishing()); } }
/* * Copyright (c) 2020 Nikifor Fedorov * 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 * Contributors: * Nikifor Fedorov and others */ package ru.krivocraft.tortoise.android.player; import android.content.Context; import android.content.SharedPreferences; import ru.krivocraft.tortoise.core.api.settings.WriteableSettings; public class SharedPreferencesSettings extends WriteableSettings { private final SharedPreferences preferences; public SharedPreferencesSettings(Context context) { this.preferences = context.getSharedPreferences("settings", Context.MODE_PRIVATE); } @Override public boolean read(String key, boolean defaultValue) { return preferences.getBoolean(key, defaultValue); } @Override public int read(String key, int defaultValue) { return preferences.getInt(key, defaultValue); } @Override public String read(String key, String defaultValue) { return preferences.getString(key, defaultValue); } @Override public void write(String key, boolean value) { preferences.edit().putBoolean(key, value).apply(); } @Override public void write(String key, int value) { preferences.edit().putInt(key, value).apply(); } @Override public void write(String key, String value) { preferences.edit().putString(key, value).apply(); } }
package com.wifisec; import android.provider.BaseColumns; public class FeedReaderContract { public FeedReaderContract() {} public static abstract class FeedEntry implements BaseColumns { public static final String TABLE_NAME_WIFI = "wifi_networks"; public static final String COLUMN_NAME_WIFI_ENTRY_ID = "id"; public static final String COLUMN_NAME_WIFI_TITLE = "ssid"; public static final String COLUMN_NAME_WIFI_BSSID = "bssid"; public static final String COLUMN_NAME_WIFI_LASTSCAN = "last_scan"; public static final String COLUMN_NAME_WIFI_SECURITY = "security"; public static final String COLUMN_NAME_WIFI_ROBUSTNESS = "robustness"; public static final String COLUMN_NAME_WIFI_PASSWORD = "password"; public static final String COLUMN_NAME_WIFI_COORDINATES_X = "coordinates_x"; public static final String COLUMN_NAME_WIFI_COORDINATES_Y = "coordinates_y"; public static final String TABLE_NAME_PASSWORDS = "wifi_passwords"; public static final String COLUMN_NAME_PASSWORDS_ENTRY_ID = "id"; public static final String COLUMN_NAME_PASSWORDS_TITLE = "passwords"; } }
package com.example.userservice; import lombok.extern.java.Log; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Bean; import org.springframework.core.env.Environment; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import java.util.Arrays; import java.util.List; @SpringBootApplication @EnableDiscoveryClient @RestController @Log public class UserServiceApplication { @Autowired private Environment environment; public static void main(String[] args) { SpringApplication.run(UserServiceApplication.class, args); } @GetMapping("status") public String string() { return "UP"; } @GetMapping("secret") public String secret() { return "SECRET"; } @GetMapping("configtest") public String string12() { return environment.getProperty("gitvalue"); } @GetMapping("getdata/{id}") public ExampleModel1 exampleModel1(@PathVariable Long id) { System.out.println("hello from"+environment.getProperty("server.port")); return new ExampleModel1(id, "samet"); } @GetMapping("/listtest") public List<ExampleModel1> exampleModel1s(){ return Arrays.asList(new ExampleModel1(1L,"da"),new ExampleModel1(2L,"dad")); } }
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.util.ElapsedTime; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.CRServo; /** * Created by Lance He 9/16/2017. */ public class Hardware { // Motor variable names public DcMotor frontLeftMotor = null; public DcMotor frontRightMotor = null; public DcMotor backLeftMotor = null; public DcMotor backRightMotor = null; public CRServo clawServo = null; // Other variable names HardwareMap hwMap; private ElapsedTime period = new ElapsedTime(); public Hardware() { hwMap = null; } public void init(HardwareMap hwMap) { // Save reference to Hardware map this.hwMap = hwMap; period.reset(); // Define Motors frontLeftMotor = hwMap.dcMotor.get("left_front"); frontRightMotor = hwMap.dcMotor.get("right_front"); backLeftMotor = hwMap.dcMotor.get("left_back"); backRightMotor = hwMap.dcMotor.get("right_back"); //frontLeftMotor = hwMap.dcMotor.get("front_left"); //frontRightMotor = hwMap.dcMotor.get("front_right"); //backLeftMotor = hwMap.dcMotor.get("back_left"); //backRightMotor = hwMap.dcMotor.get("back_right"); // Initialize Motors frontLeftMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); frontRightMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); backLeftMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); backRightMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); // ******MAY CHANGE ******* Fix Forward/Reverse under testing frontLeftMotor.setDirection(DcMotor.Direction.FORWARD); frontRightMotor.setDirection(DcMotor.Direction.FORWARD); backLeftMotor.setDirection(DcMotor.Direction.FORWARD); backRightMotor.setDirection(DcMotor.Direction.FORWARD); frontLeftMotor.setPower(0); frontRightMotor.setPower(0); backLeftMotor.setPower(0); backRightMotor.setPower(0); clawServo = hwMap.crservo.get("intake_servo"); } public void initTeleOpDelayIMU(HardwareMap hwMap){ // Save reference to Hardware map this.hwMap = hwMap; period.reset(); // Define Motors frontLeftMotor = hwMap.dcMotor.get("left_front"); frontRightMotor = hwMap.dcMotor.get("right_front"); backLeftMotor = hwMap.dcMotor.get("left_back"); backRightMotor = hwMap.dcMotor.get("right_back"); // Initialize Motors frontLeftMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); frontRightMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); backLeftMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); backRightMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); // ******MAY CHANGE ******* Fix Forward/Reverse under testing frontLeftMotor.setDirection(DcMotor.Direction.FORWARD); frontRightMotor.setDirection(DcMotor.Direction.FORWARD); backLeftMotor.setDirection(DcMotor.Direction.FORWARD); backRightMotor.setDirection(DcMotor.Direction.FORWARD); frontLeftMotor.setPower(0); frontRightMotor.setPower(0); backLeftMotor.setPower(0); backRightMotor.setPower(0); // May use RUN_USING_ENCODERS if encoders are installed frontLeftMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); frontRightMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); backLeftMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); backRightMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); } public void initTeleOpNOIMU(HardwareMap hwMap){ // Save reference to Hardware map this.hwMap = hwMap; period.reset(); // Define Motors frontLeftMotor = hwMap.dcMotor.get("left_front"); frontRightMotor = hwMap.dcMotor.get("right_front"); backLeftMotor = hwMap.dcMotor.get("left_back"); backRightMotor = hwMap.dcMotor.get("right_back"); // Initialize Motors frontLeftMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); frontRightMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); backLeftMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); backRightMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); // ******MAY CHANGE ******* Fix Forward/Reverse under testing frontLeftMotor.setDirection(DcMotor.Direction.FORWARD); frontRightMotor.setDirection(DcMotor.Direction.FORWARD); backLeftMotor.setDirection(DcMotor.Direction.FORWARD); backRightMotor.setDirection(DcMotor.Direction.FORWARD); frontLeftMotor.setPower(0); frontRightMotor.setPower(0); backLeftMotor.setPower(0); backRightMotor.setPower(0); // May use RUN_USING_ENCODERS if encoders are installed frontLeftMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); frontRightMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); backLeftMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); backRightMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); } public double getTime(){ return period.time(); } }
package com.walmart.ticketservice.entity.tables; public class SeatReserve { private long id; private long holdId; private int rowId; private char rowName; private int numSeats; public long getId() { return id; } public void setId(long id) { this.id = id; } public long getHoldId() { return holdId; } public void setHoldId(long holdId) { this.holdId = holdId; } public int getRowId() { return rowId; } public void setRowId(int rowId) { this.rowId = rowId; } public char getRowName() { return rowName; } public void setRowName(char rowName) { this.rowName = rowName; } public int getNumSeats() { return numSeats; } public void setNumSeats(int numSeats) { this.numSeats = numSeats; } @Override public String toString() { return "SeatBooking{" + "id=" + id + ", holdId=" + holdId + ", rowId=" + rowId + ", numSeats=" + numSeats + '}'; } }
package com.mahang.weather.main.mvp; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.NavigationView; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.mahang.weather.R; import com.mahang.weather.base.BaseFragment; import com.mahang.weather.common.Constants; import com.mahang.weather.model.entity.WeatherInfo; import com.mahang.weather.ui.activity.CityListActivity; import com.mahang.weather.view.NavigationHeaderLayout; import com.mahang.weather.view.WeatherViewPager; import java.util.List; public class WeatherMainFragment extends BaseFragment implements WeatherMainViewContract.View { private WeatherViewPager mViewPager; private WeatherPagerAdapter mAdapter; private WeatherMainViewContract.Presenter mPresenter; private NavigationHeaderLayout mHeaderView; private ViewPager.SimpleOnPageChangeListener mPageChangeListener = new ViewPager.SimpleOnPageChangeListener(){ @Override public void onPageSelected(int position) { mPresenter.onItemChange(position); } }; @Override public void onCreate(Bundle savedInstanceState) { mAdapter = new WeatherPagerAdapter(getChildFragmentManager()); mPresenter.loadWeatherInfo(); super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_view_pager, container, false); mViewPager = view.findViewById(R.id.view_pager); mViewPager.setAdapter(mAdapter); mViewPager.addOnPageChangeListener(mPageChangeListener); NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id.nav_view); // mHeaderView = (NavigationHeaderLayout) navigationView.getHeaderView(0); // mPresenter.updateHeaderView(); return view; } @Override public void notifyDataSetChanged() { mAdapter.notifyDataSetChanged(); } @Override public void setCurrentItem(int index){ mViewPager.setCurrentItem(index, true); } @Override public int getCurrentItem() { return mViewPager.getCurrentItem(); } @Override public void setTitle(CharSequence title) { getActivity().setTitle(title); } @Override public void updateHeaderView(WeatherInfo info) { mHeaderView.setWeatherInfo(info); } @Override public void startQueryPage() { Intent i = new Intent(getContext(), CityListActivity.class); i.putExtra("REQUEST_CODE", Constants.REQUEST_CODE_QUERY_CITY); startActivityForResult(i, Constants.REQUEST_CODE_QUERY_CITY); } @Override public void setPresenter(WeatherMainViewContract.Presenter presenter) { mPresenter = presenter; } @Override public void setData(List<WeatherInfo> weatherInfos) { mAdapter.setData(weatherInfos); } }
package noiter.spring; import org.junit.Before; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class HomeControllerTest { private HomeController controller; @Before public void setUp() { controller = new HomeController(); } @Test public void test_return_hello_to_front() { String result = controller.getContent(); assertThat(result, is("Hello world")); } }
package me.hotjoyit.learningtest.spring.pointcut; /** * Created by hotjoyit on 2016-07-24 */ public class Bean { public void method() throws RuntimeException { } }
package com.galid.commerce.domains.catalog.domain.review; import lombok.Getter; import lombok.NoArgsConstructor; import javax.persistence.*; @Entity @Table(name = "review_product") @Getter @NoArgsConstructor public class ReviewProductEntity { @Id @GeneratedValue private Long reviewProductId; @Column(unique = true) private Long productId; private double ratingAverage; private double totalRating; // 각 별점 평가 수 (상품이 별점을 각각 몇개 받았는지 보여줄 때 필요) private int oneCount; private int twoCount; private int threeCount; private int fourCount; private int fiveCount; private int totalCount; public ReviewProductEntity(Long productId) { this.productId = productId; } public void rate(Rating rating) { switch(rating) { case ONE: oneCount++; break; case TWO: twoCount++; break; case THREE: threeCount++; break; case FOUR: fourCount++; break; case FIVE: fiveCount++; break; default: throw new IllegalArgumentException("별점에 없는 수치 입니다."); } totalCount++; this.totalRating += rating.getValue(); this.ratingAverage = totalRating/totalCount; } }
package club.godfather.support.log; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import io.reactivex.Scheduler; import io.reactivex.annotations.NonNull; import io.reactivex.schedulers.Schedulers; class LogScheduler { @NonNull private static Scheduler from() { ThreadFactory threadFactory = new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r, "LogScheduler"); t.setPriority(Thread.MIN_PRIORITY); return t; } }; //noinspection UnstableApiUsage return Schedulers.from(Executors.newSingleThreadExecutor(threadFactory), false); } static final Scheduler INSTANCE = from(); }
package BridgePattern08.exercise.service; public interface FileImp { void readData(); }
/** * Copyright (c) 2014, Philipp Wagner <bytefish(at)gmx(dot)de> * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.bytefish.facerecapp.app; import android.graphics.Bitmap; import android.util.Log; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * This class is just a simple wrapper for the API defined in the blog * article. Basically all it does is creating a JSON Object to request * the recognition and waits (synchronously) for the result. * * */ public class RecognitionAPI { private static final String TAG = RecognitionAPI.class.getName(); private static final String RECOGNITION_API_URL = "http://192.168.178.21:5050/predict"; public static String requestRecognition(Bitmap bitmap) throws Exception { String result = new String(); try { JSONObject jsonRequest = constructPredictionRequest(bitmap); HttpResponse response = makeSynchronousRequest(jsonRequest); result = evaluateResponse(response); } catch (Exception e) { Log.e(TAG, "Recognition failed!", e); throw e; } return result; } private static HttpResponse makeSynchronousRequest(JSONObject jsonRequest) throws IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(RECOGNITION_API_URL); httpPost.setEntity(new StringEntity(jsonRequest.toString())); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); return httpClient.execute(httpPost); } private static String evaluateResponse(HttpResponse response) throws IOException, JSONException { String result = new String(); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); String entityContent = readEntityContentToString(entity); JSONObject jsonResponse = new JSONObject(entityContent); result = jsonResponse.getString("name"); } return result; } private static String readEntityContentToString(HttpEntity entity) throws IOException { StringBuilder result = new StringBuilder(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { result.append(line); } return result.toString(); } private static JSONObject constructPredictionRequest(Bitmap bitmap) throws JSONException { String base64encBitmap = ImageHelper.getBase64Jpeg(bitmap, 100); // Now create the object: JSONObject jsonObject = new JSONObject(); try { jsonObject.put("image", base64encBitmap); } catch (JSONException e) { Log.e(TAG, "Could not create Json object", e); throw e; } return jsonObject; } }
package Iterators; import java.util.Scanner; public class Multiplication { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a number: "); int num = in.nextInt(); int counter = 1; int product ; do { product = counter * num; System.out.printf("%d x %d = %d%n", num, counter, product); counter++; }while(counter <= 12); } }
package game.item; import game.GameHandler; import game.Player; import game.World; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import world_collision.MoveVector; import main_app.Handler; import main_app.LampPanel; public class Item { boolean inWorld; BufferedImage frame; BufferedImage image; String name; Player player; World world; Handler handler; double x; double y; double yvel; public Item(double x, double y, World world, Handler handler) { inWorld = true; this.x = x; this.y = y; this.world = world; this.handler = handler; frame = handler.loadImage("/item_frame.png"); } public Item(Player player, Handler handler) { inWorld = false; this.player = player; this.handler = handler; frame = handler.loadImage("/item_frame.png"); } public void toWorld(World world) { inWorld = true; this.world = world; } public void toPlayer(Player player) { inWorld = false; this.player = player; } public void update() { if (inWorld) { yvel += 1.3; MoveVector mv = new MoveVector (this.x + 12, this.y + 24, this.x + 12, this.y + 24 + yvel); /*MoveVector col = world.testCollision(mv); if (rmv == null) { y += yvel; } else { if (rmv.y2 - rmv.y1 != yvel) { yvel = 0; } x += rmv.x2 - rmv.x1; y += rmv.y2 - rmv.y1; }*/ } } public void draw(Graphics g) { g.setColor(Color.CYAN); g.drawImage(frame, LampPanel.PWIDTH / 2 - (int) (((GameHandler) handler).player.getX() - this.x), LampPanel.PHEIGHT / 2 - (int) (((GameHandler) handler).player.getY() - this.y), null); } public void equipDraw(int x, int y, Graphics g, boolean curr) { if (curr) { g.setColor(Color.YELLOW); g.drawRect(x, y, 48, 48); } g.drawImage(this.image, x, y, null); } public void inventoryDraw(int x, int y, Graphics g) { ((Graphics2D) g).drawImage(this.image, x + 10, y + 6, x + 106, y + 98, 0, 0, 48, 48, null); System.out.println(this.getClass() + " " + this.name); g.setColor(Color.WHITE); g.drawString(this.name, x + 116, y + 30); } }
package org.huangfugui.ibatis.po; /** * @author zqb * @decription * @create 2017/7/7 */ public class PicLabel { int id; Picture picture; Label label; float score; int mCount; public int getId() { return id; } public void setId(int id) { this.id = id; } public float getScore() { return score; } public void setScore(float score) { this.score = score; } public int getmCount() { return mCount; } public void setmCount(int mCount) { this.mCount = mCount; } public Picture getPicture() { return picture; } public void setPicture(Picture picture) { this.picture = picture; } public Label getLabel() { return label; } public void setLabel(Label label) { this.label = label; } @Override public String toString() { return "PicLabel{" + "id=" + id + ", picture=" + picture + ", label=" + label + ", score=" + score + ", mCount=" + mCount + '}'; } }
package moe.tristan.easyfxml.samples.helloworld.view.hello; import static org.testfx.assertions.api.Assertions.assertThat; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import moe.tristan.easyfxml.EasyFxml; import moe.tristan.easyfxml.model.exception.ExceptionHandler; import moe.tristan.easyfxml.test.FxNodeTest; @SpringBootTest @RunWith(SpringRunner.class) public class HelloComponentTest extends FxNodeTest { @Autowired private EasyFxml easyFxml; @Autowired private HelloComponent helloComponent; private Pane helloPane; @Before public void setUp() { this.helloPane = easyFxml.loadNode(helloComponent).getNode().getOrElseGet(ExceptionHandler::fromThrowable); } @Test public void shouldGreetWithUserEnteredName() { final String expectedUserName = "Tristan Deloche"; withNodes(helloPane).willDo(() -> { clickOn("#userNameTextField").write(expectedUserName); clickOn("#helloButton"); }).andAwaitFor(() -> lookup("#greetingBox").queryAs(HBox.class).isVisible()); assertThat(lookup("#greetingName").queryAs(Label.class)).hasText(expectedUserName); } @Test public void shouldGreetWithHelloWorldWhenDidNotEnterName() { final String defaultGreetingName = "World"; withNodes(helloPane) .willDo(() -> clickOn("#helloButton")) .andAwaitFor(() -> lookup("#greetingBox").query().isVisible()); assertThat(lookup("#greetingName").queryAs(Label.class)).hasText(defaultGreetingName); } }
package com.j1902.shopping.pojo; import java.util.Date; public class Evaluate { private Integer evalId; private Integer evalUserId; private Integer evalItemId; private String evalItemName; private Date evalCreateTime; private String evalInfo; public Integer getEvalId() { return evalId; } public void setEvalId(Integer evalId) { this.evalId = evalId; } public Integer getEvalUserId() { return evalUserId; } public void setEvalUserId(Integer evalUserId) { this.evalUserId = evalUserId; } public Integer getEvalItemId() { return evalItemId; } public void setEvalItemId(Integer evalItemId) { this.evalItemId = evalItemId; } public String getEvalItemName() { return evalItemName; } public void setEvalItemName(String evalItemName) { this.evalItemName = evalItemName == null ? null : evalItemName.trim(); } public Date getEvalCreateTime() { return evalCreateTime; } public void setEvalCreateTime(Date evalCreateTime) { this.evalCreateTime = evalCreateTime; } public String getEvalInfo() { return evalInfo; } public void setEvalInfo(String evalInfo) { this.evalInfo = evalInfo == null ? null : evalInfo.trim(); } }
public class Main { public static void main(String[] args) { Person person1 = new Person("sotou", "tarou", 25, 1.7, 55.0, "医者"); person1.printData(); Person person2 = new Person("yamamoto", "d", "tarou", 30, 1.85, 75.0, "教師"); person2.printData(); System.out.println("----------------------------"); person1.setJob("獣医"); System.out.println("person1の仕事を" + person1.getJob() + "に変更しました"); person1.printData(); Person.printCount(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package br.edu.ifrs.poa.control; import br.edu.ifrs.poa.dao.ComboDataDAO; import br.edu.ifrs.poa.dao.ComboSessaoDAO; import br.edu.ifrs.poa.model.ComboData; import br.edu.ifrs.poa.model.ComboSessao; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import javax.servlet.ServletException; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * /** * * baseado na C de @author karenborges */ public class FormProcessor extends Processor { private void getDatas(HttpServletResponse response) throws ServletException, IOException { getResponse().setContentType("text/html;charset=UTF-8"); PrintWriter out = getResponse().getWriter(); try { ArrayList datas = ComboDataDAO.getComboData(); if (!datas.isEmpty()) { Iterator it = datas.iterator(); while (it.hasNext()) { ComboData dt = (ComboData) it.next(); out.println(dt.toString()); } out.close(); } } catch (SQLException ex) { throw new ServletException(ex); } catch (ClassNotFoundException ex) { throw new ServletException(ex); } } private void getSessoes(HttpServletResponse response) throws ServletException, IOException { ArrayList lista; try { lista = ComboSessaoDAO.getComboSessao(); for (Iterator it = lista.iterator(); it.hasNext();) { ComboSessao object = (ComboSessao) it.next(); System.out.println(object.toString()); } } catch (SQLException ex) { System.out.println("Falhou" + ex); } catch (ClassNotFoundException ex) { System.out.println("Falhou" + ex); } catch (IOException ex) { System.out.println("Falhou" + ex); } } @Override public void execute() throws ServletException, IOException { getResponse().setContentType("text/html;charset=UTF-8"); PrintWriter out = getResponse().getWriter(); out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\""); out.println("\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"); out.println("<html><head><link rel='stylesheet' type='text/css' href='./style.css' />"); out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />"); out.println("<title>achados+perdidos</title></head><body>"); out.println("<div id='centro'><div id='cabecalho'></div><div id='conteudo'>"); out.println("<form action='Servlet' method='POST'>"); out.println("<p>Por favor, escolha</p>"); out.println("<p>...uma data:&nbsp;<select id='vdata'><option></option>"); getDatas(getResponse()); out.println("</select></p>"); out.println("<p></p>"); out.println("<p>...uma sess&atilde;o:&nbsp;<select id='vidsessao'>"); out.println("<option></option>"); getSessoes(getResponse()); out.println("</select></p>"); out.println("<p>...e um desenho:&nbsp;<select id='vdraw'>"); out.println("<option></option>"); out.println("<option>D001</option>"); out.println("<option>D002</option>"); out.println("<option>D003</option>"); out.println("<option>D004</option>"); out.println("<option>D005</option>"); out.println("</select></p>"); out.println("<p><input type='submit' value='veja+' /></p>"); out.println("<input type='hidden' name='cmd' value='draw'>"); out.println("</form>"); out.println("</div><div id='rodape'></div></div></body></html>"); out.close(); //getResponse().sendRedirect("index.jsp"); } }
/* Project: Zodiak Project * Author: Devin Smoot * Class: COMSC 1033 * Date: 2015-10-19 * Book location: Pg. 100 */ //Import Scanner utility import java.util.Scanner; public class Zodiak_class { public static void main(String[] args) { //Initialize scanner Scanner input = new Scanner(System.in); //Take user input for year of birth System.out.print("Enter the year you were born: "); int year = input.nextInt(); //Take user input for month of birth System.out.print("Enter the month of the year you were born: "); int month = input.nextInt(); //Take user input for day of birth System.out.print("Enter the day of the month you were born: "); int day = input.nextInt(); //Display output of birth year System.out.print("\nYou were born in the year of the "); //Work the problem year % 12 and find the remainder //display a case based on the remainder to finish the sentence switch (year % 12){ case 0: System.out.println("monkey."); break; case 1: System.out.println("rooster."); break; case 2: System.out.println("dog."); break; case 3: System.out.println("pig."); break; case 4: System.out.println("rat."); break; case 5: System.out.println("ox."); break; case 6: System.out.println("tiger."); break; case 7: System.out.println("rabbit."); break; case 8: System.out.println("dragon."); break; case 9: System.out.println("snake."); break; case 10: System.out.println("horse."); break; case 11: System.out.println("sheep."); } //display Zodiak sign based on month and day switch (month){ case 1: if (day<20) {System.out.println("Capricorn."); break;} else {System.out.println("Aquarius."); break;} case 2: if (day<19) {System.out.println("Aquarius."); break;} else {System.out.println("Pices."); break;} case 3: if (day<21) {System.out.println("Pices."); break;} else {System.out.println("Aries."); break;} case 4: if (day<20) {System.out.println("Aries."); break;} else {System.out.println("Taurus."); break;} case 5: if (day<21) {System.out.println("Taurus."); break;} else {System.out.println("Gemini."); break;} case 6: if (day<22) {System.out.println("Gemini."); break;} else {System.out.println("Cancer."); break;} case 7: if (day<23) {System.out.println("Cancer."); break;} else {System.out.println("Leo."); break;} case 8: if (day<24) {System.out.println("Leo."); break;} else {System.out.println("Virgo."); break;} case 9: if (day<23) {System.out.println("Virgo."); break;} else {System.out.println("Libra."); break;} case 10: if (day<23){System.out.println("Libra."); break;} else {System.out.println("Scorpio."); break;} case 11: if (day<22){System.out.println("Scorpio."); break;} else {System.out.println("Sagittarius.");break;} case 12: if (day<22){System.out.println("Sagittarius."); } else {System.out.println("Capricorn."); } } } }
package net.acomputerdog.BlazeLoader.api.toolset; import java.util.HashSet; import com.google.common.collect.Multimap; import net.acomputerdog.BlazeLoader.util.reflect.ReflectionUtils; import net.minecraft.block.Block; import net.minecraft.item.ItemAxe; import net.minecraft.item.ItemSpade; import net.minecraft.item.ItemStack; import net.minecraft.item.Item.ToolMaterial; public class ToolAxe extends ItemAxe { private final ToolSetAttributes my_material; public static final HashSet<Block> effectiveBlocks = (HashSet<Block>)ReflectionUtils.getField(ItemAxe.class, null, 0).get(); private float damageValue = 4; public ToolAxe(ToolSetAttributes material) { super(ToolMaterial.WOOD); my_material = material; setMaxDamage(material.getMaxUses()); efficiencyOnProperMaterial = material.getEfficiencyOnProperMaterial(); damageValue = material.getDamageVsEntity(3); } public int getItemEnchantability() { return my_material.getEnchantability(); } public String getToolMaterialName() { return my_material.toString(); } public boolean getIsRepairable(ItemStack par1ItemStack, ItemStack par2ItemStack) { return my_material.getIsRepairable(par2ItemStack); } public Multimap getItemAttributeModifiers() { return my_material.getAttributeModifiers(super.getItemAttributeModifiers(), field_111210_e, damageValue, "Tool modifier"); } }
// Sample code implementing the diagrams in Q5 import java.lang.*; import java.util.*; public class SalesItem { private Stock stock; private SalesOrder salesOrder; private int quantity; public SalesItem(Stock s, SalesOrder sO, int q) { quantity=q; salesOrder=sO; stock=s; stock.reduce(quantity); } }//SalesItem
package com.project.board.Repository.Comment; import java.util.List; import com.project.board.util.PagingUtil; import com.project.board.web.Comment.dto.CommentDto; import com.project.board.web.Comment.dto.CreateCommentDto; import com.project.board.web.Comment.dto.DeleteCommentDto; import com.project.board.web.Comment.dto.ModifyCommentDto; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @Mapper public interface CommentRepository { // 댓글 조회 List<CommentDto>findByBOARDUID(@Param("pagingUtil") PagingUtil pagingUtil, @Param("BOARD_UID") Long BOARD_UID); // 댓글 생성 void createComment(CreateCommentDto createCommentDto); // 댓글 수정 void modifyComment(ModifyCommentDto modifyCommentDto); // 댓글 삭제 void deleteComment(DeleteCommentDto deleteCommentDto); // 댓글 UID로 조회 CommentDto findByCOMMENTUID(Long COMMENT_UID); // 댓글 개수 조회 int countComment(Long BOARD_UID); }
package com.igs.domain.interactor; import com.igs.callback.CallbackToCommon; import com.igs.callback.CallBackToUser; import com.igs.entity.RegistBean; /** * 类描述: * 创建人:heliang * 创建时间:2015/10/30 18:12 * 修改人:8153 * 修改时间:2015/10/30 18:12 * 修改备注: */ public interface UserCase { /** * 登陆 * * @param callback * @param userPhone * @param passWorld */ void login(CallBackToUser.login callback, String userPhone, String passWorld); /** * 注册 * * @param callback * @param registBean */ void regist(CallbackToCommon callback, RegistBean registBean); /** * 忘记密码 * * @param callback * @param userPhone * @param checkCode */ void forgetPwd(CallbackToCommon callback, String userPhone, String checkCode, String newPwd); /** * 设置新密码 * * @param callback * @param uid * @param oldPwd * @param newPwd */ void setNewPwd(CallbackToCommon callback, String uid, String oldPwd, String newPwd); /** * 上传头像 * * @param callback * @param uid * @param base64file */ void upHeadPic(CallBackToUser.updateHeadPic callback, String uid, String base64file); }
package seedu.project.logic.parser; import static seedu.project.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import seedu.project.commons.core.index.Index; import seedu.project.logic.commands.CompareCommand; import seedu.project.logic.commands.TaskHistoryCommand; import seedu.project.logic.parser.exceptions.ParseException; /** * Parses input arguments and creates a new TaskHistoryCommand object */ public class TaskHistoryCommandParser implements Parser<TaskHistoryCommand> { /** * Parses the given {@code String} of arguments in the context of the TaskHistoryCommand * and returns an TaskHistoryCommand object for execution. * @throws ParseException if the user input does not conform the expected format */ public TaskHistoryCommand parse(String args) throws ParseException { try { Index index = ParserUtil.parseIndex(args); return new TaskHistoryCommand(index); } catch (ParseException pe) { throw new ParseException( String.format(MESSAGE_INVALID_COMMAND_FORMAT, CompareCommand.MESSAGE_USAGE), pe); } } }
package Study; import Study.DB.MariaDBDemo; import java.util.Scanner; import java.sql.*; public class Update { private Connection conn = null; //连接对象 private Statement stt = null; //传递sql语句 private ResultSet rs = null; //结果集 //使用PreparedStatement接口中的executeUpdate()方法实现修改数据 public void Update(){ try { conn = MariaDBDemo.getConnection();//获取连接 if(conn==null) return; System.out.print("请输入你要修改的列名:"); Scanner input = new Scanner(System.in); String Attributes = input.next(); System.out.print("请输入修改列名为:"+Attributes+"的书号"); String Bookno = input.next(); Bookno="'"+Bookno+"'"; System.out.print("请输入修改列名为:"+Attributes+"的数据"); String NewDate = input.next(); NewDate="'"+NewDate+"'"; String UpdateSql = "UPDATE test.book SET "+Attributes+" = "+NewDate+" WHERE bookno = "+Bookno; // String UpdateSql= "update test.book set author = 'wi' where bookno= '11' "; stt = conn.createStatement(); // 获取Statement对象 stt.executeUpdate(UpdateSql); // 执行sql语句 System.out.println(UpdateSql); System.out.print("成功将的书号为"+Bookno+"的列名"+Attributes+"修改为"+NewDate); } catch (SQLException e) { e.printStackTrace(); } finally { //释放资源 try { conn.close(); } catch (Exception e2) {} } } }
package com.atlassian.theplugin.idea.jira; public enum JiraIssueGroupBy { NONE("None"), PROJECT("Project"), TYPE("Type"), STATUS("Status"), PRIORITY("Priority"), LAST_UPDATED("Last Updated"); private String name; JiraIssueGroupBy(String name) { this.name = name; } @Override public String toString() { return name; } public static JiraIssueGroupBy getDefaultGroupBy() { return TYPE; } }
package com.impetus.services.exception; /** * Exception class for EDR services * @author punit * @since 03-Aug-2012 */ public class EDRServiceException extends Exception { /** * */ private static final long serialVersionUID = 1L; /** * Constructor with message * @param message */ public EDRServiceException(String message) { super(message); } /** * Constructor with exception object * @param throwable object */ public EDRServiceException(Throwable t) { super(t); } /** * Constructor with message and throwable object * @param message * @param throwable object */ public EDRServiceException(String msg, Throwable t) { super(msg, t); } }
package io.ambershogun.ampq; import io.ambershogun.RequestProcessor; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.Queue; import org.springframework.amqp.core.TopicExchange; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class RabbitConfiguration { public final static String QUEUE_NAME = "request-queue"; private final static String EXCHANGE_NAME = "request-exchange"; @Bean public Queue queue() { return new Queue(QUEUE_NAME, false); } @Bean public TopicExchange exchange() { return new TopicExchange(EXCHANGE_NAME); } @Bean public Binding binding(Queue queue, TopicExchange exchange) { return BindingBuilder.bind(queue).to(exchange).with(QUEUE_NAME); } @Bean public MessageListenerAdapter listenerAdapter(RequestProcessor requestProcessor) { return new MessageListenerAdapter(requestProcessor, "receiveMessage"); } @Bean SimpleMessageListenerContainer container(ConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.setQueueNames(QUEUE_NAME); container.setMessageListener(listenerAdapter); container.setConcurrentConsumers(10); return container; } }
package com.youthlin.example.chat.client.handler; import com.youthlin.example.chat.model.User; import com.youthlin.example.chat.protocol.request.QuitGroupRequestPacket; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import java.util.List; import java.util.stream.Collectors; /** * 创建: youthlin.chen * 时间: 2018-11-14 10:18 */ @ChannelHandler.Sharable public class QuitGroupResponseHandler extends SimpleChannelInboundHandler<QuitGroupRequestPacket> { public static final QuitGroupResponseHandler INSTANCE = new QuitGroupResponseHandler(); @Override protected void channelRead0(ChannelHandlerContext ctx, QuitGroupRequestPacket msg) throws Exception { User whoQuit = msg.getWhoQuit(); long groupId = msg.getGroupId(); List<User> userList = msg.getUserList(); List<String> userNameList = userList.stream().map(User::getName).collect(Collectors.toList()); System.out.println("[" + whoQuit.getName() + "]退出群聊[" + groupId + "]群里还有:" + userNameList); } }
package ru.stqa.pft.sandbox; public class Equality { public static void main(String[] args) { String s1 = "firefox"; //String s2 = s1; //String s2 = new String(s1); String s2 = "fire" + "fox"; // Переменная ссылка на обьект. Обьект - данные, которые хранятся где то в памяти, // имеют определенную структуру и принадлежат к определенному типу System.out.println(s1 == s2); System.out.println(s1.equals(s2)); } }
package entity; import Excecoes.UsuarioJaExistenteException; public class Funcionario extends Pessoa{ public Funcionario(String nome, String CPF, String endereco, String login, String senha, int telefone) throws UsuarioJaExistenteException { super(nome, CPF, endereco, login, senha, telefone); } }
package org.formation.controller; import org.formation.model.Account; import org.formation.model.AccountCrudRepository; import org.springframework.http.MediaType; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @Component public class AccountHandler { private final AccountCrudRepository accountCrudRepository; public AccountHandler(AccountCrudRepository accountCrudRepository) { this.accountCrudRepository = accountCrudRepository; } public Mono<ServerResponse> listAccounts(ServerRequest request) { Flux<Account> accounts = accountCrudRepository.findAll(); return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(accounts, Account.class); } public Mono<ServerResponse> createAccount(ServerRequest request) { Mono<Account> account = request.bodyToMono(Account.class); return ServerResponse.ok().body(accountCrudRepository.saveAll(account), Account.class); } public Mono<ServerResponse> getAccount(ServerRequest request) { String id = request.pathVariable("id"); Mono<ServerResponse> notFound = ServerResponse.notFound().build(); Mono<Account> accountMono = this.accountCrudRepository.findById(Mono.just(id)); return accountMono .then(ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(accountMono, Account.class)) .defaultIfEmpty(notFound.block()); } }
package com.bike_style.model; import java.util.*; public interface Bike_styleDAO_interface { public void insert(Bike_styleVO bike_styleVO); public void update(Bike_styleVO bike_styleVO); public void delete(String bike_styno); public Bike_styleVO findByPrimaryKey(String bike_styno); public List<Bike_styleVO> getAll(); }
package com.jackal.jack.healthdaily.Database; import android.database.Cursor; import android.database.CursorWrapper; import com.jackal.jack.healthdaily.Database.GoalDbSchema.GoalTable; import com.jackal.jack.healthdaily.Goal; /** * Created by Jack on 1/23/18. */ public class GoalCursorWrapper extends CursorWrapper { public GoalCursorWrapper(Cursor cursor) { super(cursor); } public Goal getGoal() { String stringQuestionNumber = getString(getColumnIndex(GoalTable.Cols.questionNumber)); String goalType = getString(getColumnIndex(GoalTable.Cols.type)); String questionText = getString(getColumnIndex(GoalTable.Cols.questionText)); String answer = getString(getColumnIndex(GoalTable.Cols.userAnswer)); Goal goal = new Goal(); goal.setQuestionNumber(Integer.parseInt(stringQuestionNumber)); goal.setType(goalType); goal.setQuestion(questionText); return goal; } }
package com.lenovohit.hwe.treat.service.impl; import java.util.Map; import com.lenovohit.hwe.treat.dto.GenericRestDto; import com.lenovohit.hwe.treat.model.Foregift; import com.lenovohit.hwe.treat.service.HisForegiftService; import com.lenovohit.hwe.treat.transfer.RestEntityResponse; import com.lenovohit.hwe.treat.transfer.RestListResponse; /** * * @author xiaweiyi */ public class HisForegiftRestServiceImpl implements HisForegiftService { GenericRestDto<Foregift> dto; public HisForegiftRestServiceImpl(final GenericRestDto<Foregift> dto) { super(); this.dto = dto; } @Override public RestEntityResponse<Foregift> recharge(Foregift request, Map<String, ?> variables) { return dto.postForEntity("hcp/app/test/foregift/recharge", request); } @Override public RestEntityResponse<Foregift> transfer(Foregift request, Map<String, ?> variables) { // TODO Auto-generated method stub return null; } @Override public RestListResponse<Foregift> findList(Foregift request, Map<String, ?> variables) { return dto.getForList("hcp/app/test/foregift/list", request); } }
package problem80; import java.util.Stack; /** * Created by yaodong.hyd on 2016/8/2. */ public class Solution { /** * 回溯法 * @param board * @param word * @return */ public boolean exist(char[][] board, String word) { boolean isExists = false; Stack<Item> stack = new Stack<>(); if (board == null || board.length == 0 || board[0] == null || board[0].length == 0) return false; int m = board.length,n = board[0].length; if (m*n<word.length()) return false; for (int i = 0;i<m;i++){ for (int j =0;j<n;j++){ if (board[i][j] == word.charAt(0)) { stack.push(new Item(i,j,board[i][j],0)); int current = 1; board[i][j] = '*'; while (!stack.empty()){ if (current >= word.length()) return true; Item peek = stack.peek(); if (peek.direction == 0 ) { peek.direction = 1; if (peek.x > 0 && board[peek.x-1][peek.y] == word.charAt(current)){ stack.push(new Item(peek.x-1,peek.y,board[peek.x-1][peek.y],0)); board[peek.x-1][peek.y] = '*'; current ++; continue; } } if (peek.direction == 1) { peek.direction = 2; if (peek.x < m-1 && board[peek.x+1][peek.y] == word.charAt(current)){ stack.push(new Item(peek.x+1,peek.y,board[peek.x+1][peek.y],0)); board[peek.x+1][peek.y] = '*'; current += 1; continue; } } if (peek.direction == 2) { peek.direction = 3; if (peek.y > 0 && board[peek.x][peek.y-1] == word.charAt(current)){ stack.push(new Item(peek.x,peek.y-1,board[peek.x][peek.y-1],0)); board[peek.x][peek.y-1] = '*'; current += 1; continue; } } if (peek.direction == 3) { peek.direction = 4; if (peek.y < n-1 && board[peek.x][peek.y+1] == word.charAt(current)){ stack.push(new Item(peek.x,peek.y+1,board[peek.x][peek.y+1],0)); board[peek.x][peek.y+1] = '*'; current += 1; continue; } } Item p = stack.pop(); board[p.x][p.y] = p.c; current--; } } } } return false; } class Item { int x; int y; char c; int direction; //0-上,1-下,2-左,3-右 public Item(int x, int y, char c, int direction) { this.x = x; this.y = y; this.c = c; this.direction = direction; } } public static void main(String[] args){ char[][] board = { {'A', 'B'}, {'C','D'}, }; Solution s = new Solution(); System.out.println(s.exist(board,"DBAC")); } }
package main.java.oop.Inherit6; public abstract class MediaFile extends File{ public MediaFile(String filename) { super(filename); } // 상속받은 execute()는 숨어있음. public abstract void forward(); public abstract void rewind(); }
package com.Exam.Service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.Exam.DAO.SalesCodeDAO; import com.Exam.Entity.SalesCode; @Service public class SalesCodeService { @Autowired SalesCodeDAO codeDAO; // Show sale code public List<SalesCode> ShowAll(){ return codeDAO.findAll(); } }
/* * 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 ejercicio1; /** * * @author Juan */ public class Pais { protected String nombre,presidente,ciudades,gente; protected double cantpersonas,tamaño,ubicacion; public Pais(String nombre, String presidente, String ciudades, String gente, double cantpersonas, double tamaño, double ubicacion) { this.nombre = nombre; this.presidente = presidente; this.ciudades = ciudades; this.gente = gente; this.cantpersonas = cantpersonas; this.tamaño = tamaño; this.ubicacion= ubicacion; } public String mostrarPais(){ String resultado=""; resultado= nombre + "/t" + presidente + "/t" + ciudades + "/t" + gente + "/t" + Double.toString(cantpersonas) + "/t" + Double.toString(tamaño) + "/t" + Double.toString(ubicacion); return resultado; } }
package Sekcja8.Exercise.Exercise46; import java.util.ArrayList; import java.util.LinkedList; import java.util.ListIterator; public class Album { private String name; private String artist; private ArrayList<Song> songs; public Album(String name, String artist) { this.name = name; this.artist = artist; this.songs = new ArrayList<>(); } public boolean addSong(String title, double duration) { if (findSong(title) != null) { return false; } Song newSong = new Song(title, duration); songs.add(newSong); return true; } private Song findSong(String title) { if (!songs.isEmpty()) { for (Song s : songs) { if (s.getTitle().equals(title)) { return s; } } } return null; } public boolean addToPlayList(int trackNumber, LinkedList<Song> playList) { if (trackNumber <= 0 || trackNumber > songs.size()) { return false; } Song songToAdd = songs.get(trackNumber-1); String songToAddTitle = songToAdd.getTitle(); ListIterator<Song> playListIterator = playList.listIterator(); while (playListIterator.hasNext()) { if (playListIterator.next().getTitle().compareTo(songToAddTitle) == 0) { return false; } } playList.add(songToAdd); return true; } public boolean addToPlayList(String title, LinkedList<Song> playList) { Song songToAdd = findSong(title); if (songToAdd == null) { return false; } ListIterator<Song> playListIterator = playList.listIterator(); while (playListIterator.hasNext()) { if (playListIterator.next().getTitle().compareTo(songToAdd.getTitle()) == 0) { return false; } } playList.add(songToAdd); return true; } }
package lesson8.homeWork; import lesson8.homeWork.barrier.Treadmill; import lesson8.homeWork.barrier.Wall; import lesson8.homeWork.interfaces.Barriers; import lesson8.homeWork.interfaces.Member; import lesson8.homeWork.member.Cat; import lesson8.homeWork.member.Human; import lesson8.homeWork.member.Robot; import java.util.ArrayList; public class Main { public static void main(String[] args) { Cat cat = new Cat(300, 3); Human human = new Human(1000, 1.5); Robot robot = new Robot(5000, 0.5); ArrayList<Member> members = new ArrayList<>(); members.add(cat); members.add(human); members.add(robot); Wall wall = new Wall(1.5); Treadmill treadmill = new Treadmill(300); ArrayList<Barriers> barriers = new ArrayList<>(); barriers.add(wall); barriers.add(treadmill); for (Member member : members) { boolean isContinue = true; for (Barriers barrier : barriers) { if (barrier instanceof Wall){ Wall wallBarrier = (Wall) barrier; isContinue = member.jump(wallBarrier.getHeight()); } else if (barrier instanceof Treadmill){ Treadmill treadmillBarrier = (Treadmill) barrier; isContinue = member.run(treadmillBarrier.getLength()); } if (!isContinue){ break; } } if (isContinue) { System.out.println("Участник завершил полосу препятствий"); } else { System.out.println("Участник сошёл с дистанции"); } } } }
package com.pastelstudios.spring.zookeeper.discovery; import java.util.HashMap; import java.util.Map; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceInstanceBuilder; import org.apache.curator.x.discovery.UriSpec; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; public class CuratorServiceInstanceFactoryBean implements FactoryBean<ServiceInstance<ServiceMetadata>>, InitializingBean, DisposableBean { private ServiceInstance<ServiceMetadata> serviceInstance = null; private ServiceDiscovery<ServiceMetadata> serviceDiscovery = null; private UriSpec uriSpec = new UriSpec("{scheme}://{address}:{port}"); private String serviceName = null; private Integer port = null; private Integer sslPort = null; private Map<String, String> metadata = new HashMap<>(); public void setServiceDiscovery(ServiceDiscovery<ServiceMetadata> serviceDiscovery) { this.serviceDiscovery = serviceDiscovery; } public void setUriSpec(UriSpec uriSpec) { this.uriSpec = uriSpec; } public void setServiceName(String serviceName) { this.serviceName = serviceName; } public void setPort(Integer port) { this.port = port; } public void setMetadata(Map<String, String> metadata) { this.metadata = metadata; } @Override public void afterPropertiesSet() throws Exception { Assert.notNull(serviceDiscovery); Assert.notNull(serviceName); Assert.notNull(uriSpec); Assert.notNull(port); ServiceMetadata serviceMetadata = new ServiceMetadata(); serviceMetadata.setMetadata(metadata); ServiceInstanceBuilder<ServiceMetadata> builder = ServiceInstance.<ServiceMetadata> builder() .uriSpec(uriSpec) .name(serviceName) .port(port) .payload(serviceMetadata); if (sslPort != null) { builder.sslPort(sslPort); } serviceInstance = builder.build(); serviceDiscovery.registerService(serviceInstance); } @Override public void destroy() throws Exception { if (serviceInstance != null) { serviceDiscovery.unregisterService(serviceInstance); } } @Override public ServiceInstance<ServiceMetadata> getObject() throws Exception { return serviceInstance; } @Override public Class<?> getObjectType() { return ServiceInstance.class; } @Override public boolean isSingleton() { return true; } }
package com.gsccs.sme.center.controller; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.gsccs.sme.api.domain.Account; import com.gsccs.sme.api.domain.base.Datagrid; import com.gsccs.sme.api.domain.base.JsonMsg; import com.gsccs.sme.api.domain.corp.CorpMsw; import com.gsccs.sme.api.domain.corp.CorpRun; import com.gsccs.sme.api.exception.ApiException; import com.gsccs.sme.api.service.AccountServiceI; import com.gsccs.sme.api.service.CorpServiceI; /** * 企业固体废弃物管理 * * @author x.d zhang * */ @Controller(value = "CorpMswCtl") @RequestMapping(value = "/cp/corpmsw") public class CorpMswController { @Autowired private AccountServiceI accountAPI; @Autowired private CorpServiceI corpAPI; /** * 企业固体废弃物 * * @param model * @param response * @return */ @RequestMapping(method = RequestMethod.GET) public String corptech(Model model, HttpServletResponse response) { return "corp/msw-list"; } /** * 企业固体废弃物 * * @param model * @param response * @return */ @RequestMapping(value = "/datagrid", method = RequestMethod.POST) @ResponseBody public Datagrid datagrid(CorpMsw param, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int pagesize, Model model, HttpServletResponse response) { Datagrid datagrid = new Datagrid(); try { Subject subject = SecurityUtils.getSubject(); String username = (String) subject.getPrincipal(); Account user = accountAPI.getAccount(username); if (null == param) { param = new CorpMsw(); param.setCorpid(user.getOrgid()); } List<CorpMsw> corpMsws = corpAPI.find(param, "year desc", page, pagesize); datagrid.setRows(corpMsws); datagrid.setTotal(0l); } catch (ApiException e) { e.printStackTrace(); } return datagrid; } /** * 企业经营数据表单 * * @param model * @param response * @return */ @RequestMapping(value = "/form", method = RequestMethod.GET) public String mswForm(Long id, Model model, HttpServletResponse response) { CorpMsw corpMsw = null; if (null != id) { corpMsw = corpAPI.getCorpMsw(id); } model.addAttribute("corpMsw", corpMsw); return "corp/msw-form"; } /** * 数据保存 * @param param * @param model * @return */ @RequestMapping(value = "/save", method = RequestMethod.POST) @ResponseBody public JsonMsg datagrid(CorpMsw param, Model model) { JsonMsg jsonMsg = new JsonMsg(); if (null == param) { jsonMsg.setSuccess(false); return jsonMsg; } Subject subject = SecurityUtils.getSubject(); String username = (String) subject.getPrincipal(); Account user; try { user = accountAPI.getAccount(username); param.setCorpid(user.getOrgid()); corpAPI.saveMsw(param); } catch (Exception e) { jsonMsg.setSuccess(false); jsonMsg.setMsg("未知错误"); } return jsonMsg; } }
package com.example.scso.school_social; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; /** * Created by CYH on 2017/7/5. */ public class PinglunActivity extends Activity { private String type; private String id; private String user_id; private ListView pinglun_list; private Handler handler; private Handler handler1; private ArrayList<HashMap<String,String>> pinglun_data_list; private String target_user_id; private String target_user_name; private EditText pinglun_edit; private Button pinglun_button; private Button huifu_button; private JSONObject json; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { Intent intent=getIntent(); type=intent.getStringExtra("type"); id=intent.getStringExtra("id"); user_id=intent.getStringExtra("user_id"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_pinglun); //Toast.makeText(PinglunActivity.this,type+id, Toast.LENGTH_SHORT).show(); pinglun_list =(ListView) findViewById(R.id.pinglun_list); pinglun_edit =(EditText) findViewById(R.id.pinglun_edit); pinglun_button=(Button) findViewById(R.id.pinglun_button); huifu_button=(Button) findViewById(R.id.huifu_button); handler1=new Handler(){ @Override public void handleMessage(Message msg) { if(msg.what==3){ Toast.makeText(PinglunActivity.this,"评论成功",Toast.LENGTH_SHORT).show(); pinglun_edit.setText(""); get_data(); } else{ Toast.makeText(PinglunActivity.this,"评论失败,请稍后再试",Toast.LENGTH_SHORT).show(); } } }; pinglun_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (TextUtils.isEmpty(pinglun_edit.getText())) { Toast.makeText(PinglunActivity.this, "评论不能为空", Toast.LENGTH_SHORT).show(); } else { json = new JSONObject(); try { json.put("type", type); json.put("id", id); json.put("user_id", user_id); json.put("content", pinglun_edit.getText().toString()); json.put("is_huifu", 0); } catch (JSONException e) { e.printStackTrace(); } HttpPost httpPost = new HttpPost(json, "pinglun.jsp", handler1); httpPost.doPost(); } } }); huifu_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Toast.makeText(PinglunActivity.this,"huifu",Toast.LENGTH_SHORT).show(); if (TextUtils.isEmpty(pinglun_edit.getText())) { Toast.makeText(PinglunActivity.this, "评论不能为空", Toast.LENGTH_SHORT).show(); } else { json = new JSONObject(); try { json.put("type", type); json.put("id", id); json.put("user_id", user_id); json.put("is_huifu", 1); json.put("target_user_id", target_user_id); json.put("content", "回复 @" + target_user_name + " :" + pinglun_edit.getText().toString()); } catch (JSONException e) { e.printStackTrace(); } HttpPost httpPost = new HttpPost(json, "pinglun.jsp", handler1); httpPost.doPost(); } } }); pinglun_list.setOnItemClickListener(new ListListener()); handler=new Handler(){ @Override public void handleMessage(Message msg) { if(msg.what==3){ pinglun_data_list=new ArrayList<>(); JSONArray pinglunJSON=(JSONArray) msg.obj; try { for (int i = 0; i < pinglunJSON.length(); i++) { HashMap<String, String> data = new HashMap<>(); data.put("user_name", pinglunJSON.getJSONObject(i).getString("user_name")); data.put("user_id",pinglunJSON.getJSONObject(i).getString("user_id")); data.put("date_time",pinglunJSON.getJSONObject(i).getString("date_time")); data.put("content",pinglunJSON.getJSONObject(i).getString("content")); pinglun_data_list.add(data); } }catch (JSONException e){ e.printStackTrace(); } SimpleAdapter adapter=new SimpleAdapter(PinglunActivity.this,pinglun_data_list,R.layout.pinglun_list_layout, new String[] {"user_name","user_id","date_time","content"},new int[] {R.id.user_name,R.id.user_id, R.id.date_time,R.id.content}); pinglun_list.setAdapter(adapter); } else{ Toast.makeText(PinglunActivity.this,"获取评论失败",Toast.LENGTH_SHORT); } } }; get_data(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode==KeyEvent.KEYCODE_BACK && huifu_button.getVisibility()==View.VISIBLE){ huifu_button.setVisibility(View.GONE); pinglun_button.setVisibility(View.VISIBLE); } else{ finish(); } return false; } public class ListListener implements AdapterView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { int now_position=position-parent.getFirstVisiblePosition(); View v=(View)parent.getChildAt(now_position); TextView user_id_text=(TextView) v.findViewById(R.id.user_id); TextView user_name_text=(TextView) v.findViewById(R.id.user_name); //TextView id_text=(TextView)layout.findViewById(R.id.goods_id); target_user_id=user_id_text.getText().toString(); target_user_name=user_name_text.getText().toString(); pinglun_edit.requestFocus(); InputMethodManager imm=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(0,InputMethodManager.SHOW_IMPLICIT); pinglun_button.setVisibility(View.GONE); huifu_button.setVisibility(View.VISIBLE); } } public void get_data(){ Log.d("tag", "get_data: "); JSONObject json=new JSONObject(); try { json.put("type",type); json.put("id",id); } catch (JSONException e) { e.printStackTrace(); } HttpPost httpPost=new HttpPost(json,"get_pinglun.jsp",handler); httpPost.doPost(); } public void back(View v){ finish(); } }
package object; public class TestSuper { public static void main(String[] args) { System.out.println("开始创建一个ChildClass对象"); new ChildClass2(); } } class FatherClass2{ public FatherClass2(){ super(); // 默认调用父类Object的super(),写不写都会调 System.out.println("创建FatherClass"); } } class ChildClass2 extends FatherClass2{ public ChildClass2(){ super(); // 调用父类的super(),写不写都会调 System.out.println("创建ChildClass2"); } }
package basic; import javax.management.InstanceNotFoundException; /* * Thread의 stop()메서드를 호출하면 쓰레드가 바로 멈춘다. * 이 때 사용하던 자원을 정리하지 못하고 프로그램이 종료되어 나중에 실행되는 * 프로그램에 영향을 줄 수 있다. 그래서 stop()메서드는 비추천되어 있다. */ public class ThreadTest14 { public static void main(String[] args) { ThreadStopEx1 th1 = new ThreadStopEx1(); th1.start(); /* try { Thread.sleep(1000); } catch (InterruptedException e) { } // th1.stop(); //stop() 메서드는 사용하지 않는다. th1.setStop(true);*/ //interrupt()메서드를 이용한 쓰레드 멈추기 ThreadStopEx2 th2 = new ThreadStopEx2(); th2.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { } th2.interrupt(); } } class ThreadStopEx1 extends Thread{ private boolean stop; public void setStop(boolean stop){ this.stop = stop; } @Override public void run() { while(!stop){ System.out.println("쓰레드 실행 중 ..."); } System.out.println("자원 정리..."); System.out.println("실행 종료..."); } } //interrupt()메서드를 이용하여 쓰레드를 멈추게 하는 방법 class ThreadStopEx2 extends Thread{ @Override public void run() { /* // 방법 1 while(true){ System.out.println("실행 중..."); try { Thread.sleep(1); //sleep()에 의해 일시정지 상태에서 interrupt()메서드가 실행되면 //InterruptedException이 발생한다. } catch (InterruptedException e) { break; } } System.out.println("자원 정리..."); System.out.println("실행 종료...");*/ while(true){ System.out.println("실행 중..."); //interrupt()메서드가 호출되었는지를 검사하기 /*// 검사 방법1 // ==> 인스턴그 객체용 메서드 isInterrupted()를 이용하여 검사한다. if(this.isInterrupted()){ break; }*/ //검사 방법2 //==>Thread의 정적 메서드 interrupted()를 이용하여 검사한다. if(Thread.interrupted()){ break; } } System.out.println("자원 정리..."); System.out.println("실행 종료..."); } }
module ContratosDeTrabalho { }
package moobie.rest; import java.util.List; import javax.annotation.PostConstruct; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import moobie.dao.CarroDisponibilidadeDAO; import moobie.entidade.Carro; import moobie.entidade.CarroDisponibilidade;; @Path("/disponibilidade") public class CarroDisponibilidadeService { private CarroDisponibilidadeDAO carroDisponibilidadeDAO; @PostConstruct private void init(){ carroDisponibilidadeDAO = new CarroDisponibilidadeDAO(); } @GET @Path("/list") @Produces(MediaType.APPLICATION_JSON) public List<CarroDisponibilidade> listarAgendamentos(Carro carro) { List<CarroDisponibilidade> lista = null; try { lista = carroDisponibilidadeDAO.listarDisponibilidadePorCarro(carro); } catch (Exception e) { e.printStackTrace(); } return lista; } @POST @Path("/add") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.TEXT_PLAIN) public String addDisponibilidade(CarroDisponibilidade disponibilidade) { String msg = ""; System.out.println("Adicionando disponibilidade para o carro :" + disponibilidade.getCarro().getId()); try { int idGerado = carroDisponibilidadeDAO.addDisponibilidade(disponibilidade); msg = String.valueOf(idGerado); } catch (Exception e) { msg = "Erro ao adicionar disponibilidade!"; e.printStackTrace(); } return msg; } @GET @Path("/get/{id}") @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.APPLICATION_JSON) public CarroDisponibilidade buscarDisponibilidade(CarroDisponibilidade disponibilidade) { CarroDisponibilidade carroDisponibilidade = null; try { carroDisponibilidade = carroDisponibilidadeDAO.buscarDisponibilidadePorDataHora(disponibilidade.getCarro(), disponibilidade.getData(), disponibilidade.getHora_ini(), disponibilidade.getHora_fim()); } catch (Exception e) { e.printStackTrace(); } return carroDisponibilidade; } @PUT @Path("/edit/{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.TEXT_PLAIN) public String editarDisponibilidade(CarroDisponibilidade disponibilidade, @PathParam("id") int idDisponibilidade) { String msg = ""; System.out.println("Editando disponibilidade do carro :" + disponibilidade.getCarro().getId()); try { carroDisponibilidadeDAO.editDisponibilidade(disponibilidade, idDisponibilidade); msg = "Disponibilidade editada com sucesso!"; } catch (Exception e) { msg = "Erro ao editar disponibilidade!"; e.printStackTrace(); } return msg; } @DELETE @Path("/delete/{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.TEXT_PLAIN) public String removerDisponibilidade(@PathParam("id") int idDisponibilidade) { String msg = ""; try { carroDisponibilidadeDAO.deleteDisponibilidade(idDisponibilidade); msg = "Disponibilidade removida com sucesso!"; } catch (Exception e) { msg = "Erro ao remover disponibilidade!"; e.printStackTrace(); } return msg; } }
import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * This program displays the sum of a range of numbers entered in text fields * when a button is clicked. * * This version is for practising with BlueJ's interactive debugging tool. * * @author sbj * @version 16 October 2005 */ public class SumUp extends JFrame implements ActionListener { /** The textfield for entering the first number in the range to be summed */ private JTextField start; /** The textfield for entering the final number in the range to be summed */ private JTextField end; /** The textfield for displaying the resultant sum */ private JTextField result; /** The button for triggering a calculation to be carried out */ private JButton button; /** Holds the range start value. * Set up in actionPerformed from the start textfield. * Should preferably be a local variable in actionPerformed */ private int rangeStart; /** Holds the range end value. * Set up in actionPerformed from the end textfield. * Should preferably be a local variable in actionPerformed */ private int rangeEnd; /** * The main launch program for the SumUp class * * @param args The command line arguments (ignored here) */ public static void main( String[] args ) { SumUp demo = new SumUp(); demo.setSize( 400, 150 ); demo.createGUI(); demo.setVisible( true ); } // End of main /** Sets up the graphical user interface */ private void createGUI() { setDefaultCloseOperation( EXIT_ON_CLOSE ); Container window = getContentPane(); window.setLayout( new FlowLayout() ); window.add( new JLabel( "Range start:" ) ); start = new JTextField( 5 ); window.add( start ); window.add( new JLabel( "Range end:" ) ); end = new JTextField( 5 ); window.add( end ); button = new JButton( "Calculate" ); window.add( button ); button.addActionListener( this ); window.add( new JLabel( "Sum:" ) ); result = new JTextField( 5 ); window.add( result ); } // End of createGUI /** * Responds to a button click by carrying out the requested * calculation and displaying the result * * @param event Details of the event (ignored here) */ public void actionPerformed( ActionEvent event ) { String startText = start.getText(); rangeStart = Integer.parseInt( startText ); String endText = end.getText(); rangeEnd = Integer.parseInt( endText ); // int total = 0; // X // int count = rangeStart; // while ( count <= rangeEnd ) { // Preferably should be a for loop // total = total + count; // count++; // } // XX int total = sum( rangeStart, rangeEnd ); result.setText( Integer.toString( total ) ); } // End of actionPerformed /** * Returns the sum of integers from start up to end inclusive * * @param start The first value in the range * @param end The final value in the range * @return The sum from start up to end inclusive */ private int sum( int start, int end ) { int total = 0; int count = start; while ( count <= end ) { // Preferably should be a for loop total = total + count; count++; } return total; } // End of sum } // End of SumUp
package Model; import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonArray; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; import java.text.SimpleDateFormat; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.Locale; /** * * @author Aidan */ public class NodeControl { private ContactNode node; static String hostName = "127.0.0.1"; static int portNumber = 2000; static String address; static String balance; static String balanceSpendable; static String balanceStaking; static String balanceUnconfirmed; public Transaction[] transactions = null; public Transaction[] recentTransactions = null; public Transaction[] coinbaseTransactions = null; public int estimatedBlocks; public String block; static String version; static String uptime; static String nodes; static String staking; static String sync; static Boolean connected = false; Double totalWinnings; public void setup() { node = new ContactNode(); } public JsonObject sendCommandObject(String command, int timeout) { JsonObject objResponse = node.sendCommandAndGetJsonObject(command, timeout); return objResponse; } public JsonObject sendCommandObject(String command, String nested, int timeout) { JsonObject objResponse = node.sendCommandAndGetJsonObject(command, nested, timeout); return objResponse; } public JsonArray sendCommandArray(String command, String nested, int timeout) { JsonArray arrayResponse = node.sendCommandAndGetJsonArray(command, nested, timeout); return arrayResponse; } public void updateInfo() { JsonObject updateResponse = sendCommandObject("json getinfo", 50); if (updateResponse != null) { version = updateResponse.getString("version", "Unavailable"); uptime = updateResponse.getString("uptime", "Unavailable"); nodes = updateResponse.getString("nodes_connected", "Unavailable"); staking = updateResponse.getString("staking_status", "Unavailable"); sync = updateResponse.getString("sync_status", "Unavailable"); } else { System.out.println("Error updating info..."); } } //Update to allow for multiple addresses public void updateWallet(String nested) { JsonArray arrayResponse = sendCommandArray("json wallet", nested, 50); if (arrayResponse != null) { JsonObject firstAddress = arrayResponse.get(0).asObject(); String balanceResponse = firstAddress.getString("balance", "Unavailable"); String parts[] = balanceResponse.split("\\("); balance = parts[1]; address = firstAddress.getString("address", "Unavailable"); //balance = firstAddress.getString("balance", "Unavailable"); } else { address = "Unavailable"; balance = "Unavailable"; } } public void updateWallet() { JsonArray arrayResponse = sendCommandArray("json wallet", "list_addresses", 50); if (arrayResponse != null) { JsonObject firstAddress = arrayResponse.get(0).asObject(); String balanceResponse = firstAddress.getString("balance", "Unavailable"); String parts[] = balanceResponse.split("\\("); balance = parts[0]; balanceSpendable = parts[1].substring(0, parts[1].length() - 1); balanceStaking = parts[0]; double difference = Double.parseDouble(balanceSpendable) - Double.parseDouble(balance); if (difference > 0.0) { balanceUnconfirmed = Double.toString(difference); } else { balanceUnconfirmed = "0.00"; } address = firstAddress.getString("address", "Unavailable"); } else { } } public void updateBlock() { JsonObject updateResponse = sendCommandObject("json_block", "blockheader", 50); if (updateResponse != null) { block = Integer.toString(updateResponse.getInt("blocknumber", 0)); try { Double timestamp = updateResponse.getDouble("timestamp", 0) * 1000; Double now = (double) Instant.now().toEpochMilli(); Double difference = now - timestamp; estimatedBlocks = (int) ((difference / 46000) + Integer.valueOf(block)); } catch (Exception e) { System.out.println("Error retrieving block height and timestamp..."); e.printStackTrace(); } } else { System.out.println("Error updating blocks..."); } } public void updateTransactions() { JsonArray arrayResponse = sendCommandArray("json search " + address, "transactions", 200); if (arrayResponse != null) { ArrayList<Transaction> listTransactions = new ArrayList<Transaction>(); ArrayList<Transaction> listRecentTransactions = new ArrayList<Transaction>(); ArrayList<Transaction> listCoinbaseTransactions = new ArrayList<Transaction>(); for (JsonValue value : arrayResponse) { JsonObject object = value.asObject(); try { Transaction transaction = new Transaction( Double.toString(object.getDouble("timestamp", -1.0)), object.getString("subtype", "default"), object.getString("txhash", "default"), object.getString("txto", "default"), object.getString("txfrom", "default"), Double.toString(object.getDouble("amount", -1.0)), Integer.toString(object.getInt("block", -1)) ); if(transaction.getTypeProperty().get().equals("TX")) { System.out.println("TX = TX"); System.out.println(transaction); listTransactions.add(transaction); } else if(transaction.getTypeProperty().get().equals("COINBASE")) { System.out.println("TX = COINBASE"); listCoinbaseTransactions.add(transaction); } else { System.out.println("NOTHING HERE"); } } catch (Exception e) { System.out.println("Error managing transactions..."); e.printStackTrace(); } } Transaction[] transactionArray = listTransactions.toArray(new Transaction[listTransactions.size()]); Transaction[] recentTransactionArray = listRecentTransactions.toArray(new Transaction[listTransactions.size()]); Transaction[] coinbaseTransactionArray = listCoinbaseTransactions.toArray(new Transaction[listTransactions.size()]); transactions = transactionArray; recentTransactions = recentTransactionArray; coinbaseTransactions = coinbaseTransactionArray; addStakeWinnings(); } else { System.out.println("Error updating transactions..."); } } public void addStakeWinnings() { totalWinnings = 0.0; for(Transaction t : coinbaseTransactions) { totalWinnings += Double.parseDouble(t.getAmountProperty().get()); } } public String[] sendQRL(String fromAddress, String toAddress, String amount) { String query = "json send " + fromAddress + " " + toAddress + " " + amount; JsonObject sendResponse = sendCommandObject(query, 1000); String stringResponse = sendResponse.getString("message", "Undelivered..."); String[] responses = stringResponse.split(">>>"); return responses; } public void connect() { try { System.out.println("About to connect!!"); node.connect(); connected = true; } catch (Exception e) { System.out.println("EEEEERRRROR"); e.printStackTrace(); } } public String getVersion() { return version; } public String getUptime() { if (uptime != null) { try { double timed = Double.parseDouble(uptime); int time = (int) timed; int hours = time / 3600; int secondsLeft = time - hours * 3600; int minutes = secondsLeft / 60; int seconds = secondsLeft - minutes * 60; String formattedTime = ""; if (hours != 0) { formattedTime += hours + " hrs "; } if (minutes != 0) { formattedTime += minutes + " mins "; } if (seconds != 0) { formattedTime += seconds + " seconds"; } return formattedTime; } catch (Exception e) { return uptime; } } else { return ""; } } public int getEstimatedBlocks() { return estimatedBlocks; } public String getBlock() { return block; } public String getNodes() { return nodes; } public String getStaking() { return staking; } public String getSync() { return sync; } public String getAddress() { return address; } public String getBalance() { return balance; } public String getBalanceSpendable() { return balanceSpendable; } public String getBalanceUnconfirmed() { return balanceUnconfirmed; } public String getBalanceStaking() { return balanceStaking; } public boolean getConnected() { return connected; } public Transaction[] getTransactions() { return transactions; } public Transaction[] getCoinbaseTransactions() { return coinbaseTransactions; } }
package biz.tekeye.listeners; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class main extends Activity implements OnClickListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //Method 1 attach an instance of HandleClick class to the Button findViewById(R.id.button1).setOnClickListener(new HandleClick()); //Method 2 use the handleClick variable to attach the event listener findViewById(R.id.button2).setOnClickListener(handleClick); //Method 3 anonymous inner class to attach the event listener findViewById(R.id.button3).setOnClickListener(new OnClickListener(){ public void onClick(View arg0) { Button btn = (Button)arg0; TextView tv = (TextView) findViewById(R.id.textview3); tv.setText("You pressed " + btn.getText()); } }); //Method 4 Implementation in Activity findViewById(R.id.button4).setOnClickListener(this); //Method 5 set up via layout attribute onClick assigned to HandleClickByAttribute } //Method 1 a call implementing onClickListener private class HandleClick implements OnClickListener{ public void onClick(View arg0) { Button btn = (Button)arg0; //cast view to a button // get a reference to the TextView TextView tv = (TextView) findViewById(R.id.textview1); // update the TextView text tv.setText("You pressed " + btn.getText()); } } //Method 2 a variable declared as a type of interface private OnClickListener handleClick = new OnClickListener(){ public void onClick(View arg0) { Button btn = (Button)arg0; TextView tv = (TextView) findViewById(R.id.textview2); tv.setText("You pressed " + btn.getText()); } }; //Method 4 Implementation on the onClickListener by the Activity public void onClick(View arg0) { Button btn = (Button)arg0; TextView tv = (TextView) findViewById(R.id.textview4); tv.setText("You pressed " + btn.getText()); } public void HandleClickByAttribute(View arg0) { Button btn = (Button)arg0; TextView tv = (TextView) findViewById(R.id.textview5); tv.setText("You pressed " + btn.getText()); } }
/* * External Code Formatter Copyright (c) 2007-2009 Esko Luontola, www.orfjackal.net 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 krasa.formatter.settings; import javax.swing.*; import krasa.formatter.Messages; import krasa.formatter.Resources; import krasa.formatter.plugin.ProjectCodeStyleInstaller; import krasa.formatter.plugin.ProjectSettingsForm; import krasa.formatter.utils.ProjectUtils; import org.apache.commons.lang.ObjectUtils; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import com.intellij.notification.NotificationDisplayType; import com.intellij.notification.NotificationGroup; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.ProjectComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; /** * Takes care of initializing a project's CodeFormatter and disposing of it when the project is closed. Updates the * formatter whenever the plugin settings are changed. * * @author Esko Luontola * @since 4.12.2007 */ @State(name = "EclipseCodeFormatter", storages = { @Storage(id = "other", file = "$PROJECT_FILE$") }) public class ProjectSettingsComponent implements ProjectComponent, PersistentStateComponent<Settings> { private static final Logger LOG = Logger.getInstance(ProjectSettingsComponent.class.getName()); public static final NotificationGroup GROUP_DISPLAY_ID_ERROR = new NotificationGroup("Eclipse code formatter error", NotificationDisplayType.BALLOON, true); public static final NotificationGroup GROUP_DISPLAY_ID_INFO = new NotificationGroup("Eclipse code formatter info", NotificationDisplayType.NONE, true); @NotNull private final ProjectCodeStyleInstaller projectCodeStyle; @NotNull private Settings settings = new Settings(); @Nullable private ImageIcon icon; @NotNull private Project project; public ProjectSettingsComponent(@NotNull Project project) { this.projectCodeStyle = new ProjectCodeStyleInstaller(project); this.project = project; } public static Settings getSettings(PsiFile psiFile) { return getInstance(psiFile.getProject()).getSettings(); } public void install(@NotNull Settings settings) { projectCodeStyle.changeFormatterTo(settings); } private void uninstall() { projectCodeStyle.changeFormatterTo(null); } @Override public void initComponent() { } @Override public void disposeComponent() { } @Override @NotNull public String getComponentName() { return "ProjectSettingsComponent"; } public void settingsUpdatedFromOtherProject(Settings updatedSettings) { final Settings.Formatter formatter = settings.getFormatter(); settings = GlobalSettings.getInstance().getSettings(updatedSettings, project); settings.setFormatter(formatter); install(settings); } @Override public void projectOpened() { settings = GlobalSettings.getInstance().getSettings(settings, project); install(settings); } @Override public void projectClosed() { uninstall(); } // implements Configurable public class MyConfigurable implements Configurable { @Nullable private ProjectSettingsForm form; @Override @Nls public String getDisplayName() { return Messages.message("action.pluginSettings"); } @Nullable public Icon getIcon() { if (icon == null) { icon = new ImageIcon(Resources.PROGRAM_LOGO_32); } return icon; } @Override @Nullable @NonNls public String getHelpTopic() { return "EclipseCodeFormatter.Configuration"; } @Override @NotNull public JComponent createComponent() { if (form == null) { form = new ProjectSettingsForm(project, this); } return form.getRootComponent(); } @Override public boolean isModified() { return form != null && (form.isModified(settings) || (form.getDisplayedSettings() != null && !isSameId())); } private boolean isSameId() { return ObjectUtils.equals(form.getDisplayedSettings().getId(), settings.getId()); } @Override public void apply() throws ConfigurationException { if (form != null) { form.validate(); settings = form.exportDisplayedSettings(); GlobalSettings.getInstance().updateSettings(settings, project); ProjectUtils.applyToAllOpenedProjects(settings); } } @Override public void reset() { if (form != null) { form.importFrom(settings); } } @Override public void disposeUIResources() { form = null; } } // implements PersistentStateComponent @Override @NotNull public Settings getState() { return settings; } /** * sets profile for this project */ @Override public void loadState(@NotNull Settings state) { settings = state; } public static ProjectSettingsComponent getInstance(Project project) { return project.getComponent(ProjectSettingsComponent.class); } @NotNull public Project getProject() { return project; } @NotNull public Settings getSettings() { return settings; } }
package com.javaee.ebook1.mybatis.dao; import com.javaee.ebook1.mybatis.entity.Log; import com.javaee.ebook1.mybatis.entity.LogExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface LogMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table log * * @mbg.generated Wed Apr 14 14:41:41 CST 2021 */ long countByExample(LogExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table log * * @mbg.generated Wed Apr 14 14:41:41 CST 2021 */ int deleteByExample(LogExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table log * * @mbg.generated Wed Apr 14 14:41:41 CST 2021 */ int insert(Log record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table log * * @mbg.generated Wed Apr 14 14:41:41 CST 2021 */ int insertSelective(Log record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table log * * @mbg.generated Wed Apr 14 14:41:41 CST 2021 */ List<Log> selectByExample(LogExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table log * * @mbg.generated Wed Apr 14 14:41:41 CST 2021 */ int updateByExampleSelective(@Param("record") Log record, @Param("example") LogExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table log * * @mbg.generated Wed Apr 14 14:41:41 CST 2021 */ int updateByExample(@Param("record") Log record, @Param("example") LogExample example); }
package com.master.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.master.R; /** * Created by YeXiang on 15/2/2. */ public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> { /* LayoutInflater inflater; public RecyclerAdapter(Context context){ inflater = LayoutInflater.from(context); }*/ public static final String TAG = "RecyclerAdapter"; public String[] TITLES; private MyItemClickListener mListener; public RecyclerAdapter(String[] titles) { TITLES = titles; } public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public final TextView tvList; private MyItemClickListener listener; public MyViewHolder(View itemView, MyItemClickListener listener) { super(itemView); this.listener = listener; tvList = (TextView) itemView.findViewById(R.id.tv_list); itemView.setOnClickListener(this); } @Override public void onClick(View v) { if (listener != null) listener.onItemClick(v, getPosition()); } } /** * 设置item点击事件 **/ public void setOnItemClickListener(MyItemClickListener listener) { this.mListener = listener; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false); return new MyViewHolder(v, mListener); } @Override public void onBindViewHolder(RecyclerAdapter.MyViewHolder holder, int position) { /* holder.ivList.setBackgroundResource(mData.get(position).icon);*/ holder.tvList.setText(TITLES[position]); } @Override public int getItemCount() { return TITLES.length; } }
package com.cs.payment; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlRootElement; /** * @author Omid Alaepour */ @XmlRootElement @XmlEnum public enum CreditTransactionType { CONVERSION, BACK_OFFICE_CREDIT_DEPOSIT, BACK_OFFICE_CREDIT_WITHDRAW, }
//package Pro03.LongString; // //import java.util.HashMap; //import java.util.Map; // //public class Solution //{ // // 果然重建map time太长了。。。 // public int lengthOfLongestSubstring(String s) // { // if (s == null || s.length() == 0) // { // return 0; // } // // int len = 0; // int res = 0; // //// 建立一个新的map,key值存储string字符串的没一个字符,value存储字符串的位置 // HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>(); // for (int i = 0; i < s.length(); i++) // { //// 如果hashmap已经存在这个字符了,就清空hashmap,重建一个hashmap,并且从第一次出现字符的下一个字符开始 // if (hashMap.containsKey(s.charAt(i))) // { // i = hashMap.get(s.charAt(i)); // hashMap.clear(); // len = 0; // //所以这里continue循环回了这个if语句的开头,也就直接往下走了 // continue; //continue用于结束循环体中其后语句的执行,并跳回循环程序块的开头执行下一次循环,而不是立刻循环体。 // } // len++; // hashMap.put(s.charAt(i), i); // res = Math.max(res, len); // } // return res; // } // // // 不重建的话,可以用个flag值来记录每次字符串发生重复了的位置 // public int lengthOfLongestSubstring1(String s) // { // if (s == null || s.length() == 0) // { // return 0; // } // // int flag = 0; // int len = 0; // int res = 0; // // HashMap<Character, Integer> hashMap = new HashMap<>(); // for (int i = 0; i < s.length(); i++) // { //// 如果hashmap里存在这个字符,flag设置为这个字符的下一个字符的位置 // if (hashMap.containsKey(s.charAt(i))&&hashMap.get(s.charAt(i))>=flag) // { // flag=hashMap.get(s.charAt(i))+1; // } // len=i-flag+1; // hashMap.put(s.charAt(i),i); // res=Math.max(len,res); // } // return res; // } //}
package com.test.promanage.pojo; public class User { private String user; private String userId; private String userName; private String userPhoto; public User() { } public User(String user,String userId,String userName,String userPhoto){ this.user=user; this.userId=userId; this.userName=userName; this.userPhoto=userPhoto; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPhoto() { return userPhoto; } public void setUserPhoto(String userPhoto) { this.userPhoto = userPhoto; } }
package ua.edu.ucu.stream; import ua.edu.ucu.function.*; import ua.edu.ucu.iterators.BaseIterator; import ua.edu.ucu.iterators.FilterIterator; import ua.edu.ucu.iterators.FlatMapIterator; import ua.edu.ucu.iterators.MapIterator; import java.util.ArrayList; import java.util.Iterator; public class AsIntStream implements IntStream { private final Iterator<Integer> myIterator; private AsIntStream(Iterator<Integer> inpIt) { this.myIterator = inpIt; } public static IntStream of(int... values) { return new AsIntStream(new BaseIterator(values)); } public void isEmpty() { if (!myIterator.hasNext()) { throw new IllegalArgumentException(); } } @Override public Double average() { isEmpty(); int sum = 0; int size = 0; while (myIterator.hasNext()) { sum += myIterator.next(); size += 1; } return (double) sum/size; } @Override public Integer max() { isEmpty(); double myMax = Double.NEGATIVE_INFINITY; while (myIterator.hasNext()) { int next = myIterator.next(); if (next > myMax) { myMax = next; } } return (int) myMax; } @Override public Integer min() { isEmpty(); double myMin = Double.POSITIVE_INFINITY; while (myIterator.hasNext()) { int next = myIterator.next(); if (next < myMin) { myMin = next; } } return (int) myMin; } @Override public long count() { isEmpty(); return reduce(0, (count, x) -> count + 1); } @Override public Integer sum() { isEmpty(); return reduce(0, Integer::sum); } @Override public IntStream filter(IntPredicate predicate) { return new AsIntStream(new FilterIterator(myIterator, predicate)); } @Override public void forEach(IntConsumer action) { while (myIterator.hasNext()) { action.accept(myIterator.next()); } } @Override public IntStream map(IntUnaryOperator mapper) { return new AsIntStream(new MapIterator(myIterator, mapper)); } @Override public IntStream flatMap(IntToIntStreamFunction func) { return new AsIntStream(new FlatMapIterator(myIterator, func)); } @Override public int reduce(int identity, IntBinaryOperator op) { int res = identity; while (myIterator.hasNext()) { res = op.apply(res, myIterator.next()); } return res; } @Override public int[] toArray() { ArrayList<Integer> arr = new ArrayList<>(); while (myIterator.hasNext()) { arr.add(myIterator.next()); } int[] resArr = new int[arr.size()]; for (int i = 0; i < arr.size(); i++) { resArr[i] = arr.get(i); } return resArr; } }
package com.kingnode.gou.dto; import java.util.List; /** * @author 58120775@qq.com (chenchao) */ public class ShoppCommentDTO{ private Long productId;//商品id private String content;//心得 private String score;//评分 private String label;//标签 private List<ShoppCommentImgDTO> commentImgs; public Long getProductId(){ return productId; } public void setProductId(Long productId){ this.productId=productId; } public String getContent(){ return content; } public void setContent(String content){ this.content=content; } public String getScore(){ return score; } public void setScore(String score){ this.score=score; } public String getLabel(){ return label; } public void setLabel(String label){ this.label=label; } public List<ShoppCommentImgDTO> getCommentImgs(){ return commentImgs; } public void setCommentImgs(List<ShoppCommentImgDTO> commentImgs){ this.commentImgs=commentImgs; } }
package com.gustavoballeste.authlogin.detail; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.InputType; import android.widget.TextView; import android.widget.Toast; import com.afollestad.materialdialogs.MaterialDialog; import com.gustavoballeste.authlogin.R; import com.gustavoballeste.authlogin.data.model.User; import com.gustavoballeste.authlogin.login.LoginActivity; import butterknife.ButterKnife; import butterknife.BindView; import butterknife.OnClick; public class DetailActivity extends AppCompatActivity implements DetailIViewContract { private DetailPresenterContract presenter; private Toast toast; @BindView(R.id.first_name_text_view) TextView firstNameTv; @BindView(R.id.last_name_text_view) TextView lastNameTv; @BindView(R.id.password_text_view) TextView passwordTv; @OnClick(R.id.btn_logout) public void onClick() { presenter.logout(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); ButterKnife.bind(this); presenter = new DetailPresenter(this, this); presenter.startService(); } @Override public void updateScreen(User user) { firstNameTv.setText(user.getFirstName()); lastNameTv.setText(user.getLastName()); } @Override public void refreshData(TextView textView, String newValue, String message) { textView.setText(newValue); // toast = Toast.makeText(this, message, Toast.LENGTH_SHORT); // toast.show(); } @Override public void backLogin() { Intent intent = new Intent(DetailActivity.this, LoginActivity.class); startActivity(intent); finish(); } @OnClick(R.id.first_name_card_view) public void showFirstNameDialog() { new MaterialDialog.Builder(this) .title(R.string.first_name_dialog_title) .content(R.string.first_name_dialog_label) .inputType( InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_WORDS) .inputRange(2, 30) .positiveText(R.string.submit) .input( null, this.firstNameTv.getText(), false, (dialog, input) -> this.presenter.updateRemote(input.toString(), firstNameTv,"firstName")) .show(); } @OnClick(R.id.last_name_card_view) public void showLastNameDialog() { new MaterialDialog.Builder(this) .title(R.string.last_name_dialog_title) .content(R.string.last_name_dialog_label) .inputType( InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_WORDS) .inputRange(2, 30) .positiveText(R.string.submit) .input( null, this.lastNameTv.getText(), false, (dialog, input) -> this.presenter.updateRemote(input.toString(), lastNameTv,"lastName")) .show(); } @OnClick(R.id.password_card_view) public void showPasswordDialog() { new MaterialDialog.Builder(this) .title(R.string.password_dialog_title) .content(R.string.password_dialog_label) .inputType( InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PERSON_NAME | InputType.TYPE_TEXT_FLAG_CAP_WORDS) .inputRange(2, 30) .positiveText(R.string.submit) .input( null, this.passwordTv.getText(), false, (dialog, input) -> this.presenter.updateRemote(input.toString(), passwordTv,"password")) .show(); } }
/** * */ package com.application.utils; import org.json.JSONArray; import org.json.JSONObject; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.os.AsyncTask; import android.os.Build; import android.os.PowerManager; import com.application.sqlite.DBConstant; import com.squareup.okhttp.OkHttpClient; /** * @author Vikalp Patel(VikalpPatelCE) * */ public class FetchFeedActionAsyncTask extends AsyncTask<String, String, String> { private PowerManager.WakeLock mWakeLock; private String TAG; private JSONObject mJSONObject; private Context mContext; private String mCategory; private boolean isSuccess = false; OnPostExecuteFeedActionTaskListener onPostExecuteListener; public void setOnPostExecuteFeedActionTaskListener( OnPostExecuteFeedActionTaskListener onPostExecuteListener) { this.onPostExecuteListener = onPostExecuteListener; } public interface OnPostExecuteFeedActionTaskListener { public abstract void onPostExecute(String mReponseFromApi, boolean isSuccess); } public FetchFeedActionAsyncTask(Context mContext, String mCategory,JSONObject mJSONObject, String TAG) { this.TAG = TAG; this.mContext = mContext; this.mCategory = mCategory; this.mJSONObject = mJSONObject; } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); if (mContext != null) { acquirePowerLock(); } } /* * (non-Javadoc) * * @see android.os.AsyncTask#doInBackground(Params[]) */ @Override protected String doInBackground(String... arg0) { // TODO Auto-generated method stub String mResponseFromApi; try{ mResponseFromApi = RetroFitClient.postJSON(new OkHttpClient(), AppConstants.API.API_FETCH_FEED_ACTION, mJSONObject.toString(), TAG); updateActionsInDB(mResponseFromApi); return mResponseFromApi; }catch(Exception e){ mResponseFromApi = JSONRequestBuilder.getErrorMessageFromApi("mErrorMessage").toString(); return mResponseFromApi; } } @Override protected void onPostExecute(String mResponseFromApi) { // TODO Auto-generated method stub super.onPostExecute(mResponseFromApi); try { releasePowerLock(); if (onPostExecuteListener != null) { if (Utilities.isSuccessFromApi(mResponseFromApi)) { onPostExecuteListener.onPostExecute(mResponseFromApi, isSuccess); } } } catch (Exception e) { FileLog.e(TAG, e.toString()); } } @Override protected void onCancelled() { // TODO Auto-generated method stub super.onCancelled(); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override protected void onCancelled(String result) { // TODO Auto-generated method stub super.onCancelled(result); } /** * Update : Actions */ private void updateActionsInDB(String mResponseFromApi){ if(mCategory.equalsIgnoreCase(AppConstants.INTENTCONSTANTS.MOBCAST)){ updateActionsInMobcast(mResponseFromApi); }else if(mCategory.equalsIgnoreCase(AppConstants.INTENTCONSTANTS.TRAINING)){ updateActionsInTraining(mResponseFromApi); }else if(mCategory.equalsIgnoreCase(AppConstants.INTENTCONSTANTS.AWARD)){ updateActionsInAward(mResponseFromApi); }else if(mCategory.equalsIgnoreCase(AppConstants.INTENTCONSTANTS.EVENT)){ updateActionsInEvent(mResponseFromApi); } } /** * Update Mobcast : Actions -> Single Update : Use Transaction in replacement */ private void updateActionsInMobcast(String mResponseFromApi) { try { ContentResolver mContentResolver = mContext.getContentResolver(); JSONObject mJSONMobcastObj = new JSONObject(mResponseFromApi); JSONArray mJSONMobcastArray = mJSONMobcastObj.getJSONArray(AppConstants.API_KEY_PARAMETER.mobcast); for(int i = 0 ; i < mJSONMobcastArray.length();i++){ JSONObject mJSONMobObj = mJSONMobcastArray.getJSONObject(i); ContentValues mValues = new ContentValues(); mValues.put(DBConstant.Mobcast_Columns.COLUMN_MOBCAST_LIKE_NO, mJSONMobObj.getString(AppConstants.API_KEY_PARAMETER.mobcastLikeCount)); mValues.put(DBConstant.Mobcast_Columns.COLUMN_MOBCAST_VIEWCOUNT, mJSONMobObj.getString(AppConstants.API_KEY_PARAMETER.mobcastViewCount)); mContentResolver.update(DBConstant.Mobcast_Columns.CONTENT_URI, mValues, DBConstant.Mobcast_Columns.COLUMN_MOBCAST_ID + "=?", new String[]{mJSONMobObj.getString(AppConstants.API_KEY_PARAMETER.mobcastId)}); } isSuccess = true; } catch (Exception e) { FileLog.e(TAG, e.toString()); } } private void updateActionsInTraining(String mResponseFromApi) { try { ContentResolver mContentResolver = mContext.getContentResolver(); JSONObject mJSONTrainingObj = new JSONObject(mResponseFromApi); JSONArray mJSONTrainingArray = mJSONTrainingObj.getJSONArray(AppConstants.API_KEY_PARAMETER.training); for(int i = 0 ; i < mJSONTrainingArray.length();i++){ JSONObject mJSONMobObj = mJSONTrainingArray.getJSONObject(i); ContentValues mValues = new ContentValues(); mValues.put(DBConstant.Training_Columns.COLUMN_TRAINING_LIKE_NO, mJSONMobObj.getString(AppConstants.API_KEY_PARAMETER.trainingLikeCount)); mValues.put(DBConstant.Training_Columns.COLUMN_TRAINING_VIEWCOUNT, mJSONMobObj.getString(AppConstants.API_KEY_PARAMETER.trainingViewCount)); mContentResolver.update(DBConstant.Training_Columns.CONTENT_URI, mValues, DBConstant.Training_Columns.COLUMN_TRAINING_ID + "=?", new String[]{mJSONMobObj.getString(AppConstants.API_KEY_PARAMETER.trainingId)}); } isSuccess = true; } catch (Exception e) { FileLog.e(TAG, e.toString()); } } private void updateActionsInEvent(String mResponseFromApi) { try { ContentResolver mContentResolver = mContext.getContentResolver(); JSONObject mJSONEventObj = new JSONObject(mResponseFromApi); JSONArray mJSONEventArray = mJSONEventObj.getJSONArray(AppConstants.API_KEY_PARAMETER.event); for(int i = 0 ; i < mJSONEventArray.length();i++){ JSONObject mJSONMobObj = mJSONEventArray.getJSONObject(i); ContentValues mValues = new ContentValues(); mValues.put(DBConstant.Event_Columns.COLUMN_EVENT_LIKE_NO, mJSONMobObj.getString(AppConstants.API_KEY_PARAMETER.eventLikeCount)); mValues.put(DBConstant.Event_Columns.COLUMN_EVENT_READ_NO, mJSONMobObj.getString(AppConstants.API_KEY_PARAMETER.eventViewCount)); mValues.put(DBConstant.Event_Columns.COLUMN_EVENT_INVITED_NO, mJSONMobObj.getString(AppConstants.API_KEY_PARAMETER.eventInvitedCount)); mValues.put(DBConstant.Event_Columns.COLUMN_EVENT_GOING_NO, mJSONMobObj.getString(AppConstants.API_KEY_PARAMETER.eventGoingCount)); mContentResolver.update(DBConstant.Event_Columns.CONTENT_URI, mValues, DBConstant.Event_Columns.COLUMN_EVENT_ID + "=?", new String[]{mJSONMobObj.getString(AppConstants.API_KEY_PARAMETER.eventId)}); } isSuccess = true; } catch (Exception e) { FileLog.e(TAG, e.toString()); } } private void updateActionsInAward(String mResponseFromApi) { try { ContentResolver mContentResolver = mContext.getContentResolver(); JSONObject mJSONAwardObj = new JSONObject(mResponseFromApi); JSONArray mJSONAwardArray = mJSONAwardObj.getJSONArray(AppConstants.API_KEY_PARAMETER.award); for(int i = 0 ; i < mJSONAwardArray.length();i++){ JSONObject mJSONMobObj = mJSONAwardArray.getJSONObject(i); ContentValues mValues = new ContentValues(); mValues.put(DBConstant.Award_Columns.COLUMN_AWARD_LIKE_NO, mJSONMobObj.getString(AppConstants.API_KEY_PARAMETER.awardLikeCount)); mValues.put(DBConstant.Award_Columns.COLUMN_AWARD_READ_NO, mJSONMobObj.getString(AppConstants.API_KEY_PARAMETER.awardViewCount)); mValues.put(DBConstant.Award_Columns.COLUMN_AWARD_CONGRATULATE_NO, mJSONMobObj.getString(AppConstants.API_KEY_PARAMETER.awardCongratulatedCount)); mContentResolver.update(DBConstant.Award_Columns.CONTENT_URI, mValues, DBConstant.Award_Columns.COLUMN_AWARD_ID + "=?", new String[]{mJSONMobObj.getString(AppConstants.API_KEY_PARAMETER.awardId)}); } isSuccess = true; } catch (Exception e) { FileLog.e(TAG, e.toString()); } } /** * Power Lock */ @SuppressLint("Wakelock") private void acquirePowerLock() { try { PowerManager pm = (PowerManager) mContext .getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName()); mWakeLock.acquire(); } catch (Exception e) { FileLog.e(TAG, e.toString()); } } private void releasePowerLock() { try { mWakeLock.release(); mWakeLock = null; } catch (Exception e) { } } }
package com.ngocdt.tttn.entity; import javax.persistence.*; import lombok.Getter; import lombok.Setter; @Entity @Table(name = "Account") @Getter @Setter public class Account { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column private int accountID; @Column(unique = true) private String email; @Column private String password; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "employeeID") private Employee employee; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "customerID") private Customer customer; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "roleID", nullable = false) private Role role; public int getAccountID() { return accountID; } public void setAccountID(int accountID) { this.accountID = accountID; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Employee getEmployee() { return employee; } public void setEmployee(Employee employee) { this.employee = employee; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } }
package com.ece590.dropbox; import com.amazonaws.util.json.JSONObject; import com.mongodb.MongoClient; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import java.util.UUID; /**This class contains the operation on AWSS3 such as authentication, adding and deleting bucket for users, uploading * and downloading files. * Created by JerryCheung on 3/27/16. */ public class UserManagement { private static final String HOST = "54.210.164.65"; private static final int PORT = 27017; private static final String EMAIL = "email"; private static final String USERNAME = "username"; private static final String PASSWORD = "password"; private static final String DB_EMAIL_PASSWORD = "db_email_password"; //private static final String DB_EMAIL_PASSWORD = "db_email_password_test"; private static final String DB_META = "db_meta"; //private static final String DB_META = "db_meta_test"; private static final String COLLECTION_EMAIL_PASSWORD_PAIR = "collection_email_password_pair"; private static final String COLLECTION_USAGE = "collection_usage"; private static final String MSG = "message"; private static final String SUCC = "success"; private static final String FAIL = "fail"; private static final String FIRSTNAME = "firstname"; private static final String LASTNAME = "lastname"; private static final String BUCKETNAME = "bucketname"; private static final String CURUSAGE = "currentusage"; private static final String LIMIT = "limit"; private static final String DB_TEST = "db_test"; private static final String COLLECTION_TEST = "collection_test"; /* public static void main(String[] args) { String firstname1 = "Jianyu1"; String lastname1 = "Zhang"; String password1 = "123456"; String email1 = "foo1@example.com"; String res = UserManagement.addNewUser(firstname1, lastname1, password1, email1); System.out.println(res + ""); System.out.println("The bucket name is" + getBucket(email1)); String firstname2 = "Jianyu2"; String lastname2 = "Zhang"; String password2 = "123456"; String email2 = "foo2@example.com"; JSONObject res2 = UserManagement.addNewUser(firstname2, lastname2, password2, email2); System.out.println(res2 + ""); System.out.println("The bucket name is" + getBucket(email2)); String firstname3 = "Jianyu3"; String lastname3 = "Zhang"; String password3 = "123456"; String email3 = "foo3@example.com"; JSONObject res3 = UserManagement.addNewUser(firstname3, lastname3, password3, email3); System.out.println(res3 + ""); System.out.println("The bucket name is" + getBucket(email3)); MongoClient mongoClient = new MongoClient(HOST, PORT); MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_EMAIL_PASSWORD); MongoCollection collection = mongoDatabase.getCollection(COLLECTION_EMAIL_PASSWORD_PAIR); String tmp = "Zhang"; Document queryObject = new Document(LASTNAME, tmp); FindIterable<Document> searchRes = collection.find(queryObject); for (Document doc : searchRes) { System.out.println("" + doc); } } */ public static void main(String[] args) { String res = UserManagement.addNewUser("Jianyu", "Zhang", "testemail", "123456"); System.out.println(res + ""); } /** * Just for test * @return */ public static String testGreeting() { return "This is the test function in UserManagement class"; } /** * Just for testing whether the tomcat server can connect to the database * @param firstname * @param lastname * @return */ public static String addTestObj(String firstname, String lastname) { MongoClient mongoClient = new MongoClient(HOST, PORT); MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_TEST); MongoCollection mongoCollection = mongoDatabase.getCollection(COLLECTION_TEST); Document doc = new Document("firstname", firstname).append("lastname", lastname); mongoCollection.insertOne(doc); return SUCC; } /** * authenticate user based on the provided email and password */ public static JSONObject authenticate(String email, String password) { System.out.println("in authenticate(String, String)"); JSONObject tuple = new JSONObject(); JSONObject res = null; try { tuple.put(EMAIL, email); tuple.put(PASSWORD, password); res = authenticate(tuple); } catch (Exception e) { e.printStackTrace(); } return res; } /** * authenticate user based on the provided JSONObject */ private static JSONObject authenticate(JSONObject tuple) throws Exception{ JSONObject res = new JSONObject(); String savedPassword = null; System.out.println("------in authenticate(JSONObject)"); MongoClient mongoClient = new MongoClient(HOST, PORT); MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_EMAIL_PASSWORD); MongoCollection collection = mongoDatabase.getCollection(COLLECTION_EMAIL_PASSWORD_PAIR); //BasicDBObject queryObject = new BasicDBObject(); //queryObject.put(USERNAME, tuple.get(USERNAME)); Document queryObject = new Document(EMAIL, tuple.get(EMAIL)); FindIterable<Document> searchRes = collection.find(queryObject); for (Document document : searchRes) { savedPassword = document.getString(PASSWORD); System.out.println("Saved password = " + savedPassword); } if (tuple.getString(PASSWORD).equals(savedPassword)) { res.put(MSG, SUCC); } else { res.put(MSG, FAIL); } return res; } /** * add new user based on provided firstname, lastname, email */ public static String addNewUser(String firstname, String lastname, String password, String email) { JSONObject res = null; String bucketname = lastname.toLowerCase() + UUID.randomUUID().toString(); //BucketMaking bucketMaking = new BucketMaking(); //bucketMaking.createNewBucket(lastname + UUID.randomUUID().toString()); System.out.println("---------in addNewUser(String, String, String)"); JSONObject userInfo = new JSONObject(); try { userInfo.put(FIRSTNAME, firstname); userInfo.put(LASTNAME, lastname); userInfo.put(PASSWORD, password); userInfo.put(EMAIL, email); userInfo.put(BUCKETNAME, bucketname); res = addNewUser(userInfo); AwsOperation.createBucket(bucketname); } catch (Exception e) { e.printStackTrace(); return "Exception in addNewUser"; } return res.toString(); } /** * insert the new user info into the database * @param userInfo * @return JSONObject containing success or fail message * @throws Exception */ private static JSONObject addNewUser(JSONObject userInfo) throws Exception { JSONObject res = new JSONObject(); boolean isExisted = false; Document newUserDoc = new Document(FIRSTNAME, userInfo.getString(FIRSTNAME)).append(LASTNAME, userInfo.getString(LASTNAME)) .append(PASSWORD, userInfo.getString(PASSWORD)).append(EMAIL, userInfo.getString(EMAIL)) .append(BUCKETNAME, userInfo.getString(BUCKETNAME)); MongoClient mongoClient = new MongoClient(HOST, PORT); MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_EMAIL_PASSWORD); MongoCollection mongoCollection = mongoDatabase.getCollection(COLLECTION_EMAIL_PASSWORD_PAIR); Document queryObject = new Document(EMAIL, userInfo.get(EMAIL)); FindIterable<Document> searchRes = mongoCollection.find(queryObject); for (Document document : searchRes) { if ((document.getString(EMAIL)).equals(userInfo.getString(EMAIL))) { isExisted = true; } } if (isExisted) { res.put(MSG, SUCC); } else { Double curUsage = new Double(0.0); Double limit = new Double(1024.0); mongoCollection.insertOne(newUserDoc); mongoDatabase = mongoClient.getDatabase(DB_META); mongoCollection = mongoDatabase.getCollection(COLLECTION_USAGE); Document newDoc = new Document(EMAIL, userInfo.getString(EMAIL)).append(CURUSAGE, curUsage).append(LIMIT, limit); mongoCollection.insertOne(newDoc); //send email to the user //AmazonSESSample aSES=new AmazonSESSample(); //String response=aSES.sendRegisterMail(user.getString("firstname"),user.getString("email"),password); res.put(MSG, SUCC); } return res; } /** * get the name of the bucket assocaited with the given email */ public static String getBucket(String email) { String res = null; System.out.println("---------in getBucket(String)"); try { MongoClient mongoClient = new MongoClient(HOST, PORT); MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_EMAIL_PASSWORD); MongoCollection mongoCollection = mongoDatabase.getCollection(COLLECTION_EMAIL_PASSWORD_PAIR); Document queryObject = new Document(EMAIL, email); FindIterable<Document> searchRes = mongoCollection.find(queryObject); for (Document document : searchRes) { res = document.getString(BUCKETNAME); } } catch (Exception e) { e.printStackTrace(); } return res; } }
package com.mardyoe.multiplelayoutrecyclerview.controller.entity; /** * Created by TVA INTERN 02 on 22/6/2017. */ public class Information { private String message; private String time; public Information(String message, String time) { this.message = message; this.time = time; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } }
public class Strings1{ public static void main(String[] args){ String texto="Hola mundo"; System.out.println(texto); texto = new String(); System.out.println(texto); texto = new String("Hola"); System.out.println(texto); String texto2 = "Hola mundo",temp; System.out.println(texto2.toUpperCase()); for (int i=0;i<texto2.length() ;i++ ) { temp = ""+texto2.charAt(i); System.out.println(temp); } } }
package uk.ac.ebi.intact.view.webapp.controller; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import uk.ac.ebi.intact.core.context.IntactContext; import uk.ac.ebi.intact.core.persistence.dao.DaoFactory; /** * Abstract controller giving access to IntAct database access via JPA. * * @author Bruno Aranda (baranda@ebi.ac.uk) * @version $Id$ */ public abstract class JpaBaseController extends BaseController { private static final Log log = LogFactory.getLog( JpaBaseController.class ); IntactContext intactContext; @Autowired private DaoFactory daoFactory; protected DaoFactory getDaoFactory() { return this.daoFactory; } protected IntactContext getIntactContext() { if (intactContext == null){ intactContext = IntactContext.getCurrentInstance(); } return intactContext; } }
package com.esum.framework.core.management.admin; import java.io.FileNotFoundException; import java.io.IOException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import javax.management.MBeanServerConnection; import javax.management.MBeanServerInvocationHandler; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import javax.management.remote.JMXConnector; import org.apache.commons.collections.OrderedMap; import org.apache.commons.collections.map.ListOrderedMap; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.framework.FrameworkSystemVariables; import com.esum.framework.common.util.NetworkUtil; import com.esum.framework.common.util.SequenceProperties; import com.esum.framework.core.component.ComponentConstants; import com.esum.framework.core.component.ComponentException; import com.esum.framework.core.component.ComponentManagerFactory; import com.esum.framework.core.component.ComponentStatus; import com.esum.framework.core.component.table.InfoTable; import com.esum.framework.core.config.Configurator; import com.esum.framework.core.event.message.MessageEvent; import com.esum.framework.core.exception.SystemException; import com.esum.framework.core.management.ManagementConstants; import com.esum.framework.core.management.ManagementException; import com.esum.framework.core.management.mbean.component.ComponentControlMBean; import com.esum.framework.core.management.mbean.hotdeploy.HotDeployControlMBean; import com.esum.framework.core.management.mbean.message.MessageControlMBean; import com.esum.framework.core.management.mbean.queue.QueueControlMBean; import com.esum.framework.core.management.mbean.queue.QueueStatus; import com.esum.framework.core.management.mbean.security.SecurityControlMBean; import com.esum.framework.core.management.mbean.system.LogControlMBean; import com.esum.framework.core.node.table.NodeInfo; import com.esum.framework.jmx.JmxClientTemplate; import com.esum.framework.jmx.MBeanQueryCreator; public class XTrusAdmin { private static Logger log = LoggerFactory.getLogger(XTrusAdmin.class); private String traceId; private String ipAddr; private int port = ManagementConstants.DEFAULT_MANAGER_PORT; private String nodeId; public static synchronized XTrusAdmin newInstance(String nodeId) throws ManagementException { try { boolean isAgent = System.getProperty(FrameworkSystemVariables.NODE_TYPE, ComponentConstants.LOCATION_TYPE_MAIN).equals(ComponentConstants.LOCATION_TYPE_SUB); if(isAgent) { log.info("Creating XtrusAdmin for '"+nodeId+"' AGENT NODE."); return new XTrusAdmin(nodeId, Configurator.getInstance().getString("agent.ip"), Configurator.getInstance().getInt("agent.port")); } else { log.info("Creating XtrusAdmin for '"+nodeId+"' MAIN NODE."); NodeInfo nodeInfo = ComponentManagerFactory.getInstance().getComponentManager(nodeId).getNodeInfo(nodeId); if(nodeInfo!=null) return new XTrusAdmin(nodeInfo); else throw new ManagementException("newInstance()", "Can not found node info. nodeId : "+nodeId); } } catch (ManagementException e) { throw e; } catch (Exception e) { log.error("Can not create XtrusAdmin instance.", e); throw new ManagementException("newInstance()", e.getMessage(), e); } } public XTrusAdmin(NodeInfo nodeInfo) throws UnknownHostException { this.nodeId = nodeInfo.getNodeId(); this.port = nodeInfo.getPort(); List<String> hostAddrList = NetworkUtil.getHostAddressList(nodeInfo.getHostName()); this.ipAddr = hostAddrList.get(0); this.traceId = "["+nodeId+"] "; log.debug(traceId+"New XtrusAdmin. nodeId : "+nodeId+", ip : "+ipAddr+", port : "+port); } public XTrusAdmin(String nodeId, String hostname, int port) throws UnknownHostException { this.nodeId = nodeId; this.port = port; List<String> hostAddrList = NetworkUtil.getHostAddressList(hostname); this.ipAddr = hostAddrList.get(0); this.traceId = "["+nodeId+"] "; log.debug(traceId+"New XtrusAdmin. nodeId : "+nodeId+", hostname : "+hostname+", port : "+port); } private JmxClientTemplate createJmxClient() throws ManagementException { return JmxClientTemplate.createJmxClient(ipAddr, port); } private void closeJmxConnector(JMXConnector jmxConnector) { if(jmxConnector!=null) { try { jmxConnector.close(); } catch (IOException e) { } jmxConnector = null; } } public JMXConnector connect() throws ManagementException { JmxClientTemplate jmxClient = createJmxClient(); return jmxClient.getJmxConnector(); } public void startupComponent(String componentId) throws ManagementException { JmxClientTemplate jmxClient = null; try { jmxClient = createJmxClient(); ComponentControlMBean cc = jmxClient.query(ManagementConstants.OBJECT_NAME_COMPONENT_CONTROL, ComponentControlMBean.class); log.info(traceId+"Starting " + componentId + " component..."); cc.startup(componentId); log.info(traceId+"Started " + componentId + " component."); } catch (ManagementException e) { throw e; } catch (SystemException e) { throw new ManagementException("startupComponent()", e.getMessage(), e); } catch (Exception e) { throw new ManagementException("startupComponent()", e.getMessage(), e); } finally { if(jmxClient!=null) jmxClient.close(); } } public void shutdownComponent(String componentId) throws ManagementException { JmxClientTemplate jmxClient = null; try { jmxClient = createJmxClient(); ComponentControlMBean cc = jmxClient.query(ManagementConstants.OBJECT_NAME_COMPONENT_CONTROL, ComponentControlMBean.class); log.info(traceId+"Shutdowning " + componentId + " component..."); cc.shutdown(componentId); log.info(traceId+"Shutdowned " + componentId + " component."); } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("shutdownComponent()", e.getMessage(), e); } finally { if(jmxClient!=null) jmxClient.close(); } } public void reloadComponent(String componentId, String[] ids, boolean channel, boolean etc) throws ManagementException { JmxClientTemplate jmxClient = null; try { jmxClient = createJmxClient(); ComponentControlMBean cc = jmxClient.query(ManagementConstants.OBJECT_NAME_COMPONENT_CONTROL, ComponentControlMBean.class); log.info(traceId+"Reloading " + componentId + " component..."); cc.reload(componentId, ids, channel, etc); log.info(traceId+"Reloaded " + componentId + " component."); } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("reloadComponent()", e.getMessage(), e); } finally { if(jmxClient!=null) jmxClient.close(); } } public void reprocessComponent(String componentId, MessageEvent repEvent) throws ManagementException { JmxClientTemplate jmxClient = null; try { jmxClient = createJmxClient(); ComponentControlMBean cc = jmxClient.query(ManagementConstants.OBJECT_NAME_COMPONENT_CONTROL, ComponentControlMBean.class); log.info(traceId+"Reprocessing " + componentId + " component..."); cc.reprocess(componentId, repEvent); log.info(traceId+"Reprocessing " + componentId + " component."); } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("reprocessComponent()", e.getMessage(), e); } finally { if(jmxClient!=null) jmxClient.close(); } } public String getComponentStatus(String componentId) throws ManagementException { JmxClientTemplate jmxClient = null; try { jmxClient = createJmxClient(); ComponentControlMBean cc = jmxClient.query(ManagementConstants.OBJECT_NAME_COMPONENT_CONTROL, ComponentControlMBean.class); log.info(traceId+"Retrieving " + componentId + " Status..."); return cc.getStatus(this.nodeId, componentId); } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("getComponentStatus()", e.getMessage(), e); } finally { if(jmxClient!=null) jmxClient.close(); } } public List<ComponentStatus> getComponentListStatus() throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_COMPONENT_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, ComponentControlMBean.class, true); ComponentControlMBean componentControlMBean = (ComponentControlMBean)object; log.info(traceId+"Retrieving Component List Status..."); return componentControlMBean.getComponentListStatus(); } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("getComponentListStatus()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } @SuppressWarnings("unchecked") public OrderedMap getQueueStatusList() throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName compObjName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_COMPONENT_CONTROL); Object compControl = MBeanServerInvocationHandler.newProxyInstance(connection, compObjName, ComponentControlMBean.class, true); ComponentControlMBean componentControlMBean = (ComponentControlMBean)compControl; List<ComponentStatus> compStatusMap = componentControlMBean.getComponentListStatus(); ObjectName queueControlName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_QUEUE_CONTROL); Object queueControl = MBeanServerInvocationHandler.newProxyInstance(connection, queueControlName, QueueControlMBean.class, true); QueueControlMBean queueControlMBean = (QueueControlMBean)queueControl; if(log.isDebugEnabled()) log.debug(traceId+"Retrieving Queue Status List..."); OrderedMap retMap = new ListOrderedMap(); retMap.putAll(getQueueStatusByCompId(compStatusMap, "SYS", queueControlMBean)); retMap.putAll(getQueueStatusByCompId(compStatusMap, "VAS", queueControlMBean)); retMap.putAll(getQueueStatusByCompId(compStatusMap, "COM", queueControlMBean)); return retMap; } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("getQueueStatusList()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } private OrderedMap getQueueStatusByCompId(List<ComponentStatus> compStatusList, String category, QueueControlMBean queueControlMBean) { OrderedMap retMap = new ListOrderedMap(); Iterator<ComponentStatus> i = compStatusList.iterator(); while(i.hasNext()) { ComponentStatus compStatus = i.next(); if(!compStatus.getCategory().equals(category)) continue; List<QueueStatus> queueStatusList = queueControlMBean.getQueueStatusList(compStatus.getNodeId(), compStatus.getCompId()); if(queueStatusList==null) { queueStatusList = new ArrayList<QueueStatus>(); } else { // 채널은 node에 설정된 component가 공유한다. 즉 여러개의 node에 동일 컴포넌트가 구동될 수 있기때문에 // Queue 기준으로 해당되는 컴포넌트를 put한다.(컴포넌트 기준이 아닌 채널 이름 기준) for(QueueStatus q : queueStatusList) q.putComponentStatus(compStatus.getNodeId(), compStatus); } if(retMap.containsKey(compStatus.getCompId())) { List<QueueStatus> qList = (List<QueueStatus>)retMap.get(compStatus.getCompId()); for(QueueStatus q : qList) q.putComponentStatus(compStatus.getNodeId(), compStatus); } else { retMap.put(compStatus.getCompId(), queueStatusList); } } return retMap; } /** * 특정 Queue들에 대한 상태 정보를 검색하여 리턴한다. */ public List<QueueStatus> getQueueStatusAt(List<String> queueNames) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName queueControlName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_QUEUE_CONTROL); Object queueControl = MBeanServerInvocationHandler.newProxyInstance(connection, queueControlName, QueueControlMBean.class, true); QueueControlMBean queueControlMBean = (QueueControlMBean)queueControl; if(log.isDebugEnabled()) log.debug(traceId+"Retrieving Queue Status..."); return queueControlMBean.getQueueStatusAt(queueNames); } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("getQueueStatusAt()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } public <T> T query(MBeanQueryCreator<T> queryCreator) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); if(queryCreator!=null) return (T)queryCreator.executeQuery(connection); } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("query()", e.getMessage(), e); } finally { closeJmxConnector(connector); } return null; } public boolean purgeQueue(String queueName) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_QUEUE_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, QueueControlMBean.class, true); QueueControlMBean queueControlMBean = (QueueControlMBean)object; log.info(traceId+"Purging " + queueName + " Queue..."); return queueControlMBean.purgeQueue(queueName); } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("purgeQueue()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } public boolean createQueue(String queueName, boolean durable) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_QUEUE_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, QueueControlMBean.class, true); QueueControlMBean queueControlMBean = (QueueControlMBean)object; log.info(traceId+"Creating " + queueName + " Queue..."); return queueControlMBean.createQueue(queueName, durable); } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("createQueue()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } public boolean destoryQueue(String queueName) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_QUEUE_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, QueueControlMBean.class, true); QueueControlMBean queueControlMBean = (QueueControlMBean)object; log.info(traceId+"Destorying " + queueName + " Queue..."); return queueControlMBean.destoryQueue(queueName); } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("destoryQueue()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } public List<Map<String, String>> viewQueue(String queueName) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_QUEUE_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, QueueControlMBean.class, true); QueueControlMBean queueControlMBean = (QueueControlMBean)object; log.info(traceId+"View message in " + queueName + " Queue..."); return queueControlMBean.listMessage(queueName); } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("purgeQueue()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } public Map<String, String> removeMessage(String queueName, String messageId) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_QUEUE_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, QueueControlMBean.class, true); QueueControlMBean queueControlMBean = (QueueControlMBean)object; log.info(traceId+"Removing "+messageId+" message in " + queueName + " Queue..."); boolean removed = queueControlMBean.removeMessage(queueName, messageId); Map<String, String> map = new HashMap<String, String>(); map.put(ManagementConstants.STATUS_KEY, removed?ManagementConstants.STATUS_VALUE_PASS:ManagementConstants.STATUS_VALUE_PASS); return map; } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("purgeQueue()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("removeMessage()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } public Map<String, Object> getMessage(String fileLocation) throws ManagementException { return getMessage(fileLocation, null); } public Map<String, Object> getMessage(String fileLocation, String encoding) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_MESSAGE_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, MessageControlMBean.class, true); MessageControlMBean messageControlMBean = (MessageControlMBean)object; log.info(traceId+"Reading " + fileLocation + " file..."); if (StringUtils.isEmpty(encoding)) { return messageControlMBean.getMessage(fileLocation); } else { return messageControlMBean.getMessage(fileLocation, encoding); } } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("getMessage()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("getMessage()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } public Map<String, String> processMessageReProcess(List msgCtrlIdList) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_MESSAGE_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, MessageControlMBean.class, true); MessageControlMBean messageControlMBean = (MessageControlMBean)object; log.info(traceId+"Processing Message ReProcess... Message Count: " + msgCtrlIdList.size()); return messageControlMBean.processMessageReProcess(msgCtrlIdList); } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("processMessageReProcess()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("processMessageReProcess()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } public Map<String, String> processMessageReSend(List msgCtrlIdList) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_MESSAGE_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, MessageControlMBean.class, true); MessageControlMBean messageControlMBean = (MessageControlMBean)object; log.info(traceId+"Processing Message ReProcess... Message Count: " + msgCtrlIdList.size()); return messageControlMBean.processMessageReSend(msgCtrlIdList); } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("processMessageReProcess()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("processMessageReProcess()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } public Map<String, String> processNotifyReSend(List<String> msgCtrlIdList) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_MESSAGE_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, MessageControlMBean.class, true); MessageControlMBean messageControlMBean = (MessageControlMBean)object; log.info(traceId+"Processing Notify Resending... Message Count: " + msgCtrlIdList.size()); return messageControlMBean.processNotifyReSend(msgCtrlIdList); } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("processMessageReProcess()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("processMessageReProcess()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } public Map<String, String> processDocumentReProcess(List msgCtrlIdList, List docSeqList) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_MESSAGE_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, MessageControlMBean.class, true); MessageControlMBean messageControlMBean = (MessageControlMBean)object; log.info(traceId+"Processing Document ReSend... Document Count: " + docSeqList.size()); return messageControlMBean.processDocumentReProcess(msgCtrlIdList, docSeqList); } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("processDocumentReSend()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("processDocumentReSend()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } public void reloadInfoRecord(String infoTableId, String[] ids) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_COMPONENT_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, ComponentControlMBean.class, true); ComponentControlMBean componentControlMBean = (ComponentControlMBean)object; if(ids!=null) log.debug(traceId+"Reloading InfoRecord.. TableId: " + infoTableId + ", IDs: " + InfoTable.marshalIds(ids)); else log.debug(traceId+"Reloading InfoRecord.. TableId: " + infoTableId); componentControlMBean.reloadInfoRecord(infoTableId, ids); } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("reloadInfoRecord()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("reloadInfoRecord()", e.getMessage(), e); } catch (ComponentException e) { throw new ManagementException("reloadInfoRecord()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } public String getProperty(String componentId, String key) throws ManagementException { return this.getComponentProperty(componentId, key); } public String getComponentProperty(String componentId, String key) throws ManagementException { String value = null; JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_COMPONENT_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, ComponentControlMBean.class, true); ComponentControlMBean componentControlMBean = (ComponentControlMBean)object; value = componentControlMBean.getComponentProperty(componentId, key); } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("getComponentProperty()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("getComponentProperty()", e.getMessage(), e); } catch (ComponentException e) { throw new ManagementException("getComponentProperty()", e.getMessage(), e); } finally { closeJmxConnector(connector); } return value; } /** * Xtrus시스템의 Configuration정보를 가져온다. * Config정보는 상대경로로 xtrus.home을 제외한 나머지 경로를 입력해야 한다. * * @param relatedConfigPath * @return * @throws ManagementException */ public SequenceProperties getConfigProperties(String relatedConfigPath) throws ManagementException { SequenceProperties config = null; JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_COMPONENT_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, ComponentControlMBean.class, true); ComponentControlMBean componentControlMBean = (ComponentControlMBean)object; config = componentControlMBean.getConfigProperties(relatedConfigPath); } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("getConfigProperties()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("getConfigProperties()", e.getMessage(), e); } catch (ComponentException e) { throw new ManagementException("getConfigProperties()", e.getMessage(), e); } finally { closeJmxConnector(connector); } return config; } public SequenceProperties getSSLSequencePropertiesConfig(String path) throws SystemException { SequenceProperties config = null; JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_SECURITY_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, SecurityControlMBean.class, true); SecurityControlMBean securityControlMBean = (SecurityControlMBean)object; config = securityControlMBean.getSSLSequencePropertiesConfig(this.getNodeId(), path); } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("getSSLSequencePropertiesConfig()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("getSSLSequencePropertiesConfig()", e.getMessage(), e); } catch (SystemException e) { throw e; } finally { closeJmxConnector(connector); } return config; } public String replacePropertyToValue(String nodeId, String path) throws SystemException { String returnVal = ""; JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_SECURITY_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, SecurityControlMBean.class, true); SecurityControlMBean securityControlMBean = (SecurityControlMBean)object; if(nodeId==null) nodeId = this.getNodeId(); returnVal = securityControlMBean.replacePropertyToValue(nodeId, path); } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("replacePropertyToValue()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("replacePropertyToValue()", e.getMessage(), e); } catch (SystemException e) { throw e; } finally { closeJmxConnector(connector); } return returnVal; } public void loadAllStore(String path1, char[] bytes1, String type1, String path2, char[] bytes2, String type2) throws SystemException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_SECURITY_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, SecurityControlMBean.class, true); SecurityControlMBean securityControlMBean = (SecurityControlMBean)object; securityControlMBean.loadAllStore(this.getNodeId(), path1, bytes1, type1, path2, bytes2, type2); } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("loadAllStore()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("loadAllStore()", e.getMessage(), e); } catch (SystemException e) { throw e; } finally { closeJmxConnector(connector); } } public Map<String, Vector<String>> getStoreValueList(String alias, int startIdx, int endIdx) throws SystemException { Map<String, Vector<String>> map = null; JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_SECURITY_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, SecurityControlMBean.class, true); SecurityControlMBean securityControlMBean = (SecurityControlMBean)object; map = securityControlMBean.getStoreValueList(this.getNodeId(), alias, startIdx, endIdx); } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("getStoreValueList()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("getStoreValueList()", e.getMessage(), e); } catch (SystemException e) { throw e; } finally { closeJmxConnector(connector); } return map; } public Map<String, String> getStoreValue(String alias)throws SystemException { Map<String, String> map = null; JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_SECURITY_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, SecurityControlMBean.class, true); SecurityControlMBean securityControlMBean = (SecurityControlMBean)object; map = securityControlMBean.getStoreValue(this.getNodeId(), alias); } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("getStoreValue()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("getStoreValue()", e.getMessage(), e); } catch (SystemException e) { throw e; } finally { closeJmxConnector(connector); } return map; } public void setSSLProperty(String key, String value, String path)throws SystemException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_SECURITY_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, SecurityControlMBean.class, true); SecurityControlMBean securityControlMBean = (SecurityControlMBean)object; securityControlMBean.setSSLProperty(this.getNodeId(), key, value, path); } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("setSSLProperty()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("setSSLProperty()", e.getMessage(), e); } catch (SystemException e) { throw e; } finally { closeJmxConnector(connector); } } public void loadTrustStore(String path, char[] bytes, String type)throws SystemException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_SECURITY_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, SecurityControlMBean.class, true); SecurityControlMBean securityControlMBean = (SecurityControlMBean)object; securityControlMBean.loadTrustStore(this.getNodeId(), path, bytes, type); } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("loadTrustStore()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("loadTrustStore()", e.getMessage(), e); } catch (SystemException e) { throw e; } finally { closeJmxConnector(connector); } } public void deleteEntry(String nodeId, String alias)throws SystemException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_SECURITY_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, SecurityControlMBean.class, true); SecurityControlMBean securityControlMBean = (SecurityControlMBean)object; securityControlMBean.deleteEntry(nodeId, alias); } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("deleteEntry()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("deleteEntry()", e.getMessage(), e); } catch (SystemException e) { throw e; } finally { closeJmxConnector(connector); } } public void loadKeyStore(String path, char[] bytes, String type)throws SystemException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_SECURITY_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, SecurityControlMBean.class, true); SecurityControlMBean securityControlMBean = (SecurityControlMBean)object; securityControlMBean.loadKeyStore(this.getNodeId(), path, bytes, type); } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("loadKeyStore()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("loadKeyStore()", e.getMessage(), e); } catch (SystemException e) { throw e; } finally { closeJmxConnector(connector); } } public void setCertificateEntry(String nodeId, byte[] items, String alias)throws SystemException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_SECURITY_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, SecurityControlMBean.class, true); SecurityControlMBean securityControlMBean = (SecurityControlMBean)object; securityControlMBean.setCertificateEntry(nodeId, items, alias); } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("setCertificateEntry()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("setCertificateEntry()", e.getMessage(), e); } catch (SystemException e) { throw e; } finally { closeJmxConnector(connector); } } public boolean isKeyEntry(String nodeid, String path, char[] bytes, String type, String alias) throws SystemException { boolean returnVal = false; JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_SECURITY_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, SecurityControlMBean.class, true); SecurityControlMBean securityControlMBean = (SecurityControlMBean)object; returnVal = securityControlMBean.isKeyEntry(nodeid, path, bytes, type, alias); } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("isKeyEntry()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("isKeyEntry()", e.getMessage(), e); } catch (SystemException e) { throw e; } finally { closeJmxConnector(connector); } return returnVal; } /** * 특정 nodeId에 대한 infoTableId에 해당되는 목록에서 특정 id들을 다시 로드한다. */ public void reloadSecurityInfo(String infoTableId, String[] ids) throws SystemException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_SECURITY_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, SecurityControlMBean.class, true); SecurityControlMBean securityControlMBean = (SecurityControlMBean)object; securityControlMBean.reloadSecurityInfo(infoTableId, ids); } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("reloadInfoRecord()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("reloadInfoRecord()", e.getMessage(), e); } catch (SystemException e) { throw e; } finally { closeJmxConnector(connector); } } public JMXConnector getJMXConnector() throws Exception { JMXConnector connector = null; try { connector = connect(); return connector; } catch (Exception e) { if(connector!=null) connector.close(); throw e; } } public Map<String, String> createCertificateStore(String nodeid, String keystoreType, String alias, String path, String password, String certPath) throws SystemException, FileNotFoundException, IOException { Map<String, String> returnVal = null; JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_SECURITY_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, SecurityControlMBean.class, true); SecurityControlMBean securityControlMBean = (SecurityControlMBean)object; returnVal = securityControlMBean.createCertificateStore(nodeid, keystoreType, alias, path, password, certPath); } catch (ManagementException e) { throw e; } catch (MalformedObjectNameException e) { throw new ManagementException("createCertificateStore()", e.getMessage(), e); } catch(SystemException se){ log.error(traceId+"createCertificateStore SystemException is Error Check!!"); throw se; } catch(FileNotFoundException fe){ log.error(traceId+"createCertificateStore FileNotFoundException is Error Check!!"); throw fe; } catch (IOException e) { throw new ManagementException("createCertificateStore()", e.getMessage(), e); } finally { closeJmxConnector(connector); } return returnVal; } // public List multiQueryForRemote(String query, List<String> params) throws SystemException { // JMXConnector connector = null; // MBeanServerConnection connection = null; // // try { // connector = connect(); // connection = connector.getMBeanServerConnection(); // // ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_STATUS_CONTROL); // Object object = MBeanServerInvocationHandler.newProxyInstance(connection, // objectName, StatusControlMBean.class, true); // StatusControlMBean statusControl = (StatusControlMBean)object; // // return statusControl.multiQueryForRemote(query, params); // } catch (ManagementException e) { // throw e; // } catch (MalformedObjectNameException e) { // throw new ManagementException("multiQueryForRemote()", e.getMessage(), e); // } catch (IOException e) { // throw new ManagementException("multiQueryForRemote()", e.getMessage(), e); // } finally { // closeJmxConnector(connector); // } // } // public Record singleQueryForRemote(String query, List<String> params) throws SystemException { // JMXConnector connector = null; // MBeanServerConnection connection = null; // // try { // connector = connect(); // connection = connector.getMBeanServerConnection(); // // ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_STATUS_CONTROL); // Object object = MBeanServerInvocationHandler.newProxyInstance(connection, // objectName, StatusControlMBean.class, true); // StatusControlMBean statusControl = (StatusControlMBean)object; // // return statusControl.singleQueryForRemote(query, params); // } catch (ManagementException e) { // throw e; // } catch (MalformedObjectNameException e) { // throw new ManagementException("singleQueryForRemote()", e.getMessage(), e); // } catch (IOException e) { // throw new ManagementException("singleQueryForRemote()", e.getMessage(), e); // } finally { // closeJmxConnector(connector); // } // } public String getNodeId() { return nodeId; } public Map<String, Object> readDocuments(List<String> msgCtrlIdList) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_MESSAGE_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, MessageControlMBean.class, true); MessageControlMBean messageControlMBean = (MessageControlMBean)object; log.info(traceId+"Processing Message ReProcess... Message Count: " + msgCtrlIdList.size()); return messageControlMBean.readDocuments(msgCtrlIdList); } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("processMessageReProcess()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("processMessageReProcess()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } /** * 특정 MessageCtrlId들에 대한 재전송 요청을 보내고 그 결과를 가져온다. */ public Map<String, String> resendResponse(List<String> msgCtrlIdList) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_MESSAGE_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, MessageControlMBean.class, true); MessageControlMBean messageControlMBean = (MessageControlMBean)object; log.info(traceId+"resendResponse... Message Count: " + msgCtrlIdList.size()); return messageControlMBean.resendResponse(msgCtrlIdList); } catch (ManagementException e) { throw e; } catch (IOException e) { throw new ManagementException("resendResponse()", e.getMessage(), e); } catch (MalformedObjectNameException e) { throw new ManagementException("resendResponse()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } /** * 특정 채널의 모든 데이터를 targetName의 채널로 옮긴다. */ public Map<String, String> moveMessage(String queueName, String targetName) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_QUEUE_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, QueueControlMBean.class, true); QueueControlMBean queueControlMBean = (QueueControlMBean)object; log.info(traceId+"Move Message form " + queueName + " to " + targetName); return queueControlMBean.moveMessage(queueName, targetName); } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("moveMessage()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } /** * 채널 Listener를 restart한다. */ public void restartQueueListener(String componentId, String channelName) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_COMPONENT_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, ComponentControlMBean.class, true); ComponentControlMBean componentControlMBean = (ComponentControlMBean)object; log.info(traceId+"Restart Queue Listener. Component Id : " + componentId+", Channel Name : " + channelName); componentControlMBean.restartListener(componentId, true, false, channelName); } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("restartQueueListener()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } /** * Set the log level for component. */ public void setLogLevel(String compId, String packageNames, String logLevel) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_LOG_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, LogControlMBean.class, true); LogControlMBean logControl = (LogControlMBean)object; log.info(traceId+"Set the logLevel to '"+packageNames+"'"); String[] pkgList = packageNames.split(","); for(String packageName : pkgList) { if(StringUtils.isEmpty(packageName)) continue; logControl.setLogLevel(compId, packageName, logLevel); } } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("setLogLevel()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } /** * Set the log level for system. */ public void setSystemLogLevel(String nodeId, String packageNames, String logLevel) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_LOG_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, LogControlMBean.class, true); LogControlMBean logControl = (LogControlMBean)object; log.info(traceId+"Set the logLevel to '"+packageNames+"'"); String[] pkgList = packageNames.split(","); for(String packageName : pkgList) { if(StringUtils.isEmpty(packageName)) continue; logControl.setSystemLogLevel(nodeId, packageName, logLevel); } } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("setSystemLogLevel()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } /** * 새로운 어플리케이션을 배포한다. * * @param nodeIDs 설치대상 노드 배열 * @param appName 어플리케이션 이름 * @param version 버전 * @param appFileName 어플리케이션 파일 이름 * @param fileData 어플리케이션 파일 데이터 * @param description 설명 * @return * @throws ManagementException */ public String deploy(String[] nodeIds, String appName, String version, String appFileName, byte[] fileData, String description) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_DEPLOY_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, HotDeployControlMBean.class, true); HotDeployControlMBean hotDeploy = (HotDeployControlMBean)object; log.info(traceId+"Deploy to '"+appName+"'"); return hotDeploy.deploy(nodeIds, appName, version, appFileName, fileData, description); } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("deploy()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } /** * 설치된 어플리케이션을 삭제한다, unZip된 어플리케이션 파일을 삭제한다. * @param appName 삭제대상 어플리케이션 아이디 * @param version 삭제대상 버전 * @return * @throws ManagementException */ public String delete(String appName, String version) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_DEPLOY_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, HotDeployControlMBean.class, true); HotDeployControlMBean hotDeploy = (HotDeployControlMBean)object; log.info(traceId+"Delete to '"+appName+"','"+version+"'"); return hotDeploy.delete(appName, version); } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("delete()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } /** * 어플리케이션을 ClassLoader에 등록한다. * @param appName 어플리케이션 아이디 * @param version 실행 대상 버전 * @param mode SAFETY, FORCED * @return * @throws ManagementException */ public String start(String appName, String version, String mode) throws ManagementException{ JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_DEPLOY_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, HotDeployControlMBean.class, true); HotDeployControlMBean hotDeploy = (HotDeployControlMBean)object; log.info(traceId+"Start '"+appName+"','"+version+"'"); return hotDeploy.start(appName, version, mode); } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("start()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } /** * 현재 시작(classLoading)된 어플리케이션을 종료한다. * @param appName 어플리케이션 아이디 * @param version 종료 대상 버전 * @return * @throws ManagementException */ public String stop(String appName, String version) throws ManagementException{ JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_DEPLOY_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, HotDeployControlMBean.class, true); HotDeployControlMBean hotDeploy = (HotDeployControlMBean)object; log.info(traceId+"Stop '"+appName+"','"+version+"'"); return hotDeploy.stop(appName, version); } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("stop()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } /** * 어플리케이션을 재시작한다. 재시작시 시작 옵션은 SAFETY이다. * @param appName 어플리케이션 아이디 * @param version 실행 버전 * @return * @throws ManagementException */ public String restart(String appName, String version) throws ManagementException{ JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_DEPLOY_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, HotDeployControlMBean.class, true); HotDeployControlMBean hotDeploy = (HotDeployControlMBean)object; log.info(traceId+"reStart '"+appName+"','"+version+"'"); return hotDeploy.restart(appName, version); } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("restart()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } /** * 삭제된 어플리케이션을 대상으로 재 배포을 실행한다. * @param appName 어플리케이션 아이디 * @param version 실행 대상 버전 * @return * @throws ManagementException */ public String redeploy(String appName, String version) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_DEPLOY_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, HotDeployControlMBean.class, true); HotDeployControlMBean hotDeploy = (HotDeployControlMBean)object; log.info(traceId+"redeploy '"+appName+"','"+version+"'"); return hotDeploy.redeploy(appName, version); } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("reDeploy()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } /** * 배치를 실행한다. */ public boolean executeBatch(String batchIfId) throws ManagementException { JMXConnector connector = null; MBeanServerConnection connection = null; try { connector = connect(); connection = connector.getMBeanServerConnection(); ObjectName objectName = ObjectName.getInstance(ManagementConstants.OBJECT_NAME_MESSAGE_CONTROL); Object object = MBeanServerInvocationHandler.newProxyInstance(connection, objectName, MessageControlMBean.class, true); MessageControlMBean messageControl = (MessageControlMBean)object; log.info(traceId+"Executing Batch. '"+batchIfId+"' IF ID."); return messageControl.executeBatch(batchIfId); } catch (ManagementException e) { throw e; } catch (Exception e) { throw new ManagementException("executeBatch()", e.getMessage(), e); } finally { closeJmxConnector(connector); } } }
package com.cinema.biz.dao; import java.util.List; import java.util.Map; import com.cinema.biz.model.SimDependency; import com.cinema.biz.model.base.TSimDependency; import tk.mybatis.mapper.common.Mapper; import tk.mybatis.mapper.common.MySqlMapper; public interface SimDependencyMapper extends Mapper<TSimDependency>,MySqlMapper<TSimDependency>{ /**列表*/ List<SimDependency> getList(Map<String, Object> paraMap); /**详情*/ SimDependency getDetail(Map<String, Object> paraMap); }
package rc.security; import io.jsonwebtoken.Jwt; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; import rc.model.JwtAuthenticationToken; import rc.model.JwtUser; import rc.model.JwtUserDetails; import java.util.List; @Component public class JwtAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider { @Autowired private JwtValidator jwtValidator; @Override protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken) throws AuthenticationException { } @Override protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken) throws AuthenticationException { JwtAuthenticationToken jwtAuthenticationToken=(JwtAuthenticationToken) usernamePasswordAuthenticationToken; String token=jwtAuthenticationToken.getToken(); JwtUser jwtUser =jwtValidator.validate(token); if (jwtUser == null){ throw new RuntimeException("JWT Token is incorrect"); } List<GrantedAuthority> grantedAuthorities= AuthorityUtils.commaSeparatedStringToAuthorityList(jwtUser.getRole()); return new JwtUserDetails(jwtUser.getUserName(),jwtUser.getId(),token,grantedAuthorities); } @Override public boolean supports(Class<?> aClass) { return (JwtAuthenticationToken.class.isAssignableFrom(aClass)); } }
package com.japaricraft.japaricraftmod.render.modelrender; import com.japaricraft.japaricraftmod.mob.Araisan; import com.japaricraft.japaricraftmod.render.ModelAraisan; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import static com.japaricraft.japaricraftmod.JapariCraftMod.MODID; @SideOnly(Side.CLIENT) public class AraisanRender extends RenderLiving<Araisan> { private static final ResourceLocation Arai_TEXTURES = new ResourceLocation(MODID, "textures/entity/araisan.png"); public AraisanRender(RenderManager renderManager) { super(renderManager, new ModelAraisan(), 0.5F); } @Override protected ResourceLocation getEntityTexture(Araisan entity) { return Arai_TEXTURES; } }
package org.yx.db.sql; public interface DBNameResolver { /** * 根据java字段名,返回数据库的列名 * * @param javaFieldName * java的字段名,大小写敏感 * @return 数据库列名,一般为小写格式 */ String resolveColumnName(String javaFieldName); /** * 根据java类名,返回数据库的表名 * * @param simpleJavaName * java的类名,大小写敏感 * @return 数据库表名,一般为小写格式 */ String resolveTableName(String simpleJavaName); }
package com.automat.CTFREE; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Random; import android.app.Activity; import android.app.Dialog; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Rect; import android.graphics.RectF; import android.media.AudioManager; import android.media.SoundPool; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.automat.CTFREE.views.HistoryView; import com.automat.CTFREE.views.HistoryView.HistoryRowTuple; import com.automat.CTFREE.views.QueryView; import com.automat.CTFREE.views.SelectorView; import com.automat.CTFREE.views.StatsView; /* * TODO * -problem with f# drawing as f (draw double flat/sharps! in staves) * -make keyboard keys match staves (i.e. from g to f) * -draw clef symbols */ public class Functions { private static Random rand = new Random(); private static PianoApplication appState; private static final String flat_str = "\u266D"; private static final String sharp_str = "\u266F"; /*Data types*/ public static enum Tone{ A,B,C,D,E,F,G; } public static class ScaleInterval{ public int interval; public int accidental; public ScaleInterval(int interval, int accidental) {this.interval = interval;this.accidental = accidental;} } public static enum ChordType{ maj,min,aug,dim; } private static enum DisplayType{ KEYBOARD, SYMBOL, STAVE; } public static final class QuizType{ DisplayType query; DisplayType selector; public QuizType(DisplayType query, DisplayType selector) { super(); this.query = query; this.selector = selector; } @Override public String toString(){ return "Match " + query.toString().toLowerCase() + " to " + selector.toString().toLowerCase(); } public String tableName(){ return query + "_" + selector; } } public static final QuizType[] available_quizTypes = { new QuizType(DisplayType.KEYBOARD, DisplayType.SYMBOL), new QuizType(DisplayType.SYMBOL, DisplayType.KEYBOARD), new QuizType(DisplayType.STAVE, DisplayType.KEYBOARD), new QuizType(DisplayType.STAVE, DisplayType.SYMBOL), }; private static enum ScaleType{ maj, min; } public static class Note{ public Tone root; public int accidental; public Note(Tone root, int a){this.root = root; this.accidental = a;} @Override public boolean equals(Object o){ Note n = (Note)o; if(n.root == this.root && n.accidental == this.accidental){ return true; } else return false; } @Override public String toString(){ return this.root + " " + this.accidental; } } public static class DiatonicIntervalNode{ public Note note; public int toNextNote; public DiatonicIntervalNode(Note n, int toNextNote) {this.note = n;this.toNextNote = toNextNote;} @Override public String toString(){ return note.toString() + " " + this.toNextNote; } } public static class Chord{ public Note root; public ChordType type; public int inversion; public int octave; public Chord(Note root, ChordType type, int inversion, int octave) {this.root = root;this.type = type;this.inversion = inversion;this.octave = octave;} @Override public String toString(){ return root.toString() + " " + this.type.toString() + " " + this.octave; } @Override public boolean equals(Object c){ Chord ch = (Chord) c; return equivalent_note(this.root, ch.root) && this.type == ch.type; } } private static class PianoKey{ Note note; RectF bounds; boolean isSharp; public PianoKey(Note n, RectF b, boolean s){this.note=n;this.bounds=b;this.isSharp=s;} } private static Map<ChordType,ScaleInterval[]> chord_definitions; static{ HashMap<ChordType,ScaleInterval[]> temp = new HashMap<ChordType, ScaleInterval[]>(); temp.put(ChordType.maj, new ScaleInterval[] { new ScaleInterval(1,0), new ScaleInterval(3,0), new ScaleInterval(5,0)}); temp.put(ChordType.min, new ScaleInterval[] { new ScaleInterval(1,0), new ScaleInterval(3,-1), new ScaleInterval(5,0)}); // temp.put(ChordType.sus2, new ScaleInterval[] { new ScaleInterval(1,0), // new ScaleInterval(2,0), // new ScaleInterval(5,0)}); // temp.put(ChordType.sus4, new ScaleInterval[] { new ScaleInterval(1,0), // new ScaleInterval(4,0), // new ScaleInterval(5,0)}); // temp.put(ChordType.maj7, new ScaleInterval[] { new ScaleInterval(1,0), // new ScaleInterval(3,0), // new ScaleInterval(5,0), // new ScaleInterval(7,0)}); // temp.put(ChordType.maj6, new ScaleInterval[] { new ScaleInterval(1,0), // new ScaleInterval(3,0), // new ScaleInterval(5,0), // new ScaleInterval(6,0)}); // temp.put(ChordType.min7, new ScaleInterval[] { new ScaleInterval(1,0), // new ScaleInterval(3,-1), // new ScaleInterval(5,0), // new ScaleInterval(7,-1)}); // temp.put(ChordType.dom7, new ScaleInterval[] { new ScaleInterval(1,0), // new ScaleInterval(3,0), // new ScaleInterval(5,0), // new ScaleInterval(7,-1)}); temp.put(ChordType.aug, new ScaleInterval[] { new ScaleInterval(1,0), new ScaleInterval(3,0), new ScaleInterval(5,1)}); temp.put(ChordType.dim, new ScaleInterval[] { new ScaleInterval(1,0), new ScaleInterval(3,-1), new ScaleInterval(5,-1)}); // temp.put(ChordType.maj7b5, new ScaleInterval[] { new ScaleInterval(1,0), // new ScaleInterval(3,0), // new ScaleInterval(5,-1), // new ScaleInterval(7,0)}); chord_definitions = Collections.unmodifiableMap(temp); } private static Map<ScaleType,int[]> scale_definitions; static{ HashMap<ScaleType,int[]> temp = new HashMap<ScaleType, int[]>(); temp.put(ScaleType.maj, new int[] {0, 2, 4, 5, 7, 9, 11}); temp.put(ScaleType.min, new int[] {0, 2, 3, 5, 7, 8, 11}); scale_definitions = Collections.unmodifiableMap(temp); } private static DiatonicIntervalNode[] diatonic_scale = { new DiatonicIntervalNode(new Note(Tone.A, 0), 2), new DiatonicIntervalNode(new Note(Tone.B, 0), 1), new DiatonicIntervalNode(new Note(Tone.C, 0), 2), new DiatonicIntervalNode(new Note(Tone.D, 0), 2), new DiatonicIntervalNode(new Note(Tone.E, 0), 1), new DiatonicIntervalNode(new Note(Tone.F, 0), 2), new DiatonicIntervalNode(new Note(Tone.G, 0), 2) }; private static Map<ChordType,String> chord_strings; static{ HashMap<ChordType,String> temp = new HashMap<ChordType, String>(); temp.put(ChordType.maj, ""); temp.put(ChordType.min, "m"); temp.put(ChordType.aug, "+"); temp.put(ChordType.dim, "\u00B0"); chord_strings = Collections.unmodifiableMap(temp); } /* * Business logic */ private static Note random_note(){ //Tone t = Tone.values()[rand.nextInt(Tone.values().length)]; //int acc = rand.nextInt(3)-1; Note n = appState.availKeys.get(rand.nextInt(appState.availKeys.size())); return n; // if(t == Tone.B && acc==1){ // return new Note(Tone.C, 0); // } // else if(t == Tone.C && acc==-1){ // return new Note(Tone.B, 0); // } // else if(t == Tone.E && acc==1){ // return new Note(Tone.F, 0); // } // else if(t == Tone.F && acc==-1){ // return new Note(Tone.E, 0); // } // else return new Note(t, acc); } private static Chord random_chord(){ Note root = random_note(); //ChordType type = ChordType.values()[rand.nextInt(ChordType.values().length)]; ChordType type = appState.availChords.get(rand.nextInt(appState.availChords.size())); while( root.root == Tone.G && root.accidental == -1 && (type == ChordType.min) || root.root == Tone.D && root.accidental == -1 && (type == ChordType.min) || root.root == Tone.A && root.accidental == -1 && (type == ChordType.min) || root.root == Tone.C && root.accidental == 1 && (type == ChordType.maj || type == ChordType.aug) || root.root == Tone.G && root.accidental == 1 && (type == ChordType.maj || type == ChordType.aug) || root.root == Tone.D && root.accidental == 1 && (type == ChordType.maj || type == ChordType.aug)){ root = random_note(); type = ChordType.values()[rand.nextInt(ChordType.values().length)]; } int octave = rand.nextInt(2); if(root.root == Tone.G || root.root == Tone.A || root.root == Tone.B){ if(octave >= 1){ octave=0; } } return new Chord( root, type, rand.nextInt(4), octave); } private static DiatonicIntervalNode[] rotate_to(Note n, DiatonicIntervalNode[] ar){ DiatonicIntervalNode[] rotated = new DiatonicIntervalNode[ar.length]; int seek = 0; while(ar[seek].note.root != n.root){ seek++; } for (int i = 0; i < rotated.length; i++) { int ix = (seek + i) % ar.length; rotated[i] = ar[ix]; } return rotated; } private static Note[] major_scale_notes(Note root){ int[] scale_def = scale_definitions.get(ScaleType.maj); DiatonicIntervalNode[] skeleton = rotate_to(root, diatonic_scale); Note[] notes = new Note[scale_def.length]; int expected_interval = 0; int actual_interval = 0; int skeleton_ix = 0; for (int i = 0; i < scale_def.length; i++) { expected_interval=scale_def[i]; notes[i] = new Note(skeleton[skeleton_ix].note.root, expected_interval - actual_interval); if(skeleton_ix<skeleton.length){ skeleton_ix+=1; actual_interval += skeleton[skeleton_ix-1].toNextNote; } } //If root note is nondiatonic adjust scale for (int i = 0; i < notes.length; i++) { notes[i].accidental+=root.accidental; } return notes; } private static Note[] chord_notes(Chord c){ ScaleInterval[] chord_def = chord_definitions.get(c.type); Note[] major_scale = major_scale_notes(c.root); Note[] chord_notes = new Note[chord_def.length]; for (int i = 0; i < chord_notes.length; i++) { int index = chord_def[i].interval-1; int acc = chord_def[i].accidental; Note chord_note = major_scale[index]; chord_note.accidental += acc; chord_notes[i] = chord_note; } return chord_notes; } private static String chord_symbol(Chord c){ StringBuilder sb = new StringBuilder(); sb.append(c.root.root); if(c.root.accidental == 1)sb.append(sharp_str); if(c.root.accidental == -1)sb.append(flat_str); sb.append(chord_strings.get(c.type)); return sb.toString(); } private static int natural_offset(Note lower, Note higher){ DiatonicIntervalNode[] rotated = rotate_to(lower, diatonic_scale); Note rootnote = new Note(higher.root, 0); int j = 0; int offset = 0; while(!equivalent_note(rootnote, rotated[j].note)){ offset+=rotated[j].toNextNote; j++; } offset -= lower.accidental; offset += higher.accidental; return offset; } private static int diatonic_offset(Note lower, Note higher){ DiatonicIntervalNode[] rotated = rotate_to(lower, diatonic_scale); Note rootnote = new Note(higher.root, 0); int j = 0; while(!equivalent_note(rootnote, rotated[j].note)){ j++; } return j; } private static int note_index(Note n){ int diatonic_index = 0; switch(n.root){ case A: diatonic_index = 0; break; case B: diatonic_index = 2; break; case C: diatonic_index = 3; break; case D: diatonic_index = 5; break; case E: diatonic_index = 7; break; case F: diatonic_index = 8; break; case G: diatonic_index = 10; break; } diatonic_index += n.accidental; //loop left if(diatonic_index < 0){ int j = (-1*diatonic_index) % 12; return 12 - j; } //loop right else return diatonic_index % 12; } private static boolean equivalent_note(Note a, Note b){ return note_index(a)==note_index(b); } private static ArrayList<PianoKey> position_keys(ArrayList<PianoKey> keys, int num_white_keys, RectF bounds){ //Get bounds float lft = bounds.left; float rgt = bounds.right; float top = bounds.top; float bot = bounds.bottom; //Scale widths and heights float w_w = (rgt - lft) / (float) num_white_keys; float w_h = (bot - top); float b_w = 0.666f * w_w; float b_h = 0.666f * w_h; //Note: first key is always off screen //TODO we assume here first key is white... keys.get(0).bounds.left = lft - w_w; keys.get(0).bounds.top = top; keys.get(0).bounds.bottom = top + w_h; keys.get(0).bounds.right = keys.get(0).bounds.left + w_w; for (int i = 1; i < keys.size(); i++) { PianoKey curr_key = keys.get(i); if(curr_key.isSharp){ curr_key.bounds.top = top; curr_key.bounds.bottom = top + b_h; switch(curr_key.note.root){ case C: curr_key.bounds.left = keys.get(i-1).bounds.left + 0.550f * w_w; break; case D: curr_key.bounds.left = keys.get(i-1).bounds.left + 0.800f * w_w; break; case F: curr_key.bounds.left = keys.get(i-1).bounds.left + 0.550f * w_w; break; case G: curr_key.bounds.left = keys.get(i-1).bounds.left + 0.700f * w_w; break; case A: curr_key.bounds.left = keys.get(i-1).bounds.left + 0.800f * w_w; break; } curr_key.bounds.right = curr_key.bounds.left + b_w; } else{ //is a white key curr_key.bounds.top = top; curr_key.bounds.bottom = top + w_h; curr_key.bounds.left = (keys.get(i-1).note.accidental != 0) ? keys.get(i-2).bounds.right : keys.get(i-1).bounds.right; curr_key.bounds.right = curr_key.bounds.left + w_w; } } return keys; } private static Canvas render_keyboard( Canvas c, RectF rect, Chord chord){ int num_white_keys = 17; Note start_note = new Note(Tone.C,0); DiatonicIntervalNode[] keyboard_scale = rotate_to(start_note, diatonic_scale); //Create list of visible keys ArrayList<PianoKey> keys = new ArrayList<PianoKey>(); int counter = 0; while(counter < num_white_keys){ DiatonicIntervalNode current_node = keyboard_scale[(counter % keyboard_scale.length)]; for (int i = 0; i < current_node.toNextNote; i++) { keys.add(new PianoKey(new Note(current_node.note.root, i), new RectF(), i>0?true:false)); } counter++; } //Position keys keys = position_keys(keys, num_white_keys, rect); //Render keys //Fill whites first Paint p = new Paint(); p.setAntiAlias(true); p.setColor(Color.WHITE); p.setStyle(Style.FILL); for(PianoKey k : keys){ if(!k.isSharp){ c.drawRect(k.bounds, p); } } //Then black keys p.setColor(Color.BLACK); p.setStyle(Style.FILL); for(PianoKey k : keys){ if(k.isSharp){ c.drawRect(k.bounds, p); } } /*Then overlay grid*/ p.setColor(Color.BLACK); p.setStyle(Style.STROKE); for(PianoKey k : keys){ if(!k.isSharp){ c.drawRect(k.bounds, p); } } /*Now overlay chord notes*/ Note[] chord_notes = chord_notes(chord); Note last_note = start_note; int last_offset = chord.octave * 12; for (int i = 0; i < chord_notes.length; i++) { int offset = last_offset + natural_offset(last_note, chord_notes[i]); if(offset < 0) offset += 12; if(offset > keys.size()-1) offset -= 12; PianoKey k = keys.get(offset); p.setColor(Color.BLUE); p.setStyle(Style.FILL); c.drawRect(k.bounds, p); /*Redraw occluded sharps*/ if(offset > 1 && keys.get(offset-1).isSharp){ /*(left sharp key)*/ PianoKey l = keys.get(offset-1); p.setColor(Color.BLACK); p.setStyle(Style.FILL); c.drawRect(l.bounds, p); } if(offset < keys.size()-2 && keys.get(offset+1).isSharp){ /*(right sharp key)*/ PianoKey r = keys.get(offset+1); p.setColor(Color.BLACK); p.setStyle(Style.FILL); c.drawRect(r.bounds, p); } last_note = chord_notes[i]; last_offset = offset; } return c; } private static final Canvas render_staves( Canvas c, RectF bounds, Chord chord){ float space = (bounds.bottom - bounds.top) / 10; /*Render staff lines*/ Paint p = new Paint(); p.setAntiAlias(true); c.drawRect(bounds, p); p.setColor(Color.WHITE); for (int i = 0; i < 11; i++) { if(i!=5){ c.drawLine( bounds.left, bounds.top + (i * space), bounds.right, bounds.top + (i * space), p); } } /*Render chord notes*/ Note[] chord_notes = chord_notes(chord); int curr_offset = diatonic_offset(new Note(Tone.G,0), chord_notes[0]); curr_offset+=chord.octave * 7; for (int i = 0; i < chord_notes.length; i++) { if(i>0){ curr_offset += diatonic_offset(chord_notes[i-1], chord_notes[i]); } p.setColor(Color.WHITE); float circle_x = bounds.left + (bounds.right - bounds.left) / 2.0f; float circle_y = bounds.bottom - (curr_offset * (space / 2.0f)); c.drawCircle( circle_x, circle_y, space / 2.0f, p); /*Render accidentals*/ if(chord_notes[i].accidental > 0){ /*Scale text -- hacky*/ float ts = 1; p.setTextSize(ts); Rect tbounds = new Rect(); p.getTextBounds(sharp_str, 0, sharp_str.length(), tbounds); while(tbounds.height() < space && ts < 1000){ ts = 1.1f * ts; p.setTextSize(ts); p.getTextBounds(sharp_str, 0, sharp_str.length(), tbounds); } c.drawText(sharp_str, circle_x * 0.85f, circle_y + (space/2.0f), p); } if(chord_notes[i].accidental < 0){ /*Scale text -- hacky*/ float ts = 1; p.setTextSize(ts); Rect tbounds = new Rect(); p.getTextBounds(flat_str, 0, flat_str.length(), tbounds); while(tbounds.height() < space && ts < 1000){ ts = 1.1f * ts; p.setTextSize(ts); p.getTextBounds(flat_str, 0, flat_str.length(), tbounds); } c.drawText(flat_str, circle_x * 0.85f, circle_y + (space/2.0f), p); } /*Render line*/ } return c; } @SuppressWarnings("unused") private static final Canvas render_symbol( Canvas c, RectF rect, Chord chord){ return c; } private static final void play_chord(Chord c, View v){ AudioManager mgr = (AudioManager)v.getContext().getSystemService(Context.AUDIO_SERVICE); float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC); float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC); float volume = streamVolumeCurrent / streamVolumeMax; Note[] notes = chord_notes(c); SoundPool sp = appState.soundPool; int[] sound_array = appState.sound_array; for (int i = 0; i < notes.length; i++) { sp.play(sound_array[note_index(notes[i])], volume, volume, 1, 0, 1f); } } // private static final void punch_timestamp(Chord selected_chord){ // ContentValues values = new ContentValues(); // values.put("target_chord", appState.target_chord.toString()); // values.put("round", appState.currentRound); // values.put("selected_chord", selected_chord.toString()); // values.put("correct", (selected_chord.equals(appState.target_chord) ? 1 : 0)); // values.put("response_time", System.currentTimeMillis() - appState.quizStartTime); // values.put("date", System.currentTimeMillis()); // appState.db.insert(appState.quizType.tableName(), null, values); // } /* * GUI user event callbacks */ public static void on_selector_down(SelectorView v){ /* * When a selector view is pressed, check if correct selection */ if(appState.target_chord == appState.viewToChord.get(v)){ v.setBackgroundColor(Color.GREEN); } else{ v.setBackgroundColor(Color.RED); } } public static void on_selector_up(SelectorView v){ v.setBackgroundColor(Color.BLACK); //punch_timestamp(appState.viewToChord.get(v)); appState.attempts++; if(appState.target_chord == appState.viewToChord.get(v)){ play_chord(appState.target_chord, v); appState.correctCount++; reset_quiz(); } else{ appState.statsView.invalidate(); } } /* * GUI rendering callbacks */ public static final Canvas on_render_queryView(QueryView v, Canvas c){ if(appState.target_chord != null){ if(appState.quizType.query == DisplayType.KEYBOARD){ Chord chord = appState.target_chord; float left = (0.1f * v.getWidth()); float top = (0.2f * v.getHeight()); float rgt = (1.0f * v.getWidth()); float bot = (0.8f * v.getHeight()); c = render_keyboard( c, new RectF( left, top, rgt, bot), chord); } if(appState.quizType.query == DisplayType.SYMBOL){ Chord chord = appState.target_chord; String chord_str = chord_symbol(chord); Paint p = new Paint(); p.setColor(Color.BLUE); p.setAntiAlias(true); p.setStrokeWidth(3); /*Scale text*/ float ts = v.getHeight() * 0.7f; p.setTextSize(ts); Rect bounds = new Rect(); p.getTextBounds(chord_str, 0, chord_str.length(), bounds); while(bounds.width() > v.getWidth() && ts > 1){ Log.d("", ts+""); ts = 0.9f * ts; p.setTextSize(ts); p.getTextBounds(chord_str, 0, chord_str.length(), bounds); } p.setTextAlign(Paint.Align.CENTER); c.drawText(chord_str, 0.5f * v.getWidth(), 0.7f * v.getHeight(), p); } if(appState.quizType.query == DisplayType.STAVE){ Chord chord = appState.target_chord; float left = (0.05f * v.getWidth()); float top = (0.1f * v.getHeight()); float rgt = (0.95f * v.getWidth()); float bot = (0.9f * v.getHeight()); c = render_staves(c, new RectF(left, top, rgt, bot), chord); } } return c; } public static final Canvas on_render_selectorView(SelectorView v, Canvas c){ if(appState.target_chord!=null){ /* * Draw the selector based on type. */ if(appState.quizType.selector == DisplayType.KEYBOARD){ Paint p = new Paint(); p.setAntiAlias(true); Chord chord = appState.viewToChord.get(v); float left = (0.1f * v.getWidth()); float top = (0.05f * v.getHeight()); float rgt = (1.0f * v.getWidth()); float bot = (0.95f * v.getHeight()); c = render_keyboard(c, new RectF( left, top, rgt, bot), chord); } if(appState.quizType.selector == DisplayType.SYMBOL){ Chord chord = appState.viewToChord.get(v); String chord_str = chord_symbol(chord); Paint p = new Paint(); p.setColor(Color.BLUE); p.setAntiAlias(true); p.setStrokeWidth(3); /*Scale text*/ float ts = v.getHeight() * 0.7f; p.setTextSize(ts); Rect bounds = new Rect(); p.getTextBounds(chord_str, 0, chord_str.length(), bounds); while(bounds.width() > v.getWidth() && ts > 1){ Log.d("", ts+""); ts = 0.9f * ts; p.setTextSize(ts); p.getTextBounds(chord_str, 0, chord_str.length(), bounds); } p.setTextAlign(Paint.Align.CENTER); c.drawText( chord_str, 0.5f * v.getWidth(), 0.7f * v.getHeight(), p); } if(appState.quizType.selector == DisplayType.STAVE){ Chord chord = appState.viewToChord.get(v); float left = (0.05f * v.getWidth()); float top = (0.1f * v.getHeight()); float rgt = (0.95f * v.getWidth()); float bot = (0.9f * v.getHeight()); c = render_staves(c, new RectF(left, top, rgt, bot), chord); } } return c; } public static final Canvas on_render_statsView(StatsView v, Canvas c){ String resp = "Reaction time: " + appState.lastResponseTime / 1000.0 + "sec"; Paint p = new Paint(); p.setAntiAlias(true); p.setColor(Color.MAGENTA); /*Scale text -- hacky*/ float ts = 1f; p.setTextSize(ts); Rect tbounds = new Rect(); p.getTextBounds(resp, 0, resp.length(), tbounds); while(tbounds.height() < 0.55f * v.getHeight() && ts < 1000){ ts = 1.05f * ts; p.setTextSize(ts); p.getTextBounds(resp, 0, resp.length(), tbounds); } c.drawText(resp, 10, tbounds.height(), p); String cors = appState.correctCount + " for " + appState.attempts; /*Scale text -- hacky*/ Rect vbounds = new Rect(); p.getTextBounds(cors, 0, cors.length(), vbounds); c.drawText(cors, v.getRight() - vbounds.width() - 10, tbounds.height(), p); return c; } // public static Canvas on_render_historyView(View v, Canvas c){ // // System.out.println("in redner hidstory"); // // //TESTDATA (TODO PING DB) // ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String,String>>(); // for (int i = 0; i < 30; i++) { // HashMap<String,String> entry = new HashMap<String,String>(); // entry.put("date", Long.toString(System.currentTimeMillis())); // entry.put("percent_correct", Float.toString(rand.nextFloat())); // entry.put("avg_reaction_time", Float.toString(rand.nextFloat() * 10.0f)); // data.add(entry); // } // // float width = v.getWidth(); // float left = v.getLeft(); // float top = v.getTop(); // float col_1_w = 0.2f * width; // float col_2_w = 0.4f * width; // float col_3_w = 0.4f * width; // float row_h = 0.1f * width; // float title_row_h = 0.15f *width; // // Paint p = new Paint(); // p.setAntiAlias(true); // p.setColor(Color.WHITE); // p.setTextSize(20); // // //DRAW TITLE ROW // c.drawText("Accuracy", left + col_1_w, top, p); // c.drawText("Response Time", left + col_1_w + col_2_w, top, p); // // for (int i = 0; i < data.size(); i++) { // HashMap<String,String> entry = data.get(i); // long date = Long.parseLong(entry.get("date")); // float percent_correct = Float.parseFloat(entry.get("percent_correct")); // float avg_reaction_time = Float.parseFloat(entry.get("avg_reaction_time")); // // float thisy = i*row_h + title_row_h; // // if(i%5==0){ // c.drawText(new Date(date).toString(), 0, thisy, p); // } // // //Draw percent correct // c.drawLine( left + col_1_w, // thisy, // left + col_1_w + col_2_w * percent_correct, // thisy, // p); // // //Draw response time // c.drawLine( left + col_1_w + col_2_w, // thisy, // left + col_1_w + col_2_w + col_3_w * (avg_reaction_time / 10f), // thisy, // p); // } // // // // return c; // } public static Canvas on_render_barGraph(View v, Canvas c, float value, float maxValue){ Paint p = new Paint(); p.setColor(Color.MAGENTA); p.setStyle(Style.FILL_AND_STROKE); p.setStrokeWidth(20); System.out.println(value + " " + maxValue); c.drawLine( 0, v.getHeight() / 2, (value/maxValue)*v.getWidth(), v.getHeight() / 2, p); return c; } /* * Main menu */ public static void set_quiz_type(QuizType qt){ appState.quizType = qt; } public static void onStartButtonClick(Activity a, View v){ a.startActivity(new Intent(a, com.automat.CTFREE.activities.QuizActivity.class)); } public static void onOptionsButtonClick(Activity a, View v){ a.startActivity(new Intent(a, com.automat.CTFREE.activities.OptionsActivity.class)); } /* * Initialize app */ public static final void set_app(PianoApplication app){ Functions.appState = app; } public static void reset_chords(){ /* * Select a target answer and choices. Render all views. */ //Reset target and choices appState.target_chord = random_chord(); // for (int i = 0; i < appState.selectorViews.length; i++) { // appState.viewToChord.put(appState.selectorViews[i], random_chord()); // } appState.viewToChord.clear(); int i = 0; while(i < 4){ Chord c = random_chord(); if(!c.equals(appState.target_chord) && !appState.viewToChord.containsValue(c)){ appState.viewToChord.put(appState.selectorViews[i], c); i++; } } //Ensure at least one choice is correct appState.viewToChord.put(appState.selectorViews[rand.nextInt(appState.selectorViews.length)], appState.target_chord); //Redraw query and selector views appState.queryView.invalidate(); for (i = 0; i < appState.selectorViews.length; i++) { appState.selectorViews[i].invalidate(); } appState.statsView.invalidate(); appState.quizStartTime = System.currentTimeMillis(); } public static void reset_quiz(){ // int lastResponseTime = 0; // int correctCount = 0; // int attempts = 0; // // String query = "SELECT correct, response_time FROM " + // appState.quizType.tableName() + " " + // "WHERE round=" + appState.currentRound + " " + // "ORDER BY _id DESC"; // // Cursor cursor = appState.db.rawQuery(query, null); // // if(cursor.getCount() > 0){ // // cursor.moveToFirst(); // // //Get latest response time // lastResponseTime = cursor.getInt(cursor.getColumnIndex("response_time")); // //Calculate correct / attempts // while (!cursor.isAfterLast()) { // correctCount += cursor.getInt(cursor.getColumnIndex("correct")); // attempts++; // cursor.moveToNext(); // } // cursor.close(); if(appState.correctCount >= appState.maxTrials){ //1. Write new round entry into history and db long date = System.currentTimeMillis(); float percent_correct = (float)appState.correctCount / (float)appState.attempts; float avg_response_time = appState.totalResponseTimeForRound / (float)appState.maxTrials; appState.history.add(new HistoryRowTuple(date, percent_correct, avg_response_time)); ContentValues values = new ContentValues(); values.put("date", date); values.put("percent_correct", percent_correct); values.put("avg_response_time", avg_response_time); appState.db.insert(appState.quizType.tableName(), null, values); //2. Show dialog with SimpleCursorAdapter final Dialog dialog = new Dialog(appState.quizActivity); dialog.setContentView(R.layout.history); dialog.setTitle("Round Complete!"); HistoryView historyView = (HistoryView) dialog.findViewById(R.id.historyList); historyView.setAdapter(new HistoryView.CustomAdapter(appState.quizActivity, appState.history)); Button button = (Button) dialog.findViewById(R.id.dismissDialogButton); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { reset_chords(); dialog.cancel(); } }); dialog.setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { reset_chords(); } }); dialog.show(); //3. Reset appstate data appState.correctCount = 0; appState.lastResponseTime = 0; appState.totalResponseTimeForRound = 0; appState.attempts = 0; } else{ if(appState.attempts != 0){ appState.lastResponseTime = System.currentTimeMillis() - appState.quizStartTime; appState.totalResponseTimeForRound += appState.lastResponseTime; } reset_chords(); } // } // else{ // reset_chords(); // } } }
package demo; public class SemFiltro implements FiltroDados { @Override public boolean condicao(Tuplo tuplo) { return true; } }
/* * 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 com.ut.healthelink.controller; import com.ut.healthelink.model.newsArticle; import com.ut.healthelink.service.newsArticleManager; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.view.RedirectView; /** * * @author chadmccue */ @Controller @RequestMapping(value={"/administrator/sysadmin/news", "/news"}) public class newsArticleController { @Autowired private newsArticleManager newsarticlemanager; /** The '' request will return the list of news articles that are currently in the * system. */ @RequestMapping(value = "", method = RequestMethod.GET) public ModelAndView newsArticleList(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/administrator/sysadmin/news"); List<newsArticle> newsArticles = newsarticlemanager.listAllNewsArticles(); mav.addObject("newsArticles", newsArticles); return mav; } /** The '/create' request will return a blank news article form. * */ @RequestMapping(value = "/create", method = RequestMethod.GET) public ModelAndView createnewsArticle(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/administrator/sysadmin/news/details"); mav.addObject("newsArticle", new newsArticle()); return mav; } /** * The '/create' POST request will submit the new article once all required fields are checked. * * @param newsArticle The object holding the news article form fields * @param result The validation result * @param redirectAttr The variable that will hold values that can be read after the redirect * @param action The variable that holds which button was pressed * * @return Will return the news article list page on "Save" * @throws Exception */ @RequestMapping(value = "/create", method = RequestMethod.POST) public ModelAndView saveNewArticle(@Valid newsArticle newsArticle, BindingResult result, RedirectAttributes redirectAttr, @RequestParam String action) throws Exception { if (result.hasErrors()) { ModelAndView mav = new ModelAndView(); mav.setViewName("/administrator/sysadmin/news/details"); return mav; } newsarticlemanager.createNewsArticle(newsArticle); redirectAttr.addFlashAttribute("savedStatus", "created"); ModelAndView mav = new ModelAndView(new RedirectView("/administrator/sysadmin/news")); return mav; } /** The '/edit' request will return a blank news article form. * */ @RequestMapping(value = "/edit", method = RequestMethod.GET) public ModelAndView editnewsArticle(@RequestParam(value = "i", required = true) Integer articleId, HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/administrator/sysadmin/news/details"); newsArticle newsArticle = newsarticlemanager.getNewsArticleById(articleId); mav.addObject("newsArticle", newsArticle); return mav; } /** * The '/edit' POST request will submit the new article once all required fields are checked. * * @param newsArticle The object holding the news article form fields * @param result The validation result * @param redirectAttr The variable that will hold values that can be read after the redirect * @param action The variable that holds which button was pressed * * @return Will return the news article list page on "Save" * @throws Exception */ @RequestMapping(value = "/edit", method = RequestMethod.POST) public ModelAndView saveArticleUpdates(@Valid newsArticle newsArticle, BindingResult result, RedirectAttributes redirectAttr, @RequestParam String action) throws Exception { if (result.hasErrors()) { ModelAndView mav = new ModelAndView(); mav.setViewName("/administrator/sysadmin/news/details"); return mav; } newsarticlemanager.updateNewsArticle(newsArticle); redirectAttr.addFlashAttribute("savedStatus", "updated"); ModelAndView mav = new ModelAndView(new RedirectView("/administrator/sysadmin/news")); return mav; } /** Front-end News Article Methods **/ /** * The '/articles' GET request will search for a clicked article by the passed in article name. * * @param articleTitle The title of the selected article. * * @return Will return the selected news article. */ @RequestMapping(value = "/articles", method = RequestMethod.GET) public ModelAndView viewArticles() throws Exception { List<newsArticle> articles = newsarticlemanager.listAllActiveNewsArticles(); ModelAndView mav = new ModelAndView(); mav.setViewName("/news/list"); mav.addObject("articles", articles); mav.addObject("pageTitle", "News"); return mav; } /** * The '/news/article/{articleTitle}' GET request will search for a clicked article by the passed in article name. * * @param articleTitle The title of the selected article. * * @return Will return the selected news article. */ @RequestMapping(value = "/article/{articleTitle}", method = RequestMethod.GET) public ModelAndView viewArticleDetails(@PathVariable String articleTitle) throws Exception { String articleTitleStripped = articleTitle.replace("-", " "); List<newsArticle> article = newsarticlemanager.getNewsArticleByTitle(articleTitleStripped); ModelAndView mav = new ModelAndView(); mav.setViewName("/news/articleDetails"); if(article != null && article.size() > 0) { mav.addObject("article", article.get(0)); } else { mav.addObject("article", ""); } mav.addObject("pageTitle", "News"); return mav; } }
package in.tecmentor.service.impl; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import in.tecmentor.entity.ProductDetailsEntity; import in.tecmentor.entity.ProductEntity; import in.tecmentor.model.Product; import in.tecmentor.model.ProductDetails; import in.tecmentor.repository.ProductRepository; import in.tecmentor.service.ProductService; @Service public class ProductServiceImpl implements ProductService { @Autowired private ProductRepository productRepository; @Override public void saveOrUpdateProduct(Product product) { ProductEntity productEntity = new ProductEntity(); ProductDetailsEntity productDetails = new ProductDetailsEntity(); BeanUtils.copyProperties(product, productEntity); BeanUtils.copyProperties(product.getProductDetails(), productDetails); productEntity.setProductDetails(productDetails); productDetails.setProduct(productEntity); productRepository.save(productEntity); } @Override public List<Product> getAllProduct() { List<ProductEntity> productEntities = productRepository.findAll(); List<Product> products = new ArrayList<Product>(); Product product = null; ProductDetails productDetails = null; for (ProductEntity productEntity : productEntities) { product = new Product(); productDetails = new ProductDetails(); BeanUtils.copyProperties(productEntity, product); BeanUtils.copyProperties(productEntity.getProductDetails(), productDetails); product.setProductDetails(productDetails); products.add(product); } return products; } @Override public void deleteProduct(Long productId) { productRepository.deleteById(productId); } @Override public Product getProductById(Long productId) { Optional<ProductEntity> optionalProduct = productRepository.findById(productId); Product product = new Product(); ProductDetails productDetails = new ProductDetails(); BeanUtils.copyProperties(optionalProduct.get(), product); BeanUtils.copyProperties(optionalProduct.get().getProductDetails(), productDetails); product.setProductDetails(productDetails); return product; } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.http.server.reactive; import java.net.URI; import java.time.Duration; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; import org.springframework.core.io.buffer.DefaultDataBufferFactory; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import org.springframework.web.testfixture.http.server.reactive.bootstrap.AbstractHttpHandlerIntegrationTests; import org.springframework.web.testfixture.http.server.reactive.bootstrap.HttpServer; import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Maldini * @since 5.0 */ class AsyncIntegrationTests extends AbstractHttpHandlerIntegrationTests { private final Scheduler asyncGroup = Schedulers.parallel(); @Override protected AsyncHandler createHttpHandler() { return new AsyncHandler(); } @ParameterizedHttpServerTest void basicTest(HttpServer httpServer) throws Exception { startServer(httpServer); URI url = URI.create("http://localhost:" + port); @SuppressWarnings("resource") ResponseEntity<String> response = new RestTemplate().exchange(RequestEntity.get(url).build(), String.class); assertThat(response.getBody()).isEqualTo("hello"); } private class AsyncHandler implements HttpHandler { @Override @SuppressWarnings("deprecation") public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) { return response.writeWith(Flux.just("h", "e", "l", "l", "o") .delayElements(Duration.ofMillis(100)) .publishOn(asyncGroup) .collect(DefaultDataBufferFactory.sharedInstance::allocateBuffer, (buffer, str) -> buffer.write(str.getBytes()))); } } }
package me.msce; import com.sun.org.apache.xpath.internal.operations.Bool; import net.md_5.bungee.api.chat.ClickEvent; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.player.PlayerInteractEvent; import java.util.ArrayList; import java.util.List; public class EnchanterLocator { List<Location> locations = new ArrayList<>(); public static Boolean enchanterIsSetup(Location loc1, Location loc2) { Integer xMin, xMax, yMin, yMax, zMin, zMax = 0; Block b = null; if (loc1.getX() >= loc2.getX()) { xMax = (int) loc1.getX(); xMin = (int) loc2.getX(); } else { xMax = (int) loc2.getX(); xMin = (int) loc1.getX(); } if (loc1.getY() >= loc2.getY()) { yMax = (int) loc1.getY(); yMin = (int) loc2.getY(); } else { yMax = (int) loc2.getY(); yMin = (int) loc1.getY(); } if (loc1.getZ() >= loc2.getZ()) { zMax = (int) loc1.getZ(); zMin = (int) loc2.getZ(); } else { zMax = (int) loc2.getZ(); zMin = (int) loc1.getZ(); } for (int x = xMin; x <= xMax; x++) { for (int y = yMin; y <= yMax; y++) { for (int z = zMin; z <= zMax; z++) { b = loc1.getWorld().getBlockAt( x, y, z ); if (b.getType() != Material.BARRIER) { return false; } } } } return true; } }
package core.server.game.controllers; import cards.Card; public interface ArbitrationRequiredGameController extends GameController { public void onArbitrationCompleted(Card card); }
package cl.cafeines.web.menu.demo.model; import lombok.Data; import javax.persistence.*; @Entity @Table(name="Product") @Data public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Integer Id; Integer idCategory; String Name; String ImageUrl; String Description; }
import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.sql.*; public class RepresentativeTest { private Statement statement; private Connection connection; @BeforeClass public void connect() throws SQLException { String url = "jdbc:mysql://database-techno.c771qxmldhez.us-east-2.rds.amazonaws.com:3306/daulet2030_studens_database"; String user = "daulet2030"; String password = "daulet2030@gmail.com"; connection = DriverManager.getConnection( url, user, password ); statement = connection.createStatement(); } @AfterClass public void disconnect() throws SQLException { connection.close(); } @DataProvider(name = "representative") public Object[][] data() throws SQLException { ResultSet resultSet = statement.executeQuery( "select * from representative" ); resultSet.last(); int rowNumbers = resultSet.getRow(); resultSet.beforeFirst(); int i = 0; Object[][] result = new Object[rowNumbers][4]; while(resultSet.next()){ String name = resultSet.getString( "firstname" ); String lastname = resultSet.getString( "lastname" ); String country = resultSet.getString( "country" ); String phone = resultSet.getString( "phone" ); result[i][0] = name; result[i][1] = lastname; result[i][2] = country; result[i][3] = phone; i++; } return result; } @Test(dataProvider = "representative") public void test(String c1, String c2, String c3, String c4){ System.out.print(c1 + c2 + c3 + c4); } }
//designpatterns.proxy.Searcher.java package designpatterns.proxy; //抽象查询类:抽象主题类 public interface Searcher { public String doSearch(String userId,String keyword); }
package com.arthur.bishi.ali.day20210320; import sun.security.krb5.Asn1Exception; import java.util.Arrays; import java.util.Scanner; /** * @title: No1 * @Author ArthurJi * @Date: 2021/3/20 10:26 * @Version 1.0 */ public class No1 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] nums = new int[n]; for (int i = 0; i < n; i++) { nums[i] = scanner.nextInt(); } for (int i = 0; i < n; i++) { nums[i] = (int) Math.abs(nums[i] - Math.pow(Math.round(Math.sqrt(nums[i])), 2)); } Arrays.sort(nums); int ans = 0; for (int i = 0; i < n / 2; i++) { ans += nums[i]; } System.out.println(ans); } }
package com.freddy.sample.mpesa; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class ManagerDashboard extends AppCompatActivity { ImageView occupancy,payments,bookings, hearsepayments,morticinas; RelativeLayout relativeLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_manager_dashboard); try { relativeLayout = (RelativeLayout) findViewById(R.id.r56); occupancy = (ImageView) findViewById(R.id.occupancybtn); payments = (ImageView) findViewById(R.id.funeralhomepayment); hearsepayments = (ImageView) findViewById(R.id.hearsepayment); morticinas = (ImageView) findViewById(R.id.morticnasreport); bookings = (ImageView) findViewById(R.id.hearsereport); occupancy.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(ManagerDashboard.this, ManagerOccupancyReport.class); startActivity(intent); } }); morticinas.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(ManagerDashboard.this,ManagerViewMorticiansActivity.class); startActivity(intent); } }); payments.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(ManagerDashboard.this, ViewPaymentReportActivity.class); startActivity(intent); } }); hearsepayments.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(ManagerDashboard.this, ManagerViewHearsePaymentReport.class); startActivity(intent); } }); bookings.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(ManagerDashboard.this, ManagerCheckHearseBookings.class); startActivity(intent); } }); }catch(Exception e){ e.printStackTrace(); Toast.makeText(ManagerDashboard.this,e.getMessage(),Toast.LENGTH_LONG).show(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.managerdashboardoptions,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); if (item.getItemId()== R.id.forMortician){ Intent intent=new Intent(ManagerDashboard.this,MnagerRegisterMorticiansActivity.class); startActivity(intent); } return super.onOptionsItemSelected(item); } }
package mono.com.google.android.exoplayer2.offline; public class Downloader_ProgressListenerImplementor extends java.lang.Object implements mono.android.IGCUserPeer, com.google.android.exoplayer2.offline.Downloader.ProgressListener { /** @hide */ public static final String __md_methods; static { __md_methods = "n_onDownloadProgress:(Lcom/google/android/exoplayer2/offline/Downloader;FJ)V:GetOnDownloadProgress_Lcom_google_android_exoplayer2_offline_Downloader_FJHandler:Com.Google.Android.Exoplayer2.Offline.IDownloaderProgressListenerInvoker, ExoPlayer.Core\n" + ""; mono.android.Runtime.register ("Com.Google.Android.Exoplayer2.Offline.IDownloaderProgressListenerImplementor, ExoPlayer.Core", Downloader_ProgressListenerImplementor.class, __md_methods); } public Downloader_ProgressListenerImplementor () { super (); if (getClass () == Downloader_ProgressListenerImplementor.class) mono.android.TypeManager.Activate ("Com.Google.Android.Exoplayer2.Offline.IDownloaderProgressListenerImplementor, ExoPlayer.Core", "", this, new java.lang.Object[] { }); } public void onDownloadProgress (com.google.android.exoplayer2.offline.Downloader p0, float p1, long p2) { n_onDownloadProgress (p0, p1, p2); } private native void n_onDownloadProgress (com.google.android.exoplayer2.offline.Downloader p0, float p1, long p2); private java.util.ArrayList refList; public void monodroidAddReference (java.lang.Object obj) { if (refList == null) refList = new java.util.ArrayList (); refList.add (obj); } public void monodroidClearReferences () { if (refList != null) refList.clear (); } }
package kafka2file; import org.apache.flink.streaming.api.CheckpointingMode; import org.apache.flink.streaming.api.environment.CheckpointConfig; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.table.api.EnvironmentSettings; import org.apache.flink.table.api.java.StreamTableEnvironment; import org.apache.flink.table.catalog.CatalogBaseTable; import org.apache.flink.table.catalog.CatalogTable; import org.apache.flink.table.catalog.CatalogTableImpl; import org.apache.flink.table.catalog.ObjectPath; import org.apache.flink.table.catalog.hive.HiveCatalog; import org.apache.flink.types.Row; import java.util.Map; import static org.apache.flink.table.descriptors.StreamTableDescriptorValidator.UPDATE_MODE; import static org.apache.flink.table.descriptors.StreamTableDescriptorValidator.UPDATE_MODE_VALUE_APPEND; public class StreamETLKafka2HdfsSQL { public static void main(String[] args) throws Exception { EnvironmentSettings environmentSettings = EnvironmentSettings.newInstance() .useBlinkPlanner() .inStreamingMode() .build(); StreamExecutionEnvironment executionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment(); executionEnvironment.enableCheckpointing(1000); executionEnvironment.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE); executionEnvironment.getCheckpointConfig().setMinPauseBetweenCheckpoints(500); executionEnvironment.getCheckpointConfig().setCheckpointTimeout(60000); executionEnvironment.getCheckpointConfig().setMaxConcurrentCheckpoints(1); executionEnvironment.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION); executionEnvironment.getCheckpointConfig().setPreferCheckpointForRecovery(true); executionEnvironment.setParallelism(1); StreamTableEnvironment tableEnvironment = StreamTableEnvironment.create(executionEnvironment, environmentSettings); testHiveSink(tableEnvironment); // testHivePartition(tableEnvironment); testKafka2hive(tableEnvironment); } private static void testHiveSink(StreamTableEnvironment tableEnvironment) throws Exception{ String csvSourceDDL = "create table csv( " + "user_name VARCHAR, " + "is_new BOOLEAN, " + "content VARCHAR) with ( " + " 'connector.type' = 'filesystem',\n" + " 'connector.path' = '/Users/bang/sourcecode/project/flink-sql-etl/data-generator/src/main/resources/user.csv',\n" + " 'format.type' = 'csv',\n" + " 'format.fields.0.name' = 'user_name',\n" + " 'format.fields.0.data-type' = 'STRING',\n" + " 'format.fields.1.name' = 'is_new',\n" + " 'format.fields.1.data-type' = 'BOOLEAN',\n" + " 'format.fields.2.name' = 'content',\n" + " 'format.fields.2.data-type' = 'STRING')"; System.out.println(csvSourceDDL); HiveCatalog hiveCatalog = new HiveCatalog("myhive", "default", "/Users/bang/hive-3.1.2/conf", "3.1.2"); tableEnvironment.registerCatalog("myhive", hiveCatalog); tableEnvironment.useCatalog("myhive"); tableEnvironment.useDatabase("default"); tableEnvironment.sqlUpdate(csvSourceDDL); String hiveTableDDL = "insert into user_ino_no_part select user_name, is_new, content from csv"; tableEnvironment.sqlUpdate(hiveTableDDL); tableEnvironment.execute("StreamETLKafka2HdfsSQL"); } private static void testHivePartition(StreamTableEnvironment tableEnvironment) throws Exception{ String csvSourceDDL = "create table csv( " + "user_name VARCHAR, " + "is_new BOOLEAN, " + "content VARCHAR, " + "date_col VARCHAR) with ( " + " 'connector.type' = 'filesystem',\n" + " 'connector.path' = '/Users/bang/sourcecode/project/flink-sql-etl/data-generator/src/main/resources/user_part.csv',\n" + " 'format.type' = 'csv',\n" + " 'format.fields.0.name' = 'user_name',\n" + " 'format.fields.0.data-type' = 'STRING',\n" + " 'format.fields.1.name' = 'is_new',\n" + " 'format.fields.1.data-type' = 'BOOLEAN',\n" + " 'format.fields.2.name' = 'content',\n" + " 'format.fields.2.data-type' = 'STRING',\n" + " 'format.fields.3.name' = 'date_col',\n" + " 'format.fields.3.data-type' = 'STRING')"; System.out.println(csvSourceDDL); HiveCatalog hiveCatalog = new HiveCatalog("myhive", "hive_test", "/Users/bang/hive-3.1.2/conf", "3.1.2"); tableEnvironment.registerCatalog("myhive", hiveCatalog); tableEnvironment.sqlUpdate(csvSourceDDL); // dynamic partition // String hiveTableDDL = "insert into myhive.hive_test.user_info_partition select user_name, is_new, content, date_col from csv"; String hiveTableDDL = "insert into myhive.hive_test.user_info_partition PARTITION(date_col='2020-01-01') select user_name, is_new, content from csv"; tableEnvironment.sqlUpdate(hiveTableDDL); tableEnvironment.execute("StreamETLKafka2HdfsSQL"); } private static void testKafka2hive(StreamTableEnvironment tableEnvironment) throws Exception{ String soureTableDDL = "CREATE TABLE csvData (\n" + " user_name STRING,\n" + " is_new BOOLEAN,\n" + " content STRING,\n" + " date_col STRING" + ") WITH (\n" + " 'connector.type' = 'kafka',\n" + " 'connector.version' = '0.10',\n" + " 'connector.topic' = 'csv_data',\n" + " 'connector.properties.zookeeper.connect' = 'localhost:2181',\n" + " 'connector.properties.bootstrap.servers' = 'localhost:9092',\n" + " 'connector.properties.group.id' = 'testGroup-1',\n" + " 'connector.startup-mode' = 'earliest-offset',\n" + " 'format.type' = 'csv')"; System.out.println(soureTableDDL); HiveCatalog hiveCatalog = new HiveCatalog("myhive", "hive_test", "/Users/bang/hive-3.1.2/conf", "3.1.2"); tableEnvironment.registerCatalog("myhive", hiveCatalog); tableEnvironment.sqlUpdate(soureTableDDL); //set hive streaming table ObjectPath path = new ObjectPath("hive_test", "user_info_kafka"); CatalogTableImpl catalogTable = (CatalogTableImpl)hiveCatalog.getTable(path); Map<String, String> properties = catalogTable.getProperties(); properties.put(UPDATE_MODE, UPDATE_MODE_VALUE_APPEND); CatalogTableImpl newTable = new CatalogTableImpl(catalogTable.getSchema(), properties, "newTable"); hiveCatalog.alterTable(path, newTable, false); hiveCatalog.listTables("hive_test"); String hiveTableDDL = "insert into myhive.hive_test.user_info_kafka select user_name, is_new, content from csvData"; tableEnvironment.sqlUpdate(hiveTableDDL); System.out.println(hiveTableDDL); // tableEnvironment.toAppendStream(tableEnvironment.sqlQuery("select user_name, is_new, content from csvData"), Row.class).print(); tableEnvironment.execute("StreamETLKafka2HdfsSQL"); } }
package com.xianzaishi.wms.tmscore.vo; import com.xianzaishi.wms.tmscore.vo.DistributionWaitSeqVO; public class DistributionWaitSeqDO extends DistributionWaitSeqVO { }
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org) package org.xbill.DNS.tools; import java.io.IOException; import java.net.InetAddress; import org.xbill.DNS.DClass; import org.xbill.DNS.ExtendedFlags; import org.xbill.DNS.Message; import org.xbill.DNS.Name; import org.xbill.DNS.Record; import org.xbill.DNS.ReverseMap; import org.xbill.DNS.SimpleResolver; import org.xbill.DNS.TSIG; import org.xbill.DNS.Type; import org.xbill.DNS.WireParseException; import org.xbill.DNS.ZoneTransferException; import org.xbill.DNS.ZoneTransferIn; /** @author Brian Wellington &lt;bwelling@xbill.org&gt; */ public class dig { static Name name = null; static int type = Type.A, dclass = DClass.IN; static void usage() { System.out.println("; dnsjava dig"); System.out.println("Usage: dig [@server] name [<type>] [<class>] [options]"); System.exit(0); } static void doQuery(Message response, long ms) { System.out.println("; dnsjava dig"); System.out.println(response); System.out.println(";; Query time: " + ms + " ms"); } public static void main(String[] argv) throws IOException { String server = null; int arg; Message query, response; Record rec; SimpleResolver res = null; boolean printQuery = false; long startTime, endTime; if (argv.length < 1) { usage(); } try { arg = 0; if (argv[arg].startsWith("@")) { server = argv[arg++].substring(1); } if (server != null) { res = new SimpleResolver(server); } else { res = new SimpleResolver(); } String nameString = argv[arg++]; if (nameString.equals("-x")) { name = ReverseMap.fromAddress(argv[arg++]); type = Type.PTR; dclass = DClass.IN; } else { name = Name.fromString(nameString, Name.root); type = Type.value(argv[arg]); if (type < 0) { type = Type.A; } else { arg++; } dclass = DClass.value(argv[arg]); if (dclass < 0) { dclass = DClass.IN; } else { arg++; } } while (argv[arg].startsWith("-") && argv[arg].length() > 1) { switch (argv[arg].charAt(1)) { case 'p': String portStr; int port; if (argv[arg].length() > 2) { portStr = argv[arg].substring(2); } else { portStr = argv[++arg]; } port = Integer.parseInt(portStr); if (port < 0 || port > 65535) { System.out.println("Invalid port"); return; } res.setPort(port); break; case 'b': String addrStr; if (argv[arg].length() > 2) { addrStr = argv[arg].substring(2); } else { addrStr = argv[++arg]; } InetAddress addr; try { addr = InetAddress.getByName(addrStr); } catch (Exception e) { System.out.println("Invalid address"); return; } res.setLocalAddress(addr); break; case 'k': String key; if (argv[arg].length() > 2) { key = argv[arg].substring(2); } else { key = argv[++arg]; } String[] parts = key.split("[:/]", 3); switch (parts.length) { case 2: res.setTSIGKey(new TSIG(TSIG.HMAC_MD5, parts[0], parts[1])); break; case 3: res.setTSIGKey(new TSIG(parts[0], parts[1], parts[2])); break; default: throw new IllegalArgumentException("Invalid TSIG key specification"); } break; case 't': res.setTCP(true); break; case 'i': res.setIgnoreTruncation(true); break; case 'e': String ednsStr; int edns; if (argv[arg].length() > 2) { ednsStr = argv[arg].substring(2); } else { ednsStr = argv[++arg]; } edns = Integer.parseInt(ednsStr); if (edns < 0 || edns > 1) { System.out.println("Unsupported EDNS level: " + edns); return; } res.setEDNS(edns); break; case 'd': res.setEDNS(0, 0, ExtendedFlags.DO); break; case 'q': printQuery = true; break; default: System.out.print("Invalid option: "); System.out.println(argv[arg]); } arg++; } } catch (ArrayIndexOutOfBoundsException e) { if (name == null) { usage(); } } if (res == null) { res = new SimpleResolver(); } rec = Record.newRecord(name, type, dclass); query = Message.newQuery(rec); if (printQuery) { System.out.println(query); } if (type == Type.AXFR) { System.out.println("; dnsjava dig <> " + name + " axfr"); ZoneTransferIn xfrin = ZoneTransferIn.newAXFR(name, res.getAddress(), res.getTSIGKey()); xfrin.setTimeout(res.getTimeout()); try { xfrin.run( new ZoneTransferIn.ZoneTransferHandler() { @Override public void startAXFR() {} @Override public void startIXFR() {} @Override public void startIXFRDeletes(Record soa) {} @Override public void startIXFRAdds(Record soa) {} @Override public void handleRecord(Record r) { System.out.println(r); } }); } catch (ZoneTransferException e) { throw new WireParseException(e.getMessage()); } } else { startTime = System.currentTimeMillis(); response = res.send(query); endTime = System.currentTimeMillis(); doQuery(response, endTime - startTime); } } }
package maven_ssm.generation.mappers; import java.util.List; import java.util.Map; import maven_ssm.generation.entity.TableEntity; public interface TableMapper { List<TableEntity> findAllTables(Map<String,String> map); }
package com.tonyzanyar.knowledge; import android.content.ContentUris; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import static com.tonyzanyar.knowledge.data.Contract.COLUMN_CONTENT; import static com.tonyzanyar.knowledge.data.Contract.COLUMN_NUM; import static com.tonyzanyar.knowledge.data.Contract.COLUMN_TOPIC; import static com.tonyzanyar.knowledge.data.Contract.CONTENT_URI; import static com.tonyzanyar.knowledge.data.Contract.MAX_LIMIT; import static com.tonyzanyar.knowledge.data.Contract.MIN_LIMIT; import static com.tonyzanyar.knowledge.data.Contract.TWO_COLUMN_TOPIC_ID; /** * @author zhangxin */ public class EditTopicActivity extends AppCompatActivity { private static final String TAG = "EditTopicActivity1"; private boolean isEdit; private EditText num; private EditText topic; private EditText content; private FloatingActionButton fab3; private Button editQuestion; long idGot; long idFromView; String topicFromView; String contentFromView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit); Intent intent=getIntent(); num=(EditText)findViewById(R.id.edit_num); topic=(EditText)findViewById(R.id.edit_topic); content=(EditText)findViewById(R.id.edit_content); editQuestion=(Button)findViewById(R.id.edit_questions_of_topic); fab3=(FloatingActionButton)findViewById(R.id.floatingActionButton3); fab3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { saveData(); } }); Uri uri=intent.getData(); isEdit=uri!=null; if (!isEdit){ editQuestion.setVisibility(View.GONE); num.setFocusable(false); num.setFocusableInTouchMode(false); }else { initViews(uri); } } private void saveData() { if (!isEdit){ String id=num.getText().toString(); int intId=Integer.parseInt(id); if (intId<MIN_LIMIT||intId>MAX_LIMIT){ Toast.makeText(this, "请输入1-999之间的序号", Toast.LENGTH_SHORT).show(); return; } Uri uri=Uri.withAppendedPath(CONTENT_URI,String.valueOf(intId)); Cursor cursor=getContentResolver().query(uri,null,null,null,null); if (cursor.getCount()==0){ insertData(); } } updateData(); finish(); } private void insertData() { ContentValues value=initValue(); getContentResolver().insert(CONTENT_URI,value); } private void updateData(){ ContentValues value=initValue(); getContentResolver().update(Uri.withAppendedPath(CONTENT_URI,String.valueOf(idFromView)),value,null,null); } private ContentValues initValue(){ ContentValues value=new ContentValues(); String i=num.getText().toString(); idFromView=Integer.valueOf(i); topicFromView=topic.getText().toString(); contentFromView=content.getText().toString(); value.put(COLUMN_NUM,idFromView); value.put(COLUMN_TOPIC,topicFromView); value.put(COLUMN_CONTENT,contentFromView); return value; } private void initViews(Uri uri){ Cursor cursor=getContentResolver().query(uri,null,null,null,null); cursor.moveToNext(); idGot=cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_NUM)); String topicGot=cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_TOPIC)); String contentGot=cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_CONTENT)); num.setText(String.valueOf(idGot)); topic.setText(topicGot); content.setText(contentGot); cursor.close(); editQuestion.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent=new Intent(EditTopicActivity.this,EditQuestionActivity.class); intent.putExtra(TWO_COLUMN_TOPIC_ID,idGot); Log.d(TAG, "initViews: id"+idGot); startActivity(intent); } }); } }
package com.example.myselfimageview; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); CircleImageView circleImageView = (CircleImageView) findViewById(R.id.circle_image); Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test1); circleImageView.setImageBitmap(bitmap); } }
interface STatic { static void new_test() { //static in Interface System.out.println("static in interface"); } } public class StaticInterface { public static void main(String[] args) { STatic.new_test(); } }
package com.spring.tutorial.controller; import java.util.List; import java.util.Locale; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import com.spring.tutorial.model.Employee; import com.spring.tutorial.service.EmployeeService; @Controller @RequestMapping("/employee") public class HomeController { @Autowired private EmployeeService employeeService; @RequestMapping(value = "/get/{id}", method = RequestMethod.GET) public ModelAndView getEmployee(@PathVariable Integer id){ ModelAndView mav = new ModelAndView("home"); //name of jsp page to be displayed List<Employee> emp = employeeService.findById(id); mav.addObject("emp",emp); return mav; } /*//@GetMapping("/") @GetMapping(produces = {"application/json"}) //public String homeInit(Locale locale, Model model) { //public ResponseEntity<String> homeInit(@RequestParam(required = false) String filter) { public String homeInit(@RequestParam(required = false) String filter) { //return new ResponseEntity<>("{\"Message\":\"Successful\"}", new HttpHeaders(), HttpStatus.OK); return "{\"Message\":\"Successful\"}"; }*/ /*@PostMapping(consumes = {"application/json"}, produces = {"application/json"}) public ResponseEntity<String> postHandler( @RequestBody String input){ return new ResponseEntity<>(input, new HttpHeaders(), HttpStatus.CREATED); }*/ }
import java.io.*; import java.util.*; import java.util.stream.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { static int twoPluses(String[] grid) { int rows = grid.length; int cols = grid[0].length(); char[][] G = new char[rows][cols]; for(int i = 0; i < rows; i++) { G[i] = grid[i].toCharArray(); } return maxArea(G); } static int maxArea(char[][] grid) { Set<Set<Integer>> allMax = new HashSet<>(); for(int i = 0; i < grid.length; i++) { for(int j = 0; j < grid[0].length; j++) { int plusLength = 1; Set<Integer> plusPoints; while((plusPoints = getValidPlus(grid, i, j, plusLength)) != null) { allMax.add(plusPoints); plusLength++; } } } return allMax.stream(). flatMapToInt(p0 -> allMax.stream().mapToInt(p1 -> Collections.disjoint(p0, p1) ? p0.size() * p1.size() : 0)). max().orElse(0); } static Set<Integer> getValidPlus(char[][] grid, int i, int j, int len) { char GOOD = 'G'; Set<Integer> plusPoints = new HashSet<>(); for(int l = 0; l < len; l++) { if(i - l >= 0 && i + l < grid.length && j - l >= 0 && j + l < grid[0].length && grid[i][j - l] == GOOD && grid[i][j + l] == GOOD && grid[i - l][j] == GOOD && grid[i + l][j] == GOOD) { plusPoints.add(grid[0].length * (i) + j - l); plusPoints.add(grid[0].length * (i) + j + l); plusPoints.add(grid[0].length * (i + l) + j); plusPoints.add(grid[0].length * (i - l) + j); } else { return null; } } return plusPoints; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); String[] grid = new String[n]; for(int grid_i = 0; grid_i < n; grid_i++){ grid[grid_i] = in.next(); } int result = twoPluses(grid); System.out.println(result); in.close(); } }
// SPDX-License-Identifier: BSD-3-Clause package org.xbill.DNS; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; import org.junit.jupiter.api.Test; class NSEC3PARAMRecordTest { @Test void rdataFromString() throws IOException { Tokenizer t = new Tokenizer("1 1 10 5053851B"); NSEC3PARAMRecord record = new NSEC3PARAMRecord(); record.rdataFromString(t, null); assertEquals(NSEC3Record.Digest.SHA1, record.getHashAlgorithm()); assertEquals(NSEC3Record.Flags.OPT_OUT, record.getFlags()); assertNotNull(record.getSalt()); } }